Coverage for app / services / ai_client.py: 66%

1385 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2HTTP client for delegating LLM calls to svc-ai. 

3 

4svc-core no longer calls LLM providers directly and no longer manages a local 

5models table. All model metadata is sourced from svc-ai, and all invocations 

6are forwarded there. 

7""" 

8 

9import asyncio 

10import contextvars 

11import json 

12import logging 

13import threading 

14import time 

15from contextlib import contextmanager 

16from dataclasses import dataclass, field 

17from datetime import date 

18from decimal import Decimal 

19from typing import TYPE_CHECKING, Any, Awaitable, Callable, Iterator 

20from uuid import UUID 

21 

22import anyio.from_thread 

23import httpx 

24 

25from app.common.settings import get_settings 

26from app.common.internal_auth import mint_internal_token 

27from app.services import quality_check 

28from app.util import knowledge_report as knowledge_wire 

29from app.util import web_domains, web_search_report 

30 

31if TYPE_CHECKING: 

32 from app.services.turns import RunningTurn 

33 

34logger = logging.getLogger(__name__) 

35 

36 

37def _internal_headers(sub: str = "system") -> dict: 

38 """ 

39 Build the headers for an outbound svc-ai call. 

40 

41 When internal auth is configured this carries a short-lived, audience-bound 

42 token so svc-ai can verify the caller is svc-core. And it names the 

43 workspace the work is done in (``WORKSPACE_HEADER``), which svc-ai stamps 

44 on its trace rows so a workspace's usage figures are its own, the 

45 turn it is part of (``INVOCATION_HEADER``), so the decision record can 

46 find the calls behind one answer, the most the turn may spend 

47 (``SPEND_LIMIT_HEADER``), where svc-ai stops it, and the web sources it 

48 may use (``WEB_POLICY_HEADER``), which svc-ai's web tools hold to. 

49 """ 

50 token = mint_internal_token(sub=sub) 

51 headers = {"X-Internal-Token": token} if token else {} 

52 workspace = current_workspace() 

53 if workspace: 

54 headers[WORKSPACE_HEADER] = workspace 

55 invocation = current_invocation() 

56 if invocation: 

57 headers[INVOCATION_HEADER] = invocation 

58 limit = current_spend_limit() 

59 if limit is not None: 

60 headers[SPEND_LIMIT_HEADER] = str(limit.usd) 

61 web = current_web_policy() 

62 if web is not None and web.restricts: 

63 headers[WEB_POLICY_HEADER] = web.encode() 

64 return headers 

65 

66 

67# ── The workspace work is done in ──────────────────────────────────────────── 

68# 

69# svc-ai stamps it on every trace row (``llm_invocations.workspace``, 

70# ``tool_invocations.workspace``), so the usage figures a workspace's pages 

71# read from svc-ai — the Overview cards, the Usage & spend tiles, Activity's 

72# invocation feed — count the work done there and not a person's others. 

73# A request names it (``app/dependency/workspace.py``); work with no request 

74# behind it — a scheduled refresh, a background run, a chat socket that 

75# names its workspace in a frame — says so with ``in_workspace``. 

76 

77WORKSPACE_HEADER = "X-Workspace" 

78 

79_WORKSPACE: contextvars.ContextVar[str | None] = contextvars.ContextVar( 

80 "svc_ai_workspace", default=None 

81) 

82 

83 

84def current_workspace() -> str | None: 

85 """The workspace key svc-ai is told about: the one set with 

86 :func:`in_workspace` / :func:`use_workspace`, else the request's. 

87 ``personal`` is resolved by svc-ai to the row's own user.""" 

88 explicit = _WORKSPACE.get() 

89 if explicit: 

90 return explicit 

91 from app.dependency.workspace import requested_workspace 

92 

93 return requested_workspace() 

94 

95 

96@contextmanager 

97def in_workspace(key: str | None) -> Iterator[None]: 

98 """Name the workspace of the svc-ai calls made inside the block.""" 

99 token = _WORKSPACE.set(key or None) 

100 try: 

101 yield 

102 finally: 

103 _WORKSPACE.reset(token) 

104 

105 

106def use_workspace(key: str | None) -> contextvars.Token: 

107 """Name the workspace for the rest of the current task or thread — for 

108 a handler whose work spans a long block (a chat socket's turn). The 

109 token resets it, for a caller that shares its thread.""" 

110 return _WORKSPACE.set(key or None) 

111 

112 

113def reset_workspace(token: contextvars.Token) -> None: 

114 _WORKSPACE.reset(token) 

115 

116 

117# ── The invocation work is part of ─────────────────────────────────────────── 

118# 

119# One id per governed turn — an answer, a skill run, an evaluation cell 

120# (``rule_engine.new_invocation_id``). The ledger, the review queue, the 

121# governance activity log and the turn's messages carry it, and svc-ai stamps 

122# it on its trace rows (``core_invocation_id``), so the decision record for an 

123# answer is every row that names it. Set around a turn's svc-ai calls; the 

124# rows svc-core writes take it as an argument, because most are written in a 

125# worker thread (``run_in_executor``) that does not inherit contextvars. 

126 

127INVOCATION_HEADER = "X-Invocation-Id" 

128 

129_INVOCATION: contextvars.ContextVar[str | None] = contextvars.ContextVar( 

130 "svc_ai_invocation", default=None 

131) 

132 

133 

134def current_invocation() -> str | None: 

135 """The invocation svc-ai is told its calls are part of, if any.""" 

136 return _INVOCATION.get() 

137 

138 

139@contextmanager 

140def in_invocation(invocation_id: str | UUID | None) -> Iterator[None]: 

141 """Name the invocation of the svc-ai calls made inside the block.""" 

142 token = _INVOCATION.set(str(invocation_id) if invocation_id else None) 

143 try: 

144 yield 

145 finally: 

146 _INVOCATION.reset(token) 

147 

148 

149def use_invocation(invocation_id: str | UUID | None) -> contextvars.Token: 

150 """Name the invocation for the rest of the current task or thread — for 

151 a handler whose turn spans a long block (a chat socket's). The token 

152 resets it, for a caller that shares its thread.""" 

153 return _INVOCATION.set(str(invocation_id) if invocation_id else None) 

154 

155 

156def reset_invocation(token: contextvars.Token) -> None: 

157 _INVOCATION.reset(token) 

158 

159 

160# ── What a stream ends with ────────────────────────────────────────────────── 

161# 

162# svc-ai's terminal frame (``done``, or ``error``) carries more than the chat 

163# keeps: every passage retrieved (``citations``, where the answer's own are 

164# ``cited_citations``), the skill's state and outputs. A scenario run 

165# (``app/services/scenarios``) wants all of it, so ``tap_stream`` hands each 

166# terminal frame of the streams started inside the block to a callback, 

167# before the chat reads it. Without a tap the stream is as it was. 

168 

169_STREAM_TAP: contextvars.ContextVar[Callable[[dict], None] | None] = ( 

170 contextvars.ContextVar("svc_ai_stream_tap", default=None) 

171) 

172 

173 

174@contextmanager 

175def tap_stream(callback: Callable[[dict], None]) -> Iterator[None]: 

176 """Hand ``callback`` the terminal frame of each svc-ai stream started in 

177 the block (or in tasks it starts).""" 

178 token = _STREAM_TAP.set(callback) 

179 try: 

180 yield 

181 finally: 

182 _STREAM_TAP.reset(token) 

183 

184 

185def _tap(frame: dict) -> None: 

186 tap = _STREAM_TAP.get() 

187 if tap is None: 

188 return 

189 try: 

190 tap(frame) 

191 except Exception: # noqa: BLE001 — a tap never costs the turn 

192 logger.warning("A stream tap failed on a %s frame", frame.get("type")) 

193 

194 

195# ── The most a turn may spend ──────────────────────────────────────────────── 

196# 

197# A cost cap that lets a turn start has an amount left, and so does the 

198# platform allowance; the rule engine hands back the tightest 

199# (``RulePass.spend_limit``, a ``rule_engine.SpendLimit``). Set around the 

200# turn's svc-ai calls, it travels as ``X-Spend-Limit`` and svc-ai refuses the 

201# turn's next model call once it has spent that (svc-ai 

202# ``app/common/spend_limit.py``). The refusal comes back as 

203# ``SpendLimitReached``, whose message names the budget — which svc-ai never 

204# knew. Kept duck-typed (``.usd``, ``.stop_message()``): this module must not 

205# import the rule engine. 

206 

207SPEND_LIMIT_HEADER = "X-Spend-Limit" 

208 

209_SPEND_LIMIT: contextvars.ContextVar[Any | None] = contextvars.ContextVar( 

210 "svc_ai_spend_limit", default=None 

211) 

212 

213 

214def current_spend_limit() -> Any | None: 

215 """The limit svc-ai is told the current turn's calls share, if any.""" 

216 return _SPEND_LIMIT.get() 

217 

218 

219@contextmanager 

220def in_spend_limit(limit: Any | None) -> Iterator[None]: 

221 """Limit what the svc-ai calls made inside the block may spend.""" 

222 token = _SPEND_LIMIT.set(limit) 

223 try: 

224 yield 

225 finally: 

226 _SPEND_LIMIT.reset(token) 

227 

228 

229def use_spend_limit(limit: Any | None) -> contextvars.Token: 

230 """Set the limit for the rest of the current task or thread — for a 

231 handler whose turn spans a long block (a chat socket's). The token 

232 resets it, for a caller that shares its thread.""" 

233 return _SPEND_LIMIT.set(limit) 

234 

235 

236def reset_spend_limit(token: contextvars.Token) -> None: 

237 _SPEND_LIMIT.reset(token) 

238 

239 

240# ── The web sources a turn may use ─────────────────────────────────────────── 

241# 

242# A workspace's Tools rules name sources to put first, the only ones to use, 

243# or ones never to use; the rule engine merges them into one policy 

244# (``RulePass.web_policy``, ``app/util/web_domains.py``). Set around the 

245# turn's svc-ai calls, it travels as ``X-Web-Policy`` and every web tool 

246# svc-ai runs for the turn holds to it — whichever node, worker or tool node 

247# reached the web (svc-ai ``app/common/web_policy.py``). 

248 

249WEB_POLICY_HEADER = "X-Web-Policy" 

250 

251_WEB_POLICY: contextvars.ContextVar[web_domains.WebPolicy | None] = ( 

252 contextvars.ContextVar("svc_ai_web_policy", default=None) 

253) 

254 

255 

256def current_web_policy() -> web_domains.WebPolicy | None: 

257 """The web sources svc-ai is told the current turn may use, if any rule 

258 set them.""" 

259 return _WEB_POLICY.get() 

260 

261 

262@contextmanager 

263def in_web_policy(policy: web_domains.WebPolicy | None) -> Iterator[None]: 

264 """Hold the svc-ai calls made inside the block to ``policy``.""" 

265 token = _WEB_POLICY.set(policy) 

266 try: 

267 yield 

268 finally: 

269 _WEB_POLICY.reset(token) 

270 

271 

272# ── A turn's governance, as its svc-ai calls carry it ──────────────────────── 

273# 

274# What a turn's rules hand svc-ai beside the prompt: the most it may spend 

275# and the web sources it may use. One helper sets both, so a path that 

276# governs a turn cannot pass one on and forget the other 

277# (``tests/test_turn_spend_limit.py`` holds every caller of 

278# ``rule_engine.evaluate_input`` to it). 

279 

280 

281@dataclass(frozen=True) 

282class TurnGovernance: 

283 """A turn's spend limit and web policy, for a later part of the turn — a 

284 resume after a pause — whose figures are worked out rather than read off 

285 one rule pass. Duck-typed like :class:`rule_engine.RulePass`.""" 

286 

287 spend_limit: Any | None = None 

288 web_policy: web_domains.WebPolicy | None = None 

289 

290 

291@contextmanager 

292def in_turn_governance(rules: Any | None) -> Iterator[None]: 

293 """Govern the svc-ai calls made inside the block as ``rules`` (a 

294 ``RulePass`` or :class:`TurnGovernance`) say: its spend limit and web 

295 policy. None governs nothing.""" 

296 with ( 

297 in_spend_limit(getattr(rules, "spend_limit", None)), 

298 in_web_policy(getattr(rules, "web_policy", None)), 

299 ): 

300 yield 

301 

302 

303def use_turn_governance(rules: Any | None) -> None: 

304 """Govern the rest of the current task's svc-ai calls as ``rules`` say — 

305 for a handler whose turn spans a long block (a chat socket's).""" 

306 _SPEND_LIMIT.set(getattr(rules, "spend_limit", None)) 

307 _WEB_POLICY.set(getattr(rules, "web_policy", None)) 

308 

309 

310# ── Measured usage ─────────────────────────────────────────────────────────── 

311# 

312# svc-ai meters every model call it makes while serving a request — each call 

313# priced on the model that actually answered it — and reports the total on 

314# the ``X-LLM-Usage`` header (non-streaming) or the terminal ``done`` / 

315# ``hitl_interrupt`` frame (streaming). See svc-ai ``app/services/metering.py``. 

316# 

317# A caller that ledgers spend opens ``usage_capture()`` around its svc-ai 

318# calls; every call below that reaches a model feeds it through ``_capture``. 

319# The ledger then records what svc-ai measured, instead of estimating from the 

320# one model the request named — which was wrong for every multi-model run and 

321# blank for every run that paused. ``docs/guides/cost-monitoring.md``. 

322 

323USAGE_HEADER = "X-LLM-Usage" 

324 

325 

326@dataclass 

327class UsageCapture: 

328 """What svc-ai measured across the calls made inside one capture.""" 

329 

330 calls: int = 0 

331 input_tokens: int = 0 

332 output_tokens: int = 0 

333 #: None until something priced is recorded — never zero for "unknown". 

334 cost_usd: Decimal | None = None 

335 #: Calls svc-ai could not price (a model in neither price table). 

336 unpriced_calls: int = 0 

337 #: What those calls are taken to have cost when a limit is judged: their 

338 #: tokens at the catalogue's dearest rates (svc-ai's ``ceiling_estimate``). 

339 #: Never part of ``cost_usd``, which stays what was measured. 

340 unpriced_estimate_usd: Decimal | None = None 

341 by_model: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict) 

342 #: The model that wrote the answer when svc-ai says it was not the 

343 #: agent's own (``{"provider", "model", "reason"}``: an Economy profile's 

344 #: lighter model, for a request triage called simple), else None. 

345 answered_by: dict[str, Any] | None = None 

346 #: Every web search the turn made, as its report 

347 #: (``app/util/web_search_report.py``), in order: read from the raw 

348 #: stream before any frame is held back, and from a batch response's 

349 #: context. What the turn's summary and the settling of its Tools rules 

350 #: read (``services/web_search_summary.py``). 

351 web_searches: list[web_search_report.SearchReport] = field(default_factory=list) 

352 #: What the turn asked of its agent's knowledge and what each source 

353 #: gave (``app/util/knowledge_report.py``): from the stream's ``done`` 

354 #: frame or a batch response's context; None for an agent with none. 

355 #: What the retrieval record keeps (``services/knowledge/retrievals.py``). 

356 knowledge_report: knowledge_wire.KnowledgeReport | None = None 

357 _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) 

358 

359 @property 

360 def measured(self) -> bool: 

361 return self.calls > 0 

362 

363 def enforcement_usd(self) -> Decimal: 

364 """What a spending limit counts these calls as: the measured cost, 

365 plus the high estimate for any call that could not be priced — so an 

366 unpriced model cannot spend round a cap. Zero when nothing was made.""" 

367 with self._lock: 

368 return (self.cost_usd or Decimal(0)) + ( 

369 self.unpriced_estimate_usd or Decimal(0) 

370 ) 

371 

372 def as_summary(self) -> dict[str, Any]: 

373 """This capture in svc-ai's usage-summary shape — what ``add`` folds 

374 in, so one capture can be added to another.""" 

375 return { 

376 "calls": self.calls, 

377 "prompt_tokens": self.input_tokens, 

378 "completion_tokens": self.output_tokens, 

379 "unpriced_calls": self.unpriced_calls, 

380 "unpriced_estimate_usd": self.unpriced_estimate_usd, 

381 "estimated_cost_usd": self.cost_usd, 

382 "by_model": [ 

383 { 

384 "provider": r["provider"], 

385 "model": r["model"], 

386 "calls": r["calls"], 

387 "prompt_tokens": r["input_tokens"], 

388 "completion_tokens": r["output_tokens"], 

389 "unpriced_calls": r["unpriced_calls"], 

390 "estimated_cost_usd": r["cost_usd"], 

391 } 

392 for r in self.by_model.values() 

393 ], 

394 } 

