-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathmain.py
More file actions
374 lines (322 loc) · 11.9 KB
/
main.py
File metadata and controls
374 lines (322 loc) · 11.9 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import argparse # noqa: I001
import asyncio
import base64
import logging
import uuid
import grpc
import httpx
import uvicorn
from fastapi import FastAPI
from pyproto import instruction_pb2
from a2a.client import ClientConfig, create_client
from a2a.compat.v0_3 import a2a_v0_3_pb2_grpc
from a2a.compat.v0_3.grpc_handler import CompatGrpcHandler
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.routes.rest_routes import create_rest_routes
from a2a.server.events import EventQueue
from a2a.server.events.in_memory_queue_manager import InMemoryQueueManager
from a2a.server.request_handlers import DefaultRequestHandler, GrpcHandler
from a2a.server.tasks import TaskUpdater
from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore
from a2a.types import a2a_pb2_grpc
from a2a.types.a2a_pb2 import (
AgentCapabilities,
AgentCard,
AgentInterface,
Message,
Part,
SendMessageRequest,
TaskState,
)
from a2a.utils import TransportProtocol
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def extract_instruction(
message: Message | None,
) -> instruction_pb2.Instruction | None:
"""Extracts an Instruction proto from an A2A Message."""
if not message or not message.parts:
return None
for part in message.parts:
# 1. Handle binary protobuf part (media_type or filename)
if (
part.media_type == 'application/x-protobuf'
or part.filename == 'instruction.bin'
):
try:
inst = instruction_pb2.Instruction()
if part.raw:
inst.ParseFromString(part.raw)
elif part.text:
# Some clients might send it as base64 in text part
raw = base64.b64decode(part.text)
inst.ParseFromString(raw)
except Exception:
logger.debug(
'Failed to parse instruction from binary part',
exc_info=True,
)
continue
else:
return inst
# 2. Handle base64 encoded instruction in any text part
if part.text:
try:
raw = base64.b64decode(part.text)
inst = instruction_pb2.Instruction()
inst.ParseFromString(raw)
except Exception:
logger.debug(
'Failed to parse instruction from text part', exc_info=True
)
continue
else:
return inst
return None
def wrap_instruction_to_request(inst: instruction_pb2.Instruction) -> Message:
"""Wraps an Instruction proto into an A2A Message."""
inst_bytes = inst.SerializeToString()
return Message(
role='ROLE_USER',
message_id=str(uuid.uuid4()),
parts=[
Part(
raw=inst_bytes,
media_type='application/x-protobuf',
filename='instruction.bin',
)
],
)
async def handle_call_agent(call: instruction_pb2.CallAgent) -> list[str]:
"""Handles the CallAgent instruction by invoking another agent."""
logger.info('Calling agent %s via %s', call.agent_card_uri, call.transport)
# Mapping transport string to TransportProtocol enum
transport_map = {
'JSONRPC': TransportProtocol.JSONRPC,
'HTTP+JSON': TransportProtocol.HTTP_JSON,
'HTTP_JSON': TransportProtocol.HTTP_JSON,
'REST': TransportProtocol.HTTP_JSON,
'GRPC': TransportProtocol.GRPC,
}
selected_transport = transport_map.get(call.transport.upper())
if selected_transport is None:
raise ValueError(f'Unsupported transport: {call.transport}')
config = ClientConfig()
config.httpx_client = httpx.AsyncClient(timeout=30.0)
config.grpc_channel_factory = grpc.aio.insecure_channel
config.supported_protocol_bindings = [selected_transport]
config.streaming = call.streaming or (
selected_transport == TransportProtocol.GRPC
)
try:
client = await create_client(call.agent_card_uri, client_config=config)
# Wrap nested instruction
async with client:
nested_msg = wrap_instruction_to_request(call.instruction)
request = SendMessageRequest(message=nested_msg)
results: list[str] = []
async for event in client.send_message(request):
# Event is StreamResponse
logger.info('Event: %s', event)
stream_resp = event
message = None
if stream_resp.HasField('message'):
message = stream_resp.message
elif stream_resp.HasField(
'task'
) and stream_resp.task.status.HasField('message'):
message = stream_resp.task.status.message
elif stream_resp.HasField(
'status_update'
) and stream_resp.status_update.status.HasField('message'):
message = stream_resp.status_update.status.message
if message:
results.extend(
part.text for part in message.parts if part.text
)
except Exception as e:
logger.exception('Failed to call outbound agent')
raise RuntimeError(
f'Outbound call to {call.agent_card_uri} failed: {e!s}'
) from e
else:
return results
async def handle_instruction(inst: instruction_pb2.Instruction) -> list[str]:
"""Recursively handles instructions."""
if inst.HasField('call_agent'):
return await handle_call_agent(inst.call_agent)
if inst.HasField('return_response'):
return [inst.return_response.response]
if inst.HasField('steps'):
all_results = []
for step in inst.steps.instructions:
results = await handle_instruction(step)
all_results.extend(results)
return all_results
raise ValueError('Unknown instruction type')
class V10AgentExecutor(AgentExecutor):
"""Executor for ITK v10 agent tasks."""
async def execute(
self, context: RequestContext, event_queue: EventQueue
) -> None:
"""Executes a task instruction."""
logger.info('Executing task %s', context.task_id)
task_updater = TaskUpdater(
event_queue,
context.task_id,
context.context_id,
)
await task_updater.update_status(TaskState.TASK_STATE_SUBMITTED)
await task_updater.update_status(TaskState.TASK_STATE_WORKING)
instruction = extract_instruction(context.message)
if not instruction:
error_msg = 'No valid instruction found in request'
logger.error(error_msg)
await task_updater.update_status(
TaskState.TASK_STATE_FAILED,
message=task_updater.new_agent_message([Part(text=error_msg)]),
)
return
try:
logger.info('Instruction: %s', instruction)
results = await handle_instruction(instruction)
response_text = '\n'.join(results)
logger.info('Response: %s', response_text)
await task_updater.update_status(
TaskState.TASK_STATE_COMPLETED,
message=task_updater.new_agent_message(
[Part(text=response_text)]
),
)
logger.info('Task %s completed', context.task_id)
except Exception as e:
logger.exception('Error during instruction handling')
await task_updater.update_status(
TaskState.TASK_STATE_FAILED,
message=task_updater.new_agent_message([Part(text=str(e))]),
)
async def cancel(
self, context: RequestContext, event_queue: EventQueue
) -> None:
"""Cancels a task."""
logger.info('Cancel requested for task %s', context.task_id)
task_updater = TaskUpdater(
event_queue,
context.task_id,
context.context_id,
)
await task_updater.update_status(TaskState.TASK_STATE_CANCELED)
async def main_async(http_port: int, grpc_port: int) -> None:
"""Starts the Agent with HTTP and gRPC interfaces."""
interfaces = [
AgentInterface(
protocol_binding=TransportProtocol.GRPC,
url=f'127.0.0.1:{grpc_port}',
protocol_version='1.0',
),
AgentInterface(
protocol_binding=TransportProtocol.GRPC,
url=f'127.0.0.1:{grpc_port}',
protocol_version='0.3',
),
]
interfaces.append(
AgentInterface(
protocol_binding=TransportProtocol.JSONRPC,
url=f'http://127.0.0.1:{http_port}/jsonrpc/',
protocol_version='1.0',
)
)
interfaces.append(
AgentInterface(
protocol_binding=TransportProtocol.JSONRPC,
url=f'http://127.0.0.1:{http_port}/jsonrpc/',
protocol_version='0.3',
)
)
interfaces.append(
AgentInterface(
protocol_binding=TransportProtocol.HTTP_JSON,
url=f'http://127.0.0.1:{http_port}/rest/',
protocol_version='1.0',
)
)
interfaces.append(
AgentInterface(
protocol_binding=TransportProtocol.HTTP_JSON,
url=f'http://127.0.0.1:{http_port}/rest/',
protocol_version='0.3',
)
)
agent_card = AgentCard(
name='ITK v10 Agent',
description='Python agent using SDK 1.0.',
version='1.0.0',
capabilities=AgentCapabilities(
streaming=True,
push_notifications=True,
extended_agent_card=True,
),
default_input_modes=['text/plain'],
default_output_modes=['text/plain'],
supported_interfaces=interfaces,
)
task_store = InMemoryTaskStore()
handler = DefaultRequestHandler(
agent_executor=V10AgentExecutor(),
task_store=task_store,
agent_card=agent_card,
queue_manager=InMemoryQueueManager(),
)
handler_extended = DefaultRequestHandler(
agent_executor=V10AgentExecutor(),
task_store=task_store,
agent_card=agent_card,
queue_manager=InMemoryQueueManager(),
extended_agent_card=agent_card,
)
app = FastAPI()
agent_card_routes = create_agent_card_routes(
agent_card=agent_card, card_url='/.well-known/agent-card.json'
)
jsonrpc_routes = create_jsonrpc_routes(
request_handler=handler_extended,
rpc_url='/',
enable_v0_3_compat=True,
)
app.mount(
'/jsonrpc',
FastAPI(routes=jsonrpc_routes + agent_card_routes),
)
rest_routes = create_rest_routes(
request_handler=handler,
enable_v0_3_compat=True,
)
app.mount('/rest', FastAPI(routes=rest_routes + agent_card_routes))
server = grpc.aio.server()
compat_servicer = CompatGrpcHandler(handler)
a2a_v0_3_pb2_grpc.add_A2AServiceServicer_to_server(compat_servicer, server)
servicer = GrpcHandler(handler)
a2a_pb2_grpc.add_A2AServiceServicer_to_server(servicer, server)
server.add_insecure_port(f'127.0.0.1:{grpc_port}')
await server.start()
logger.info(
'Starting ITK v10 Agent on HTTP port %s and gRPC port %s',
http_port,
grpc_port,
)
config = uvicorn.Config(
app, host='127.0.0.1', port=http_port, log_level='info'
)
uvicorn_server = uvicorn.Server(config)
await uvicorn_server.serve()
def main() -> None:
"""Main entry point for the agent."""
parser = argparse.ArgumentParser()
parser.add_argument('--httpPort', type=int, default=10102)
parser.add_argument('--grpcPort', type=int, default=11002)
args = parser.parse_args()
asyncio.run(main_async(args.httpPort, args.grpcPort))
if __name__ == '__main__':
main()