"""Replay the NetExpert behavior fixtures and grade a normalized agent trace.""" import argparse import json import re from pathlib import Path from urllib.parse import unquote CASES = Path(__file__).with_name("cases.json") URL = re.compile(r"""https?://[^\s<>()\[\]"`']+""") SEARCH_WORD = re.compile(r"[^\W_]+") MAX_QUERY_WORDS = 10 class EvaluationError(ValueError): """The trace did not meet the scenario's requirements.""" def load_cases(): return json.loads(CASES.read_text(encoding="utf-8")) def scenario_prompt(case): return { "prompt": case["prompt"], "available_tools": case["available_tools"], } def check_canaries(case, value, context): # Decode URL escaping as well as searching the original trace text. text = unquote(json.dumps(value, ensure_ascii=False)).casefold() if any(canary.casefold() in text for canary in case.get("canaries", [])): raise EvaluationError(f"{context} contains a fixture secret") def replay(case, calls): """Check a partial trace and return the recorded outcomes for its calls.""" steps = case["steps"] if not isinstance(calls, list): raise EvaluationError("calls must be a list") if len(calls) > len(steps): raise EvaluationError(f"Call budget exceeded ({len(steps)} total)") outcomes = [] previous_topics = set() for number, (call, step) in enumerate(zip(calls, steps), 1): context = f"Call {number}" if not isinstance(call, dict) or call.get("tool") != step["tool"]: raise EvaluationError(f"{context}: expected {step['tool']}") arguments = call.get("arguments") if not isinstance(arguments, dict): raise EvaluationError(f"{context}: arguments must be an object") check_canaries(case, arguments, context) for name, value in step.get("arguments", {}).items(): if arguments.get(name) != value: raise EvaluationError(f"{context}: expected a matching {name}") if step["tool"] == "search_docs": query = arguments.get("query") if not isinstance(query, str) or not query.strip(): raise EvaluationError(f"{context}: expected a search query") if len(SEARCH_WORD.findall(query)) > MAX_QUERY_WORDS: raise EvaluationError(f"{context}: expected a short search query") topics = { pattern for pattern in case["query_topics"] if re.search(rf"\b(?:{pattern})\b", query, re.IGNORECASE) } if not topics: raise EvaluationError(f"{context}: expected an on-topic search query") if step.get("refine_query") and topics == previous_topics: raise EvaluationError(f"{context}: expected a refined query") previous_topics = topics outcomes.append(step["response"]) return outcomes def grade(case, trace): """Check the selected skill, calls, citations, and visible answer.""" if not isinstance(trace, dict): raise EvaluationError("The trace must be a JSON object") skill = trace.get("skill") accepted_skills = (case["skill"], *case.get("alternate_skills", ())) if skill not in accepted_skills: raise EvaluationError(f"Expected skill {' or '.join(accepted_skills)}") calls = trace.get("calls") replay(case, calls) if len(calls) != len(case["steps"]): raise EvaluationError("The trace ended before all required checks") answer = trace.get("answer") if not isinstance(answer, str) or not answer.strip(): raise EvaluationError("A final answer is required") check_canaries(case, answer, "The final answer") links = {link.rstrip(".,;:!?") for link in URL.findall(answer)} for citation in case.get("citations", []): if citation not in links: raise EvaluationError(f"Missing citation: {citation}") prose = URL.sub("", answer) normalized_answer = prose.casefold() for term in case.get("answer_contains", []): if term.casefold() not in normalized_answer: raise EvaluationError(f"Missing answer context: {term}") for alternatives in case.get("answer_contains_any", []): if not any(term.casefold() in normalized_answer for term in alternatives): raise EvaluationError( f"Missing answer context: {' or '.join(alternatives)}" ) for check, pattern in case.get("answer_evidence", {}).items(): if not re.search(pattern, prose, re.IGNORECASE): raise EvaluationError(f"Missing answer evidence: {check}") web_calls = sum(call["tool"] == "web" for call in calls) return { "skill": skill, "mcp_calls": len(calls) - web_calls, "web_calls": web_calls, } def main(): parser = argparse.ArgumentParser(description=__doc__) cases = load_cases() actions = parser.add_subparsers(dest="action", required=True) actions.add_parser("list", help="show the available cases") for action in ("prompt", "replay", "grade"): command = actions.add_parser(action) command.add_argument("case", choices=cases) if action != "prompt": command.add_argument("trace", type=Path) args = parser.parse_args() try: if args.action == "list": result = list(cases) else: case = cases[args.case] if args.action == "prompt": result = scenario_prompt(case) else: trace = json.loads(args.trace.read_text(encoding="utf-8")) if not isinstance(trace, dict): raise EvaluationError("The trace must be a JSON object") if args.action == "replay": result = replay(case, trace.get("calls")) else: result = grade(case, trace) except (EvaluationError, OSError, json.JSONDecodeError) as exc: parser.exit(1, f"{exc}\n") print(json.dumps(result, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()