395 

396 def report(self) -> dict[str, Any] | None: 

397 """What the captured calls cost, for a record a person reads (a 

398 background event, a run's summary) — or None when none was made.""" 

399 if not self.measured: 

400 return None 

401 return { 

402 "calls": self.calls, 

403 "prompt_tokens": self.input_tokens, 

404 "completion_tokens": self.output_tokens, 

405 # None, never 0, when nothing was priced — "unknown" is not "free". 

406 "estimated_cost_usd": ( 

407 float(self.cost_usd) if self.cost_usd is not None else None 

408 ), 

409 "unpriced_calls": self.unpriced_calls, 

410 } 

411 

412 def add(self, summary: dict[str, Any] | None) -> None: 

413 """Fold one svc-ai usage summary in.""" 

414 if not isinstance(summary, dict) or not summary.get("calls"): 

415 return 

416 with self._lock: 

417 self.calls += int(summary.get("calls") or 0) 

418 self.input_tokens += int(summary.get("prompt_tokens") or 0) 

419 self.output_tokens += int(summary.get("completion_tokens") or 0) 

420 self.unpriced_calls += int(summary.get("unpriced_calls") or 0) 

421 cost = summary.get("estimated_cost_usd") 

422 if cost is not None: 

423 self.cost_usd = (self.cost_usd or Decimal(0)) + Decimal(str(cost)) 

424 estimate = summary.get("unpriced_estimate_usd") 

425 if estimate is not None: 

426 self.unpriced_estimate_usd = ( 

427 self.unpriced_estimate_usd or Decimal(0) 

428 ) + Decimal(str(estimate)) 

429 for row in summary.get("by_model") or []: 

430 if not isinstance(row, dict): 

431 continue 

432 key = (str(row.get("provider") or ""), str(row.get("model") or "")) 

433 merged = self.by_model.setdefault( 

434 key, 

435 { 

436 "provider": key[0], 

437 "model": key[1], 

438 "calls": 0, 

439 "input_tokens": 0, 

440 "output_tokens": 0, 

441 "cost_usd": None, 

442 "unpriced_calls": 0, 

443 }, 

444 ) 

445 merged["calls"] += int(row.get("calls") or 0) 

446 merged["input_tokens"] += int(row.get("prompt_tokens") or 0) 

447 merged["output_tokens"] += int(row.get("completion_tokens") or 0) 

448 merged["unpriced_calls"] += int(row.get("unpriced_calls") or 0) 

449 if row.get("estimated_cost_usd") is not None: 

450 merged["cost_usd"] = float( 

451 Decimal(str(merged["cost_usd"] or 0)) 

452 + Decimal(str(row["estimated_cost_usd"])) 

453 ) 

454 

455 def breakdown(self) -> list[dict[str, Any]]: 

456 """Per-model rows, costliest first — what a run page shows.""" 

457 return sorted( 

458 self.by_model.values(), 

459 key=lambda r: (r["cost_usd"] is None, -(r["cost_usd"] or 0)), 

460 ) 

461 

462 

463_CAPTURE: contextvars.ContextVar[UsageCapture | None] = contextvars.ContextVar( 

464 "svc_ai_usage_capture", default=None 

465) 

466 

467 

468@contextmanager 

469def usage_capture() -> Iterator[UsageCapture]: 

470 """Collect what svc-ai measured for the calls made inside the block. 

471 

472 Nests: an inner capture also reports to the outer one, so a flow that 

473 ledgers one step can sit inside a caller that totals the whole. 

474 """ 

475 outer = _CAPTURE.get() 

476 capture = UsageCapture() 

477 token = _CAPTURE.set(capture) 

478 try: 

479 yield capture 

480 finally: 

481 _CAPTURE.reset(token) 

482 if outer is not None: 

483 outer.add(capture.as_summary()) 

484 

485 

486# ── Trace attribution ──────────────────────────────────────────────────────── 

487# 

488# svc-ai writes a trace row for every invocation (``llm_invocations``), and 

489# the Stats page and the Activity feed read them per user. A call whose 

490# request body names no user is traced to nobody, so its model calls are 

491# missing from that user's figures. The paths that call svc-ai deep inside 

492# shared helpers — indexing, crawling, search — say whose work it is once, 

493# around the block, the same way they open ``usage_capture()``. 

494 

495_ATTRIBUTION: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar( 

496 "svc_ai_trace_attribution", default=None 

497) 

498 

499 

500@contextmanager 

501def attributed( 

502 user_id: str | UUID | None, **reference: str | UUID | None 

503) -> Iterator[None]: 

504 """Attribute the svc-ai calls made inside the block, for svc-ai's trace. 

505 

506 ``user_id`` is whose work it is (None for the platform's own, like a 

507 built-in source's crawl); ``reference`` names what it was for 

508 (``knowledge_id=…``), kept on the trace beside it. 

509 """ 

510 token = _ATTRIBUTION.set( 

511 { 

512 "user_id": str(user_id) if user_id else None, 

513 "reference": {k: str(v) for k, v in reference.items() if v}, 

514 } 

515 ) 

516 try: 

517 yield 

518 finally: 

519 _ATTRIBUTION.reset(token) 

520 

521 

522def _attribute(payload: dict) -> dict: 

523 """``payload`` with the active attribution's ``user_id`` / ``reference``, 

524 never overriding what the caller put there itself.""" 

525 attribution = _ATTRIBUTION.get() 

526 if attribution is None: 

527 return payload 

528 out = dict(payload) 

529 if attribution["user_id"] and not out.get("user_id"): 

530 out["user_id"] = attribution["user_id"] 

531 if attribution["reference"] and not out.get("reference"): 

532 out["reference"] = attribution["reference"] 

533 return out 

534 

535 

536def open_capture() -> UsageCapture: 

537 """Start capturing for the rest of the current task, without a ``with``. 

538 

539 For a handler whose invocation spans a long block — a websocket turn with 

540 a human-approval loop in the middle — where indenting it all under a 

541 context manager would obscure it. The task owns the context; it ends with 

542 the task. 

543 """ 

544 capture = UsageCapture() 

545 _CAPTURE.set(capture) 

546 return capture 

547 

548 

549def _capture_summary(summary: dict[str, Any] | None) -> None: 

550 capture = _CAPTURE.get() 

551 if capture is not None: 

552 capture.add(summary) 

553 

554 

555#: Where svc-ai says which model wrote a run's answer, when it was not the 

556#: agent's own: the stream's ``done`` frame and ``ExecuteResponse.context``. 

557ANSWERED_BY_KEY = "answered_by" 

558 

559 

560#: Where a batch response's context carries the run's web searches 

561#: (svc-ai ``graph_based.WEB_SEARCHES_KEY``). 

562WEB_SEARCHES_KEY = "web_searches" 

563 

564 

565def _capture_web_searches(values: Any) -> None: 

566 """Note on the active capture the web searches svc-ai reports: one 

567 report from a ``tool_call`` frame, or a batch response's list.""" 

568 capture = _CAPTURE.get() 

569 if capture is None: 

570 return 

571 found = web_search_report.reports(values if isinstance(values, list) else [values]) 

572 if found: 

573 with capture._lock: 

574 capture.web_searches.extend(found) 

575 

576 

577#: Where svc-ai sends a turn's knowledge report: the ``done`` frame and a 

578#: batch response's context (svc-ai ``turn_report.KEY``). 

579KNOWLEDGE_REPORT_KEY = "knowledge_report" 

580 

581 

582def _capture_knowledge(value: Any) -> None: 

583 """Note on the active capture what the turn's knowledge did (svc-ai's 

584 ``knowledge_report``); one that does not read is no report.""" 

585 capture = _CAPTURE.get() 

586 report = knowledge_wire.KnowledgeReport.read(value) 

587 if capture is not None and report is not None: 

588 capture.knowledge_report = report 

589 

590 

591def _capture_answered(value: Any) -> None: 

592 """Note on the active capture which model wrote the answer (svc-ai's 

593 ``answered_by``) — a fact about the turn's calls, like their usage.""" 

594 capture = _CAPTURE.get() 

595 if capture is not None and isinstance(value, dict) and value: 

596 capture.answered_by = dict(value) 

597 

598 

599def _capture(response: httpx.Response | None) -> None: 

600 """Feed the active capture from a non-streaming svc-ai response. 

601 

602 Called on error responses too: a call that failed after the model 

603 answered — a rule block on the output, a parse failure — was still paid 

604 for. 

605 """ 

606 if response is None: 

607 return 

608 raw = getattr(response, "headers", {}).get(USAGE_HEADER) 

609 if not isinstance(raw, str) or not raw: 

610 return 

611 try: 

612 _capture_summary(json.loads(raw)) 

613 except ValueError: 

614 logger.warning("Unreadable %s header from svc-ai", USAGE_HEADER) 

615 

616 

617# Default completion-token budget when an agent/model config does not set one. 

618# Must be generous: agent responses carry markdown structure and inline 

619# citations, and a hit cap truncates the user-facing message mid-sentence. 

620# 4096 is supported as an output ceiling by every current provider model. 

621DEFAULT_MAX_TOKENS = 4096 

622 

623#: The sampling temperature a model runs at when its config sets none — what 

624#: a chat turn, and a dashboard tile on a model, answer with. 

625DEFAULT_TEMPERATURE = 0.7 

626 

627#: How long a batch call to svc-ai may take before svc-core gives up on it: 

628#: a plain model call, and one agent turn (``execute_agent_request``). 

629MODEL_TIMEOUT_S = 60.0 

630AGENT_TIMEOUT_S = 120.0 

631 

632# Streaming timeout: ``read`` is the maximum silence between SSE chunks, not 

633# total stream duration. svc-ai emits keepalive comments every ~10s, so a 

634# 600s read window only trips when svc-ai is genuinely gone — a multi-node 

635# graph execution (planning → retrieval → skills → synthesis → evaluator, 

636# plus eval retries) can legitimately run far beyond 120s in total. 

637STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=600.0, write=30.0, pool=10.0) 

638 

639#: How long a model call asked for a reply to a schema may take. svc-ai 

640#: gives a route that decodes natively 300 s, because Bedrock compiles a 

641#: schema it has not seen before answering ("may take up to a few minutes", 

642#: then cached a day); svc-core waits a little longer, so it is svc-ai's 

643#: timeout that ends a slow call, not a disconnect that leaves it running. 

644STRUCTURED_TIMEOUT_S = 330.0 

645 

646 

647class AIServiceError(Exception): 

648 """Raised when svc-ai returns an error or is unreachable.""" 

649 

650 

651class AIServiceTimeout(AIServiceError): 

652 """svc-ai did not answer within the time the caller gave it: it stopped 

653 the run at the limit it was told (504), or it never answered at all. 

654 ``user_message`` says so and is safe to show — the call reached svc-ai, 

655 and "could not answer" blamed the model for the caller's own limit.""" 

656 

657 def __init__(self, timeout_s: float) -> None: 

658 super().__init__(f"svc-ai did not answer within {timeout_s:.0f}s") 

659 self.timeout_s = timeout_s 

660 

661 @property 

662 def user_message(self) -> str: 

663 minutes = round(self.timeout_s / 60) 

664 took = ( 

665 f"{minutes} minute{'s' if minutes != 1 else ''}" 

666 if self.timeout_s >= 60 

667 else f"{max(1, round(self.timeout_s))} seconds" 

668 ) 

669 return f"It was still working when its time ran out ({took})." 

670 

671 

672#: How much sooner than the caller gives up svc-ai stops a batch run 

673#: (``time_limit_s``): a tenth of the wait, at most this — so the 504, and 

674#: what the run spent, arrive before the caller stops listening. 

675TIME_LIMIT_MARGIN_S = 15.0 

676 

677 

678def time_limit(timeout: float) -> float: 

679 """The ``time_limit_s`` svc-ai is told for a call svc-core waits 

680 ``timeout`` seconds on.""" 

681 return max(1.0, timeout - min(TIME_LIMIT_MARGIN_S, timeout * 0.1)) 

682 

683 

684class ModelRefusedError(AIServiceError): 

685 """svc-ai could not use the model for a reason a person must fix: no route 

686 on the deployment's inference backend, credentials, model access, quota or 

687 the spending ceiling. svc-ai answers these 502 with a message that is safe 

688 to show and the kind as ``code`` (its ``main.py`` / ``model_errors``).""" 

689 

690 def __init__(self, user_message: str, code: str) -> None: 

691 super().__init__(f"svc-ai refused the model ({code}): {user_message}") 

692 self.user_message = user_message 

693 self.code = code 

694 

695 

696class SpendLimitReached(ModelRefusedError): 

697 """svc-ai stopped the turn at the most it was told it may spend 

698 (``X-Spend-Limit``): what was left of a budget, or of the platform 

699 allowance. Its message names which, from the limit the turn was given 

700 (``limit``, a ``rule_engine.SpendLimit``); svc-ai's own says only "a 

701 budget".""" 

702 

703 CODE = "spend_limit" 

704 

705 def __init__( 

706 self, 

707 user_message: str, 

708 *, 

709 limit: Any | None = None, 

710 spent_usd: Decimal | None = None, 

711 ) -> None: 

712 if limit is not None: 

713 user_message = limit.stop_message() 

714 super().__init__(user_message, self.CODE) 

715 self.limit = limit 

716 #: What the turn had spent when it was stopped, as svc-ai counted it. 

717 self.spent_usd = spent_usd 

718 

719 

720def _refusal(message: str, code: str, body: dict[str, Any]) -> ModelRefusedError: 

721 """svc-ai's refusal as the error a caller handles: a turn stopped at its 

722 spend limit as ``SpendLimitReached``, anything else ``ModelRefusedError``.""" 

723 if code != SpendLimitReached.CODE: 

724 return ModelRefusedError(message, code) 

725 spent = body.get("spent_usd") 

726 try: 

727 spent_usd = Decimal(str(spent)) if spent is not None else None 

728 except (ArithmeticError, ValueError): 

729 spent_usd = None 

730 return SpendLimitReached(message, limit=current_spend_limit(), spent_usd=spent_usd) 

731 

732 

733def _raise_for_refusal(exc: httpx.HTTPStatusError) -> None: 

734 """Raise svc-ai's 502 refusal as a ``ModelRefusedError``; return for any 

735 other failure.""" 

736 if exc.response.status_code != 502: 

737 return 

738 try: 

739 body = exc.response.json() 

740 except ValueError: 

741 return 

742 if isinstance(body, dict): 

743 detail, code = body.get("detail"), body.get("code") 

744 if isinstance(detail, str) and isinstance(code, str): 

745 raise _refusal(detail, code, body) from exc 

746 

747 

748class DocumentRejected(AIServiceError): 

749 """svc-ai refused a document as invalid (``DocumentSpec``).""" 

750 

751 

752class DocumentFetchRefused(AIServiceError): 

753 """svc-ai could not have a document from a URL for a file source: the 

754 site refused it, it is no document, it is too large (``status``). 

755 ``message`` is safe to show beside the URL.""" 

756 

757 def __init__(self, status: str, message: str) -> None: 

758 super().__init__(f"svc-ai could not fetch the document ({status}): {message}") 

759 self.status = status 

760 self.message = message 

761 

762 

763@dataclass(frozen=True) 

764class FetchedDocument: 

765 """A document svc-ai downloaded for a file source (``fetch_document``).""" 

766 

767 content: bytes 

768 mime_type: str 

769 #: Where it was found, after redirects. 

770 url: str 

771 filename: str 

772 last_modified: str | None = None 

773 

774 

775class GenerationFailedError(AIServiceError): 

776 """Raised when svc-ai rejects a generation request as unfulfillable 

777 (e.g. the selected model does not support structured output).""" 

778 

779 

780class RuleBlockedError(AIServiceError): 

781 """Raised when svc-ai reports that a governance policy rule blocked the 

782 request. Carries the rule's identity and the user-facing block message so 

783 callers can surface them instead of a generic stream error. 

784 

785 ``rule_name`` mirrors ``rule_engine.RuleBlock`` so both kinds of block — 

786 enforced here or inside svc-ai — persist through the same trace builder. 

787 ``rule`` is retained as the original spelling. 

788 """ 

789 

