选项
首页首页 Skill 数据科学与机器学习 azure-ai-language-conversations-py

azure-ai-language-conversations-py

microsoft/skills microsoft/skills

使用 Azure AI Language Conversations Python SDK 分析对话意图和实体,并遵循身份验证和错误处理的最佳实践。

...展开全部
3
更新时间 2026-09-18

适用于 Python 的 Azure AI 语言对话

系统提示

您是一位精通 Python 的开发人员,专精于 Azure AI 服务和自然语言处理。 您的任务是帮助用户使用azure-ai-language-conversationsSDK 实现会话语言理解 (CLU)。

在回应有关 Azure AI 语言对话的请求时:

  1. 请始终使用最新版本的azure-ai-language-conversationsSDK。
  2. 强调应使用带DefaultAzureCredentialConversationAnalysisClient
  3. 提供清晰的代码示例,演示如何构建对话有效载荷。
  4. 正确处理异常。

身份验证与生命周期

🔑 以下所有代码示例均需遵循两条规则:

  1. 优先使用DefaultAzureCredential它既可在本地(Azure CLI / VS Code / Developer CLI)使用,也可在 Azure 中(托管身份、工作负载身份)使用,且无需修改代码。避免使用连接字符串、账户/API 密钥——它们会绕过 Entra 的审计和轮换机制。
    • 本地开发:DefaultAzureCredential直接即可使用。
    • 生产环境:将AZURE_TOKEN_CREDENTIALS设置为prod(或AZURE_TOKEN_CREDENTIALS= ),以将凭据链限制为生产环境安全的凭据。
  2. 将每个客户端封装在上下文管理器中,以确保 HTTP 传输、套接字和令牌缓存能以可预测的方式被释放:
    • 同步模式:使用 `(...) as client:`
    • 异步:async with(...) as client: 以及 async with DefaultAzureCredential() as credential:(来自azure.identity.aio

代码片段可能会简化此配置,但生产环境中的代码应始终遵循这两条规则。

ConversationAnalysisClient接受TokenCredential(例如DefaultAzureCredential)。请使用令牌凭据——它既可在本地(Azure CLI / VS Code / Developer CLI)使用,也可在 Azure 中(托管身份、工作负载身份)使用,且无需修改代码。

旧版:API 密钥(现有基于密钥的部署)

新代码应使用DefaultAzureCredential。仅当您有尚未迁移到 Entra ID 的现有基于密钥的部署时,才应使用AzureKeyCredential—— 例如,仍在完成 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:
    # 有关 analyze_conversation 有效负载的详细信息,请参阅下文“基本对话分析”
    ...

最佳实践

  • 请选择同步或异步模式,并保持一致。请勿在同一调用路径中将azure.ai.language.conversations的同步客户端与azure.ai.language.conversations.aio的异步客户端混合使用。每个模块应选择一种模式。
  • 始终为客户端和异步凭据使用上下文管理器。将每个客户端封装在`ConversationAnalysisClient(...) as client:`(同步)或`ConversationAnalysisClient(...) as client:`异步。 对于来自azure.identity.aio 的异步DefaultAzureCredential,也应使用异步方式并指定 credential:,以便对令牌和传输进行清理。
  • 使用DefaultAzureCredential实现本地开发环境与 Azure 之间的可移植身份验证(避免使用 API 密钥;它们会绕过 Entra 审计和轮换机制)。
  • 请使用环境变量设置端点、项目名称和部署名称。
  • conversationItem有效负载中明确映射participantIdid

示例

基础对话分析

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 无需修改代码即可在本地和 Azure 中使用。
credential = DefaultAzureCredential()

with ConversationAnalysisClient(endpoint, credential) as client:
    query = "给 Carol 发一封关于明天会议的电子邮件"
    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"首要意图:{result['result']['prediction']['topIntent']}")
在 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']}")

所有文件

0 个文件

安装 azure-ai-language-conversations-py

下载技能文件并将其解压到 .claude/skills/ 目录中。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

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

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ Claude 会自动检测并使用该技能

相关技能

web-search
更新时间 2026-06-29
webapp-testing
更新时间 2026-06-29
lark-base
更新时间 2026-07-05
agentmail
更新时间 2026-06-29
OR