forked from themanojdesai/python-a2a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.py
More file actions
219 lines (173 loc) · 6.98 KB
/
Copy pathbase.py
File metadata and controls
219 lines (173 loc) · 6.98 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""
Base client for interacting with A2A-compatible agents.
"""
from abc import ABC, abstractmethod
from typing import Optional, AsyncGenerator, Any, Union, Dict, Callable
from ..models.message import Message
from ..models.conversation import Conversation
from ..models.task import Task
class BaseA2AClient(ABC):
"""
Abstract base class for A2A clients.
Provides a common interface for interacting with different types of A2A-compatible
agents, whether they're accessible via HTTP APIs, local models, or other methods.
All client implementations should inherit from this class and implement the
`send_message` and `send_conversation` methods.
"""
@abstractmethod
def send_message(self, message: Message) -> Message:
"""
Send a message to an A2A-compatible agent and get a response.
Args:
message: The message to send
Returns:
The agent's response
"""
pass
@abstractmethod
def send_conversation(self, conversation: Conversation) -> Conversation:
"""
Send a conversation to an A2A-compatible agent and get an updated conversation.
Args:
conversation: The conversation to send
Returns:
The updated conversation with the agent's response
"""
pass
async def stream_response(
self,
message: Message,
chunk_callback: Optional[Callable[[Union[str, Dict]], None]] = None
) -> AsyncGenerator[Union[str, Dict], None]:
"""
Stream a response from an A2A-compatible agent.
Args:
message: The A2A message to send
chunk_callback: Optional callback function for each chunk
Yields:
Response chunks from the agent
Note:
This is a default implementation that should be overridden by
client implementations that support streaming.
"""
# Default implementation just yields the entire response as one chunk
response = self.send_message(message)
# Get text from response
if hasattr(response.content, "text"):
result = response.content.text
else:
result = str(response.content)
# Call the callback if provided
if chunk_callback:
chunk_callback(result)
# Yield the entire response as one chunk
yield result
async def send_message_async(self, message: Message) -> Message:
"""
Send a message to an A2A-compatible agent asynchronously.
Default implementation that wraps the synchronous send_message
in an asynchronous interface.
Args:
message: The A2A message to send
Returns:
The agent's response
"""
# Default implementation runs sync version in executor
import asyncio
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, self.send_message, message)
async def send_conversation_async(self, conversation: Conversation) -> Conversation:
"""
Send a conversation to an A2A-compatible agent asynchronously.
Default implementation that wraps the synchronous send_conversation
in an asynchronous interface.
Args:
conversation: The conversation to send
Returns:
The updated conversation with the agent's response
"""
# Default implementation runs sync version in executor
import asyncio
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, self.send_conversation, conversation)
async def stream_task(
self,
task: Task,
chunk_callback: Optional[Callable[[Dict], None]] = None
) -> AsyncGenerator[Dict, None]:
"""
Stream the execution of a task.
Default implementation that doesn't support actual streaming,
just returns the final result.
Args:
task: The task to execute
chunk_callback: Optional callback function for each chunk
Yields:
Task status and result chunks
"""
# Create a complete task result
result = await self.send_task_async(task)
# Create a single chunk with the complete result
chunk = {
"status": result.status.state.value if hasattr(result.status, "state") else "unknown",
"artifacts": result.artifacts
}
# Call the callback if provided
if chunk_callback:
chunk_callback(chunk)
# Yield the entire response as one chunk
yield chunk
async def send_task_async(self, task: Task) -> Task:
"""
Send a task to an A2A-compatible agent asynchronously.
Default implementation for task handling. Should be overridden
by implementations that support the tasks API.
Args:
task: The task to send
Returns:
The updated task with the agent's response
"""
from ..models.task import TaskStatus, TaskState
from ..models.message import MessageRole, TextContent
# Default implementation extracts message from task and uses send_message
message_data = task.message or {}
content = message_data.get("content", {})
if isinstance(content, dict) and "text" in content:
text = content["text"]
elif hasattr(content, '__str__'):
text = str(content)
else:
text = repr(content) if content else ""
if not text:
task.status = TaskStatus(
state=TaskState.INPUT_REQUIRED,
message="Please provide a text query."
)
return task
try:
# Create a message
message = Message(
content=TextContent(text=text),
role=MessageRole.USER
)
# Process with send_message
response = await self.send_message_async(message)
# Extract text
if hasattr(response.content, "text"):
result = response.content.text
else:
result = str(response.content)
# Create response
task.artifacts = [{
"parts": [{"type": "text", "text": result}]
}]
task.status = TaskStatus(state=TaskState.COMPLETED)
except Exception as e:
# Handle error
import logging
logging.exception("Error processing task")
task.status = TaskStatus(
state=TaskState.FAILED,
message=f"Error: {str(e)}"
)
return task