790 def __init__( 

791 self, 

792 rule: str, 

793 message: str, 

794 *, 

795 rule_id: str | None = None, 

796 rule_version: int | None = None, 

797 scope_type: str | None = None, 

798 scope_id: str | None = None, 

799 ) -> None: 

800 self.rule = rule 

801 self.rule_name = rule 

802 self.message = message 

803 self.rule_id = rule_id 

804 self.rule_version = rule_version 

805 self.scope_type = scope_type 

806 self.scope_id = scope_id 

807 super().__init__(message) 

808 

809 

810def _model_spec( 

811 provider: str, model_name: str, config: dict, system_prompt: str = "" 

812) -> dict: 

813 """The model half of an execute request. 

814 

815 ``effort`` is forwarded only when the stored config sets it, so the 

816 request shape is unchanged for every model that does not use one. 

817 svc-ai drops it again for models that take no effort level — it is the 

818 service that knows which those are. 

819 

820 It matters because ``temperature`` no longer reaches the newest models 

821 at all: svc-ai omits it for Anthropic past Opus 4.6 and for OpenAI's 

822 reasoning families, which reject it. Effort is its replacement, and 

823 without this passthrough those models have no steering control. 

824 """ 

825 spec = { 

826 "provider": provider, 

827 "model": model_name, 

828 "temperature": config.get("temperature", DEFAULT_TEMPERATURE), 

829 "max_tokens": config.get("max_tokens", DEFAULT_MAX_TOKENS), 

830 "system_prompt": system_prompt, 

831 } 

832 effort = config.get("effort") 

833 if effort: 

834 spec["effort"] = effort 

835 return spec 

836 

837 

838def _rule_blocked_from_payload(payload: dict) -> RuleBlockedError: 

839 """Build a ``RuleBlockedError`` from svc-ai's block payload. 

840 

841 svc-ai emits one shape for both transports (``inference.rules 

842 .block_payload``): the SSE ``error`` frame and the HTTP 403 detail. Every 

843 identity field is optional so a block from an svc-ai that predates them 

844 still surfaces as a block rather than a generic service error. 

845 """ 

846 return RuleBlockedError( 

847 rule=str(payload.get("rule", "unknown")), 

848 message=payload.get("message", "This request is not permitted."), 

849 rule_id=payload.get("rule_id"), 

850 rule_version=payload.get("rule_version"), 

851 scope_type=payload.get("scope_type"), 

852 scope_id=payload.get("scope_id"), 

853 ) 

854 

855 

856def _raise_for_rule_block(exc: httpx.HTTPStatusError) -> None: 

857 """Re-raise a 403 carrying a rule block as ``RuleBlockedError``. 

858 

859 Batch execution endpoints report a block as HTTP 403 rather than an SSE 

860 frame. Without this the structured detail is flattened into a generic 

861 ``AIServiceError`` and the turn is recorded as a failure instead of a 

862 policy decision — losing the rule that made it. No-op for any other 

863 status or body, so callers can invoke it before their own handling. 

864 """ 

865 if exc.response.status_code != 403: 

866 return 

867 try: 

868 detail = exc.response.json().get("detail") 

869 except ValueError: 

870 return 

871 if isinstance(detail, dict) and detail.get("rule"): 

872 raise _rule_blocked_from_payload(detail) from exc 

873 

874 

875class ModelNotAvailableError(Exception): 

876 """Raised when svc-ai reports a provider/model is not usable.""" 

877 

878 

879def _raise_stream_error(data: dict) -> None: 

880 """Raise the appropriate exception for an SSE ``error`` frame from svc-ai. 

881 

882 A frame with a ``code`` is a fatal model error (``model_errors`` in 

883 svc-ai): its message is written to be shown, and says what to fix. It is 

884 the streamed form of the batch API's 502, so it raises the same 

885 ``ModelRefusedError``; a chat used to answer "Processing failed". 

886 

887 The frame carries what the run had spent before it failed (svc-ai's 

888 ``metering.TERMINAL_FRAMES``): those calls were paid for, so they reach 

889 the capture before the error does, and the failed turn is ledgered with 

890 them.""" 

891 _capture_summary(data.get("usage")) 

892 if data.get("rule"): 

893 raise _rule_blocked_from_payload(data) 

894 message, code = data.get("message"), data.get("code") 

895 if isinstance(message, str) and isinstance(code, str) and message and code: 

896 raise _refusal(message, code, data) 

897 raise AIServiceError(f"svc-ai stream error: {data.get('message', 'unknown')}") 

898 

899 

900def _trace_fields( 

901 purpose: str | None, reference: dict[str, str] | None 

902) -> dict[str, Any]: 

903 """The optional trace attribution an execute request carries. 

904 

905 Omitted rather than sent as null so a request that says nothing looks to 

906 svc-ai exactly as it did before these fields existed. 

907 """ 

908 fields: dict[str, Any] = {} 

909 if purpose: 

910 fields["purpose"] = purpose 

911 if reference: 

912 fields["reference"] = {k: str(v) for k, v in reference.items() if v} 

913 return fields 

914 

915 

916def invoke_model( 

917 provider: str, 

918 model_name: str, 

919 config: dict, 

920 prompt: str, 

921 messages: list[dict], 

922 output_format: str | None = None, 

923 output_schema: str | None = None, 

924 conversation_id: str | None = None, 

925 rules: list[dict] | None = None, 

926 user_id: str = "system", 

927 purpose: str | None = None, 

928 reference: dict[str, str] | None = None, 

929 stoppable: "RunningTurn | None" = None, 

930 timeout: float = MODEL_TIMEOUT_S, 

931 attachments: list[dict] | None = None, 

932) -> tuple[str, int, int, list[dict]]: 

933 """ 

934 Send a prompt to svc-ai and return 

935 (response, input_tokens, output_tokens, rule_events). 

936 

937 ``attachments`` are the conversation's documents 

938 (``attachments.wire``), sent beside the words in ``prompt``: svc-ai puts 

939 them before the words for the model. 

940 

941 With ``stoppable`` (a chat turn in ``app/services/turns.py``) the call 

942 goes through svc-ai's stream instead of its batch endpoint, so Stop can 

943 end it: see ``_invoke_model_streamed``. 

944 

945 ``rule_events`` are the governance actions svc-ai enforced on this call — 

946 empty when none fired. 

947 

948 Args: 

949 provider: Provider string (e.g. "openai", "anthropic"). 

950 model_name: Bare model identifier (e.g. "gpt-4o"). 

951 config: Inference overrides (temperature, max_tokens, etc.). 

952 prompt: The user turn to send. 

953 messages: Prior conversation messages as role/content dicts. 

954 output_format: Optional format constraint forwarded to svc-ai 

955 ("json" | "yaml" | "csv" | "xml" | "plain"). 

956 output_schema: Optional schema string for json/yaml formats. 

957 rules: Serialised policy/audit rules for svc-ai to enforce 

958 inside its engine (see ``rule_engine.serialize_rules``). 

959 user_id: Who the call is attributed to. svc-ai's invocation 

960 trace is read back *per user*, so a call sent as 

961 ``"system"`` is one no user's activity feed can show. 

962 purpose: What produced the call, when it is not the plain 

963 ``type`` svc-ai would otherwise record — an 

964 evaluation cell says ``"evaluation"`` so the trace 

965 does not read as a chat. 

966 reference: Ids the trace should carry back to what asked for the 

967 call (an evaluation, its batch, its variant), stored 

968 on the invocation's request snapshot. 

969 timeout: Seconds to wait for svc-ai's answer; 

970 ``STRUCTURED_TIMEOUT_S`` for a reply to a schema. 

971 

972 Raises: 

973 AIServiceError: If svc-ai returns a non-2xx response or is unreachable. 

974 """ 

975 settings = get_settings() 

976 url = f"{settings.SVC_AI_URL}/agents/execute" 

977 

978 spec: dict = _model_spec( 

979 provider, model_name, config, config.get("system_prompt", "") 

980 ) 

981 if output_format: 

982 spec["output_format"] = output_format 

983 if output_schema: 

984 spec["output_schema"] = output_schema 

985 

986 payload: dict = { 

987 "type": "model", 

988 "spec": spec, 

989 "input": prompt, 

990 **({"attachments": attachments} if attachments else {}), 

991 "messages": messages, 

992 "user_id": user_id or "system", 

993 "rules": rules or [], 

994 **_trace_fields(purpose, reference), 

995 } 

996 if conversation_id: 

997 payload["conversation_id"] = conversation_id 

998 

999 logger.debug("Invoking svc-ai model %s/%s", provider, model_name) 

1000 if stoppable is not None: 

1001 return _invoke_model_streamed(payload, stoppable) 

1002 

1003 try: 

1004 with httpx.Client(timeout=timeout, headers=_internal_headers()) as client: 

1005 response = client.post(url, json=payload) 

1006 _capture(response) 

1007 response.raise_for_status() 

1008 except httpx.HTTPStatusError as exc: 

1009 _raise_for_rule_block(exc) 

1010 _raise_for_refusal(exc) 

1011 raise AIServiceError( 

1012 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1013 ) from exc 

1014 except httpx.RequestError as exc: 

1015 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1016 

1017 data = response.json() 

1018 usage = data.get("usage", {}) 

1019 input_tokens: int = usage.get("prompt_tokens", 0) 

1020 output_tokens: int = usage.get("completion_tokens", 0) 

1021 

1022 logger.debug( 

1023 "svc-ai response: %d input tokens, %d output tokens", 

1024 input_tokens, 

1025 output_tokens, 

1026 ) 

1027 

1028 return ( 

1029 data["output"], 

1030 input_tokens, 

1031 output_tokens, 

1032 data.get("rule_events", []), 

1033 ) 

1034 

1035 

1036def _invoke_model_streamed( 

1037 payload: dict, turn: "RunningTurn" 

1038) -> tuple[str, int, int, list[dict]]: 

1039 """A model call that Stop can end, made from a sync route's worker thread. 

1040 

1041 svc-ai's batch endpoint runs a call to its end whatever its client does, 

1042 so a chat whose Stop only stopped waiting still paid for — and stored — 

1043 the whole answer. Its stream ends the run when the stream is closed, as 

1044 the agent chat's Stop relies on. So the call is made as a stream, run as 

1045 a task on the event loop (``anyio.from_thread``) in a copy of this 

1046 thread's context, so the usage capture, workspace and attribution reach 

1047 it, and ``turn.stop()`` cancels that task. A client that goes away does 

1048 not: the thread keeps waiting and the answer is stored. 

1049 

1050 Raises ``TurnStopped`` carrying what had been written when Stop ended it, 

1051 and otherwise what ``astream_execute`` raises — the batch call's errors. 

1052 """ 

1053 from app.services.turns import TurnStopped 

1054 

1055 written: list[str] = [] 

1056 context = contextvars.copy_context() 

1057 

1058 async def _collect(token: str) -> None: 

1059 written.append(token) 

1060 

1061 async def _reset(event: dict) -> None: 

1062 # What svc-ai took back was never the answer (its model's reasoning 

1063 # outside its envelope): a stopped turn is not stored as it. 

1064 if event.get("type") == TOKEN_RESET: 

1065 written.clear() 

1066 

1067 async def _run() -> tuple[str, int, int, list[dict], dict, list[dict]]: 

1068 loop = asyncio.get_running_loop() 

1069 task = loop.create_task( 

1070 astream_execute(payload=payload, on_token=_collect, on_trace=_reset), 

1071 context=context, 

1072 ) 

1073 turn.on_stop(lambda: loop.call_soon_threadsafe(task.cancel)) 

1074 try: 

1075 return await task 

1076 finally: 

1077 turn.on_stop(None) 

1078 

1079 if turn.stopping: 

1080 raise TurnStopped() 

1081 try: 

1082 text, input_tokens, output_tokens, _segments, _eval, rule_events = ( 

1083 anyio.from_thread.run(_run) 

1084 ) 

1085 except asyncio.CancelledError: 

1086 if turn.stopping: 

1087 raise TurnStopped("".join(written)) from None 

1088 raise 

1089 return text, input_tokens, output_tokens, rule_events 

1090 

1091 

1092def stream_invoke_model( 

1093 provider: str, 

1094 model_name: str, 

1095 config: dict, 

1096 prompt: str, 

1097 messages: list[dict], 

1098 on_token: Callable[[str], None], 

1099) -> tuple[str, int, int, list[dict]]: 

1100 """ 

1101 Stream a model response from svc-ai's SSE endpoint, calling on_token for 

1102 each chunk. Intended to be called from a thread executor so the caller 

1103 can bridge tokens to an asyncio event loop. 

1104 

1105 Returns (full_response, input_tokens, output_tokens) once the stream ends. 

1106 

1107 Raises: 

1108 AIServiceError: If svc-ai is unreachable or returns an error frame. 

1109 """ 

1110 settings = get_settings() 

1111 url = f"{settings.SVC_AI_URL}/agents/execute/stream" 

1112 

1113 payload = { 

1114 "type": "model", 

1115 "spec": _model_spec(provider, model_name, config), 

1116 "input": prompt, 

1117 "messages": messages, 

1118 "user_id": "system", 

1119 } 

1120 

1121 full_text = "" 

1122 input_tokens = 0 

1123 output_tokens = 0 

1124 rule_events: list[dict] = [] 

1125 

1126 try: 

1127 with httpx.Client( 

1128 timeout=STREAM_TIMEOUT, headers=_internal_headers() 

1129 ) as client: 

1130 with client.stream("POST", url, json=payload) as response: 

1131 response.raise_for_status() 

1132 for line in response.iter_lines(): 

1133 if not line.startswith("data: "): 

1134 continue 

1135 try: 

1136 data = json.loads(line[6:]) 

1137 except json.JSONDecodeError: 

1138 continue 

1139 event_type = data.get("type") 

1140 if event_type == "token": 

1141 token = data.get("token", "") 

1142 if token: 

1143 full_text += token 

1144 on_token(token) 

1145 elif event_type == TOKEN_RESET: 

1146 full_text = "" 

1147 elif event_type == "done": 

1148 usage = data.get("usage", {}) 

1149 _capture_summary(usage) 

1150 input_tokens = usage.get("prompt_tokens", 0) 

1151 output_tokens = usage.get("completion_tokens", 0) 

1152 rule_events = data.get("rule_events", []) 

1153 full_text = data.get("output") or full_text 

1154 break 

1155 elif event_type == "error": 

1156 _raise_stream_error(data) 

1157 except httpx.HTTPStatusError as exc: 

1158 _raise_for_rule_block(exc) 

1159 _raise_for_refusal(exc) 

1160 raise AIServiceError( 

1161 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1162 ) from exc 

1163 except httpx.RequestError as exc: 

1164 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1165 

1166 return full_text, input_tokens, output_tokens, rule_events 

1167 

1168 

1169async def astream_invoke_model( 

1170 provider: str, 

1171 model_name: str, 

1172 config: dict, 

1173 prompt: str, 

1174 messages: list[dict], 

1175 on_token: Callable[[str], Awaitable[None]], 

1176) -> tuple[str, int, int]: 

1177 """Async streaming wrapper for plain model calls. Returns (text, in_tok, out_tok).""" 

1178 payload = { 

1179 "type": "model", 

1180 "spec": _model_spec(provider, model_name, config), 

1181 "input": prompt, 

1182 "messages": messages, 

1183 "user_id": "system", 

1184 } 

1185 text, in_t, out_t, _segments = await astream_execute( 

1186 payload=payload, on_token=on_token 

1187 ) 

1188 return text, in_t, out_t 

1189 

1190 

1191#: svc-ai's frame taking back what a node streamed since it started or was 

1192#: last reset (``graph_based.TOKEN_RESET``): text a model wrote beside a tool 

1193#: call, or a gpt-oss answer's opening analysis, which svc-ai then resends. 

1194TOKEN_RESET = "token_reset" 

1195 

1196 

1197def _is_system_node(slug: str, known: set[str]) -> bool: 

1198 """Whether ``slug`` is a pipeline node (``__retrieval_join__``), named so 

1199 by its ``node_start`` frame or by svc-ai's ``__…__`` convention.""" 

1200 return slug in known or (slug.startswith("__") and slug.endswith("__")) 

1201 

1202 

1203def _without_last(text: str, taken: str) -> str: 

1204 """``text`` without its last occurrence of ``taken``: a node's tokens are 

1205 contiguous in its own segment, but other nodes' may follow them in the 

1206 whole stream.""" 

1207 if not taken: 

