eval_agent2 / cev /core /planner.py
rongrong620's picture
Add files using upload-large-folder tool
21685ed verified
Raw
History Blame Contribute Delete
18.6 kB
"""cev L_plan Planner — design-time LLM that emits a validation_intent_battery.
Spec: docs/build/B5_planner.md + docs/REBUILD_DESIGN.md §2 (decision A, iron-rules
1/2/3, §2.6 layering). Frozen contract: cev/schemas/validation_intent_battery.schema.json.
Core principles carried over from validation_agent/core/planner.py, RESHAPED so the
output is *validation intents only* — no tool_id / no params / no data_construction:
- dataset-endogenous (iron-rule 1): plan only what feasibility + DataInventory support;
- the LLM is the decider, ZERO rules (D2): deterministic code only assembles the prompt
and validates output SHAPE — it never authors intents;
- intents carry no tool / lib / params / data_construction (iron-rule 2);
- no silent truncation (D7): everything unsupportable goes to not_planned + reason_code.
This module is intentionally LIGHT: it consumes already-built dicts (edge / paper_context /
feasibility / data_inventory / constraints) + an injected LLM provider, so it imports no
pandas/pyarrow and is unit-testable with a fake provider. Heavy upstream loading lives in
cev/cli.py. HPP runtime never runs this (design-time LLM only; hpp_llm_forbidden guard).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Protocol
_SCHEMA_PATH = (
Path(__file__).resolve().parent.parent / "schemas" / "validation_intent_battery.schema.json"
)
DEFAULT_PLANNER_MODEL = "claude-opus-4-8"
PLANNER_AGENT = "cev_planner"
MAX_PLANNER_SCHEMA_REPAIRS = 2
_MAX_REPAIR_ERRORS = 10
# Mirrored from the frozen schema for convenience (the schema file is the authority).
INTENT_TYPES = (
"correlation", "main_effect", "subgroup_cate", "dose_response", "mediation_nie_nde",
"sensitivity", "negative_control", "iv_mr", "bidirectional", "alt_estimator",
)
# tokens that must never appear in an intent (iron-rule 2 purity guard, B5 §3.4)
_FORBIDDEN_TOKENS = ("tool_id", "data_construction", "value_filter", ".tmpl", "data_construction_spec")
_INPUT_LABELS = ("edge", "paper_context", "feasibility", "data_inventory", "constraints")
class PlannerError(RuntimeError):
"""A Planner failure carrying a stable B5 §8 failure code."""
def __init__(self, message: str, *, code: str) -> None:
super().__init__(message)
self.code = code
class LLMProvider(Protocol): # structural; avoids importing the heavy provider module
def call(self, *, agent: str, prompt: str, **kwargs: Any) -> dict[str, Any]: ...
PLANNER_SYSTEM_PROMPT = """\
You are the design-time Planner (L_plan) of the cev causal-validation engine. For ONE
causal edge, on the current synthetic dataset (HPP-isomorphic), design the MOST
COMPREHENSIVE, medically-justified validation battery that THE DATA CAN ACTUALLY SUPPORT,
and emit it as VALIDATION INTENTS ONLY.
# YOU ARE THE DECIDER — ZERO RULES, ZERO TOOLS
- Every decision (which mechanisms to probe, which intent_types, which subgroups /
mediators / contrasts, how comprehensive to be) is YOURS. There is no rule table.
- Do NOT name any tool, tool_id, statistical library, estimator implementation, template,
or parameter. Do NOT emit data_construction, value_filter, cohort, joins, or per-SD
scaling — those are decided by downstream layers, not you.
- Express each verification as a validation_intent whose intent_type is from the FIXED enum.
# OUTPUT — STRICT JSON, an object with EXACTLY these three keys and nothing else
{
"intents": [ validation_intent, ... ],
"tier_index": { "T1": [int, ...], "T2": [...], ... up to "T7": [...] },
"not_planned": [ { "intent_type", "x", "y", "reason_code", "detail" }, ... ]
}
No markdown fences, no comments, no trailing commas, no ellipsis, no extra keys. The system
fills edge_id / battery_id / planner_model / dataset_version / feasibility_ref — you OMIT them.
tier_index values are integer indices into intents[]; membership is your decision and a tier
may be absent. Everything you judge warranted but UNSUPPORTABLE goes in not_planned (never
silently skip it).
validation_intent = {
"intent_type": one of [correlation, main_effect, subgroup_cate, dose_response,
mediation_nie_nde, sensitivity, negative_control, iv_mr,
bidirectional, alt_estimator],
"x": <the edge's X concept label>,
"y": <the edge's Y concept label>,
"m": <REQUIRED only for mediation_nie_nde — the mediator concept>,
"subgroup": <REQUIRED only for subgroup_cate — the stratifying concept, e.g. "sex">,
"contrast_type": <optional: one of level_contrast / unit_increment /
category_vs_reference / threshold_above; declare it for a continuous-X
main_effect / dose_response / alt_estimator>,
"covariates": [<concept labels>],
"rationale": <one sentence of medical justification; NO tool names>
}
# DATASET-ENDOGENOUS (binding — iron-rule 1)
You are given `feasibility` (per-edge runnability + inferred equation/estimator + role
mappings) and `data_inventory` (measured fields, dtypes, cross-table joinability, subgroup
availability, n). Plan ONLY within them — never your imagination.
- An equation / estimator marked not runnable (e.g. instrumental-variable / MR with no
genetic instrument): do NOT emit a runnable intent for it → not_planned
(reason_code=equation_not_runnable). EXCEPTION — longitudinal: when
`feasibility.longitudinal.status == "ok"`, a within-subject change / longitudinal
dose_response IS runnable (estimator `feasibility.longitudinal.candidate_estimator`,
e.g. e3_change / e3_lmm over `feasibility.longitudinal.timepoints`) — PLAN it (T5),
do NOT mark equation_not_runnable.
- A subgroup dimension absent in data_inventory: no subgroup_cate for it → not_planned
(no_subgroup_support).
- No mediator mapped (edge M empty): no mediation_nie_nde → not_planned (no_mediator_mapped).
- X or Y with mapping status "missing": no runnable intent on that role → not_planned
(x_not_mapped / y_not_mapped).
- dose_response: a continuous-X shape is valid cross-sectionally; do NOT reflexively skip
it. `data_inventory[].timepoints` lists the distinct research_stage values on each role
table — when the X role reports ≥2 timepoints, multi-timepoint X IS available, so PLAN the
longitudinal / within-subject change dose_response (T5). Reserve not_planned
(single_timepoint_no_dose) ONLY when the X role table has <2 timepoints.
- Any role resolving to an EXCLUDED, non-physiological source (medications / dietary /
behavioral or self-reported): never plan it → not_planned (excluded_physiological_only).
# SUBGROUPS ARE DATA-DRIVEN, NOT A FIXED CATALOG
`data_inventory.subgroup_candidates` lists EVERY field across the cohort's tables that can
form ≥2 viable strata (with stratum sizes) — discovered generically from the data, NOT a
preset list. Propose subgroup_cate for ANY candidate that is a clinically plausible effect
modifier of THIS X→Y relationship (e.g. menopausal status for a sex-linked or hormonal
outcome, body-composition / adiposity strata, comorbidity or disease-severity status),
reasoning from clinical knowledge. The legacy `subgroup_availability` (D01–D09) is only a
small subset — do NOT limit yourself to it. Skip a candidate only when it is clinically
implausible as a modifier, or is the exposure/outcome itself.
# COMPREHENSIVENESS — attempt everything the mechanism warrants + label every gap
Cover the tier battery the data supports:
T1 main_effect (primary X→Y).
T2 standard subgroups (subgroup_cate per supported effect-modifier; interaction-LRT intent).
T3 paper-named subgroups (from the study cohort / paper text).
T4 sensitivity (adjustment-set / robustness variants the data supports).
T5 dose_response (continuous-X shape; AND when feasibility.longitudinal.status=="ok",
the within-subject change / longitudinal dose_response over timepoints — plan it).
T6 alt_estimator (same X→Y under a different estimator family).
T7 negative_control + bidirectional (reverse Y→X) sanity checks.
Cross-cutting (not tier-bound): mediation_nie_nde (needs m), correlation (association probe).
"Comprehensive" = attempt everything warranted AND record what the data cannot support in
not_planned — Nature-Medicine level is the target ceiling, not a per-edge guarantee.
# PHYSIOLOGICAL-ONLY
Consume only objective physiological indicators + demographics; never plan an intent whose
role resolves to an excluded source.
"""
def build_planner_input(
*,
edge: dict[str, Any],
paper_context: dict[str, Any],
feasibility: dict[str, Any],
data_inventory: dict[str, Any],
constraints: dict[str, Any],
) -> dict[str, Any]:
"""Assemble the (deterministic, timestamp-free) L_plan prompt input.
Mirrors the proven validation_agent input shape MINUS data_inspection and
candidate_subgroups (those came from data_inspector / subgroup_expander, dropped:
the new planner designs subgroups generically as zero-rule intents).
"""
return {
"edge": edge,
"paper_context": paper_context,
"feasibility": feasibility,
"data_inventory": data_inventory,
"constraints": constraints,
}
def build_prompt(planner_input: dict[str, Any], *, repair_suffix: str = "") -> str:
"""Render SYSTEM + one <label>\\n{json} block per input key + the output tail.
Serialization is byte-deterministic (sort_keys=True, no timestamps injected here) so a
recorded-replay key is stable across runs (mirrors the old planner's determinism note).
"""
blocks = []
for label in _INPUT_LABELS:
body = json.dumps(planner_input.get(label, {}), indent=2, sort_keys=True, ensure_ascii=False)
blocks.append(f"<{label}>\n{body}")
user = "\n\n".join(blocks)
tail = (
"YOUR OUTPUT (strict JSON object with EXACTLY keys intents, tier_index, "
"not_planned — nothing else):\n"
)
return f"{PLANNER_SYSTEM_PROMPT}\n\nUSER INPUT:\n{user}\n\n{repair_suffix}{tail}"
def _schema_repair_suffix(errors: list[str]) -> str:
joined = "\n".join(f"- {e}" for e in errors[:_MAX_REPAIR_ERRORS])
return (
"PREVIOUS OUTPUT FAILED STRICT SCHEMA VALIDATION. Re-output the FULL JSON object, "
"fixing EXACTLY these errors and changing nothing else:\n" + joined + "\n\n"
)
def _load_schema() -> dict[str, Any]:
return json.loads(_SCHEMA_PATH.read_text(encoding="utf-8"))
def _build_validator():
"""Pick the strictest available validator.
Their env (jsonschema >= 4.18) uses Draft 2020-12 — the schema's declared dialect.
Falls back to Draft7 on older jsonschema: the schema's `$ref`s are plain JSON-pointers
into `$defs`, which Draft7 resolves, and it supports allOf/if-then/patternProperties —
so validation is equivalent for this contract.
"""
import jsonschema # local import: only needed at validation time
schema = _load_schema()
draft = getattr(jsonschema, "Draft202012Validator", None) or jsonschema.Draft7Validator
return draft(schema)
def _schema_errors(battery: dict[str, Any]) -> list[str]:
validator = _build_validator()
out: list[str] = []
for err in sorted(validator.iter_errors(battery), key=lambda e: list(e.path)):
loc = "/".join(str(p) for p in err.path) or "<root>"
out.append(f"{loc}: {err.message}")
if len(out) >= _MAX_REPAIR_ERRORS:
break
return out
def _purity_violations(intents: list[dict[str, Any]]) -> list[str]:
"""Iron-rule 2 guard: no tool/data-construction token smuggled into any intent field."""
bad: list[str] = []
for idx, intent in enumerate(intents):
blob = json.dumps(intent, ensure_ascii=False).lower()
for tok in _FORBIDDEN_TOKENS:
if tok in blob:
bad.append(f"intents/{idx}: forbidden token {tok!r} (iron-rule 2: intents carry no tools/data-construction)")
return bad
def _strip_fences(text: str) -> str:
t = text.strip()
if t.startswith("```"):
t = t.split("\n", 1)[1] if "\n" in t else t[3:]
if t.rstrip().endswith("```"):
t = t.rstrip()[:-3]
return t.strip()
def _extract_content(response: Any) -> dict[str, Any]:
"""Pull the parsed JSON object out of an LLMProvider.call(...) return.
The production provider returns a dict whose ``response`` key holds the parsed JSON
(llm_provider.py); recorded/fake providers may hand back the content directly. Tolerant
of the common shapes so the same planner works in production and in unit tests.
"""
if isinstance(response, dict):
if "intents" in response or "not_planned" in response:
return response
for key in ("response", "parsed", "content", "output"):
val = response.get(key)
if isinstance(val, dict):
return val
if isinstance(val, str):
return json.loads(_strip_fences(val))
for key in ("text", "raw"):
val = response.get(key)
if isinstance(val, str):
return json.loads(_strip_fences(val))
if isinstance(response, str):
return json.loads(_strip_fences(response))
raise PlannerError(
f"could not extract a JSON battery object from provider response (type={type(response).__name__}, "
f"keys={list(response) if isinstance(response, dict) else 'n/a'})",
code="planner_schema_unrepairable",
)
class CevPlanner:
"""L_plan: one design-time LLM call (+ bounded schema-repair) → validation_intent_battery.
The composer owns ONLY the deterministic envelope (battery_id / planner_model /
dataset_version / feasibility_ref) and SHAPE validation; intents / tier_index /
not_planned are the LLM's content (never authored by code — B5 §2).
"""
def __init__(self, provider: LLMProvider, *, mode: str = "m1_v7", planner_model: str = DEFAULT_PLANNER_MODEL) -> None:
if mode.startswith("hpp"):
# hpp_llm_forbidden: HPP replays the frozen manifest; it never plans.
raise PlannerError(
"the Planner is design-time only; HPP runtime replays a frozen plan with zero LLM",
code="hpp_llm_forbidden",
)
self.provider = provider
self.mode = mode
self.planner_model = planner_model
def compose(
self,
*,
edge_id: str,
planner_input: dict[str, Any],
dataset_version: str,
feasibility_ref: str,
audit_dir: Path | None = None,
log: Any = None,
) -> dict[str, Any]:
if not planner_input.get("feasibility"):
raise PlannerError(
"Planner requires feasibility input (iron-rule 1: dataset-endogenous)",
code="planner_missing_feasibility_input",
)
_log = log if callable(log) else (lambda _m: None)
battery_id = f"{edge_id}::planner::{self.planner_model}"
base_prompt = build_prompt(planner_input)
errors: list[str] = []
def _x_role_timepoint_count() -> int | None:
"""Distinct research_stage count of the X role table, read from data_inventory.
Returns None when X has no mapped dataset or the inventory row lacks timepoints
(e.g. the static `population` table)."""
feas = planner_input.get("feasibility") or {}
inv = planner_input.get("data_inventory") or {}
x_ds = (feas.get("x_mapping") or {}).get("dataset")
if not x_ds:
return None
bare = str(x_ds).split("-", 1)[-1].split(".", 1)[0]
for d in inv.get("datasets", []) or []:
if d.get("dataset") == bare:
tps = d.get("timepoints")
return len(tps) if isinstance(tps, list) else None
return None
def _forbid_false_single_timepoint(bat: dict[str, Any]) -> None:
"""Deterministic guard (backstop for LLM inconsistency): if the X role table has
≥2 timepoints, a dose_response recorded as not_planned/single_timepoint_no_dose is
factually wrong on this dataset — drop that entry so the reason matches the data.
We never fabricate a planned intent in code (B5 §2: intents are LLM-authored);
the prompt is responsible for PLANNING the longitudinal dose_response."""
n = _x_role_timepoint_count()
if n is None or n < 2:
return
nps = bat.get("not_planned")
if not isinstance(nps, list):
return
bat["not_planned"] = [
it for it in nps
if not (isinstance(it, dict)
and it.get("intent_type") == "dose_response"
and it.get("reason_code") == "single_timepoint_no_dose")
]
for attempt in range(MAX_PLANNER_SCHEMA_REPAIRS + 1):
prompt = base_prompt if not errors else build_prompt(planner_input, repair_suffix=_schema_repair_suffix(errors))
_log(f"[cev-planner] attempt {attempt + 1}/{MAX_PLANNER_SCHEMA_REPAIRS + 1} (model={self.planner_model})")
response = self.provider.call(
agent=PLANNER_AGENT, prompt=prompt, model=self.planner_model, audit_dir=audit_dir,
)
content = _extract_content(response)
battery = {
"edge_id": edge_id,
"battery_id": battery_id,
"planner_model": self.planner_model,
"dataset_version": dataset_version,
"feasibility_ref": feasibility_ref,
"intents": content.get("intents", []),
"tier_index": content.get("tier_index", {}),
"not_planned": content.get("not_planned", []),
}
_forbid_false_single_timepoint(battery)
errors = _schema_errors(battery)
purity = _purity_violations(battery["intents"]) if isinstance(battery["intents"], list) else []
if purity:
errors = (errors + purity)[:_MAX_REPAIR_ERRORS]
if not errors:
_log(f"[cev-planner] OK: {len(battery['intents'])} intents, "
f"{len(battery['not_planned'])} not_planned")
return battery
raise PlannerError(
f"battery failed strict schema/purity after {MAX_PLANNER_SCHEMA_REPAIRS} repairs: {errors}",
code="planner_schema_unrepairable",
)