Coverage for app / models / spec.py: 99%

271 statements  

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

1from __future__ import annotations 

2 

3from typing import Annotated, Any, Literal 

4 

5from pydantic import BaseModel, BeforeValidator, Field, field_validator, model_validator 

6 

7from app.agents.enums import AgentRole 

8from app.util import knowledge_categories, vocab, web_domains 

9from app.util.attachment_wire import ( 

10 MAX_ATTACHMENT_CHARS, 

11 MAX_ATTACHMENTS, 

12 AttachedIn, 

13 Availability, 

14 carried_sources, 

15) 

16from app.util.cost_profiles import DEFAULT as COST_PROFILE_DEFAULT 

17from app.util.cost_profiles import CostProfile 

18 

19#: The rule types svc-core sent before its migration 105, as the layer each 

20#: became (routing rules were never forwarded). 

21_LEGACY_LAYERS = {"policy": "input", "audit": "output"} 

22 

23 

24class RuleSpec(BaseModel): 

25 """ 

26 A governance rule forwarded from svc-core to be enforced inside svc-ai. 

27 

28 svc-core resolves the applicable rules for the requesting user/org and 

29 serialises them into ExecuteRequest.rules so svc-ai can apply them during 

30 inference without a cross-service DB round-trip. 

31 

32 An Input rule is evaluated on the prompt before the LLM is called and an 

33 Output rule on the response after it answers (``layer``). The actions 

34 svc-ai can enforce per layer are ``app.inference.rule_vocabulary``'s 

35 (``action_types``) — svc-core's registry holds the full set, and resolves 

36 the rest itself (its Access rules) before forwarding. 

37 

38 conditions/actions follow the same JSON block schema used in svc-core's 

39 Rule model (condition: {"field", "operator", "value"}; action: {"type", ...}). 

40 """ 

41 

42 rule_id: str 

43 # Version of the rule svc-core evaluated, from its resource_versions audit 

44 # trail. Optional: a rule with no recorded history yet has no version. 

45 # Carried so events raised here attribute to the same revision svc-core 

46 # used, rather than to a name that may since have changed. 

47 rule_version: int | None = None 

48 name: str 

49 layer: str # "input" | "output" 

50 scope_type: str = "global" 

51 scope_id: str | None = None 

52 conditions: list[dict[str, Any]] = Field(default_factory=list) 

53 actions: list[dict[str, Any]] = Field(default_factory=list) 

54 priority: int = 0 

55 

56 @model_validator(mode="before") 

57 @classmethod 

58 def _from_rule_type(cls, data: Any) -> Any: 

59 """A rule from an svc-core older than its migration 105, which sent a 

60 ``rule_type`` and called Input's redaction ``filter_pii``: read as the 

61 layer it became. For the release the two services may differ by.""" 

62 if not isinstance(data, dict) or "layer" in data or "rule_type" not in data: 

63 return data 

64 legacy = {**data, "layer": _LEGACY_LAYERS.get(str(data["rule_type"]), "")} 

65 legacy["actions"] = [ 

66 {**action, "type": "redact_pii"} 

67 if isinstance(action, dict) and action.get("type") == "filter_pii" 

68 else action 

69 for action in data.get("actions") or [] 

70 ] 

71 return legacy 

72 

73 

74class ModelConfig(BaseModel): 

75 provider: str # "openai" | "anthropic" 

76 model: str # "gpt-5.6-terra", "claude-sonnet-5", … 

77 # Ignored by models that no longer accept it — Anthropic past Opus 4.6 and 

78 # OpenAI's reasoning families reject an explicit temperature outright, so 

79 # app.services.model_capabilities drops it rather than letting the call 

80 # 400. Use `effort` to steer those models. 

81 temperature: float = 0.7 

82 # How much work the model puts into a response, for models that take the 

83 # control: Anthropic's `output_config.effort` and OpenAI's 

84 # `reasoning_effort` share these level names. None leaves the provider 

85 # default in place (`high` on Claude, `medium` on GPT), which is what 

86 # every caller got before this existed. 

87 effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None 

88 # Generous default — a hit cap truncates user-facing output mid-sentence, 

89 # and structured responses (markdown + inline citations) run long. 

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

91 max_tokens: int = 4096 

92 system_prompt: str = "" 

93 output_format: str | None = ( 

94 None # "json" | "yaml" | "csv" | "xml" | "plain" | None (markdown) 

95 ) 

96 output_schema: str | None = ( 

97 None # JSON/YAML schema string enforced via system prompt 

98 ) 

99 

100 

101class ToolConfig(BaseModel): 

102 name: str 

103 type: Literal["builtin", "webhook", "code"] 

104 config: dict[str, Any] = {} 

105 description: str = "" # used for webhook/code tools without a registry entry 

106 

107 

108class RAGConfig(BaseModel): 

109 collection: str 

110 top_k: int = 5 

111 #: None: the embedding model's ``strict`` floor (each model's scores sit 

112 #: in their own range — ``app.services.embeddings.SimilarityFloors``). 

