I made an agent with a knowledge base and documents in it using dialogflow console.
know I want to test it form a python code from my computer how can I code the query to get the response?
You can use the following official python package and install using pip.
pip install google-cloud-dialogflow
Check out the quickstart on the official google cloud documentation to detect the intent and retrieve the response.
https://cloud.google.com/dialogflow/es/docs/quick/api
Please find below links for code as you required. this has multiple links which can help you to understand flow.
https://cloudacademy.com/blog/how-to-build-an-intelligent-chatbot-with-python-and-dialogflow/
https://dev.to/mrkanthaliya/build-intelligent-chatbot-using-dialogflow-54nh
https://medium.com/zenofai/creating-chatbot-using-python-flask-d6947d8ef805
https://chatbotslife.com/dialogflow-tutorial-back-functionality-in-chatbot-using-python-django-eb2ce921dd19
this is a code can solve the problem
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."""
from google.cloud import dialogflow_v2beta1
session_client = dialogflow_v2beta1.SessionsClient()
session = session_client.session_path(project_id, session_id)
print("Session path: {}\n".format(session))
#for text in texts:
text_input = dialogflow_v2beta1.TextInput(text=text, language_code=language_code)
query_input = dialogflow_v2beta1.QueryInput(text=text_input)
response = session_client.detect_intent(
request={"session": session, "query_input": query_input}
)
print("=" * 20)
print("Query text: {}".format(response.query_result.query_text))
print(
"Detected intent: {} (confidence: {})\n".format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence,
)
)
print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
my problem I was importing and using the normal dialogflow instead of using dialogflow_v2beta1 because using knowledge base is a beta feature.
Related
I am currently using RASA and developed a working chatbot. One part of my project is to use a speech-to-text recognition, and I wrote a working code in Python that returns the text said by the user.
I want to use that text for RASA’s input, instead of writing like usual.
I saw there was something to do with the inputs channels, but I only saw input that are other webservices and couldn’t figure it out for using just a local script.
Thank you for any advice,
LM
You can try rasa REST API for this purpose. Make sure that you have action_endpoint url in endpoints.yml. Normally it is
url: "http://localhost:5055/webhook"
Then make sure your rasa bot is up and if htere are any custom actions, start that server as well.
After starting your webhook, you can simple call
http://localhost:5005/webhooks/rest/webhook
and in the payload you have to put below payload
messagePayload = {
sender: 'default',
message: 'Your message is here'
}
and finally add httpheader content type as application/json like below
'Content-Type': 'application/json'
Now your bot will work fine.
tldr;
If you are using request in your python for api calls, you can try below code.
import requests
API_ENDPOINT = "http://localhost:5005/webhooks/rest/webhook"
messagePayload = {
sender: 'default',
message: 'Your message is here'
}
r = requests.post(url = API_ENDPOINT, data = messagePayload)
How about just using Rest API that is already present in the library.
For this, you just need to fill the query parameter, which you can do with your script, rather than writing a custom Input Channel.
I am following the following tutorial to understand Dialogflow Python API.
Here is how my adaptation looks:
import dialogflow_v2 as dialogflow
import json
from google.api_core.exceptions import InvalidArgument
from google.oauth2 import service_account
dialogflow_key = json.load(open(r'path_to_json_file.json'))
credentials = (service_account.Credentials.from_service_account_info(dialogflow_key))
session_client = dialogflow.SessionsClient(credentials=credentials)
DIALOGFLOW_LANGUAGE_CODE = 'en-US'
DIALOGFLOW_PROJECT_ID = 'some_project_id'
SESSION_ID = 'current-user-id'
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_to_be_analyzed = "mobile data"
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)
Here is what program outputs:
Query text: mobile data
Detected intent: support.problem
Detected intent confidence: 0.41999998688697815
Fulfillment text: Make sure mobile data is enabled and Wi-Fi is turned off.
Now my intent support.problem has follow up intent support.problem-yes, where customer replies Done it and gets back another response Let us try another step
How do I pass text/query to follow up intent and how do I get response in Python?
The response.query_result object should also contain an output_context field, which should be an array of Context objects. This array should be passed in query_parameters.context you pass to detect_intent().
You should be able to create a dictionary with the query parameters fields (including one for context) that you pass to session_client.detect_intent.
I'm a beginner to python and trying to apply Gcloud Sentiment Analysis to analyze some sentences. The python code is provided by official here: https://cloud.google.com/natural-language/docs/analyzing-sentiment
The error is as follows:
RetryError: Deadline of 600.0s exceeded while calling functools.partial(.error_remapped_callable at 0x0000020081C0EB70>, document {
type: PLAIN_TEXT
content: "yes i do!"
}
, metadata=[('x-goog-api-client', 'gl-python/3.6.5 grpc/1.17.1 gax/1.7.0 gapic/1.1.1')]), last exception: 503 channel is in state TRANSIENT_FAILURE
I've tried many ways (e.g. disable firewall, switch to other laptop / wifi) to solve but failed. I'm sure environment variable is set up using Application Default Credentials, and API is authenticated.
Could you have any ideas? Many thanks!
Coding environment:
Python 3.6
Win10
python package from CMD pip list --
gcloud (0.18.3),
google-api-core (1.7.0),
google-cloud-language (1.1.1)
from google.cloud import language_v1
from google.cloud.language_v1 import enums
import six
def sample_analyze_sentiment(content):
client = language_v1.LanguageServiceClient()
# content = 'Your text to analyze, e.g. Hello, world!'
if isinstance(content, six.binary_type):
content = content.decode('utf-8')
type_ = enums.Document.Type.PLAIN_TEXT
document = {'type': type_, 'content': content}
response = client.analyze_sentiment(document)
sentiment = response.document_sentiment
print('Score: {}'.format(sentiment.score))
print('Magnitude: {}'.format(sentiment.magnitude))
text = 'yes i do!'
sample_analyze_sentiment(text)
I'm creating a chatbot with Dialogflow and Django-python. Right now, I already created an agent in Dialogflow, already have a Django app, used ngork, and other necessary stuffs except for connecting Dialogflow to Django app's fulfillment/and calling APIs.
I stumbled across this documentation https://github.com/googleapis/dialogflow-python-client-v2 and successfully did all the steps needed. In the last part of the documentation, it seems that what I finally need to do is use the dialogflow detect intent text , so I copied it and put it into my Django app(views.py).
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
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
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('=' * 20)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
Now, I don't know what to do next. Unfortunately, I don't know how to use it or how it exactly works as I am still new to this. I already searched for answers in the web but I didn't get a clear understanding about it and got overwhelmed a bit(as it seems that there is a lot to do with this). I hope I could get an example or step by step procedure about it.
I am assuming you know the basic functionalities of Django, and you are using v2 of Dialogflow.
You need to pass the user text request from front-end to the views.py. YOu will get it in request object, then you need to extract it.
After extracting the text, you need to call dialogflow's detect_intent() function with text and session_id (text requests with same session_id will be treated as same part of conversation).
Also, you would need to get a json file from GCP console in order to authenticate the dialogflow request. You can read more about that here.
Here is sample code which you can extend according to your use:
import dialogflow
from django.http import HttpResponse
def your_view(request):
text = request.POST.get("text_request")
session_id = 'some_session_id'
res = detect_intent(text)
return HttpResponse(res)
def detect_intent(text, session_id):
language_code = 'en'
project_id = 'your_dialogflow_project_id'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path_to_your_json_file'
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 = session_client.detect_intent(session=session, query_input=query_input)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
return response.query_result.fulfillment_text
Hope it helps.
I ran for awhile a python script to post articles on my blogspot blog.
everything ran smoothly until I started to get this auth error
RequestError: {'status': 401, 'body': 'User does not have permission to create new post', 'reason': 'Unauthorized'}
I really can't understand how to fix it reading gdata documentation.
Could you please suggest me how to do?
Thank you
Here the part of my code that doesn't work anymore:
from gdata import service
import gdata
import atom
blogger_service = service.GDataService('xxxxxx','xxxxxx')
blogger_service.service = 'blogger'
blogger_service.account_type = 'GOOGLE'
blogger_service.server = 'www.blogger.com'
blogger_service.ProgrammaticLogin()
def CreatePublicPost(blogger_service, blog_id, title, content,tags):
entry = gdata.GDataEntry()
entry.title = atom.Title('xhtml', title)
entry.content = atom.Content(content_type='html', text=content)
for tag in tags :
category = atom.Category(term=tag, scheme="http://www.blogger.com/atom/ns#")
entry.category.append(category)
return blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id)
Now there is a API version 3.0...
This old version is obsolete and no longer works, apparently...
You can find more about it here:
https://developers.google.com/blogger/
https://developers.google.com/blogger/docs/3.0/using/
And if you have questions about authentication, maybe those links help:
Having trouble trying to use gdata and oauth2 in python
Authentication with the Google Docs List API, Python and OAuth 2