Search

Search papers and lessons

Executable Code Actions Elicit Better LLM Agents

Xingyao Wang, Yangyi Chen, Lifan Yuan et al. · 2024

CodeAct has a language model write Python code as its actions, run in an interpreter, so it can compose tools and fix its own errors, and it beat text or JSON actions on hard multi-step tasks.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Neural network basics
  • Linear algebra
  • Probability
  • Language & LLMs
  • ReadReady to readNot yet

TL;DR

CodeAct is a way for a language model agent to act by writing short Python programs instead of a single JSON object or a line of text in a fixed format. Each program runs in a Python interpreter, and the output or error message is fed back to the model, so the agent can chain tools, loop over inputs and repair its own mistakes over several turns. On a new benchmark of 82 multi-step tasks, the paper reports up to 20 percentage points higher success than the usual text and JSON formats, and it trains an open-source agent, CodeActAgent, on top of Llama-2 and Mistral.

Builds on: LLM Agent, Tool Use, Interpreter, Instruction Tuning · Leads to: code-executing agent designs that followed it

Why it mattered

The paper put a concrete, measured case behind a design choice that many agent builders had made by intuition: let the model act by writing code. Before it, most tool-using agents emitted JSON in a schema the developer had written, and each new tool needed new parsing and new glue. The paper showed that a general interpreter gives the model a much larger action space at no extra engineering cost, and that the model's exposure to code during pre-training makes the format natural for it.

The paper also described an open-source agent trained on a 7,139-trajectory set, along with an evaluation, M3ToolEval, for multi-turn tasks in which one task needs several tools in sequence.

The problem

An agent turns a language model into a loop: it looks at an observation, decides on an action, and the environment returns a new observation. The question is what the action should look like. The two common answers were free text, which is flexible but hard to parse, and JSON in a predefined schema, which is easy to parse but limited to the tools someone has written and cannot easily express a loop or a stored value.

Both formats are weak in the same way for complex tasks. A task that means "apply this search to each of these ten items, then sum the results" needs ten separate actions in JSON or text, with the model tracking intermediate values in its own text. Errors are also handled poorly: a malformed JSON object or a wrong tool name usually produces a generic failure rather than a message the model can act on. The paper asks whether a programming language, which already has loops, variables and error messages, could be the action format instead.

How it works

The paper's framework has three roles: the agent, a user and an environment. The agent receives an observation, optionally reasons about it, and emits an action. In CodeAct, an action sent to the environment is a block of Python code, and the environment is a Python interpreter that returns the printed output, the value of the last expression, or a traceback if the code fails.

Take one tiny instance. A user asks for the average price of the items in a shop's list. The agent has a tool named get_prices that returns a list of numbers, and the prices are 4, 8 and 9.

  1. The agent writes code for the first step. It emits prices = get_prices() and print(prices). This is one action, a short program, not a JSON object. Check: the program uses a variable, so the result is stored for later steps.

  2. The interpreter runs the code. The tool is called, the list is stored in prices, and the printed output [4, 8, 9] is sent back as the observation. Check: the agent now sees the real data, not a guess.

  3. The agent computes the answer. On the next turn it emits print(sum(prices) / len(prices)). The interpreter returns 7.0. Check: the average is 21 divided by 3, which is 7.0.

  4. The agent submits. It proposes 7.0 as the final answer, and the task ends. Check: the task took two code actions, where a JSON format would need a separate call for every price.

  5. Errors come back as messages. Suppose step 1 had a typo, get_price(). The interpreter returns a NameError traceback, and the agent reads it and emits the corrected call on the next turn. This is the self-debugging the paper highlights. Check: the error text is the feedback, and the model uses it without a human in the loop.

flowchart TD
  A[Agent reads observation] --> B[Agent writes a Python program as its action]
  B --> C[Interpreter runs the program]
  C --> D[Output or traceback is returned as the observation]
  D --> E{Solution submitted or 10 turns reached}
  E -- no --> A
  E -- yes --> F[Task ends]

The paper's full evaluation uses a limit of 10 turns per task. Within each turn the model either takes an action or proposes an answer, which is checked by exact match against the ground truth.

To make open models do this well, the authors built a training set called CodeActInstruct. They drew tasks from five existing datasets in four groups: information seeking (HotpotQA, with a Wikipedia search function), software package use (APPS for code and MATH for math), external memory (WikiTableQuestions, answered through SQL or pandas), and robot planning (ALFWorld, with robot-control functions). They generated trajectories with stronger models, then kept the trajectories in which the model made an error and recovered from it, so the training data teaches the recovery step. The result, with general chat data mixed in, was used to fine-tune Llama-2 7B and Mistral 7B into CodeActAgent.

The math

The paper's formal content is light, so the math here is the bookkeeping behind its measurements.

Let an agent be a policy π\pi that maps the history of observations and actions to the next action, at=π(o1,a1,…,ot)a_t = \pi(o_1, a_1, \ldots, o_t). The action space is the set of programs Acode\mathcal{A}_{\text{code}} in the CodeAct condition, and the sets of JSON or text strings in the baselines. The environment returns ot+1o_{t+1} after running ata_t, and the loop stops at a submitted answer or at turn T=10T = 10.

