Coverage for app / services / evaluation / context.py: 96%

242 statements  

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

1""" 

2Evaluation context — what surrounds the prompt when a variant is evaluated. 

3 

4Until now an evaluation could vary two things: which model or agent answered, 

5and what system prompt it answered with. Everything else came from the stored 

6agent. So the question people actually want to ask — "how does this agent 

7behave *with* the policy knowledge attached, five turns into a conversation, 

8with the refund tool taken away" — had no answer short of building a second 

9agent and keeping the two in sync by hand. 

10 

11A **context** is that surrounding state, declared as data and applied as an 

12override at invoke time. Nothing is mutated: the stored agent is untouched, and 

13the override lives on the variant that asked for it. 

14 

15The division of labour is deliberate and is the whole mental model: 

16 

17 a variant owns the *capability* — knowledge, tools 

18 a case owns the *situation* — history, variables, data, scripted tools 

19 

20So "with and without the compliance repository" is two variants over one 

21dataset, and "the same question asked by a frustrated customer mid-complaint" 

22is one case. Merging them any other way produces a matrix nobody can read. 

23 

24Two things are deliberately absent: 

25 

26* **Rules cannot be overridden.** Governance rules apply at inference, and an 

27 evaluation that could switch them off would be a way to measure a system 

28 that is not the system anybody runs. If you want to know how a prompt behaves 

29 unrestricted, change the rule, which is itself versioned and audited. 

30* **Variables are substitution, not a language.** ``{{name}}`` is replaced with 

31 a string. There is no expression syntax, no conditionals and no loops, 

32 because the moment there are, the evaluation harness has a runtime nobody 

33 asked for and every prompt becomes a program. 

34 

35Every id in a context is re-validated against the caller's own resources before 

36it is used — a context can arrive from a generative flow, and ids from a model 

37are never trusted at a boundary. 

38""" 

39 

40from __future__ import annotations 

41 

42import json 

43import logging 

44import re 

45from dataclasses import dataclass, field 

46from typing import Any, Optional 

47from uuid import UUID 

48 

49from sqlalchemy import or_ 

50from sqlalchemy.orm import Session 

51 

52from app.db.postgres.models import ( 

53 Knowledge, 

54 KnowledgeRepository, 

55 RepositoryKnowledge, 

56) 

57from app.services import ai_client 

58from app.services import retrieval as retrieval_service 

59from app.services.knowledge import repositories 

60 

61logger = logging.getLogger(__name__) 

62 

63#: Prior turns a case may carry. Long enough for a realistic mid-conversation 

64#: state, short enough that a dataset of them still fits in a context window. 

65MAX_HISTORY_MESSAGES = 40 

66 

67#: Characters per history message, and per variable value. 

68MAX_MESSAGE_CHARS = 8000 

69MAX_VARIABLE_CHARS = 2000 

70 

71#: Variables a context may declare. 

72MAX_VARIABLES = 30 

73 

74#: Named values a case may hand the agent beside its prompt, and the 

75#: characters each may take once written out. 

76MAX_DATA_ITEMS = 40 

77MAX_DATA_VALUE_CHARS = 4000 

78 

79#: Scripted tools a case may set up, and the characters each response may take. 

80MAX_TOOL_FIXTURES = 20 

81MAX_FIXTURE_RESPONSE_CHARS = 20_000 

82TOOL_NAME_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$") 

83 

84#: How a data value with no value is shown: the question is about it being 

85#: missing, so it is named rather than dropped. 

86DATA_NOT_PROVIDED = "(not provided)" 

87 

88#: ``{{ name }}`` — the only templating there is. 

89VARIABLE_PATTERN = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}") 

90 

91_ROLES = {"user", "assistant", "system"} 

92 

93 

94class ContextError(ValueError): 

95 """Raised when a context references something the caller cannot use.""" 

96 

97 

98@dataclass 

99class EvaluationContext: 

100 """A resolved context, ready to hand to a target. 

101 

102 ``None`` and ``[]`` mean different things throughout, and the difference is 

103 the feature: ``None`` is "whatever the agent already has", ``[]`` is 

104 "explicitly nothing". Without that distinction there is no way to express 

105 the with/without comparison this exists for. 

106 """ 

