Coverage for app / services / scenarios / schema.py: 99%

202 statements  

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

1"""A scenario file: the agents to make, the conversations to have with them, 

2the swarms to send on tasks, and what each turn and swarm run is expected to 

3do (docs/guides/scenario-runs.md). 

4 

5Written by hand (or by Claude) and uploaded, so validated like any input at 

6a boundary: ``extra="forbid"`` everywhere, a repository named by a built-in's 

7exact name, and every expectation in its owner's vocabulary — the quality 

8check's outcomes, the recommendation kinds, svc-ai's mix profiles, tools and 

9fence kinds (pinned to ``svc-ai app/knowledge/mix.py`` and 

10``app/tools/registry.py`` by the tests). A file that fails is refused whole, 

11with what is wrong, before anything is made. 

12""" 

13 

14from __future__ import annotations 

15 

16import hashlib 

17import json 

18from typing import Any, Literal 

19 

20from pydantic import ( 

21 BaseModel, 

22 ConfigDict, 

23 Field, 

24 ValidationInfo, 

25 field_validator, 

26 model_validator, 

27) 

28 

29from app.db.postgres.enums import SwarmEnum 

30from app.services.quality_check import Outcome 

31from app.services.scenarios.artifacts import ArtifactKind, VisualKind 

32from app.services.swarms.roster import MAX_NOTE_CHARS 

33from app.services.swarms.schemas import Approach 

34from app.util.cost_profiles import CostProfile 

35from app.util.knowledge_categories import KnowledgeCategory 

36 

37SCHEMA_VERSION = 1 

38#: The most turns a run asks, all conversations together: each is an 

39#: ordinary chat turn, governed and paid for like one. 

40MAX_TURNS = 60 

41MAX_AGENTS = 10 

42#: The most swarm runs a scenario makes, all swarms together: each is a 

43#: whole swarm run, many agent turns. 

44MAX_SWARM_RUNS = 8 

45#: Follow-ups one run of a scenario may have. 

46MAX_FOLLOW_UPS = 3 

47MAX_SWARMS = 4 

48MAX_PROMPT_CHARS = 8000 

49MAX_INSTRUCTIONS_CHARS = 20000 

50 

51#: The input profiles svc-ai's knowledge mix reads a turn as (svc-ai 

52#: ``app/knowledge/mix.py`` ``Profile``), which a turn may expect. 

53MIX_PROFILES: tuple[str, ...] = ( 

54 "triage_failed", 

55 "current_web", 

56 "analysis_current", 

57 "current", 

58 "analysis", 

59 "lookup", 

60) 

61 

62#: The tools a turn may expect called, or not: svc-ai's built-ins 

63#: (``app/tools/registry.py`` ``_BUILTIN_TOOLS``), then the knowledge tools 

64#: an agent with knowledge holds and the attachment tools a conversation with 

65#: a long document gets. 

66TOOL_NAMES: tuple[str, ...] = ( 

67 "current_time", 

68 "calculate", 

69 "validate_code_syntax", 

70 "web_search", 

71 "url_fetch", 

72 "geocode", 

73 "render_chart", 

74 "render_plot", 

75 "render_mermaid", 

76 "render_graph", 

77 "render_map", 

78 "render_document", 

79 "ask_user", 

80 "query_knowledge_base", 

81 "query_knowledge_graph", 

82 "search_knowledge", 

83 "read_document", 

84 "list_documents", 

85 "explore_graph", 

86 "read_attachment", 

87 "search_attachments", 

88) 

89 

90ASK_TOOL = "ask_user" 

91 

92Key = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$") 

93 

94 

95class _Strict(BaseModel): 

96 model_config = ConfigDict(extra="forbid") 

97 

98 

99class DocumentExpect(_Strict): 

100 """What the turn's document should be: its answer's ```document fence, 

101 rendered to PDF as its download is.""" 

102 

103 #: It renders to a PDF. 

104 pdf: bool = True 

105 min_pages: int | None = Field(default=None, ge=1) 

106 #: Images its PDF draws (stored when it was made). 

107 min_images: int | None = Field(default=None, ge=0) 

108 #: Every image its text links was embedded. 

109 all_images: bool = False 

110 #: Kinds of visual its body should hold, each drawn in its PDF. 

111 visuals: list[VisualKind] = [] 

112 

113 

114class TurnExpect(_Strict): 

115 """What a turn should do. Each is checked after the run and recorded, 

116 passed or not; none fails the run (``checks.py``).""" 

117 

118 #: The knowledge mix's profile (svc-ai ``knowledge.mix``). 

119 profile: str | None = None 