1208 return text 

1209 at = text.rfind(taken) 

1210 return text if at < 0 else text[:at] + text[at + len(taken) :] 

1211 

1212 

1213async def astream_execute( 

1214 payload: dict, 

1215 on_token: Callable[[str], Awaitable[None]], 

1216 on_status: Callable[[str], Awaitable[None]] | None = None, 

1217 on_citations: Callable[[list], Awaitable[None]] | None = None, 

1218 on_trace: Callable[[dict], Awaitable[None]] | None = None, 

1219 on_worker_token: Callable[[str, str], Awaitable[None]] | None = None, 

1220 on_hitl_interrupt: Callable[[dict], Awaitable[None]] | None = None, 

1221 _override_url: str | None = None, 

1222 on_sources: Callable[[list], Awaitable[None]] | None = None, 

1223) -> tuple[str, int, int, list[dict], dict, list[dict]]: 

1224 """ 

1225 Generic async streaming client for svc-ai's /agents/execute/stream endpoint. 

1226 

1227 When a ``hitl_interrupt`` frame arrives (HITL approval required), ``on_hitl_interrupt`` 

1228 is called with the interrupt payload and the stream loop exits so the caller can 

1229 prompt the user and then call ``astream_execute_resume``. 

1230 

1231 Returns: 

1232 (full_response, input_tokens, output_tokens, segments, eval_result) 

1233 ``full_response`` is empty string when interrupted. 

1234 ``eval_result`` is the evaluator's structured output (score, critique, gaps) 

1235 when the __evaluator__ node ran; empty dict otherwise. 

1236 

1237 Raises: 

1238 AIServiceError: If svc-ai is unreachable or returns an error frame. 

1239 """ 

1240 settings = get_settings() 

1241 url = _override_url or f"{settings.SVC_AI_URL}/agents/execute/stream" 

1242 

1243 accumulated_text = "" 

1244 input_tokens = 0 

1245 output_tokens = 0 

1246 full_text = "" 

1247 eval_result: dict = {} 

1248 rule_events: list[dict] = [] 

1249 

1250 worker_content: dict[str, str] = {} 

1251 worker_order: list[str] = [] 

1252 # Each node's text since it started or was last reset: what a 

1253 # ``token_reset`` frame takes back. 

1254 since_reset: dict[str, str] = {} 

1255 # The segments are each worker's text, as of its latest pass: a system 

1256 # node's is the pipeline's, never a worker's (a retrieval step's notes 

1257 # had been stored as one), and a revision replaces the pass before it 

1258 # (the two had been run together). 

1259 system_nodes: set[str] = set() 

1260 passes: dict[str, Any] = {} 

1261 

1262 try: 

1263 async with httpx.AsyncClient( 

1264 timeout=STREAM_TIMEOUT, headers=_internal_headers() 

1265 ) as client: 

1266 async with client.stream("POST", url, json=payload) as response: 

1267 response.raise_for_status() 

1268 async for line in response.aiter_lines(): 

1269 if not line.startswith("data: "): 

1270 continue 

1271 try: 

1272 data = json.loads(line[6:]) 

1273 except json.JSONDecodeError: 

1274 continue 

1275 event_type = data.get("type") 

1276 if event_type == "token": 

1277 token = data.get("token", "") 

1278 slug = data.get("worker_agent_slug") 

1279 if token: 

1280 accumulated_text += token 

1281 await on_token(token) 

1282 since_reset[slug or ""] = ( 

1283 since_reset.get(slug or "", "") + token 

1284 ) 

1285 if slug and not _is_system_node(slug, system_nodes): 

1286 if slug not in worker_content: 

1287 worker_content[slug] = "" 

1288 worker_order.append(slug) 

1289 worker_content[slug] += token 

1290 if on_worker_token: 

1291 await on_worker_token(slug, token) 

1292 elif event_type == TOKEN_RESET: 

1293 # The node's text so far was not answer — a model's 

1294 # account of what it was about to do beside a tool 

1295 # call — so it is kept neither as the answer's 

1296 # fallback nor as the node's segment. 

1297 slug = data.get("worker_agent_slug") 

1298 taken = since_reset.pop(slug or "", "") 

1299 accumulated_text = _without_last(accumulated_text, taken) 

1300 if slug in worker_content: 

1301 worker_content[slug] = _without_last( 

1302 worker_content[slug], taken 

1303 ) 

1304 if on_trace: 

1305 await on_trace(data) 

1306 elif event_type == "status": 

1307 if on_status: 

1308 await on_status(data.get("message", "")) 

1309 elif event_type == "citations": 

1310 if on_citations: 

1311 await on_citations(data.get("citations", [])) 

1312 elif event_type in ( 

1313 "graph_plan", 

1314 "node_start", 

1315 "node_end", 

1316 "tool_call", 

1317 "system_node_result", 

1318 # Where the run stopped for a person and what it 

1319 # asked; always followed by ``hitl_interrupt``. 

1320 "hitl_pause", 

1321 ): 

1322 # Capture evaluator output for persistence and next-turn planning. 

1323 if ( 

1324 event_type == "system_node_result" 

1325 and data.get("node_id") == "__evaluator__" 

1326 ): 

1327 eval_result = quality_check.from_stream_event(data) 

1328 if event_type in ("node_start", "node_end"): 

1329 # A reset takes back only the run it is sent in. 

1330 since_reset.pop(data.get("node_id") or "", None) 

1331 if event_type == "node_start": 

1332 node = str(data.get("node_id") or "") 

1333 if data.get("is_system_node"): 

1334 system_nodes.add(node) 

1335 run = data.get("pass") 

1336 if ( 

1337 node in worker_content 

1338 and run is not None 

1339 and passes.get(node, run) != run 

1340 ): 

1341 # A new pass: what the worker writes now is 

1342 # its segment. 

1343 worker_content[node] = "" 

1344 if run is not None: 

1345 passes[node] = run 

1346 if event_type == "tool_call" and data.get("report"): 

1347 # Read before ``on_trace``, which may hold the 

1348 # frame back (``withholding.held_frame``). 

1349 _capture_web_searches(data["report"]) 

1350 if on_trace: 

1351 await on_trace(data) 

1352 elif event_type == "hitl_interrupt": 

1353 # A paused run has spent what it spent before pausing. 

1354 _capture_summary(data.get("usage")) 

1355 # Graph paused for human approval — notify caller and exit loop. 

1356 if on_hitl_interrupt: 

1357 await on_hitl_interrupt(data) 

1358 full_text = "" 

1359 break 

1360 elif event_type == "done": 

1361 _tap(data) 

1362 done_output = data.get("output", "") 

1363 full_text = done_output or accumulated_text 

1364 # What the answer cites, which replaces everything the 

1365 # ``citations`` frames streamed as it was retrieved. 

1366 # Absent from an svc-ai that predates it: the streamed 

1367 # list stands. 

1368 cited = data.get("cited_citations") 

1369 if on_sources and isinstance(cited, list): 

1370 await on_sources(cited) 

1371 usage = data.get("usage", {}) 

1372 _capture_summary(usage) 

1373 _capture_answered(data.get(ANSWERED_BY_KEY)) 

1374 _capture_knowledge(data.get(KNOWLEDGE_REPORT_KEY)) 

1375 input_tokens = usage.get("prompt_tokens", 0) 

1376 output_tokens = usage.get("completion_tokens", 0) 

1377 rule_events = data.get("rule_events", []) 

1378 break 

1379 elif event_type == "error": 

1380 _tap(data) 

1381 _raise_stream_error(data) 

1382 else: 

1383 # No terminal frame: svc-ai failed without saying so. With 

1384 # nothing streamed there is no answer to keep; an empty 

1385 # one used to be audited, stored and shown as the reply. 

1386 if not accumulated_text: 

1387 raise AIServiceError( 

1388 "svc-ai's stream ended without a result or an error" 

1389 ) 

1390 full_text = accumulated_text 

1391 except httpx.HTTPStatusError as exc: 

1392 _raise_for_rule_block(exc) 

1393 _raise_for_refusal(exc) 

1394 raise AIServiceError( 

1395 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1396 ) from exc 

1397 except httpx.RequestError as exc: 

1398 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1399 

1400 segments = [ 

1401 {"worker_slug": slug, "content": worker_content[slug], "sequence": i} 

1402 for i, slug in enumerate( 

1403 worker for worker in worker_order if worker_content[worker].strip() 

1404 ) 

1405 ] 

1406 return full_text, input_tokens, output_tokens, segments, eval_result, rule_events 

1407 

1408 

1409async def astream_execute_resume( 

1410 thread_id: str, 

1411 exec_type: str, 

1412 spec: dict, 

1413 user_id: str, 

1414 approved: bool, 

1415 feedback: str, 

1416 on_token: Callable[[str], Awaitable[None]], 

1417 answers: dict | None = None, 

1418 rules: list[dict] | None = None, 

1419 on_status: Callable[[str], Awaitable[None]] | None = None, 

1420 on_citations: Callable[[list], Awaitable[None]] | None = None, 

1421 on_trace: Callable[[dict], Awaitable[None]] | None = None, 

1422 on_worker_token: Callable[[str, str], Awaitable[None]] | None = None, 

1423 on_hitl_interrupt: Callable[[dict], Awaitable[None]] | None = None, 

1424 conversation_id: str | None = None, 

1425 on_sources: Callable[[list], Awaitable[None]] | None = None, 

1426) -> tuple[str, int, int, list[dict], dict, list[dict]]: 

1427 """ 

1428 Resume a HITL-interrupted graph execution and stream the remainder. 

1429 

1430 Calls svc-ai's POST /agents/execute/stream/resume with the saved 

1431 ``thread_id`` and the human's response, then delegates SSE parsing to 

1432 ``astream_execute``. Supports re-interruption if the resumed graph 

1433 pauses again. 

1434 

1435 ``approved``/``feedback`` answer an approval interrupt; ``answers`` answers 

1436 a clarification interrupt raised by the ``ask_user`` tool. All are sent, so 

1437 this call does not need to know which kind it is resuming. 

1438 

1439 ``conversation_id`` is stored on svc-ai's trace of the resumed segment, 

1440 as it is on the first leg's, so both are found from the conversation. 

1441 """ 

1442 settings = get_settings() 

1443 resume_url = f"{settings.SVC_AI_URL}/agents/execute/stream/resume" 

1444 

1445 payload = { 

1446 "thread_id": thread_id, 

1447 "type": exec_type, 

1448 "spec": spec, 

1449 "user_id": user_id, 

1450 "approved": approved, 

1451 "feedback": feedback, 

1452 "answers": answers or {}, 

1453 "rules": rules or [], 

1454 } 

1455 if conversation_id: 

1456 payload["conversation_id"] = conversation_id 

1457 return await astream_execute( 

1458 payload=payload, 

1459 on_token=on_token, 

1460 on_status=on_status, 

1461 on_citations=on_citations, 

1462 on_trace=on_trace, 

1463 on_worker_token=on_worker_token, 

1464 on_hitl_interrupt=on_hitl_interrupt, 

1465 _override_url=resume_url, 

1466 on_sources=on_sources, 

1467 ) 

1468 

1469 

1470def get_model(model_id: UUID) -> dict: 

1471 """ 

1472 Fetch a single model by its svc-ai UUID. 

1473 

1474 Returns the svc-ai LLMModel dict (includes provider, model_name, capabilities). 

1475 

1476 Raises: 

1477 ModelNotAvailableError: If not found in svc-ai. 

1478 AIServiceError: If svc-ai is unreachable. 

1479 """ 

1480 settings = get_settings() 

1481 url = f"{settings.SVC_AI_URL}/models/{model_id}" 

1482 

1483 try: 

1484 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1485 response = client.get(url) 

1486 if response.status_code == 404: 

1487 raise ModelNotAvailableError(f"Model {model_id} not found in svc-ai.") 

1488 response.raise_for_status() 

1489 except httpx.HTTPStatusError as exc: 

1490 raise AIServiceError( 

1491 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1492 ) from exc 

1493 except httpx.RequestError as exc: 

1494 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1495 

1496 return response.json() 

1497 

1498 

1499def list_models( 

1500 provider_id: UUID | None = None, 

1501 is_available: bool | None = None, 

1502 is_default: bool | None = None, 

1503 include_archived: bool = False, 

1504) -> list[dict]: 

1505 """Fetch all models from svc-ai, with optional filters. 

1506 

1507 Archived models are left out unless ``include_archived`` — which is for 

1508 naming what old records ran on, never for choosing a model to run. 

1509 """ 

1510 settings = get_settings() 

1511 url = f"{settings.SVC_AI_URL}/models" 

1512 

1513 params: dict = {} 

1514 if include_archived: 

1515 params["include_archived"] = True 

1516 if provider_id is not None: 

1517 params["provider_id"] = str(provider_id) 

1518 if is_available is not None: 

1519 params["is_available"] = is_available 

1520 if is_default is not None: 

1521 params["is_default"] = is_default 

1522 

1523 try: 

1524 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1525 response = client.get(url, params=params) 

1526 response.raise_for_status() 

1527 except httpx.HTTPStatusError as exc: 

1528 raise AIServiceError( 

1529 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1530 ) from exc 

1531 except httpx.RequestError as exc: 

1532 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1533 

1534 return response.json() 

1535 

1536 

1537def list_providers() -> list[dict]: 

1538 """Fetch all registered providers from svc-ai.""" 

1539 settings = get_settings() 

1540 url = f"{settings.SVC_AI_URL}/models/providers" 

1541 

1542 try: 

1543 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1544 response = client.get(url) 

1545 response.raise_for_status() 

1546 except httpx.HTTPStatusError as exc: 

1547 raise AIServiceError( 

1548 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1549 ) from exc 

1550 except httpx.RequestError as exc: 

1551 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1552 

1553 return response.json() 

1554 

1555 

1556def fetch_model_info(provider: str, model_name: str) -> dict: 

1557 """ 

1558 Fetch capability metadata for a provider/model from svc-ai's canonical registry. 

1559 

1560 Raises: 

1561 ModelNotAvailableError: If the model is not registered in svc-ai. 

1562 AIServiceError: If svc-ai is unreachable. 

1563 """ 

1564 settings = get_settings() 

1565 url = f"{settings.SVC_AI_URL}/models/lookup" 

1566 

1567 try: 

1568 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1569 response = client.get( 

1570 url, params={"provider": provider, "model_name": model_name} 

1571 ) 

1572 if response.status_code == 404: 

1573 raise ModelNotAvailableError( 

1574 f"{provider}/{model_name} is not registered in svc-ai." 

1575 ) 

1576 response.raise_for_status() 

1577 except httpx.HTTPStatusError as exc: 

1578 raise AIServiceError( 

1579 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1580 ) from exc 

1581 except httpx.RequestError as exc: 

1582 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1583 

1584 return response.json() 

1585 

1586 

1587def list_mcp_templates() -> list[dict]: 

1588 """Fetch the list of built-in MCP server templates from svc-ai.""" 

1589 settings = get_settings() 

1590 url = f"{settings.SVC_AI_URL}/mcp/servers/templates" 

1591 

1592 try: 

1593 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1594 response = client.get(url) 

1595 response.raise_for_status() 

1596 except httpx.HTTPStatusError as exc: 

1597 raise AIServiceError( 

1598 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1599 ) from exc 

1600 except httpx.RequestError as exc: 

1601 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1602 

1603 return response.json().get("templates", []) 

1604 

1605 

1606def probe_mcp_server(descriptor: dict) -> dict: 

1607 """Connect to an MCP server via svc-ai and return its exposed tools. 

1608 

1609 ``descriptor`` is {name, transport, config}. Returns svc-ai's probe 

1610 result: {"ok": bool, "tools": [{"name", "description"}], "error": str}. 

1611 A bad/unreachable server comes back as ok=False with the reason — 

1612 AIServiceError is raised only when svc-ai itself cannot be reached. 

1613 """ 

1614 settings = get_settings() 

1615 url = f"{settings.SVC_AI_URL}/mcp/servers/probe" 

1616 

1617 # Generous client budget: svc-ai bounds the actual connection attempt 

1618 # with its own mcp_connect_timeout_s, we just need to outlive it. 

1619 try: 

1620 with httpx.Client(timeout=60.0, headers=_internal_headers()) as client: 

1621 response = client.post(url, json=descriptor) 

1622 response.raise_for_status() 

1623 except httpx.HTTPStatusError as exc: 

