forked from a2aproject/a2a-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
232 lines (191 loc) · 7.13 KB
/
client.py
File metadata and controls
232 lines (191 loc) · 7.13 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
import dataclasses
import logging
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Callable, MutableMapping
from types import TracebackType
from typing import Any
import httpx
from pydantic import BaseModel, Field
from typing_extensions import Self
from a2a.client.interceptors import ClientCallInterceptor
from a2a.client.optionals import Channel
from a2a.client.service_parameters import ServiceParameters
from a2a.types.a2a_pb2 import (
AgentCard,
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetExtendedAgentCardRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
ListTaskPushNotificationConfigsRequest,
ListTaskPushNotificationConfigsResponse,
ListTasksRequest,
ListTasksResponse,
SendMessageRequest,
StreamResponse,
SubscribeToTaskRequest,
Task,
TaskPushNotificationConfig,
)
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_protocol_bindings: list[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[TaskPushNotificationConfig] = (
dataclasses.field(default_factory=list)
)
"""Push notification configurations to use for every request."""
class ClientCallContext(BaseModel):
"""A context passed with each client call, allowing for call-specific.
configuration and data passing. Such as authentication details or
request deadlines.
"""
state: MutableMapping[str, Any] = Field(default_factory=dict)
timeout: float | None = None
service_parameters: ServiceParameters | None = None
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,
interceptors: list[ClientCallInterceptor] | None = None,
):
"""Initializes the client with interceptors.
Args:
interceptors: A list of interceptors to process requests and responses.
"""
self._interceptors = interceptors or []
async def __aenter__(self) -> Self:
"""Enters the async context manager."""
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Exits the async context manager and closes the client."""
await self.close()
@abstractmethod
async def send_message(
self,
request: SendMessageRequest,
*,
context: ClientCallContext | None = None,
) -> AsyncIterator[StreamResponse]:
"""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: GetTaskRequest,
*,
context: ClientCallContext | None = None,
) -> Task:
"""Retrieves the current state and history of a specific task."""
@abstractmethod
async def list_tasks(
self,
request: ListTasksRequest,
*,
context: ClientCallContext | None = None,
) -> ListTasksResponse:
"""Retrieves tasks for an agent."""
@abstractmethod
async def cancel_task(
self,
request: CancelTaskRequest,
*,
context: ClientCallContext | None = None,
) -> Task:
"""Requests the agent to cancel a specific task."""
@abstractmethod
async def create_task_push_notification_config(
self,
request: TaskPushNotificationConfig,
*,
context: ClientCallContext | None = None,
) -> TaskPushNotificationConfig:
"""Sets or updates the push notification configuration for a specific task."""
@abstractmethod
async def get_task_push_notification_config(
self,
request: GetTaskPushNotificationConfigRequest,
*,
context: ClientCallContext | None = None,
) -> TaskPushNotificationConfig:
"""Retrieves the push notification configuration for a specific task."""
@abstractmethod
async def list_task_push_notification_configs(
self,
request: ListTaskPushNotificationConfigsRequest,
*,
context: ClientCallContext | None = None,
) -> ListTaskPushNotificationConfigsResponse:
"""Lists push notification configurations for a specific task."""
@abstractmethod
async def delete_task_push_notification_config(
self,
request: DeleteTaskPushNotificationConfigRequest,
*,
context: ClientCallContext | None = None,
) -> None:
"""Deletes the push notification configuration for a specific task."""
@abstractmethod
async def subscribe(
self,
request: SubscribeToTaskRequest,
*,
context: ClientCallContext | None = None,
) -> AsyncIterator[StreamResponse]:
"""Resubscribes to a task's event stream."""
return
yield
@abstractmethod
async def get_extended_agent_card(
self,
request: GetExtendedAgentCardRequest,
*,
context: ClientCallContext | None = None,
signature_verifier: Callable[[AgentCard], None] | None = None,
) -> AgentCard:
"""Retrieves the agent's card."""
async def add_interceptor(self, interceptor: ClientCallInterceptor) -> None:
"""Attaches additional interceptors to the `Client`."""
self._interceptors.append(interceptor)
@abstractmethod
async def close(self) -> None:
"""Closes the client and releases any underlying resources."""