113 score_threshold: float | None = None 

114 

115 

116RetrievalMode = Literal["pipeline", "agentic", "hybrid"] 

117 

118_RETRIEVAL_MODES: dict[str, str] = { 

119 "pipeline": ( 

120 "deterministic pipeline only (query planning → hybrid search → fusion " 

121 "→ rerank → pack). No LLM tool loop." 

122 ), 

123 "agentic": "legacy behaviour: an LLM agent iterates over per-KB tools.", 

124 "hybrid": ( 

125 "pipeline first; its evidence bundle seeds an agentic pass that only " 

126 "fills gaps. The default." 

127 ), 

128} 

129 

130 

131class RetrievalConfig(BaseModel): 

132 """ 

133 Tunables for the context-rich retrieval pipeline (``app.knowledge.retrieval``). 

134 

135 Sent by svc-core alongside the knowledge-base specs. Every field has a 

136 sensible default so an empty ``{}`` yields the full hybrid pipeline. 

137 """ 

138 

139 mode: RetrievalMode = Field( 

140 default="hybrid", 

141 description=vocab.guide( 

142 _RETRIEVAL_MODES, RetrievalMode, indent="", joiner="\n" 

143 ), 

144 ) 

145 

146 # Query planning — LLM-generated sub-queries and rephrasings. 

147 multi_query: bool = True 

148 max_queries: int = Field(default=4, ge=1, le=8) 

149 

150 # Vector search 

151 top_k: int = Field(default=8, ge=1, le=50) # final passages per KB 

152 candidate_k: int = Field(default=24, ge=1, le=200) # per query per strategy 

153 #: None: the embedding model's ``standard`` floor. A value set here is 

154 #: specific to the model it was tuned on. 

155 score_threshold: float | None = Field(default=None, ge=0.0, le=1.0) 

156 lexical: bool = True # keyword (full-text) leg of hybrid search 

157 rrf_k: int = Field(default=60, ge=1) 

158 

159 # Context enrichment 

160 neighbour_window: int = Field(default=1, ge=0, le=3) # ±N adjacent chunks 

161 max_passages_per_document: int = Field(default=4, ge=1, le=20) 

162 

163 # Graph KBs 

164 graph_depth: int = Field(default=2, ge=1, le=4) 

165 graph_entity_limit: int = Field(default=10, ge=1, le=50) 

166 graph_seeds_vector_queries: bool = True # entity names → extra lexical queries 

167 

168 # Reranking (LLM listwise) and packing 

169 rerank: bool = True 

170 rerank_candidates: int = Field(default=30, ge=1, le=100) 

171 #: The relevance judge's verdict, applied: a passage it rates below this 

172 #: (0 unrelated, 0.5 partial background, 1 answers it) is dropped, and so 

173 #: is the unjudged tail behind its head. A passage from a document the 

174 #: request names is always kept. 0 keeps every passage, as the pipeline 

175 #: did before October 2026 — when a passage the judge called unrelated 

176 #: still reached the model, and the chat's sources, on the strength of 

177 #: its search rank. Applies only when a judge ran (``rerank`` with a 

178 #: model behind it). 

179 min_relevance: float = Field(default=0.4, ge=0.0, le=1.0) 

180 #: The evidence handed to the answering node. 6,000 until 28 October 

181 #: 2026, when it packed two to five of the 12–16 passages lanes handed on, 

182 #: and agents made up for it with their own knowledge searches. 

183 max_context_tokens: int = Field(default=12000, ge=256, le=64000) 

184 

185 # Explicit document targeting — when the query names a stored file the 

186 # search is additionally scoped to it, its passages are boosted, and 

187 # whole-document requests ("summarise X.pdf") include the document text. 

188 document_targeting: bool = True 

189 max_targeted_documents: int = Field(default=3, ge=1, le=10) 

190 full_document_share: float = Field(default=0.6, ge=0.1, le=0.9) 

191 

192 # Routing policy. ``always_retrieve`` makes the gate run internal 

193 # retrieval on every substantive turn when knowledge bases are attached 

194 # (retrieve-then-judge, cf. CRAG / Self-RAG) instead of letting the LLM 

195 # router guess relevance from filenames. Irrelevant evidence is dropped 

196 # by the relevance judge (``min_relevance``), so the cost of a wrong 

197 # "retrieve" is low while the cost of a wrong "direct" is an answer that 

198 # ignores the KB. 

199 always_retrieve: bool = True 

200 # ...except when triage chose the web alone. With this on, a successful 

201 # triage's ``retrieve_external`` stands on an agent with knowledge too, 

202 # provided the inventory it read was complete and the person's own words 

203 # (the request, its standalone form, their previous message — never the 

204 # agent's reply, which names its own sources) name no attached document 

205 # or knowledge base (which still forces the lookup). 

206 # A failed triage, an incomplete inventory, and every other route are 

207 # still forced. Forcing the knowledge onto a web-only turn handed CHAINR 

208 # Bot its user guide's page on the News repository for "what's in the 

