File size: 11,558 Bytes
b8ea052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""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"]),
        },
    }