Repository navigation
Expand file tree
/
Copy patha2a_tool.py
More file actions
155 lines (131 loc) · 5.67 KB
/
Copy patha2a_tool.py
File metadata and controls
155 lines (131 loc) · 5.67 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
"""读取远端配置,通过 A2A SDK 发送消息、查询任务和接收流式回复。"""
import asyncio
import os
from contextlib import aclosing, asynccontextmanager
from pathlib import Path
import httpx
from a2a.client.errors import (
A2AClientError,
A2AClientJSONRPCError,
A2AClientTimeoutError,
)
from a2a.client.transports.jsonrpc import JsonRpcTransport
from a2a.server.request_handlers import RequestHandler
from a2a.types import AgentCard, InternalError, PushNotificationNotSupportedError
from a2a.utils.errors import ServerError
from pydantic import ValidationError
DIRECTORY = Path(__file__).resolve().parent
TIMEOUT = 60.0
class UpstreamTimeoutError(ServerError):
def __init__(self):
super().__init__(InternalError(message="Remote A2A request timed out"))
@asynccontextmanager
async def upstream_errors():
try:
async with asyncio.timeout(TIMEOUT):
yield
except A2AClientJSONRPCError as exc:
raise ServerError(exc.error) from None
except (TimeoutError, httpx.TimeoutException, A2AClientTimeoutError):
raise UpstreamTimeoutError() from None
except (A2AClientError, httpx.HTTPError, ValidationError):
raise ServerError(InternalError(message="Remote A2A request failed")) from None
class A2ATool(RequestHandler):
"""把服务端收到的 A2A 请求直接交给远端 Agent。"""
def __init__(self, *, card_path=None, http_transport=None):
self.card_path = Path(
card_path
or os.getenv("REMOTE_AGENT_CARD_PATH", DIRECTORY / "remote_agentcard.json")
)
self.http_transport = http_transport
self.remote_card: AgentCard | None = None
self.client: JsonRpcTransport | None = None
self.http_client: httpx.AsyncClient | None = None
async def __aenter__(self):
try:
card = AgentCard.model_validate_json(self.card_path.read_text())
except (OSError, ValueError):
raise RuntimeError(
"Check remote_agentcard.json or REMOTE_AGENT_CARD_PATH"
) from None
api_key = os.getenv("HI_AGENT_API_KEY", "").strip()
if not api_key:
raise RuntimeError("Set HI_AGENT_API_KEY to the Hi Agent A2A channel key")
remote_url = card.url
if (card.preferred_transport or "JSONRPC") != "JSONRPC":
remote_url = next(
(
item.url
for item in card.additional_interfaces or []
if item.transport == "JSONRPC"
),
None,
)
if remote_url is None:
raise RuntimeError("Remote Agent Card must support JSONRPC")
self.remote_card = card
self.http_client = httpx.AsyncClient(
headers={"Apikey": api_key},
timeout=TIMEOUT,
transport=self.http_transport,
)
self.client = JsonRpcTransport(
self.http_client, agent_card=card, url=remote_url
)
return self
async def __aexit__(self, exc_type, exc_value, traceback):
if self.http_client is not None:
await self.http_client.aclose()
self.client = None
self.http_client = None
@staticmethod
def extensions(context):
return list(context.requested_extensions) if context else None
async def on_message_send(self, params, context=None):
"""发送消息,等待远端返回结果。"""
self._check_configuration(params)
async with upstream_errors():
return await self.client.send_message(
params, extensions=self.extensions(context)
)
async def on_message_send_stream(self, params, context=None):
"""发送消息,逐条转发远端事件。"""
self._check_configuration(params)
async with upstream_errors():
stream = self.client.send_message_streaming(
params, extensions=self.extensions(context)
)
async with aclosing(stream):
async for event in stream:
yield event
async def on_get_task(self, params, context=None):
async with upstream_errors():
return await self.client.get_task(
params, extensions=self.extensions(context)
)
async def on_cancel_task(self, params, context=None):
async with upstream_errors():
return await self.client.cancel_task(
params, extensions=self.extensions(context)
)
async def on_resubscribe_to_task(self, params, context=None):
async with upstream_errors():
stream = self.client.resubscribe(
params, extensions=self.extensions(context)
)
async with aclosing(stream):
async for event in stream:
yield event
@staticmethod
def _check_configuration(params):
if params.configuration and params.configuration.push_notification_config:
raise ServerError(PushNotificationNotSupportedError())
async def on_set_task_push_notification_config(self, params, context=None):
# SDK 要求实现这些方法;当前服务不使用推送通知。
raise ServerError(PushNotificationNotSupportedError())
async def on_get_task_push_notification_config(self, params, context=None):
raise ServerError(PushNotificationNotSupportedError())
async def on_list_task_push_notification_config(self, params, context=None):
raise ServerError(PushNotificationNotSupportedError())
async def on_delete_task_push_notification_config(self, params, context=None):
raise ServerError(PushNotificationNotSupportedError())