209 # news", which it then answered with. 

210 respect_triage_web_route: bool = True 

211 # ...nor when triage chose ``direct``: it read the inventory and judged 

212 # that none of the knowledge bears on the request. It stands on the same 

213 # terms as a web-only route, and not when the request names a period an 

214 # agent with dated knowledge holds. Forcing the search judged 120 

215 # passages for a backlog question asked of a law-only agent, kept none, 

216 # and filed the turn as one the knowledge could not answer. 

217 respect_triage_direct_route: bool = True 

218 # In ``hybrid`` mode, run the agentic gap-filling pass only when the 

219 # pipeline's evidence falls short: nothing found, a search that failed, 

220 # a document the request names that matched nothing, or one it names 

221 # that the evidence holds nothing from. How many passages were found is 

222 # no test — one may answer the request, three may not; a passage count 

223 # (``min_sufficient_passages``, gone; a stored config's is ignored) sent 

224 # most turns on a search of the same knowledge again. 

225 agentic_when_thin: bool = True 

226 # The agentic pass's model rounds (each may run several searches): it 

227 # is asked for up to this many targeted queries and stops when the task 

228 # is covered or a search adds nothing new. 

229 agentic_max_iterations: int = Field(default=4, ge=1, le=10) 

230 

231 

232class RetrievedPassage(BaseModel): 

233 """One ranked evidence passage produced by the retrieval pipeline.""" 

234 

235 citation_id: str = "" # "S1", "S2", … assigned after packing 

236 kb_id: str 

237 kb_name: str 

238 document_id: str = "" 

239 source: str = "" # original filename / url 

240 folder_path: str = "" 

241 page_number: int | None = None 

242 chunk_index: int | None = None 

243 chunk_span: tuple[int, int] | None = None # after neighbour expansion 

244 text: str 

245 score: float = 0.0 # fused / reranked score, higher is better 

246 #: The relevance judge's rating, 0–1; None when no judge saw it. 

247 relevance: float | None = None 

248 dense_score: float | None = None 

249 lexical_hit: bool = False 

250 matched_queries: list[str] = Field(default_factory=list) 

251 targeted: bool = False # from a document the user explicitly named 

252 full_document: bool = False # the whole document text (possibly truncated) 

253 # Website knowledge: the page the passage came from, and when that 

254 # snapshot was taken — an answer grounded in a page can go stale. 

255 url: str = "" 

256 page_title: str = "" 

257 fetched_at: str = "" 

258 # Deep citations. ``links``: pages this passage itself links to — the 

259 # article an aggregator lists, the source a post cites — ``{url, text}``. 

260 # ``via``: for a page read because another crawled page linked to it, the 

261 # page(s) that did — ``{url, title}``. Knowledge base → via → this page → 

262 # links is the chain a citation can show. 

263 links: list[dict[str, str]] = Field(default_factory=list) 

264 via: list[dict[str, str]] = Field(default_factory=list) 

265 # What a citation owes its publisher: when the page was published and by 

266 # whom, and the credit and licence its source was stored with. News is 

267 # where these matter most — a date is the first thing a reader of a news 

268 # answer needs, and an openly licensed passage is used on the terms of 

269 # its licence. 

270 published: str = "" 

271 author: str = "" 

272 attribution: str = "" 

273 licence_url: str = "" 

274 

275 def citation(self) -> dict[str, Any]: 

276 """Serialise into the citation dict shape consumed by svc-core / the UI.""" 

277 return { 

278 "tool": "retrieval", 

279 "citation_id": self.citation_id, 

280 "source": self.url or self.source or self.kb_name, 

281 "title": self.page_title or self.source or self.kb_name, 

282 "url": self.url or None, 

283 "fetched_at": self.fetched_at or None, 

284 "links": list(self.links) or None, 

285 "via": list(self.via) or None, 

286 "published": self.published or None, 

287 "author": self.author or None, 

288 "attribution": self.attribution or None, 

289 "licence_url": self.licence_url or None, 

290 "kb_id": self.kb_id, 

291 "kb_name": self.kb_name, 

292 "document_id": self.document_id, 

293 "folder_path": self.folder_path, 

294 "page_number": self.page_number, 

295 "chunk_index": self.chunk_index, 

296 # The chunks the passage's text holds, [first, last], after 

297 # neighbour expansion: what a corrective pass leaves out. 

298 "chunk_span": list(self.chunk_span) if self.chunk_span else None, 

299 "snippet": self.text[:280], 

300 "score": round(self.score, 4), 

301 } 

302 

303 

304class GraphFact(BaseModel): 

305 """One relationship triple (or standalone entity) retrieved from a graph KB.""" 

306 

307 citation_id: str = "" 

308 kb_id: str 

309 kb_name: str 

310 from_name: str 

311 from_label: str = "" 

312 relationship: str = "" 

313 to_name: str = "" 

314 to_label: str = "" 

315 properties: dict[str, Any] = Field(default_factory=dict) 

316 

317 def as_text(self) -> str: 

318 if self.relationship and self.to_name: 

