-
Notifications
You must be signed in to change notification settings - Fork 422
Expand file tree
/
Copy pathrest_handler.py
More file actions
307 lines (259 loc) · 9.78 KB
/
rest_handler.py
File metadata and controls
307 lines (259 loc) · 9.78 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
import logging
from collections.abc import AsyncIterable, AsyncIterator
from typing import TYPE_CHECKING, Any
from google.protobuf.json_format import (
MessageToDict,
MessageToJson,
Parse,
ParseDict,
)
if TYPE_CHECKING:
from starlette.requests import Request
else:
try:
from starlette.requests import Request
except ImportError:
Request = Any
from a2a.server.context import ServerCallContext
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types import a2a_pb2
from a2a.types.a2a_pb2 import (
AgentCard,
CancelTaskRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
SubscribeToTaskRequest,
)
from a2a.utils import proto_utils
from a2a.utils.errors import ServerError, TaskNotFoundError
from a2a.utils.helpers import validate
from a2a.utils.telemetry import SpanKind, trace_class
logger = logging.getLogger(__name__)
@trace_class(kind=SpanKind.SERVER)
class RESTHandler:
"""Maps incoming REST-like (JSON+HTTP) requests to the appropriate request handler method and formats responses.
This uses the protobuf definitions of the gRPC service as the source of truth. By
doing this, it ensures that this implementation and the gRPC transcoding
(via Envoy) are equivalent. This handler should be used if using the gRPC handler
with Envoy is not feasible for a given deployment solution. Use this handler
and a related application if you desire to ONLY server the RESTful API.
"""
def __init__(
self,
agent_card: AgentCard,
request_handler: RequestHandler,
):
"""Initializes the RESTHandler.
Args:
agent_card: The AgentCard describing the agent's capabilities.
request_handler: The underlying `RequestHandler` instance to delegate requests to.
"""
self.agent_card = agent_card
self.request_handler = request_handler
async def on_message_send(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'message/send' REST method.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Returns:
A `dict` containing the result (Task or Message)
"""
body = await request.body()
params = a2a_pb2.SendMessageRequest()
Parse(body, params)
task_or_message = await self.request_handler.on_message_send(
params, context
)
if isinstance(task_or_message, a2a_pb2.Task):
response = a2a_pb2.SendMessageResponse(task=task_or_message)
else:
response = a2a_pb2.SendMessageResponse(message=task_or_message)
return MessageToDict(response)
@validate(
lambda self: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def on_message_send_stream(
self,
request: Request,
context: ServerCallContext,
) -> AsyncIterator[str]:
"""Handles the 'message/stream' REST method.
Yields response objects as they are produced by the underlying handler's stream.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Yields:
JSON serialized objects containing streaming events
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) as JSON
"""
body = await request.body()
params = a2a_pb2.SendMessageRequest()
Parse(body, params)
async for event in self.request_handler.on_message_send_stream(
params, context
):
response = proto_utils.to_stream_response(event)
yield MessageToJson(response)
async def on_cancel_task(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'tasks/cancel' REST method.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Returns:
A `dict` containing the updated Task
"""
task_id = request.path_params['id']
task = await self.request_handler.on_cancel_task(
CancelTaskRequest(id=task_id), context
)
if task:
return MessageToDict(task)
raise ServerError(error=TaskNotFoundError())
@validate(
lambda self: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def on_subscribe_to_task(
self,
request: Request,
context: ServerCallContext,
) -> AsyncIterable[str]:
"""Handles the 'SubscribeToTask' REST method.
Yields response objects as they are produced by the underlying handler's stream.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Yields:
JSON serialized objects containing streaming events
"""
task_id = request.path_params['id']
async for event in self.request_handler.on_subscribe_to_task(
SubscribeToTaskRequest(id=task_id), context
):
yield MessageToJson(proto_utils.to_stream_response(event))
async def get_push_notification(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'tasks/pushNotificationConfig/get' REST method.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Returns:
A `dict` containing the config
"""
task_id = request.path_params['id']
push_id = request.path_params['push_id']
params = GetTaskPushNotificationConfigRequest(
task_id=task_id,
id=push_id,
)
config = (
await self.request_handler.on_get_task_push_notification_config(
params, context
)
)
return MessageToDict(config)
@validate(
lambda self: self.agent_card.capabilities.push_notifications,
'Push notifications are not supported by the agent',
)
async def set_push_notification(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'tasks/pushNotificationConfig/set' REST method.
Requires the agent to support push notifications.
Args:
request: The incoming `TaskPushNotificationConfig` object.
context: Context provided by the server.
Returns:
A `dict` containing the config object.
Raises:
ServerError: If push notifications are not supported by the agent
(due to the `@validate` decorator), A2AError if processing error is
found.
"""
task_id = request.path_params['id']
body = await request.body()
params = a2a_pb2.CreateTaskPushNotificationConfigRequest()
Parse(body, params)
# Set the parent to the task resource name format
params.task_id = task_id
config = (
await self.request_handler.on_create_task_push_notification_config(
params, context
)
)
return MessageToDict(config)
async def on_get_task(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'v1/tasks/{id}' REST method.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Returns:
A `Task` object containing the Task.
"""
task_id = request.path_params['id']
history_length_str = request.query_params.get('historyLength')
history_length = int(history_length_str) if history_length_str else None
params = GetTaskRequest(id=task_id, history_length=history_length)
task = await self.request_handler.on_get_task(params, context)
if task:
return MessageToDict(task)
raise ServerError(error=TaskNotFoundError())
async def list_tasks(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'tasks/list' REST method.
This method is currently not implemented.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Returns:
A list of `dict` representing the `Task` objects.
Raises:
NotImplementedError: This method is not yet implemented.
"""
params = a2a_pb2.ListTasksRequest()
# Parse query params, keeping arrays/repeated fields in mind if there are any
# Using a simple ParseDict for now, might need more robust query param parsing
# if the request structure contains nested or repeated elements
ParseDict(
dict(request.query_params), params, ignore_unknown_fields=True
)
result = await self.request_handler.on_list_tasks(params, context)
return MessageToDict(result)
async def list_push_notifications(
self,
request: Request,
context: ServerCallContext,
) -> dict[str, Any]:
"""Handles the 'tasks/pushNotificationConfig/list' REST method.
This method is currently not implemented.
Args:
request: The incoming `Request` object.
context: Context provided by the server.
Returns:
A list of `dict` representing the `TaskPushNotificationConfig` objects.
Raises:
NotImplementedError: This method is not yet implemented.
"""
raise NotImplementedError('list notifications not implemented')