107 

108 #: Knowledge base specs, or None to leave the agent's own in place. 

109 knowledge_bases: Optional[list[dict]] = None 

110 #: Tool configs, or None to leave the agent's own in place. 

111 tools: Optional[list[dict]] = None 

112 #: Prior turns, oldest first. 

113 history: list[dict] = field(default_factory=list) 

114 #: Substituted into the system prompt and the case input. 

115 variables: dict[str, str] = field(default_factory=dict) 

116 #: Named values shown to the agent beside the prompt — the figures a 

117 #: question is about. Unlike variables, nothing has to reference them: 

118 #: they are written out after the prompt, and a value of None is shown as 

119 #: not provided, because "the discount rate is missing" is a situation a 

120 #: case can be about. 

121 data: dict[str, Any] = field(default_factory=dict) 

122 #: Tools whose answers the case scripts — ``[{name, description, 

123 #: response}]``. Part of the situation, not capability: they fix what the 

124 #: world returns (a share price at a moment), so a question about live data 

125 #: has a right answer that does not move between runs. 

126 tool_fixtures: list[dict[str, Any]] = field(default_factory=list) 

127 

128 @property 

129 def is_empty(self) -> bool: 

130 return ( 

131 self.knowledge_bases is None 

132 and self.tools is None 

133 and not self.history 

134 and not self.variables 

135 and not self.data 

136 and not self.tool_fixtures 

137 ) 

138 

139 def describe(self) -> dict[str, Any]: 

140 """What this context did, recorded alongside the result. 

141 

142 A score is not interpretable without it: "0.4" means nothing unless the 

143 reader knows the run had no knowledge attached. 

144 """ 

145 described: dict[str, Any] = {} 

146 if self.knowledge_bases is not None: 

147 described["knowledge"] = [kb["name"] for kb in self.knowledge_bases] 

148 if self.tools is not None: 

149 described["tools"] = [t.get("name") for t in self.tools] 

150 if self.history: 

151 described["history_turns"] = len(self.history) 

152 if self.variables: 

153 described["variables"] = sorted(self.variables) 

154 if self.data: 

155 described["data"] = list(self.data) 

156 if self.tool_fixtures: 

157 described["tool_fixtures"] = [f["name"] for f in self.tool_fixtures] 

158 return described 

159 

160 def present(self, prompt: str) -> str: 

161 """The prompt as the agent receives it: with the case's data after it. 

162 

163 Written out rather than substituted, so a case's figures reach the 

164 agent whether or not the prompt mentions them — a question like "what 

165 is the return on this investment?" is about data it does not repeat. 

166 """ 

167 if not self.data: 

168 return prompt 

169 lines = [f"- {name}: {_data_text(value)}" for name, value in self.data.items()] 

170 return f"{prompt}\n\nData provided with this question:\n" + "\n".join(lines) 

171 

172 def render(self, text: str) -> str: 

173 """Substitute ``{{variable}}`` references in ``text``. 

174 

175 An unknown reference is left untouched rather than blanked: a prompt 

176 that happens to contain braces should survive an evaluation, and a 

177 silently emptied placeholder is the kind of thing that turns into a 

178 mystery score drop. 

179 """ 

180 if not text or not self.variables: 

181 return text 

182 return VARIABLE_PATTERN.sub( 

183 lambda match: self.variables.get(match.group(1), match.group(0)), text 

184 ) 

185 

186 

187# ── Parsing ─────────────────────────────────────────────────────────────────── 

188 

189 

190def _uuids(values: Any, label: str) -> list[UUID]: 

191 """A list of UUIDs, rejecting anything that is not one. 

192 

193 Rejects rather than skips: a context that silently dropped an unreadable 

194 knowledge id would evaluate against less than the user asked for and score 

195 it as though nothing were missing. 

196 """ 

197 if values is None: 

198 return [] 

199 if not isinstance(values, (list, tuple)): 

200 raise ContextError(f"{label} must be a list.") 

201 parsed: list[UUID] = [] 

202 for value in values: 

203 try: 

204 parsed.append(value if isinstance(value, UUID) else UUID(str(value))) 

