acps-math-multisolver 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_multisolver-1.0.0.dist-info/METADATA +187 -0
- acps_math_multisolver-1.0.0.dist-info/RECORD +24 -0
- acps_math_multisolver-1.0.0.dist-info/WHEEL +5 -0
- acps_math_multisolver-1.0.0.dist-info/entry_points.txt +2 -0
- acps_math_multisolver-1.0.0.dist-info/top_level.txt +1 -0
- math_multisolver/__init__.py +6 -0
- math_multisolver/__main__.py +6 -0
- math_multisolver/agents/__init__.py +8 -0
- math_multisolver/agents/algebra.py +40 -0
- math_multisolver/agents/base.py +118 -0
- math_multisolver/agents/geometry.py +40 -0
- math_multisolver/agents/socratic.py +40 -0
- math_multisolver/cli.py +52 -0
- math_multisolver/demo.py +98 -0
- math_multisolver/engine/__init__.py +17 -0
- math_multisolver/engine/quadratic.py +169 -0
- math_multisolver/identity.py +79 -0
- math_multisolver/mesh.py +61 -0
- math_multisolver/models.py +103 -0
- math_multisolver/orchestrator.py +205 -0
- math_multisolver/py.typed +0 -0
- math_multisolver/registry.py +85 -0
- math_multisolver/report.py +90 -0
- math_multisolver/runtime.py +229 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""ADP capability registry used by the local mathematics mesh."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from acps_sdk.acs import AgentCapabilitySpec, AgentSkill
|
|
8
|
+
from acps_sdk.adp import (
|
|
9
|
+
DiscoveryAgentGroup,
|
|
10
|
+
DiscoveryAgentSkill,
|
|
11
|
+
DiscoveryFilter,
|
|
12
|
+
DiscoveryRequest,
|
|
13
|
+
DiscoveryResult,
|
|
14
|
+
FilterCondition,
|
|
15
|
+
FilterOperator,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
GROUP = "math-multiple-solutions"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AgentRegistry:
|
|
22
|
+
"""Publish ACS documents and resolve skills through ADP requests."""
|
|
23
|
+
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
self._specs: dict[str, AgentCapabilitySpec] = {}
|
|
26
|
+
|
|
27
|
+
def publish(self, spec: AgentCapabilitySpec) -> None:
|
|
28
|
+
self._specs[spec.aic] = spec
|
|
29
|
+
|
|
30
|
+
def discover(self, request: DiscoveryRequest) -> DiscoveryResult:
|
|
31
|
+
conditions = list(request.filter.conditions or []) if request.filter else []
|
|
32
|
+
matches: list[tuple[AgentCapabilitySpec, AgentSkill]] = []
|
|
33
|
+
for spec in self._specs.values():
|
|
34
|
+
if not spec.active or not all(
|
|
35
|
+
_condition_matches(spec, condition) for condition in conditions
|
|
36
|
+
):
|
|
37
|
+
continue
|
|
38
|
+
matches.extend((spec, skill) for skill in spec.skills)
|
|
39
|
+
|
|
40
|
+
selected = matches[: request.limit or 10]
|
|
41
|
+
acs_map: dict[str, dict[str, Any]] = {}
|
|
42
|
+
agent_skills: list[DiscoveryAgentSkill] = []
|
|
43
|
+
for ranking, (spec, skill) in enumerate(selected, start=1):
|
|
44
|
+
acs_map[spec.aic] = spec.to_dict()
|
|
45
|
+
agent_skills.append(
|
|
46
|
+
DiscoveryAgentSkill(aic=spec.aic, skill_id=skill.id, ranking=ranking)
|
|
47
|
+
)
|
|
48
|
+
return DiscoveryResult(
|
|
49
|
+
acs_map=acs_map,
|
|
50
|
+
agents=[DiscoveryAgentGroup(group=GROUP, agent_skills=agent_skills)],
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _condition_matches(spec: AgentCapabilitySpec, condition: FilterCondition) -> bool:
|
|
55
|
+
actual = _resolve_field(spec, condition.field)
|
|
56
|
+
expected = condition.value
|
|
57
|
+
if condition.op == FilterOperator.ANY_OF:
|
|
58
|
+
values = actual if isinstance(actual, list) else [actual]
|
|
59
|
+
return isinstance(expected, list) and any(item in expected for item in values)
|
|
60
|
+
if condition.op == FilterOperator.EQ:
|
|
61
|
+
return actual == expected
|
|
62
|
+
if condition.op == FilterOperator.EXISTS:
|
|
63
|
+
return bool(actual) is bool(expected)
|
|
64
|
+
raise ValueError(f"unsupported local ADP filter operator: {condition.op}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _resolve_field(spec: AgentCapabilitySpec, field: str) -> Any:
|
|
68
|
+
if field == "active":
|
|
69
|
+
return spec.active
|
|
70
|
+
if field == "skills.tags":
|
|
71
|
+
return [tag for skill in spec.skills for tag in skill.tags]
|
|
72
|
+
if field == "skills.id":
|
|
73
|
+
return [skill.id for skill in spec.skills]
|
|
74
|
+
if field == "provider.organization":
|
|
75
|
+
return spec.provider.organization
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def build_filter(field: str, op: FilterOperator, value: Any) -> DiscoveryFilter:
|
|
80
|
+
return DiscoveryFilter(
|
|
81
|
+
conditions=[FilterCondition(field=field, op=op, value=value)]
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
__all__ = ["AgentRegistry", "build_filter"]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Render solutions, Socratic dialogue and ACP audit evidence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .models import MultiSolveReport, SolutionPath
|
|
6
|
+
|
|
7
|
+
_BAR = "=" * 88
|
|
8
|
+
_LINE = "-" * 88
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def render_report(report: MultiSolveReport, *, show_socratic: bool = True) -> str:
|
|
12
|
+
"""Create a terminal-friendly report without hiding protocol evidence."""
|
|
13
|
+
|
|
14
|
+
lines = [
|
|
15
|
+
_BAR,
|
|
16
|
+
f"ACPs Math MultiSolver v{report.project_version} | session={report.session_id}",
|
|
17
|
+
f"SDK=acps-sdk {report.sdk_version} | 端到端耗时 {report.total_ms} ms "
|
|
18
|
+
f"| report={report.report_id}",
|
|
19
|
+
_BAR,
|
|
20
|
+
"[User] 二次函数压轴题:",
|
|
21
|
+
report.problem,
|
|
22
|
+
"",
|
|
23
|
+
]
|
|
24
|
+
_append_solution(lines, 1, report.algebra)
|
|
25
|
+
_append_solution(lines, 2, report.geometry)
|
|
26
|
+
|
|
27
|
+
if show_socratic:
|
|
28
|
+
lines.extend(
|
|
29
|
+
[
|
|
30
|
+
"[3/4] Socratic Agent · 连续追问启发",
|
|
31
|
+
_LINE,
|
|
32
|
+
"策略:" + report.socratic.strategy,
|
|
33
|
+
"已消费的双路径要点:",
|
|
34
|
+
]
|
|
35
|
+
)
|
|
36
|
+
lines.extend(f" · {idea}" for idea in report.socratic.source_paths)
|
|
37
|
+
if report.dialogue:
|
|
38
|
+
for exchange in report.dialogue:
|
|
39
|
+
lines.extend(
|
|
40
|
+
[
|
|
41
|
+
"",
|
|
42
|
+
f"导师 {exchange.number}:{exchange.question}",
|
|
43
|
+
f"学生 {exchange.number}:{exchange.learner_response}",
|
|
44
|
+
f"反馈 {exchange.number}:{exchange.tutor_reply}",
|
|
45
|
+
]
|
|
46
|
+
)
|
|
47
|
+
else:
|
|
48
|
+
for turn in report.socratic.turns:
|
|
49
|
+
lines.extend(
|
|
50
|
+
[
|
|
51
|
+
"",
|
|
52
|
+
f"第 {turn.number} 问({turn.focus}):{turn.question}",
|
|
53
|
+
f" 按需支架:{turn.scaffold}",
|
|
54
|
+
]
|
|
55
|
+
)
|
|
56
|
+
lines.extend(["", "双路径反思:" + report.socratic.reflection, ""])
|
|
57
|
+
|
|
58
|
+
lines.extend(["[4/4] AIP v2 协作审计", _LINE])
|
|
59
|
+
for trace in report.traces:
|
|
60
|
+
lines.append(
|
|
61
|
+
f"{trace.agent} | {trace.skill_id} | {trace.state} | "
|
|
62
|
+
f"{trace.elapsed_ms} ms | task={trace.task_id}"
|
|
63
|
+
)
|
|
64
|
+
lines.extend(
|
|
65
|
+
[
|
|
66
|
+
"调度拓扑:(Algebra Agent ∥ Geometry Agent) → Socratic Agent → Leader",
|
|
67
|
+
"通信证据:ADP 按 skills.tags 发现端点;AIP start_task 分发;"
|
|
68
|
+
"StructuredDataItem 回传 typed product。",
|
|
69
|
+
"在线 Agent:" + "、".join(report.agents_online),
|
|
70
|
+
]
|
|
71
|
+
)
|
|
72
|
+
return "\n".join(lines)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _append_solution(lines: list[str], index: int, solution: SolutionPath) -> None:
|
|
76
|
+
lines.extend(
|
|
77
|
+
[
|
|
78
|
+
f"[{index}/4] {solution.agent} · {solution.title}",
|
|
79
|
+
_LINE,
|
|
80
|
+
"核心洞察:" + solution.key_idea,
|
|
81
|
+
]
|
|
82
|
+
)
|
|
83
|
+
lines.extend(
|
|
84
|
+
f" {step_number}. {step}"
|
|
85
|
+
for step_number, step in enumerate(solution.steps, start=1)
|
|
86
|
+
)
|
|
87
|
+
lines.extend(["结论:" + solution.answer, "交叉验证:" + solution.verification, ""])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
__all__ = ["render_report"]
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""AIP v2 transport, task lifecycle and structured-product helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import socket
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
import uvicorn
|
|
14
|
+
from acps_sdk.aip import (
|
|
15
|
+
Product,
|
|
16
|
+
StructuredDataItem,
|
|
17
|
+
TaskCommand,
|
|
18
|
+
TaskResult,
|
|
19
|
+
TaskState,
|
|
20
|
+
TextDataItem,
|
|
21
|
+
)
|
|
22
|
+
from acps_sdk.aip.aip_rpc_server import TaskManager, add_aip_rpc_router
|
|
23
|
+
from fastapi import FastAPI
|
|
24
|
+
from pydantic import BaseModel
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from .agents.base import AipAgent
|
|
28
|
+
|
|
29
|
+
AIP_RPC_PATH = "/aip/v2/rpc"
|
|
30
|
+
TERMINAL_STATES = frozenset(
|
|
31
|
+
{
|
|
32
|
+
TaskState.Completed,
|
|
33
|
+
TaskState.Canceled,
|
|
34
|
+
TaskState.Failed,
|
|
35
|
+
TaskState.Rejected,
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PayloadError(ValueError):
|
|
41
|
+
"""Raised when an AIP payload or product has an unexpected shape."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def encode_payload(payload: BaseModel | Mapping[str, Any]) -> str:
|
|
45
|
+
"""Serialize a typed request into an AIP text payload."""
|
|
46
|
+
|
|
47
|
+
if isinstance(payload, BaseModel):
|
|
48
|
+
return payload.model_dump_json()
|
|
49
|
+
return json.dumps(payload, ensure_ascii=False)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def decode_payload(text: str) -> dict[str, Any]:
|
|
53
|
+
"""Decode a JSON object payload."""
|
|
54
|
+
|
|
55
|
+
if not text.strip():
|
|
56
|
+
raise PayloadError("empty AIP payload")
|
|
57
|
+
try:
|
|
58
|
+
data = json.loads(text)
|
|
59
|
+
except json.JSONDecodeError as exc:
|
|
60
|
+
raise PayloadError(f"payload is not valid JSON: {exc}") from exc
|
|
61
|
+
if not isinstance(data, dict):
|
|
62
|
+
raise PayloadError("payload must be a JSON object")
|
|
63
|
+
return data
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def first_text(command: TaskCommand) -> str:
|
|
67
|
+
"""Return the first text data item from a start command."""
|
|
68
|
+
|
|
69
|
+
for item in command.dataItems or []:
|
|
70
|
+
if isinstance(item, TextDataItem) and item.text:
|
|
71
|
+
return item.text
|
|
72
|
+
return ""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def product_payload(result: TaskResult) -> dict[str, Any]:
|
|
76
|
+
"""Extract the latest structured product from a completed task."""
|
|
77
|
+
|
|
78
|
+
for product in reversed(result.products or []):
|
|
79
|
+
for item in product.dataItems or []:
|
|
80
|
+
if isinstance(item, StructuredDataItem):
|
|
81
|
+
return item.data
|
|
82
|
+
raise PayloadError(
|
|
83
|
+
f"task {result.taskId} finished in state {result.status.state.value} "
|
|
84
|
+
"without structured products"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class AgentServer:
|
|
89
|
+
"""Host one specialist as an independent loopback AIP JSON-RPC service."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, agent: AipAgent) -> None:
|
|
92
|
+
self._agent = agent
|
|
93
|
+
self._server: uvicorn.Server | None = None
|
|
94
|
+
self._thread: threading.Thread | None = None
|
|
95
|
+
self._url: str | None = None
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def url(self) -> str:
|
|
99
|
+
if self._url is None:
|
|
100
|
+
raise RuntimeError("Agent server has not been started yet")
|
|
101
|
+
return self._url
|
|
102
|
+
|
|
103
|
+
def start(self, timeout: float = 20.0) -> str:
|
|
104
|
+
if self._thread is not None:
|
|
105
|
+
return self.url
|
|
106
|
+
port = _free_port()
|
|
107
|
+
self._url = f"http://127.0.0.1:{port}{AIP_RPC_PATH}"
|
|
108
|
+
self._agent.attach_endpoint(self._url)
|
|
109
|
+
config = uvicorn.Config(
|
|
110
|
+
self._build_app(),
|
|
111
|
+
host="127.0.0.1",
|
|
112
|
+
port=port,
|
|
113
|
+
log_level="error",
|
|
114
|
+
access_log=False,
|
|
115
|
+
lifespan="off",
|
|
116
|
+
)
|
|
117
|
+
self._server = uvicorn.Server(config)
|
|
118
|
+
self._thread = threading.Thread(
|
|
119
|
+
target=self._server.run,
|
|
120
|
+
name=f"acps-agent-{self._agent.skill_id}",
|
|
121
|
+
daemon=True,
|
|
122
|
+
)
|
|
123
|
+
self._thread.start()
|
|
124
|
+
self._wait_until_ready(timeout)
|
|
125
|
+
return self.url
|
|
126
|
+
|
|
127
|
+
def stop(self, timeout: float = 10.0) -> None:
|
|
128
|
+
if self._server is not None:
|
|
129
|
+
self._server.should_exit = True
|
|
130
|
+
if self._thread is not None:
|
|
131
|
+
self._thread.join(timeout)
|
|
132
|
+
self._server = None
|
|
133
|
+
self._thread = None
|
|
134
|
+
|
|
135
|
+
def _wait_until_ready(self, timeout: float) -> None:
|
|
136
|
+
deadline = time.monotonic() + timeout
|
|
137
|
+
while self._server is not None and not self._server.started:
|
|
138
|
+
if self._thread is not None and not self._thread.is_alive():
|
|
139
|
+
raise RuntimeError(f"agent {self._agent.name} failed to start")
|
|
140
|
+
if time.monotonic() > deadline:
|
|
141
|
+
raise TimeoutError(f"agent {self._agent.name} did not start in time")
|
|
142
|
+
time.sleep(0.02)
|
|
143
|
+
|
|
144
|
+
def _build_app(self) -> FastAPI:
|
|
145
|
+
app = FastAPI(
|
|
146
|
+
title=f"{self._agent.name} (ACPs agent)",
|
|
147
|
+
version=self._agent.capability_spec.version,
|
|
148
|
+
docs_url=None,
|
|
149
|
+
redoc_url=None,
|
|
150
|
+
openapi_url=None,
|
|
151
|
+
)
|
|
152
|
+
add_aip_rpc_router(app, AIP_RPC_PATH, self._agent.build_handlers())
|
|
153
|
+
|
|
154
|
+
@app.get("/healthz")
|
|
155
|
+
async def healthz() -> dict[str, str]:
|
|
156
|
+
return {
|
|
157
|
+
"status": "ok",
|
|
158
|
+
"agent": self._agent.name,
|
|
159
|
+
"aic": self._agent.aic,
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
@app.get("/acs")
|
|
163
|
+
async def acs() -> dict[str, Any]:
|
|
164
|
+
return self._agent.capability_spec.to_dict()
|
|
165
|
+
|
|
166
|
+
return app
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class ResultBuilder:
|
|
170
|
+
"""Publish AIP status and a structured product together."""
|
|
171
|
+
|
|
172
|
+
def __init__(self, aic: str) -> None:
|
|
173
|
+
self._aic = aic
|
|
174
|
+
|
|
175
|
+
def publish(
|
|
176
|
+
self,
|
|
177
|
+
task: TaskResult,
|
|
178
|
+
state: TaskState,
|
|
179
|
+
payload: Mapping[str, Any],
|
|
180
|
+
*,
|
|
181
|
+
product_name: str,
|
|
182
|
+
summary: str,
|
|
183
|
+
) -> TaskResult:
|
|
184
|
+
result = TaskManager.update_task_status(
|
|
185
|
+
task.taskId,
|
|
186
|
+
state,
|
|
187
|
+
data_items=[TextDataItem(text=summary)],
|
|
188
|
+
)
|
|
189
|
+
result.senderId = self._aic
|
|
190
|
+
TaskManager.set_products(
|
|
191
|
+
task.taskId,
|
|
192
|
+
[
|
|
193
|
+
Product(
|
|
194
|
+
id=f"product-{uuid.uuid4()}",
|
|
195
|
+
name=product_name,
|
|
196
|
+
description=summary,
|
|
197
|
+
dataItems=[StructuredDataItem(data=dict(payload))],
|
|
198
|
+
)
|
|
199
|
+
],
|
|
200
|
+
)
|
|
201
|
+
return result
|
|
202
|
+
|
|
203
|
+
def fail(self, task: TaskResult, message: str) -> TaskResult:
|
|
204
|
+
result = TaskManager.update_task_status(
|
|
205
|
+
task.taskId,
|
|
206
|
+
TaskState.Failed,
|
|
207
|
+
data_items=[TextDataItem(text=message)],
|
|
208
|
+
)
|
|
209
|
+
result.senderId = self._aic
|
|
210
|
+
return result
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _free_port() -> int:
|
|
214
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
215
|
+
sock.bind(("127.0.0.1", 0))
|
|
216
|
+
return int(sock.getsockname()[1])
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
__all__ = [
|
|
220
|
+
"AIP_RPC_PATH",
|
|
221
|
+
"AgentServer",
|
|
222
|
+
"PayloadError",
|
|
223
|
+
"ResultBuilder",
|
|
224
|
+
"TERMINAL_STATES",
|
|
225
|
+
"decode_payload",
|
|
226
|
+
"encode_payload",
|
|
227
|
+
"first_text",
|
|
228
|
+
"product_payload",
|
|
229
|
+
]
|