"""Canonical trajectory schema shared by teacher generation and SFT. The case run and the question judgments deliberately share the same context. Training exporters can create multiple supervision records without copying a large evidence bundle into every question row. """ from __future__ import annotations import json from typing import Any TRAJECTORY_SCHEMA_VERSION = "pvr.agent_trajectory.v1" VALID_VERDICTS = {"yes", "partial", "no", "abstain"} VALID_REVIEW = {"pending", "approved", "needs_revision", "rejected"} def build_agent_evaluation_request(contract: dict[str, Any]) -> str: """Build compact inference context without teacher-only metadata or evidence.""" questions = [] for role, key, weight_key in (("reward", "reward_questions", "points"), ("penalty", "penalty_questions", "max_deduct")): for item in contract.get(key, []): if not isinstance(item, dict): continue questions.append( { "question_id": item.get("id"), "role": role, "dimension": item.get("dimension"), "question": item.get("question"), "weight": item.get(weight_key), "pass_criteria": item.get("pass_criteria"), "partial_criteria": item.get("partial_criteria"), "fail_criteria": item.get("fail_criteria"), "declared_checker": item.get("checker"), "params": item.get("params", {}), } ) manual_facts = contract.get("manual_facts", {}) compact_facts = { key: manual_facts.get(key) for key in ("intended_final_state", "important_entities", "allowed_changes", "forbidden_changes") if manual_facts.get(key) } request = { "instruction": contract.get("instruction"), "quality_gate": contract.get("quality_gate", {}), "manual_facts": compact_facts, "zones": contract.get("zones", {}), "atomic_questions": questions, } return ( "Compare the input image and prediction image. Plan evidence for every atomic question. " "After saved tool observations are provided, judge each question as yes, partial, no, or abstain. " "Never invent evidence and do not calculate the aggregate score.\n" + json.dumps(request, ensure_ascii=False, separators=(",", ":")) ) def _string(value: Any) -> str: return str(value or "").strip() def _list(value: Any) -> list[Any]: return list(value) if isinstance(value, list) else [] def normalize_trajectory(payload: dict[str, Any]) -> dict[str, Any]: """Validate and normalize one shared case-level trajectory. This function is intentionally strict about identifiers and verdicts but permissive about tool-specific evidence, which evolves independently. """ if not isinstance(payload, dict): raise ValueError("trajectory must be an object") case_id = _string(payload.get("case_id")) prediction_id = _string(payload.get("prediction_id")) if not case_id: raise ValueError("trajectory.case_id is required") if not prediction_id: raise ValueError("trajectory.prediction_id is required") questions: list[dict[str, Any]] = [] seen: set[str] = set() for raw in _list(payload.get("question_judgments")): if not isinstance(raw, dict): continue question_id = _string(raw.get("question_id")) if not question_id: raise ValueError("question judgment is missing question_id") if question_id in seen: raise ValueError(f"duplicate question_id: {question_id}") seen.add(question_id) verdict = _string(raw.get("verdict")).lower() or "abstain" if verdict not in VALID_VERDICTS: raise ValueError(f"invalid verdict {verdict!r} for {question_id}") review = _string(raw.get("human_review_status")).lower() or "pending" if review not in VALID_REVIEW: raise ValueError(f"invalid human_review_status {review!r} for {question_id}") item = dict(raw) item.update( { "question_id": question_id, "verdict": verdict, "human_review_status": review, "evidence_refs": [str(ref) for ref in _list(raw.get("evidence_refs"))], "tool_calls": _list(raw.get("tool_calls")), "reason_codes": [str(code) for code in _list(raw.get("reason_codes"))], } ) questions.append(item) normalized = dict(payload) normalized.update( { "schema_version": TRAJECTORY_SCHEMA_VERSION, "case_id": case_id, "prediction_id": prediction_id, "model_id": _string(payload.get("model_id")) or "unknown_model", "case_review_status": _string(payload.get("case_review_status")).lower() or "pending", "planner": dict(payload.get("planner") or {}), "tool_trace": _list(payload.get("tool_trace")), "evidence_bundle": dict(payload.get("evidence_bundle") or {}), "question_judgments": questions, "metadata": dict(payload.get("metadata") or {}), } ) if normalized["case_review_status"] not in VALID_REVIEW: raise ValueError(f"invalid case_review_status: {normalized['case_review_status']}") return normalized def ready_for_sft(trajectory: dict[str, Any], *, mode: str = "full") -> tuple[bool, str]: """Return whether human review is complete for the requested SFT mode.""" trajectory = normalize_trajectory(trajectory) if trajectory["case_review_status"] != "approved": return False, "case_review_not_approved" if mode == "full": if not trajectory["question_judgments"]: return False, "question_judgments_missing" if any(item.get("human_review_status") != "approved" for item in trajectory["question_judgments"]): return False, "question_review_not_approved" if not trajectory.get("evidence_bundle"): return False, "evidence_bundle_missing" return True, "ready" def build_teacher_prompt( *, contract: dict[str, Any], available_tools: dict[str, str], evidence_bundle: dict[str, Any] | None = None, planner_context: dict[str, Any] | None = None, stage: str = "plan_and_judge", ) -> str: """Build a strict GPT teacher prompt using real saved observations.""" questions = [] for role, key, weight_key in (("reward", "reward_questions", "points"), ("penalty", "penalty_questions", "max_deduct")): for item in contract.get(key, []): if not isinstance(item, dict): continue questions.append( { "question_id": item.get("id"), "role": role, "dimension": item.get("dimension"), "question": item.get("question"), "weight": item.get(weight_key), "criteria": { "pass": item.get("pass_criteria"), "partial": item.get("partial_criteria"), "fail": item.get("fail_criteria"), }, "declared_checker": item.get("checker"), "params": item.get("params", {}), } ) output_schema = { "planner": { "evidence_strategy": "short description", "question_plans": [ { "question_id": "string", "required_evidence": ["string"], "tool_calls": [{"tool": "string", "arguments": {}}], "fallback": "string", } ], }, "question_judgments": [ { "question_id": "string", "verdict": "yes|partial|no|abstain", "confidence": 0.0, "evidence_sufficient": True, "evidence_refs": ["evidence_id"], "reason_codes": ["string"], "reason": "short concrete explanation", "tool_calls": ["tool_call_id"], } ], } return ( "You are the teacher for a structured PVR evaluation agent.\n" "Do not invent detector, OCR, SAM, parser, or VLM observations.\n" "Use only the contract and the provided saved evidence bundle.\n" "The final scorer is deterministic; do not calculate or change the overall score.\n" "For insufficient or conflicting evidence, use verdict=abstain.\n" f"Stage: {stage}\n\n" f"Available tools (tools are executed outside this prompt):\n{json.dumps(available_tools, ensure_ascii=False, indent=2)}\n\n" f"Contract:\n{json.dumps(contract, ensure_ascii=False, indent=2)}\n\n" f"Saved evidence bundle:\n{json.dumps(evidence_bundle or {}, ensure_ascii=False, indent=2)}\n\n" f"Existing planner output (if any):\n{json.dumps(planner_context or {}, ensure_ascii=False, indent=2)}\n\n" "Return JSON only with exactly this high-level schema:\n" f"{json.dumps(output_schema, ensure_ascii=False, indent=2)}\n\n" f"Atomic questions:\n{json.dumps(questions, ensure_ascii=False, indent=2)}" ) def trajectory_to_sft_record(trajectory: dict[str, Any], *, mode: str = "full") -> dict[str, Any]: """Convert an approved trajectory into one Qwen-style multimodal record. Images are referenced by path rather than embedded, keeping JSONL small and allowing the training collator to load images lazily. """ trajectory = normalize_trajectory(trajectory) if trajectory["case_review_status"] != "approved": raise ValueError("only case_review_status=approved trajectories can enter SFT") messages: list[dict[str, Any]] = [ { "role": "system", "content": "You are a PVR evaluation agent. Use tools and evidence; never invent evidence. Return structured JSON.", }, { "role": "user", "content": [ {"type": "image", "image": trajectory.get("input_image", "")}, {"type": "image", "image": trajectory.get("prediction_image", "")}, {"type": "text", "text": trajectory.get("evaluation_request") or trajectory.get("user_prompt", "")}, ], }, ] if mode in {"plan", "full"}: messages.append({"role": "assistant", "content": json.dumps(trajectory["planner"], ensure_ascii=False)}) if mode == "full": messages.append({ "role": "user", "content": "Saved tool observations:\n" + json.dumps(trajectory["evidence_bundle"], ensure_ascii=False), }) if mode == "full": messages.append( { "role": "assistant", "content": json.dumps( {"question_judgments": trajectory["question_judgments"]}, ensure_ascii=False ), } ) return { "id": trajectory["prediction_id"], "case_id": trajectory["case_id"], "model_id": trajectory["model_id"], "messages": messages, "metadata": { "schema_version": TRAJECTORY_SCHEMA_VERSION, "mode": mode, "question_count": len(trajectory["question_judgments"]), }, }