319 return ( 

320 f"{self.from_name} ({self.from_label}) —[{self.relationship}]→ " 

321 f"{self.to_name} ({self.to_label})" 

322 ) 

323 props = ", ".join(f"{k}: {v}" for k, v in self.properties.items()) 

324 return f"{self.from_name} ({self.from_label})" + ( 

325 f" — {props}" if props else "" 

326 ) 

327 

328 def citation(self) -> dict[str, Any]: 

329 entity = f"Entity:{self.from_name}" 

330 return { 

331 "tool": "retrieval_graph", 

332 "citation_id": self.citation_id, 

333 "source": entity, 

334 "title": entity, 

335 "kb_id": self.kb_id, 

336 "kb_name": self.kb_name, 

337 "snippet": self.as_text()[:280], 

338 } 

339 

340 

341class RetrievalBundle(BaseModel): 

342 """ 

343 The structured output of one retrieval pipeline run. 

344 

345 ``context_markdown`` is the LLM-facing rendering (numbered ``[S#]`` evidence 

346 blocks); ``citations`` is the machine-readable list forwarded to callers. 

347 """ 

348 

349 query: str 

350 queries: list[str] = Field(default_factory=list) 

351 passages: list[RetrievedPassage] = Field(default_factory=list) 

352 graph_facts: list[GraphFact] = Field(default_factory=list) 

353 kb_ids: list[str] = Field(default_factory=list) 

354 skipped_kbs: list[str] = Field(default_factory=list) # empty / unavailable 

355 # Documents the query referred to by name: {kb_id, kb_name, document_id, 

356 # name, coverage: "full" | "partial" | "none"} 

357 targeted_documents: list[dict[str, Any]] = Field(default_factory=list) 

358 # Filename-like mentions that matched no stored document. 

359 unresolved_mentions: list[str] = Field(default_factory=list) 

360 errors: list[str] = Field(default_factory=list) 

361 #: Search legs that could not run, one line each (a knowledge base's 

362 #: semantic search failed or is waiting on a re-index), while the rest 

363 #: still answered. Kept apart from ``errors``, which mean retrieval 

364 #: itself failed and send the turn to the agentic pass. 

365 degraded: list[str] = Field(default_factory=list) 

366 #: Passages the search found and the relevance judge ruled out. Found 

367 #: something, kept nothing: the knowledge does not cover the request, 

368 #: and searching it again (the agentic pass) would find the same. 

369 judged_out: int = 0 

370 #: The query planner failed and the original question was searched on 

371 #: its own (one line, ``model_errors.describe``); empty when it ran. 

372 planner_failure: str = "" 

373 #: The relevance judge failed — raised, or rated none of the passages — 

374 #: and every passage was kept unjudged; empty when it ran. Like 

375 #: ``degraded``, a stage that ran with less, not ``errors``. 

376 judge_failure: str = "" 

377 #: Dated passages the turn's window left out (temporal knowledge). 

378 out_of_window: int = 0 

379 #: What each knowledge base searched gave, by its id: passages (or graph 

380 #: facts) ``found``, ``kept`` in what the agent was given, ``ruled_out`` 

381 #: by the relevance judge and left ``out_of_window`` — the turn's 

382 #: retrieval record (``app/util/knowledge_report.py``). 

383 kb_counts: dict[str, dict[str, int]] = Field(default_factory=dict) 

384 #: Dated passages packed into the evidence (temporal knowledge): an 

385 #: answer resting on them is not kept as a memory. 

386 dated_passages: int = 0 

387 context_markdown: str = "" 

388 #: The frameworks (reasoning knowledge) packed apart from the evidence, 

389 #: rendered for the answering node's ``<frameworks>``; their passages 

390 #: are in ``passages`` too, so they are cited like the rest. 

391 frameworks_markdown: str = "" 

392 #: How each lane of a turn's mix fared in packing, by its kind 

393 #: (``retrieval.LanePacking``): its budget, the tokens it used, the 

394 #: passages it packed and the budget it took over from the others. 

395 #: Empty outside a graph run. 

396 lanes: dict[str, dict[str, Any]] = Field(default_factory=dict) 

397 approx_tokens: int = 0 

398 timings_ms: dict[str, int] = Field(default_factory=dict) 

399 

400 @property 

401 def citations(self) -> list[dict[str, Any]]: 

402 return [p.citation() for p in self.passages] + [ 

403 g.citation() for g in self.graph_facts 

404 ] 

405 

406 @property 

407 def is_empty(self) -> bool: 

408 # An unresolved file mention is itself evidence ("this file does not 

409 # exist") that downstream agents must see, so it counts as content. 

410 return not (self.passages or self.graph_facts or self.unresolved_mentions) 

411 

412 @property 

413 def frameworks_only(self) -> bool: 

414 """Frameworks found and no evidence: there was a method to apply but 

415 nothing in the knowledge about the request itself.""" 

416 return bool(self.frameworks_markdown) and not self.context_markdown 

417 

418 

419class KnowledgeBaseSpec(BaseModel): 

