agent-framework-a2a 1.0.0b251105__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_framework_a2a-1.0.0b251105/LICENSE +21 -0
- agent_framework_a2a-1.0.0b251105/PKG-INFO +46 -0
- agent_framework_a2a-1.0.0b251105/README.md +20 -0
- agent_framework_a2a-1.0.0b251105/agent_framework_a2a/__init__.py +15 -0
- agent_framework_a2a-1.0.0b251105/agent_framework_a2a/_agent.py +401 -0
- agent_framework_a2a-1.0.0b251105/pyproject.toml +88 -0
- agent_framework_a2a-1.0.0b251105/tests/test_a2a_agent.py +556 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Microsoft Corporation.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-framework-a2a
|
|
3
|
+
Version: 1.0.0b251105
|
|
4
|
+
Summary: A2A integration for Microsoft Agent Framework.
|
|
5
|
+
Author-email: Microsoft <af-support@microsoft.com>
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: agent-framework-core
|
|
20
|
+
Requires-Dist: a2a-sdk>=0.3.5
|
|
21
|
+
Project-URL: homepage, https://aka.ms/agent-framework
|
|
22
|
+
Project-URL: issues, https://github.com/microsoft/agent-framework/issues
|
|
23
|
+
Project-URL: release_notes, https://github.com/microsoft/agent-framework/releases?q=tag%3Apython-1&expanded=true
|
|
24
|
+
Project-URL: source, https://github.com/microsoft/agent-framework/tree/main/python
|
|
25
|
+
|
|
26
|
+
# Get Started with Microsoft Agent Framework A2A
|
|
27
|
+
|
|
28
|
+
Please install this package via pip:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install agent-framework-a2a --pre
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## A2A Agent Integration
|
|
35
|
+
|
|
36
|
+
The A2A agent integration enables communication with remote A2A-compliant agents using the standardized A2A protocol. This allows your Agent Framework applications to connect to agents running on different platforms, languages, or services.
|
|
37
|
+
|
|
38
|
+
### Basic Usage Example
|
|
39
|
+
|
|
40
|
+
See the [A2A agent examples](https://github.com/microsoft/agent-framework/tree/main/python/samples/getting_started/agents/a2a/) which demonstrate:
|
|
41
|
+
|
|
42
|
+
- Connecting to remote A2A agents
|
|
43
|
+
- Sending messages and receiving responses
|
|
44
|
+
- Handling different content types (text, files, data)
|
|
45
|
+
- Streaming responses and real-time interaction
|
|
46
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Get Started with Microsoft Agent Framework A2A
|
|
2
|
+
|
|
3
|
+
Please install this package via pip:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install agent-framework-a2a --pre
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## A2A Agent Integration
|
|
10
|
+
|
|
11
|
+
The A2A agent integration enables communication with remote A2A-compliant agents using the standardized A2A protocol. This allows your Agent Framework applications to connect to agents running on different platforms, languages, or services.
|
|
12
|
+
|
|
13
|
+
### Basic Usage Example
|
|
14
|
+
|
|
15
|
+
See the [A2A agent examples](https://github.com/microsoft/agent-framework/tree/main/python/samples/getting_started/agents/a2a/) which demonstrate:
|
|
16
|
+
|
|
17
|
+
- Connecting to remote A2A agents
|
|
18
|
+
- Sending messages and receiving responses
|
|
19
|
+
- Handling different content types (text, files, data)
|
|
20
|
+
- Streaming responses and real-time interaction
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Copyright (c) Microsoft. All rights reserved.
|
|
2
|
+
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
|
|
5
|
+
from ._agent import A2AAgent
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = importlib.metadata.version(__name__)
|
|
9
|
+
except importlib.metadata.PackageNotFoundError:
|
|
10
|
+
__version__ = "0.0.0" # Fallback for development mode
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"A2AAgent",
|
|
14
|
+
"__version__",
|
|
15
|
+
]
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
# Copyright (c) Microsoft. All rights reserved.
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from collections.abc import AsyncIterable, Sequence
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from a2a.client import Client, ClientConfig, ClientFactory, minimal_agent_card
|
|
12
|
+
from a2a.client.auth.interceptor import AuthInterceptor
|
|
13
|
+
from a2a.types import (
|
|
14
|
+
AgentCard,
|
|
15
|
+
Artifact,
|
|
16
|
+
FilePart,
|
|
17
|
+
FileWithBytes,
|
|
18
|
+
FileWithUri,
|
|
19
|
+
Message,
|
|
20
|
+
Task,
|
|
21
|
+
TaskState,
|
|
22
|
+
TextPart,
|
|
23
|
+
TransportProtocol,
|
|
24
|
+
)
|
|
25
|
+
from a2a.types import Message as A2AMessage
|
|
26
|
+
from a2a.types import Part as A2APart
|
|
27
|
+
from a2a.types import Role as A2ARole
|
|
28
|
+
from agent_framework import (
|
|
29
|
+
AgentRunResponse,
|
|
30
|
+
AgentRunResponseUpdate,
|
|
31
|
+
AgentThread,
|
|
32
|
+
BaseAgent,
|
|
33
|
+
ChatMessage,
|
|
34
|
+
Contents,
|
|
35
|
+
DataContent,
|
|
36
|
+
Role,
|
|
37
|
+
TextContent,
|
|
38
|
+
UriContent,
|
|
39
|
+
prepend_agent_framework_to_user_agent,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = ["A2AAgent"]
|
|
43
|
+
|
|
44
|
+
URI_PATTERN = re.compile(r"^data:(?P<media_type>[^;]+);base64,(?P<base64_data>[A-Za-z0-9+/=]+)$")
|
|
45
|
+
TERMINAL_TASK_STATES = [
|
|
46
|
+
TaskState.completed,
|
|
47
|
+
TaskState.failed,
|
|
48
|
+
TaskState.canceled,
|
|
49
|
+
TaskState.rejected,
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _get_uri_data(uri: str) -> str:
|
|
54
|
+
match = URI_PATTERN.match(uri)
|
|
55
|
+
if not match:
|
|
56
|
+
raise ValueError(f"Invalid data URI format: {uri}")
|
|
57
|
+
|
|
58
|
+
return match.group("base64_data")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class A2AAgent(BaseAgent):
|
|
62
|
+
"""Agent2Agent (A2A) protocol implementation.
|
|
63
|
+
|
|
64
|
+
Wraps an A2A Client to connect the Agent Framework with external A2A-compliant agents
|
|
65
|
+
via HTTP/JSON-RPC. Converts framework ChatMessages to A2A Messages on send, and converts
|
|
66
|
+
A2A responses (Messages/Tasks) back to framework types. Inherits BaseAgent capabilities
|
|
67
|
+
while managing the underlying A2A protocol communication.
|
|
68
|
+
|
|
69
|
+
Can be initialized with a URL, AgentCard, or existing A2A Client instance.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
*,
|
|
75
|
+
name: str | None = None,
|
|
76
|
+
id: str | None = None,
|
|
77
|
+
description: str | None = None,
|
|
78
|
+
agent_card: AgentCard | None = None,
|
|
79
|
+
url: str | None = None,
|
|
80
|
+
client: Client | None = None,
|
|
81
|
+
http_client: httpx.AsyncClient | None = None,
|
|
82
|
+
auth_interceptor: AuthInterceptor | None = None,
|
|
83
|
+
**kwargs: Any,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Initialize the A2AAgent.
|
|
86
|
+
|
|
87
|
+
Keyword Args:
|
|
88
|
+
name: The name of the agent.
|
|
89
|
+
id: The unique identifier for the agent, will be created automatically if not provided.
|
|
90
|
+
description: A brief description of the agent's purpose.
|
|
91
|
+
agent_card: The agent card for the agent.
|
|
92
|
+
url: The URL for the A2A server.
|
|
93
|
+
client: The A2A client for the agent.
|
|
94
|
+
http_client: Optional httpx.AsyncClient to use.
|
|
95
|
+
auth_interceptor: Optional authentication interceptor for secured endpoints.
|
|
96
|
+
kwargs: any additional properties, passed to BaseAgent.
|
|
97
|
+
"""
|
|
98
|
+
super().__init__(id=id, name=name, description=description, **kwargs)
|
|
99
|
+
self._http_client: httpx.AsyncClient | None = http_client
|
|
100
|
+
if client is not None:
|
|
101
|
+
self.client = client
|
|
102
|
+
self._close_http_client = True
|
|
103
|
+
return
|
|
104
|
+
if agent_card is None:
|
|
105
|
+
if url is None:
|
|
106
|
+
raise ValueError("Either agent_card or url must be provided")
|
|
107
|
+
# Create minimal agent card from URL
|
|
108
|
+
agent_card = minimal_agent_card(url, [TransportProtocol.jsonrpc])
|
|
109
|
+
|
|
110
|
+
# Create or use provided httpx client
|
|
111
|
+
if http_client is None:
|
|
112
|
+
timeout = httpx.Timeout(
|
|
113
|
+
connect=10.0, # 10 seconds to establish connection
|
|
114
|
+
read=60.0, # 60 seconds to read response (A2A operations can take time)
|
|
115
|
+
write=10.0, # 10 seconds to send request
|
|
116
|
+
pool=5.0, # 5 seconds to get connection from pool
|
|
117
|
+
)
|
|
118
|
+
headers = prepend_agent_framework_to_user_agent()
|
|
119
|
+
http_client = httpx.AsyncClient(timeout=timeout, headers=headers)
|
|
120
|
+
self._http_client = http_client # Store for cleanup
|
|
121
|
+
self._close_http_client = True
|
|
122
|
+
|
|
123
|
+
# Create A2A client using factory
|
|
124
|
+
config = ClientConfig(
|
|
125
|
+
httpx_client=http_client,
|
|
126
|
+
supported_transports=[TransportProtocol.jsonrpc],
|
|
127
|
+
)
|
|
128
|
+
factory = ClientFactory(config)
|
|
129
|
+
interceptors = [auth_interceptor] if auth_interceptor is not None else None
|
|
130
|
+
|
|
131
|
+
# Attempt transport negotiation with the provided agent card
|
|
132
|
+
try:
|
|
133
|
+
self.client = factory.create(agent_card, interceptors=interceptors) # type: ignore
|
|
134
|
+
except Exception as transport_error:
|
|
135
|
+
# Transport negotiation failed - fall back to minimal agent card with JSONRPC
|
|
136
|
+
fallback_card = minimal_agent_card(agent_card.url, [TransportProtocol.jsonrpc])
|
|
137
|
+
try:
|
|
138
|
+
self.client = factory.create(fallback_card, interceptors=interceptors) # type: ignore
|
|
139
|
+
except Exception as fallback_error:
|
|
140
|
+
raise RuntimeError(
|
|
141
|
+
f"A2A transport negotiation failed. "
|
|
142
|
+
f"Primary error: {transport_error}. "
|
|
143
|
+
f"Fallback error: {fallback_error}"
|
|
144
|
+
) from transport_error
|
|
145
|
+
|
|
146
|
+
async def __aenter__(self) -> "A2AAgent":
|
|
147
|
+
"""Async context manager entry."""
|
|
148
|
+
return self
|
|
149
|
+
|
|
150
|
+
async def __aexit__(
|
|
151
|
+
self,
|
|
152
|
+
exc_type: type[BaseException] | None,
|
|
153
|
+
exc_val: BaseException | None,
|
|
154
|
+
exc_tb: Any,
|
|
155
|
+
) -> None:
|
|
156
|
+
"""Async context manager exit with httpx client cleanup."""
|
|
157
|
+
# Close our httpx client if we created it
|
|
158
|
+
if self._http_client is not None and self._close_http_client:
|
|
159
|
+
await self._http_client.aclose()
|
|
160
|
+
|
|
161
|
+
async def run(
|
|
162
|
+
self,
|
|
163
|
+
messages: str | ChatMessage | list[str] | list[ChatMessage] | None = None,
|
|
164
|
+
*,
|
|
165
|
+
thread: AgentThread | None = None,
|
|
166
|
+
**kwargs: Any,
|
|
167
|
+
) -> AgentRunResponse:
|
|
168
|
+
"""Get a response from the agent.
|
|
169
|
+
|
|
170
|
+
This method returns the final result of the agent's execution
|
|
171
|
+
as a single AgentRunResponse object. The caller is blocked until
|
|
172
|
+
the final result is available.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
messages: The message(s) to send to the agent.
|
|
176
|
+
|
|
177
|
+
Keyword Args:
|
|
178
|
+
thread: The conversation thread associated with the message(s).
|
|
179
|
+
kwargs: Additional keyword arguments.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
An agent response item.
|
|
183
|
+
"""
|
|
184
|
+
# Collect all updates and use framework to consolidate updates into response
|
|
185
|
+
updates = [update async for update in self.run_stream(messages, thread=thread, **kwargs)]
|
|
186
|
+
return AgentRunResponse.from_agent_run_response_updates(updates)
|
|
187
|
+
|
|
188
|
+
async def run_stream(
|
|
189
|
+
self,
|
|
190
|
+
messages: str | ChatMessage | list[str] | list[ChatMessage] | None = None,
|
|
191
|
+
*,
|
|
192
|
+
thread: AgentThread | None = None,
|
|
193
|
+
**kwargs: Any,
|
|
194
|
+
) -> AsyncIterable[AgentRunResponseUpdate]:
|
|
195
|
+
"""Run the agent as a stream.
|
|
196
|
+
|
|
197
|
+
This method will return the intermediate steps and final results of the
|
|
198
|
+
agent's execution as a stream of AgentRunResponseUpdate objects to the caller.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
messages: The message(s) to send to the agent.
|
|
202
|
+
|
|
203
|
+
Keyword Args:
|
|
204
|
+
thread: The conversation thread associated with the message(s).
|
|
205
|
+
kwargs: Additional keyword arguments.
|
|
206
|
+
|
|
207
|
+
Yields:
|
|
208
|
+
An agent response item.
|
|
209
|
+
"""
|
|
210
|
+
messages = self._normalize_messages(messages)
|
|
211
|
+
a2a_message = self._chat_message_to_a2a_message(messages[-1])
|
|
212
|
+
|
|
213
|
+
response_stream = self.client.send_message(a2a_message)
|
|
214
|
+
|
|
215
|
+
async for item in response_stream:
|
|
216
|
+
if isinstance(item, Message):
|
|
217
|
+
# Process A2A Message
|
|
218
|
+
contents = self._a2a_parts_to_contents(item.parts)
|
|
219
|
+
yield AgentRunResponseUpdate(
|
|
220
|
+
contents=contents,
|
|
221
|
+
role=Role.ASSISTANT if item.role == A2ARole.agent else Role.USER,
|
|
222
|
+
response_id=str(getattr(item, "message_id", uuid.uuid4())),
|
|
223
|
+
raw_representation=item,
|
|
224
|
+
)
|
|
225
|
+
elif isinstance(item, tuple) and len(item) == 2: # ClientEvent = (Task, UpdateEvent)
|
|
226
|
+
task, _update_event = item
|
|
227
|
+
if isinstance(task, Task) and task.status.state in TERMINAL_TASK_STATES:
|
|
228
|
+
# Convert Task artifacts to ChatMessages and yield as separate updates
|
|
229
|
+
task_messages = self._task_to_chat_messages(task)
|
|
230
|
+
if task_messages:
|
|
231
|
+
for message in task_messages:
|
|
232
|
+
# Use the artifact's ID from raw_representation as message_id for unique identification
|
|
233
|
+
artifact_id = getattr(message.raw_representation, "artifact_id", None)
|
|
234
|
+
yield AgentRunResponseUpdate(
|
|
235
|
+
contents=message.contents,
|
|
236
|
+
role=message.role,
|
|
237
|
+
response_id=task.id,
|
|
238
|
+
message_id=artifact_id,
|
|
239
|
+
raw_representation=task,
|
|
240
|
+
)
|
|
241
|
+
else:
|
|
242
|
+
# Empty task
|
|
243
|
+
yield AgentRunResponseUpdate(
|
|
244
|
+
contents=[],
|
|
245
|
+
role=Role.ASSISTANT,
|
|
246
|
+
response_id=task.id,
|
|
247
|
+
raw_representation=task,
|
|
248
|
+
)
|
|
249
|
+
else:
|
|
250
|
+
# Unknown response type
|
|
251
|
+
msg = f"Only Message and Task responses are supported from A2A agents. Received: {type(item)}"
|
|
252
|
+
raise NotImplementedError(msg)
|
|
253
|
+
|
|
254
|
+
def _chat_message_to_a2a_message(self, message: ChatMessage) -> A2AMessage:
|
|
255
|
+
"""Convert a ChatMessage to an A2A Message.
|
|
256
|
+
|
|
257
|
+
Transforms Agent Framework ChatMessage objects into A2A protocol Messages by:
|
|
258
|
+
- Converting all message contents to appropriate A2A Part types
|
|
259
|
+
- Mapping text content to TextPart objects
|
|
260
|
+
- Converting file references (URI/data/hosted_file) to FilePart objects
|
|
261
|
+
- Preserving metadata and additional properties from the original message
|
|
262
|
+
- Setting the role to 'user' as framework messages are treated as user input
|
|
263
|
+
"""
|
|
264
|
+
parts: list[A2APart] = []
|
|
265
|
+
if not message.contents:
|
|
266
|
+
raise ValueError("ChatMessage.contents is empty; cannot convert to A2AMessage.")
|
|
267
|
+
|
|
268
|
+
# Process ALL contents
|
|
269
|
+
for content in message.contents:
|
|
270
|
+
match content.type:
|
|
271
|
+
case "text":
|
|
272
|
+
parts.append(
|
|
273
|
+
A2APart(
|
|
274
|
+
root=TextPart(
|
|
275
|
+
text=content.text,
|
|
276
|
+
metadata=content.additional_properties,
|
|
277
|
+
)
|
|
278
|
+
)
|
|
279
|
+
)
|
|
280
|
+
case "error":
|
|
281
|
+
parts.append(
|
|
282
|
+
A2APart(
|
|
283
|
+
root=TextPart(
|
|
284
|
+
text=content.message or "An error occurred.",
|
|
285
|
+
metadata=content.additional_properties,
|
|
286
|
+
)
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
case "uri":
|
|
290
|
+
parts.append(
|
|
291
|
+
A2APart(
|
|
292
|
+
root=FilePart(
|
|
293
|
+
file=FileWithUri(
|
|
294
|
+
uri=content.uri,
|
|
295
|
+
mime_type=content.media_type,
|
|
296
|
+
),
|
|
297
|
+
metadata=content.additional_properties,
|
|
298
|
+
)
|
|
299
|
+
)
|
|
300
|
+
)
|
|
301
|
+
case "data":
|
|
302
|
+
parts.append(
|
|
303
|
+
A2APart(
|
|
304
|
+
root=FilePart(
|
|
305
|
+
file=FileWithBytes(
|
|
306
|
+
bytes=_get_uri_data(content.uri),
|
|
307
|
+
mime_type=content.media_type,
|
|
308
|
+
),
|
|
309
|
+
metadata=content.additional_properties,
|
|
310
|
+
)
|
|
311
|
+
)
|
|
312
|
+
)
|
|
313
|
+
case "hosted_file":
|
|
314
|
+
parts.append(
|
|
315
|
+
A2APart(
|
|
316
|
+
root=FilePart(
|
|
317
|
+
file=FileWithUri(
|
|
318
|
+
uri=content.file_id,
|
|
319
|
+
mime_type=None, # HostedFileContent doesn't specify media_type
|
|
320
|
+
),
|
|
321
|
+
metadata=content.additional_properties,
|
|
322
|
+
)
|
|
323
|
+
)
|
|
324
|
+
)
|
|
325
|
+
case _:
|
|
326
|
+
raise ValueError(f"Unknown content type: {content.type}")
|
|
327
|
+
|
|
328
|
+
return A2AMessage(
|
|
329
|
+
role=A2ARole("user"),
|
|
330
|
+
parts=parts,
|
|
331
|
+
message_id=message.message_id or uuid.uuid4().hex,
|
|
332
|
+
metadata=cast(dict[str, Any], message.additional_properties),
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
def _a2a_parts_to_contents(self, parts: Sequence[A2APart]) -> list[Contents]:
|
|
336
|
+
"""Convert A2A Parts to Agent Framework Contents.
|
|
337
|
+
|
|
338
|
+
Transforms A2A protocol Parts into framework-native Content objects,
|
|
339
|
+
handling text, file (URI/bytes), and data parts with metadata preservation.
|
|
340
|
+
"""
|
|
341
|
+
contents: list[Contents] = []
|
|
342
|
+
for part in parts:
|
|
343
|
+
inner_part = part.root
|
|
344
|
+
match inner_part.kind:
|
|
345
|
+
case "text":
|
|
346
|
+
contents.append(
|
|
347
|
+
TextContent(
|
|
348
|
+
text=inner_part.text,
|
|
349
|
+
additional_properties=inner_part.metadata,
|
|
350
|
+
raw_representation=inner_part,
|
|
351
|
+
)
|
|
352
|
+
)
|
|
353
|
+
case "file":
|
|
354
|
+
if isinstance(inner_part.file, FileWithUri):
|
|
355
|
+
contents.append(
|
|
356
|
+
UriContent(
|
|
357
|
+
uri=inner_part.file.uri,
|
|
358
|
+
media_type=inner_part.file.mime_type or "",
|
|
359
|
+
additional_properties=inner_part.metadata,
|
|
360
|
+
raw_representation=inner_part,
|
|
361
|
+
)
|
|
362
|
+
)
|
|
363
|
+
elif isinstance(inner_part.file, FileWithBytes):
|
|
364
|
+
contents.append(
|
|
365
|
+
DataContent(
|
|
366
|
+
data=base64.b64decode(inner_part.file.bytes),
|
|
367
|
+
media_type=inner_part.file.mime_type or "",
|
|
368
|
+
additional_properties=inner_part.metadata,
|
|
369
|
+
raw_representation=inner_part,
|
|
370
|
+
)
|
|
371
|
+
)
|
|
372
|
+
case "data":
|
|
373
|
+
contents.append(
|
|
374
|
+
TextContent(
|
|
375
|
+
text=json.dumps(inner_part.data),
|
|
376
|
+
additional_properties=inner_part.metadata,
|
|
377
|
+
raw_representation=inner_part,
|
|
378
|
+
)
|
|
379
|
+
)
|
|
380
|
+
case _:
|
|
381
|
+
raise ValueError(f"Unknown Part kind: {inner_part.kind}")
|
|
382
|
+
return contents
|
|
383
|
+
|
|
384
|
+
def _task_to_chat_messages(self, task: Task) -> list[ChatMessage]:
|
|
385
|
+
"""Convert A2A Task artifacts to ChatMessages with ASSISTANT role."""
|
|
386
|
+
messages: list[ChatMessage] = []
|
|
387
|
+
|
|
388
|
+
if task.artifacts is not None:
|
|
389
|
+
for artifact in task.artifacts:
|
|
390
|
+
messages.append(self._artifact_to_chat_message(artifact))
|
|
391
|
+
|
|
392
|
+
return messages
|
|
393
|
+
|
|
394
|
+
def _artifact_to_chat_message(self, artifact: Artifact) -> ChatMessage:
|
|
395
|
+
"""Convert A2A Artifact to ChatMessage using part contents."""
|
|
396
|
+
contents = self._a2a_parts_to_contents(artifact.parts)
|
|
397
|
+
return ChatMessage(
|
|
398
|
+
role=Role.ASSISTANT,
|
|
399
|
+
contents=contents,
|
|
400
|
+
raw_representation=artifact,
|
|
401
|
+
)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "agent-framework-a2a"
|
|
3
|
+
description = "A2A integration for Microsoft Agent Framework."
|
|
4
|
+
authors = [{ name = "Microsoft", email = "af-support@microsoft.com"}]
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
version = "1.0.0b251105"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
urls.homepage = "https://aka.ms/agent-framework"
|
|
10
|
+
urls.source = "https://github.com/microsoft/agent-framework/tree/main/python"
|
|
11
|
+
urls.release_notes = "https://github.com/microsoft/agent-framework/releases?q=tag%3Apython-1&expanded=true"
|
|
12
|
+
urls.issues = "https://github.com/microsoft/agent-framework/issues"
|
|
13
|
+
classifiers = [
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"agent-framework-core",
|
|
27
|
+
"a2a-sdk>=0.3.5",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.uv]
|
|
31
|
+
prerelease = "if-necessary-or-explicit"
|
|
32
|
+
environments = [
|
|
33
|
+
"sys_platform == 'darwin'",
|
|
34
|
+
"sys_platform == 'linux'",
|
|
35
|
+
"sys_platform == 'win32'"
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[tool.uv-dynamic-versioning]
|
|
39
|
+
fallback-version = "0.0.0"
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
testpaths = 'tests'
|
|
42
|
+
addopts = "-ra -q -r fEX"
|
|
43
|
+
asyncio_mode = "auto"
|
|
44
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
45
|
+
filterwarnings = [
|
|
46
|
+
"ignore:Support for class-based `config` is deprecated:DeprecationWarning:pydantic.*"
|
|
47
|
+
]
|
|
48
|
+
timeout = 120
|
|
49
|
+
|
|
50
|
+
[tool.ruff]
|
|
51
|
+
extend = "../../pyproject.toml"
|
|
52
|
+
|
|
53
|
+
[tool.coverage.run]
|
|
54
|
+
omit = [
|
|
55
|
+
"**/__init__.py"
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
[tool.pyright]
|
|
59
|
+
extends = "../../pyproject.toml"
|
|
60
|
+
|
|
61
|
+
[tool.mypy]
|
|
62
|
+
plugins = ['pydantic.mypy']
|
|
63
|
+
strict = true
|
|
64
|
+
python_version = "3.10"
|
|
65
|
+
ignore_missing_imports = true
|
|
66
|
+
disallow_untyped_defs = true
|
|
67
|
+
no_implicit_optional = true
|
|
68
|
+
check_untyped_defs = true
|
|
69
|
+
warn_return_any = true
|
|
70
|
+
show_error_codes = true
|
|
71
|
+
warn_unused_ignores = false
|
|
72
|
+
disallow_incomplete_defs = true
|
|
73
|
+
disallow_untyped_decorators = true
|
|
74
|
+
|
|
75
|
+
[tool.bandit]
|
|
76
|
+
targets = ["agent_framework_a2a"]
|
|
77
|
+
exclude_dirs = ["tests"]
|
|
78
|
+
|
|
79
|
+
[tool.poe]
|
|
80
|
+
executor.type = "uv"
|
|
81
|
+
include = "../../shared_tasks.toml"
|
|
82
|
+
[tool.poe.tasks]
|
|
83
|
+
mypy = "mypy --config-file $POE_ROOT/pyproject.toml agent_framework_a2a"
|
|
84
|
+
test = "pytest --cov=agent_framework_a2a --cov-report=term-missing:skip-covered tests"
|
|
85
|
+
|
|
86
|
+
[build-system]
|
|
87
|
+
requires = ["flit-core >= 3.11,<4.0"]
|
|
88
|
+
build-backend = "flit_core.buildapi"
|
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
# Copyright (c) Microsoft. All rights reserved.
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
from typing import Any
|
|
5
|
+
from unittest.mock import AsyncMock, MagicMock, patch
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
from a2a.types import (
|
|
9
|
+
AgentCard,
|
|
10
|
+
Artifact,
|
|
11
|
+
DataPart,
|
|
12
|
+
FilePart,
|
|
13
|
+
FileWithUri,
|
|
14
|
+
Message,
|
|
15
|
+
Part,
|
|
16
|
+
Task,
|
|
17
|
+
TaskState,
|
|
18
|
+
TaskStatus,
|
|
19
|
+
TextPart,
|
|
20
|
+
)
|
|
21
|
+
from a2a.types import Role as A2ARole
|
|
22
|
+
from agent_framework import (
|
|
23
|
+
AgentRunResponse,
|
|
24
|
+
AgentRunResponseUpdate,
|
|
25
|
+
ChatMessage,
|
|
26
|
+
DataContent,
|
|
27
|
+
ErrorContent,
|
|
28
|
+
HostedFileContent,
|
|
29
|
+
Role,
|
|
30
|
+
TextContent,
|
|
31
|
+
UriContent,
|
|
32
|
+
)
|
|
33
|
+
from agent_framework.a2a import A2AAgent
|
|
34
|
+
from pytest import fixture, raises
|
|
35
|
+
|
|
36
|
+
from agent_framework_a2a._agent import _get_uri_data # type: ignore
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MockA2AClient:
|
|
40
|
+
"""Mock implementation of A2A Client for testing."""
|
|
41
|
+
|
|
42
|
+
def __init__(self) -> None:
|
|
43
|
+
self.call_count: int = 0
|
|
44
|
+
self.responses: list[Any] = []
|
|
45
|
+
|
|
46
|
+
def add_message_response(self, message_id: str, text: str, role: str = "agent") -> None:
|
|
47
|
+
"""Add a mock Message response."""
|
|
48
|
+
|
|
49
|
+
# Create actual TextPart instance and wrap it in Part
|
|
50
|
+
text_part = Part(root=TextPart(text=text))
|
|
51
|
+
|
|
52
|
+
# Create actual Message instance
|
|
53
|
+
message = Message(
|
|
54
|
+
message_id=message_id, role=A2ARole.agent if role == "agent" else A2ARole.user, parts=[text_part]
|
|
55
|
+
)
|
|
56
|
+
self.responses.append(message)
|
|
57
|
+
|
|
58
|
+
def add_task_response(self, task_id: str, artifacts: list[dict[str, Any]]) -> None:
|
|
59
|
+
"""Add a mock Task response."""
|
|
60
|
+
# Create mock artifacts
|
|
61
|
+
mock_artifacts = []
|
|
62
|
+
for artifact_data in artifacts:
|
|
63
|
+
# Create actual TextPart instance and wrap it in Part
|
|
64
|
+
text_part = Part(root=TextPart(text=artifact_data.get("content", "Test content")))
|
|
65
|
+
|
|
66
|
+
artifact = Artifact(
|
|
67
|
+
artifact_id=artifact_data.get("id", str(uuid4())),
|
|
68
|
+
name=artifact_data.get("name", "test-artifact"),
|
|
69
|
+
description=artifact_data.get("description", "Test artifact"),
|
|
70
|
+
parts=[text_part],
|
|
71
|
+
)
|
|
72
|
+
mock_artifacts.append(artifact)
|
|
73
|
+
|
|
74
|
+
# Create task status
|
|
75
|
+
status = TaskStatus(state=TaskState.completed, message=None)
|
|
76
|
+
|
|
77
|
+
# Create actual Task instance
|
|
78
|
+
task = Task(
|
|
79
|
+
id=task_id, context_id="test-context", status=status, artifacts=mock_artifacts if mock_artifacts else None
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Mock the ClientEvent tuple format
|
|
83
|
+
update_event = None # No specific update event for completed tasks
|
|
84
|
+
client_event = (task, update_event)
|
|
85
|
+
self.responses.append(client_event)
|
|
86
|
+
|
|
87
|
+
async def send_message(self, message: Any) -> AsyncIterator[Any]:
|
|
88
|
+
"""Mock send_message method that yields responses."""
|
|
89
|
+
self.call_count += 1
|
|
90
|
+
|
|
91
|
+
if self.responses:
|
|
92
|
+
response = self.responses.pop(0)
|
|
93
|
+
yield response
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@fixture
|
|
97
|
+
def mock_a2a_client() -> MockA2AClient:
|
|
98
|
+
"""Fixture that provides a mock A2A client."""
|
|
99
|
+
return MockA2AClient()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@fixture
|
|
103
|
+
def a2a_agent(mock_a2a_client: MockA2AClient) -> A2AAgent:
|
|
104
|
+
"""Fixture that provides an A2AAgent with a mock client."""
|
|
105
|
+
return A2AAgent(name="Test Agent", id="test-agent", client=mock_a2a_client, http_client=None)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_a2a_agent_initialization_with_client(mock_a2a_client: MockA2AClient) -> None:
|
|
109
|
+
"""Test A2AAgent initialization with provided client."""
|
|
110
|
+
# Use model_construct to bypass Pydantic validation for mock objects
|
|
111
|
+
agent = A2AAgent(
|
|
112
|
+
name="Test Agent", id="test-agent-123", description="A test agent", client=mock_a2a_client, http_client=None
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
assert agent.name == "Test Agent"
|
|
116
|
+
assert agent.id == "test-agent-123"
|
|
117
|
+
assert agent.description == "A test agent"
|
|
118
|
+
assert agent.client == mock_a2a_client
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_a2a_agent_initialization_without_client_raises_error() -> None:
|
|
122
|
+
"""Test A2AAgent initialization without client or URL raises ValueError."""
|
|
123
|
+
with raises(ValueError, match="Either agent_card or url must be provided"):
|
|
124
|
+
A2AAgent(name="Test Agent")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
async def test_run_with_message_response(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
|
|
128
|
+
"""Test run() method with immediate Message response."""
|
|
129
|
+
mock_a2a_client.add_message_response("msg-123", "Hello from agent!", "agent")
|
|
130
|
+
|
|
131
|
+
response = await a2a_agent.run("Hello agent")
|
|
132
|
+
|
|
133
|
+
assert isinstance(response, AgentRunResponse)
|
|
134
|
+
assert len(response.messages) == 1
|
|
135
|
+
assert response.messages[0].role == Role.ASSISTANT
|
|
136
|
+
assert response.messages[0].text == "Hello from agent!"
|
|
137
|
+
assert response.response_id == "msg-123"
|
|
138
|
+
assert mock_a2a_client.call_count == 1
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
async def test_run_with_task_response_single_artifact(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
|
|
142
|
+
"""Test run() method with Task response containing single artifact."""
|
|
143
|
+
artifacts = [{"id": "art-1", "content": "Generated report content"}]
|
|
144
|
+
mock_a2a_client.add_task_response("task-456", artifacts)
|
|
145
|
+
|
|
146
|
+
response = await a2a_agent.run("Generate a report")
|
|
147
|
+
|
|
148
|
+
assert isinstance(response, AgentRunResponse)
|
|
149
|
+
assert len(response.messages) == 1
|
|
150
|
+
assert response.messages[0].role == Role.ASSISTANT
|
|
151
|
+
assert response.messages[0].text == "Generated report content"
|
|
152
|
+
assert response.response_id == "task-456"
|
|
153
|
+
assert mock_a2a_client.call_count == 1
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
async def test_run_with_task_response_multiple_artifacts(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
|
|
157
|
+
"""Test run() method with Task response containing multiple artifacts."""
|
|
158
|
+
artifacts = [
|
|
159
|
+
{"id": "art-1", "content": "First artifact content"},
|
|
160
|
+
{"id": "art-2", "content": "Second artifact content"},
|
|
161
|
+
{"id": "art-3", "content": "Third artifact content"},
|
|
162
|
+
]
|
|
163
|
+
mock_a2a_client.add_task_response("task-789", artifacts)
|
|
164
|
+
|
|
165
|
+
response = await a2a_agent.run("Generate multiple outputs")
|
|
166
|
+
|
|
167
|
+
assert isinstance(response, AgentRunResponse)
|
|
168
|
+
assert len(response.messages) == 3
|
|
169
|
+
|
|
170
|
+
assert response.messages[0].text == "First artifact content"
|
|
171
|
+
assert response.messages[1].text == "Second artifact content"
|
|
172
|
+
assert response.messages[2].text == "Third artifact content"
|
|
173
|
+
|
|
174
|
+
# All should be assistant messages
|
|
175
|
+
for message in response.messages:
|
|
176
|
+
assert message.role == Role.ASSISTANT
|
|
177
|
+
|
|
178
|
+
assert response.response_id == "task-789"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
async def test_run_with_task_response_no_artifacts(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
|
|
182
|
+
"""Test run() method with Task response containing no artifacts."""
|
|
183
|
+
mock_a2a_client.add_task_response("task-empty", [])
|
|
184
|
+
|
|
185
|
+
response = await a2a_agent.run("Do something with no output")
|
|
186
|
+
|
|
187
|
+
assert isinstance(response, AgentRunResponse)
|
|
188
|
+
assert response.response_id == "task-empty"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
async def test_run_with_unknown_response_type_raises_error(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
|
|
192
|
+
"""Test run() method with unknown response type raises NotImplementedError."""
|
|
193
|
+
mock_a2a_client.responses.append("invalid_response")
|
|
194
|
+
|
|
195
|
+
with raises(NotImplementedError, match="Only Message and Task responses are supported"):
|
|
196
|
+
await a2a_agent.run("Test message")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def test_task_to_chat_messages_empty_artifacts(a2a_agent: A2AAgent) -> None:
|
|
200
|
+
"""Test _task_to_chat_messages with task containing no artifacts."""
|
|
201
|
+
task = MagicMock()
|
|
202
|
+
task.artifacts = None
|
|
203
|
+
|
|
204
|
+
result = a2a_agent._task_to_chat_messages(task)
|
|
205
|
+
|
|
206
|
+
assert len(result) == 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def test_task_to_chat_messages_with_artifacts(a2a_agent: A2AAgent) -> None:
|
|
210
|
+
"""Test _task_to_chat_messages with task containing artifacts."""
|
|
211
|
+
task = MagicMock()
|
|
212
|
+
|
|
213
|
+
# Create mock artifacts
|
|
214
|
+
artifact1 = MagicMock()
|
|
215
|
+
artifact1.artifact_id = "art-1"
|
|
216
|
+
text_part1 = MagicMock()
|
|
217
|
+
text_part1.root = MagicMock()
|
|
218
|
+
text_part1.root.kind = "text"
|
|
219
|
+
text_part1.root.text = "Content 1"
|
|
220
|
+
text_part1.root.metadata = None
|
|
221
|
+
artifact1.parts = [text_part1]
|
|
222
|
+
|
|
223
|
+
artifact2 = MagicMock()
|
|
224
|
+
artifact2.artifact_id = "art-2"
|
|
225
|
+
text_part2 = MagicMock()
|
|
226
|
+
text_part2.root = MagicMock()
|
|
227
|
+
text_part2.root.kind = "text"
|
|
228
|
+
text_part2.root.text = "Content 2"
|
|
229
|
+
text_part2.root.metadata = None
|
|
230
|
+
artifact2.parts = [text_part2]
|
|
231
|
+
|
|
232
|
+
task.artifacts = [artifact1, artifact2]
|
|
233
|
+
|
|
234
|
+
result = a2a_agent._task_to_chat_messages(task)
|
|
235
|
+
|
|
236
|
+
assert len(result) == 2
|
|
237
|
+
assert result[0].text == "Content 1"
|
|
238
|
+
assert result[1].text == "Content 2"
|
|
239
|
+
assert all(msg.role == Role.ASSISTANT for msg in result)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def test_artifact_to_chat_message(a2a_agent: A2AAgent) -> None:
|
|
243
|
+
"""Test _artifact_to_chat_message conversion."""
|
|
244
|
+
artifact = MagicMock()
|
|
245
|
+
artifact.artifact_id = "test-artifact"
|
|
246
|
+
|
|
247
|
+
text_part = MagicMock()
|
|
248
|
+
text_part.root = MagicMock()
|
|
249
|
+
text_part.root.kind = "text"
|
|
250
|
+
text_part.root.text = "Artifact content"
|
|
251
|
+
text_part.root.metadata = None
|
|
252
|
+
|
|
253
|
+
artifact.parts = [text_part]
|
|
254
|
+
|
|
255
|
+
result = a2a_agent._artifact_to_chat_message(artifact)
|
|
256
|
+
|
|
257
|
+
assert isinstance(result, ChatMessage)
|
|
258
|
+
assert result.role == Role.ASSISTANT
|
|
259
|
+
assert result.text == "Artifact content"
|
|
260
|
+
assert result.raw_representation == artifact
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def test_get_uri_data_valid_uri() -> None:
|
|
264
|
+
"""Test _get_uri_data with valid data URI."""
|
|
265
|
+
|
|
266
|
+
uri = "data:application/json;base64,eyJ0ZXN0IjoidmFsdWUifQ=="
|
|
267
|
+
result = _get_uri_data(uri)
|
|
268
|
+
assert result == "eyJ0ZXN0IjoidmFsdWUifQ=="
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def test_get_uri_data_invalid_uri() -> None:
|
|
272
|
+
"""Test _get_uri_data with invalid URI format."""
|
|
273
|
+
|
|
274
|
+
with raises(ValueError, match="Invalid data URI format"):
|
|
275
|
+
_get_uri_data("not-a-valid-data-uri")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def test_a2a_parts_to_contents_conversion(a2a_agent: A2AAgent) -> None:
|
|
279
|
+
"""Test A2A parts to contents conversion."""
|
|
280
|
+
|
|
281
|
+
agent = A2AAgent(name="Test Agent", client=MockA2AClient(), _http_client=None)
|
|
282
|
+
|
|
283
|
+
# Create A2A parts
|
|
284
|
+
parts = [Part(root=TextPart(text="First part")), Part(root=TextPart(text="Second part"))]
|
|
285
|
+
|
|
286
|
+
# Convert to contents
|
|
287
|
+
contents = agent._a2a_parts_to_contents(parts)
|
|
288
|
+
|
|
289
|
+
# Verify conversion
|
|
290
|
+
assert len(contents) == 2
|
|
291
|
+
assert isinstance(contents[0], TextContent)
|
|
292
|
+
assert isinstance(contents[1], TextContent)
|
|
293
|
+
assert contents[0].text == "First part"
|
|
294
|
+
assert contents[1].text == "Second part"
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def test_chat_message_to_a2a_message_with_error_content(a2a_agent: A2AAgent) -> None:
|
|
298
|
+
"""Test _chat_message_to_a2a_message with ErrorContent."""
|
|
299
|
+
|
|
300
|
+
# Create ChatMessage with ErrorContent
|
|
301
|
+
error_content = ErrorContent(message="Test error message")
|
|
302
|
+
message = ChatMessage(role=Role.USER, contents=[error_content])
|
|
303
|
+
|
|
304
|
+
# Convert to A2A message
|
|
305
|
+
a2a_message = a2a_agent._chat_message_to_a2a_message(message)
|
|
306
|
+
|
|
307
|
+
# Verify conversion
|
|
308
|
+
assert len(a2a_message.parts) == 1
|
|
309
|
+
assert a2a_message.parts[0].root.text == "Test error message"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def test_chat_message_to_a2a_message_with_uri_content(a2a_agent: A2AAgent) -> None:
|
|
313
|
+
"""Test _chat_message_to_a2a_message with UriContent."""
|
|
314
|
+
|
|
315
|
+
# Create ChatMessage with UriContent
|
|
316
|
+
uri_content = UriContent(uri="http://example.com/file.pdf", media_type="application/pdf")
|
|
317
|
+
message = ChatMessage(role=Role.USER, contents=[uri_content])
|
|
318
|
+
|
|
319
|
+
# Convert to A2A message
|
|
320
|
+
a2a_message = a2a_agent._chat_message_to_a2a_message(message)
|
|
321
|
+
|
|
322
|
+
# Verify conversion
|
|
323
|
+
assert len(a2a_message.parts) == 1
|
|
324
|
+
assert a2a_message.parts[0].root.file.uri == "http://example.com/file.pdf"
|
|
325
|
+
assert a2a_message.parts[0].root.file.mime_type == "application/pdf"
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def test_chat_message_to_a2a_message_with_data_content(a2a_agent: A2AAgent) -> None:
|
|
329
|
+
"""Test _chat_message_to_a2a_message with DataContent."""
|
|
330
|
+
|
|
331
|
+
# Create ChatMessage with DataContent (base64 data URI)
|
|
332
|
+
data_content = DataContent(uri="data:text/plain;base64,SGVsbG8gV29ybGQ=", media_type="text/plain")
|
|
333
|
+
message = ChatMessage(role=Role.USER, contents=[data_content])
|
|
334
|
+
|
|
335
|
+
# Convert to A2A message
|
|
336
|
+
a2a_message = a2a_agent._chat_message_to_a2a_message(message)
|
|
337
|
+
|
|
338
|
+
# Verify conversion
|
|
339
|
+
assert len(a2a_message.parts) == 1
|
|
340
|
+
assert a2a_message.parts[0].root.file.bytes == "SGVsbG8gV29ybGQ="
|
|
341
|
+
assert a2a_message.parts[0].root.file.mime_type == "text/plain"
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def test_chat_message_to_a2a_message_empty_contents_raises_error(a2a_agent: A2AAgent) -> None:
|
|
345
|
+
"""Test _chat_message_to_a2a_message with empty contents raises ValueError."""
|
|
346
|
+
# Create ChatMessage with no contents
|
|
347
|
+
message = ChatMessage(role=Role.USER, contents=[])
|
|
348
|
+
|
|
349
|
+
# Should raise ValueError for empty contents
|
|
350
|
+
with raises(ValueError, match="ChatMessage.contents is empty"):
|
|
351
|
+
a2a_agent._chat_message_to_a2a_message(message)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
async def test_run_stream_with_message_response(a2a_agent: A2AAgent, mock_a2a_client: MockA2AClient) -> None:
|
|
355
|
+
"""Test run_stream() method with immediate Message response."""
|
|
356
|
+
mock_a2a_client.add_message_response("msg-stream-123", "Streaming response from agent!", "agent")
|
|
357
|
+
|
|
358
|
+
# Collect streaming updates
|
|
359
|
+
updates: list[AgentRunResponseUpdate] = []
|
|
360
|
+
async for update in a2a_agent.run_stream("Hello agent"):
|
|
361
|
+
updates.append(update)
|
|
362
|
+
|
|
363
|
+
# Verify streaming response
|
|
364
|
+
assert len(updates) == 1
|
|
365
|
+
assert isinstance(updates[0], AgentRunResponseUpdate)
|
|
366
|
+
assert updates[0].role == Role.ASSISTANT
|
|
367
|
+
assert len(updates[0].contents) == 1
|
|
368
|
+
|
|
369
|
+
content = updates[0].contents[0]
|
|
370
|
+
assert isinstance(content, TextContent)
|
|
371
|
+
assert content.text == "Streaming response from agent!"
|
|
372
|
+
|
|
373
|
+
assert updates[0].response_id == "msg-stream-123"
|
|
374
|
+
assert mock_a2a_client.call_count == 1
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
async def test_context_manager_cleanup() -> None:
|
|
378
|
+
"""Test context manager cleanup of http client."""
|
|
379
|
+
|
|
380
|
+
# Create mock http client that tracks aclose calls
|
|
381
|
+
mock_http_client = AsyncMock()
|
|
382
|
+
mock_a2a_client = MagicMock()
|
|
383
|
+
|
|
384
|
+
agent = A2AAgent(client=mock_a2a_client)
|
|
385
|
+
agent._http_client = mock_http_client
|
|
386
|
+
|
|
387
|
+
# Test context manager cleanup
|
|
388
|
+
async with agent:
|
|
389
|
+
pass
|
|
390
|
+
|
|
391
|
+
# Verify aclose was called
|
|
392
|
+
mock_http_client.aclose.assert_called_once()
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
async def test_context_manager_no_cleanup_when_no_http_client() -> None:
|
|
396
|
+
"""Test context manager when _http_client is None."""
|
|
397
|
+
|
|
398
|
+
mock_a2a_client = MagicMock()
|
|
399
|
+
|
|
400
|
+
agent = A2AAgent(client=mock_a2a_client, _http_client=None)
|
|
401
|
+
|
|
402
|
+
# This should not raise any errors
|
|
403
|
+
async with agent:
|
|
404
|
+
pass
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def test_chat_message_to_a2a_message_with_multiple_contents() -> None:
|
|
408
|
+
"""Test conversion of ChatMessage with multiple contents."""
|
|
409
|
+
|
|
410
|
+
agent = A2AAgent(client=MagicMock(), _http_client=None)
|
|
411
|
+
|
|
412
|
+
# Create message with multiple content types
|
|
413
|
+
message = ChatMessage(
|
|
414
|
+
role=Role.USER,
|
|
415
|
+
contents=[
|
|
416
|
+
TextContent(text="Here's the analysis:"),
|
|
417
|
+
DataContent(data=b"binary data", media_type="application/octet-stream"),
|
|
418
|
+
UriContent(uri="https://example.com/image.png", media_type="image/png"),
|
|
419
|
+
TextContent(text='{"structured": "data"}'),
|
|
420
|
+
],
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
result = agent._chat_message_to_a2a_message(message)
|
|
424
|
+
|
|
425
|
+
# Should have converted all 4 contents to parts
|
|
426
|
+
assert len(result.parts) == 4
|
|
427
|
+
|
|
428
|
+
# Check each part type
|
|
429
|
+
assert result.parts[0].root.kind == "text" # Regular text
|
|
430
|
+
assert result.parts[1].root.kind == "file" # Binary data
|
|
431
|
+
assert result.parts[2].root.kind == "file" # URI content
|
|
432
|
+
assert result.parts[3].root.kind == "text" # JSON text remains as text (no parsing)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def test_a2a_parts_to_contents_with_data_part() -> None:
|
|
436
|
+
"""Test conversion of A2A DataPart."""
|
|
437
|
+
|
|
438
|
+
agent = A2AAgent(client=MagicMock(), _http_client=None)
|
|
439
|
+
|
|
440
|
+
# Create DataPart
|
|
441
|
+
data_part = Part(root=DataPart(data={"key": "value", "number": 42}, metadata={"source": "test"}))
|
|
442
|
+
|
|
443
|
+
contents = agent._a2a_parts_to_contents([data_part])
|
|
444
|
+
|
|
445
|
+
assert len(contents) == 1
|
|
446
|
+
|
|
447
|
+
assert isinstance(contents[0], TextContent)
|
|
448
|
+
assert contents[0].text == '{"key": "value", "number": 42}'
|
|
449
|
+
assert contents[0].additional_properties == {"source": "test"}
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def test_a2a_parts_to_contents_unknown_part_kind() -> None:
|
|
453
|
+
"""Test error handling for unknown A2A part kind."""
|
|
454
|
+
agent = A2AAgent(client=MagicMock(), _http_client=None)
|
|
455
|
+
|
|
456
|
+
# Create a mock part with unknown kind
|
|
457
|
+
mock_part = MagicMock()
|
|
458
|
+
mock_part.root.kind = "unknown_kind"
|
|
459
|
+
|
|
460
|
+
with raises(ValueError, match="Unknown Part kind: unknown_kind"):
|
|
461
|
+
agent._a2a_parts_to_contents([mock_part])
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def test_chat_message_to_a2a_message_with_hosted_file() -> None:
|
|
465
|
+
"""Test conversion of ChatMessage with HostedFileContent to A2A message."""
|
|
466
|
+
|
|
467
|
+
agent = A2AAgent(client=MagicMock(), _http_client=None)
|
|
468
|
+
|
|
469
|
+
# Create message with hosted file content
|
|
470
|
+
message = ChatMessage(
|
|
471
|
+
role=Role.USER,
|
|
472
|
+
contents=[HostedFileContent(file_id="hosted://storage/document.pdf")],
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
result = agent._chat_message_to_a2a_message(message) # noqa: SLF001
|
|
476
|
+
|
|
477
|
+
# Verify the conversion
|
|
478
|
+
assert len(result.parts) == 1
|
|
479
|
+
part = result.parts[0]
|
|
480
|
+
assert part.root.kind == "file"
|
|
481
|
+
|
|
482
|
+
# Verify it's a FilePart with FileWithUri
|
|
483
|
+
|
|
484
|
+
assert isinstance(part.root, FilePart)
|
|
485
|
+
assert isinstance(part.root.file, FileWithUri)
|
|
486
|
+
assert part.root.file.uri == "hosted://storage/document.pdf"
|
|
487
|
+
assert part.root.file.mime_type is None # HostedFileContent doesn't specify media_type
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def test_a2a_parts_to_contents_with_hosted_file_uri() -> None:
|
|
491
|
+
"""Test conversion of A2A FilePart with hosted file URI back to UriContent."""
|
|
492
|
+
|
|
493
|
+
agent = A2AAgent(client=MagicMock(), _http_client=None)
|
|
494
|
+
|
|
495
|
+
# Create FilePart with hosted file URI (simulating what A2A would send back)
|
|
496
|
+
file_part = Part(
|
|
497
|
+
root=FilePart(
|
|
498
|
+
file=FileWithUri(
|
|
499
|
+
uri="hosted://storage/document.pdf",
|
|
500
|
+
mime_type=None,
|
|
501
|
+
)
|
|
502
|
+
)
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
contents = agent._a2a_parts_to_contents([file_part]) # noqa: SLF001
|
|
506
|
+
|
|
507
|
+
assert len(contents) == 1
|
|
508
|
+
|
|
509
|
+
assert isinstance(contents[0], UriContent)
|
|
510
|
+
assert contents[0].uri == "hosted://storage/document.pdf"
|
|
511
|
+
assert contents[0].media_type == "" # Converted None to empty string
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def test_auth_interceptor_parameter() -> None:
|
|
515
|
+
"""Test that auth_interceptor parameter is accepted without errors."""
|
|
516
|
+
# Create a mock auth interceptor
|
|
517
|
+
mock_auth_interceptor = MagicMock()
|
|
518
|
+
|
|
519
|
+
# Test that A2AAgent can be created with auth_interceptor parameter
|
|
520
|
+
# Using url parameter for simplicity
|
|
521
|
+
agent = A2AAgent(
|
|
522
|
+
name="test-agent",
|
|
523
|
+
url="https://test-agent.example.com",
|
|
524
|
+
auth_interceptor=mock_auth_interceptor,
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
# Verify the agent was created successfully
|
|
528
|
+
assert agent.name == "test-agent"
|
|
529
|
+
assert agent.client is not None
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def test_transport_negotiation_both_fail() -> None:
|
|
533
|
+
"""Test that RuntimeError is raised when both primary and fallback transport negotiation fail."""
|
|
534
|
+
# Create a mock agent card
|
|
535
|
+
mock_agent_card = MagicMock(spec=AgentCard)
|
|
536
|
+
mock_agent_card.url = "http://test-agent.example.com"
|
|
537
|
+
|
|
538
|
+
# Mock the factory to simulate both primary and fallback failures
|
|
539
|
+
mock_factory = MagicMock()
|
|
540
|
+
|
|
541
|
+
# Both calls to factory.create() fail
|
|
542
|
+
primary_error = Exception("no compatible transports found")
|
|
543
|
+
fallback_error = Exception("fallback also failed")
|
|
544
|
+
mock_factory.create.side_effect = [primary_error, fallback_error]
|
|
545
|
+
|
|
546
|
+
with (
|
|
547
|
+
patch("agent_framework_a2a._agent.ClientFactory", return_value=mock_factory),
|
|
548
|
+
patch("agent_framework_a2a._agent.minimal_agent_card"),
|
|
549
|
+
patch("agent_framework_a2a._agent.httpx.AsyncClient"),
|
|
550
|
+
raises(RuntimeError, match="A2A transport negotiation failed"),
|
|
551
|
+
):
|
|
552
|
+
# Attempt to create A2AAgent - should raise RuntimeError
|
|
553
|
+
A2AAgent(
|
|
554
|
+
name="test-agent",
|
|
555
|
+
agent_card=mock_agent_card,
|
|
556
|
+
)
|