The success rate over NN tasks is

SR=#{tasks whose submitted answer exactly matches the ground truth}N.\text{SR} = \frac{\#\{\text{tasks whose submitted answer exactly matches the ground truth}\}}{N}.

With N=82N = 82 tasks, the reported best score of 74.4 percent corresponds to 0.744×82≈610.744 \times 82 \approx 61 correct tasks. The average number of turns is the mean of the number of turns used on each task, and the paper reports it alongside the success rate, because a format that succeeds in fewer turns uses fewer model calls and less time.

The absolute improvement is a difference of two success rates. For the best model, the text baseline is implied to be 74.4−20.7=53.774.4 - 20.7 = 53.7 percent, and the paper reports the gain as an absolute improvement of 20.7 points, not as a ratio.

Results

The paper has three main results, each on a different benchmark.

Atomic tool calls (API-Bank). On single tool calls, where code has no advantage from control flow, CodeAct was comparable to or better than JSON and text for most of the 17 models tested. The gains were largest for open-source models, which the authors read as evidence that code data in pre-training helps.

Multi-turn tasks (M3ToolEval). On 82 human-written tasks, each needing several tools across several turns, CodeAct had a higher success rate for 12 of the 17 models and used fewer turns for 12 of 17. The best model, gpt-4-1106-preview, reached 74.4 percent with CodeAct, which is 20.7 points above the next best format, text, and it needed 2.1 fewer turns on average. The paper summarises the overall gain as up to 20 percent absolute improvement in success rate and up to 30 percent fewer actions.

Open-source agent. The Mistral-based CodeActAgent beat open-source models of 7B and 13B size on M3ToolEval and came close to 70B models, according to the paper. The best open-source model on M3ToolEval in the main comparison reached 13.4 percent, which the paper calls a large gap to the closed models. The Llama-2 variant did not improve on M3ToolEval, and the paper discusses possible reasons. On both the in-domain and out-of-domain MINT subsets, CodeActAgent beat the other open-source models, and on general benchmarks it kept or improved its scores, with a slight drop on MMLU for the Mistral variant. Against the earlier training sets AgentInstruct and FireAct, the paper reports relative improvements of 24 and 119 percent on the same backbone.

Limits. The evaluation is zero-shot, with no examples in the prompt, which is a strict test but not the only way to use these models. The M3ToolEval benchmark has 82 tasks, so single-task differences are noisy. The open-source gap to the best closed model remains large, and the paper suggests weak task-solving and poor instruction-following in open models as a likely cause.

Reading guide

The paper is long, but the main argument is in the first three sections, and the appendices hold details most readers can skip.

  • Section 1, Introduction. Read it for the problem and the three benefits of code. It assumes agents and Tool Use, so read those first.
  • Section 2.1, What is CodeAct? The framework and its three roles. Needs LLM Agent and Interpreter.
  • Section 2.2, API-Bank. The atomic tool-call experiment. Needs Tool Use and the idea of a Transformer having seen lots of code in pre-training.
  • Section 2.3, M3ToolEval. The main multi-turn experiment. Needs In-Context Learning, since the prompts give no examples.
  • Section 2.4, Existing software packages. The worked trace in Figure 3. Needs Interpreter.
  • Section 3.1, CodeActInstruct. How the training data was built. Needs Instruction Tuning and the idea of generating trajectories with a stronger model.
  • Section 3.2, CodeActAgent. The fine-tuning setup and results. Needs Fine-Tuning and Transformer.
  • Section 4, Related work. Places the paper against ReAct Prompting and Chain-of-Thought Prompting, which also let a model interleave reasoning and tool actions.

Check yourself

QuestionIn one or two sentences, what is the difference between a CodeAct action and a JSON action?Show answer

A JSON action is a single structured object in a schema that a developer has fixed in advance. A CodeAct action is a short Python program that runs in an interpreter, so it can use variables, loops and any installed package, and its output or error message becomes the next observation.

QuestionA task has 82 instances and the agent answers 61 correctly. What is the success rate, to one decimal place?Show answer

The success rate is 61/82≈0.743961 / 82 \approx 0.7439, so 74.4 percent.

QuestionWhy does the paper keep traces where the model first made an error and then recovered, rather than only the clean successes?Show answer

Those traces show the model reading an error message and correcting its next action. Training on them teaches the self-debugging step that the paper says makes CodeAct useful in multi-turn interactions.

QuestionWhy does the paper report the 20.7 gain as a difference in percentage points rather than as a ratio?Show answer

The paper calls it an absolute improvement. Both figures are shares of the same 82 tasks, so their difference is the extra share of tasks solved. A relative gain divides that difference by the smaller baseline (here 20.7 / 53.7, about 39 percent), which makes the same improvement look larger.

Sources

Read the full paper

Xingyao Wang, Yangyi Chen, Lifan Yuan et al., 2024. arXiv:2402.01030