420 """ 

421 Descriptor for a knowledge base granted to an agent. 

422 

423 Passed from svc-core at execution time so svc-ai can build per-KB 

424 retrieval tools without a cross-service database query. 

425 

426 Fields: 

427 id: UUID of the Knowledge record (used as Qdrant collection 

428 name for vector KBs, or Neo4j knowledge_id for graphs). 

429 name: Human-readable name used to derive tool identifiers. 

430 description: Optional context shown in the tool description. 

431 source_type: "graph" → Neo4j graph tool; anything else → Qdrant RAG tool. 

432 config: Per-agent overrides, e.g. {"top_k": 10} or {"depth": 3}. 

433 """ 

434 

435 id: str 

436 name: str 

437 description: str = "" 

438 source_type: str # "file" | "web" | "db" | "api" | "graph" 

439 source_config: dict[ 

440 str, Any 

441 ] = {} # KB-level metadata (e.g. graph node/edge descriptions) 

442 config: dict[str, Any] = {} # per-agent overrides (e.g. top_k, depth) 

443 # Document manifest from svc-core (vector KBs): the authoritative list of 

444 # stored files — {id, name, source_id, folder_path, mime_type, 

445 # index_status, index_error, chunk_count}. Lets svc-ai resolve a file the 

446 # user names even when indexing is pending or the vector store is down. 

447 documents: list[dict[str, Any]] = Field(default_factory=list) 

448 #: What kind of knowledge it is — the category of the repositories it was 

449 #: granted through (``app/util/knowledge_categories.py``), which decides 

450 #: how it is searched and read (``app/knowledge/categories.py``). One an 

451 #: older svc-core sends without it, or with a value this copy does not 

452 #: know, is domain: how every knowledge base was used before. 

453 #: A plain string, so the dicts the engines put in graph state (and its 

454 #: checkpoints) hold no enum. 

455 category: str = knowledge_categories.DEFAULT.value 

456 #: The names of the agent's repositories that hold it: a request naming 

457 #: one ("According to the Security guidance repository…") names its 

458 #: knowledge bases. Empty from an older svc-core. 

459 repositories: list[str] = Field(default_factory=list) 

460 

461 @field_validator("category", mode="before") 

462 @classmethod 

463 def _unknown_category_is_the_default(cls, value: Any) -> str: 

464 return knowledge_categories.of(value).value 

465 

466 

467class MCPServerSpec(BaseModel): 

468 """ 

469 Descriptor for an MCP server whose tools an agent may call. 

470 

471 Passed from svc-core at execution time (resolved from access-checked 

472 MCPServer rows) so svc-ai can connect and bind the server's tools 

473 without a cross-service database query. 

474 

475 Fields: 

476 name: Unique label; used for logging and tool namespacing on 

477 name collisions (``<name>__<tool>``). 

478 transport: One of ``app.mcp.loader``'s transports — validated 

479 against the deployment's transport policy at load time. 

480 config: Connection details for that transport (a URL and headers, 

481 or a command, args and env). 

482 """ 

483 

484 name: str 

485 transport: str 

486 config: dict[str, Any] = {} 

487 

488 

489class ToolFixture(BaseModel): 

490 """A tool whose answer is scripted rather than computed. 

491 

492 Evaluation cases use these to fix what the world returns — a share price, 

493 a 24-hour change — so a question about live data has a reproducible right 

494 answer, and a run does not move for reasons unrelated to the agent. A 

495 fixture replaces a bound tool of the same name (keeping its description 

496 and arguments, so the agent calls it exactly as it would the real one) or, 

497 for a name no tool has, adds one. 

498 """ 

499 

500 name: str = Field(pattern=r"^[A-Za-z_][A-Za-z0-9_]{0,63}$") 

501 description: str | None = Field(default=None, max_length=1000) 

502 #: Returned verbatim on every call. 

503 response: str = Field(max_length=20_000) 

504 

505 

506def _platform_domains(value: Any) -> list[str]: 

507 return list(web_domains.normalise_domains(value or ())[: web_domains.MAX_DOMAINS]) 

508 

509 

510#: The web sources CHAIN-R puts first for its own agent, CHAINR Bot 

511#: (``app/tools/web/platform_sources.py``): stored as a Tools rule's domains 

512#: are, at most as many, anything naming no domain left out. svc-core sends 

513#: them for the built-in agent only. 

514PlatformSources = Annotated[list[str], BeforeValidator(_platform_domains)] 

515 

516 

517class AgentConfig(BaseModel): 

518 """ 

519 Configuration for a single agent instance. 

520 

521 ``role`` drives which concrete WorkerAgent class is instantiated when 

522 building a graph from spec (see AgentFactory.from_config). 

523 ``name`` is the user-configured agent name (e.g. "Aria"). When set it is 

524 injected into GraphState so all system nodes (gate trivial bypass, synthesis, 

525 etc.) can respond in-persona rather than with generic canned text. 

526 """ 

527 

528 name: str = "" 

529 role: AgentRole = AgentRole.WORKER 

