-
Notifications
You must be signed in to change notification settings - Fork 420
Expand file tree
/
Copy pathclient.py
More file actions
255 lines (207 loc) · 8.07 KB
/
client.py
File metadata and controls
255 lines (207 loc) · 8.07 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
import dataclasses
import logging
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Callable, Coroutine
from typing import TYPE_CHECKING, Any
import httpx
from a2a.client.middleware import ClientCallContext, ClientCallInterceptor
from a2a.client.optionals import Channel
from a2a.types import (
AgentCard,
GetTaskPushNotificationConfigParams,
Message,
PushNotificationConfig,
Task,
TaskArtifactUpdateEvent,
TaskIdParams,
TaskPushNotificationConfig,
TaskQueryParams,
TaskStatusUpdateEvent,
TransportProtocol,
)
if TYPE_CHECKING:
from a2a.client.tls import TLSConfig
logger = logging.getLogger(__name__)
@dataclasses.dataclass
class ClientConfig:
"""Configuration class for the A2AClient Factory."""
streaming: bool = True
"""Whether client supports streaming"""
polling: bool = False
"""Whether client prefers to poll for updates from message:send. It is
the callers job to check if the response is completed and if not run a
polling loop."""
httpx_client: httpx.AsyncClient | None = None
"""Http client to use to connect to agent."""
grpc_channel_factory: Callable[[str], Channel] | None = None
"""Generates a grpc connection channel for a given url."""
supported_transports: list[TransportProtocol | str] = dataclasses.field(
default_factory=list
)
"""Ordered list of transports for connecting to agent
(in order of preference). Empty implies JSONRPC only.
This is a string type to allow custom
transports to exist in closed ecosystems.
"""
use_client_preference: bool = False
"""Whether to use client transport preferences over server preferences.
Recommended to use server preferences in most situations."""
accepted_output_modes: list[str] = dataclasses.field(default_factory=list)
"""The set of accepted output modes for the client."""
push_notification_configs: list[PushNotificationConfig] = dataclasses.field(
default_factory=list
)
"""Push notification callbacks to use for every request."""
extensions: list[str] = dataclasses.field(default_factory=list)
"""A list of extension URIs the client supports."""
tls_config: 'TLSConfig | None' = None
"""TLS/SSL configuration for secure communication. If provided, this
will be used to configure secure connections for HTTP and gRPC
transports. Ignored if httpx_client or grpc_channel_factory is
explicitly provided."""
validate_messages: bool = False
"""Whether to validate messages against JSON Schema before sending
and after receiving. Useful for protocol compliance testing."""
def get_httpx_client(self) -> httpx.AsyncClient:
"""Get or create an httpx client with TLS configuration.
Returns:
Configured httpx.AsyncClient instance.
"""
if self.httpx_client is not None:
return self.httpx_client
if self.tls_config is not None:
return self.tls_config.create_httpx_client()
return httpx.AsyncClient()
def get_grpc_channel_factory(self) -> Callable[[str], Channel] | None:
"""Get or create a gRPC channel factory with TLS configuration.
Returns:
A callable that creates gRPC channels, or None.
"""
if self.grpc_channel_factory is not None:
return self.grpc_channel_factory
if self.tls_config is not None:
from a2a.client.tls import create_grpc_channel_factory
return create_grpc_channel_factory(self.tls_config)
return None
UpdateEvent = TaskStatusUpdateEvent | TaskArtifactUpdateEvent | None
# Alias for emitted events from client
ClientEvent = tuple[Task, UpdateEvent]
# Alias for an event consuming callback. It takes either a (task, update) pair
# or a message as well as the agent card for the agent this came from.
Consumer = Callable[
[ClientEvent | Message, AgentCard], Coroutine[None, Any, Any]
]
class Client(ABC):
"""Abstract base class defining the interface for an A2A client.
This class provides a standard set of methods for interacting with an A2A
agent, regardless of the underlying transport protocol (e.g., gRPC, JSON-RPC).
It supports sending messages, managing tasks, and handling event streams.
"""
def __init__(
self,
consumers: list[Consumer] | None = None,
middleware: list[ClientCallInterceptor] | None = None,
):
"""Initializes the client with consumers and middleware.
Args:
consumers: A list of callables to process events from the agent.
middleware: A list of interceptors to process requests and responses.
"""
if middleware is None:
middleware = []
if consumers is None:
consumers = []
self._consumers = consumers
self._middleware = middleware
@abstractmethod
async def send_message(
self,
request: Message,
*,
context: ClientCallContext | None = None,
request_metadata: dict[str, Any] | None = None,
extensions: list[str] | None = None,
) -> AsyncIterator[ClientEvent | Message]:
"""Sends a message to the server.
This will automatically use the streaming or non-streaming approach
as supported by the server and the client config. Client will
aggregate update events and return an iterator of (`Task`,`Update`)
pairs, or a `Message`. Client will also send these values to any
configured `Consumer`s in the client.
"""
return
yield
@abstractmethod
async def get_task(
self,
request: TaskQueryParams,
*,
context: ClientCallContext | None = None,
extensions: list[str] | None = None,
) -> Task:
"""Retrieves the current state and history of a specific task."""
@abstractmethod
async def cancel_task(
self,
request: TaskIdParams,
*,
context: ClientCallContext | None = None,
extensions: list[str] | None = None,
) -> Task:
"""Requests the agent to cancel a specific task."""
@abstractmethod
async def set_task_callback(
self,
request: TaskPushNotificationConfig,
*,
context: ClientCallContext | None = None,
extensions: list[str] | None = None,
) -> TaskPushNotificationConfig:
"""Sets or updates the push notification configuration for a specific task."""
@abstractmethod
async def get_task_callback(
self,
request: GetTaskPushNotificationConfigParams,
*,
context: ClientCallContext | None = None,
extensions: list[str] | None = None,
) -> TaskPushNotificationConfig:
"""Retrieves the push notification configuration for a specific task."""
@abstractmethod
async def resubscribe(
self,
request: TaskIdParams,
*,
context: ClientCallContext | None = None,
extensions: list[str] | None = None,
) -> AsyncIterator[ClientEvent]:
"""Resubscribes to a task's event stream."""
return
yield
@abstractmethod
async def get_card(
self,
*,
context: ClientCallContext | None = None,
extensions: list[str] | None = None,
signature_verifier: Callable[[AgentCard], None] | None = None,
) -> AgentCard:
"""Retrieves the agent's card."""
async def add_event_consumer(self, consumer: Consumer) -> None:
"""Attaches additional consumers to the `Client`."""
self._consumers.append(consumer)
async def add_request_middleware(
self, middleware: ClientCallInterceptor
) -> None:
"""Attaches additional middleware to the `Client`."""
self._middleware.append(middleware)
async def consume(
self,
event: tuple[Task, UpdateEvent] | Message | None,
card: AgentCard,
) -> None:
"""Processes the event via all the registered `Consumer`s."""
if not event:
return
for c in self._consumers:
await c(event, card)