-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathhello_world_agent.py
More file actions
275 lines (240 loc) · 8.31 KB
/
hello_world_agent.py
File metadata and controls
275 lines (240 loc) · 8.31 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
import argparse
import asyncio
import contextlib
import logging
import grpc
import uvicorn
from fastapi import FastAPI
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.agent_executor import AgentExecutor
from a2a.server.agent_execution.context import RequestContext
from a2a.server.events.event_queue import EventQueue
from a2a.server.request_handlers import DefaultRequestHandler, GrpcHandler
from a2a.server.routes import (
create_agent_card_routes,
create_jsonrpc_routes,
create_rest_routes,
)
from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore
from a2a.server.tasks.task_updater import TaskUpdater
from a2a.types import (
AgentCapabilities,
AgentCard,
AgentInterface,
AgentProvider,
AgentSkill,
Part,
Task,
TaskState,
TaskStatus,
a2a_pb2_grpc,
)
logger = logging.getLogger(__name__)
class SampleAgentExecutor(AgentExecutor):
"""Sample agent executor logic similar to the a2a-js sample."""
def __init__(self) -> None:
self.running_tasks: set[str] = set()
async def cancel(
self, context: RequestContext, event_queue: EventQueue
) -> None:
"""Cancels a task."""
task_id = context.task_id
if task_id in self.running_tasks:
self.running_tasks.remove(task_id)
updater = TaskUpdater(
event_queue=event_queue,
task_id=task_id or '',
context_id=context.context_id or '',
)
await updater.cancel()
async def execute(
self, context: RequestContext, event_queue: EventQueue
) -> None:
"""Executes a task inline."""
user_message = context.message
task_id = context.task_id
context_id = context.context_id
if not user_message or not task_id or not context_id:
return
self.running_tasks.add(task_id)
logger.info(
'[SampleAgentExecutor] Processing message %s for task %s (context: %s)',
user_message.message_id,
task_id,
context_id,
)
await event_queue.enqueue_event(
Task(
id=task_id,
context_id=context_id,
status=TaskStatus(state=TaskState.TASK_STATE_SUBMITTED),
history=[user_message],
)
)
updater = TaskUpdater(
event_queue=event_queue,
task_id=task_id,
context_id=context_id,
)
working_message = updater.new_agent_message(
parts=[Part(text='Processing your question...')]
)
await updater.start_work(message=working_message)
query = context.get_user_input()
agent_reply_text = self._parse_input(query)
await asyncio.sleep(1)
if task_id not in self.running_tasks:
return
await updater.add_artifact(
parts=[Part(text=agent_reply_text)],
name='response',
last_chunk=True,
)
await updater.complete()
logger.info(
'[SampleAgentExecutor] Task %s finished with state: completed',
task_id,
)
def _parse_input(self, query: str) -> str:
if not query:
return 'Hello! Please provide a message for me to respond to.'
ql = query.lower()
if 'hello' in ql or 'hi' in ql:
return 'Hello World! Nice to meet you!'
if 'how are you' in ql:
return (
"I'm doing great! Thanks for asking. How can I help you today?"
)
if 'goodbye' in ql or 'bye' in ql:
return 'Goodbye! Have a wonderful day!'
return f"Hello World! You said: '{query}'. Thanks for your message!"
async def serve(
host: str = '127.0.0.1',
port: int = 41241,
grpc_port: int = 50051,
compat_grpc_port: int = 50052,
) -> None:
"""Run the Sample Agent server with mounted JSON-RPC, HTTP+JSON and gRPC transports."""
agent_card = AgentCard(
name='Sample Agent',
description='A sample agent to test the stream functionality.',
provider=AgentProvider(
organization='A2A Samples', url='https://example.com'
),
version='1.0.0',
capabilities=AgentCapabilities(
streaming=True, push_notifications=False
),
default_input_modes=['text'],
default_output_modes=['text', 'task-status'],
skills=[
AgentSkill(
id='sample_agent',
name='Sample Agent',
description='Say hi.',
tags=['sample'],
examples=['hi'],
input_modes=['text'],
output_modes=['text', 'task-status'],
)
],
supported_interfaces=[
AgentInterface(
protocol_binding='GRPC',
protocol_version='1.0',
url=f'{host}:{grpc_port}',
),
AgentInterface(
protocol_binding='GRPC',
protocol_version='0.3',
url=f'{host}:{compat_grpc_port}',
),
AgentInterface(
protocol_binding='JSONRPC',
protocol_version='1.0',
url=f'http://{host}:{port}/a2a/jsonrpc',
),
AgentInterface(
protocol_binding='JSONRPC',
protocol_version='0.3',
url=f'http://{host}:{port}/a2a/jsonrpc',
),
AgentInterface(
protocol_binding='HTTP+JSON',
protocol_version='1.0',
url=f'http://{host}:{port}/a2a/rest',
),
AgentInterface(
protocol_binding='HTTP+JSON',
protocol_version='0.3',
url=f'http://{host}:{port}/a2a/rest',
),
],
)
task_store = InMemoryTaskStore()
request_handler = DefaultRequestHandler(
agent_executor=SampleAgentExecutor(),
task_store=task_store,
agent_card=agent_card,
)
rest_routes = create_rest_routes(
request_handler=request_handler,
path_prefix='/a2a/rest',
enable_v0_3_compat=True,
)
jsonrpc_routes = create_jsonrpc_routes(
request_handler=request_handler,
rpc_url='/a2a/jsonrpc',
enable_v0_3_compat=True,
)
agent_card_routes = create_agent_card_routes(
agent_card=agent_card,
)
app = FastAPI()
app.routes.extend(jsonrpc_routes)
app.routes.extend(agent_card_routes)
app.routes.extend(rest_routes)
grpc_server = grpc.aio.server()
grpc_server.add_insecure_port(f'{host}:{grpc_port}')
servicer = GrpcHandler(request_handler)
a2a_pb2_grpc.add_A2AServiceServicer_to_server(servicer, grpc_server)
compat_grpc_server = grpc.aio.server()
compat_grpc_server.add_insecure_port(f'{host}:{compat_grpc_port}')
compat_servicer = CompatGrpcHandler(request_handler)
a2a_v0_3_pb2_grpc.add_A2AServiceServicer_to_server(
compat_servicer, compat_grpc_server
)
config = uvicorn.Config(app, host=host, port=port)
uvicorn_server = uvicorn.Server(config)
logger.info('Starting Sample Agent servers:')
logger.info(' - HTTP on http://%s:%s', host, port)
logger.info(' - gRPC on %s:%s', host, grpc_port)
logger.info(' - gRPC (v0.3 compat) on %s:%s', host, compat_grpc_port)
logger.info(
'Agent Card available at http://%s:%s/.well-known/agent-card.json',
host,
port,
)
await asyncio.gather(
grpc_server.start(),
compat_grpc_server.start(),
uvicorn_server.serve(),
)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description='Sample A2A agent server')
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', type=int, default=41241)
parser.add_argument('--grpc-port', type=int, default=50051)
parser.add_argument('--compat-grpc-port', type=int, default=50052)
args = parser.parse_args()
with contextlib.suppress(KeyboardInterrupt):
asyncio.run(
serve(
host=args.host,
port=args.port,
grpc_port=args.grpc_port,
compat_grpc_port=args.compat_grpc_port,
)
)