205 except (ValueError, AttributeError, TypeError) as exc: 

206 raise ContextError(f"{label} contains an invalid id: {value!r}") from exc 

207 return parsed 

208 

209 

210def _history(values: Any) -> list[dict]: 

211 """Prior turns as role/content dicts, oldest first.""" 

212 if values is None: 

213 return [] 

214 if not isinstance(values, (list, tuple)): 

215 raise ContextError("History must be a list of messages.") 

216 if len(values) > MAX_HISTORY_MESSAGES: 

217 raise ContextError( 

218 f"History is limited to {MAX_HISTORY_MESSAGES} messages; got {len(values)}." 

219 ) 

220 messages: list[dict] = [] 

221 for entry in values: 

222 if not isinstance(entry, dict): 

223 raise ContextError("Each history message must be an object.") 

224 role = str(entry.get("role") or "").strip().lower() 

225 if role not in _ROLES: 

226 raise ContextError( 

227 f"History message role must be one of {sorted(_ROLES)}; got {role!r}." 

228 ) 

229 content = entry.get("content") 

230 if not isinstance(content, str) or not content.strip(): 

231 raise ContextError("Each history message needs text content.") 

232 if len(content) > MAX_MESSAGE_CHARS: 

233 raise ContextError( 

234 f"A history message is limited to {MAX_MESSAGE_CHARS} characters." 

235 ) 

236 messages.append({"role": role, "content": content}) 

237 return messages 

238 

239 

240def _variables(values: Any) -> dict[str, str]: 

241 if values is None: 

242 return {} 

243 if not isinstance(values, dict): 

244 raise ContextError("Variables must be an object of name to value.") 

245 if len(values) > MAX_VARIABLES: 

246 raise ContextError(f"A context is limited to {MAX_VARIABLES} variables.") 

247 variables: dict[str, str] = {} 

248 for name, value in values.items(): 

249 key = str(name).strip() 

250 if not VARIABLE_PATTERN.fullmatch("{{" + key + "}}"): 

251 raise ContextError( 

252 f"Variable name {name!r} must be a letter or underscore followed " 

253 "by letters, digits or underscores." 

254 ) 

255 text = "" if value is None else str(value) 

256 if len(text) > MAX_VARIABLE_CHARS: 

257 raise ContextError( 

258 f"Variable {key!r} is limited to {MAX_VARIABLE_CHARS} characters." 

259 ) 

260 variables[key] = text 

261 return variables 

262 

263 

264def _data_text(value: Any) -> str: 

265 if value is None or value == "": 

266 return DATA_NOT_PROVIDED 

267 if isinstance(value, (dict, list)): 

268 return json.dumps(value, ensure_ascii=False) 

269 return str(value) 

270 

271 

272def _data(values: Any) -> dict[str, Any]: 

273 """A case's data: names to scalar, list or object values, in order.""" 

274 if values is None: 

275 return {} 

276 if not isinstance(values, dict): 

277 raise ContextError("Data must be an object of name to value.") 

278 if len(values) > MAX_DATA_ITEMS: 

279 raise ContextError(f"A case is limited to {MAX_DATA_ITEMS} data values.") 

280 data: dict[str, Any] = {} 

281 for name, value in values.items(): 

282 key = str(name).strip() 

283 if not key or len(key) > 100: 

284 raise ContextError("Each data value needs a name of up to 100 characters.") 

285 if len(_data_text(value)) > MAX_DATA_VALUE_CHARS: 

286 raise ContextError( 

287 f"Data value {key!r} is limited to {MAX_DATA_VALUE_CHARS} characters." 

288 ) 

289 data[key] = value 

290 return data 

291 

292 

293def _tool_fixtures(values: Any) -> list[dict[str, Any]]: 

294 """A case's scripted tools, as svc-ai's ``ToolFixture`` takes them.""" 

295 if values is None: 

296 return [] 

297 if not isinstance(values, list): 

298 raise ContextError("Scripted tools must be a list.") 

299 if len(values) > MAX_TOOL_FIXTURES: 

300 raise ContextError(f"A case is limited to {MAX_TOOL_FIXTURES} scripted tools.") 

