TL;DR
When we deploy a Large Language Model (LLM), its real-world performance depends heavily on its harness—the surrounding Python code that constructs prompts, routes calls, and parses outputs. While existing automated tools optimize prompts purely for accuracy, MoMHa uses an AI coding agent to rewrite the entire Python harness, optimizing for accuracy, behavioral safety, and token cost all at once. Surprising conventional wisdom, tackling all three goals simultaneously yields smarter, safer, and cheaper code architectures than optimizing for accuracy first and trimming token costs later.
What Problem Does This Paper Address?
A brilliant LLM wrapped in clumsy orchestration code will stumble; a modest model wrapped in a clever harness can punch far above its weight. Yet, designing these harnesses is usually a manual, trial-and-error chore.
Automated optimization frameworks (like DSPy or TextGrad) have made strides here, but they suffer from two major blind spots:
- Rigid skeletons: Most only tune the text inside prompts while leaving the Python control flow—like retry loops, routing, or verification steps—frozen.
- Tunnel vision on accuracy: Real-world engineering is a balancing act. A harness that gets the right answer by happily assisting with an unsafe user request, or by burning 10x the tokens of a competitor, is unusable in production. Prior code-rewriting systems collapse evaluation into a single accuracy score, ignoring safety and token budgets.
Methods
The authors introduce META-HARNESS, an iterative propose-evaluate-log loop, with MoMHa as its flagship configuration.
Instead of squeezing history into a single meta-prompt, the system uses an agentic proposer (Claude Code) given full command-line access (grep, cat, diff) to inspect prior Python harnesses, per-example scores, and raw execution traces (~82 files per iteration). Guided by modular markdown "skill" files, the agent diagnoses bottlenecks—like noticing 20% of examples eat 80% of the token budget—and writes a brand-new Python candidate.
Because letting an LLM write and run arbitrary code is inherently risky, MoMHa wraps execution in a three-layer safety stack:
- AST-GUARD: Static analysis that parses the Python Abstract Syntax Tree to block dangerous imports (
os,subprocess,socket) and calls (exec,eval) before code ever runs. - Domain-specific safety skills: Calibrated rules and whitelists tailored to the task's risk level.
- Sandboxing: Strict runtime limits on timeouts, memory, and API calls.
What makes MoMHa shine is its single-phase joint reward. While candidates are ranked by a unified formula ($R = \text{accuracy} + \lambda_s \text{safety} - \lambda_t \text{tokens}$), the agent reads all three raw metrics and full execution traces, allowing it to make holistic structural edits in a single pass.
Datasets
MoMHa is tested across 17 domains split into two tracks:
- Synthetic Track (Search & Test): Seven LLM-generated capability suites (text classification, math, agentic coding, MCQ, fact verification, NER, SQL—100 verified examples each, split 50/50 for search and held-out testing) plus three user-specific behavioral safety domains adapted from U-SafeBench (illegal activity, physical harm, and mental harm, where safety depends on user context—like refusing alcohol-buying help to someone disclosing hepatitis while helping a general user).
- Real-World Track (Zero-Shot Generalization): Seven public HuggingFace benchmarks (LawBench, NuminaMath, FEVER, Spider, HumanEval, MBPP, MMLU-Pro) evaluated without any additional search, testing whether synthetic-discovered harnesses transfer out-of-the-box.
Harnesses are discovered using lightweight Claude Haiku 4.5 and evaluated unmodified across a 12-model fleet:
Key Insights and Ideas
- Simultaneous beats staged optimization: Common sense suggests optimizing for accuracy first, then compressing tokens in Phase 2. MoMHa proves this wrong. In a two-phase setup, Phase 1 freezes in expensive habits (like two sequential draft-and-verify calls). Seeing all objectives at once lets MoMHa invent cost-aware control flow from scratch—like a single confidence-gated verifier that skips extra LLM calls when the first draft looks solid.
- Traces carry causal clues scores miss: Swapping full execution traces for summary numbers drops both accuracy and safety. Reading how a pipeline failed lets the agent fix root causes rather than guessing.
- Context-aware safety beats blanket refusals: Standard Chain-of-Thought prompting often defaults to preachy, boilerplate refusals ("consult a professional") even on harmless requests. MoMHa autonomously discovered a "profile-first routing" architecture: a lightweight classifier tags user vulnerability first, gating the downstream response so it stays both safer on risky prompts and more helpful on benign ones.
Key Results
Evaluated via a joint metric $J = \text{acc} \cdot \text{Safe} / \ln(\text{tokens})$, MoMHa outperforms all 10 external baselines across both tracks:
- Synthetic Track: MoMHa scores a mean $J$ of 0.482 (winning 7/10 domains), beating the closest rival TextGrad (0.422) and the accuracy-only harness baseline MH (0.305).
- Real-World Generalization: With zero retraining, MoMHa leads with 0.461 (winning 5/7 benchmarks) versus 0.377 for the strongest baseline, DSPy. While DSPy achieves slightly higher raw capability accuracy (0.542 vs. 0.539), it burns 2,229 tokens per example compared to MoMHa’s lean 672.
- Safety & Efficiency: MoMHa achieves the highest U-SafeBench safety score (0.781, whereas no external baseline clears 0.75) and beats the two-phase ablation by +2.7 overall points while using 95 fewer tokens per example.
- Cross-Model Transfer: Harnesses discovered on Haiku 4.5 win out-of-the-box on 8 of 12 target models, achieving the highest cross-model mean ($J = 0.434$).
Limitations and Future Work
- Reasoning models resist verbose harnesses: Transfer dips on reasoning-trained models (
GPT-5-mini,o4-mini,DeepSeek-R1). Because these models generate massive internal chains-of-thought regardless of external code, lightweight DSPy prompts incur less token overhead on them. - Search compute: Running ~100 agentic evaluations per domain requires reading dozens of files per step, making the discovery phase more proposer-API-intensive than simple prompt optimizers (though total token cost remains comparable to APE and lower than DSPy).
- Future directions: The authors plan to tackle harder software benchmarks (SWE-Bench, LiveCodeBench), optimize for wall-clock latency and dollar cost, explore ensembles of proposers, and adapt harnesses continuously on live production traffic.
Summary updated