Skip to content

CodeAct: Executable Code Actions Elicit Better LLM Agents

Skip →Context engineering
main track #4corefundamentalpaperrubric 12/122024 · ICML 2024 · ~30 min

Xingyao Wang, Yangyi Chen, Lifan Yuan, …, Heng Ji

Status

TL;DR. Most LLM agents act by emitting one tool call per turn, written as JSON or a fixed text format. CodeAct lets the agent write Python code instead, which a live interpreter runs. One code action can call many tools, loop over inputs, keep results in variables and use any installed library. The interpreter’s output, or its error traceback, becomes the next observation. Across 17 LLMs, code actions give up to 20% higher success on a new multi-tool benchmark (M3ToolEval) with fewer turns. The authors also release CodeActInstruct, 7,139 multi-turn trajectories, and CodeActAgent, a 7B model fine-tuned on them.

Why it matters now. Many current agent frameworks let the model write code as its main way of acting, and coding agents such as SWE-agent depend on shell and code execution. CodeAct is the clean argument for this design, and it is a direct prerequisite for Recursive Language Models, which put the prompt itself inside a Python REPL. For search agents, the action space decides whether query fan-out, deduplication and rank fusion take one step or ten.

Frame the agent as a loop over turns. At turn tt, given the history hth_t, the policy emits an action ata_t and gets an observation oto_t:

at∼π(⋅∣ht),(ot,St+1)=Exec(at,St),ht+1=ht⊕(at,ot).a_t \sim \pi(\cdot \mid h_t), \qquad (o_t, S_{t+1}) = \mathrm{Exec}(a_t, S_t), \qquad h_{t+1} = h_t \oplus (a_t, o_t).

In a JSON agent, ata_t is a single function name and arguments, and the environment state StS_t is outside the model’s reach. In CodeAct, ata_t is a Python program and StS_t is the interpreter state: variables, imported modules and defined functions persist across turns. This changes two things:

  • Composition inside one action. If a task needs kk dependent tool calls, a JSON agent needs at least kk turns, each passing a result back through the model. A code action can chain them with variables and loops in one turn.
  • Errors as feedback. A failed action returns a traceback, which tells the model what went wrong. The paper calls this self-debugging.

The action space is also open-ended: the model can import pandas, scikit-learn or sympy without anyone writing a tool wrapper for them.

