Don’t Constrain the Thought, Constrain the Edge
How to restrain LLMs toward intent: four boundaries that each need their own level of restraint, plus a ratchet that moves mature paths into plain code.
When teams build software with LLMs, they usually picture restraint as a single linear ladder: vague natural-language prompts at one end, pure deterministic code at the other, and better specs, JSON schemas, tool-calling agents, and code workflows arranged neatly in between.
In production, treating “more structure” as a single system-wide dial makes LLM systems worse:
- Crank structural rigidity too high on internal reasoning or inbound error traces, and accuracy and self-correction drop sharply.
- Leave structural rigidity too low on retry loops, authorization, secret handling, or outbound wire formats, and you ship brittle software and security holes.
Current empirical research across constrained decoding, context engineering, and agent harnesses points to a different model. LLM restraint is not one ladder. It is four independent boundaries, plus a lifecycle ratchet that compiles mature paths down to pure code over time. Two of those boundaries need semantic breathing room; the other two require strict deterministic host code.
1. Why a Single 1D Ladder Breaks Down
A linear progression (Free NL -> Specified NL -> Schemas -> Agent Tools -> Code Workflows -> Pure Code) hides three architectural realities:
- “Tool use” can either shrink or explode the action space. Exposing a narrow domain RPC like
issue_refund(order_id, amount_cents)restricts the model to a single safe state transition. Exposingbashor a Python REPL uses a tool schema on paper, yet hands the model Turing-complete execution inside whatever container it occupies. Grouping both as a single step confuses a straitjacket with a chainsaw. - Control flow and tool breadth move independently. Mini-SWE-agent solves over 74% of SWE-bench Verified in roughly 100 lines of Python using a minimal linear loop over raw
bashoutput, relying on container sandboxing and test suites rather than narrow tool schemas. By contrast, an invoice processor might run zero loops and zero tools, calling one schema-locked extraction function inside a rigid Rust state machine. - Enforced schemas are already host code. Asking for JSON or XML in a prompt is probabilistic hope. Actual schema guarantees come from token-level grammar masking (CFG/FSM constrained decoding) or deterministic parse-and-retry loops in host code. Once a schema is enforced, deterministic code already owns that edge.
2. The Four-Boundary Model
Every LLM component touches host software across four distinct surfaces: control flow, reasoning, inbound evidence, and outbound actions. Each surface has its own optimal level of restraint.
| Boundary | Question | Optimal Restraint | Primary Failure Mode When Misconfigured |
|---|---|---|---|
| 1. Control Flow & State | Who owns the while loop, retries, and budgets? |
High (Deterministic Host Code); grant bounded agent loops only when paths are unpredictable and verifiable | Runaway loops, compounding errors, unenforced permission or spend limits |
| 2. Specification & Reasoning | How tightly constrained is intermediate thought? | Specified intent + Unconstrained thought (explicit invariants, free-form scratchpad / thinking tokens) | “Projection tax” and premature token commitment when forced to reason inside rigid JSON fields |
| 3. Inbound Evidence | How do tool outputs and errors enter context? | Hybrid (tiny typed metadata envelope + bounded head/tail slice of redacted raw output) | Blind self-correction from closed enums; trajectory elongation from polite LLM summaries; KV-cache thrashing |
| 4. Outbound Actions | How does model output cross into side effects? | High (“Parse, don’t validate”) via enforced schemas, narrow domain primitives, and host-side auth/redaction | Unparseable payloads, hallucinated arguments, or unsandboxed shell side effects |
Boundary 1: Control Flow & State (Workflows vs. Agents)
Anthropic’s Building Effective Agents (2024) draws the primary macro-architectural split between Workflows (systems where LLMs and tools are orchestrated through predefined code paths) and Agents (systems where LLMs dynamically direct their own processes and tool usage). Extending that split to its deterministic limit yields three runtime modes:
- Zero Runtime LLM (Pure Code): Ambiguity is resolved at design or build time; production runs parsers, types, and algorithms with zero token cost or latency.
- Deterministic Workflow (Code Calls LLM): Host code owns branching, retries, parallel fan-out, state persistence, and termination. The LLM acts as a bounded semantic subroutine.
- Bounded Agent Loop (LLM Drives Inside a Cage): The LLM chooses tool ordering and stopping criteria inside hard host-enforced walls: step caps, token/cost ceilings, sandboxed environments, and automated ground-truth checks (compilers, tests, linters).
Evidence verdict: Default to Deterministic Workflows whenever the process is repeatable or requires predictable latency, cost, and auditability. Reserve autonomous Agent Loops for open-ended tasks where valid solution paths cannot be scripted upfront and outcomes can be verified automatically.
Boundary 2: Specification & Reasoning (Tight Intent, Free Thought)
Specification clarity and output-format rigidity are often conflated, yet they pull in opposite directions during reasoning:
- Specification altitude: In Effective Context Engineering for AI Agents (2025), Anthropic identifies a “Goldilocks zone” between two failure modes: vague prompts that force the model to invent unstated assumptions, and brittle prompt-encoded
if-elsetrees that break on edge cases. Strong prompts state explicit goals, domain invariants, priorities, and canonical examples while leaving reasoning heuristics flexible. - The cost of reasoning inside schemas: Tam et al. (Let Me Speak Freely?, 2024, arXiv:2408.02442) demonstrated steep drops on reasoning benchmarks like GSM8K when models were forced directly into strict structured formats without free-form reasoning space. Follow-up analysis by Will Kurt at .txt (Say What You Mean, 2024) showed that autoregressive field ordering is a major culprit: placing
answerbeforereasoning(or omitting a scratchpad field) forces the model to commit to an answer token before computing the steps that justify it. - Decoupling reasoning from projection: Hybrid constrained-decoding methods such as CRANE (Banerjee et al., ICML 2025, arXiv:2502.09061) and Draft-Conditioned Constrained Decoding (2026, arXiv:2603.03305) alternate or separate unconstrained natural-language reasoning from grammar-constrained output generation. Crucially, Nguyen et al. (Constrained Decoding: Harmful or Beneficial?, Oct 2026, arXiv:2610.35328) found across 11 models that decoder-level grammar masking itself is not inherently harmful when prompts and target formats are matched fairly: once reasoning is not starved, constraining the output answer space to valid structures consistently improves performance (up to +17.4%).
Evidence verdict: Specify invariants tightly in natural language, let the model think freely in prose (using native extended-thinking blocks or an unconstrained scratchpad), and apply grammar constraints strictly to the final emitted action or payload.
Boundary 3: Inbound Evidence (Envelopes, Raw Traces, and KV Caches)
How an environment reports state and failures back to the model governs whether an agent converges or loops endlessly:
- External error traces are mandatory for recovery: Huang et al. (Large Language Models Cannot Self-Correct Reasoning Yet, ICLR 2024, arXiv:2310.01798) showed that intrinsic self-correction without external feedback degrades reasoning accuracy rather than improving it. Conversely, Shinn et al. (Reflexion, NeurIPS 2023, arXiv:2303.11366) and Mini-SWE-agent show strong recovery gains when agents receive concrete execution and test-failure traces. Mapping rich errors into closed enums (
ERR_COMPILE) blinds the model to unexpected failure modes. - Raw observations vs. LLM summaries: Lindenbauer et al. at JetBrains Research (The Complexity Trap, 2025, arXiv:2508.21433) compared raw SWE-agent histories, LLM-summarized histories, and simple observation masking (keeping recent tool outputs raw while replacing older bulky outputs with placeholders). Simple observation masking cut instance costs by more than half compared to uncompacted agents and matched or outperformed LLM summarization, because LLM summaries smoothed over failure cues and encouraged trajectory elongation (continuing down dead-end paths instead of pivoting).
- Just-in-time loading and KV-cache physics: Anthropic’s Effective Context Engineering (2025) recommends maintaining lightweight structured identifiers (file paths, URLs, query handles) in context and loading raw data just-in-time via tools. Because LLM APIs price cached prompt prefixes far cheaper than fresh tokens, conversations should stay append-only from turn to turn; compact or mask old observations in periodic multi-turn blocks rather than mutating a sliding window on every request.
Evidence verdict: Return a small deterministic envelope (stage, exit_code, timed_out, artifact_handle) for host code routing, paired with a secret-redacted head-plus-tail slice of raw stdout/stderr so both the initial root-cause panic and final exit summary remain visible.
Boundary 4: Outbound Actions (“Parse, Don’t Validate” + Poka-Yoke Primitives)
When model tokens cross back into host software to trigger side effects, apply Alexis King’s type-design rule (Parse, don’t validate, 2019) alongside Anthropic’s Agent-Computer Interface (ACI) guidelines:
- Parse into domain types at the edge: Use constrained decoding / structured outputs to enforce wire shape, then parse arguments into strongly typed domain structures before business logic ever sees them.
- Poka-yoke (mistake-proof) narrow tools: Design tool signatures so invalid states are hard to express (for example, requiring repo-relative paths or strongly typed IDs rather than raw string interpolation).
- Keep security deterministic: Schema validation checks syntax and types, never authorization or data sensitivity. Tenant isolation, permission checks, rate limits, and outbound secret scrubbing must run in deterministic host code wrapping the tool execution.
- Sandbox open-ended escape hatches: When narrow primitives are impractical (such as general software engineering or ad-hoc data exploration), isolate general tools (
bash, SQL, code interpreters) inside ephemeral containers with scoped network and credential boundaries.
3. The Lifecycle Dimension: Ratcheting from Runtime to Build Time
The four boundaries describe how to restrain a live LLM call today. Across weeks of iteration, a fifth force applies: ratcheting stabilized work out of runtime LLM inference altogether.
Treat high-autonomy LLM paths as empirical discovery scaffolding:
- Explore with bounded autonomy: Let an agent or flexible workflow handle messy real-world inputs while logging trajectories, edge cases, and failure traces.
- Extract recurring action sequences into narrow tools: If an agent routinely chains the same three commands to inspect state, replace that sequence with one tested host primitive.
- Collapse predictable trajectories into workflows: Once tool ordering stabilizes, move the
whileloop from the agent into deterministic host code. - Compile stable semantic steps into pure code: Once an LLM classification, extraction, or routing step follows rules you can specify completely, use a coding agent at build time to generate and fuzz-test a deterministic parser or rule module, removing the runtime LLM call entirely.
Runtime tokens should only pay for genuine runtime ambiguity.
4. Operational Rules
- Never enforce a host invariant in a prompt. Put retry limits, budgets, auth checks, tenant scoping, and secret redaction in host code, never in uppercase prompt warnings.
- Specify invariants tightly; leave reasoning unconstrained. Write unambiguous specs at the prompt level, keep native thinking / free-form scratchpads active, and never place answer fields ahead of reasoning fields in non-thinking structured calls.
- Parse, don’t validate, at every outbound edge. Enforce strict schemas on tool calls and structured outputs, parse immediately into domain types, and run deterministic permission checks before executing side effects.
- Feed structured envelopes + head/tail raw traces on failure. Give host code typed status fields (
exit_code,stage) for routing and give the model a bounded, redacted head-plus-tail raw log slice for diagnosis; avoid closed error enums and LLM-summarized error logs. - Keep history append-only between compaction checkpoints. Preserve prompt-cache prefixes by batching observation masking or compaction every N turns rather than rewriting history every turn.
- Default to workflows, earn agent loops, and ratchet to pure code. Start with deterministic code calling bounded LLM steps; grant open-ended loops only when paths are unpredictable and verifiable; compile predictable steps down to zero-LLM code.
5. Open Questions
- RL-trained schema reasoning: As frontier models train natively with reinforcement learning over interleaved thinking-and-tool traces, does the formatting “projection tax” shrink even without explicit scratchpad separation, or does autoregressive commitment still penalize early-field constraints?
- Optimal compaction cadence under prompt caching: What exact turn/token threshold maximizes solve rate per dollar across different provider cache TTLs and read/write price ratios when batch-masking bulky tool outputs?
- Code-execution tool calling (MCP / programmatic tool composition): Anthropic’s work on letting models write small sandboxed scripts to compose multiple MCP tools in one turn blurs the line between narrow primitives and general shells. Where does programmatic tool composition beat individual typed tool calls on reliability vs. security surface?
- Automated runtime-to-build-time distillation: Can production traces from an LLM workflow be systematically clustered to flag sub-tasks ready to be replaced by generated deterministic code + property tests?
6. References
- Anthropic (Dec 2024). Building Effective Agents. https://www.anthropic.com/research/building-effective-agents
- Anthropic (Sep 2025). Effective Context Engineering for AI Agents. https://www.anthropic.com/research/effective-context-engineering-for-ai-agents
- Tam, Z. R., et al. (Aug 2024). Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models. https://arxiv.org/abs/2408.02442
- Kurt, W. / .txt (2024). Say What You Mean: A Response to ‘Let Me Speak Freely’. https://blog.dottxt.ai/say-what-you-mean.html
- Banerjee, D., et al. (ICML 2025). CRANE: Reasoning with Constrained LLM Generation. https://arxiv.org/abs/2502.09061
- Draft-Conditioned Constrained Decoding (2026). The Hidden Cost of Structured Generation in LLMs: Draft-Conditioned Constrained Decoding. https://arxiv.org/abs/2603.03305
- Nguyen, N. T. H., et al. (Oct 2026). Constrained Decoding: Harmful or Beneficial? Revisiting Its Impact on LLM Performance. https://arxiv.org/abs/2610.35328
- Huang, J., et al. (ICLR 2024). Large Language Models Cannot Self-Correct Reasoning Yet. https://arxiv.org/abs/2310.01798
- Shinn, N., et al. (NeurIPS 2023). Reflexion: Language Agents with Verbal Reinforcement Learning. https://arxiv.org/abs/2303.11366
- Lindenbauer, T., et al. / JetBrains Research (2025). The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management. https://arxiv.org/abs/2508.21433
- SWE-agent Team. mini-swe-agent: The 100-line AI software engineering agent. https://github.com/SWE-agent/mini-swe-agent
- King, A. (Nov 2019). Parse, don’t validate. https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/