# LLM-agent evaluation for the Classification Fields environment (v2.2), # hard mode (arXiv:2605.07119). # # A simple tool-calling agent loop that plays hard mode through the # environment's MCP tools (get_task, get_paper_summary, get_training_levels, # run_python, submit_predictions) using Hugging Face Inference Providers # (OpenAI-compatible chat completions with tools, routed by provider="auto"). # # The agent must RESEARCH and PREDICT: it reads the task and paper summary, # fetches the observed levels 0-2, writes code via run_python to fit a # residual rule and roll it out, and submits with submit_predictions. The # server computes the hidden ground truth and the log-ratio reward: # reward = clip(log(MSE_affine/MSE_agent) / log(MSE_affine/MSE_cfp), 0, 3) # # Per-episode transcripts (full message list, tool calls, usage, reward) are # written as JSON for the public dataset # ArnavM10/rl-env-2605.07119-agent-evals. # # Usage: # export HF_TOKEN=... # Inference Providers + private eval salt # python scripts/eval_llm_agent.py --base-url http://localhost:8000 \ # --model Qwen/Qwen2.5-7B-Instruct --seeds eval --out out/qwen7b/ import argparse import json import os import sys import time from types import SimpleNamespace import requests sys.path.insert( 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "hard") ) from huggingface_hub import InferenceClient from classification_fields_env import ClassificationFieldsEnv from hard_common import parse_seeds DATASET_REPO = "ArnavM10/rl-env-2605.07119-agent-evals" HARD_TOOLS = ["get_task", "get_paper_summary", "get_training_levels", "run_python", "submit_predictions"] TOOL_SCHEMAS = [ { "type": "function", "function": { "name": "get_task", "description": "Get the task description, reward formula, seed namespaces and budgets.", "parameters": {"type": "object", "properties": {}, "required": []}, }, }, { "type": "function", "function": { "name": "get_paper_summary", "description": "Method context from arXiv:2605.07119: the Classification Field Generator/Predictor, the affine baseline, the protocol, and how hard-mode hierarchies are constructed and scored.", "parameters": {"type": "object", "properties": {}, "required": []}, }, }, { "type": "function", "function": { "name": "get_training_levels", "description": "Levels 0-2 of this episode's nonlinear IFS hierarchy: 'levels' = {0: [[x,y]], 1: [...], 2: [...]} (ordered points), 'parents' per level (index of the parent of each point), 'slots' per level (0..K-1, the child slot), plus K, x0 and the run_python budget. Levels 3-5 are hidden.", "parameters": {"type": "object", "properties": {}, "required": []}, }, }, { "type": "function", "function": { "name": "run_python", "description": "Run Python code server-side (numpy and torch available, CPU, max 120 s per call, 30 calls per episode). stdout is returned. Use it to fit a model of the residual rule r_k(x) = child_k(x) - x from the observed levels and print predictions for levels 3-5 as JSON.", "parameters": { "type": "object", "properties": {"code": {"type": "string", "description": "Python source code"}}, "required": ["code"], }, }, }, { "type": "function", "function": { "name": "submit_predictions", "description": "Submit the predicted ordered point sets for levels 3, 4 and 5 and END the episode. The server scores the ordered MSE against hidden ground truth and returns the reward. Format: {'predictions': {'3': [[x, y], ...], '4': [...], '5': [...]}} with K^l points per level l, parent-by-parent slot order (level l point j*K+k is the k-th child of parent j).", "parameters": { "type": "object", "properties": { "predictions": { "type": "object", "description": "{'3': [[x,y],...], '4': [...], '5': [...]}", } }, "required": ["predictions"], }, }, }, ] SYSTEM_PROMPT = ( "You are an RL agent solving a research task in hard mode of the " "Classification Fields environment (arXiv:2605.07119). Each episode seed " "generated a NEW nonlinear IFS hierarchy. You receive ONLY levels 0-2 " "(via get_training_levels) and must predict the ordered point sets at " "levels 3, 4 and 5, then submit with submit_predictions (this ends the " "episode and returns the reward).\n\n" "Suggested strategy:\n" "1. get_task and get_paper_summary to learn the method and scoring.\n" "2. get_training_levels to fetch the observed levels 0-2 (points, parent " "indices, slots, K).\n" "3. run_python: fit a model of the residual rule r_k(x) = child_k(x) - x " "for each slot k from the observed edges (e.g. least squares on " "[x, 1], or a small torch MLP), then roll it out autoregressively " "(each level's parents are the predicted level) to levels 3-5 and print " "the predictions as JSON: [[x, y], ...] with K^l points per level l in " "parent-by-parent slot order (point j*K+k is the k-th child of parent " "j). Keep each run_python call under 60 s.\n" "4. submit_predictions with {'predictions': {'3': ..., '4': ..., " "'5': ...}}.\n\n" "Reward = clip(log(MSE_affine/MSE_agent)/log(MSE_affine/MSE_cfp), 0, 3): " "the paper's affine residual predictor = 0, its CFP = 1, and every " "factor-of-k MSE improvement counts the same. Work efficiently: you have " "a limited number of tool calls. Do NOT invent points: derive them from " "a fitted rule. Use tools only; when you have submitted, stop." ) def unwrap(result): if isinstance(result, dict): for key in ("data", "result"): inner = result.get(key) if isinstance(inner, dict): return inner return result for attr in ("data", "structured_content", "result"): inner = getattr(result, attr, None) if isinstance(inner, dict): return inner return {"raw": str(result)} def _round_floats(obj, nd=4): """Round floats and compact — long float dumps in tool messages push small models off the rails (and cost tokens).""" if isinstance(obj, float): return round(obj, nd) if isinstance(obj, dict): return {k: _round_floats(v, nd) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return [_round_floats(v, nd) for v in obj] return obj def tool_output_text(result, limit=2000): text = json.dumps(_round_floats(unwrap(result)), separators=(",", ":"), default=str) if len(text) > limit: text = text[:limit] + f"... [truncated, {len(text)} chars total]" return text def chat_via_router(token, model, messages, tools, max_tokens, temperature): """OpenAI-compatible chat completion straight against the HF router, with bounded retry on 429/5xx. Needed for models whose provider id is newer than huggingface_hub's provider classes (e.g. ':parasail' suffix on the model id). """ resp = requests.post( "https://router.huggingface.co/v1/chat/completions", headers={"Authorization": f"Bearer {token}"}, json={ "model": model, "messages": messages, "tools": tools, "max_tokens": max_tokens, "temperature": temperature, }, timeout=300, ) if resp.status_code == 429 or resp.status_code >= 500: for attempt in range(1, 7): wait = min(60, 5 * attempt) print(f" [retry {attempt}] router HTTP {resp.status_code} for {model}; sleeping {wait}s") time.sleep(wait) resp = requests.post( "https://router.huggingface.co/v1/chat/completions", headers={"Authorization": f"Bearer {token}"}, json={ "model": model, "messages": messages, "tools": tools, "max_tokens": max_tokens, "temperature": temperature, }, timeout=300, ) if resp.status_code != 429 and resp.status_code < 500: break if resp.status_code >= 400: raise RuntimeError(f"router HTTP {resp.status_code} for {model}: {resp.text[:500]}") data = resp.json() def _ns(d): return SimpleNamespace(**{k: _ns(v) if isinstance(v, dict) else v for k, v in d.items()}) choice = data["choices"][0]["message"] # tool_calls arrive as dicts; the episode loop expects .function.name/.arguments _tcs = choice.get("tool_calls") or [] for _tc in _tcs: _tc["function"] = SimpleNamespace( name=_tc.get("function", {}).get("name"), arguments=_tc.get("function", {}).get("arguments"), ) _tc["id"] = _tc.get("id") or f"call_auto_{id(_tc)}" # _ns() recurses into dicts but not lists: rebuild the elements as objects. choice["tool_calls"] = [SimpleNamespace(**_tc) for _tc in _tcs] return SimpleNamespace( choices=[SimpleNamespace(message=_ns(choice))], usage=_ns(data["usage"]) if data.get("usage") else None, ) def run_episode(client, model, base_url, seed, max_iterations, max_tokens, temperature, provider=None, providers=None, http_router=False, token=None): # noqa: C901 record = { "model": model, "seed": seed, "seed_kind": "eval" if 100 <= seed <= 109 else "practice", "reward": None, "submitted": False, "n_tool_calls": 0, "n_model_calls": 0, "tool_calls": [], "usage": {"prompt_tokens": 0, "completion_tokens": 0, "n_calls": 0}, "wall_seconds": None, "error": None, } t0 = time.time() consecutive_nudges = 0 # Some providers (DeepInfra Qwen3.5) reject a system-only first turn. messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "Begin."}, ] with ClassificationFieldsEnv(base_url=base_url).sync() as env: env.reset(mode="hard", seed=seed) try: for _ in range(max_iterations): record["n_model_calls"] += 1 kwargs = { "messages": messages, "tools": TOOL_SCHEMAS, "model": model, "max_tokens": max_tokens, "temperature": temperature, } tried = [] tried_providers = set() response = None if http_router: response = chat_via_router(token, model, messages, TOOL_SCHEMAS, max_tokens, temperature) candidates = [] elif provider: candidates = [provider] + list(providers or []) else: candidates = list(providers or []) or [None] for cand in (candidates if not http_router else []): if cand in tried_providers: continue # provider already failed this episode try: if cand is None: response = client.chat_completion(**kwargs) elif cand in providers and providers[cand] is not None: response = providers[cand].chat_completion( messages=messages, tools=TOOL_SCHEMAS, model=model, max_tokens=max_tokens, temperature=temperature, ) else: # hub>=1.x: provider is a chat kwarg response = client.chat_completion(provider=cand, **kwargs) break except (TypeError, KeyError) as exc: tried.append(f"{cand}: {type(exc).__name__}: {exc}") tried_providers.add(cand) continue except Exception as exc: tried.append(f"{cand}: {type(exc).__name__}: {str(exc)[:200]}") tried_providers.add(cand) continue if response is None: raise RuntimeError("all provider candidates failed: " + " | ".join(tried)) choice = response.choices[0].message if response.usage is not None: record["usage"]["prompt_tokens"] += getattr(response.usage, "prompt_tokens", 0) or 0 record["usage"]["completion_tokens"] += getattr(response.usage, "completion_tokens", 0) or 0 record["usage"]["n_calls"] += 1 tool_calls = list(getattr(choice, "tool_calls", None) or []) content = getattr(choice, "content", None) if not tool_calls: # Nudge: the agent must act through tools. Cap at 2 — some # models reply with text forever and the context balloons. consecutive_nudges += 1 if consecutive_nudges > 2: record["error"] = ( "model produced no tool calls (3 consecutive " "text-only responses)" ) break messages.append({"role": "assistant", "content": content or ""}) messages.append( { "role": "user", "content": ( "Respond by CALLING A TOOL (get_training_levels, " "run_python or submit_predictions). Text alone does " "not score." ), } ) if record["n_model_calls"] >= max_iterations - 1: record["error"] = "model produced no tool calls within budget" break continue consecutive_nudges = 0 messages.append( { "role": "assistant", "content": content or "", "tool_calls": [ { "id": f"call_{j}", "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments, }, } for j, tc in enumerate(tool_calls) ], } ) for i, tc in enumerate(tool_calls): name = tc.function.name raw_args = tc.function.arguments try: args = json.loads(raw_args) if isinstance(raw_args, str) else (raw_args or {}) except (TypeError, json.JSONDecodeError): args = {} if not isinstance(args, dict): # Models emit null/empty arguments for no-arg tools. args = {} entry = {"name": name, "arguments": args} record["n_tool_calls"] += 1 print(f" [{model}] iter {record['n_model_calls']}: tool {name}", flush=True) if raw_args is not None and not isinstance(raw_args, dict) and args == {} and entry.get("arguments") == {}: # Unparseable (usually token-truncated) arguments: tell # the model visibly instead of calling with {}. try: json.loads(raw_args) except Exception as parse_exc: # noqa: BLE001 output = { "error": ( f"tool '{name}' arguments are not valid JSON " f"({parse_exc}) - likely truncated; re-issue " "the SAME tool call with COMPLETE arguments" ) } entry["ok"] = False entry["output"] = json.dumps(output) record["tool_calls"].append(entry) messages.append( { "role": "tool", "tool_call_id": f"call_{i}", "name": name, "content": json.dumps(output), } ) continue if name not in HARD_TOOLS: output = {"error": f"unknown tool '{name}' (hard-mode tools: {HARD_TOOLS})"} else: try: output = unwrap(env.call_tool(name, **args)) except Exception as exc: # noqa: BLE001 - record, keep looping output = {"error": str(exc)} entry["ok"] = "error" not in output if ( name == "submit_predictions" and record["reward"] is None and "error" not in output ): sd = output.get("score_details") or {} record["reward"] = output.get("reward", sd.get("reward")) record["submitted"] = True record["score_details"] = sd entry["output"] = tool_output_text(output) record["tool_calls"].append(entry) # Level data must arrive complete in-context (a 2500-char # cap left models without full level-2 points and they # looped on run_python forever); keep run_python dumps tight. in_context_limit = 15000 if name == "get_training_levels" else 2500 messages.append( { "role": "tool", "tool_call_id": f"call_{i}", "name": name, "content": tool_output_text(output, limit=in_context_limit), } ) if record["submitted"]: break except Exception as exc: # noqa: BLE001 - whole-episode failure is a result record["error"] = f"{type(exc).__name__}: {exc}" record["wall_seconds"] = round(time.time() - t0, 1) record["transcript"] = messages return record def main() -> int: parser = argparse.ArgumentParser( description=( "LLM-agent evaluation on the hard mode of the Classification " "Fields environment via HF Inference Providers tool calling." ) ) parser.add_argument("--base-url", required=True) parser.add_argument( "--model", required=True, help="model id on HF Inference Providers, e.g. Qwen/Qwen2.5-7B-Instruct", ) parser.add_argument("--seeds", default="eval", help="'eval', 'practice', '100-109' or a comma list") parser.add_argument("--max-iterations", type=int, default=24) # 1024 truncated gpt-oss-20b's tool-call arguments mid-JSON (finish_reason # = length); 4096 leaves room for reasoning + full code/point-list args. parser.add_argument("--max-tokens", type=int, default=4096) parser.add_argument("--temperature", type=float, default=0.2) parser.add_argument( "--provider", default=None, help="pin an Inference Provider (e.g. 'hf-inference'); default: auto-routing", ) parser.add_argument( "--fallback-providers", default=None, help="comma list of extra Inference Providers to try in order when the primary fails", ) parser.add_argument( "--http-router", action="store_true", help="POST straight to https://router.huggingface.co/v1/chat/completions " "(model id may carry a ':provider' suffix); bypasses hub provider classes", ) parser.add_argument("--out", required=True, help="output directory for transcript JSON files") args = parser.parse_args() token = os.environ.get("HF_TOKEN") client = InferenceClient(token=token) providers = {} if args.provider: try: providers[args.provider] = InferenceClient(token=token, provider=args.provider, timeout=300) except TypeError: providers[args.provider] = None # hub>=1.x: provider is a chat arg if args.fallback_providers: for fp in [p.strip() for p in args.fallback_providers.split(",") if p.strip()]: if fp not in providers: try: providers[fp] = InferenceClient(token=token, provider=fp, timeout=300) except TypeError: providers[fp] = None seeds = parse_seeds(args.seeds) safe_model = args.model.replace("/", "__") os.makedirs(args.out, exist_ok=True) rewards = [] total_prompt = total_completion = 0 for seed in seeds: print(f"[{args.model}] episode seed={seed} ...", flush=True) record = run_episode( client, args.model, args.base_url, seed, args.max_iterations, args.max_tokens, args.temperature, provider=args.provider, providers=providers, http_router=args.http_router, token=token, ) path = os.path.join(args.out, f"{safe_model}--seed{seed}.json") with open(path, "w") as fh: json.dump(record, fh, default=str) total_prompt += record["usage"]["prompt_tokens"] total_completion += record["usage"]["completion_tokens"] reward = record["reward"] rewards.append(reward if reward is not None else 0.0) status = f"reward={reward}" if reward is not None else f"FAILURE: {record['error']}" print( f"[{args.model}] seed={seed} K={record.get('score_details', {}).get('K', '?')} " f"{status} tool_calls={record['n_tool_calls']} " f"wall={record['wall_seconds']}s", flush=True, ) valid = [r for r in rewards if r is not None] mean = sum(valid) / len(valid) if valid else float("nan") print( f"[{args.model}] mean reward: {mean:.4f} over {len(valid)} episodes | " f"prompt_tokens={total_prompt} completion_tokens={total_completion}", flush=True, ) return 0 if __name__ == "__main__": sys.exit(main())