301 fixtures: list[dict[str, Any]] = [] 

302 seen: set[str] = set() 

303 for entry in values: 

304 if not isinstance(entry, dict): 

305 raise ContextError("Each scripted tool must be an object.") 

306 name = str(entry.get("name") or "").strip() 

307 if not TOOL_NAME_PATTERN.fullmatch(name): 

308 raise ContextError( 

309 f"Scripted tool name {name!r} must be a letter or underscore " 

310 "followed by up to 63 letters, digits or underscores." 

311 ) 

312 if name in seen: 

313 raise ContextError(f"Scripted tool {name!r} is listed twice.") 

314 seen.add(name) 

315 response = entry.get("response") 

316 if response is None: 

317 raise ContextError(f"Scripted tool {name!r} needs a response.") 

318 # An object is sent as the JSON a real tool would return. 

319 text = response if isinstance(response, str) else json.dumps(response) 

320 if len(text) > MAX_FIXTURE_RESPONSE_CHARS: 

321 raise ContextError( 

322 f"Scripted tool {name!r}'s response is limited to " 

323 f"{MAX_FIXTURE_RESPONSE_CHARS} characters." 

324 ) 

325 fixture: dict[str, Any] = {"name": name, "response": text} 

326 description = str(entry.get("description") or "").strip() 

327 if description: 

328 fixture["description"] = description[:1000] 

329 fixtures.append(fixture) 

330 return fixtures 

331 

332 

333# ── Resolution ──────────────────────────────────────────────────────────────── 

334 

335 

336def _owner_filter(model, owner): 

337 """A predicate limiting ``model`` to what ``owner``'s owner may reach. 

338 

339 A context names ids, and an id in a request body — or proposed by a 

340 generative flow — is never trusted at a boundary. Scoping every lookup by 

341 the evaluation's *own* ownership means a context can only ever attach 

342 something the evaluation could already see. 

343 

344 Scoped by the owning resource rather than by the request user, because 

345 contexts are resolved inside the background task too, where there is no 

346 request to check against. An evaluation that cannot be scoped is refused: 

347 this is access control, so it fails closed. 

348 """ 

349 for column in ("owner_user_id", "owner_organisation_id", "owner_project_id"): 

350 value = getattr(owner, column, None) 

351 if value is not None: 

352 return getattr(model, column) == value 

353 raise ContextError( 

354 "This experiment has no owner, so the resources a context names cannot " 

355 "be checked against it." 

356 ) 

357 

358 

359def _resolve_knowledge( 

360 db: Session, 

361 owner: Any, 

362 repository_ids: list[UUID], 

363 knowledge_ids: list[UUID], 

364) -> list[dict]: 

365 """Knowledge base specs for the repositories and bases a context names. 

366 

367 An id the owner cannot reach reports as *not found* rather than as 

368 forbidden: whether somebody else's repository exists is not this caller's 

369 business, and the two answers together are an existence oracle. 

370 """ 

371 resolved: dict[str, dict] = {} 

372 

373 if repository_ids: 

374 rows = ( 

375 db.query( 

376 Knowledge, 

377 KnowledgeRepository.id, 

378 KnowledgeRepository.category, 

379 KnowledgeRepository.name, 

380 ) 

381 .join( 

382 RepositoryKnowledge, 

383 RepositoryKnowledge.knowledge_id == Knowledge.id, 

384 ) 

385 .join( 

386 KnowledgeRepository, 

387 KnowledgeRepository.id == RepositoryKnowledge.repository_id, 

388 ) 

389 .filter( 

390 KnowledgeRepository.id.in_(repository_ids), 

391 # The owner's own, or a built-in one: every user may read and 

392 # grant those, so an evaluation may compare with and without 

393 # one (``system_resources.knowledge``). 

394 or_( 

395 _owner_filter(KnowledgeRepository, owner), 

396 KnowledgeRepository.is_system.is_(True), 

397 ), 

398 ) 

399 .all() 

400 ) 

401 found = {row[1] for row in rows} 

402 missing = [str(r) for r in repository_ids if r not in found] 

403 if missing: 

