acps-math-visualizer 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- acps_math_visualizer/__init__.py +5 -0
- acps_math_visualizer/__main__.py +5 -0
- acps_math_visualizer/agents/__init__.py +7 -0
- acps_math_visualizer/agents/base.py +133 -0
- acps_math_visualizer/agents/intuition.py +154 -0
- acps_math_visualizer/agents/plotter.py +162 -0
- acps_math_visualizer/agents/transformation.py +234 -0
- acps_math_visualizer/cli.py +76 -0
- acps_math_visualizer/demo.py +125 -0
- acps_math_visualizer/identity.py +67 -0
- acps_math_visualizer/math_engine.py +333 -0
- acps_math_visualizer/mesh.py +55 -0
- acps_math_visualizer/models.py +214 -0
- acps_math_visualizer/orchestrator.py +300 -0
- acps_math_visualizer/protocol.py +64 -0
- acps_math_visualizer/py.typed +0 -0
- acps_math_visualizer/registry.py +84 -0
- acps_math_visualizer/runtime.py +178 -0
- acps_math_visualizer/visualization.py +160 -0
- acps_math_visualizer-1.0.0.dist-info/METADATA +39 -0
- acps_math_visualizer-1.0.0.dist-info/RECORD +24 -0
- acps_math_visualizer-1.0.0.dist-info/WHEEL +5 -0
- acps_math_visualizer-1.0.0.dist-info/entry_points.txt +2 -0
- acps_math_visualizer-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""Leader orchestration using ADP discovery and AIP v2 task dispatch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from importlib.metadata import version
|
|
11
|
+
from typing import TypeVar
|
|
12
|
+
from uuid import uuid4
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
from acps_sdk.adp import DiscoveryRequest, FilterOperator
|
|
16
|
+
from acps_sdk.aip import AipRpcClient, TaskResult, TaskState
|
|
17
|
+
from pydantic import BaseModel, ValidationError
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .identity import LEADER_AIC
|
|
21
|
+
from .models import (
|
|
22
|
+
AgentTrace,
|
|
23
|
+
AnimationProduct,
|
|
24
|
+
AnimationRequest,
|
|
25
|
+
FunctionRequest,
|
|
26
|
+
IntuitionConcept,
|
|
27
|
+
IntuitionProduct,
|
|
28
|
+
IntuitionRequest,
|
|
29
|
+
MessageKind,
|
|
30
|
+
PlotProduct,
|
|
31
|
+
ProductMeta,
|
|
32
|
+
TransformationProduct,
|
|
33
|
+
TransformationRequest,
|
|
34
|
+
VisualizationResult,
|
|
35
|
+
)
|
|
36
|
+
from .protocol import encode_message
|
|
37
|
+
from .registry import AgentRegistry, build_filter
|
|
38
|
+
from .runtime import AIP_RPC_PATH, PayloadError, product_payload
|
|
39
|
+
|
|
40
|
+
PLOTTER_TAG = "math-plotter"
|
|
41
|
+
TRANSFORMATION_TAG = "math-transformation"
|
|
42
|
+
INTUITION_TAG = "math-intuition"
|
|
43
|
+
SKILL_TAGS = (PLOTTER_TAG, TRANSFORMATION_TAG, INTUITION_TAG)
|
|
44
|
+
ModelT = TypeVar("ModelT", bound=BaseModel)
|
|
45
|
+
TraceCallback = Callable[[AgentTrace], None]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class AgentEndpoint:
|
|
50
|
+
"""A partner skill resolved from an SDK-native ADP discovery result."""
|
|
51
|
+
|
|
52
|
+
aic: str
|
|
53
|
+
name: str
|
|
54
|
+
skill_id: str
|
|
55
|
+
rpc_url: str
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def health_url(self) -> str:
|
|
59
|
+
return self.rpc_url.removesuffix(AIP_RPC_PATH) + "/healthz"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class MathOrchestrator:
|
|
63
|
+
"""Coordinate plot → transform → animate → intuition with data fan-in."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, registry: AgentRegistry, *, session_id: str | None = None) -> None:
|
|
66
|
+
self._registry = registry
|
|
67
|
+
self.session_id = session_id or f"math-{uuid4()}"
|
|
68
|
+
self._endpoints: dict[str, AgentEndpoint] = {}
|
|
69
|
+
self._clients: dict[str, AipRpcClient] = {}
|
|
70
|
+
self._traces: list[AgentTrace] = []
|
|
71
|
+
self._on_trace: TraceCallback | None = None
|
|
72
|
+
self._started = False
|
|
73
|
+
|
|
74
|
+
async def __aenter__(self) -> MathOrchestrator:
|
|
75
|
+
self.resolve_team()
|
|
76
|
+
for tag, endpoint in self._endpoints.items():
|
|
77
|
+
self._clients[tag] = AipRpcClient(endpoint.rpc_url, leader_id=LEADER_AIC)
|
|
78
|
+
await self._check_health()
|
|
79
|
+
return self
|
|
80
|
+
|
|
81
|
+
async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
|
|
82
|
+
for client in self._clients.values():
|
|
83
|
+
await client.close()
|
|
84
|
+
self._clients.clear()
|
|
85
|
+
|
|
86
|
+
def resolve_team(self) -> dict[str, AgentEndpoint]:
|
|
87
|
+
"""Discover every required skill through an ADP ``skills.tags`` filter."""
|
|
88
|
+
|
|
89
|
+
for tag in SKILL_TAGS:
|
|
90
|
+
if tag not in self._endpoints:
|
|
91
|
+
self._endpoints[tag] = self._discover(tag)
|
|
92
|
+
return dict(self._endpoints)
|
|
93
|
+
|
|
94
|
+
async def run(
|
|
95
|
+
self,
|
|
96
|
+
request: FunctionRequest,
|
|
97
|
+
*,
|
|
98
|
+
concept: IntuitionConcept = IntuitionConcept.AUTO,
|
|
99
|
+
on_trace: TraceCallback | None = None,
|
|
100
|
+
) -> VisualizationResult:
|
|
101
|
+
"""Run the dependency-aware workflow and aggregate all typed products."""
|
|
102
|
+
|
|
103
|
+
if self._started:
|
|
104
|
+
raise RuntimeError("one MathOrchestrator cannot be run twice")
|
|
105
|
+
if not self._clients:
|
|
106
|
+
raise RuntimeError("use 'async with MathOrchestrator(...)' before run")
|
|
107
|
+
self._started = True
|
|
108
|
+
self._on_trace = on_trace
|
|
109
|
+
started = time.perf_counter()
|
|
110
|
+
|
|
111
|
+
plot_result = await self._start(
|
|
112
|
+
PLOTTER_TAG,
|
|
113
|
+
MessageKind.PLOT_REQUEST,
|
|
114
|
+
request,
|
|
115
|
+
"Sample function and render PNG/CSV",
|
|
116
|
+
)
|
|
117
|
+
plot = self._product(plot_result, PlotProduct, PLOTTER_TAG)
|
|
118
|
+
|
|
119
|
+
transformation_result = await self._start(
|
|
120
|
+
TRANSFORMATION_TAG,
|
|
121
|
+
MessageKind.TRANSFORM_REQUEST,
|
|
122
|
+
TransformationRequest(plot=plot),
|
|
123
|
+
"Interpret parameters and build animation keyframes",
|
|
124
|
+
)
|
|
125
|
+
transformation = self._product(
|
|
126
|
+
transformation_result,
|
|
127
|
+
TransformationProduct,
|
|
128
|
+
TRANSFORMATION_TAG,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
animation_result = await self._continue(
|
|
132
|
+
PLOTTER_TAG,
|
|
133
|
+
task_id=plot.task_id,
|
|
134
|
+
kind=MessageKind.ANIMATION_REQUEST,
|
|
135
|
+
payload=AnimationRequest(
|
|
136
|
+
trig_function=transformation.trig_function,
|
|
137
|
+
frames=transformation.frames,
|
|
138
|
+
),
|
|
139
|
+
summary="Return transformation plan to the original Plotter task",
|
|
140
|
+
)
|
|
141
|
+
animation = self._product(animation_result, AnimationProduct, PLOTTER_TAG)
|
|
142
|
+
|
|
143
|
+
intuition_result = await self._start(
|
|
144
|
+
INTUITION_TAG,
|
|
145
|
+
MessageKind.INTUITION_REQUEST,
|
|
146
|
+
IntuitionRequest(
|
|
147
|
+
plot=plot,
|
|
148
|
+
transformation=transformation,
|
|
149
|
+
animation=animation,
|
|
150
|
+
concept=concept,
|
|
151
|
+
),
|
|
152
|
+
"Ground an everyday analogy in all upstream products",
|
|
153
|
+
)
|
|
154
|
+
intuition = self._product(intuition_result, IntuitionProduct, INTUITION_TAG)
|
|
155
|
+
|
|
156
|
+
return VisualizationResult(
|
|
157
|
+
session_id=self.session_id,
|
|
158
|
+
project_version=__version__,
|
|
159
|
+
sdk_version=version("acps-sdk"),
|
|
160
|
+
generated_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
161
|
+
request=request,
|
|
162
|
+
plot=plot,
|
|
163
|
+
transformation=transformation,
|
|
164
|
+
animation=animation,
|
|
165
|
+
intuition=intuition,
|
|
166
|
+
traces=self._traces,
|
|
167
|
+
total_ms=max(0, int((time.perf_counter() - started) * 1000)),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
async def _start(
|
|
171
|
+
self,
|
|
172
|
+
tag: str,
|
|
173
|
+
kind: MessageKind,
|
|
174
|
+
payload: BaseModel,
|
|
175
|
+
summary: str,
|
|
176
|
+
) -> TaskResult:
|
|
177
|
+
task_id = f"task-{tag}-{uuid4()}"
|
|
178
|
+
message = encode_message(
|
|
179
|
+
kind=kind,
|
|
180
|
+
session_id=self.session_id,
|
|
181
|
+
task_id=task_id,
|
|
182
|
+
payload=payload,
|
|
183
|
+
)
|
|
184
|
+
started = time.perf_counter()
|
|
185
|
+
result = await self._client(tag).start_task(
|
|
186
|
+
self.session_id,
|
|
187
|
+
message,
|
|
188
|
+
task_id=task_id,
|
|
189
|
+
)
|
|
190
|
+
self._record_trace(tag, result, "start", started, summary)
|
|
191
|
+
self._ensure_success(tag, result)
|
|
192
|
+
return result
|
|
193
|
+
|
|
194
|
+
async def _continue(
|
|
195
|
+
self,
|
|
196
|
+
tag: str,
|
|
197
|
+
*,
|
|
198
|
+
task_id: str,
|
|
199
|
+
kind: MessageKind,
|
|
200
|
+
payload: BaseModel,
|
|
201
|
+
summary: str,
|
|
202
|
+
) -> TaskResult:
|
|
203
|
+
message = encode_message(
|
|
204
|
+
kind=kind,
|
|
205
|
+
session_id=self.session_id,
|
|
206
|
+
task_id=task_id,
|
|
207
|
+
payload=payload,
|
|
208
|
+
)
|
|
209
|
+
started = time.perf_counter()
|
|
210
|
+
result = await self._client(tag).continue_task(task_id, self.session_id, message)
|
|
211
|
+
self._record_trace(tag, result, "continue", started, summary)
|
|
212
|
+
self._ensure_success(tag, result)
|
|
213
|
+
return result
|
|
214
|
+
|
|
215
|
+
def _product(
|
|
216
|
+
self,
|
|
217
|
+
result: TaskResult,
|
|
218
|
+
model_type: type[ModelT],
|
|
219
|
+
tag: str,
|
|
220
|
+
) -> ModelT:
|
|
221
|
+
endpoint = self._endpoints[tag]
|
|
222
|
+
try:
|
|
223
|
+
product = model_type.model_validate(product_payload(result))
|
|
224
|
+
meta = ProductMeta.model_validate(product.model_dump(mode="json"))
|
|
225
|
+
except (PayloadError, ValidationError) as exc:
|
|
226
|
+
raise RuntimeError(f"malformed product from {endpoint.name}: {exc}") from exc
|
|
227
|
+
if (
|
|
228
|
+
meta.session_id != self.session_id
|
|
229
|
+
or meta.task_id != result.taskId
|
|
230
|
+
or meta.agent != endpoint.name
|
|
231
|
+
):
|
|
232
|
+
raise RuntimeError(f"invalid product correlation or identity from {endpoint.name}")
|
|
233
|
+
return product
|
|
234
|
+
|
|
235
|
+
def _discover(self, tag: str) -> AgentEndpoint:
|
|
236
|
+
request = DiscoveryRequest(
|
|
237
|
+
type="filtered",
|
|
238
|
+
limit=5,
|
|
239
|
+
filter=build_filter("skills.tags", FilterOperator.ANY_OF, [tag]),
|
|
240
|
+
)
|
|
241
|
+
result = self._registry.discover(request)
|
|
242
|
+
for aic, acs, skill, _group in result.iter_agent_skills():
|
|
243
|
+
endpoints = acs.get("endPoints") or []
|
|
244
|
+
if endpoints and endpoints[0].get("url"):
|
|
245
|
+
return AgentEndpoint(
|
|
246
|
+
aic=aic,
|
|
247
|
+
name=str(acs.get("name", skill.skill_id)),
|
|
248
|
+
skill_id=skill.skill_id,
|
|
249
|
+
rpc_url=str(endpoints[0]["url"]),
|
|
250
|
+
)
|
|
251
|
+
raise LookupError(f"no ACPs agent advertises the tag '{tag}'")
|
|
252
|
+
|
|
253
|
+
async def _check_health(self) -> None:
|
|
254
|
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
|
255
|
+
responses = await asyncio.gather(
|
|
256
|
+
*(client.get(endpoint.health_url) for endpoint in self._endpoints.values())
|
|
257
|
+
)
|
|
258
|
+
for endpoint, response in zip(self._endpoints.values(), responses, strict=True):
|
|
259
|
+
if response.status_code != 200 or response.json().get("aic") != endpoint.aic:
|
|
260
|
+
raise RuntimeError(f"heartbeat failed for {endpoint.name}")
|
|
261
|
+
|
|
262
|
+
def _client(self, tag: str) -> AipRpcClient:
|
|
263
|
+
try:
|
|
264
|
+
return self._clients[tag]
|
|
265
|
+
except KeyError as exc:
|
|
266
|
+
raise RuntimeError("orchestrator clients are not started") from exc
|
|
267
|
+
|
|
268
|
+
def _record_trace(
|
|
269
|
+
self,
|
|
270
|
+
tag: str,
|
|
271
|
+
result: TaskResult,
|
|
272
|
+
operation: str,
|
|
273
|
+
started: float,
|
|
274
|
+
summary: str,
|
|
275
|
+
) -> None:
|
|
276
|
+
endpoint = self._endpoints[tag]
|
|
277
|
+
trace = AgentTrace(
|
|
278
|
+
agent=endpoint.name,
|
|
279
|
+
aic=endpoint.aic,
|
|
280
|
+
skill_id=endpoint.skill_id,
|
|
281
|
+
task_id=result.taskId,
|
|
282
|
+
operation=operation,
|
|
283
|
+
state=result.status.state.value,
|
|
284
|
+
elapsed_ms=max(0, int((time.perf_counter() - started) * 1000)),
|
|
285
|
+
summary=summary,
|
|
286
|
+
)
|
|
287
|
+
self._traces.append(trace)
|
|
288
|
+
if self._on_trace is not None:
|
|
289
|
+
self._on_trace(trace)
|
|
290
|
+
|
|
291
|
+
@staticmethod
|
|
292
|
+
def _ensure_success(tag: str, result: TaskResult) -> None:
|
|
293
|
+
if result.status.state not in {TaskState.Completed, TaskState.AwaitingInput}:
|
|
294
|
+
details = "; ".join(
|
|
295
|
+
item.text for item in result.status.dataItems or [] if getattr(item, "text", None)
|
|
296
|
+
)
|
|
297
|
+
raise RuntimeError(f"{tag} returned {result.status.state.value}: {details}")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
__all__ = ["AgentEndpoint", "MathOrchestrator"]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Validation and serialization layered on the SDK's AIP message types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from acps_sdk.aip import TaskCommand, TextDataItem
|
|
10
|
+
from pydantic import BaseModel, ValidationError
|
|
11
|
+
|
|
12
|
+
from .models import MessageKind, WireMessage
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ProtocolError(ValueError):
|
|
16
|
+
"""Raised when an AIP payload violates application correlation rules."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def encode_message(
|
|
20
|
+
*,
|
|
21
|
+
kind: MessageKind,
|
|
22
|
+
session_id: str,
|
|
23
|
+
task_id: str,
|
|
24
|
+
payload: BaseModel | Mapping[str, Any],
|
|
25
|
+
) -> str:
|
|
26
|
+
"""Encode a typed payload for ``AipRpcClient``."""
|
|
27
|
+
|
|
28
|
+
data = payload.model_dump(mode="json") if isinstance(payload, BaseModel) else dict(payload)
|
|
29
|
+
message = WireMessage(
|
|
30
|
+
kind=kind,
|
|
31
|
+
session_id=session_id,
|
|
32
|
+
task_id=task_id,
|
|
33
|
+
payload=data,
|
|
34
|
+
)
|
|
35
|
+
return message.model_dump_json()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def decode_message(command: TaskCommand, *, expected_task_id: str) -> WireMessage:
|
|
39
|
+
"""Decode a non-empty payload and verify task/session correlation."""
|
|
40
|
+
|
|
41
|
+
if not command.taskId or command.taskId != expected_task_id:
|
|
42
|
+
raise ProtocolError("AIP taskId is missing or does not match the active task")
|
|
43
|
+
if not command.sessionId:
|
|
44
|
+
raise ProtocolError("AIP sessionId is required")
|
|
45
|
+
text = next(
|
|
46
|
+
(
|
|
47
|
+
item.text
|
|
48
|
+
for item in command.dataItems or []
|
|
49
|
+
if isinstance(item, TextDataItem) and item.text.strip()
|
|
50
|
+
),
|
|
51
|
+
"",
|
|
52
|
+
)
|
|
53
|
+
if not text:
|
|
54
|
+
raise ProtocolError("AIP command requires one non-empty TextDataItem")
|
|
55
|
+
try:
|
|
56
|
+
message = WireMessage.model_validate(json.loads(text))
|
|
57
|
+
except (json.JSONDecodeError, ValidationError) as exc:
|
|
58
|
+
raise ProtocolError(f"invalid application message: {exc}") from exc
|
|
59
|
+
if message.task_id != command.taskId or message.session_id != command.sessionId:
|
|
60
|
+
raise ProtocolError("payload correlation does not match the AIP command")
|
|
61
|
+
return message
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
__all__ = ["ProtocolError", "decode_message", "encode_message"]
|
|
File without changes
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""ADP capability discovery backed by an in-process ACS registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Final
|
|
7
|
+
|
|
8
|
+
from acps_sdk.acs import AgentCapabilitySpec, AgentSkill
|
|
9
|
+
from acps_sdk.adp import (
|
|
10
|
+
DiscoveryAgentGroup,
|
|
11
|
+
DiscoveryAgentSkill,
|
|
12
|
+
DiscoveryFilter,
|
|
13
|
+
DiscoveryRequest,
|
|
14
|
+
DiscoveryResult,
|
|
15
|
+
FilterCondition,
|
|
16
|
+
FilterOperator,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
_GROUP: Final[str] = "mathematical-visualization"
|
|
20
|
+
_TOKEN_PATTERN: Final[re.Pattern[str]] = re.compile(r"[a-z0-9][a-z0-9\-]*")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AgentRegistry:
|
|
24
|
+
"""Publish ACS documents and resolve skills with SDK-native ADP requests."""
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
self._specs: dict[str, AgentCapabilitySpec] = {}
|
|
28
|
+
|
|
29
|
+
def publish(self, spec: AgentCapabilitySpec) -> None:
|
|
30
|
+
self._specs[spec.aic] = spec
|
|
31
|
+
|
|
32
|
+
def discover(self, request: DiscoveryRequest) -> DiscoveryResult:
|
|
33
|
+
tokens = set(_TOKEN_PATTERN.findall((request.query or "").lower()))
|
|
34
|
+
filters = list(request.filter.conditions or []) if request.filter else []
|
|
35
|
+
ranked: list[tuple[int, str, AgentCapabilitySpec, AgentSkill]] = []
|
|
36
|
+
for spec in self._specs.values():
|
|
37
|
+
if not spec.active or not _matches_filters(spec, filters):
|
|
38
|
+
continue
|
|
39
|
+
for skill in spec.skills:
|
|
40
|
+
score = _skill_score(skill, tokens)
|
|
41
|
+
if not tokens or score:
|
|
42
|
+
ranked.append((score, spec.name, spec, skill))
|
|
43
|
+
ranked.sort(key=lambda item: (-item[0], item[1]))
|
|
44
|
+
selected = ranked[: request.limit or 10]
|
|
45
|
+
acs_map: dict[str, dict[str, Any]] = {}
|
|
46
|
+
agent_skills: list[DiscoveryAgentSkill] = []
|
|
47
|
+
for ranking, (_score, _name, spec, skill) in enumerate(selected, start=1):
|
|
48
|
+
acs_map[spec.aic] = spec.to_dict()
|
|
49
|
+
agent_skills.append(
|
|
50
|
+
DiscoveryAgentSkill(aic=spec.aic, skill_id=skill.id, ranking=ranking)
|
|
51
|
+
)
|
|
52
|
+
return DiscoveryResult(
|
|
53
|
+
acs_map=acs_map,
|
|
54
|
+
agents=[DiscoveryAgentGroup(group=_GROUP, agent_skills=agent_skills)],
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_filter(field: str, op: FilterOperator, value: Any) -> DiscoveryFilter:
|
|
59
|
+
return DiscoveryFilter(conditions=[FilterCondition(field=field, op=op, value=value)])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _skill_score(skill: AgentSkill, tokens: set[str]) -> int:
|
|
63
|
+
haystack = " ".join([skill.id, skill.name, skill.description, *skill.tags]).lower()
|
|
64
|
+
return len(tokens & set(_TOKEN_PATTERN.findall(haystack)))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _matches_filters(spec: AgentCapabilitySpec, filters: list[FilterCondition]) -> bool:
|
|
68
|
+
for condition in filters:
|
|
69
|
+
if condition.field != "skills.tags":
|
|
70
|
+
return False
|
|
71
|
+
actual = [tag for skill in spec.skills for tag in skill.tags]
|
|
72
|
+
expected = condition.value
|
|
73
|
+
if condition.op == FilterOperator.ANY_OF:
|
|
74
|
+
if not isinstance(expected, list) or not any(item in expected for item in actual):
|
|
75
|
+
return False
|
|
76
|
+
elif condition.op == FilterOperator.EQ:
|
|
77
|
+
if expected not in actual:
|
|
78
|
+
return False
|
|
79
|
+
else:
|
|
80
|
+
return False
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
__all__ = ["AgentRegistry", "build_filter"]
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""AIP v2 JSON-RPC hosting and structured-product helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import socket
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
import uvicorn
|
|
13
|
+
from acps_sdk.aip import Product, StructuredDataItem, TaskResult, TaskState, TextDataItem
|
|
14
|
+
from acps_sdk.aip.aip_rpc_server import TaskManager, add_aip_rpc_router
|
|
15
|
+
from fastapi import FastAPI
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .agents.base import AipAgent
|
|
19
|
+
|
|
20
|
+
AIP_RPC_PATH = "/aip/v2/rpc"
|
|
21
|
+
TERMINAL_STATES = frozenset(
|
|
22
|
+
{TaskState.Completed, TaskState.Canceled, TaskState.Failed, TaskState.Rejected}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PayloadError(ValueError):
|
|
27
|
+
"""Raised when an AIP product does not match the expected shape."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def product_payload(result: TaskResult) -> dict[str, Any]:
|
|
31
|
+
"""Extract the newest structured product from an AIP task result."""
|
|
32
|
+
|
|
33
|
+
for product in reversed(result.products or []):
|
|
34
|
+
for item in product.dataItems or []:
|
|
35
|
+
if isinstance(item, StructuredDataItem):
|
|
36
|
+
return item.data
|
|
37
|
+
raise PayloadError(f"task {result.taskId} returned no structured product")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AgentServer:
|
|
41
|
+
"""Host one partner as an independent loopback AIP JSON-RPC service."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, agent: AipAgent) -> None:
|
|
44
|
+
self._agent = agent
|
|
45
|
+
self._server: uvicorn.Server | None = None
|
|
46
|
+
self._thread: threading.Thread | None = None
|
|
47
|
+
self._url: str | None = None
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def url(self) -> str:
|
|
51
|
+
if self._url is None:
|
|
52
|
+
raise RuntimeError("agent server has not been started")
|
|
53
|
+
return self._url
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def health_url(self) -> str:
|
|
57
|
+
return self.url.removesuffix(AIP_RPC_PATH) + "/healthz"
|
|
58
|
+
|
|
59
|
+
def start(self, timeout: float = 20.0) -> str:
|
|
60
|
+
if self._thread is not None:
|
|
61
|
+
return self.url
|
|
62
|
+
port = _free_port()
|
|
63
|
+
self._url = f"http://127.0.0.1:{port}{AIP_RPC_PATH}"
|
|
64
|
+
self._agent.attach_endpoint(self._url)
|
|
65
|
+
config = uvicorn.Config(
|
|
66
|
+
self._build_app(),
|
|
67
|
+
host="127.0.0.1",
|
|
68
|
+
port=port,
|
|
69
|
+
log_level="error",
|
|
70
|
+
access_log=False,
|
|
71
|
+
lifespan="off",
|
|
72
|
+
)
|
|
73
|
+
self._server = uvicorn.Server(config)
|
|
74
|
+
self._thread = threading.Thread(
|
|
75
|
+
target=self._server.run,
|
|
76
|
+
name=f"acps-math-{self._agent.skill_id}",
|
|
77
|
+
daemon=True,
|
|
78
|
+
)
|
|
79
|
+
self._thread.start()
|
|
80
|
+
self._wait_until_ready(timeout)
|
|
81
|
+
return self.url
|
|
82
|
+
|
|
83
|
+
def stop(self, timeout: float = 10.0) -> None:
|
|
84
|
+
if self._server is not None:
|
|
85
|
+
self._server.should_exit = True
|
|
86
|
+
if self._thread is not None:
|
|
87
|
+
self._thread.join(timeout)
|
|
88
|
+
self._server = None
|
|
89
|
+
self._thread = None
|
|
90
|
+
|
|
91
|
+
def _wait_until_ready(self, timeout: float) -> None:
|
|
92
|
+
deadline = time.monotonic() + timeout
|
|
93
|
+
while self._server is not None and not self._server.started:
|
|
94
|
+
if self._thread is not None and not self._thread.is_alive():
|
|
95
|
+
raise RuntimeError(f"agent {self._agent.name} failed to start")
|
|
96
|
+
if time.monotonic() > deadline:
|
|
97
|
+
raise TimeoutError(f"agent {self._agent.name} did not start in time")
|
|
98
|
+
time.sleep(0.02)
|
|
99
|
+
|
|
100
|
+
def _build_app(self) -> FastAPI:
|
|
101
|
+
app = FastAPI(
|
|
102
|
+
title=f"{self._agent.name} (ACPs agent)",
|
|
103
|
+
version=self._agent.capability_spec.version,
|
|
104
|
+
docs_url=None,
|
|
105
|
+
redoc_url=None,
|
|
106
|
+
openapi_url=None,
|
|
107
|
+
)
|
|
108
|
+
add_aip_rpc_router(app, AIP_RPC_PATH, self._agent.build_handlers())
|
|
109
|
+
|
|
110
|
+
@app.get("/healthz")
|
|
111
|
+
async def healthz() -> dict[str, Any]:
|
|
112
|
+
return {"status": "ok", "agent": self._agent.name, "aic": self._agent.aic}
|
|
113
|
+
|
|
114
|
+
@app.get("/acs")
|
|
115
|
+
async def acs() -> dict[str, Any]:
|
|
116
|
+
return self._agent.capability_spec.to_dict()
|
|
117
|
+
|
|
118
|
+
return app
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ResultBuilder:
|
|
122
|
+
"""Publish AIP status and a typed structured product."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, aic: str) -> None:
|
|
125
|
+
self._aic = aic
|
|
126
|
+
|
|
127
|
+
def publish(
|
|
128
|
+
self,
|
|
129
|
+
task: TaskResult,
|
|
130
|
+
state: TaskState,
|
|
131
|
+
payload: Mapping[str, Any],
|
|
132
|
+
*,
|
|
133
|
+
product_name: str,
|
|
134
|
+
summary: str,
|
|
135
|
+
) -> TaskResult:
|
|
136
|
+
result = TaskManager.update_task_status(
|
|
137
|
+
task.taskId,
|
|
138
|
+
state,
|
|
139
|
+
data_items=[TextDataItem(text=summary)],
|
|
140
|
+
)
|
|
141
|
+
result.senderId = self._aic
|
|
142
|
+
TaskManager.set_products(
|
|
143
|
+
task.taskId,
|
|
144
|
+
[
|
|
145
|
+
Product(
|
|
146
|
+
id=f"product-{uuid.uuid4()}",
|
|
147
|
+
name=product_name,
|
|
148
|
+
description=summary,
|
|
149
|
+
dataItems=[StructuredDataItem(data=dict(payload))],
|
|
150
|
+
)
|
|
151
|
+
],
|
|
152
|
+
)
|
|
153
|
+
return result
|
|
154
|
+
|
|
155
|
+
def fail(self, task: TaskResult, message: str) -> TaskResult:
|
|
156
|
+
result = TaskManager.update_task_status(
|
|
157
|
+
task.taskId,
|
|
158
|
+
TaskState.Failed,
|
|
159
|
+
data_items=[TextDataItem(text=message)],
|
|
160
|
+
)
|
|
161
|
+
result.senderId = self._aic
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _free_port() -> int:
|
|
166
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
167
|
+
sock.bind(("127.0.0.1", 0))
|
|
168
|
+
return int(sock.getsockname()[1])
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
__all__ = [
|
|
172
|
+
"AIP_RPC_PATH",
|
|
173
|
+
"AgentServer",
|
|
174
|
+
"PayloadError",
|
|
175
|
+
"ResultBuilder",
|
|
176
|
+
"TERMINAL_STATES",
|
|
177
|
+
"product_payload",
|
|
178
|
+
]
|