530 model: ModelConfig 

531 # Extra tools on top of the general set — webhooks, and any builtin whose 

532 # config differs from the default (a narrowed web_search domain policy, say). 

533 tools: list[ToolConfig] = [] 

534 # Whether the general builtin toolset is bound. True for an ordinary agent 

535 # turn: arithmetic, time, web lookup and the renderers are platform 

536 # capabilities, not things a user wires up one at a time. False is how a 

537 # caller expresses "exactly the tools in ``tools``, and nothing else" — 

538 # which is what makes an evaluation's with/without comparison possible. 

539 # Mirrors WorkerAgentDefinition.tools_enabled, which does this for workers. 

540 tools_enabled: bool = True 

541 rag: RAGConfig | None = None 

542 knowledge_bases: list[KnowledgeBaseSpec] = [] 

543 mcp_servers: list[MCPServerSpec] = [] 

544 # Tunables for the context-rich retrieval pipeline applied to knowledge_bases. 

545 retrieval: RetrievalConfig = Field(default_factory=RetrievalConfig) 

546 # Tools answered from a script instead of run (see ToolFixture). Bound on 

547 # the agent's own node; the pipeline's retrieval and planning nodes are 

548 # not the agent and keep their real tools. 

549 tool_fixtures: list[ToolFixture] = Field(default_factory=list, max_length=20) 

550 # Check the request's scope before any work starts, and pause to ask the 

551 # person when it is ambiguous (the ``__clarify__`` node). Only for callers 

552 # with a person to answer — a chat turn, or an evaluation of one; a 

553 # dashboard tile or a batch job leaves it off. Distinct from ``ask_user``, 

554 # which the agent may call mid-task whenever its tools are bound. 

555 clarify_scope: bool = False 

556 # How much pipeline work a turn does (app/agents/effort.py): the agent's 

557 # own choice, from the vocabulary both services carry. 

558 cost_profile: CostProfile = COST_PROFILE_DEFAULT 

559 # The model a profile that uses one (``cost_profiles.LIGHTER_MODEL``) 

560 # does its lighter work on: chosen by svc-core — the agent's maker's 

561 # lightest model in the same region, under the workspace's rules — and 

562 # None when there is none or the profile uses none. 

563 lighter_model: ModelConfig | None = None 

564 # A model of the same maker, in the same region, that decodes a reply to 

565 # a schema natively, for the run's structured system steps when the model 

566 # making one cannot (``services/native_sibling.py``). Chosen by svc-core 

567 # (``NATIVE_STRUCTURED_SIBLING``, off by default); svc-ai checks it again 

568 # and stands it in only where it applies. ``max_tokens``, when sent, is 

569 # its ceiling. 

570 structured_model: ModelConfig | None = None 

571 # Sources a search puts first and never restricts to, where no Tools rule 

572 # of the workspace's chose any (``platform_sources``). Carried in the run 

573 # config, never a tool's, so no caller tool config can set it. 

574 platform_sources: PlatformSources = Field(default_factory=list) 

575 

576 

577class PipelineStep(BaseModel): 

578 id: str 

579 type: Literal["agent", "transform", "condition"] 

580 config: AgentConfig | dict[str, Any] 

581 

582 

583class AgentGraphConfig(BaseModel): 

584 """Configuration for a dynamic agent graph submitted via the API.""" 

585 

586 name: str 

587 description: str = "" 

588 knowledge_bases: list[KnowledgeBaseSpec] = [] 

589 retrieval: RetrievalConfig = Field(default_factory=RetrievalConfig) 

590 agents: dict[str, AgentConfig] = Field( 

591 default_factory=dict, 

592 description="Map of node_id → AgentConfig", 

593 ) 

594 edges: list[tuple[str, str]] = Field( 

595 default_factory=list, 

596 description="Unconditional edges as (from_node, to_node) pairs", 

597 ) 

598 start_agent: str = Field(description="Entry node ID (typically 'planner')") 

599 end_agents: list[str] = Field( 

600 default_factory=list, 

601 description="Terminal node IDs", 

602 ) 

603 conditional_routes: dict[str, dict[str, Any]] = Field( 

604 default_factory=dict, 

605 description="Conditional routing configs keyed by source node ID", 

606 ) 

607 

608 

609class SkillSpec(BaseModel): 

610 """ 

611 Execute a stored Skill's graph_definition as a dynamic agent graph. 

612 

613 ``graph_definition`` is the JSON blob from svc-core's Skill table — the 

614 caller (svc-core / svc-bff) fetches the Skill and passes its 

615 graph_definition here so svc-ai can build and run the graph without a 

616 cross-service DB query. 

617 

618 graph_definition format:: 

619 

620 { 

621 "nodes": { 

622 "<node_id>": {"agent_name": str, "config_overrides": dict} 

623 }, 

624 "edges": [["<from>", "<to>"], ...], 

625 "start_node": str, 

626 "end_nodes": [str, ...] 

627 } 

628 

629 ``system_model_override`` — when present, all agents in the graph (both 

630 system infrastructure nodes and skill worker nodes) are built using this 

631 model instead of their stored default_model_config. Format mirrors 

632 ModelConfig: {"provider": str, "model": str, "temperature": float, 

633 "max_tokens": int}. 

634 

635 ``default_model`` — the model of the agent the skill runs for. A node 

636 with no model of its own (no pin) runs on it, and so do the system nodes; 

637 a pinned node keeps its pin. Absent (a standalone run), such nodes run on 

638 the deployment's default model. 

639 """ 

