如何在 Python 中使用 dialogflow 客户端

How to use dialogflow Client In Python

我正在尝试的是在 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

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

您需要从您的 导出 服务帐户密钥 (JSON) 文件,并将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为 JSON 包含您的服务帐户密钥的文件。然后你就可以调用dialogflow了。

获取服务帐户密钥的步骤: 确保您使用的是 Dialogflow v2。 转到常规设置并单击您的服务帐户。这会将您重定向到 Google Cloud Platform 项目的服务帐户页面。 下一步是为服务帐户创建一个新密钥。现在创建一个服务帐户并选择 JSON 作为输出密钥。按照说明操作,JSON 文件将下载到您的计算机。此文件将用作 GOOGLE_APPLICATION_CREDENTIALS.

现在在代码中,

import os
import dialogflow
os.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)

如果您想从文件系统中获取文件,这个也可以使用。 推荐的方法是使用环境变量 thoguh

import json from google.cloud import dialogflow_v2 from google.oauth2 import * <pre><code>session_client = None dialogflow_key = None creds_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