CodeAct: the agent acts by writing Python code instead of one JSON tool call per turn An LLM agent chooses its next action. In the usual text or JSON format, each action is a single tool call with no variables or loops, and the result must be read back before the next call. In CodeAct, the action is a Python code block that can loop over inputs, store results in variables and call any library. Both kinds of action go to an executor, but CodeAct uses a Python interpreter whose output or error traceback is returned to the agent as the next observation, which lets it debug itself. LLM agent picks next action text or JSON action one tool call per turn no variables or loops each result read back by LLM code action (CodeAct) for c in cities: r[c] = lookup(c) print(max(r, key=r.get)) Python interpreter runs code, any library observation: printed output or error traceback
Original sketch. A JSON agent makes one call per turn; a CodeAct agent writes a program that can loop, store variables and use any library, and the interpreter's output or error returns as the next observation.
  • Atomic calls (Table 2, API-Bank level 1). Counting best format per model, code wins for 8 of 17 models, JSON for 5, text for 4. For gpt-4-1106-preview, JSON is better (82.7 vs 76.7). The authors read this as closed models having targeted JSON tuning.
  • Multi-tool tasks (Table 3, M3ToolEval). gpt-4-1106-preview reaches 74.4% success with code vs 52.4% with JSON and 53.7% with text, using 5.5 turns on average vs 7.6 and 7.7. The best open model reaches only 13.4%, so the format does not close the gap between open and closed models.
  • CodeActAgent (Table 5). The Mistral-7B variant scores 57.4 on MINT in-domain, 32.4 on MINT out-of-domain and 12.2 on M3ToolEval, beating the other open 7B agents compared. The Llama-2-7B variant scores 0.0 on M3ToolEval; the authors hypothesise pretraining artifacts or a weaker base (Appendix H), but do not test it.
  • General ability kept (Table 5, Table A.8). Mixing in general conversations keeps MMLU, GSM8K and MT-Bench close to or above the base, except a slight MMLU drop for Mistral. The ablation shows both data sources help agent tasks, and the general data is what protects general ability.
  • Benchmark size. M3ToolEval has 82 tasks, so one task is about 1.2 points, and the paper reports single runs.
  • Format, not just capability. Part of the gain may be that the prompt for code actions happens to suit the models better; prompts for each format were kept simple, without demonstrations.
  • Safety. Free code execution is a large capability grant. The paper names sandbox escape as a worst case and notes hallucination (for example imagining a variable’s value without printing it).
  • Model-generation drift. The models tested are from 2023; today’s frontier models have strong native function calling, so the size of the gap on current models is an open question.
  • Where is the boundary? The paper does not study when code is the wrong action space, for example GUI tasks or actions with irreversible side effects.
  • Builds toward: Recursive Language Models (prompt stored in a REPL variable, recursive sub-calls from code); SWE-agent (shell and editor commands as the action space).
  • Earlier agent loop: ReAct interleaves reasoning with text actions; CodeAct replaces the text action with a program.
  • Multi-agent contrast: AutoGen also runs model-written code, through a user-proxy agent that executes it.
  • Evaluation: trajectory and cost evaluation for comparing action spaces at equal turn and token budgets.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    An agent must look up the population of 8 cities with a lookup tool and return the largest. With JSON actions, each turn holds one tool call. With CodeAct, one turn can hold a loop. Count the minimum number of agent turns for each format, assuming the final answer takes its own turn, and explain why the M3ToolEval gap for gpt-4-1106-preview (5.5 vs 7.6 average turns, 74.4% vs 52.4% success) is smaller than this idealised count suggests.

    What a strong answer covers
    • JSON: 8 lookup turns plus 1 answer turn, so 9 turns; each result must pass back through the model before the next call.
    • CodeAct: 1 turn with a for-loop that stores results in a dictionary and prints the maximum, plus 1 answer turn, so 2 turns.
    • Real tasks have dependencies the model does not know in advance, so it must still observe intermediate results, write exploratory code and fix errors, which adds turns.
    • M3ToolEval caps interaction at 10 turns and some tasks are not loop-shaped, so the average saving (about 2.1 turns for the best model) is far below the 8 to 2 idealised saving.
    • Fewer turns also means fewer chances to copy a value wrongly between calls, which is one route to the higher success rate.
  2. Mechanism

    On single atomic API calls (API-Bank, Table 2), CodeAct is the best format for 4 of 8 open-source models but JSON is best for 5 of 9 closed models, such as gpt-4-1106-preview (82.7 JSON vs 76.7 code). Yet on multi-tool M3ToolEval, CodeAct wins for 12 of 17 models. Explain the mechanisms behind both patterns.

    What a strong answer covers
    • Atomic calls test only format familiarity: code is common in pretraining data, while JSON function calling is a skill closed models were likely fine-tuned for, which the authors suggest as the reason for their JSON edge.
    • On atomic calls the control-flow and data-flow benefits of code are removed by design, so the comparison isolates format, not composition.
    • On multi-tool tasks, code lets the model chain outputs into inputs through variables and loops inside one action, instead of re-reading and re-typing values each turn.
    • Code also returns structured error tracebacks, which give the model a concrete signal to repair the next action.
    • So the advantage of code grows with the amount of composition a task requires, not with tool-call accuracy alone.
  3. What if…

    CodeActAgent is fine-tuned on 7,139 CodeActInstruct trajectories mixed with general conversation data. The Mistral-7B variant reaches 12.2 on M3ToolEval, but the Llama-2-7B variant stays at 0.0 despite the same mixture, and the paper's Table A.8 ablates the two data sources. What does the ablation establish, what does the Llama-2 anomaly leave open, and what extra experiment would separate data effects from backbone effects?

    What a strong answer covers
    • Table A.8 shows both CodeActInstruct and general conversation help agent tasks, and the general data is needed to keep MMLU, GSM8K and MT-Bench performance from dropping.
    • The Llama-2 failure is explained only by hypothesis (pretraining artifacts or a weaker base), not by a controlled test.
    • The trajectories were filtered to keep runs where the model first errs and then recovers, so the data teaches self-debugging specifically; the ablation does not isolate that filter.
    • An extra experiment: train several backbones on the same data and on a version without the error-then-fix filter, and report M3ToolEval and MINT for each.
    • Report variance across seeds, since 82 M3ToolEval tasks means one task is about 1.2 points.
  4. Critique

    A team proposes adopting CodeAct for a customer-facing assistant on the grounds that "the code runs in a sandbox, so it is safe". Critique this claim using the paper's own impact statement and what CodeAct actually changes about the agent.

    What a strong answer covers
    • CodeAct is an action-space choice; it widens what the agent can do in one step to anything the interpreter and its libraries allow, which widens the attack surface.
    • The paper's impact statement itself notes that an agent with free code execution could in the worst case break out of its sandbox, and calls for better safety mechanisms.
    • A sandbox limits damage only if network access, file system, credentials and resource use are also restricted; prompt injection in tool outputs can steer the code the model writes.
    • The paper also reports hallucination such as imagining a variable's value without printing it, so executable actions do not guarantee grounded answers.
    • Safe deployment needs least-privilege tools, audit logs, resource limits and human approval for side-effecting actions.
  5. Connect

    Recursive Language Models (RLMs) give the model a Python REPL in which a long prompt is stored as a variable that the model can slice and pass to sub-calls of itself. Explain why CodeAct is a direct prerequisite for this design, and what RLM adds beyond CodeAct.

    What a strong answer covers
    • CodeAct establishes that a model can act by writing code that a persistent interpreter executes, keeping state in variables across turns.
    • RLM reuses this loop but puts the input context itself in the interpreter, so the model never has to read all of it in its own context window.
    • RLM adds recursive LLM calls as a function available inside the code, so one code action can launch sub-model calls over chunks of the context.
    • Both rely on printed outputs and errors as observations; RLM additionally depends on the model choosing good decompositions of the context.
  6. Design

    You are building a deep-research agent over a fixed web corpus with a BM25 search tool, a dense retriever and a document reader. Design the action space as CodeAct-style Python, list two things code makes easier than JSON tool calls for retrieval, and describe how you would compare the two action spaces fairly.

    What a strong answer covers
    • Expose search, dense_search and read as Python functions; results come back as lists of objects the code can filter, deduplicate and sort.
    • Code makes query fan-out easy (a loop over reformulated queries) and makes fusion easy (for example reciprocal rank fusion of BM25 and dense lists in a few lines).
    • Code also lets the agent keep candidate documents in variables instead of pasting long snippets into its context.
    • Fair comparison: same model, same tools, same turn and token budget, the same corpus (for example BrowseComp-Plus style), and report accuracy, turns, tokens and search calls.
    • Add safety limits: no network outside the corpus API, execution timeouts, and logging of every executed action.

Done with this page?

Status