640 

641 skill_id: str 

642 name: str = "" 

643 graph_definition: dict[str, Any] 

644 knowledge_bases: list[KnowledgeBaseSpec] = [] 

645 retrieval: RetrievalConfig = Field(default_factory=RetrievalConfig) 

646 output_format: str | None = None # "json" | "yaml" | "csv" | "xml" | "plain" | None 

647 output_schema: str | None = None # schema string for json/yaml formats 

648 system_model_override: dict[str, Any] | None = ( 

649 None # optional model override for all nodes 

650 ) 

651 default_model: ModelConfig | None = None 

652 # Persona of the agent the skill is attached to. Without these the skill 

653 # pipeline responds generically — the gate's trivial bypass, synthesis, and 

654 # skill nodes all read the persona from GraphState. 

655 agent_name: str = "" 

656 agent_system_prompt: str = "" 

657 # Schema v3 — values for the skill's declared ``interface.inputs``. They 

658 # seed ``GraphState.state_vars`` (validated/coerced against the declared 

659 # FieldSpecs) so nodes can bind them before any node has run. 

660 inputs: dict[str, Any] = Field(default_factory=dict) 

661 # As ``AgentConfig.clarify_scope``: set when the skill runs as an agent's 

662 # chat turn and that agent checks scope before starting. 

663 clarify_scope: bool = False 

664 # As ``AgentConfig.cost_profile``: the owning agent's, when it has one. 

665 cost_profile: CostProfile = COST_PROFILE_DEFAULT 

666 # As ``AgentConfig.lighter_model``. A skill graph's nodes keep their own 

667 # models; only the steps nobody reads move to it. 

668 lighter_model: ModelConfig | None = None 

669 # As ``AgentConfig.structured_model``. A node's own typed output stays on 

670 # the node's model; only the system steps' structured calls move. 

671 structured_model: ModelConfig | None = None 

672 # As ``AgentConfig.tool_fixtures``: an evaluation case's scripted tools, 

673 # standing in for a tool of their name wherever a node binds or calls one 

674 # (``app/agents/fixtures.py``), so an agent evaluated through its skill 

675 # graph meets the same scripted world as one evaluated without. 

676 tool_fixtures: list[ToolFixture] = Field(default_factory=list, max_length=20) 

677 # As ``AgentConfig.platform_sources``: the built-in agent's, when it 

678 # answers through a skill (a chat command). 

679 platform_sources: PlatformSources = Field(default_factory=list) 

680 

681 

682class ResumeSpec(BaseModel): 

683 """Continue a paused graph run — the batch counterpart of the stream 

684 resume endpoint. 

685 

686 ``thread_id`` is the one the paused response's ``interrupt`` carried. One 

687 payload serves both kinds of pause: an approval gate reads ``approved`` 

688 and ``feedback``, ``ask_user`` reads ``answers`` (question id → list of 

689 values). The request's spec must describe the same graph that paused. 

690 """ 

691 

692 thread_id: str 

693 approved: bool = True 

694 feedback: str = "" 

695 answers: dict[str, Any] | None = None 

696 

697 

698class AttachmentSpec(BaseModel): 

699 """A document the person attached to the conversation, as svc-core sends 

700 it (``app/util/attachment_wire.py``): its text, never pasted into 

701 ``input``.""" 

702 

703 id: str = Field(max_length=100) 

704 name: str = Field(max_length=512) 

705 mime_type: str | None = Field(default=None, max_length=255) 

706 text: str = Field(default="", max_length=MAX_ATTACHMENT_CHARS) 

707 attached_in: AttachedIn = AttachedIn.turn 

708 availability: Availability = Availability.available 

709 #: svc-core cut it to ``MAX_ATTACHMENT_CHARS``. 

710 truncated: bool = False 

711 #: For a document that is an answer — a swarm's piece, an earlier 

712 #: request's answer — the sources its text cites ``[1]``, ``[2]``…: 

713 #: each gets an id of the run's (``app/util/attachments.gather``), so a 

714 #: step that reads it cites the source itself. Malformed ones are left 

715 #: out (``attachment_wire.carried_sources``), never refused. 

716 sources: list[dict[str, Any]] = Field(default_factory=list) 

717 

718 @field_validator("sources", mode="before") 

719 @classmethod 

720 def _carried(cls, value: Any) -> list[dict[str, Any]]: 

721 return carried_sources(value) 

722 

723 

724class ExecuteRequest(BaseModel): 

725 type: Literal["model", "agent", "pipeline", "graph", "skill"] 