120 #: Kinds of knowledge that should, and should not, have been searched. 

121 searched: list[KnowledgeCategory] = [] 

122 not_searched: list[KnowledgeCategory] = [] 

123 #: Built-in repositories the answer should, and should not, cite. 

124 cites: list[str] = [] 

125 not_cites: list[str] = [] 

126 #: Quality check outcomes any of which is acceptable. 

127 quality: list[Outcome] = [] 

128 #: Tools that should have been called and done their work, and tools 

129 #: that should not have been called at all. 

130 tools: list[str] = [] 

131 not_tools: list[str] = [] 

132 #: Fence kinds the answer should hold, each well-formed and made by its 

133 #: render tool, and kinds it should not hold. 

134 artifacts: list[ArtifactKind] = [] 

135 not_artifacts: list[ArtifactKind] = [] 

136 document: DocumentExpect | None = None 

137 #: True: the turn paused to ask the person. False: it did not. 

138 asks: bool | None = None 

139 #: The command target the turn ran, by its slug (``research-brief``). 

140 command: str | None = Field(default=None, max_length=80) 

141 

142 @field_validator("profile") 

143 @classmethod 

144 def _a_profile(cls, value: str | None) -> str | None: 

145 if value is not None and value not in MIX_PROFILES: 

146 raise ValueError(f"profile must be one of: {', '.join(MIX_PROFILES)}") 

147 return value 

148 

149 @field_validator("tools", "not_tools") 

150 @classmethod 

151 def _real_tools(cls, value: list[str], info: ValidationInfo) -> list[str]: 

152 unknown = [name for name in value if name not in TOOL_NAMES] 

153 if unknown: 

154 raise ValueError( 

155 f"not a tool: {', '.join(unknown)}. Choose from: {', '.join(TOOL_NAMES)}" 

156 ) 

157 if info.field_name == "tools" and ASK_TOOL in value: 

158 # Asking pauses the turn rather than returning a result. 

159 raise ValueError(f"{ASK_TOOL} pauses the turn: expect asks: true instead") 

160 return value 

161 

162 

163#: What a run does with a pause the file wrote no answers for: ``leave`` it 

164#: unanswered (the turn ends there, unmeasured), or ``answer`` it as a 

165#: person with no preference would (``driver.default_answers``). 

166PauseHandling = Literal["leave", "answer"] 

167 

168 

169class Turn(_Strict): 

170 prompt: str = Field(min_length=1, max_length=MAX_PROMPT_CHARS) 

171 #: The answers to give if the agent pauses to ask (field id → value); 

172 #: without them a pause is handled as the file's ``pauses`` says. 

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

174 #: A chat command's form values (field id → value), sent beside the 

175 #: prompt as fe-core's command form sends them. 

176 command_inputs: dict[str, Any] | None = None 

177 expect: TurnExpect = TurnExpect() 

178 

179 

180class Conversation(_Strict): 

181 key: str = Key 

182 #: The ``key`` of the agent it is had with. 

183 agent: str 

184 turns: list[Turn] = Field(min_length=1) 

185 

186 

187class AgentExpect(_Strict): 

188 """What an agent's page should offer, read once its turns are done.""" 

189 

190 #: Per kind of knowledge it lacks, the built-in its context panel should 

191 #: suggest first (``agent_context``), read before any turn. 

192 suggests_first: dict[KnowledgeCategory, str] = {} 

193 #: Recommendation kinds that should be offered for it after its turns. 

194 recommends: list[str] = [] 

195 

196 

197class AgentSpec(_Strict): 

198 key: str = Key 

199 name: str = Field(min_length=1, max_length=120) 

200 description: str = Field(default="", max_length=2000) 

201 instructions: str = Field(default="", max_length=MAX_INSTRUCTIONS_CHARS) 

202 #: A catalogue model's name (``model_name``), or None for the 

203 #: deployment's default, as an agent made without one has. 

204 model: str | None = None 

205 cost_profile: CostProfile = CostProfile.thorough 

206 #: Off by default: a scripted run has nobody to ask. 

207 clarify_scope: bool = False 

208 #: Built-in repositories to grant, by their exact names. 

209 repositories: list[str] = [] 

210 expect: AgentExpect = AgentExpect() 

211 

212 

213class SwarmMemberSpec(_Strict): 

214 """One roster entry: an agent of the file in one of the shape's roles.""" 

215 

216 role: str = Field(min_length=1, max_length=40) 

217 #: The ``key`` of the agent. 

218 agent: str 

219 note: str = Field(default="", max_length=MAX_NOTE_CHARS) 

220 spawn: bool = False 

221 

222 

