Google Cloud Dialogflow CX

2.5.0 · active · verified Mon Apr 13

The `google-cloud-dialogflow-cx` client library provides Pythonic access to the Google Cloud Dialogflow CX API. Dialogflow CX is a conversational AI platform designed for building advanced virtual agents with complex, multi-turn conversations using a visual state-machine approach. This library facilitates interaction with Dialogflow CX agents, sessions, intents, flows, and other resources. It is part of the larger `google-cloud-python` ecosystem, which typically sees frequent updates and releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a `SessionsClient` and use it to detect intent from a text input against a specified Dialogflow CX agent. Ensure the Dialogflow CX API is enabled for your Google Cloud project and that you have appropriate authentication configured (e.g., `gcloud auth application-default login`).

import os
import uuid
from google.cloud.dialogflowcx_v3 import types
from google.cloud.dialogflowcx_v3.services.sessions import SessionsClient

# Set environment variables or replace with your actual values
PROJECT_ID = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-gcp-project-id')
LOCATION_ID = os.environ.get('DIALOGFLOW_LOCATION', 'global') # e.g., 'us-central1'
AGENT_ID = os.environ.get('DIALOGFLOW_CX_AGENT_ID', 'your-agent-id')

# Unique session ID for a conversation
SESSION_ID = str(uuid.uuid4())

def detect_intent_text(project_id: str, location_id: str, agent_id: str, session_id: str, text: str):
    """Detects intent using text input."""
    session_path = (
        f"projects/{project_id}/locations/{location_id}/agents/{agent_id}/sessions/{session_id}"
    )

    client_options = None
    if location_id != "global":
        client_options = {"api_endpoint": f"{location_id}-dialogflow.googleapis.com"}

    session_client = SessionsClient(client_options=client_options)

    text_input = types.TextInput(text=text)
    query_input = types.QueryInput(text=text_input, language_code="en-US")

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

    response = session_client.detect_intent(request=request)

    print(f"User query: {response.query_result.text}")
    for message in response.query_result.response_messages:
        if message.text:
            print(f"Agent response: {message.text.text[0]}")
    if response.query_result.match.intent:
        print(f"Matched intent: {response.query_result.match.intent.display_name}")

if __name__ == '__main__':
    # Example usage:
    user_input = "Hello, how are you?"
    print(f"Attempting to detect intent for: '{user_input}'")
    detect_intent_text(PROJECT_ID, LOCATION_ID, AGENT_ID, SESSION_ID, user_input)
    print("\nMake sure to set GOOGLE_CLOUD_PROJECT, DIALOGFLOW_LOCATION, and DIALOGFLOW_CX_AGENT_ID environment variables, and enable the Dialogflow CX API in your project.")

view raw JSON →