File: test_conversation_multi_turn_prediction_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 (167 lines) | stat: -rw-r--r-- 7,284 bytes parent folder | download | duplicates (2)
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
167
# pylint: disable=line-too-long,useless-suppression
import functools
import pytest

from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy
from azure.ai.language.conversations.aio import ConversationAnalysisClient
from azure.ai.language.conversations.models import (
    ConversationalAITask,
    ConversationalAIAnalysisInput,
    TextConversation,
    TextConversationItem,
    ConversationalAIActionContent,
    AnalyzeConversationActionResult,
    StringIndexType,
    ConversationalAITaskResult,
    ConversationalAIResult,
    ConversationalAIAnalysis,
    ConversationalAIIntent,
    ConversationalAIEntity,
    ConversationItemRange,
    DateTimeResolution,
    EntitySubtype,
    EntityTag,
)
from typing import cast
from devtools_testutils.aio import recorded_by_proxy_async
from azure.core.async_paging import AsyncItemPaged

from azure.core.credentials import AzureKeyCredential

ConversationsPreparer = functools.partial(
    EnvironmentVariableLoader,
    "conversations",
    conversations_endpoint="https://Sanitized.cognitiveservices.azure.com/",
    conversations_key="fake_key",
)


class TestConversations(AzureRecordedTestCase):

    # Start with any helper functions you might need, for example a client creation method:
    async def create_client(self, endpoint, key):
        credential = AzureKeyCredential(key)
        client = ConversationAnalysisClient(endpoint, credential)
        return client

    ...


class TestConversationsCase(TestConversations):
    @ConversationsPreparer()
    @recorded_by_proxy_async
    @pytest.mark.asyncio
    async def test_conversation_multi_turn_prediction_async(self, conversations_endpoint, conversations_key):
        client = await self.create_client(conversations_endpoint, conversations_key)

        try:
            project_name = "EmailApp"
            deployment_name = "production"

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

            # Async call
            response: AnalyzeConversationActionResult = await client.analyze_conversation(data)

            # Cast to ConversationalAI task result
            ai_task_result = cast(ConversationalAITaskResult, response)
            ai_result: ConversationalAIResult = ai_task_result.result

            # Basic sanity
            assert ai_result is not None
            assert ai_result.conversations is not None

            # Iterate conversations
            for conversation in ai_result.conversations or []:
                conversation = cast(ConversationalAIAnalysis, conversation)
                print(f"Conversation ID: {conversation.id}\n")

                # Intents
                print("Intents:")
                for intent in conversation.intents or []:
                    intent = cast(ConversationalAIIntent, intent)
                    print(f"  Name: {intent.name}")
                    print(f"  Type: {getattr(intent, 'type', None)}")

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

                    print("\n  Entities (Scoped to Intent):")
                    for ent in intent.entities or []:
                        ent = cast(ConversationalAIEntity, ent)
                        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
                        if ent.resolutions:
                            for res in ent.resolutions:
                                if isinstance(res, DateTimeResolution):
                                    print(
                                        f"    - [DateTimeResolution] SubKind: {getattr(res, 'date_time_sub_kind', None)}, "
                                        f"Timex: {res.timex}, Value: {res.value}"
                                    )

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

                    print()

                # Global entities
                print("Global Entities:")
                for ent in conversation.entities or []:
                    ent = cast(ConversationalAIEntity, ent)
                    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}"
                    )

                    if ent.extra_information:
                        for extra in ent.extra_information:
                            if isinstance(extra, EntitySubtype):
                                print(f"    - [EntitySubtype] Value: {extra.value}")
                                for tag in extra.tags or []:
                                    tag = cast(EntityTag, tag)
                                    print(f"      • Tag: {tag.name}, Confidence: {tag.confidence_score}")
                print("-" * 40)
        finally:
            await client.close()