When to reach for it
- Calculations, data transformations, or complex tool calls must be precisely executable.
- The result should be reproducible.
- Multi-step logic composes more cleanly as one program than as a chain of separate tool calls.
Think in code. Execute. Observe. Repeat.
The agent uses executable code rather than pure text as its primary medium for action and reasoning — it writes code, runs it in a sandbox, observes the typed result, and iterates, so a computation is executed rather than approximated in prose.
Think, emit code, execute in a sandbox, observe the typed result — and back to think. Code is the action.
| Turn | Agent writes | Sandbox returns |
|---|---|---|
| 1 | late = df[df.shipped > df.due], then the revenue share | AttributeError: no attribute 'due' |
| 2 | print(df.columns) | id, amount, shipped, due_date |
| 3 | The same calculation with due_date | 89 orders, 7.4 |
| 4 | The answer in prose: 7.4% of March revenue, from 89 of 1,200 orders | Nothing. No code, so the loop ends |
def codeact(task, max_turns=6):
messages = [task]
for _ in range(max_turns):
reply = model(messages)
code = extract_code(reply)
if code is None: # no code block: this is the final answer
return reply
# isolated runtime; returns stdout or the traceback
result = sandbox.run(code)
messages += [reply, f"Output:\n{result}"]
raise RuntimeError("no answer within the turn budget")When to reach for it
When it backfires
The emitted code reads sensitive files or opens outbound connections despite the sandbox.
Countermeasure
Use a hardened sandbox with strict seccomp policies, no network, and a read-only filesystem.
A failed tool call returns stderr, but the agent interprets it as a valid observation and proceeds with corrupted state.
Countermeasure
Always check exit codes. Treat non-zero exits as errors and route to an error-handling node.
Threat exposure
Adopting this pattern opens these attack surfaces. Each links to its entry in the threat model.
Full threat model →Search patterns, frameworks, and pages.