跳转到主要内容

Microsoft Azure Python会话语言理解客户端库

项目描述

Build Status

Azure会话语言理解Python客户端库

会话语言理解 - 简称 CLU - 是一种基于云的会话式人工智能服务,提供许多语言理解功能,如

  • 会话应用:用于从会话中提取意图和实体
  • 工作流应用:作为协调器,选择最佳候选者来分析会话,从而从Qna、Luis和会话应用等应用中获取最佳响应
  • 会话摘要:用于分析以问题/解决方案、章节标题和叙述摘要形式呈现的会话

源代码 | 包(PyPI) | 包(Conda) | API参考文档 | 示例 | 产品文档 | REST API文档

入门

先决条件

安装包

使用pip安装Azure Conversations客户端库

pip install azure-ai-language-conversations

注意:此版本的客户端库默认使用服务的2023-04-01版本

认证客户端

为了与CLU服务交互,您需要创建一个ConversationAnalysisClient类实例或ConversationAuthoringClient类实例。您需要一个端点和一个API密钥来实例化客户端对象。有关使用认知服务进行认证的更多信息,请参阅认证Azure认知服务请求

获取API密钥

您可以从Azure门户中的认知服务资源中获取端点API密钥

或者,使用以下Azure CLI命令从认知服务资源中获取API密钥。

az cognitiveservices account keys list --resource-group <resource-group-name> --name <resource-name>

创建ConversationAnalysisClient

一旦确定您的端点API密钥,您就可以实例化一个ConversationAnalysisClient

from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api-key>")
client = ConversationAnalysisClient(endpoint, credential)

创建ConversationAuthoringClient

一旦确定您的端点API密钥,您就可以实例化一个ConversationAuthoringClient

from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations.authoring import ConversationAuthoringClient

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api-key>")
client = ConversationAuthoringClient(endpoint, credential)

使用Azure Active Directory凭证创建客户端

要使用Azure Active Directory (AAD)令牌凭证,请提供一个从azure-identity库获取的所需凭证类型的实例。请注意,区域端点不支持AAD认证。为您的资源创建一个自定义子域名,以便使用此类型的认证。

AAD认证需要一些初始设置

设置后,您可以选择使用azure.identity中哪种类型的凭证。例如,可以使用DefaultAzureCredential来认证客户端

将AAD应用程序的客户端ID、租户ID和客户端密钥设置为环境变量: AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET

使用返回的令牌凭证来认证客户端

from azure.ai.language.conversations import ConversationAnalysisClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
client = ConversationAnalysisClient(endpoint="https://<my-custom-subdomain>.cognitiveservices.azure.com/", credential=credential)

关键概念

ConversationAnalysisClient

《ConversationAnalysisClient》是使用已部署的对话模型进行预测的主要接口。对于异步操作,异步的ConversationAnalysisClient位于azure.ai.language.conversation.aio命名空间中。

ConversationAuthoringClient

您可以使用ConversationAuthoringClientAzure 语言门户进行接口,以在您的语言资源/项目中执行作者操作。例如,您可以使用它来创建项目、填充训练数据、训练、测试和部署。对于异步操作,异步的ConversationAuthoringClient位于azure.ai.language.conversation.authoring.aio命名空间中。

示例

《azure-ai-language-conversation》客户端库提供了同步和异步API。

以下示例显示了使用上述创建的client的常见场景。

使用对话应用程序分析文本

如果您想从用户的语句中提取自定义意图和实体,您可以调用以下方法的client.analyze_conversation(),使用您的对话的项目名称

# import libraries
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient

# get secrets
clu_endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
clu_key = os.environ["AZURE_CONVERSATIONS_KEY"]
project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"]
deployment_name = os.environ["AZURE_CONVERSATIONS_DEPLOYMENT_NAME"]

# analyze quey
client = ConversationAnalysisClient(clu_endpoint, AzureKeyCredential(clu_key))
with client:
    query = "Send an email to Carol about the tomorrow's demo"
    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
            }
        }
    )