404 raise ContextError(f"Knowledge repository not found: {', '.join(missing)}.") 

405 # Each base as the kind of the repositories it was named through, as 

406 # an agent granted them reads it (``repositories.one_category``). 

407 kinds: dict[str, set[str]] = {} 

408 names: dict[str, set[str]] = {} 

409 for kb, _repo_id, category, repository_name in rows: 

410 kinds.setdefault(str(kb.id), set()).add(category) 

411 names.setdefault(str(kb.id), set()).add(repository_name) 

412 for kb, _repo_id, _category, _name in rows: 

413 resolved.setdefault( 

414 str(kb.id), 

415 retrieval_service.knowledge_spec( 

416 kb, 

417 category=repositories.one_category(kb.id, kinds[str(kb.id)]), 

418 repositories=names[str(kb.id)], 

419 ), 

420 ) 

421 

422 if knowledge_ids: 

423 bases = ( 

424 db.query(Knowledge) 

425 .filter( 

426 Knowledge.id.in_(knowledge_ids), 

427 or_(_owner_filter(Knowledge, owner), Knowledge.is_system.is_(True)), 

428 ) 

429 .all() 

430 ) 

431 found = {kb.id for kb in bases} 

432 missing = [str(k) for k in knowledge_ids if k not in found] 

433 if missing: 

434 raise ContextError(f"Knowledge base not found: {', '.join(missing)}.") 

435 # A base named on its own is the kind of the repositories holding it. 

436 categories = repositories.categories_of(db, [kb.id for kb in bases]) 

437 for kb in bases: 

438 resolved.setdefault( 

439 str(kb.id), 

440 retrieval_service.knowledge_spec(kb, category=categories.get(kb.id)), 

441 ) 

442 

443 specs = list(resolved.values()) 

444 # The document manifest is what lets svc-ai resolve a file the user names 

445 # even while indexing is pending — the agent path attaches it, so an 

446 # evaluation of that agent has to attach it too or it measures something 

447 # slightly different from production. 

448 manifests = retrieval_service.load_document_manifests( 

449 db, [spec["id"] for spec in specs if spec["source_type"] != "graph"] 

450 ) 

451 for spec in specs: 

452 spec["documents"] = manifests.get(spec["id"], []) 

453 return specs 

454 

455 

456def _resolve_tools(names: list[str]) -> list[dict]: 

457 """Tool configs for the built-in tools a context names. 

458 

459 Named rather than referenced by id because a context is written next to a 

460 prompt by a person choosing what the agent may reach for, and "web_search" 

461 is what they know it as — it is also the name svc-ai's registry uses, so 

462 there is nothing to look up in between. Nothing is owner-scoped here: a 

463 built-in belongs to the platform, not to a tenant. 

464 

465 An unknown name is refused rather than dropped. The whole point of a 

466 context is a controlled comparison, and a run that quietly went without the 

467 tool it said it had answers a different question from the one asked. 

468 """ 

469 if not names: 

470 return [] 

471 

472 known = _builtin_tool_names() 

473 if known is not None: 

474 unknown = [name for name in names if name not in known] 

475 if unknown: 

476 raise ContextError( 

477 f"Unknown tool(s): {', '.join(sorted(unknown))}. " 

478 f"Available: {', '.join(sorted(known))}." 

479 ) 

480 # Duplicates collapse — naming a tool twice is not asking for it twice. 

481 return [ 

482 {"name": name, "type": "builtin", "config": {}} for name in dict.fromkeys(names) 

483 ] 

484 

485 

486def _builtin_tool_names() -> set[str] | None: 

487 """Every built-in tool name svc-ai reports, or None if it could not be asked. 

488 

489 None rather than an empty set so a caller can tell "svc-ai is down" from 

490 "svc-ai has no tools": an outage must not turn every context into a 

491 validation error, and the name is checked again by svc-ai when the tool is 

492 actually bound. 

493 """ 

494 try: 

495 return { 

496 str(entry["name"]) 

497 for entry in ai_client.list_tools() or [] 

498 if isinstance(entry, dict) and entry.get("name") 

499 } 

500 except Exception: 

