File: sample_conversation_prediction_with_language_async.py

package info (click to toggle)
python-azure 20251118%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 783,356 kB
  • sloc: python: 6,474,533; ansic: 804; javascript: 287; sh: 205; makefile: 198; xml: 109
file content (121 lines) | stat: -rw-r--r-- 4,225 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

"""
FILE: sample_conversation_prediction_with_language_async.py

DESCRIPTION:
    This sample demonstrates how to analyze an utterance in a non-English language
    (Spanish in this example) using a CLU Conversation project (async).

USAGE:
    python sample_conversation_prediction_with_language_async.py

REQUIRED ENV VARS (for AAD / DefaultAzureCredential):
    AZURE_CONVERSATIONS_ENDPOINT
    AZURE_CLIENT_ID
    AZURE_TENANT_ID
    AZURE_CLIENT_SECRET
    AZURE_CONVERSATIONS_PROJECT_NAME
    AZURE_CONVERSATIONS_DEPLOYMENT_NAME

NOTE:
    If you want to use AzureKeyCredential instead, set:
      - AZURE_CONVERSATIONS_ENDPOINT
      - AZURE_CONVERSATIONS_KEY
"""

# [START conversation_prediction_with_language_async]
import os
import asyncio

from azure.identity.aio import DefaultAzureCredential
from azure.ai.language.conversations.aio import ConversationAnalysisClient
from azure.ai.language.conversations.models import (
    ConversationLanguageUnderstandingInput,
    ConversationAnalysisInput,
    TextConversationItem,
    ConversationActionContent,
    StringIndexType,
    ConversationActionResult,
    ConversationPrediction,
    DateTimeResolution,
)


async def sample_conversation_prediction_with_language_async():
    # settings
    endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
    project_name = os.environ["AZURE_CONVERSATIONS_PROJECT_NAME"]
    deployment_name = os.environ["AZURE_CONVERSATIONS_DEPLOYMENT_NAME"]

    credential = DefaultAzureCredential()

    async with ConversationAnalysisClient(endpoint, credential=credential) as client:
        # build request with Spanish input text
        data = ConversationLanguageUnderstandingInput(
            conversation_input=ConversationAnalysisInput(
                conversation_item=TextConversationItem(
                    id="1",
                    participant_id="participant1",
                    text="Enviar un email a Carol acerca de la presentación de mañana",
                    language="es",  # specify input language
                )
            ),
            action_content=ConversationActionContent(
                project_name=project_name,
                deployment_name=deployment_name,
                string_index_type=StringIndexType.UTF16_CODE_UNIT,
                verbose=True,
            ),
        )

        # call async API
        response = await client.analyze_conversation(data)

        if isinstance(response, ConversationActionResult):
            pred = response.result.prediction
            if isinstance(pred, ConversationPrediction):
                # top intent
                print(f"Top intent: {pred.top_intent}\n")

                # intents
                print("Intents:")
                for intent in pred.intents or []:
                    print(f"  Category: {intent.category}")
                    print(f"  Confidence: {intent.confidence}")
                    print()

                # entities
                print("Entities:")
                for entity in pred.entities or []:
                    print(f"  Category: {entity.category}")
                    print(f"  Text: {entity.text}")
                    print(f"  Offset: {entity.offset}")
                    print(f"  Length: {entity.length}")
                    print(f"  Confidence: {entity.confidence}")

                    for res in entity.resolutions or []:
                        if isinstance(res, DateTimeResolution):
                            print("  DateTime Resolution:")
                            print(f"    Sub Kind: {res.date_time_sub_kind}")
                            print(f"    Timex: {res.timex}")
                            print(f"    Value: {res.value}")
                    print()
        else:
            print("Unexpected result type from analyze_conversation.")


# [END conversation_prediction_with_language_async]


async def main():
    await sample_conversation_prediction_with_language_async()


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())