# view result
print("query: {}".format(result["result"]["query"]))
print("project kind: {}\n".format(result["result"]["prediction"]["projectKind"]))

print("top intent: {}".format(result["result"]["prediction"]["topIntent"]))
print("category: {}".format(result["result"]["prediction"]["intents"][0]["category"]))
print("confidence score: {}\n".format(result["result"]["prediction"]["intents"][0]["confidenceScore"]))

print("entities:")
for entity in result["result"]["prediction"]["entities"]:
    print("\ncategory: {}".format(entity["category"]))
    print("text: {}".format(entity["text"]))
    print("confidence score: {}".format(entity["confidenceScore"]))
    if "resolutions" in entity:
        print("resolutions")
        for resolution in entity["resolutions"]:
            print("kind: {}".format(resolution["resolutionKind"]))
            print("value: {}".format(resolution["value"]))
    if "extraInformation" in entity:
        print("extra info")
        for data in entity["extraInformation"]:
            print("kind: {}".format(data["extraInformationKind"]))
            if data["extraInformationKind"] == "ListKey":
                print("key: {}".format(data["key"]))
            if data["extraInformationKind"] == "EntitySubtype":
                print("value: {}".format(data["value"]))

使用编排应用程序分析文本

如果您想将用户语句传递到您的编排应用程序(工作流)中,您可以调用带有您的编排项目名称的client.analyze_conversation()方法。编排项目只是简单地编排提交的用户语句,在您的语言应用程序(Luis、对话和问答)之间,根据用户意图获取最佳响应。请看下一个示例

# import libraries
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient

# get secrets
clu_endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
clu_key = os.environ["AZURE_CONVERSATIONS_KEY"]
project_name = os.environ["AZURE_CONVERSATIONS_WORKFLOW_PROJECT_NAME"]
deployment_name = os.environ["AZURE_CONVERSATIONS_WORKFLOW_DEPLOYMENT_NAME"]

# analyze query
client = ConversationAnalysisClient(clu_endpoint, AzureKeyCredential(clu_key))
with client:
    query = "Reserve a table for 2 at the Italian restaurant"
    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
            }
        }
    )

# view result
print("query: {}".format(result["result"]["query"]))
print("project kind: {}\n".format(result["result"]["prediction"]["projectKind"]))

# top intent
top_intent = result["result"]["prediction"]["topIntent"]
print("top intent: {}".format(top_intent))
top_intent_object = result["result"]["prediction"]["intents"][top_intent]
print("confidence score: {}".format(top_intent_object["confidenceScore"]))
print("project kind: {}".format(top_intent_object["targetProjectKind"]))

if top_intent_object["targetProjectKind"] == "Luis":
    print("\nluis response:")
    luis_response = top_intent_object["result"]["prediction"]
    print("top intent: {}".format(luis_response["topIntent"]))
    print("\nentities:")
    for entity in luis_response["entities"]:
        print("\n{}".format(entity))

对话摘要

如果您需要将对话总结为问题及其最终解决方案的形式,则可以使用此示例。例如,技术支持对话

