"""Render the AgentDoG-Step pre-execution prompt and parse its diagnostic output."""
import json
from pathlib import Path
import re
HERE = Path(__file__).resolve().parent
TAXONOMY = json.loads((HERE / "taxonomy.json").read_text(encoding="utf-8"))
TITLES = {"safety": "Safety", "failure_mode": "Failure Mode",
"risk_consequence": "Risk Consequence", "risk_source": "Risk Source"}
CANONICAL = {key: {label.casefold() for label in labels} for key, labels in TAXONOMY.items()}
EMPTY_THINK = re.compile(r"^\s*\s*\s*", re.I)
ANALYSIS_TAG = re.compile(r"?(?:analysis|think)\b", re.I)
ANALYSIS_BLOCK = re.compile(r"(.*?)", re.I | re.S)
SAFETY = re.compile(r"^\s*Safety\s*:", re.I)
DECISION = re.compile(r"Safety\s*:\s*(safe|unsafe)", re.I)
USER = re.compile(r"(?ms)^\[USER\]:\s*(.+?)(?=^\[(?:AGENT|USER|ENVIRONMENT)\]|^\[Step \d+\]|^===|\Z)")
TOOLS = re.compile(r"(?ms)^=== Available Tools ===[ \t]*\n(.+?)(?=^===|\Z)")
def render_prompt(phase, user_request, interaction_history, action_under_review, available_tools=None):
"""Accept serialized, visible-only history and the candidate action as separate fields."""
kind = action_under_review["kind"]
if (phase, kind) not in {("pre_action", "tool_call"), ("pre_send", "assistant_text"),
("pre_send", "final_response")}:
raise ValueError("Expected a tool call before execution or assistant text before sending")
if action_under_review.keys() - {"kind", "step_id", "text"}:
raise ValueError("Candidate action accepts only kind, step_id and text")
if not isinstance(interaction_history, str) or not isinstance(action_under_review["text"], str):
raise TypeError("Expected text for interaction history and candidate action")
if not user_request and (match := USER.search(interaction_history)):
user_request = match[1].strip()
if available_tools is None and (match := TOOLS.search(interaction_history)):
available_tools = match[1].rstrip()
context = {"phase": phase, "user_request": user_request, "interaction_history": interaction_history,
"action_under_review": action_under_review, "available_tools": available_tools}
taxonomy = "\n\n".join(f"{TITLES[key]}:\n" + "\n".join(f"- {label}" for label in labels)
for key, labels in TAXONOMY.items())
template = (HERE / "safety-rs.txt").read_text(encoding="utf-8")
return template.replace("{taxonomy}", taxonomy).replace(
"{step_context_json}", json.dumps(context, ensure_ascii=False, indent=2, allow_nan=False))
def parse_response(response):
"""Return the Safety verdict and independently flag the full diagnostic format."""
text = EMPTY_THINK.sub("", response, count=1).strip()
blocks = list(ANALYSIS_BLOCK.finditer(text))
tail = ANALYSIS_BLOCK.sub("", text)
malformed = ANALYSIS_TAG.search(tail) or any(ANALYSIS_TAG.search(block[1]) for block in blocks)
analysis_valid = not malformed and len(blocks) == 1 and blocks[0].start() == 0 and bool(blocks[0][1].strip())
result = {"prediction": None, "status": "malformed_analysis", "format_valid": False, "labels": {},
"analysis_valid": analysis_valid}
if malformed:
return result
lines = [line.strip() for line in tail.splitlines() if line.strip()]
safety_lines = [line for line in lines if SAFETY.match(line)]
match = DECISION.fullmatch(safety_lines[0]) if len(safety_lines) == 1 else None
if not match:
result["status"] = "duplicate_safety" if len(safety_lines) > 1 else "missing_or_invalid_safety"
return result
label = match[1].lower()
fields = tuple(TITLES) if label == "unsafe" else ("safety", "risk_source")
parsed = {}
if len(fields) == len(lines):
for key, line in zip(fields, lines):
if match := re.fullmatch(re.escape(TITLES[key]) + r"\s*:\s*(\S.*)", line, re.I):
parsed[key] = match[1].strip().casefold()
format_valid = (analysis_valid and len(parsed) == len(fields)
and all(value in CANONICAL[key] for key, value in parsed.items() if key != "safety")
and not (label == "unsafe" and parsed.get("risk_source") == "none"))
result.update(prediction=label, status="parsed", format_valid=format_valid, labels=parsed)
return result