'Dialogflow CX python SDK not picking up credentials set in the environment variable GOOGLE_APPLICATION_CREDENTIALS

I have hosted an API to detect intent in Dialogflow CX using python Flask. I have the environment variable GOOGLE_APPLICATION_CREDENTIALS correctly set to the service account credential json. While calling the API, it results in Default Credential error. If I try to print the value set in GOOGLE_APPLICATION_CREDENTIALS within the python code, it shows None. Whereas, if I check the environment variable in the server using printenv GOOGLE_APPLICATION_CREDENTIALS, I get the location of my json file. What could have went wrong? Could anybody help on this please...

UPDATE Now, I tried by adding the environment variable in the code. This time, detect_intent doesn't give any response. It just times out after 300 seconds

Here's the code:

from flask import make_response, jsonify, request
from flask_restful import Resource, reqparse
import os
from google.cloud import dialogflowcx_v3

_KEY = 'abcd-chat-bot-e440cw2t611c.json'

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = _KEY


class DetectIntentLatest(Resource):
    @classmethod
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('text')
        parser.add_argument('session_id')
        args = parser.parse_args()
        text = args['text']
        session_id = args['session_id']

        project_id = "abcd-chat-bot"

        location_id = "global"

        agent_id = "grt31207-18q3-1a22-6dqa-44856u783364"
        agent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"

        language_code = "en-us"

        session_path = f"{agent}/sessions/{session_id}"
        print(f"Session path: {session_path}\n")
        client_options = None

        client = dialogflowcx_v3.SessionsClient()

        # Initialize request argument(s)
        query_input = dialogflowcx_v3.QueryInput()
        query_input.text.text = text
        query_input.language_code = language_code

        print("_____________________ QUERY INPUT _____________________")
        print(query_input)

        request = dialogflowcx_v3.DetectIntentRequest(
            session=session_path,
            query_input=query_input,
        )

        # Make the request
        response = client.detect_intent(request=request)

        # Handle the response
        print("_____________________ RESPONSE _____________________")
        print(response)

        return make_response(jsonify(status=1, result='success'), 200)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source