Jeeva Bharathi
Jeeva Bharathi

Reputation: 99

How to make request query to DialogFlow using V2 API?

I was using V1 API to make requests for a while. I am looking to upgrade from V1 to V2 API.

I am using this python code to make requests:

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()

What I tried to migrate to V2 API is,

  1. I created a service account with 'DialogFlow API client' Role.
  2. Created a private key and set it as GOOGLE_APPLICATION_CREDENTIALS
  3. Deleted the client access token and tried to access

It showed IAM permission denied, Client access token does not exists errors.

Is there a separate python code for V2 API to access dialogflow?

Upvotes: 0

Views: 1185

Answers (1)

Jeeva Bharathi
Jeeva Bharathi

Reputation: 99

I figured it out after several hours of searching regarding this issue. This is a python code to send request to DialogFlow using V1 API.

To use, V2 API there is a separate client code for it and the response from the DialogFlow is changed very drastically from 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])

The response from the DialogFlow is stored in the variable

test

Note: It is no longer in Json format. It's an object. To access the values, you must use the parameters. Example:

test = response.query_result.parameters
from google.protobuf.json_format import MessageToDict
output_entities = MessageToDict(test)
print(output_entities)

The entities are now stored in the variable

output_entities

Upvotes: 2

Related Questions