1624 raise AIServiceError( 

1625 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1626 ) from exc 

1627 except httpx.RequestError as exc: 

1628 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1629 

1630 return response.json() 

1631 

1632 

1633def list_tools() -> list[dict]: 

1634 """Fetch the list of built-in tools available in svc-ai.""" 

1635 settings = get_settings() 

1636 url = f"{settings.SVC_AI_URL}/tools/available" 

1637 

1638 try: 

1639 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1640 response = client.get(url) 

1641 response.raise_for_status() 

1642 except httpx.HTTPStatusError as exc: 

1643 raise AIServiceError( 

1644 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1645 ) from exc 

1646 except httpx.RequestError as exc: 

1647 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1648 

1649 return response.json().get("tools", []) 

1650 

1651 

1652def list_skills() -> list[dict]: 

1653 """Fetch the list of built-in skill templates available in svc-ai.""" 

1654 settings = get_settings() 

1655 url = f"{settings.SVC_AI_URL}/skills/available" 

1656 

1657 try: 

1658 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1659 response = client.get(url) 

1660 response.raise_for_status() 

1661 except httpx.HTTPStatusError as exc: 

1662 raise AIServiceError( 

1663 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1664 ) from exc 

1665 except httpx.RequestError as exc: 

1666 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1667 

1668 return response.json().get("skills", []) 

1669 

1670 

1671def list_agent_definitions( 

1672 role: str | None = None, 

1673 tag: str | None = None, 

1674 is_builtin: bool | None = None, 

1675) -> list[dict]: 

1676 """Fetch worker agent definitions from svc-ai, with optional filters.""" 

1677 settings = get_settings() 

1678 url = f"{settings.SVC_AI_URL}/skills/agents" 

1679 params: dict = {} 

1680 if role is not None: 

1681 params["role"] = role 

1682 if tag is not None: 

1683 params["tag"] = tag 

1684 if is_builtin is not None: 

1685 params["is_builtin"] = is_builtin 

1686 

1687 try: 

1688 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

1689 response = client.get(url, params=params) 

1690 response.raise_for_status() 

1691 except httpx.HTTPStatusError as exc: 

1692 raise AIServiceError( 

1693 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1694 ) from exc 

1695 except httpx.RequestError as exc: 

1696 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1697 

1698 return response.json() 

1699 

1700 

1701def generate_agent_config(payload: dict) -> dict: 

1702 """ 

1703 Ask svc-ai to generate a proposed agent configuration from a problem 

1704 description plus catalogs of the caller's existing skills/knowledge bases. 

1705 

1706 Returns svc-ai's {"config": {...}, "warnings": [...]} response. 

1707 

1708 Raises: 

1709 GenerationFailedError: If svc-ai reports the request unfulfillable (422). 

1710 AIServiceError: If svc-ai returns another error or is unreachable. 

1711 """ 

1712 settings = get_settings() 

1713 url = f"{settings.SVC_AI_URL}/agents/generate-config" 

1714 

1715 try: 

1716 # Generation is a single large structured-output completion; allow it 

1717 # far longer than ordinary registry calls. 

1718 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1719 response = client.post(url, json=payload) 

1720 _capture(response) 

1721 response.raise_for_status() 

1722 except httpx.HTTPStatusError as exc: 

1723 if exc.response.status_code == 422: 

1724 try: 

1725 detail = exc.response.json().get("detail", exc.response.text) 

1726 except ValueError: 

1727 detail = exc.response.text 

1728 raise GenerationFailedError(detail) from exc 

1729 raise AIServiceError( 

1730 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1731 ) from exc 

1732 except httpx.RequestError as exc: 

1733 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1734 

1735 return response.json() 

1736 

1737 

1738def generate_skill_config(payload: dict) -> dict: 

1739 """ 

1740 Ask svc-ai to design one skill graph from a description, an optional 

1741 pattern and the caller's worker catalogue (``routers/skill_setup``). 

1742 

1743 Returns svc-ai's response: the raw ``proposal``, the ``graph_definition`` 

1744 (only when svc-ai found no ``problems``), name, description, tags, 

1745 reasoning and warnings. 

1746 

1747 Raises: 

1748 GenerationFailedError: If svc-ai reports the request unfulfillable (422). 

1749 AIServiceError: If svc-ai returns another error or is unreachable. 

1750 """ 

1751 settings = get_settings() 

1752 url = f"{settings.SVC_AI_URL}/skills/generate-config" 

1753 

1754 try: 

1755 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1756 response = client.post(url, json=payload) 

1757 _capture(response) 

1758 response.raise_for_status() 

1759 except httpx.HTTPStatusError as exc: 

1760 if exc.response.status_code == 422: 

1761 try: 

1762 detail = exc.response.json().get("detail", exc.response.text) 

1763 except ValueError: 

1764 detail = exc.response.text 

1765 raise GenerationFailedError(detail) from exc 

1766 raise AIServiceError( 

1767 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1768 ) from exc 

1769 except httpx.RequestError as exc: 

1770 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1771 

1772 return response.json() 

1773 

1774 

1775def generate_skillset_config(payload: dict) -> dict: 

1776 """ 

1777 Ask svc-ai to generate a proposed skillset (name, description, selected/ 

1778 proposed skills) from a capability description plus a catalog of the 

1779 caller's existing skills. Skills-only — svc-ai's schema has no tool/ 

1780 MCP-server fields, so a generated skillset can never bundle either. 

1781 

1782 Returns svc-ai's {"config": {...}, "warnings": [...]} response. 

1783 

1784 Raises: 

1785 GenerationFailedError: If svc-ai reports the request unfulfillable (422). 

1786 AIServiceError: If svc-ai returns another error or is unreachable. 

1787 """ 

1788 settings = get_settings() 

1789 url = f"{settings.SVC_AI_URL}/skillsets/generate-config" 

1790 

1791 try: 

1792 # Generation is a single large structured-output completion; allow it 

1793 # far longer than ordinary registry calls. 

1794 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1795 response = client.post(url, json=payload) 

1796 _capture(response) 

1797 response.raise_for_status() 

1798 except httpx.HTTPStatusError as exc: 

1799 if exc.response.status_code == 422: 

1800 try: 

1801 detail = exc.response.json().get("detail", exc.response.text) 

1802 except ValueError: 

1803 detail = exc.response.text 

1804 raise GenerationFailedError(detail) from exc 

1805 raise AIServiceError( 

1806 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1807 ) from exc 

1808 except httpx.RequestError as exc: 

1809 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1810 

1811 return response.json() 

1812 

1813 

1814def generate_toolkit_config(payload: dict) -> dict: 

1815 """ 

1816 Ask svc-ai to recommend a proposed toolkit (name, description, selected 

1817 tools/MCP servers) from a use-case description plus catalogs of the 

1818 caller's existing tools and MCP servers. Existing-only — svc-ai's schema 

1819 has no field for inventing a new tool or MCP server, since either would 

1820 need real credentials only a human can configure. 

1821 

1822 Returns svc-ai's {"config": {...}, "warnings": [...]} response. 

1823 

1824 Raises: 

1825 GenerationFailedError: If svc-ai reports the request unfulfillable (422). 

1826 AIServiceError: If svc-ai returns another error or is unreachable. 

1827 """ 

1828 settings = get_settings() 

1829 url = f"{settings.SVC_AI_URL}/toolkits/generate-config" 

1830 

1831 try: 

1832 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1833 response = client.post(url, json=payload) 

1834 _capture(response) 

1835 response.raise_for_status() 

1836 except httpx.HTTPStatusError as exc: 

1837 if exc.response.status_code == 422: 

1838 try: 

1839 detail = exc.response.json().get("detail", exc.response.text) 

1840 except ValueError: 

1841 detail = exc.response.text 

1842 raise GenerationFailedError(detail) from exc 

1843 raise AIServiceError( 

1844 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1845 ) from exc 

1846 except httpx.RequestError as exc: 

1847 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1848 

1849 return response.json() 

1850 

1851 

1852def generate_knowledge_config(payload: dict) -> dict: 

1853 """ 

1854 Ask svc-ai to design a proposed knowledge repository (name, description, 

1855 appearance, selected existing sources, proposed new sources) from a 

1856 description of what an agent needs to know, plus a catalog of the 

1857 caller's existing knowledge bases. 

1858 

1859 With ``candidates`` (what discovery found and checked), a proposed source 

1860 names the ones it takes by their index in that list — never an address: 

1861 svc-core maps them back to its own copy (``knowledge/candidates.py``). 

1862 Without, a proposed source is a stub. A connection string or an API 

1863 endpoint can never be proposed at all. 

1864 

1865 Returns svc-ai's {"config": {...}, "warnings": [...]} response. 

1866 

1867 Raises: 

1868 GenerationFailedError: If svc-ai reports the request unfulfillable (422). 

1869 AIServiceError: If svc-ai returns another error or is unreachable. 

1870 """ 

1871 settings = get_settings() 

1872 url = f"{settings.SVC_AI_URL}/knowledge/generate-config" 

1873 

1874 try: 

1875 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1876 response = client.post(url, json=payload) 

1877 _capture(response) 

1878 response.raise_for_status() 

1879 except httpx.HTTPStatusError as exc: 

1880 if exc.response.status_code == 422: 

1881 try: 

1882 detail = exc.response.json().get("detail", exc.response.text) 

1883 except ValueError: 

1884 detail = exc.response.text 

1885 raise GenerationFailedError(detail) from exc 

1886 raise AIServiceError( 

1887 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1888 ) from exc 

1889 except httpx.RequestError as exc: 

1890 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1891 

1892 return response.json() 

1893 

1894 

1895def _discovery_response(response: httpx.Response) -> dict: 

1896 """A discovery step's answer, or its failure as the error a caller 

1897 handles: a 422 says the step could not be done (``GenerationFailedError``, 

1898 its detail safe to show).""" 

1899 try: 

1900 response.raise_for_status() 

1901 except httpx.HTTPStatusError as exc: 

1902 if exc.response.status_code == 422: 

1903 raise GenerationFailedError( 

1904 str(_detail(exc.response) or exc.response.text) 

1905 ) from exc 

1906 raise AIServiceError( 

1907 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

1908 ) from exc 

1909 return response.json() 

1910 

1911 

1912def _post_discovery(url: str, payload: dict) -> dict: 

1913 """One model-free step of knowledge discovery on svc-ai.""" 

1914 try: 

1915 with httpx.Client(timeout=60.0, headers=_internal_headers()) as client: 

1916 response = client.post(url, json=payload) 

1917 except httpx.RequestError as exc: 

1918 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1919 return _discovery_response(response) 

1920 

1921 

1922def plan_knowledge_discovery(payload: dict) -> dict: 

1923 """The web searches svc-ai's model would run to find the knowledge 

1924 described — ``{"searches": [{query, looking_for}]}``. A model call. 

1925 

1926 Raises ``GenerationFailedError`` when none could be planned (422), 

1927 ``AIServiceError`` when svc-ai could not be reached.""" 

1928 url = f"{get_settings().SVC_AI_URL}/knowledge/discover/plan" 

1929 try: 

1930 with httpx.Client(timeout=60.0, headers=_internal_headers()) as client: 

1931 response = client.post(url, json=payload) 

1932 _capture(response) 

1933 except httpx.RequestError as exc: 

1934 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1935 return _discovery_response(response) 

1936 

1937 

1938def assign_knowledge_sources(payload: dict) -> dict: 

1939 """Which checked candidates fill each of the given sources — 

1940 ``{"assignments": [{source, candidates, scope, refresh}]}``, by index of 

1941 the request's sources and candidates. A model call (none when there are 

1942 no candidates). 

1943 

1944 Raises ``GenerationFailedError`` when no assignment could be made (422), 

1945 ``AIServiceError`` when svc-ai could not be reached.""" 

1946 url = f"{get_settings().SVC_AI_URL}/knowledge/discover/assign" 

1947 try: 

1948 # svc-ai gives the call 100 s; the client waits a little longer. 

1949 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1950 response = client.post(url, json=payload) 

1951 _capture(response) 

1952 except httpx.RequestError as exc: 

1953 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

1954 return _discovery_response(response) 

1955 

1956 

1957def search_knowledge_candidates(payload: dict) -> dict: 

1958 """Run a plan's searches on svc-ai (no model): ``{found, made, failed, 

1959 provider, unavailable}``.""" 

1960 url = f"{get_settings().SVC_AI_URL}/knowledge/discover/search" 

1961 return _post_discovery(url, payload) 

1962 

1963 

1964def check_knowledge_candidates(payload: dict) -> dict: 

1965 """Probe what the searches found on svc-ai (no model): ``{checked}``, 

1966 one per URL asked, in order.""" 

1967 url = f"{get_settings().SVC_AI_URL}/knowledge/discover/check" 

1968 return _post_discovery(url, payload) 

1969 

1970 

1971def generate_rules_config(payload: dict) -> dict: 

1972 """ 

1973 Ask svc-ai to propose governance rules from a description of what the 

1974 user wants governed, plus the rule vocabulary this service owns. 

1975 

1976 The vocabulary travels with the request rather than living in svc-ai: a 

1977 rule's condition fields, operators and actions are registries here 

1978 (``app.services.rules``), and a rule written against a field the engine 

1979 does not have is stored, shown as active, and never matches. Whatever 

1980 comes back is re-validated against those registries before anything is 

1981 persisted — svc-ai's copy of the grammar is advisory, this one decides. 

1982 

1983 Returns svc-ai's {"config": {...}, "warnings": [...]} response. 

1984 

1985 Raises: 

1986 GenerationFailedError: If svc-ai reports the request unfulfillable (422). 

1987 AIServiceError: If svc-ai returns another error or is unreachable. 

1988 """ 

1989 settings = get_settings() 

1990 url = f"{settings.SVC_AI_URL}/rules/generate-config" 

1991 

1992 try: 

1993 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

1994 response = client.post(url, json=payload) 

1995 _capture(response) 

1996 response.raise_for_status() 

1997 except httpx.HTTPStatusError as exc: 

1998 if exc.response.status_code == 422: 

1999 try: 

2000 detail = exc.response.json().get("detail", exc.response.text) 

2001 except ValueError: 

2002 detail = exc.response.text 

2003 raise GenerationFailedError(detail) from exc 

2004 raise AIServiceError( 

2005 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2006 ) from exc 

2007 except httpx.RequestError as exc: 

2008 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2009 

2010 return response.json() 

2011 

2012 

2013def create_agent_definition(payload: dict) -> dict: 

2014 """Register a custom worker agent definition in svc-ai's registry. 

2015 

2016 Once registered, the definition is referencable as a skill-graph 

2017 ``agent_name`` exactly like a builtin. 

2018 """ 

2019 settings = get_settings() 

2020 url = f"{settings.SVC_AI_URL}/skills/agents" 

2021 try: 

2022 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2023 response = client.post(url, json=payload) 

2024 response.raise_for_status() 

2025 except httpx.HTTPStatusError as exc: 

2026 raise AIServiceError( 

2027 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2028 ) from exc 

2029 except httpx.RequestError as exc: 

2030 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2031 return response.json() 

2032 

2033 

2034def update_agent_definition(name: str, payload: dict) -> dict: 

2035 """Update a custom worker agent definition in svc-ai's registry.""" 

2036 settings = get_settings() 

2037 url = f"{settings.SVC_AI_URL}/skills/agents/{name}" 

2038 try: 

2039 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2040 response = client.patch(url, json=payload) 

2041 response.raise_for_status() 

2042 except httpx.HTTPStatusError as exc: 

2043 raise AIServiceError( 

2044 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2045 ) from exc 

2046 except httpx.RequestError as exc: 

2047 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2048 return response.json() 

2049 

2050 

2051def delete_agent_definition(name: str) -> None: 

2052 """Delete a custom worker agent definition from svc-ai's registry.""" 

2053 settings = get_settings() 

2054 url = f"{settings.SVC_AI_URL}/skills/agents/{name}" 

2055 try: 

2056 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2057 response = client.delete(url) 

2058 response.raise_for_status() 

2059 except httpx.HTTPStatusError as exc: 

2060 raise AIServiceError( 

2061 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2062 ) from exc 

2063 except httpx.RequestError as exc: 

2064 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2065 

2066 