501 logger.warning( 

502 "Could not reach svc-ai to list built-in tools — context tool names " 

503 "are passed through unvalidated", 

504 exc_info=True, 

505 ) 

506 return None 

507 

508 

509def resolve( 

510 db: Session, spec: Optional[dict], *, owner: Any = None 

511) -> EvaluationContext: 

512 """Turn a stored context block into an :class:`EvaluationContext`. 

513 

514 ``owner`` is the experiment or suite the context belongs to; every id it 

515 names is scoped to that resource's own ownership. 

516 

517 Raises :class:`ContextError` for anything unusable, so a misconfigured 

518 context is a 422 at request time rather than a batch that quietly evaluates 

519 the wrong thing. 

520 """ 

521 if not spec: 

522 return EvaluationContext() 

523 if not isinstance(spec, dict): 

524 raise ContextError("Context must be an object.") 

525 

526 unknown = set(spec) - { 

527 "knowledge_repository_ids", 

528 "knowledge_ids", 

529 "tools", 

530 "history", 

531 "variables", 

532 } 

533 if unknown: 

534 # Loudly, because a typo'd key would otherwise be a context that says it 

535 # attached knowledge and did not. 

536 raise ContextError(f"Unknown context field(s): {', '.join(sorted(unknown))}.") 

537 

538 repository_ids = _uuids( 

539 spec.get("knowledge_repository_ids"), "knowledge_repository_ids" 

540 ) 

541 knowledge_ids = _uuids(spec.get("knowledge_ids"), "knowledge_ids") 

542 

543 knowledge: Optional[list[dict]] = None 

544 if "knowledge_repository_ids" in spec or "knowledge_ids" in spec: 

545 # Present but empty is "explicitly no knowledge" — the other half of the 

546 # with/without comparison. 

547 knowledge = _resolve_knowledge(db, owner, repository_ids, knowledge_ids) 

548 

549 tools: Optional[list[dict]] = None 

550 if "tools" in spec: 

551 raw = spec.get("tools") 

552 if raw is not None and not isinstance(raw, (list, tuple)): 

553 raise ContextError("Tools must be a list of tool names.") 

554 tools = _resolve_tools([str(name) for name in (raw or [])]) 

555 

556 return EvaluationContext( 

557 knowledge_bases=knowledge, 

558 tools=tools, 

559 history=_history(spec.get("history")), 

560 variables=_variables(spec.get("variables")), 

561 ) 

562 

563 

564def parse_situation(spec: Optional[dict]) -> EvaluationContext: 

565 """The *situation* half of a context — history, variables and data only. 

566 

567 This is what a case may declare. Capability (knowledge, tools) is 

568 deliberately not parsed here and not merely ignored downstream: those 

569 require an owner-scoped lookup, and there is no owner in scope when a case 

570 is read. Naming the boundary as its own function is what stops a later 

571 change quietly widening it. 

572 

573 Raises :class:`ContextError` like :func:`resolve`; the caller decides 

574 whether one bad case fails the run. 

575 """ 

576 if not spec: 

577 return EvaluationContext() 

578 if not isinstance(spec, dict): 

579 raise ContextError("Context must be an object.") 

580 return EvaluationContext( 

581 history=_history(spec.get("history")), 

582 variables=_variables(spec.get("variables")), 

583 data=_data(spec.get("data")), 

584 tool_fixtures=_tool_fixtures(spec.get("tool_fixtures")), 

585 ) 

586 

587 

588def merge(variant: EvaluationContext, case: EvaluationContext) -> EvaluationContext: 

589 """Combine a variant's context with a case's. 

590 

591 The variant owns capability and the case owns situation, so knowledge and 

592 tools come from the variant and history from the case. Variables merge, with 

593 the case winning — a dataset-wide default that one case overrides is the 

594 obvious thing to want, and the reverse never is. 

595 """ 

596 return EvaluationContext( 

597 knowledge_bases=variant.knowledge_bases, 

598 tools=variant.tools, 

599 history=case.history or variant.history, 

600 variables={**variant.variables, **case.variables}, 

601 # A case's own: a variant has no data (``resolve`` refuses the key). 

602 data=case.data, 

603 tool_fixtures=case.tool_fixtures, 

604 )