726 spec: ModelConfig | AgentConfig | list[PipelineStep] | AgentGraphConfig | SkillSpec 

727 # What the person wrote — empty when they sent documents without a word. 

728 # A ``<documents>`` block svc-core still pastes in front of it is lifted 

729 # out at the boundary (``app/util/attachments.gather``). 

730 input: str 

731 # The documents the conversation's messages attached, this one's and 

732 # earlier ones'. 

733 attachments: list[AttachmentSpec] = Field( 

734 default_factory=list, 

735 max_length=MAX_ATTACHMENTS, 

736 description="Documents attached to the conversation, beside the input.", 

737 ) 

738 messages: list[dict[str, Any]] = Field( 

739 default_factory=list, 

740 description="Prior conversation messages to prepend (role/content dicts).", 

741 ) 

742 session_id: str | None = None 

743 user_id: str 

744 

745 # Optional conversation continuation and agent context 

746 conversation_id: str | None = None 

747 external_agent_id: str | None = None 

748 

749 # Governance rules pre-resolved by svc-core for this request. 

750 # Policy rules are enforced on the input; audit rules on the output. 

751 rules: list[RuleSpec] = Field(default_factory=list) 

752 

753 # What produced this call, when it is not the plain ``type``. The 

754 # invocation trace records ``purpose = request.type`` by default, which 

755 # makes an evaluation cell read as a chat; a caller that knows better 

756 # says so here ("evaluation", "evaluation_judge"). 

757 purpose: str | None = Field( 

758 default=None, 

759 max_length=50, 

760 description="Recorded as the invocation's purpose instead of `type`.", 

761 ) 

762 # Ids the trace carries back to whatever asked for the call — an 

763 # evaluation, its batch, its variant. Stored on the invocation's request 

764 # snapshot so the activity feed can link a call to the run it belongs to. 

765 reference: dict[str, str] | None = Field( 

766 default=None, 

767 description="Caller-side ids stored on the invocation trace.", 

768 ) 

769 # Set to continue a run that paused on an interrupt (graph and skill 

770 # executions only); ``input`` is then what the person answered, which is 

771 # what the policy rules evaluate. 

772 resume: ResumeSpec | None = None 

773 # Whether the run reads and writes the agent's memory of this user. An 

774 # evaluation sends False: its cases are not a person's conversation, and 

775 # remembering them leaked one case's data and answers into the next (and 

776 # into the person's own chats with the agent). 

777 memory: bool = Field( 

778 default=True, 

779 description="Read and write the agent's memory of this user.", 

780 ) 

781 # Whether the run may pause to ask the person something (``ask_user``, 

782 # the scope check). A dashboard tile sends False: it refreshes on a 

783 # timer with nobody to answer, and a question it asked was cached as the 

784 # tile's answer. 

785 may_ask: bool = Field( 

786 default=True, 

787 description="Whether the run may pause to ask the person (False: unattended).", 

788 ) 

789 # How long the caller waits for the answer, less a margin. A batch run 

790 # past it is stopped and answered 504 with what it spent: svc-core had 

791 # hung up on such a run, which went on spending with nobody to read it 

792 # and nothing on the caller's ledger (``routers.agent.execute_and_persist``). 

793 time_limit_s: float | None = Field( 

794 default=None, 

795 gt=0, 

796 description="Stop a batch run after this many seconds (504).", 

797 ) 

798 

799 

800class ExecuteResponse(BaseModel): 

801 output: str 

802 usage: dict[str, Any] = {} 

803 session_id: str | None = None 

804 conversation_id: str | None = None 

805 messages: list[dict[str, Any]] = Field( 

806 default_factory=list, 

807 description="Execution trace from all agents", 

808 ) 

809 context: dict[str, Any] = Field( 

810 default_factory=dict, 

811 description="Final context from graph execution", 

812 ) 

813 citations: list[dict[str, Any]] = Field( 

814 default_factory=list, 

815 description=( 

816 "Every source the run retrieved — pipeline passages, then tool " 

817 "results — each with its ``kind`` (agents/source_ledger.TOOL_KINDS)" 

818 ), 

819 ) 

820 cited_citations: list[dict[str, Any]] = Field( 

821 default_factory=list, 

822 description=( 

823 "The citations the answer itself cites " 

824 "(agents/source_ledger.cited_citations over ``output``), in the " 

825 "shape of ``citations``: what a chat shows as the answer's sources" 

826 ), 

827 ) 

828 interrupt: dict[str, Any] | None = Field( 

829 default=None, 

830 description="HITL interrupt payload when graph is paused awaiting human approval", 

831 ) 

832 rule_events: list[dict[str, Any]] = Field( 

833 default_factory=list, 

834 description=( 

835 "Governance rule actions enforced inside svc-ai during this " 

836 "request (app.inference.rule_vocabulary's actions). Each carries " 

837 "the firing rule's identity and the phase it ran in, so svc-core " 

838 "can render and persist them alongside the rules it enforced itself." 

839 ), 

840 )