2067def invoke_agent( 

2068 provider: str, 

2069 model_name: str, 

2070 config: dict, 

2071 prompt: str, 

2072 messages: list[dict], 

2073 system_prompt: str = "", 

2074 tools: list[dict] | None = None, 

2075 knowledge_bases: list[dict] | None = None, 

2076 mcp_servers: list[dict] | None = None, 

2077 user_id: str = "system", 

2078 conversation_id: str | None = None, 

2079 agent_name: str = "", 

2080 external_agent_id: str | None = None, 

2081 session_id: str | None = None, 

2082 rules: list[dict] | None = None, 

2083 retrieval: dict | None = None, 

2084 tools_enabled: bool = True, 

2085 purpose: str | None = None, 

2086 reference: dict[str, str] | None = None, 

2087 tool_fixtures: list[dict] | None = None, 

2088 clarify_scope: bool = False, 

2089 memory: bool = True, 

2090 output_format: str | None = None, 

2091 output_schema: str | None = None, 

2092 _detail: dict[str, Any] | None = None, 

2093) -> tuple[str, int, int, list[dict]]: 

2094 """ 

2095 Send a prompt to svc-ai as an agent execution (supports tool-calling). 

2096 

2097 Args: 

2098 provider: Provider string (e.g. "openai"). 

2099 model_name: Bare model identifier (e.g. "gpt-4o"). 

2100 config: Inference overrides (temperature, max_tokens, etc.). 

2101 prompt: The user turn to send. 

2102 messages: Prior conversation messages as role/content dicts. 

2103 system_prompt: Optional system prompt for the agent. 

2104 tools: List of ToolConfig dicts (name, type, config) to equip 

2105 on top of svc-ai's general set. 

2106 tools_enabled: Whether svc-ai binds its general built-in set. False 

2107 means "exactly ``tools``, nothing else" — how an 

2108 evaluation expresses the *without* half of a 

2109 with/without comparison. 

2110 knowledge_bases: List of KnowledgeBaseSpec dicts (id, name, description, 

2111 source_type, config) granting retrieval access. 

2112 mcp_servers: List of MCPServerSpec dicts (name, transport, config) 

2113 whose tools svc-ai loads into the agent's toolset. 

2114 user_id: User identifier forwarded to svc-ai. 

2115 agent_name: User-configured agent name (e.g. "Aria"). Injected into 

2116 svc-ai's AgentConfig so the graph can respond in-persona. 

2117 external_agent_id: Agent UUID from svc-core for cross-service correlation. 

2118 session_id: Session ID for HITL checkpointing and memory scoping. 

2119 retrieval: RetrievalConfig overrides (svc-ai defaults apply to any 

2120 key omitted) governing the knowledge retrieval pipeline. 

2121 purpose: What produced the call when it is not a plain agent 

2122 turn — see ``invoke_model``. 

2123 reference: Ids for the trace to carry back to what asked for 

2124 the call — see ``invoke_model``. 

2125 memory: Whether the run reads and writes the agent's memory 

2126 of ``user_id``. False for an evaluation: its cases 

2127 are not a person's conversation. 

2128 

2129 Raises: 

2130 AIServiceError: If svc-ai returns a non-2xx response or is unreachable. 

2131 """ 

2132 tool_configs = [ 

2133 { 

2134 "name": t["name"], 

2135 "type": t.get("type", "builtin"), 

2136 "config": t.get("config", {}), 

2137 } 

2138 for t in (tools or []) 

2139 ] 

2140 

2141 payload = { 

2142 "type": "agent", 

2143 "spec": { 

2144 "name": agent_name, 

2145 "role": "worker", 

2146 "model": { 

2147 **_model_spec(provider, model_name, config, system_prompt), 

2148 # A reply to a schema (``structured_reply``): svc-ai's agent 

2149 # engine states it in the agent's instructions. 

2150 **({"output_format": output_format} if output_format else {}), 

2151 **({"output_schema": output_schema} if output_schema else {}), 

2152 }, 

2153 "tools": tool_configs, 

2154 "tools_enabled": tools_enabled, 

2155 "knowledge_bases": knowledge_bases or [], 

2156 "mcp_servers": mcp_servers or [], 

2157 "retrieval": retrieval or {}, 

2158 # Scripted tools (evaluation cases): answered from a fixture, never run. 

2159 **({"tool_fixtures": tool_fixtures} if tool_fixtures else {}), 

2160 # Only an interactive caller sets it: a pause needs someone to 

2161 # answer (an evaluation records the questions as the answer). 

2162 **({"clarify_scope": True} if clarify_scope else {}), 

2163 }, 

2164 "input": prompt, 

2165 "messages": messages, 

2166 "user_id": user_id, 

2167 "rules": rules or [], 

2168 **({"conversation_id": conversation_id} if conversation_id else {}), 

2169 **({"external_agent_id": external_agent_id} if external_agent_id else {}), 

2170 **({"session_id": session_id} if session_id else {}), 

2171 **({} if memory else {"memory": False}), 

2172 **_trace_fields(purpose, reference), 

2173 } 

2174 

2175 logger.debug( 

2176 "Invoking svc-ai agent %s/%s with %d tool(s)", 

2177 provider, 

2178 model_name, 

2179 len(tool_configs), 

2180 ) 

2181 data = execute(payload) 

2182 # The caller asked for the detail (see ``invoke_agent_detailed``): hand 

2183 # back the whole body beside the unpacked figures. 

2184 if _detail is not None: 

2185 _detail.update(data if isinstance(data, dict) else {}) 

2186 return _turn_result(data) 

2187 

2188 

2189def execute(payload: dict, *, timeout: float = 120.0) -> dict: 

2190 """Send one execute request to svc-ai — any type: an agent, a skill, a 

2191 model — and return its whole response body. 

2192 

2193 The one batch sender: what svc-ai measured is captured (on error 

2194 responses too: a call that failed after the model answered was paid 

2195 for), a rule block raises ``RuleBlockedError``, a refusal 

2196 ``ModelRefusedError`` (``SpendLimitReached`` for a turn stopped at its 

2197 budget), a run past ``timeout`` ``AIServiceTimeout``, and anything else 

2198 ``AIServiceError``. 

2199 

2200 svc-ai is told to stop the run a little before ``timeout`` 

2201 (``time_limit_s``), so a slow run ends with svc-ai's 504 and what it 

2202 spent rather than svc-core hanging up on a run that goes on spending. 

2203 """ 

2204 settings = get_settings() 

2205 url = f"{settings.SVC_AI_URL}/agents/execute" 

2206 payload = {**payload, "time_limit_s": time_limit(timeout)} 

2207 try: 

2208 with httpx.Client(timeout=timeout, headers=_internal_headers()) as client: 

2209 response = client.post(url, json=payload) 

2210 _capture(response) 

2211 response.raise_for_status() 

2212 except httpx.HTTPStatusError as exc: 

2213 if exc.response.status_code == 504: 

2214 raise AIServiceTimeout(timeout) from exc 

2215 _raise_for_rule_block(exc) 

2216 _raise_for_refusal(exc) 

2217 raise AIServiceError( 

2218 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2219 ) from exc 

2220 except httpx.ReadTimeout as exc: 

2221 # It reached svc-ai, which did not answer in time — an older svc-ai, 

2222 # or one too busy to stop at the limit. 

2223 raise AIServiceTimeout(timeout) from exc 

2224 except httpx.RequestError as exc: 

2225 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2226 data = response.json() 

2227 if isinstance(data, dict): 

2228 _capture_answered((data.get("context") or {}).get(ANSWERED_BY_KEY)) 

2229 _capture_web_searches((data.get("context") or {}).get(WEB_SEARCHES_KEY)) 

2230 _capture_knowledge((data.get("context") or {}).get(KNOWLEDGE_REPORT_KEY)) 

2231 return data 

2232 

2233 

2234def _turn_result(data: dict) -> tuple[str, int, int, list[dict]]: 

2235 """``(output, input tokens, output tokens, rule events)`` of a response.""" 

2236 usage = data.get("usage", {}) or {} 

2237 return ( 

2238 data["output"], 

2239 int(usage.get("prompt_tokens", 0) or 0), 

2240 int(usage.get("completion_tokens", 0) or 0), 

2241 data.get("rule_events", []), 

2242 ) 

2243 

2244 

2245def _turn_detail(data: dict) -> dict[str, Any]: 

2246 """What an evaluation (or a swarm) needs to see of a run beside its 

2247 answer: the pause it stopped on, if any, every tool it called, and the 

2248 sources its answer cites.""" 

2249 interrupt = data.get("interrupt") 

2250 cited = data.get("cited_citations") 

2251 return { 

2252 "interrupt": interrupt if isinstance(interrupt, dict) else None, 

2253 "tool_calls": tool_calls_from_trace(data.get("messages")), 

2254 # What the answer cites, each with its marker: a swarm keeps them, 

2255 # and hands them on with the answer to the steps that read it. 

2256 "cited_citations": cited if isinstance(cited, list) else None, 

2257 } 

2258 

2259 

2260def execute_agent_request( 

2261 payload: dict, 

2262 *, 

2263 detail: bool = False, 

2264 timeout: float = AGENT_TIMEOUT_S, 

2265 body: dict[str, Any] | None = None, 

2266) -> tuple: 

2267 """Send an agent turn built by ``app/services/agent_spec.py`` — as the 

2268 agent itself, or through its skill graph — and return ``(output, input 

2269 tokens, output tokens, rule events)``, plus ``invoke_agent_detailed``'s 

2270 fifth element when ``detail``. 

2271 

2272 ``body``, when given, receives svc-ai's whole response, for what a caller 

2273 reads beside the figures: the batch prompt keeps the answer's own sources 

2274 (``cited_citations``) on the message it stores.""" 

2275 data = execute(payload, timeout=timeout) 

2276 if body is not None and isinstance(data, dict): 

2277 body.update(data) 

2278 result = _turn_result(data) 

2279 return (*result, _turn_detail(data)) if detail else result 

2280 

2281 

2282#: Characters of each tool result kept on an evaluation cell — enough to see 

2283#: what the tool said, not a copy of every page it fetched. svc-ai's own trace 

2284#: keeps as much (``app/routers/stats.py``). A five-result web search runs to 

2285#: about 2,700; at 2,000 (and the judge's 1,500) its last two stories never 

2286#: reached the judge (``scorers.JUDGE_TOOL_OUTPUT_CHARS``). 

2287TOOL_OUTPUT_CHARS = 4000 

2288 

2289 

2290def tool_calls_from_trace(messages: Any) -> list[dict[str, Any]]: 

2291 """The tool calls an agent made, in order, each with what came back. 

2292 

2293 Read off svc-ai's execution trace: an ``ai`` message carries the calls it 

2294 requested, and each ``tool`` message the result for one of them, matched 

2295 by ``tool_call_id``. 

2296 """ 

2297 calls: list[dict[str, Any]] = [] 

2298 by_id: dict[str, dict[str, Any]] = {} 

2299 for message in messages if isinstance(messages, list) else []: 

2300 if not isinstance(message, dict): 

2301 continue 

2302 if message.get("type") == "ai": 

2303 for call in message.get("tool_calls") or []: 

2304 if not isinstance(call, dict) or not call.get("name"): 

2305 continue 

2306 entry = { 

2307 "name": str(call["name"]), 

2308 "args": call.get("args") 

2309 if isinstance(call.get("args"), dict) 

2310 else {}, 

2311 "output": None, 

2312 } 

2313 calls.append(entry) 

2314 if call.get("id"): 

2315 by_id[str(call["id"])] = entry 

2316 elif message.get("type") == "tool": 

2317 entry = by_id.get(str(message.get("tool_call_id") or "")) 

2318 if entry is not None: 

2319 content = message.get("content") 

2320 text = content if isinstance(content, str) else json.dumps(content) 

2321 entry["output"] = text[:TOOL_OUTPUT_CHARS] 

2322 if len(text) > TOOL_OUTPUT_CHARS: 

2323 # The whole result's length, so whoever reads the cut 

2324 # copy (the judge) can be told how much is missing. 

2325 entry["output_chars"] = len(text) 

2326 if message.get("status") == "error": 

2327 entry["error"] = True 

2328 return calls 

2329 

2330 

2331def invoke_agent_detailed(**kwargs: Any) -> tuple[str, int, int, list, dict]: 

2332 """:func:`invoke_agent`, plus what an evaluation needs to see of the run. 

2333 

2334 The fifth element holds ``interrupt`` — the pause the run stopped on, if 

2335 any: an agent that calls ``ask_user`` suspends, and svc-ai answers with an 

2336 empty ``output`` and the questions here — and ``tool_calls``, every tool 

2337 the agent called with its arguments and result. A chat turn streams both 

2338 to the user; the plain tuple loses them, and an evaluation grades them. 

2339 """ 

2340 detail: dict[str, Any] = {} 

2341 output, in_tokens, out_tokens, rule_events = invoke_agent(**kwargs, _detail=detail) 

2342 return (output, in_tokens, out_tokens, rule_events, _turn_detail(detail)) 

2343 

2344 

2345def run_skill( 

2346 skill_id: str, 

2347 graph_definition: dict, 

2348 prompt: str, 

2349 user_id: str = "system", 

2350 name: str = "", 

2351 messages: list[dict] | None = None, 

2352 conversation_id: str | None = None, 

2353 external_agent_id: str | None = None, 

2354 knowledge_bases: list[dict] | None = None, 

2355 agent_name: str = "", 

2356 agent_system_prompt: str = "", 

2357 rules: list[dict] | None = None, 

2358 retrieval: dict | None = None, 

2359 inputs: dict | None = None, 

2360 purpose: str | None = None, 

2361 reference: dict[str, str] | None = None, 

2362 timeout: float = 120.0, 

2363 resume: dict | None = None, 

2364 default_model: dict | None = None, 

2365) -> dict: 

2366 """ 

2367 Execute a stored Skill's graph_definition in svc-ai and return the full 

2368 response payload (output, usage, context — including ``skill_state`` and 

2369 the projected ``skill_outputs`` for schema v3 graphs). 

2370 

2371 ``inputs`` supplies values for the skill's declared ``interface.inputs``; 

2372 they seed the graph state before the first node runs. 

2373 

2374 ``default_model`` is the model of the agent the skill runs for 

2375 (``{provider, model}``, plus the agent's sampling): nodes with no model of 

2376 their own run on it. Absent, they run on svc-ai's default model. 

2377 

2378 ``purpose`` and ``reference`` are stored on svc-ai's invocation trace, so 

2379 the Activity feed can say what the call was for and link back to it (a 

2380 standalone skill run passes its run id). ``timeout`` is the caller's: an 

2381 agent turn has a user waiting on it, a background run of a multi-step 

2382 workflow does not. 

2383 

2384 Raises: 

2385 AIServiceError: If svc-ai returns a non-2xx response or is unreachable. 

2386 """ 

2387 payload: dict = { 

2388 "type": "skill", 

2389 "spec": { 

2390 "skill_id": skill_id, 

2391 "name": name, 

2392 "graph_definition": graph_definition, 

2393 "knowledge_bases": knowledge_bases or [], 

2394 "retrieval": retrieval or {}, 

2395 "agent_name": agent_name, 

2396 "agent_system_prompt": agent_system_prompt, 

2397 "inputs": inputs or {}, 

2398 **({"default_model": default_model} if default_model else {}), 

2399 }, 

2400 "input": prompt, 

2401 "user_id": user_id, 

2402 "messages": messages or [], 

2403 "rules": rules or [], 

2404 } 

2405 if conversation_id: 

2406 payload["conversation_id"] = conversation_id 

2407 if external_agent_id: 

2408 payload["external_agent_id"] = external_agent_id 

2409 if purpose: 

2410 payload["purpose"] = purpose 

2411 if reference: 

2412 payload["reference"] = {k: str(v) for k, v in reference.items() if v} 

2413 if resume: 

2414 # Continue a run that paused: svc-ai rebuilds the same graph and 

2415 # resumes its checkpoint with the person's answer. 

2416 payload["resume"] = resume 

2417 

2418 logger.debug("Invoking svc-ai skill %s (id=%s)", name or skill_id, skill_id) 

2419 return execute(payload, timeout=timeout) 

2420 

2421 

2422def service_fingerprint() -> str | None: 

2423 """The fingerprint of the code svc-ai runs (``/health``'s ``code``), or 

2424 None when it does not say or cannot be reached. The platform benchmark 

2425 re-runs CHAINR Bot only when this, or svc-core's own code that builds the 

2426 bot's request, has changed.""" 

2427 settings = get_settings() 

2428 try: 

2429 with httpx.Client(timeout=10.0) as client: 