# import libraries
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient
# get secrets
endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
key = os.environ["AZURE_CONVERSATIONS_KEY"]
# analyze query
client = ConversationAnalysisClient(endpoint, AzureKeyCredential(key))
with client:
    poller = client.begin_conversation_analysis(
        task={
            "displayName": "Analyze conversations from xxx",
            "analysisInput": {
                "conversations": [
                    {
                        "conversationItems": [
                            {
                                "text": "Hello, how can I help you?",
                                "modality": "text",
                                "id": "1",
                                "participantId": "Agent"
                            },
                            {
                                "text": "How to upgrade Office? I am getting error messages the whole day.",
                                "modality": "text",
                                "id": "2",
                                "participantId": "Customer"
                            },
                            {
                                "text": "Press the upgrade button please. Then sign in and follow the instructions.",
                                "modality": "text",
                                "id": "3",
                                "participantId": "Agent"
                            }
                        ],
                        "modality": "text",
                        "id": "conversation1",
                        "language": "en"
                    },
                ]
            },
            "tasks": [
                {
                    "taskName": "Issue task",
                    "kind": "ConversationalSummarizationTask",
                    "parameters": {
                        "summaryAspects": ["issue"]
                    }
                },
                {
                    "taskName": "Resolution task",
                    "kind": "ConversationalSummarizationTask",
                    "parameters": {
                        "summaryAspects": ["resolution"]
                    }
                },
            ]
        }
    )

    # view result
    result = poller.result()
    task_results = result["tasks"]["items"]
    for task in task_results:
        print(f"\n{task['taskName']} status: {task['status']}")
        task_result = task["results"]
        if task_result["errors"]:
            print("... errors occurred ...")
            for error in task_result["errors"]:
                print(error)
        else:
            conversation_result = task_result["conversations"][0]
            if conversation_result["warnings"]:
                print("... view warnings ...")
                for warning in conversation_result["warnings"]:
                    print(warning)
            else:
                summaries = conversation_result["summaries"]
                print("... view task result ...")
                for summary in summaries:
                    print(f"{summary['aspect']}: {summary['text']}")

导入对话项目

此示例显示了SDK作者部分的常见场景

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations.authoring import ConversationAuthoringClient

clu_endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
clu_key = os.environ["AZURE_CONVERSATIONS_KEY"]

project_name = "test_project"

exported_project_assets = {
    "projectKind": "Conversation",
    "intents": [{"category": "Read"}, {"category": "Delete"}],
    "entities": [{"category": "Sender"}],
    "utterances": [
        {
            "text": "Open Blake's email",
            "dataset": "Train",
            "intent": "Read",
            "entities": [{"category": "Sender", "offset": 5, "length": 5}],
        },
        {
            "text": "Delete last email",
            "language": "en-gb",
            "dataset": "Test",
            "intent": "Delete",
            "entities": [],
        },
    ],
}

client = ConversationAuthoringClient(
    clu_endpoint, AzureKeyCredential(clu_key)
)
poller = client.begin_import_project(
    project_name=project_name,
    project={
        "assets": exported_project_assets,
        "metadata": {
            "projectKind": "Conversation",
            "settings": {"confidenceThreshold": 0.7},
            "projectName": "EmailApp",
            "multilingual": True,
            "description": "Trying out CLU",
            "language": "en-us",
        },
        "projectFileVersion": "2022-05-01",
    },
)
response = poller.result()
print(response)

可选配置

您可以在客户端和每个操作级别传递可选关键字参数。azure-core 参考文档描述了重试、日志记录、传输协议等可用的配置。

故障排除

一般

Conversations客户端将引发在Azure Core中定义的异常。

日志记录

此库使用标准logging库进行日志记录。基本信息(URL、头等)在INFO级别记录。

可以通过带有logging_enable参数的客户端启用详细的DEBUG级别日志记录,包括请求/响应正文和未编辑的头。

有关示例,请参阅完整的SDK日志记录文档此处

import sys
import logging
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<my-api-key>")

# This client will log detailed information about its HTTP sessions, at DEBUG level
client = ConversationAnalysisClient(endpoint, credential, logging_enable=True)
result = client.analyze_conversation(...)

同样,即使未为客户端启用,logging_enable也可以为单个操作启用详细日志记录

result = client.analyze_conversation(..., logging_enable=True)

下一步

更多示例代码

有关在CLU Python API中使用的常见模式的代码片段,请参阅示例README

贡献

有关构建、测试和为此库做出贡献的详细信息,请参阅CONTRIBUTING.md

此项目欢迎贡献和建议。大多数贡献都需要您同意贡献者许可协议(CLA),声明您有权并且实际上确实授予我们使用您的贡献的权利。有关详细信息,请访问cla.microsoft.com

当您提交拉取请求时,CLA机器人会自动判断您是否需要提供CLA,并相应地装饰PR(例如,标签、注释)。只需遵循机器人提供的说明。您只需在所有使用我们CLA的仓库中做一次即可。

