如何在Python中使用dialogflow客户端

我正在尝试的是在 python 中获得响应


import dialogflow

from google.api_core.exceptions import InvalidArgument


DIALOGFLOW_PROJECT_ID = 'imposing-fx-333333'

DIALOGFLOW_LANGUAGE_CODE = 'en'

GOOGLE_APPLICATION_CREDENTIALS = 'imposing-fx-333333-e6e3cb9e4adb.json'

text_to_be_analyzed = "Hi! I'm David and I'd like to eat some sushi, can you help me?"

session_client = dialogflow.SessionsClient()

session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)

text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, 

language_code=DIALOGFLOW_LANGUAGE_CODE)

query_input = dialogflow.types.QueryInput(text=text_input)

try:

    response = session_client.detect_intent(session=session, query_input=query_input)

except InvalidArgument:

    raise

print("Query text:", response.query_result.query_text)

print("Detected intent:", response.query_result.intent.display_name)

print("Detected intent confidence:", response.query_result.intent_detection_confidence)

print("Fulfillment text:", response.query_result.fulfillment_text)

我无法验证凭据


google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

这是我在 stackoverflow 中的第一个问题:)我知道我已经做了很多


慕姐8265434
浏览 104回答 2
2回答

肥皂起泡泡

您需要从 导出服务帐户密钥 (JSON)文件,并将环境变量设置GOOGLE_APPLICATION_CREDENTIALS为包含服务帐户密钥的 JSON 文件的文件路径。然后你就可以调用dialogflow了。获取服务帐户密钥的步骤: 确保您使用的是 Dialogflow v2。转到常规设置并单击您的服务帐户。这会将您重定向到 Google Cloud Platform 项目的服务帐户页面。下一步是为服务帐户创建新密钥。现在创建一个服务帐户并选择 JSON 作为输出密钥。按照说明操作,JSON 文件将下载到您的计算机。该文件将用作GOOGLE_APPLICATION_CREDENTIALS.现在在代码中,import osimport dialogflowos.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/file.json"project_id = "your_project_id"session_id = "your_session_id"language_code = "en"session_client = dialogflow.SessionsClient()session = session_client.session_path(project_id, session_id)text_input = dialogflow.types.TextInput(text=text, language_code=language_code)query_input = dialogflow.types.QueryInput(text=text_input)response_dialogflow = session_client.detect_intent(session=session, query_input=query_input)

慕虎7371278

如果您想从文件系统中获取文件,此方法也适用。推荐的方法是使用环境变量    import json    from google.cloud import dialogflow_v2    from google.oauth2 import *session_client = Nonedialogflow_key = Nonecreds_file = "/path/to/json/file.json"dialogflow_key = json.load(open(creds_file))credentials = (service_account.Credentials.from_service_account_info(dialogflow_key))session_client = dialogflow_v2.SessionsClient(credentials=credentials)print("it works : " + session_client.DEFAULT_ENDPOINT) if session_client is not None else print("does not work")我忘记添加主要文章抱歉...这里是:https://googleapis.dev/python/google-auth/latest/user-guide.html#service-account-private-key-files
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python