我使用V1 API发出请求已有一段时间。我希望从V1升级到V2 API。
我正在使用以下python代码发出请求:
import os.path
import sys
import json
try:
import apiai
except ImportError:
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
import apiai
#CLIENT_ACCESS_TOKEN = 'client access token'
def main():
try:
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.lang = 'en' # optional, default value equal 'en'
request.query = "techm bid satyam computers" #Enter question here
response = request.getresponse()
hi=json.loads(response.read())
res=hi
print (res)
except TimeoutError:
print ("Couldn't connect to dialogflow")
if __name__ == '__main__':
main()
我试图迁移到V2 API的是
它显示IAM权限被拒绝,客户端访问令牌不存在错误。
是否有用于V2 API的单独的python代码以访问dialogflow?
答案 0 :(得分:2)
经过数小时的搜索,我发现了这个问题。 这是使用V1 API将请求发送到DialogFlow的python代码。
要使用V2 API,它有一个单独的客户端代码,而DialogFlow的响应与V1相比发生了很大变化。
import random
import string
def randomString(stringLength=10):
"""Generate a random string of letters, digits and special characters """
password_characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_characters) for i in range(stringLength))
def detect_intent_texts(project_id, session_id, texts, language_code):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversation."""
import dialogflow_v2 as dialogflow
import json
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session))
text_input = dialogflow.types.TextInput(text=texts, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(session=session, query_input=query_input)
test = response.query_result
print(test)
'''
print('=' * 20)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(response.query_result,response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(response.query_result.fulfillment_text))'''
detect_intent_texts(project_ID,randomString(),'Input query text', 'language code'[doc][1])
DialogFlow的响应存储在变量中
测试
注意:它不再是Json格式。这是一个对象。要访问这些值,必须使用参数。 示例:
test = response.query_result.parameters
from google.protobuf.json_format import MessageToDict
output_entities = MessageToDict(test)
print(output_entities)
实体现在存储在变量中
output_entities