本项目采用了微软开源行为准则。更多信息请参阅行为准则FAQ或通过opencode@microsoft.com联系,如有任何其他问题或评论。

Impressions

发布历史

1.1.0 (2023-06-13)

新增功能

  • 添加了对服务版本2023-04-01的支持。

重大变更

注意:以下变更仅从上一个beta版本开始产生影响。由于那些类型和成员在1.0.0版本中不存在,因此它们不会在1.0.0版本中产生重大变更。

  • 移除了对服务版本2022-05-15-preview的支持。
  • 移除了对服务版本2022-10-01-preview的支持。
  • 移除了使用ConversationAnalysisClient对"ConversationalPIITask"进行分析的支持。
  • 移除了使用ConversationAnalysisClient对"ConversationalSentimentTask"的支持。
  • ConversationAuthoringClient中移除了以下方法
    • begin_assign_deployment_resources
    • get_assign_deployment_resources_status
    • begin_unassign_deployment_resources
    • get_unassign_deployment_resources_status
    • begin_delete_deployment_from_resources
    • get_deployment_delete_from_resources_status
    • list_assigned_resource_deployments
    • list_deployment_resources

1.1.0b3 (2022-11-10)

新增功能

  • 添加了对"ConversationalSentimentTask"类型的支持,使用begin_conversation_analysis
  • 为ConversationalSummarizationTasks添加了"chapterTitle"和"narrative"的summaryAspects选项。
  • ConversationAuthoringClient中添加了管理部署资源的方法
    • begin_assign_deployment_resources
    • get_assign_deployment_resources_status
    • begin_unassign_deployment_resources
    • get_unassign_deployment_resources_status
    • begin_delete_deployment_from_resources
    • get_deployment_delete_from_resources_status
    • begin_load_snapshot
    • get_load_snapshot_status
    • list_assigned_resource_deployments
    • list_deployment_resources
  • begin_export_project中添加了可选的trained_model_label关键字参数。

其他变更

  • 此版本及所有未来版本将需要Python 3.7+。Python 3.6不再受支持。

1.1.0b2 (2022-07-01)

新增功能

  • 添加了Azure Active Directory (AAD)身份验证支持
  • 添加了在azure.ai.language.conversations.authoring命名空间下使用ConversationAuthoringClient进行创作操作的支持。

1.0.0 (2022-06-27)

新增功能

  • 添加了Azure Active Directory (AAD)身份验证支持
  • 为实体添加了更多解析类型
  • 添加了在azure.ai.language.conversations.authoring命名空间下使用ConversationAuthoringClient进行创作操作的支持。

重大变更

  • 客户端现在使用Python字典作为方法参数和结果的类型,而不是类。

1.1.0b1 (2022-05-26)

新增功能

  • 对话摘要任务(长运行操作)
  • 对话PII提取任务(长运行操作)

重大变更

  • 客户端现在使用Python字典作为方法参数和结果的类型,而不是类。
  • analyze_conversation()方法中许多输入和结果参数的名称发生了变化

1.0.0b3 (2022-04-19)

新增功能

  • 实体解析
  • 额外功能

重大变更

  • 用作analyze_conversation操作输入的ConversationAnalysisOptions模型现在被包装在CustomConversationalTask中,该模型将分析选项与项目参数合并为单个模型。
  • ConversationAnalysisOptions中的query现在进一步指定为带有额外属性的TextConversationItem
  • 根据输入模型,输出AnalyzeConversationResult现在被包装在CustomConversationalTaskResult中。

其他变更

  • Python 2.7不再受支持。请使用Python 3.6或更高版本。

1.0.0b1 (2021-11-03)

新增功能

  • 首次发布

项目详情


下载文件

下载您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码分发

azure-ai-language-conversations-1.1.0.zip (186.2 kB 查看哈希值)

上传时间 源代码

构建分发

azure_ai_language_conversations-1.1.0-py3-none-any.whl (122.0 kB 查看哈希值)

上传时间 Python 3

支持者