Azure AI Language - Conversational Language Understanding

1.1.0 · active · verified Fri Apr 17

The Azure AI Language - Conversational Language Understanding (CLU) client library for Python allows developers to integrate CLU capabilities into their applications. It enables natural language understanding of conversational inputs, extracting intents, entities, and performing orchestrations across multiple language services. The current version is 1.1.0, and Azure SDKs typically have a frequent release cadence, with minor updates monthly or bi-monthly.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `ConversationAnalysisClient` and perform a basic conversation analysis to extract intents and entities from a given text using a deployed Conversational Language Understanding (CLU) project. It uses `AzureKeyCredential` for authentication, requiring an endpoint and an API key for your Azure Language resource, along with the CLU project and deployment names.

import os
from azure.ai.language.conversations import ConversationAnalysisClient
from azure.core.credentials import AzureKeyCredential
# from azure.identity import DefaultAzureCredential # Uncomment for Azure AD authentication

# --- Set these environment variables before running ---
# export LANGUAGE_ENDPOINT='https://your-language-resource.cognitiveservices.azure.com/'
# export LANGUAGE_KEY='your-azure-language-resource-key'
# export CLU_PROJECT_NAME='your-clu-project-name'
# export CLU_DEPLOYMENT_NAME='your-clu-deployment-name'
# -----------------------------------------------------

language_endpoint = os.environ.get("LANGUAGE_ENDPOINT", "")
language_key = os.environ.get("LANGUAGE_KEY", "")
clu_project_name = os.environ.get("CLU_PROJECT_NAME", "")
clu_deployment_name = os.environ.get("CLU_DEPLOYMENT_NAME", "")

if not all([language_endpoint, language_key, clu_project_name, clu_deployment_name]):
    print("ERROR: Please set the environment variables LANGUAGE_ENDPOINT, LANGUAGE_KEY, CLU_PROJECT_NAME, and CLU_DEPLOYMENT_NAME.")
    print("Refer to the comments in the quickstart code for examples.")
    exit(1)

# Authenticate with AzureKeyCredential
# For production scenarios, consider using DefaultAzureCredential from azure.identity for Azure AD authentication:
# client = ConversationAnalysisClient(endpoint=language_endpoint, credential=DefaultAzureCredential())
client = ConversationAnalysisClient(
    endpoint=language_endpoint,
    credential=AzureKeyCredential(language_key)
)

text = "How do I get to the nearest ATM?"

print(f"\nAnalyzing conversation: '{text}' for project '{clu_project_name}' (deployment '{clu_deployment_name}')")

try:
    response = client.analyze_conversation(
        task={
            "kind": "Conversation",
            "analysisInput": {
                "conversationItem": {
                    "participantId": "1",
                    "id": "1",
                    "text": text
                }
            },
            "parameters": {
                "projectName": clu_project_name,
                "deploymentName": clu_deployment_name,
                "verbose": True # Set to False for less detailed output
            }
        }
    )

    result = response.as_dict()
    prediction = result["result"]["prediction"]
    
    if prediction["projectKind"] == "Conversation":
        print("  Top intent:", prediction["topIntent"])
        print("  Entities:")
        for entity in prediction["entities"]:
            print(f"  - {entity['category']}: {entity['text']} (confidence: {entity['confidence']:.2f})")
    else:
        # This branch handles orchestrator projects or other unknown kinds
        print(f"  Prediction project kind: {prediction['projectKind']}. Full prediction: {prediction}")

except Exception as e:
    print(f"\nAn error occurred: {e}")
    print("Please ensure your environment variables are correct and the CLU project is deployed.")

view raw JSON →