File: sample_conversation_multi_turn_prediction.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 (166 lines) | stat: -rw-r--r-- 6,124 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

"""
FILE: sample_conversation_multi_turn_prediction.py

DESCRIPTION:
    Run a multi-turn conversation prediction synchronously using the
    Conversational AI task. Prints intents and entities, including spans,
    datetime resolutions, and subtype/tag metadata.

USAGE:
    python sample_conversation_multi_turn_prediction.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 prefer `AzureKeyCredential`, set:
    AZURE_CONVERSATIONS_ENDPOINT
    AZURE_CONVERSATIONS_KEY
"""

# [START conversation_multi_turn_prediction]
import os

from azure.identity import DefaultAzureCredential
from azure.ai.language.conversations import ConversationAnalysisClient
from azure.ai.language.conversations.models import (
    ConversationalAITask,
    ConversationalAIAnalysisInput,
    ConversationalAIActionContent,
    TextConversation,
    TextConversationItem,
    StringIndexType,
    ConversationalAITaskResult,
    DateTimeResolution,
    EntitySubtype,
    EntityTag,
)


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

    # AAD credential
    credential = DefaultAzureCredential()

    client = ConversationAnalysisClient(endpoint, credential=credential)

    # Build a small multi-turn dialog
    data = ConversationalAITask(
        analysis_input=ConversationalAIAnalysisInput(
            conversations=[
                TextConversation(
                    id="order",
                    language="en-GB",
                    conversation_items=[
                        TextConversationItem(id="1", participant_id="user", text="Hi"),
                        TextConversationItem(id="2", participant_id="bot", text="Hello, how can I help you?"),
                        TextConversationItem(
                            id="3",
                            participant_id="user",
                            text="Send an email to Carol about tomorrow's demo",
                        ),
                    ],
                )
            ]
        ),
        parameters=ConversationalAIActionContent(
            project_name=project_name,
            deployment_name=deployment_name,
            string_index_type=StringIndexType.UTF16_CODE_UNIT,
        ),
    )

    # Sync call
    response = client.analyze_conversation(data)

    if isinstance(response, ConversationalAITaskResult):
        ai_result = response.result
        if not ai_result or not ai_result.conversations:
            print("No conversations found in result.")
            return

        for conversation in ai_result.conversations or []:
            print(f"Conversation ID: {conversation.id}\n")

            # Intents
            print("Intents:")
            for intent in conversation.intents or []:
                print(f"  Name: {intent.name}")
                print(f"  Type: {intent.type}")

                print("  Conversation Item Ranges:")
                for rng in intent.conversation_item_ranges or []:
                    print(f"    - Offset: {rng.offset}, Count: {rng.count}")

                print("\n  Entities (Scoped to Intent):")
                for ent in intent.entities or []:
                    print(f"    Name: {ent.name}")
                    print(f"    Text: {ent.text}")
                    print(f"    Confidence: {ent.confidence_score}")
                    print(f"    Offset: {ent.offset}, Length: {ent.length}")
                    print(
                        f"    Conversation Item ID: {ent.conversation_item_id}, "
                        f"Index: {ent.conversation_item_index}"
                    )

                    # Date/time resolutions
                    for res in ent.resolutions or []:
                        if isinstance(res, DateTimeResolution):
                            print(
                                f"    - [DateTimeResolution] SubKind: {res.date_time_sub_kind}, "
                                f"Timex: {res.timex}, Value: {res.value}"
                            )

                    # Extra information (entity subtype + tags)
                    for extra in ent.extra_information or []:
                        if isinstance(extra, EntitySubtype):
                            print(f"    - [EntitySubtype] Value: {extra.value}")
                            for tag in extra.tags or []:
                                print(f"      • Tag: {tag.name}, Confidence: {tag.confidence_score}")
                print()

                # Global entities
                print("Global Entities:")
                for ent in conversation.entities or []:
                    print(f"  Name: {ent.name}")
                    print(f"  Text: {ent.text}")
                    print(f"  Confidence: {ent.confidence_score}")
                    print(f"  Offset: {ent.offset}, Length: {ent.length}")
                    print(
                        f"  Conversation Item ID: {ent.conversation_item_id}, " f"Index: {ent.conversation_item_index}"
                    )

                    for extra in ent.extra_information or []:
                        if isinstance(extra, EntitySubtype):
                            print(f"    - [EntitySubtype] Value: {extra.value}")
                            for tag in extra.tags or []:
                                print(f"      • Tag: {tag.name}, Confidence: {tag.confidence_score}")
                print("-" * 40)
    else:
        print("No Conversational AI result returned.")


# [END conversation_multi_turn_prediction]


def main():
    sample_conversation_multi_turn_prediction()


if __name__ == "__main__":
    main()