采取Dialogflow意图并查询Firestore [英] Take Dialogflow intent and query Firestore

查看:65
本文介绍了采取Dialogflow意图并查询Firestore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的聊天机器人是在Dialogflow中创建的,现在我正尝试从Python访问它,以在GUI中输入用户输入并显示输出(想想基本的聊天机器人gui)。

My chatbot has been created in Dialogflow and I am now trying to access it from Python, to take user inputs and display outputs in the GUI (think a basic chatbot gui).

我已将Python环境连接到Dialogflow和Firestore,

I have connected my Python environment to Dialogflow and to firestore,

这是检测意图的代码;

Here is the code that detects intents;

#Detection of Dialogflow intents, project and input.
def detect_intent_texts(project_id, session_id, texts, language_code):
   #Returns the result of detect intent with texts as inputs, later can implement same `session_id` between requests allows continuation of the conversaion.
    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
#To ensure session path is correct - print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session, query_input=query_input)

        print ('Chatbot:{}\n'.format(response.query_result.fulfillment_text))
detect_intent_texts("chat-8","abc",["Hey"],"en-us")

我需要以某种方式说一下是否触发了此意图,请从数据库中获取内容并显示给用户。

I need to somehow say if THIS intent is triggered, get something from the db and display to user.

更新

我当前的代码完整,一切对我来说都不错,但是会抛出错误,我不知道理解,总之,感谢Sid8491的帮助。

My current code in full, everything is looking right to me but it's throwing an error I don't understand, thanks to Sid8491 for the help so far.

总之,我的问题是,我之前的代码允许我键入内容,并且聊天机器人可以响应,所有这些都在控制台中但它确实有效。新代码应该允许我说当触发此意图时,请执行此操作

in short, my issue is, my previous code allowed me to type something and the chatbot respond, it was all in the console but it worked... The new code is supposed to allow me to say "When THIS intent is triggered, do THIS"

import os, json
import sys
import dialogflow
from dialogflow_v2beta1 import *
import firebase_admin
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
from firebase_admin import firestore
from firebase_admin import credentials
import requests.packages.urllib3
from Tkinter import *
from dialogflow_v2beta1 import agents_client
import Tkinter as tk
result = None
window = Tk()

def Response():
    #no need to use global here
    result = myText.get()
    displayText.configure(state='normal')
    displayText.insert(END, "User:"+ result + '\n')
    displayText.configure(state='disabled')

#Creating the GUI
myText = tk.StringVar()
window.resizable(False, False)
window.title("Chatbot")
window.geometry('400x400')
User_Input = tk.Entry(window, textvariable=myText, width=50).place(x=20, y=350)
subButton = tk.Button(window, text="Send", command=Response).place(x =350, y=350)
displayText = Text(window, height=20, width=40)
displayText.pack()
scroll = Scrollbar(window, command=displayText).pack(side=RIGHT)
window.mainloop()

#Initialize the firebase admin SDK
cred = credentials.Certificate('./file.json')
default_app = firebase_admin.initialize_app(cred)
db = firestore.client()

def getCourse():
    doc_ref = db.collection(u"Course_Information").document(u"CourseTypes")
    try:
        doc = doc_ref.get()
        return 'Document data: {}'.format(doc.to_dict())
    except google.cloud.exceptions.NotFound:
        return 'Not found'

def detect_intent_text(project_id, session_id, text, language_code):
    GOOGLE_APPLICATION_CREDENTIALS=".chat-8.json"
    session_client = dialogflow.SessionsClient(GOOGLE_APPLICATION_CREDENTIALS)

    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 = session_client.detect_intent(
        session=session, query_input=query_input)

queryText = [myText.get()]

res = detect_intent_text('chat-8', 'session-test', queryText, 'en')
intentName = res['query_result']['intent']['display_name']

if intentName == 'CourseEnquiry':
    reponse = getCourse()
    print json.dumps({
        'fulfillmentText': reponse,
    })
elif intentName == 'Greetings':
    print "Yo"

detect_intent_texts("chat-8","abc", queryText,"en-us")

但我收到此错误:

C:\Users\chat\PycharmProjects\Chatbot\venv\Scripts\python.exe C:/Users/chat/PycharmProjects/Chatbot/venv/Chatbot.py
Traceback (most recent call last):
  File "C:/Users/chat/PycharmProjects/Chatbot/venv/Chatbot.py", line 65, in <module>
    res = detect_intent_text('chat-8', 'session-test', queryText, 'en')
  File "C:/Users/chat/PycharmProjects/Chatbot/venv/Chatbot.py", line 51, in detect_intent_text
    session_client = dialogflow.SessionsClient(GOOGLE_APPLICATION_CREDENTIALS)
  File "C:\Users\chat\PycharmProjects\Chatbot\venv\lib\site-packages\dialogflow_v2\gapic\sessions_client.py", line 109, in __init__
    self.sessions_stub = (session_pb2.SessionsStub(channel))
  File "C:\Users\chat\PycharmProjects\Chatbot\venv\lib\site-packages\dialogflow_v2\proto\session_pb2.py", line 1248, in __init__
    self.DetectIntent = channel.unary_unary(
AttributeError: 'str' object has no attribute 'unary_unary'

Process finished with exit code 1


推荐答案

是的,我认为您的做法正确。

Yes, I think you are on the right track.

您需要提取 intentName actionaName dialogFlow 并调用您的相应函数,然后将响应发送回用户。

You need to extract intentName or actionaName from the response you got from the dialogFlow and call your corresponding functions and then send the response back to user.

res = detect_intent_texts("chat-8","abc",["Hey"],"en-us")
action = res['queryResult']['action']

if action == 'getSomethingFromDb':
    reponse = someFunction(req)
    return json.dumps({
        'fulfillmentText': reponse,
    })
elif action == 'somethingElse':
    ....

如果需要它可以使用 intentName 代替 actionName 来完成,然后可以提取 intentName 如下所示

If you want it to do using intentName instead of actionName then you can extract intentName like below

intentName = res['query_result']['intent']['display_name']

编辑1:

示例-

EDIT 1:
Example -

import dialogflow
import os, json

def getCourse():
    doc_ref = db.collection(u"Course_Information").document(u"CourseTypes")
    try:
        doc = doc_ref.get()
        return 'Document data: {}'.format(doc.to_dict())
    except google.cloud.exceptions.NotFound:
        return 'Not found'

def detect_intent_text(project_id, session_id, text, language_code):
    GOOGLE_APPLICATION_CREDENTIALS="C:\\pyth_to_...\\cred.json"
    session_client = dialogflow.SessionsClient(GOOGLE_APPLICATION_CREDENTIALS)

    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 = session_client.detect_intent(
        session=session, query_input=query_input)

queryText = 'get courses of Python' # you will call some function to get text from your app

res = detect_intent_text('project_1234', 'session-test', queryText, 'en')
intentName = res['query_result']['intent']['display_name']

if intentName == 'getCourse':
    reponse = getCourse()
    return json.dumps({
        'fulfillmentText': reponse,
    })

尝试以上示例并根据您的应用需求进行更改。我的建议是首先使DialogFlow在没有应用程序的情况下工作,然后将其与应用程序集成。否则,您将无法理解DialogFlow还是您的应用程序是否正在发生问题。

Try above example and change according to your needs of app. My suggestion is to first get DialogFlow working without app, then integrate it with the app. Otherwise you won't be able to understand whether problem is happening in DialogFlow or your app.

希望它会有所帮助。

这篇关于采取Dialogflow意图并查询Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