2430 response = client.get(f"{settings.SVC_AI_URL}/health") 

2431 response.raise_for_status() 

2432 code = response.json().get("code") 

2433 except (httpx.HTTPError, ValueError, AttributeError): 

2434 return None 

2435 return str(code) if code else None 

2436 

2437 

2438def inference_backend() -> str: 

2439 """How svc-ai reaches models (``/health``'s ``backend``): ``direct`` 

2440 (the vendors' APIs) or ``bedrock``. ``direct`` when it does not say, 

2441 which is what every svc-ai before the Bedrock route was.""" 

2442 settings = get_settings() 

2443 try: 

2444 with httpx.Client(timeout=10.0) as client: 

2445 response = client.get(f"{settings.SVC_AI_URL}/health") 

2446 response.raise_for_status() 

2447 backend = response.json().get("backend") 

2448 except (httpx.HTTPError, ValueError, AttributeError): 

2449 return "direct" 

2450 return str(backend) if backend else "direct" 

2451 

2452 

2453def spend_status() -> dict[str, Any] | None: 

2454 """svc-ai's spending ceiling (``GET /spend``): what model calls have cost 

2455 today and this month against each limit. None when svc-ai cannot say — 

2456 its own guard still refuses calls past the ceiling.""" 

2457 settings = get_settings() 

2458 try: 

2459 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2460 response = client.get(f"{settings.SVC_AI_URL}/spend") 

2461 response.raise_for_status() 

2462 body = response.json() 

2463 except (httpx.HTTPError, ValueError): 

2464 return None 

2465 return body if isinstance(body, dict) else None 

2466 

2467 

2468def get_daily_meter(day: date) -> dict[str, Any]: 

2469 """Every model call svc-ai metered on one UTC day, summed by workspace, 

2470 purpose, model and outcome (``GET /stats/meter``), with the spending 

2471 ceiling's count for the day. The deployment's whole spend, platform work 

2472 included: the daily economics export reads it 

2473 (``app/services/economics``).""" 

2474 settings = get_settings() 

2475 url = f"{settings.SVC_AI_URL}/stats/meter" 

2476 try: 

2477 with httpx.Client(timeout=60.0, headers=_internal_headers()) as client: 

2478 response = client.get(url, params={"day": day.isoformat()}) 

2479 response.raise_for_status() 

2480 except httpx.HTTPStatusError as exc: 

2481 raise AIServiceError( 

2482 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2483 ) from exc 

2484 except httpx.RequestError as exc: 

2485 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2486 return response.json() 

2487 

2488 

2489def discard_paused_run(thread_id: str) -> None: 

2490 """Tell svc-ai to drop the paused state it holds for ``thread_id``. 

2491 

2492 A paused run's checkpoint lives in svc-ai's memory until it is resumed; 

2493 one that is cancelled or expires would otherwise stay there for good. 

2494 """ 

2495 settings = get_settings() 

2496 url = f"{settings.SVC_AI_URL}/agents/execute/threads/{thread_id}" 

2497 try: 

2498 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2499 response = client.delete(url) 

2500 response.raise_for_status() 

2501 except httpx.HTTPStatusError as exc: 

2502 raise AIServiceError( 

2503 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2504 ) from exc 

2505 except httpx.RequestError as exc: 

2506 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2507 

2508 

2509def retrieve_knowledge( 

2510 query: str, 

2511 knowledge_bases: list[dict], 

2512 retrieval: dict | None = None, 

2513 model: dict | None = None, 

2514) -> dict: 

2515 """ 

2516 Run svc-ai's context-rich retrieval pipeline directly (no agent execution). 

2517 

2518 Args: 

2519 query: Natural-language question or search text. 

2520 knowledge_bases: KnowledgeBaseSpec dicts (id, name, description, 

2521 source_type, source_config, config). 

2522 retrieval: RetrievalConfig overrides (mode, top_k, lexical, …). 

2523 model: Optional ModelConfig dict enabling LLM query planning 

2524 and reranking; deterministic stages run without it. 

2525 

2526 Returns the evidence bundle: ranked passages with document/page/chunk 

2527 provenance, graph facts, citations and the rendered Markdown context. 

2528 svc-ai traces the call to the user the caller named with 

2529 ``attributed(...)``. 

2530 

2531 Raises: 

2532 AIServiceError: If svc-ai returns a non-2xx response or is unreachable. 

2533 """ 

2534 settings = get_settings() 

2535 url = f"{settings.SVC_AI_URL}/knowledge/retrieve" 

2536 payload: dict = { 

2537 "query": query, 

2538 "knowledge_bases": knowledge_bases, 

2539 "retrieval": retrieval or {}, 

2540 } 

2541 if model: 

2542 payload["model"] = model 

2543 try: 

2544 with httpx.Client(timeout=120.0, headers=_internal_headers()) as client: 

2545 response = client.post(url, json=_attribute(payload)) 

2546 _capture(response) 

2547 response.raise_for_status() 

2548 return response.json() 

2549 except httpx.HTTPStatusError as exc: 

2550 raise AIServiceError( 

2551 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2552 ) from exc 

2553 except httpx.RequestError as exc: 

2554 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2555 

2556 

2557# Embedding requests carry hundreds of chunk texts; give the provider time. 

2558EMBED_TIMEOUT = httpx.Timeout(connect=10.0, read=300.0, write=60.0, pool=10.0) 

2559 

2560 

2561def embed_texts(texts: list[str]) -> dict: 

2562 """ 

2563 Embed *texts* through svc-ai's ``POST /knowledge/embed``. 

2564 

2565 svc-core runs on internal networks without LLM egress, so embedding is 

2566 delegated to svc-ai — which also guarantees that ingestion and retrieval 

2567 use the same embedding model. 

2568 

2569 Returns ``{"model", "dimensions", "embeddings"}``. svc-ai traces the call 

2570 to the user the caller named with ``attributed(...)``. 

2571 

2572 Raises: 

2573 AIServiceError: If svc-ai returns a non-2xx response or is unreachable. 

2574 """ 

2575 settings = get_settings() 

2576 url = f"{settings.SVC_AI_URL}/knowledge/embed" 

2577 try: 

2578 with httpx.Client(timeout=EMBED_TIMEOUT, headers=_internal_headers()) as client: 

2579 response = client.post(url, json=_attribute({"texts": texts})) 

2580 _capture(response) 

2581 response.raise_for_status() 

2582 return response.json() 

2583 except httpx.HTTPStatusError as exc: 

2584 # The spending ceiling or the account's model access: a person must 

2585 # act, so it reaches the caller as such, not as a broken embed. 

2586 _raise_for_refusal(exc) 

2587 raise AIServiceError( 

2588 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2589 ) from exc 

2590 except httpx.RequestError as exc: 

2591 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2592 

2593 

2594def embedding_identity() -> dict: 

2595 """svc-ai's active embedding model, ``GET /knowledge/embedding``: 

2596 ``{provider, model, dimensions, key, backend, available}``. No model is 

2597 called.""" 

2598 settings = get_settings() 

2599 url = f"{settings.SVC_AI_URL}/knowledge/embedding" 

2600 try: 

2601 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2602 response = client.get(url) 

2603 response.raise_for_status() 

2604 return response.json() 

2605 except httpx.HTTPStatusError as exc: 

2606 raise AIServiceError( 

2607 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2608 ) from exc 

2609 except httpx.RequestError as exc: 

2610 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2611 

2612 

2613def validate_model(provider: str, model_name: str) -> None: 

2614 """ 

2615 Ask svc-ai whether a provider/model combination is usable. 

2616 

2617 Raises: 

2618 ModelNotAvailableError: If the provider has no key or the model is unknown. 

2619 AIServiceError: If svc-ai is unreachable. 

2620 """ 

2621 settings = get_settings() 

2622 url = f"{settings.SVC_AI_URL}/models/validate" 

2623 

2624 try: 

2625 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2626 response = client.post( 

2627 url, json={"provider": provider, "model": model_name} 

2628 ) 

2629 response.raise_for_status() 

2630 except httpx.HTTPStatusError as exc: 

2631 raise AIServiceError( 

2632 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2633 ) from exc 

2634 except httpx.RequestError as exc: 

2635 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2636 

2637 data = response.json() 

2638 if not data.get("valid"): 

2639 raise ModelNotAvailableError( 

2640 data.get("reason") or f"{provider}/{model_name} is not available." 

2641 ) 

2642 

2643 

2644def list_node_types() -> list[dict]: 

2645 """Fetch the list of built-in knowledge graph node type definitions from svc-ai.""" 

2646 settings = get_settings() 

2647 url = f"{settings.SVC_AI_URL}/knowledge/node-types" 

2648 

2649 try: 

2650 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2651 response = client.get(url) 

2652 response.raise_for_status() 

2653 except httpx.HTTPStatusError as exc: 

2654 raise AIServiceError( 

2655 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2656 ) from exc 

2657 except httpx.RequestError as exc: 

2658 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2659 

2660 return response.json().get("node_types", []) 

2661 

2662 

2663async def run_simulation(payload: dict) -> dict: 

2664 """ 

2665 POST /simulate/run to svc-ai and return the SimulationRunResult as a dict. 

2666 

2667 Raises: 

2668 AIServiceError: If svc-ai returns an error or is unreachable. 

2669 """ 

2670 settings = get_settings() 

2671 url = f"{settings.SVC_AI_URL}/simulate/run" 

2672 

2673 logger.debug("Running simulation %s via svc-ai", payload.get("simulation_id")) 

2674 

2675 try: 

2676 async with httpx.AsyncClient( 

2677 timeout=600.0, headers=_internal_headers() 

2678 ) as client: 

2679 response = await client.post(url, json=payload) 

2680 _capture(response) 

2681 response.raise_for_status() 

2682 except httpx.HTTPStatusError as exc: 

2683 raise AIServiceError( 

2684 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2685 ) from exc 

2686 except httpx.RequestError as exc: 

2687 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2688 

2689 return response.json() 

2690 

2691 

2692def _stats_params(user_id: str, workspace: str | None, **params: Any) -> dict: 

2693 """A stats query's parameters: always the user; the workspace when the 

2694 figures are a workspace's rather than the whole account's.""" 

2695 out: dict[str, Any] = {"user_id": user_id, **params} 

2696 if workspace: 

2697 out["workspace"] = workspace 

2698 return out 

2699 

2700 

2701def get_usage_stats(user_id: str, workspace: str | None = None) -> dict: 

2702 """Fetch a user's aggregated token usage statistics from svc-ai — in 

2703 ``workspace`` (a workspace key), or across their account without one. 

2704 

2705 svc-ai's aggregate is deployment-wide unless told whose rows to count, so 

2706 the id is required here: nothing in the product shows one person another 

2707 person's spend. 

2708 """ 

2709 settings = get_settings() 

2710 url = f"{settings.SVC_AI_URL}/stats/usage" 

2711 

2712 try: 

2713 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2714 response = client.get(url, params=_stats_params(user_id, workspace)) 

2715 response.raise_for_status() 

2716 except httpx.HTTPStatusError as exc: 

2717 raise AIServiceError( 

2718 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2719 ) from exc 

2720 except httpx.RequestError as exc: 

2721 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2722 

2723 return response.json() 

2724 

2725 

2726def get_trace_stats(user_id: str, workspace: str | None = None) -> dict: 

2727 """Fetch a user's LLM and tool invocation trace statistics from svc-ai. 

2728 

2729 Scoped as :func:`get_usage_stats` is. 

2730 """ 

2731 settings = get_settings() 

2732 url = f"{settings.SVC_AI_URL}/stats/traces" 

2733 

2734 try: 

2735 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2736 response = client.get(url, params=_stats_params(user_id, workspace)) 

2737 response.raise_for_status() 

2738 except httpx.HTTPStatusError as exc: 

2739 raise AIServiceError( 

2740 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2741 ) from exc 

2742 except httpx.RequestError as exc: 

2743 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2744 

2745 return response.json() 

2746 

2747 

2748def list_llm_invocations( 

2749 user_id: str, 

2750 purpose: str | None = None, 

2751 limit: int = 200, 

2752 offset: int = 0, 

2753 workspace: str | None = None, 

2754) -> list[dict]: 

2755 """Fetch individual LLM invocation traces for a user from svc-ai, newest 

2756 first, ``offset`` rows in — in ``workspace``, or across the account.""" 

2757 settings = get_settings() 

2758 url = f"{settings.SVC_AI_URL}/stats/invocations" 

2759 params: dict = _stats_params(user_id, workspace, limit=limit, offset=offset) 

2760 if purpose: 

2761 params["purpose"] = purpose 

2762 

2763 try: 

2764 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2765 response = client.get(url, params=params) 

2766 response.raise_for_status() 

2767 except httpx.HTTPStatusError as exc: 

2768 raise AIServiceError( 

2769 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2770 ) from exc 

2771 except httpx.RequestError as exc: 

2772 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2773 

2774 return response.json() 

2775 

2776 

2777def get_turn_trace(core_invocation_id: str | UUID, user_id: str | UUID) -> dict: 

2778 """The model and tool calls svc-ai recorded for one turn — every row 

2779 stamped with its invocation id (``X-Invocation-Id``) — narrowed to the 

2780 turn's owner. ``{"invocations": [...], "tool_calls": [...]}``, empty 

2781 for a turn from before the id was sent.""" 

2782 settings = get_settings() 

2783 url = f"{settings.SVC_AI_URL}/stats/turns/{core_invocation_id}" 

2784 try: 

2785 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2786 response = client.get(url, params={"user_id": str(user_id)}) 

2787 response.raise_for_status() 

2788 except httpx.HTTPStatusError as exc: 

2789 raise AIServiceError( 

2790 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2791 ) from exc 

2792 except httpx.RequestError as exc: 

2793 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2794 

2795 return response.json() 

2796 

2797 

2798#: Most turns one ``get_step_usage`` call asks svc-ai about 

2799#: (``MAX_STEP_TURNS`` there). 

2800MAX_STEP_TURNS = 2000 

2801 

2802 

2803def get_step_usage(core_invocation_ids: list[str | UUID]) -> dict: 

2804 """Where a set of turns' tokens went: every model call svc-ai recorded 

2805 for them, summed by graph node, step, pass and model 

2806 (``POST /stats/steps``). ``{"turns": n, "steps": [...]}``. 

2807 

2808 The caller chooses the turns — from its own ledger, narrowed to a 

2809 workspace and to what the reader may see — so svc-ai answers for exactly 

2810 these; at most ``MAX_STEP_TURNS`` of them. 

2811 """ 

2812 ids = list(dict.fromkeys(str(i) for i in core_invocation_ids))[:MAX_STEP_TURNS] 

2813 if not ids: 

2814 return {"turns": 0, "steps": []} 

2815 settings = get_settings() 

2816 url = f"{settings.SVC_AI_URL}/stats/steps" 

2817 try: 

2818 with httpx.Client(timeout=30.0, headers=_internal_headers()) as client: 

2819 response = client.post(url, json={"core_invocation_ids": ids}) 

2820 response.raise_for_status() 

2821 except httpx.HTTPStatusError as exc: 

2822 raise AIServiceError( 

2823 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2824 ) from exc 

2825 except httpx.RequestError as exc: 

2826 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2827 return response.json() 

2828 

2829 

2830def capture_from_trace(trace: dict | None) -> UsageCapture: 

2831 """svc-ai's record of one turn (``get_turn_trace``) as a capture: every 

2832 call it traced that did work, priced as svc-ai priced it. 

2833 

2834 Successful calls only, as svc-ai's own usage summary counts them 

2835 (``metering.UsageMeter.summary``): a provider does not bill a refused 

2836 request. A call svc-ai could not price adds to ``unpriced_calls``. 

2837 """ 

2838 capture = UsageCapture() 

2839 for invocation in (trace or {}).get("invocations") or []: 

2840 for call in invocation.get("calls") or []: 

2841 if not isinstance(call, dict) or call.get("status") != "success": 

2842 continue 

2843 cost = call.get("estimated_cost_usd") 

2844 figures = { 

2845 "calls": 1, 

2846 "prompt_tokens": int(call.get("prompt_tokens") or 0), 

2847 "completion_tokens": int(call.get("completion_tokens") or 0), 

2848 "unpriced_calls": 0 if cost is not None else 1, 

2849 "estimated_cost_usd": cost, 

2850 } 

