組建狀態

適用于 Python 的 Azure 對話式Language Understanding用戶端程式庫 - 1.1.0 版

交談式Language Understanding - 也稱為CLU - 是雲端式交談式 AI 服務,可提供許多語言理解功能,例如:

  • 交談應用程式:用於擷取交談中的意圖和實體
  • 工作流程應用程式:像協調器一樣,選取最佳候選項目來分析交談,以從 Qna、Luis 和交談應用程式等應用程式取得最佳回應
  • 交談摘要:用來以問題/解決、章節標題和敘述摘要的形式分析交談

| 原始程式碼套件 (PyPI) | 封裝 (Conda) | API 參考檔 | 樣品 | 產品檔 | REST API 檔

開始使用

Prerequisites

安裝套件

使用 pip安裝適用于 Python 的 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 應用程式的用戶端識別碼、租使用者識別碼和用戶端密碼的值設定為環境變數: AZURE_CLIENT_ID 、、、 AZURE_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"]))

使用協調流程應用程式分析文字

如果您想要將使用者語句傳遞至協調器, (worflow) 應用程式,您可以使用協調流程的專案名稱呼叫 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 核心 參考檔 說明重試、記錄、傳輸通訊協定等可用的組態。

疑難排解

一般

Conversations 用戶端會引發 Azure Core中定義的例外狀況。

記錄

此程式庫會使用標準記錄程式庫進行 記錄 。 HTTP 會話的基本資訊 (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 中常用模式的數個程式碼片段,請參閱 範例讀我檔案

參與

如需建置、測試和參與此程式庫的詳細資訊,請參閱 CONTRIBUTING.md

此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資訊,請造訪 cla.microsoft.com

當您提交提取要求時,CLA Bot 會自動判斷您是否需要提供 CLA,並適當地裝飾 PR (例如標籤、註解)。 請遵循 bot 提供的指示。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。

此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com

曝光數