ビルドの状態

Python 用 Azure Conversational Language Understanding クライアント ライブラリ - バージョン 1.1.0

会話型Language Understanding (略して CLU とも呼ばれる) は、次のような多くの言語理解機能を提供するクラウドベースの会話型 AI サービスです。

  • 会話アプリ: 会話内の意図とエンティティを抽出する場合に使用されます
  • ワークフロー アプリ: オーケストレーターのように機能し、会話を分析するための最適な候補を選択して、Qna、Luis、Conversation App などのアプリから最適な応答を得ます。
  • 会話の要約: 問題/解決、章のタイトル、説明の要約の形式で会話を分析するために使用されます

ソースコード | パッケージ (PyPI) | パッケージ (Conda) | API リファレンス ドキュメント | サンプル | 製品ドキュメント | REST API のドキュメント

作業の開始

前提条件

パッケージをインストールする

pip を使用して Python 用 Azure Conversations クライアント ライブラリをインストールします。

pip install azure-ai-language-conversations

注: このバージョンのクライアント ライブラリの既定値は、サービスの 2023-04-01 バージョンです

クライアントを認証する

CLU サービスを操作するには、 ConversationAnalysisClient クラスまたは ConversationAuthoringClient クラスのインスタンスを作成する必要があります。 クライアント オブジェクトをインスタンス化するには、 エンドポイントAPI キー が必要です。 Cognitive Services での認証の詳細については、「 Azure Cognitive Services への要求を認証する」を参照してください。

API キーを取得する

エンドポイントAPI キーは、Azure Portal の Cognitive Services リソースから取得できます。

または、次に示す Azure CLI コマンドを使用して、Cognitive Service リソースから 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 は、デプロイされた Conversations モデルを使用して予測を行う主要なインターフェイスです。 非同期操作の場合、非同期 ConversationAnalysisClient は 名前空間にあります azure.ai.language.conversation.aio

ConversationAuthoringClient

ConversationAuthoringClient を使用して、Azure 言語ポータルとインターフェイスし、言語リソース/プロジェクトに対して作成操作を実行できます。 たとえば、プロジェクトの作成、トレーニング データの設定、トレーニング、テスト、デプロイに使用できます。 非同期操作の場合、非同期 ConversationAuthoringClient は 名前空間にあります azure.ai.language.conversation.authoring.aio

クライアント ライブラリには azure-ai-language-conversation 、同期 API と非同期 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、Conversation、Question Answering) の間で送信されたユーザー発話を調整するだけで、ユーザーの意図に従って最適な応答を得ることができます。 次の例を参照してください。

# 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)

オプションの構成

省略可能なキーワード (keyword)引数は、クライアントと操作ごとのレベルで渡すことができます。 azure-core リファレンス ドキュメント では、再試行、ログ記録、トランスポート プロトコルなどの使用可能な構成について説明しています。

トラブルシューティング

全般

Conversations クライアントは、 Azure Core で定義されている例外を発生させます。

ログ記録

このライブラリでは、ログ記録に標準 のログ ライブラリが使用されます。 HTTP セッションに関する基本情報 (URL、ヘッダーなど) は INFO レベルでログに記録されます。

要求/応答本文、未変換ヘッダーなど、詳細な DEBUG レベルのログは、 引数を使用してクライアントで logging_enable 有効にすることができます。

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 は、詳細なログ記録がクライアントで有効になっていない場合でも、1 回の操作のために有効にすることができます。

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

次のステップ

その他のサンプル コード

CLU Python API で使用される一般的なパターンを示すいくつかのコード スニペットについては、 README のサンプル を参照してください。

共同作成

このライブラリのビルド、テスト、および投稿の詳細については、 CONTRIBUTING.md を参照してください。

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「 cla.microsoft.com」を参照してください。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。

インプレッション数