Coverage for app / services / evaluation / optimiser.py: 56%
196 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Automatic prompt optimisation.
4Given a starting prompt and a scored dataset, the optimiser iterates:
61. Evaluate the current best prompt against the dataset.
72. Show a proposer model the prompt, the grading criteria, and the cases it
8 got *wrong* (with the grader's reasons).
93. Ask for N rewritten candidate prompts.
104. Evaluate every candidate on the same cases and keep the winner.
12Each round's candidates are persisted as ordinary
13:class:`ExperimentVariant` rows and each evaluation as an ordinary experiment
14batch, so an optimisation run is inspectable with exactly the same UI as a
15hand-built experiment — and the winning prompt can be promoted onto the agent
16it came from.
17"""
19from __future__ import annotations
21import logging
22from dataclasses import dataclass
23from typing import Any, Callable, Optional
24from uuid import UUID, uuid4
26from pydantic import Field, OnErrorOmit
27from sqlalchemy.orm import Session
29from app.db.postgres.engine import SessionLocal
30from app.db.postgres.enums import RunnableEnum, UsageEnum
31from app.db.postgres.models import Experiment, ExperimentVariant
32from app.services import usage as usage_service
33from app.services.evaluation import runner
34from app.services.evaluation.criteria import as_text as criteria_as_text
35from app.services.evaluation.dataset import DatasetCase, cases_from_dataset
36from app.services.evaluation.targets import (
37 ExecutionTarget,
38 build_target,
39 invoke_structured,
40 resolve_default_judge_target,
41)
42from app.util.model_output import ModelOutput
43from app.util.time import aware_utcnow
45logger = logging.getLogger(__name__)
47# Bounds on the search. The cost of a round is
48# ``candidates × cases`` provider calls, so both are capped.
49MAX_ROUNDS = 5
50MAX_CANDIDATES_PER_ROUND = 5
51DEFAULT_ROUNDS = 3
52DEFAULT_CANDIDATES = 3
54# How many failing cases to show the proposer. Enough signal to spot a pattern
55# without burying the prompt itself in transcript.
56MAX_FAILURE_EXAMPLES = 6
57MAX_EXAMPLE_CHARS = 600
59PROPOSER_SYSTEM_PROMPT = (
60 "You are a prompt engineer. You improve a system prompt so that it scores "
61 "better on a fixed set of evaluation cases.\n\n"
62 "You are given the current system prompt, the grading criteria, the "
63 "current score, and examples of cases the prompt handled badly along with "
64 "the grader's reasoning.\n\n"
65 "Rules:\n"
66 "- Fix the causes of the observed failures. Do not rewrite for style.\n"
67 "- Never mention the evaluation, the grader, or the example cases in the "
68 "prompt you write, and never hard-code an answer to a specific case — the "
69 "prompt is graded on held-out inputs too.\n"
70 "- Keep the prompt's original task and persona intact.\n"
71 "- Each candidate must take a genuinely different approach from the "
72 "others, not be a reworded copy."
73)
76class ProposedCandidate(ModelOutput):
77 """One rewritten system prompt, as the proposer writes it."""
79 name: str = Field(default="", description="A short label naming the change")
80 prompt: str = Field(description="The full rewritten system prompt")
81 # ``change``, not ``rationale``: a field named for a model's reasoning
82 # can be refused (``RESERVED_FIELD_NAMES``). Stored as the rationale.
83 change: str = Field(
84 default="", description="One sentence on what you changed and why"
85 )
88class ProposerReply(ModelOutput):
89 """What the proposer is asked to fill."""
91 candidates: list[OnErrorOmit[ProposedCandidate]] = Field(
92 description="The candidate prompts, each a different approach"
93 )
96@dataclass
97class Candidate:
98 """One proposed prompt, before it has been evaluated."""
100 name: str
101 prompt: str
102 rationale: str = ""
105class OptimisationError(ValueError):
106 """Raised when an optimisation run cannot be started."""
109def start_optimisation(
110 db: Session,
111 experiment: Experiment,
112 *,
113 base_variant_id: UUID,
114 rounds: int = DEFAULT_ROUNDS,
115 candidates_per_round: int = DEFAULT_CANDIDATES,
116 instructions: str = "",
117) -> str:
118 """Record a queued optimisation on the experiment and return its id.
120 Validation happens here, on the request thread, so a misconfigured run is
121 a 422 rather than a background failure the user has to go looking for.
122 """
123 base = db.get(ExperimentVariant, base_variant_id)
124 if base is None or base.experiment_id != experiment.id:
125 raise OptimisationError("Base variant not found on this experiment.")
126 if not (base.prompt or "").strip():
127 raise OptimisationError(
128 "The base variant has no prompt to optimise. Add a system prompt first."
129 )
131 config = dict(experiment.config or {})
132 # Raises DatasetError for an unusable dataset — surfaced as a 422 upstream.
133 cases = cases_from_dataset(db, experiment.dataset_id)
135 if runner.scoring_config(experiment)["scorer"] == "manual":
136 raise OptimisationError(
137 "Optimisation needs an automatic scorer. Set the experiment's scorer "
138 "to something other than 'manual' first."
139 )
141 rounds = max(1, min(int(rounds or DEFAULT_ROUNDS), MAX_ROUNDS))
142 candidates_per_round = max(
143 1,
144 min(int(candidates_per_round or DEFAULT_CANDIDATES), MAX_CANDIDATES_PER_ROUND),
145 )
147 state = {
148 "id": str(uuid4()),
149 "status": RunnableEnum.Status.queued.value,
150 "created_at": aware_utcnow().isoformat(),
151 "base_variant_id": str(base_variant_id),
152 "rounds": rounds,
153 "candidates_per_round": candidates_per_round,
154 "dataset": {"dataset_id": str(experiment.dataset_id)},
155 "instructions": instructions,
156 "case_count": len(cases),
157 "history": [],
158 "best": None,
159 }
160 experiment.config = {**config, "optimisation": state}
161 db.commit()
162 return state["id"]
165def execute_optimisation(experiment_id: UUID, optimisation_id: str) -> None:
166 """Background task: run the optimisation loop to completion."""
167 db = SessionLocal()
168 try:
169 experiment = db.get(Experiment, experiment_id)
170 if experiment is None:
171 return
172 state = dict((experiment.config or {}).get("optimisation") or {})
173 if state.get("id") != optimisation_id:
174 logger.warning(
175 "Optimisation %s superseded before it started", optimisation_id
176 )
177 return
179 _patch(
180 db, experiment_id, optimisation_id, status=RunnableEnum.Status.running.value
181 )
183 config = dict(experiment.config or {})
184 cases = cases_from_dataset(db, experiment.dataset_id)
185 default_scorer, scorer_config, judge_fn = runner._prepare_scoring(
186 db, runner.scoring_config(experiment), owner=experiment
187 )
189 # Governed and attributed like the judge (owned by the evaluation),
190 # so its calls meet the workspace's budgets: it used to run with no
191 # rules at all, and no budget could stop it.
192 proposer = resolve_default_judge_target(
193 db, config.get("proposer"), owner=experiment
194 )
195 if proposer is None:
196 raise OptimisationError("No model available to propose prompt candidates.")
197 # Proposals need variety across candidates, so unlike the grader the
198 # proposer runs warm.
199 proposer.temperature = 0.8
200 proposer.max_tokens = 2048
201 proposer.config["temperature"] = 0.8
202 proposer.config["max_tokens"] = 2048
204 base_variant = db.get(ExperimentVariant, UUID(state["base_variant_id"]))
205 target_spec = (base_variant.config or {}).get("target")
206 if not target_spec:
207 raise OptimisationError(
208 "The base variant has no model or agent configured."
209 )
211 current = base_variant
212 current_score = _evaluate(
213 db,
214 experiment_id,
215 {
216 str(current.id): (
217 build_target(target_spec, db, owner=experiment),
218 current.prompt or "",
219 )
220 },
221 cases,
222 default_scorer,
223 scorer_config,
224 judge_fn,
225 config,
226 batch_id=UUID(optimisation_id),
227 )[str(current.id)]
228 best = {
229 "variant_id": str(current.id),
230 "name": current.name,
231 "prompt": current.prompt,
232 "mean_score": current_score["mean_score"],
233 "pass_rate": current_score["pass_rate"],
234 "round": 0,
235 }
236 history = [
237 {
238 "round": 0,
239 "label": "Baseline",
240 "results": [
241 {
242 **current_score,
243 "variant_id": str(current.id),
244 "name": current.name,
245 }
246 ],
247 "best_variant_id": str(current.id),
248 }
249 ]
250 _patch(db, experiment_id, optimisation_id, best=best, history=history)
252 for round_no in range(1, int(state["rounds"]) + 1):
253 if _cancelled(db, experiment_id, optimisation_id):
254 _patch(
255 db,
256 experiment_id,
257 optimisation_id,
258 status=RunnableEnum.Status.cancelled.value,
259 finished_at=aware_utcnow().isoformat(),
260 )
261 return
263 failures = _failing_examples(
264 db,
265 experiment_id,
266 cases,
267 current,
268 target_spec,
269 default_scorer,
270 scorer_config,
271 judge_fn,
272 config,
273 )
274 proposals = _propose(
275 ledger=lambda invocation: usage_service.record_measured(
276 db,
277 owner_user_id=experiment.owner_user_id,
278 execution_type="evaluation",
279 source_type=UsageEnum.Source.experiment,
280 source_id=experiment.id,
281 measured=invocation.usage,
282 owner_project_id=experiment.owner_project_id,
283 owner_organisation_id=experiment.owner_organisation_id,
284 failed=not invocation.ok,
285 latency_ms=invocation.latency_ms,
286 ),
287 proposer=proposer,
288 prompt=current.prompt or "",
289 criteria=_criteria(cases, default_scorer),
290 score=best["mean_score"],
291 failures=failures,
292 count=int(state["candidates_per_round"]),
293 instructions=state.get("instructions") or "",
294 )
295 if not proposals:
296 logger.info(
297 "Optimisation %s: no candidates in round %d",
298 optimisation_id,
299 round_no,
300 )
301 break
303 new_variants: list[ExperimentVariant] = []
304 for candidate in proposals:
305 variant = ExperimentVariant(
306 experiment_id=experiment_id,
307 name=f"R{round_no} · {candidate.name}"[:255],
308 prompt=candidate.prompt,
309 config={
310 "target": target_spec,
311 "optimisation": {
312 "id": optimisation_id,
313 "round": round_no,
314 "parent_variant_id": str(current.id),
315 "rationale": candidate.rationale,
316 },
317 },
318 )
319 db.add(variant)
320 new_variants.append(variant)
321 db.commit()
322 for variant in new_variants:
323 db.refresh(variant)
325 scores = _evaluate(
326 db,
327 experiment_id,
328 {
329 str(v.id): (
330 build_target(target_spec, db, owner=experiment),
331 v.prompt or "",
332 )
333 for v in new_variants
334 },
335 cases,
336 default_scorer,
337 scorer_config,
338 judge_fn,
339 config,
340 batch_id=UUID(optimisation_id),
341 )
343 round_results = [
344 {
345 **scores[str(v.id)],
346 "variant_id": str(v.id),
347 "name": v.name,
348 "rationale": (v.config or {})
349 .get("optimisation", {})
350 .get("rationale"),
351 }
352 for v in new_variants
353 ]
354 winner = max(
355 round_results,
356 key=lambda r: (
357 r.get("mean_score") if r.get("mean_score") is not None else -1,
358 r.get("pass_rate") if r.get("pass_rate") is not None else -1,
359 ),
360 )
361 history.append(
362 {
363 "round": round_no,
364 "label": f"Round {round_no}",
365 "results": round_results,
366 "best_variant_id": winner["variant_id"],
367 }
368 )
370 improved = (winner.get("mean_score") or -1) > (best.get("mean_score") or -1)
371 if improved:
372 best = {
373 "variant_id": winner["variant_id"],
374 "name": winner["name"],
375 "prompt": next(
376 v.prompt
377 for v in new_variants
378 if str(v.id) == winner["variant_id"]
379 ),
380 "mean_score": winner.get("mean_score"),
381 "pass_rate": winner.get("pass_rate"),
382 "round": round_no,
383 }
384 current = next(
385 v for v in new_variants if str(v.id) == winner["variant_id"]
386 )
387 else:
388 # Keep searching from the incumbent rather than a worse prompt,
389 # so a bad round cannot drag the next round's proposals down.
390 logger.info(
391 "Optimisation %s round %d did not beat the incumbent",
392 optimisation_id,
393 round_no,
394 )
396 _patch(db, experiment_id, optimisation_id, best=best, history=history)
398 _patch(
399 db,
400 experiment_id,
401 optimisation_id,
402 status=RunnableEnum.Status.completed.value,
403 finished_at=aware_utcnow().isoformat(),
404 best=best,
405 history=history,
406 )
407 logger.info(
408 "Optimisation %s complete: best mean score %s (round %s)",
409 optimisation_id,
410 best.get("mean_score"),
411 best.get("round"),
412 )
413 except Exception as exc: # noqa: BLE001 — the failure must land on the state
414 logger.exception("Optimisation %s failed", optimisation_id)
415 db.rollback()
416 _patch(
417 db,
418 experiment_id,
419 optimisation_id,
420 status=RunnableEnum.Status.failed.value,
421 finished_at=aware_utcnow().isoformat(),
422 error=f"{type(exc).__name__}: {exc}",
423 )
424 finally:
425 db.close()
428# ── Internals ─────────────────────────────────────────────────────────────────
431def _criteria(cases: list[DatasetCase], scorer: str) -> str:
432 """What the proposer is told a good answer is — the dataset's criteria.
434 Read off the cases (each carries the dataset's), never the scorer, whose
435 settings no longer say what is correct. A case's own criteria reach the
436 proposer through the judge's reasons on its failing examples.
437 """
438 shared = next((c.dataset_criteria for c in cases if c.dataset_criteria), None)
439 if shared:
440 return criteria_as_text(shared)
441 return f"Graded by the '{scorer}' scorer against each case's label."
444def _evaluate(
445 db: Session,
446 experiment_id: UUID,
447 targets: dict[str, tuple[ExecutionTarget, str]],
448 cases: list[DatasetCase],
449 default_scorer: str,
450 scorer_config: dict,
451 judge_fn,
452 config: dict,
453 batch_id: Optional[UUID] = None,
454) -> dict[str, dict[str, Any]]:
455 """Score a set of variants on the dataset, persisting the runs.
457 ``batch_id`` groups the rows under the optimisation that produced them, so
458 they stay distinguishable from a manually-triggered batch.
459 """
460 from app.db.postgres.models import ExperimentRun
462 # Candidate scoring is evaluation spend like any batch — cells and judge
463 # both — on the ledger as each call finishes, so a cap sees it mid-round.
464 owner = db.get(Experiment, experiment_id)
465 if owner is not None:
466 runner.ledger_as_it_goes(db, owner, targets, judge_fn)
467 started = aware_utcnow()
468 outcomes = runner._execute_matrix(
469 targets=targets,
470 cases=cases,
471 default_scorer=default_scorer,
472 scorer_config=scorer_config,
473 judge_fn=judge_fn,
474 concurrency=int(config.get("concurrency") or runner.DEFAULT_CONCURRENCY),
475 )
476 finished = aware_utcnow()
478 # Anything a live write missed, and the judge's calls drained once.
479 if owner is not None:
480 runner.record_ledger(db, owner, targets, outcomes, judge_fn=judge_fn)
482 for outcome in outcomes:
483 db.add(
484 ExperimentRun(
485 experiment_id=experiment_id,
486 variant_id=UUID(outcome.target_key),
487 batch_id=batch_id,
488 test_case_id=runner._case_id(outcome.case),
489 input=outcome.case.describe(),
490 output=outcome.invocation.output or None,
491 score=outcome.score.as_score_json(outcome.scorer_kind),
492 score_reason=outcome.score.reason,
493 scorer=runner._scorer_enum(outcome.scorer_kind),
494 status=(
495 RunnableEnum.Status.completed
496 if outcome.invocation.ok
497 else RunnableEnum.Status.failed
498 ),
499 started_at=started,
500 finished_at=finished,
501 run_metadata={**outcome.metadata(), "source": "optimisation"},
502 )
503 )
504 db.commit()
506 grouped: dict[str, list] = {}
507 for outcome in outcomes:
508 grouped.setdefault(outcome.target_key, []).append(outcome)
509 return {key: runner.aggregate(items) for key, items in grouped.items()}
512def _failing_examples(
513 db: Session,
514 experiment_id: UUID,
515 cases: list[DatasetCase],
516 variant: ExperimentVariant,
517 target_spec: dict,
518 default_scorer: str,
519 scorer_config: dict,
520 judge_fn,
521 config: dict,
522) -> list[dict[str, str]]:
523 """Re-read the incumbent's worst cases from its persisted runs.
525 Reading the stored runs avoids paying for a second evaluation of a prompt
526 that was just scored.
527 """
528 from app.db.postgres.models import ExperimentRun
530 rows = (
531 db.query(ExperimentRun)
532 .filter(
533 ExperimentRun.experiment_id == experiment_id,
534 ExperimentRun.variant_id == variant.id,
535 )
536 .order_by(ExperimentRun.created_at.desc())
537 .limit(len(cases))
538 .all()
539 )
541 def score_of(row) -> float:
542 raw = (row.score or {}).get("value")
543 try:
544 return float(raw)
545 except (TypeError, ValueError):
546 return 0.0
548 worst = sorted(rows, key=score_of)[:MAX_FAILURE_EXAMPLES]
549 return [
550 {
551 "input": str((row.input or {}).get("prompt", ""))[:MAX_EXAMPLE_CHARS],
552 "expected": str((row.input or {}).get("expected_output") or "")[
553 :MAX_EXAMPLE_CHARS
554 ],
555 "output": (row.output or "")[:MAX_EXAMPLE_CHARS],
556 "score": score_of(row),
557 "reason": (row.score_reason or "")[:MAX_EXAMPLE_CHARS],
558 }
559 for row in worst
560 if score_of(row) < 1.0
561 ]
564def _propose(
565 *,
566 ledger: Optional[Callable[[Any], Any]] = None,
567 proposer: ExecutionTarget,
568 prompt: str,
569 criteria: str,
570 score: Optional[float],
571 failures: list[dict[str, str]],
572 count: int,
573 instructions: str,
574) -> list[Candidate]:
575 """Ask the proposer model for ``count`` improved prompts."""
576 sections = [
577 f"## Current system prompt\n{prompt}",
578 f"## Grading criteria\n{criteria}",
579 f"## Current mean score\n{score if score is not None else 'unknown'} (out of 1.0)",
580 ]
581 if instructions.strip():
582 sections.append(
583 f"## Additional instructions from the user\n{instructions.strip()}"
584 )
585 if failures:
586 rendered = "\n\n".join(
587 "\n".join(
588 filter(
589 None,
590 [
591 f"### Case {i + 1} (scored {f['score']:.2f})",
592 f"Input: {f['input']}",
593 f"Expected: {f['expected']}" if f["expected"] else None,
594 f"Got: {f['output'] or '(no output)'}",
595 f"Grader said: {f['reason']}" if f["reason"] else None,
596 ],
597 )
598 )
599 for i, f in enumerate(failures)
600 )
601 sections.append(f"## Cases the current prompt handled worst\n{rendered}")
602 else:
603 sections.append(
604 "## Cases the current prompt handled worst\n"
605 "None — the prompt already scores well. Propose changes that make it "
606 "more robust to inputs outside these cases."
607 )
608 sections.append(f"## Task\nPropose exactly {count} candidate prompts.")
610 result = invoke_structured(
611 proposer, "\n\n".join(sections), PROPOSER_SYSTEM_PROMPT, ProposerReply
612 )
613 if ledger is not None:
614 # Every call is spend, a correction's included.
615 for invocation in result.invocations:
616 ledger(invocation)
617 if result.failed_call:
618 raise OptimisationError(f"Proposer model failed: {result.failure}")
619 if result.value is None:
620 logger.warning("Proposer returned no usable candidates: %s", result.failure)
621 return []
623 candidates: list[Candidate] = []
624 for index, entry in enumerate(result.value.candidates[:count]):
625 text = entry.prompt.strip()
626 if not text:
627 continue
628 candidates.append(
629 Candidate(
630 name=(entry.name.strip() or f"Candidate {index + 1}")[:80],
631 prompt=text,
632 rationale=entry.change.strip(),
633 )
634 )
635 if not candidates:
636 logger.warning("Proposer returned no usable candidates")
637 return candidates
640def _patch(
641 db: Session, experiment_id: UUID, optimisation_id: str, **fields: Any
642) -> None:
643 """Merge ``fields`` into the experiment's optimisation state."""
644 experiment = db.get(Experiment, experiment_id)
645 if experiment is None:
646 return
647 config = dict(experiment.config or {})
648 state = dict(config.get("optimisation") or {})
649 if state.get("id") != optimisation_id:
650 return
651 state.update(fields)
652 config["optimisation"] = state
653 experiment.config = config
654 db.commit()
657def _cancelled(db: Session, experiment_id: UUID, optimisation_id: str) -> bool:
658 experiment = db.get(Experiment, experiment_id)
659 if experiment is None:
660 return True
661 db.expire(experiment, ["config"])
662 state = (experiment.config or {}).get("optimisation") or {}
663 return (
664 state.get("id") == optimisation_id
665 and state.get("status") == RunnableEnum.Status.cancelled.value
666 )