opción
HogarHogar Skill Ciencia de datos y aprendizaje automático azure-ai-language-conversations-py

azure-ai-language-conversations-py

microsoft/skills microsoft/skills

Analiza la intención y las entidades de una conversación utilizando el SDK de Python de Azure AI Language Conversations, siguiendo las prácticas recomendadas para la autenticación y la gestión de errores.

...Expandir todo
3
Tiempo actualizado 18 de septiembre de 2026

Azure AI Language Conversations para Python

Mensaje del sistema

Eres un desarrollador experto en Python especializado en los servicios de Azure AI y el procesamiento del lenguaje natural. Tu tarea consiste en ayudar a los usuarios a implementar la comprensión del lenguaje conversacional (CLU) mediante el SDK de azure-ai-language-conversations.

Al responder a consultas sobre Azure AI Language Conversations:

  1. Utiliza siempre la última versión del SDK de azure-ai-language-conversations.
  2. Haz hincapié en el uso de ConversationAnalysisClient con DefaultAzureCredential.
  3. Proporcione ejemplos de código claros que muestren cómo estructurar la carga útil de la conversación.
  4. Gestiona las excepciones correctamente.

Autenticación y ciclo de vida

🔑 Hay dos reglas que se aplican a todos los ejemplos de código que aparecen a continuación:

  1. Da prioridad a DefaultAzureCredential. Funciona tanto a nivel local (Azure CLI / VS Code / Developer CLI) como en Azure (identidad gestionada, identidad de carga de trabajo) sin necesidad de modificar el código. Evita las cadenas de conexión y las claves de cuenta o API, ya que estas eluden la auditoría y la rotación de Entra.
    • Desarrollo local: DefaultAzureCredential funciona tal cual.
    • Producción: establece AZURE_TOKEN_CREDENTIALS=prod (o AZURE_TOKEN_CREDENTIALS=) para limitar la cadena de credenciales a aquellas seguras para producción.
  2. Envuelve cada cliente en un gestor de contexto para que los transportes HTTP, los sockets y las cachés de tokens se liberen de forma determinista:
    • Sincrónico: con (...) como cliente:
    • Asíncrono: async con (...) como cliente: y async con DefaultAzureCredential() como credencial: (de azure.identity.aio)

Los fragmentos de código pueden abreviar esta configuración, pero el código de producción siempre debe seguir ambas reglas.

ConversationAnalysisClient acepta una TokenCredential como DefaultAzureCredential. Utiliza la credencial de token: funciona tanto a nivel local (Azure CLI / VS Code / Developer CLI) como en Azure (identidad gestionada, identidad de carga de trabajo) sin necesidad de modificar el código.

Herencia: clave de API (implementaciones con clave existentes)

El código nuevo debe utilizar DefaultAzureCredential. Utiliza AzureKeyCredential solo si tienes una implementación con clave ya existente que aún no se haya migrado a Entra ID; por ejemplo, entornos regulados que aún estén completando su implementación de 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álisis básico de conversaciones» más abajo para ver la carga útil de analyze_conversation
    ...

Prácticas recomendadas

  • Elige entre sincrónico O asíncrono y mantén la coherencia. No mezcles clientes sincrónicos de azure.ai.language.conversations con clientes asíncronos de azure.ai.language.conversations.aio en la misma ruta de llamada. Elige un modo por módulo.
  • Utilice siempre gestores de contexto para los clientes y las credenciales asíncronas. Envuelva cada cliente con ConversationAnalysisClient(...) como cliente: (sincrónico) o asíncrono con ConversationAnalysisClient(...) como cliente: (asíncrono). Para el modo asíncrono, utiliza DefaultAzureCredential de azure.identity.aio y, además, utiliza el modo asíncrono con «credential:», de modo que se eliminen los tokens y los transportes.
  • Utilice DefaultAzureCredential para una autenticación portátil entre el desarrollo local y Azure (evite las claves de API, ya que eluden la auditoría y la rotación de Entra).
  • Utilice variables de entorno para el punto final, el nombre del proyecto y el nombre de la implementación.
  • Asigna claramente el participantId y el id en la carga útil de conversationItem.

Ejemplos

Análisis básico de conversaciones

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 funciona tanto localmente como en Azure sin necesidad de modificar el código.
credential = DefaultAzureCredential()

with ConversationAnalysisClient(endpoint, credential) as client:
    query = "Envía un correo electrónico a Carol sobre la reunión de mañana"
    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"Intención principal: {result['result']['prediction']['topIntent']}")
Ver en GitHub
---
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 los archivos

0 archivos

Instalar azure-ai-language-conversations-py

Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

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 Copiar
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

web-search
Tiempo actualizado 29 de junio de 2026
webapp-testing
Tiempo actualizado 29 de junio de 2026
lark-base
Tiempo actualizado 5 de julio de 2026
agentmail
Tiempo actualizado 29 de junio de 2026
OR