-
Notifications
You must be signed in to change notification settings - Fork 422
Expand file tree
/
Copy pathgrpc_handler.py
More file actions
424 lines (374 loc) · 15.3 KB
/
grpc_handler.py
File metadata and controls
424 lines (374 loc) · 15.3 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# ruff: noqa: N802
import contextlib
import logging
from abc import ABC, abstractmethod
from collections.abc import AsyncIterable, Sequence
try:
import grpc
import grpc.aio
from grpc.aio import Metadata
except ImportError as e:
raise ImportError(
'GrpcHandler requires grpcio and grpcio-tools to be installed. '
'Install with: '
"'pip install a2a-sdk[grpc]'"
) from e
from collections.abc import Callable
import a2a.grpc.a2a_pb2_grpc as a2a_grpc
from a2a import types
from a2a.auth.user import UnauthenticatedUser
from a2a.extensions.common import (
HTTP_EXTENSION_HEADER,
HTTP_EXTENSION_HEADER_DEPRECATED,
get_requested_extensions,
)
from a2a.grpc import a2a_pb2
from a2a.server.context import ServerCallContext
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types import AgentCard, TaskNotFoundError
from a2a.utils import proto_utils
from a2a.utils.errors import ServerError
from a2a.utils.helpers import validate, validate_async_generator
logger = logging.getLogger(__name__)
# For now we use a trivial wrapper on the grpc context object
class CallContextBuilder(ABC):
"""A class for building ServerCallContexts using the Starlette Request."""
@abstractmethod
def build(self, context: grpc.aio.ServicerContext) -> ServerCallContext:
"""Builds a ServerCallContext from a gRPC Request."""
def _get_metadata_value(
context: grpc.aio.ServicerContext, key: str
) -> list[str]:
md = context.invocation_metadata
raw_values: list[str | bytes] = []
if isinstance(md, Metadata):
raw_values = md.get_all(key)
elif isinstance(md, Sequence):
lower_key = key.lower()
raw_values = [e for (k, e) in md if k.lower() == lower_key]
return [e if isinstance(e, str) else e.decode('utf-8') for e in raw_values]
class DefaultCallContextBuilder(CallContextBuilder):
"""A default implementation of CallContextBuilder."""
def build(self, context: grpc.aio.ServicerContext) -> ServerCallContext:
"""Builds the ServerCallContext."""
user = UnauthenticatedUser()
state = {}
with contextlib.suppress(Exception):
state['grpc_context'] = context
extension_values = _get_metadata_value(
context, HTTP_EXTENSION_HEADER
) or _get_metadata_value(context, HTTP_EXTENSION_HEADER_DEPRECATED)
return ServerCallContext(
user=user,
state=state,
requested_extensions=get_requested_extensions(extension_values),
)
class GrpcHandler(a2a_grpc.A2AServiceServicer):
"""Maps incoming gRPC requests to the appropriate request handler method."""
def __init__(
self,
agent_card: AgentCard,
request_handler: RequestHandler,
context_builder: CallContextBuilder | None = None,
card_modifier: Callable[[AgentCard], AgentCard] | None = None,
):
"""Initializes the GrpcHandler.
Args:
agent_card: The AgentCard describing the agent's capabilities.
request_handler: The underlying `RequestHandler` instance to
delegate requests to.
context_builder: The CallContextBuilder object. If none the
DefaultCallContextBuilder is used.
card_modifier: An optional callback to dynamically modify the public
agent card before it is served.
"""
self.agent_card = agent_card
self.request_handler = request_handler
self.context_builder = context_builder or DefaultCallContextBuilder()
self.card_modifier = card_modifier
async def SendMessage(
self,
request: a2a_pb2.SendMessageRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.SendMessageResponse:
"""Handles the 'SendMessage' gRPC method.
Args:
request: The incoming `SendMessageRequest` object.
context: Context provided by the server.
Returns:
A `SendMessageResponse` object containing the result (Task or
Message) or throws an error response if a `ServerError` is raised
by the handler.
"""
try:
# Construct the server context object
server_context = self.context_builder.build(context)
# Transform the proto object to the python internal objects
a2a_request = proto_utils.FromProto.message_send_params(
request,
)
task_or_message = await self.request_handler.on_message_send(
a2a_request, server_context
)
self._set_extension_metadata(context, server_context)
return proto_utils.ToProto.task_or_message(task_or_message)
except ServerError as e:
await self.abort_context(e, context)
return a2a_pb2.SendMessageResponse()
@validate_async_generator(
lambda self: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def SendStreamingMessage(
self,
request: a2a_pb2.SendMessageRequest,
context: grpc.aio.ServicerContext,
) -> AsyncIterable[a2a_pb2.StreamResponse]:
"""Handles the 'StreamMessage' gRPC method.
Yields response objects as they are produced by the underlying handler's
stream.
Args:
request: The incoming `SendMessageRequest` object.
context: Context provided by the server.
Yields:
`StreamResponse` objects containing streaming events
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent)
or gRPC error responses if a `ServerError` is raised.
"""
server_context = self.context_builder.build(context)
# Transform the proto object to the python internal objects
a2a_request = proto_utils.FromProto.message_send_params(
request,
)
try:
async for event in self.request_handler.on_message_send_stream(
a2a_request, server_context
):
yield proto_utils.ToProto.stream_response(event)
self._set_extension_metadata(context, server_context)
except ServerError as e:
await self.abort_context(e, context)
return
async def CancelTask(
self,
request: a2a_pb2.CancelTaskRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.Task:
"""Handles the 'CancelTask' gRPC method.
Args:
request: The incoming `CancelTaskRequest` object.
context: Context provided by the server.
Returns:
A `Task` object containing the updated Task or a gRPC error.
"""
try:
server_context = self.context_builder.build(context)
task_id_params = proto_utils.FromProto.task_id_params(request)
task = await self.request_handler.on_cancel_task(
task_id_params, server_context
)
if task:
return proto_utils.ToProto.task(task)
await self.abort_context(
ServerError(error=TaskNotFoundError()), context
)
except ServerError as e:
await self.abort_context(e, context)
return a2a_pb2.Task()
@validate_async_generator(
lambda self: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def TaskSubscription(
self,
request: a2a_pb2.TaskSubscriptionRequest,
context: grpc.aio.ServicerContext,
) -> AsyncIterable[a2a_pb2.StreamResponse]:
"""Handles the 'TaskSubscription' gRPC method.
Yields response objects as they are produced by the underlying handler's
stream.
Args:
request: The incoming `TaskSubscriptionRequest` object.
context: Context provided by the server.
Yields:
`StreamResponse` objects containing streaming events
"""
try:
server_context = self.context_builder.build(context)
async for event in self.request_handler.on_resubscribe_to_task(
proto_utils.FromProto.task_id_params(request),
server_context,
):
yield proto_utils.ToProto.stream_response(event)
except ServerError as e:
await self.abort_context(e, context)
async def GetTaskPushNotificationConfig(
self,
request: a2a_pb2.GetTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.TaskPushNotificationConfig:
"""Handles the 'GetTaskPushNotificationConfig' gRPC method.
Args:
request: The incoming `GetTaskPushNotificationConfigRequest` object.
context: Context provided by the server.
Returns:
A `TaskPushNotificationConfig` object containing the config.
"""
try:
server_context = self.context_builder.build(context)
config = (
await self.request_handler.on_get_task_push_notification_config(
proto_utils.FromProto.task_id_params(request),
server_context,
)
)
return proto_utils.ToProto.task_push_notification_config(config)
except ServerError as e:
await self.abort_context(e, context)
return a2a_pb2.TaskPushNotificationConfig()
@validate(
lambda self: self.agent_card.capabilities.push_notifications,
'Push notifications are not supported by the agent',
)
async def CreateTaskPushNotificationConfig(
self,
request: a2a_pb2.CreateTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.TaskPushNotificationConfig:
"""Handles the 'CreateTaskPushNotificationConfig' gRPC method.
Requires the agent to support push notifications.
Args:
request: The incoming `CreateTaskPushNotificationConfigRequest` object.
context: Context provided by the server.
Returns:
A `TaskPushNotificationConfig` object
Raises:
ServerError: If push notifications are not supported by the agent
(due to the `@validate` decorator).
"""
try:
server_context = self.context_builder.build(context)
config = (
await self.request_handler.on_set_task_push_notification_config(
proto_utils.FromProto.task_push_notification_config_request(
request,
),
server_context,
)
)
return proto_utils.ToProto.task_push_notification_config(config)
except ServerError as e:
await self.abort_context(e, context)
return a2a_pb2.TaskPushNotificationConfig()
async def GetTask(
self,
request: a2a_pb2.GetTaskRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.Task:
"""Handles the 'GetTask' gRPC method.
Args:
request: The incoming `GetTaskRequest` object.
context: Context provided by the server.
Returns:
A `Task` object.
"""
try:
server_context = self.context_builder.build(context)
task = await self.request_handler.on_get_task(
proto_utils.FromProto.task_query_params(request), server_context
)
if task:
return proto_utils.ToProto.task(task)
await self.abort_context(
ServerError(error=TaskNotFoundError()), context
)
except ServerError as e:
await self.abort_context(e, context)
return a2a_pb2.Task()
async def GetAgentCard(
self,
request: a2a_pb2.GetAgentCardRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.AgentCard:
"""Get the agent card for the agent served."""
card_to_serve = self.agent_card
if self.card_modifier:
card_to_serve = self.card_modifier(card_to_serve)
return proto_utils.ToProto.agent_card(card_to_serve)
async def abort_context(
self, error: ServerError, context: grpc.aio.ServicerContext
) -> None:
"""Sets the grpc errors appropriately in the context."""
match error.error:
case types.JSONParseError():
await context.abort(
grpc.StatusCode.INTERNAL,
f'JSONParseError: {error.error.message}',
)
case types.InvalidRequestError():
await context.abort(
grpc.StatusCode.INVALID_ARGUMENT,
f'InvalidRequestError: {error.error.message}',
)
case types.MethodNotFoundError():
await context.abort(
grpc.StatusCode.NOT_FOUND,
f'MethodNotFoundError: {error.error.message}',
)
case types.InvalidParamsError():
await context.abort(
grpc.StatusCode.INVALID_ARGUMENT,
f'InvalidParamsError: {error.error.message}',
)
case types.InternalError():
await context.abort(
grpc.StatusCode.INTERNAL,
f'InternalError: {error.error.message}',
)
case types.TaskNotFoundError():
await context.abort(
grpc.StatusCode.NOT_FOUND,
f'TaskNotFoundError: {error.error.message}',
)
case types.TaskNotCancelableError():
await context.abort(
grpc.StatusCode.UNIMPLEMENTED,
f'TaskNotCancelableError: {error.error.message}',
)
case types.PushNotificationNotSupportedError():
await context.abort(
grpc.StatusCode.UNIMPLEMENTED,
f'PushNotificationNotSupportedError: {error.error.message}',
)
case types.UnsupportedOperationError():
await context.abort(
grpc.StatusCode.UNIMPLEMENTED,
f'UnsupportedOperationError: {error.error.message}',
)
case types.ContentTypeNotSupportedError():
await context.abort(
grpc.StatusCode.UNIMPLEMENTED,
f'ContentTypeNotSupportedError: {error.error.message}',
)
case types.InvalidAgentResponseError():
await context.abort(
grpc.StatusCode.INTERNAL,
f'InvalidAgentResponseError: {error.error.message}',
)
case _:
await context.abort(
grpc.StatusCode.UNKNOWN,
f'Unknown error type: {error.error}',
)
def _set_extension_metadata(
self,
context: grpc.aio.ServicerContext,
server_context: ServerCallContext,
) -> None:
if server_context.activated_extensions:
context.set_trailing_metadata(
[
(HTTP_EXTENSION_HEADER, e)
for e in sorted(server_context.activated_extensions)
]
)