빌드 상태

Python용 Azure 대화형 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 클래스의 instance 만들어야 합니다. 클라이언트 개체를 인스턴스화하려면 엔드포인트API 키가 필요합니다. Cognitive Services 인증에 대한 자세한 내용은 Azure Cognitive Services에 대한 요청 인증을 참조하세요.

API 키 가져오기

Azure Portal의 Cognitive Services 리소스에서 엔드포인트API 키를 가져올 수 있습니다.

또는 아래 표시된 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 자격 증명을 사용하여 클라이언트 만들기

AAD(Azure Active Directory) 토큰 자격 증명을 사용하려면 azure-identity 라이브러리에서 가져온 원하는 자격 증명 형식의 instance 제공합니다. 지역 엔드포인트는 AAD 인증을 지원하지 않습니다. 이 유형의 인증을 사용하기 위해 리소스에 대한 사용자 지정 하위 도메인 이름을 만듭니다.

AAD를 사용하여 인증하려면 몇 가지 초기 설정이 필요합니다.

설치 후 azure.identity에서 사용할 자격 증명 유형을 선택할 수 있습니다. 예를 들어 DefaultAzureCredential을 사용하여 클라이언트를 인증할 수 있습니다.

AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. 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

ConversationAuthoringClient를 사용하여 Azure 언어 포털과 인터페이스하여 언어 리소스/프로젝트에 대한 제작 작업을 수행할 수 있습니다. 예를 들어 프로젝트를 만들고, 학습 데이터로 채우고, 학습, 테스트 및 배포하는 데 사용할 수 있습니다. 비동기 작업의 경우 비동 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, 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_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 참조 설명서 에서는 재시도, 로깅, 전송 프로토콜 등에 사용할 수 있는 구성에 대해 설명합니다.

문제 해결

일반

대화 클라이언트는 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은 클라이언트에 대해 상세 로깅을 사용하지 않는 경우에도 한 작업에만 사용하게 설정할 수 있습니다.

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

다음 단계

추가 샘플 코드

CLU Python API에서 사용되는 일반적인 패턴을 보여 주는 여러 코드 조각은 샘플 추가 정보 를 참조하세요.

참여

이 라이브러리의 빌드, 테스트 및 기여에 대한 자세한 내용은 CONTRIBUTING.md 참조하세요.

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.

Impressions