Azure AI Language - Conversational Language Understanding
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
-
azure.core.exceptions.ClientAuthenticationError: Authentication failed: You don't have permission to perform this action. Request ID: ...
cause The Azure Language resource key or endpoint is incorrect, expired, or the principal lacks necessary permissions (e.g., 'Cognitive Services User').fixVerify that `LANGUAGE_KEY` and `LANGUAGE_ENDPOINT` environment variables match your Azure Language resource. Check the resource's Access Control (IAM) settings for appropriate permissions if using Azure AD authentication. -
ValueError: Invalid URL 'your-endpoint.cognitiveservices.azure.com': No schema supplied. Perhaps you meant https://your-endpoint.cognitiveservices.azure.com/
cause The `endpoint` provided to the client constructor is missing the `https://` protocol prefix.fixEnsure your `LANGUAGE_ENDPOINT` environment variable (or hardcoded endpoint) includes `https://` at the beginning, e.g., `https://your-resource.cognitiveservices.azure.com/`. -
KeyError: 'prediction'
cause The structure of the response object from the `analyze_conversation` method did not contain the expected 'prediction' key. This can happen if the service returns an error or if the response model changes.fixInspect the full `response.as_dict()` output to understand the actual structure. This might indicate a service-side error (check `response.error`) or an API version mismatch. Update your parsing logic or client library version if an API model has changed. -
ModuleNotFoundError: No module named 'azure.ai.language.conversations'
cause The `azure-ai-language-conversations` package is not installed or the Python environment is incorrect.fixInstall the package using `pip install azure-ai-language-conversations`. If using virtual environments, ensure you've activated the correct one. -
TypeError: 'AzureKeyCredential' object is not callable
cause This typically occurs if you pass the `AzureKeyCredential` object directly to the `credential` argument without instantiating it with the key, or if you accidentally call it like a function.fixEnsure you instantiate the credential correctly: `credential=AzureKeyCredential(language_key)`. Do not use `credential=language_key` or `credential=AzureKeyCredential` without the key in parentheses.
Warnings
- gotcha The Azure Language resource endpoint must include the `https://` scheme. Omitting it will lead to `ValueError: Invalid URL` errors.
- gotcha The `ConversationAnalysisClient` constructor expects `credential` to be an instance of a credential type (e.g., `AzureKeyCredential(key)`) not just the key string itself. Swapping `endpoint` and `credential` arguments is also a common mistake.
- breaking The structure of the `task` dictionary passed to `analyze_conversation` (and `analyze_conversation_orchestration`) can change between minor versions or if using preview API versions. Always consult the official documentation for the exact payload required for your service version.
- gotcha Azure SDKs often provide both synchronous (default) and asynchronous clients. If you're building an async application, ensure you import `ConversationAnalysisClient` from `azure.ai.language.conversations.aio` and use `await` with its methods.
Install
-
pip install azure-ai-language-conversations
Imports
- ConversationAnalysisClient
from azure.cognitiveservices.language.conversations import ConversationAnalysisClient
from azure.ai.language.conversations import ConversationAnalysisClient
- AzureKeyCredential
from azure.ai.language.conversations.credentials import AzureKeyCredential
from azure.core.credentials import AzureKeyCredential
- DefaultAzureCredential
from azure.ai.language.conversations import DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
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.")