223class SwarmRunExpect(_Strict): 

224 """What a swarm run should come to. Each is checked after the run and 

225 recorded, passed or not (``checks.py``).""" 

226 

227 #: Statuses any of which is acceptable. 

228 status: list[SwarmEnum.RunStatus] = [] 

229 #: It answered, from all or part of its work. 

230 answered: bool | None = None 

231 #: How its lead planned the work (a shape that plans). 

232 approach: Approach | None = None 

233 #: How many pieces of work its plan held, at least and at most. 

234 min_pieces: int | None = Field(default=None, ge=0) 

235 max_pieces: int | None = Field(default=None, ge=0) 

236 #: Kinds of task the run should hold (a routing, votes…). 

237 kinds: list[SwarmEnum.TaskKind] = [] 

238 #: The most it should have spent, as a budget counts it. 

239 max_cost_usd: float | None = Field(default=None, gt=0) 

240 #: Its answer cites a page or a document — a source a piece read — not 

241 #: only the team's own pieces (``swarms`` sources carried through). 

242 cites_pages: bool | None = None 

243 #: For a follow-up: how many of its plan's pieces build on pieces of the 

244 #: request before, at least. 

245 min_builds_on: int | None = Field(default=None, ge=0) 

246 #: For a follow-up: its answer cites a source an earlier request of its 

247 #: thread cited — carried through, not found again or lost. 

248 cites_carried: bool | None = None 

249 

250 

251class FollowUpSpec(_Strict): 

252 """A follow-up of the run before it in its thread (``engine.follow_up``): 

253 the swarm sent on the next request, building on what the thread did.""" 

254 

255 task: str = Field(min_length=1, max_length=MAX_PROMPT_CHARS) 

256 budget_usd: float | None = Field(default=None, gt=0) 

257 time_cap_s: int | None = Field(default=None, gt=0) 

258 expect: SwarmRunExpect = SwarmRunExpect() 

259 

260 

261class SwarmRunSpec(_Strict): 

262 task: str = Field(min_length=1, max_length=MAX_PROMPT_CHARS) 

263 budget_usd: float | None = Field(default=None, gt=0) 

264 time_cap_s: int | None = Field(default=None, gt=0) 

265 expect: SwarmRunExpect = SwarmRunExpect() 

266 #: Follow-ups sent in turn once it has finished, each of the one before. 

267 follow_ups: list[FollowUpSpec] = Field(default=[], max_length=MAX_FOLLOW_UPS) 

268 

269 

270class SwarmSpec(_Strict): 

271 """A swarm made of the file's agents, and the tasks to send it on — 

272 each run unattended (no plan to approve, no questions).""" 

273 

274 key: str = Key 

275 name: str = Field(min_length=1, max_length=120) 

276 #: The shape's key (``GET /app/swarms/topologies``). 

277 topology: str 

278 params: dict[str, Any] = {} 

279 roster: list[SwarmMemberSpec] = Field(min_length=1) 

280 runs: list[SwarmRunSpec] = Field(min_length=1) 

281 

282 @field_validator("topology") 

283 @classmethod 

284 def _a_shape(cls, value: str) -> str: 

285 from app.services.swarms import topologies 

286 

287 if topologies.get(value) is None: 

288 raise ValueError( 

289 f"not a shape: {value}. Choose from: {', '.join(topologies.keys())}" 

290 ) 

291 return value 

292 

293 

294class ScenarioFile(_Strict): 

295 schema_version: Literal[1] = Field(alias="schema") 

296 name: str = Field(min_length=1, max_length=80) 

297 description: str = Field(default="", max_length=4000) 

298 pauses: PauseHandling = "leave" 

299 agents: list[AgentSpec] = Field(min_length=1, max_length=MAX_AGENTS) 

300 conversations: list[Conversation] = [] 

301 swarms: list[SwarmSpec] = Field(default=[], max_length=MAX_SWARMS) 

302 

303 model_config = ConfigDict(extra="forbid", populate_by_name=True) 

304 

305 @model_validator(mode="after") 

306 def _consistent(self) -> ScenarioFile: 

307 agent_keys = [a.key for a in self.agents] 

308 if len(set(agent_keys)) != len(agent_keys): 

309 raise ValueError("agent keys must be unique") 

310 conversation_keys = [c.key for c in self.conversations] 

311 if len(set(conversation_keys)) != len(conversation_keys): 

312 raise ValueError("conversation keys must be unique") 

313 for conversation in self.conversations: 

314 if conversation.agent not in agent_keys: 

315 raise ValueError( 

316 f"conversation {conversation.key!r} names agent " 

317 f"{conversation.agent!r}, which the file does not define" 

318 ) 

