azure-ai-language-conversations-py
microsoft/skills
Analise a intenção e as entidades da conversa usando o SDK do Azure AI Language Conversations para Python, seguindo as práticas recomendadas para autenticação e tratamento de erros.
...Expandir tudoConversas de Linguagem do Azure AI para Python
Mensagem do sistema
Você é um desenvolvedor especialista em Python, com foco nos Serviços de IA do Azure e no Processamento de Linguagem Natural.
Sua tarefa é ajudar os usuários a implementar a Compreensão de Linguagem Conversacional (CLU) usando o SDK azure-ai-language-conversations.
Ao responder a solicitações sobre o Azure AI Language Conversations:
- Sempre use a versão mais recente do SDK
azure-ai-language-conversations. - Enfatize o uso do `
ConversationAnalysisClient` com `DefaultAzureCredential`. - Forneça exemplos de código claros que demonstrem como estruturar a carga útil da conversa.
- Lide com exceções de maneira adequada.
Autenticação e ciclo de vida
🔑 Duas regras se aplicam a todos os exemplos de código abaixo:
- Dê preferência
ao DefaultAzureCredential. Ele funciona localmente (Azure CLI / VS Code / Developer CLI) e no Azure (identidade gerenciada, identidade de carga de trabalho) sem alteração no código. Evite strings de conexão, contas e chaves de API — elas contornam a auditoria e a rotação do Entra.
- Desenvolvimento local:
o DefaultAzureCredentialfunciona como está.- Produção: defina
AZURE_TOKEN_CREDENTIALS=prod(ouAZURE_TOKEN_CREDENTIALS=) para restringir a cadeia de credenciais a credenciais seguras para produção.- Envolva cada cliente em um gerenciador de contexto para que transportes HTTP, soquetes e caches de tokens sejam liberados de forma determinística:
- Sincrônica:
com `(...)` como cliente: - Assíncrono:
async come(...) como cliente: async com DefaultAzureCredential() como credencial:(deazure.identity.aio)Trechos de código podem abreviar essa configuração, mas o código de produção deve sempre seguir ambas as regras.
O ConversationAnalysisClient aceita uma TokenCredential, como a DefaultAzureCredential. Use a credencial de token — ela funciona localmente (Azure CLI / VS Code / Developer CLI) e no Azure (identidade gerenciada, identidade de carga de trabalho) sem alteração no código.
Legado: Chave de API (implantações existentes com chave)
O código novo deve usar o DefaultAzureCredential. Use o AzureKeyCredential somente se você tiver uma implantação com chave existente que ainda não tenha sido migrada para o Entra ID — por exemplo, ambientes regulamentados que ainda estão concluindo sua implantação do Entra.
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient
endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
key = os.environ["AZURE_CONVERSATIONS_KEY"]
with ConversationAnalysisClient(endpoint, AzureKeyCredential(key)) as client:
# Consulte “Análise básica de conversas” abaixo para obter a carga útil de analyze_conversation
...
Práticas recomendadas
- Escolha entre síncrono OU assíncrono e mantenha a consistência. Não misture clientes síncronos
do azure.ai.language.conversationscom clientes assíncronosdo azure.ai.language.conversations.aiono mesmo caminho de chamada. Escolha um modo por módulo. - Sempre use gerenciadores de contexto para clientes e credenciais assíncronas. Envolva cada cliente
com ConversationAnalysisClient(...) como client:(sincrônico) ouassíncrono com ConversationAnalysisClient(...) como client:(assíncrono). Parao DefaultAzureCredentialassíncrono doazure.identity.aio, use tambéma forma assíncrona com “credential:”,para que os tokens e transportes sejam limpos. - Use
DefaultAzureCredentialpara autenticação portátil entre o ambiente de desenvolvimento local e o Azure (evite chaves de API; elas contornam a auditoria e a rotação do Entra). - Use variáveis de ambiente para o endpoint, o nome do projeto e o nome da implantação.
- Mapeie claramente o
participantIdeo idna carga útil doconversationItem.
Exemplos
Análise básica de conversas
import os
from azure.identity import DefaultAzureCredential
from azure.ai.language.conversations import ConversationAnalysisClient
endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
project_name = os.environ["AZURE_CONVERSATIONS_PROJECT"]
deployment_name = os.environ["AZURE_CONVERSATIONS_DEPLOYMENT"]
# O DefaultAzureCredential funciona localmente e no Azure sem alteração de código.
credential = DefaultAzureCredential()
com ConversationAnalysisClient(endpoint, credential) como client:
query = "Envie um e-mail para Carol sobre a reunião de amanhã"
result = client.analyze_conversation(
task={
"kind": "Conversation",
"analysisInput": {
"conversationItem": {
"participantId": "1",
"id": "1",
"modality": "text",
"language": "en",
"text": query
},
"isLoggingEnabled": False
},
"parameters": {
"projectName": project_name,
"deploymentName": deployment_name,
"verbose": True
}
}
)
print(f"Intenção principal: {result['result']['prediction']['topIntent']}")
---
name: azure-ai-language-conversations-py
description: Analyze conversation intent and entities using the Azure AI Language Conversations Python SDK with best practices for authentication and error handling.
license: MIT
---
# Azure AI Language Conversations for Python
## System Prompt
You are an expert Python developer specializing in Azure AI Services and Natural Language Processing.
Your task is to help users implement Conversational Language Understanding (CLU) using the `azure-ai-language-conversations` SDK.
When responding to requests about Azure AI Language Conversations:
1. Always use the latest version of the `azure-ai-language-conversations` SDK.
2. Emphasize the use of `ConversationAnalysisClient` with `DefaultAzureCredential`.
3. Provide clear code examples demonstrating how to structure the conversation payload.
4. Handle exceptions properly.
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
`ConversationAnalysisClient` accepts a `TokenCredential` such as `DefaultAzureCredential`. Use the token credential — it works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change.
### Legacy: API Key (existing keyed deployments)
New code should use `DefaultAzureCredential`. Use `AzureKeyCredential` only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient
endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
key = os.environ["AZURE_CONVERSATIONS_KEY"]
with ConversationAnalysisClient(endpoint, AzureKeyCredential(key)) as client:
# See "Basic Conversation Analysis" below for the analyze_conversation payload
...
```
## Best Practices
- **Pick sync OR async and stay consistent.** Do not mix `azure.ai.language.conversations` sync clients with `azure.ai.language.conversations.aio` async clients in the same call path. Choose one mode per module.
- **Always use context managers for clients and async credentials.** Wrap every client in `with ConversationAnalysisClient(...) as client:` (sync) or `async with ConversationAnalysisClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
- **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid API keys; they bypass Entra audit and rotation).
- Use environment variables for the endpoint, project name, and deployment name.
- Clearly map the `participantId` and `id` in the `conversationItem` payload.
## Examples
### Basic Conversation Analysis
```python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.language.conversations import ConversationAnalysisClient
endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
project_name = os.environ["AZURE_CONVERSATIONS_PROJECT"]
deployment_name = os.environ["AZURE_CONVERSATIONS_DEPLOYMENT"]
# DefaultAzureCredential works locally and in Azure with no code change.
credential = DefaultAzureCredential()
with ConversationAnalysisClient(endpoint, credential) as client:
query = "Send an email to Carol about the tomorrow's meeting"
result = client.analyze_conversation(
task={
"kind": "Conversation",
"analysisInput": {
"conversationItem": {
"participantId": "1",
"id": "1",
"modality": "text",
"language": "en",
"text": query
},
"isLoggingEnabled": False
},
"parameters": {
"projectName": project_name,
"deploymentName": deployment_name,
"verbose": True
}
}
)
print(f"Top intent: {result['result']['prediction']['topIntent']}") Todos os arquivos
0 arquivosInstalar azure-ai-language-conversations-py
Baixe e descompacte os arquivos das habilidades no diretório .claude/skills/.
Baixar ZIPClone o repositório e copie os arquivos da habilidade para o seu projeto.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-language-conversations-py # Copy SKILL.md to your .claude/skills/ directory
Copiar





Lar
