CodeAct

Also known as: executable code actions

On this page 6

CodeAct is an approach to building AI agents in which the language model expresses every action as executable code, usually Python, instead of a JSON tool call or a fixed text command. An interpreter runs the code, and the execution result, output or error message returns to the model as the observation for its next step. The idea was formalized in 2024 research titled after executable code actions, which showed that such agents solve multi-step tasks more often and in fewer turns than agents using structured tool calls.

The central insight is that a programming language is already a general, composable action space. Code can call several tools in one step, store intermediate results in variables, loop over data and branch on conditions, all of which require many separate turns when each tool call must be a single JSON object.

How CodeAct turns code into agent actions

A CodeAct agent runs a multi-turn loop between the model and a code execution environment. At each turn, the model reads the task, the conversation history and previous observations, then writes a short reasoning note followed by a code block. The harness extracts the block, executes it in a stateful interpreter such as a Python process or Jupyter kernel, and appends the printed output or traceback to the context.

Tools are exposed as ordinary Python functions or importable libraries rather than as schemas. The model calls them like any other function, combines their outputs with standard operations and prints whatever it needs to inspect. When the task is complete, the agent produces a final natural-language answer instead of another code block.

The loop consists of the following stages.

StagePerformed byResult
Plan and write codeLanguage modelReasoning text plus an executable block
ExecuteInterpreter or sandboxStandard output, return values or errors
ObserveAgent harnessExecution feedback added to the context
Revise or finishLanguage modelCorrected code or a final answer
Stages of a CodeAct turn

Because the interpreter keeps variables and imports between turns, the agent can build on earlier work, much as a data analyst does in a notebook. Error messages act as automatic feedback for self-debugging: a wrong column name or a failed request produces a traceback that the model can read and fix on the next turn.

CodeAct compared with JSON and text tool calling

CodeAct differs from conventional tool calling mainly in how much one action can express. In JSON-based calling, each action names one tool with fixed arguments, and any combination of results requires another round trip through the model. In text-based formats such as the original ReAct prompting style, actions are strings that the harness parses, which is flexible but fragile.

PropertyCodeActJSON tool callsText actions
Tools per actionMany, composed freelyUsually oneUsually one
Control flowLoops and conditionalsNoneNone
Intermediate stateVariables in memoryOnly in model contextOnly in model context
Error feedbackNative tracebacksHarness-defined messagesParser errors
Safety surfaceArbitrary code executionLimited to declared toolsLimited to parsed commands
Action formats for language model agents

The original evaluation introduced a benchmark of tasks that require composing multiple tools. Across several large language models, CodeAct achieved success rates up to about 20 percentage points higher than JSON or text formats and needed noticeably fewer interaction turns. The size of the gain varied by model, and smaller open models benefited less until they were fine-tuned on code-action trajectories.

Training and frameworks built on CodeAct

To make open models better at this style, the authors released an instruction-tuning dataset of roughly 7,000 multi-turn trajectories in which models interact with an interpreter, and fine-tuned agents based on Llama 2 and Mistral 7B. The resulting agents improved on agent tasks while keeping general language abilities largely intact.

The pattern spread quickly into practice. Open-source coding agent platforms adopted a CodeAct-style agent as their default, combining Python execution with shell commands and file editing. Lightweight agent libraries also offer code agents that write Python snippets calling registered tools, alongside conventional tool-calling agents.

The following table shows where the approach typically fits.

SituationRecommended action formatReason
Data analysis and transformationCodeActLoops, filters and libraries in one step
Software engineering tasksCodeAct with shell accessAgent can run tests and inspect output
Simple single API lookupJSON tool callLower overhead and easier validation
High-risk production systemsJSON tool call with permissionsNarrower and auditable action surface
When to choose a CodeAct-style agent

Security, reliability and common pitfalls

The flexibility of CodeAct is also its main risk. Executing model-generated code means that a mistaken or manipulated model can delete files, exfiltrate data or make unwanted network requests. A production deployment therefore requires an isolated agent sandbox, such as a container or microVM with restricted file system access, network egress controls, resource limits and timeouts.

  • Prompt injection in retrieved content can lead the model to write harmful code, so untrusted input must never reach an unsandboxed interpreter.
  • Unbounded loops and heavy computations need execution time and memory limits.
  • Verbose output such as printing an entire dataset can flood the context window; agents should print summaries.
  • Hidden state in a long session can make results hard to reproduce, so trajectories and executed code should be logged.
  • Overreliance on code for tasks that a single tool call solves adds latency and failure points.

Good harnesses combine CodeAct with agent permissions, human-in-the-loop approval for sensitive operations and full agent observability, recording every executed block and its output for later review.

The short version

Most AI assistants act by filling in a form: which tool to use and what to send it. CodeAct lets the AI write a small program instead. The program runs, and the AI sees what happened.

This is like the difference between pressing one button at a time and writing a short recipe. A recipe can repeat steps, make choices and combine ingredients. If the program fails, the error message tells the AI what to fix. The catch is safety. Running code is powerful, so it must happen in a locked-down space.

Where it makes a difference

A finance analyst asks an internal assistant to compare monthly travel spending across 40 departments for the past two years and flag any department whose spending grew by more than 25 percent. With JSON tool calls, the agent would need dozens of separate queries and manual aggregation in its context, which is slow and error-prone.

A CodeAct-style agent instead writes one Python block that queries the expense database, loads the results into a table, groups them by department and month and computes year-over-year growth. The first run fails because a column is named differently than expected; the agent reads the traceback, corrects the name and reruns. Within three turns and about a minute, it returns a sorted list of six flagged departments with a chart, all executed inside a sandbox with read-only database credentials.