2851 capture.add( 

2852 { 

2853 **figures, 

2854 "by_model": [ 

2855 { 

2856 "provider": call.get("provider") or "", 

2857 "model": call.get("model_name") or "", 

2858 **figures, 

2859 } 

2860 ], 

2861 } 

2862 ) 

2863 return capture 

2864 

2865 

2866#: Pauses (seconds) while a stopped turn waits for svc-ai to finish tracing 

2867#: the leg it was cancelled in: svc-ai writes that row as the stream unwinds, 

2868#: a moment after the connection closes. 

2869TURN_TRACE_WAITS: tuple[float, ...] = (0.25, 0.75, 1.5) 

2870 

2871 

2872def reconcile_turn_usage( 

2873 captured: UsageCapture | None, 

2874 invocation_id: str | UUID, 

2875 user_id: str | UUID, 

2876 *, 

2877 legs: int, 

2878) -> UsageCapture | None: 

2879 """The fuller of two records of one turn's spend: what svc-core captured 

2880 from the stream's terminal frames, and what svc-ai traced for the turn. 

2881 

2882 A turn that ends without a terminal frame — Stop cancels the stream, or 

2883 the connection to svc-ai fails — captured nothing for the leg in flight, 

2884 though its calls were made and paid for. svc-ai traces that leg as its 

2885 stream unwinds, so its record of the turn is read until it shows every 

2886 leg the turn started (``legs``: the stream, and each resume after a 

2887 pause), waiting a moment for the last. 

2888 

2889 Blocking: call it from a worker thread. Never raises — a trace that 

2890 cannot be read leaves the capture as it was, the ledger's usual bias 

2891 toward under-counting rather than inventing a figure. 

2892 """ 

2893 if legs <= 0: 

2894 return captured 

2895 best = captured 

2896 for wait in (0.0, *TURN_TRACE_WAITS): 

2897 if wait: 

2898 time.sleep(wait) 

2899 try: 

2900 trace = get_turn_trace(invocation_id, user_id) 

2901 except AIServiceError as exc: 

2902 logger.warning( 

2903 "Could not read svc-ai's trace of turn %s (%s) — ledgering what " 

2904 "was captured", 

2905 invocation_id, 

2906 exc, 

2907 ) 

2908 return best 

2909 traced = capture_from_trace(trace) 

2910 if traced.calls > (best.calls if best is not None else 0): 

2911 best = traced 

2912 if len(trace.get("invocations") or []) >= legs: 

2913 break 

2914 return best 

2915 

2916 

2917def get_web_search_domain_stats( 

2918 user_id: str, 

2919 limit: int = 20, 

2920 since: str | None = None, 

2921 until: str | None = None, 

2922 workspace: str | None = None, 

2923) -> dict: 

2924 """Fetch web-search citation domain statistics for a user from svc-ai — 

2925 in ``workspace``, or across the account.""" 

2926 settings = get_settings() 

2927 url = f"{settings.SVC_AI_URL}/stats/web-search-domains" 

2928 params: dict = _stats_params(user_id, workspace, limit=limit) 

2929 if since: 

2930 params["since"] = since 

2931 if until: 

2932 params["until"] = until 

2933 

2934 try: 

2935 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2936 response = client.get(url, params=params) 

2937 response.raise_for_status() 

2938 except httpx.HTTPStatusError as exc: 

2939 raise AIServiceError( 

2940 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2941 ) from exc 

2942 except httpx.RequestError as exc: 

2943 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2944 

2945 return response.json() 

2946 

2947 

2948def _memory_params(user_id: str | None) -> dict[str, str]: 

2949 """``user_id`` narrows a memory route to one user's entries; omitted, 

2950 the route spans the whole agent — which only deleting the agent does.""" 

2951 return {"user_id": user_id} if user_id else {} 

2952 

2953 

2954def get_agent_memory(agent_id: str, *, user_id: str | None = None) -> list[dict]: 

2955 """Fetch persisted memory entries for an agent from svc-ai.""" 

2956 settings = get_settings() 

2957 url = f"{settings.SVC_AI_URL}/memory/{agent_id}" 

2958 

2959 try: 

2960 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

2961 response = client.get(url, params=_memory_params(user_id)) 

2962 response.raise_for_status() 

2963 except httpx.HTTPStatusError as exc: 

2964 raise AIServiceError( 

2965 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2966 ) from exc 

2967 except httpx.RequestError as exc: 

2968 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2969 

2970 return response.json() 

2971 

2972 

2973def list_user_memory(user_id: str) -> list[dict]: 

2974 """Every memory any agent keeps from one user's conversations — the data 

2975 export's copy, which per-agent reads would miss for a deleted agent.""" 

2976 settings = get_settings() 

2977 url = f"{settings.SVC_AI_URL}/memory" 

2978 

2979 try: 

2980 with httpx.Client(timeout=30.0, headers=_internal_headers()) as client: 

2981 response = client.get(url, params={"user_id": user_id}) 

2982 response.raise_for_status() 

2983 except httpx.HTTPStatusError as exc: 

2984 raise AIServiceError( 

2985 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

2986 ) from exc 

2987 except httpx.RequestError as exc: 

2988 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

2989 

2990 return response.json() 

2991 

2992 

2993def summarise_agent_memory( 

2994 agent_ids: list[str], *, user_id: str | None = None, recent: int = 0 

2995) -> list[dict]: 

2996 """How much each agent remembers, per conversation, in one svc-ai call. 

2997 

2998 ``recent`` adds each agent's newest entries as task lines. Read by the 

2999 network views, which would otherwise list every agent's memory to count 

3000 it. 

3001 """ 

3002 if not agent_ids: 

3003 return [] 

3004 settings = get_settings() 

3005 url = f"{settings.SVC_AI_URL}/memory/summary" 

3006 params: list[tuple[str, str | int]] = [("agent_id", a) for a in agent_ids] 

3007 params += list(_memory_params(user_id).items()) 

3008 if recent: 

3009 params.append(("recent", recent)) 

3010 

3011 try: 

3012 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

3013 response = client.get(url, params=params) 

3014 response.raise_for_status() 

3015 except httpx.HTTPStatusError as exc: 

3016 raise AIServiceError( 

3017 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3018 ) from exc 

3019 except httpx.RequestError as exc: 

3020 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

3021 

3022 return response.json() 

3023 

3024 

3025def delete_agent_memory_item( 

3026 agent_id: str, memory_id: str, *, user_id: str | None = None 

3027) -> None: 

3028 """Delete a single memory entry for an agent from svc-ai.""" 

3029 settings = get_settings() 

3030 url = f"{settings.SVC_AI_URL}/memory/{agent_id}/{memory_id}" 

3031 

3032 try: 

3033 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

3034 response = client.delete(url, params=_memory_params(user_id)) 

3035 response.raise_for_status() 

3036 except httpx.HTTPStatusError as exc: 

3037 raise AIServiceError( 

3038 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3039 ) from exc 

3040 except httpx.RequestError as exc: 

3041 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

3042 

3043 

3044def clear_agent_memory(agent_id: str, *, user_id: str | None = None) -> None: 

3045 """Delete memory entries for an agent from svc-ai.""" 

3046 settings = get_settings() 

3047 url = f"{settings.SVC_AI_URL}/memory/{agent_id}" 

3048 

3049 try: 

3050 with httpx.Client(timeout=10.0, headers=_internal_headers()) as client: 

3051 response = client.delete(url, params=_memory_params(user_id)) 

3052 response.raise_for_status() 

3053 except httpx.HTTPStatusError as exc: 

3054 raise AIServiceError( 

3055 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3056 ) from exc 

3057 except httpx.RequestError as exc: 

3058 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

3059 

3060 

3061def delete_user_memory(user_id: str) -> None: 

3062 """Delete everything any agent remembers of one person from svc-ai — for 

3063 an account being deleted. Every agent's, a deleted one's included.""" 

3064 settings = get_settings() 

3065 url = f"{settings.SVC_AI_URL}/memory" 

3066 

3067 try: 

3068 with httpx.Client(timeout=30.0, headers=_internal_headers()) as client: 

3069 response = client.delete(url, params={"user_id": user_id}) 

3070 response.raise_for_status() 

3071 except httpx.HTTPStatusError as exc: 

3072 raise AIServiceError( 

3073 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3074 ) from exc 

3075 except httpx.RequestError as exc: 

3076 raise AIServiceError(f"Could not reach svc-ai at {url}: {exc}") from exc 

3077 

3078 

3079def fetch_web_page( 

3080 url: str, 

3081 *, 

3082 etag: str | None = None, 

3083 last_modified: str | None = None, 

3084 article: bool = False, 

3085) -> dict: 

3086 """Fetch one page of a website knowledge source through svc-ai. 

3087 

3088 svc-core has no route to the open web; svc-ai's fetcher carries the SSRF 

3089 guard and robots.txt handling. The response always describes the page — 

3090 ``status`` says whether it was read, unchanged, refused or gone — so an 

3091 ``AIServiceError`` here means svc-ai itself could not be reached. A URL 

3092 that is a feed answers with ``feed_entries`` instead of content. 

3093 

3094 ``article``: the page is one article (a feed listed it), so svc-ai keeps 

3095 its article text rather than the whole page with its navigation. 

3096 """ 

3097 settings = get_settings() 

3098 endpoint = f"{settings.SVC_AI_URL}/knowledge/web/fetch" 

3099 body = { 

3100 "url": url, 

3101 "etag": etag, 

3102 "last_modified": last_modified, 

3103 "article": article, 

3104 } 

3105 

3106 try: 

3107 # Generous: a slow site, a robots.txt round trip and a PDF through 

3108 # docling can all land in one call. 

3109 with httpx.Client(timeout=90.0, headers=_internal_headers()) as client: 

3110 response = client.post(endpoint, json=body) 

3111 response.raise_for_status() 

3112 except httpx.HTTPStatusError as exc: 

3113 raise AIServiceError( 

3114 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3115 ) from exc 

3116 except httpx.RequestError as exc: 

3117 raise AIServiceError(f"Could not reach svc-ai at {endpoint}: {exc}") from exc 

3118 

3119 return response.json() 

3120 

3121 

3122#: svc-ai's header saying what a rendered PDF drew (its 

3123#: ``routers/documents.py``): each visual fence of the body, in order. 

3124DOCUMENT_VISUALS_HEADER = "X-Document-Visuals" 

3125 

3126 

3127@dataclass(frozen=True) 

3128class RenderedDocument: 

3129 """A stored document's PDF, and what it drew.""" 

3130 

3131 pdf: bytes 

3132 #: Each visual fence of the document's body, in order: ``{"kind", 

3133 #: "drawn"}``, drawn or a note in its place. 

3134 visuals: list[dict[str, Any]] = field(default_factory=list) 

3135 

3136 

3137def _drawn_visuals(header: str | None) -> list[dict[str, Any]]: 

3138 """svc-ai's :data:`DOCUMENT_VISUALS_HEADER`, read: only well-formed 

3139 entries, never an error.""" 

3140 try: 

3141 entries = json.loads(header or "[]") 

3142 except ValueError: 

3143 return [] 

3144 return [ 

3145 {"kind": entry["kind"], "drawn": entry["drawn"]} 

3146 for entry in (entries if isinstance(entries, list) else []) 

3147 if isinstance(entry, dict) 

3148 and isinstance(entry.get("kind"), str) 

3149 and isinstance(entry.get("drawn"), bool) 

3150 ] 

3151 

3152 

3153def render_document_pdf( 

3154 document: dict[str, Any], 

3155 *, 

3156 footer: str | None = None, 

3157 generated_at: str | None = None, 

3158) -> bytes: 

3159 """A stored document rendered to PDF by svc-ai (``app/documents``). 

3160 

3161 svc-ai validates ``document`` against its ``DocumentSpec`` whatever 

3162 produced it; a document it refuses raises ``DocumentRejected`` with the 

3163 reason. No model is involved, so nothing is metered. 

3164 """ 

3165 return render_document(document, footer=footer, generated_at=generated_at).pdf 

3166 

3167 

3168def render_document( 

3169 document: dict[str, Any], 

3170 *, 

3171 footer: str | None = None, 

3172 generated_at: str | None = None, 

3173) -> RenderedDocument: 

3174 """:func:`render_document_pdf`, with what the PDF drew.""" 

3175 settings = get_settings() 

3176 endpoint = f"{settings.SVC_AI_URL}/documents/pdf" 

3177 body = {"document": document, "footer": footer, "generated_at": generated_at} 

3178 try: 

3179 with httpx.Client(timeout=60.0, headers=_internal_headers()) as client: 

3180 response = client.post(endpoint, json=body) 

3181 response.raise_for_status() 

3182 except httpx.HTTPStatusError as exc: 

3183 if exc.response.status_code == 422: 

3184 raise DocumentRejected(exc.response.text) from exc 

3185 raise AIServiceError( 

3186 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3187 ) from exc 

3188 except httpx.RequestError as exc: 

3189 raise AIServiceError(f"Could not reach svc-ai at {endpoint}: {exc}") from exc 

3190 return RenderedDocument( 

3191 response.content, 

3192 _drawn_visuals(response.headers.get(DOCUMENT_VISUALS_HEADER)), 

3193 ) 

3194 

3195 

3196def fetch_document(url: str) -> FetchedDocument: 

3197 """A document downloaded by svc-ai for a file knowledge source — svc-core 

3198 has no route to the open web — under the crawler's rules (robots.txt, 

3199 the public https guard), and only a document by its bytes (a page is a 

3200 website source's). No model is involved, so nothing is metered. 

3201 

3202 Raises ``DocumentFetchRefused`` with svc-ai's reason when it could not be 

3203 had, ``AIServiceError`` when svc-ai could not be reached. 

3204 """ 

3205 from urllib.parse import unquote 

3206 

3207 settings = get_settings() 

3208 endpoint = f"{settings.SVC_AI_URL}/knowledge/web/document" 

3209 try: 

3210 # svc-ai gives one document 120 s all told; this waits a little more. 

3211 with httpx.Client(timeout=150.0, headers=_internal_headers()) as client: 

3212 response = client.post(endpoint, json={"url": url}) 

3213 response.raise_for_status() 

3214 except httpx.HTTPStatusError as exc: 

3215 if exc.response.status_code == 422: 

3216 detail = _detail(exc.response) 

3217 if isinstance(detail, dict): 

3218 raise DocumentFetchRefused( 

3219 str(detail.get("status") or "error"), 

3220 str(detail.get("message") or "The document could not be fetched."), 

3221 ) from exc 

3222 raise AIServiceError( 

3223 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3224 ) from exc 

3225 except httpx.RequestError as exc: 

3226 raise AIServiceError(f"Could not reach svc-ai at {endpoint}: {exc}") from exc 

3227 headers = response.headers 

3228 return FetchedDocument( 

3229 content=response.content, 

3230 mime_type=headers.get("content-type", "application/octet-stream") 

3231 .split(";", 1)[0] 

3232 .strip(), 

3233 url=unquote(headers.get("x-document-url") or url), 

3234 filename=unquote(headers.get("x-document-filename") or "document"), 

3235 last_modified=unquote(headers["x-document-last-modified"]) 

3236 if headers.get("x-document-last-modified") 

3237 else None, 

3238 ) 

3239 

3240 

3241def _detail(response: httpx.Response) -> Any: 

3242 try: 

3243 return response.json().get("detail") 

3244 except Exception: # noqa: BLE001 — not JSON: no detail 

3245 return None 

3246 

3247 

3248def fetch_favicon(domain: str) -> dict: 

3249 """A site's icon, found and fetched by svc-ai (knowledge/favicon.py). 

3250 

3251 ``status`` is ok | missing | unsafe | invalid; on ok, ``data_b64`` holds 

3252 a verified raster image. ``AIServiceError`` only when svc-ai could not be 

3253 reached. 

3254 """ 

3255 settings = get_settings() 

3256 endpoint = f"{settings.SVC_AI_URL}/knowledge/web/favicon" 

3257 try: 

3258 with httpx.Client(timeout=20.0, headers=_internal_headers()) as client: 

3259 response = client.post(endpoint, json={"domain": domain}) 

3260 response.raise_for_status() 

3261 except httpx.HTTPStatusError as exc: 

3262 raise AIServiceError( 

3263 f"svc-ai returned HTTP {exc.response.status_code}: {exc.response.text}" 

3264 ) from exc 

3265 except httpx.RequestError as exc: 

3266 raise AIServiceError(f"Could not reach svc-ai at {endpoint}: {exc}") from exc 

3267 return response.json()