319 if self.turn_count > MAX_TURNS: 

320 raise ValueError(f"a scenario asks at most {MAX_TURNS} turns") 

321 if not self.conversations and not self.swarms: 

322 raise ValueError("a scenario has a conversation or a swarm, at least") 

323 swarm_keys = [s.key for s in self.swarms] 

324 if len(set(swarm_keys)) != len(swarm_keys): 

325 raise ValueError("swarm keys must be unique") 

326 for swarm in self.swarms: 

327 for member in swarm.roster: 

328 if member.agent not in agent_keys: 

329 raise ValueError( 

330 f"swarm {swarm.key!r} names agent {member.agent!r}, " 

331 "which the file does not define" 

332 ) 

333 if self.swarm_run_count > MAX_SWARM_RUNS: 

334 raise ValueError(f"a scenario makes at most {MAX_SWARM_RUNS} swarm runs") 

335 return self 

336 

337 @property 

338 def turn_count(self) -> int: 

339 return sum(len(c.turns) for c in self.conversations) 

340 

341 @property 

342 def swarm_run_count(self) -> int: 

343 """Swarm runs, each follow-up one.""" 

344 return sum(1 + len(r.follow_ups) for s in self.swarms for r in s.runs) 

345 

346 @property 

347 def step_count(self) -> int: 

348 """Turns and swarm runs: what a run's progress counts.""" 

349 return self.turn_count + self.swarm_run_count 

350 

351 def agent(self, key: str) -> AgentSpec: 

352 return next(a for a in self.agents if a.key == key) 

353 

354 def document(self) -> dict[str, Any]: 

355 """The file as validated, for the run's record.""" 

356 return self.model_dump(mode="json", by_alias=True) 

357 

358 def sha256(self) -> str: 

359 """The digest of the validated file, so two runs of one file say so.""" 

360 canonical = json.dumps(self.document(), sort_keys=True, separators=(",", ":")) 

361 return hashlib.sha256(canonical.encode()).hexdigest() 

362 

363 

364class ScenarioInvalid(ValueError): 

365 """A scenario that cannot run as written; its message says why.""" 

366 

367 

368def parse(document: Any) -> ScenarioFile: 

369 """A scenario from its JSON, or ``ScenarioInvalid`` naming every problem.""" 

370 from pydantic import ValidationError 

371 

372 try: 

373 return ScenarioFile.model_validate(document) 

374 except ValidationError as exc: 

375 problems = "; ".join( 

376 f"{'.'.join(str(p) for p in e['loc']) or 'file'}: {e['msg']}" 

377 for e in exc.errors() 

378 ) 

379 raise ScenarioInvalid(problems) from exc 

380 

381 

382def resolve_repositories(scenario: ScenarioFile, settings: Any = None) -> dict: 

383 """``{name: BuiltInRepository}`` for every repository the file grants, 

384 or ``ScenarioInvalid`` naming the ones that are no built-in a user may 

385 grant here (with the names that are).""" 

386 from app.services.system_resources import knowledge as built_in 

387 

388 grantable = {r.name: r for r in built_in.grantable(settings)} 

389 named = {name for agent in scenario.agents for name in agent.repositories} 

390 unknown = sorted(named - set(grantable)) 

391 if unknown: 

392 raise ScenarioInvalid( 

393 f"Not a built-in repository that can be granted here: " 

394 f"{', '.join(unknown)}. Choose from: {', '.join(sorted(grantable))}." 

395 ) 

396 return {name: grantable[name] for name in named} 

397 

398 

399def check_recommendation_kinds(scenario: ScenarioFile) -> None: 

400 """``ScenarioInvalid`` for an expected recommendation kind that is no 

401 kind (``knowledge/recommendations``).""" 

402 from app.services.knowledge import recommendations 

403 

404 known = {k.key for k in recommendations.kinds()} 

405 wrong = sorted( 

406 {kind for agent in scenario.agents for kind in agent.expect.recommends} - known 

407 ) 

408 if wrong: 

409 raise ScenarioInvalid( 

410 f"Not a recommendation kind: {', '.join(wrong)}. " 

411 f"Choose from: {', '.join(sorted(known))}." 

412 ) 

413 

414 

415def load(document: Any, settings: Any = None) -> tuple[ScenarioFile, dict]: 

416 """Validate a scenario whole: its shape, its repositories and its 

417 expected recommendation kinds. Returns it with its repositories.""" 

418 scenario = parse(document) 

419 repositories = resolve_repositories(scenario, settings) 

420 check_recommendation_kinds(scenario) 

421 return scenario, repositories