Chain-of-code is a prompting technique in which a language model expresses its reasoning as a program and then executes that program with an interpreter, while the model itself simulates any line the interpreter cannot run. In prompting for language models, it extends chain-of-thought and program-aided approaches to problems that mix precise computation with semantic judgment, such as counting sarcastic sentences or sorting items by an informal property.
The technique was introduced in 2023 by researchers from Google DeepMind and Stanford University. Its central contribution is the LMulator, a combination of a real code interpreter and a language model acting as a code emulator, which lets reasoning written as code continue even when it calls functions that do not exist.
How chain-of-code reasons through code
Chain-of-code works in two phases: code generation and code execution. First, the model receives a question, often with a few demonstrations, and writes a short program that breaks the task into steps. The program may contain ordinary Python as well as pseudocode calls such as is_fruit(item) or detect_sarcasm(sentence) that no library implements.
Second, the program runs line by line. When a line is valid executable code, the Python interpreter evaluates it and the program state updates exactly. When a line raises an error because a function is undefined or the logic is semantic, the language model predicts the result of that line, writes the value into the program state and execution continues from the next line.
The table below shows how each kind of line is handled during execution.
| Line type | Example | Who evaluates it |
|---|---|---|
| Arithmetic and control flow | total = total + 1 | Python interpreter |
| Standard library calls | sorted(values) | Python interpreter |
| Undefined semantic function | is_sarcastic(sentence) | Language model simulation |
| Ambiguous comparison | answer = more_formal(a, b) | Language model simulation |
| Line that fails at runtime | Type error on a string | Language model simulation |
Why mixing execution and simulation helps
Chain-of-code addresses a gap between two earlier methods. Plain chain-of-thought reasoning handles semantic questions well but makes arithmetic and bookkeeping errors. Program-aided methods compute precisely but fail completely when the task needs a judgment that cannot be written as code.
Because the interpreter keeps an explicit program state, intermediate values such as counters, lists and dictionaries stay consistent across many steps. The model needs to reason only about the small semantic sub-questions, while loops, sums and comparisons are delegated to deterministic execution. On the BIG-Bench Hard suite, the original authors reported about 84 percent accuracy, roughly 12 percentage points above chain-of-thought in their setup.
The following table summarizes which kinds of reasoning benefit most.
| Task type | Main difficulty | Expected benefit |
|---|---|---|
| Algorithmic tasks | Exact counting, sorting, tracking state | High, mostly from the interpreter |
| Mixed semantic and numeric tasks | Judgments combined with arithmetic | High, from the combination |
| Purely semantic tasks | Interpretation, tone, world knowledge | Small to moderate |
| Robotics and planning | Object reasoning plus spatial logic | Moderate to high in reported tests |
Chain-of-code compared with related prompting techniques
Chain-of-code belongs to a family of structured reasoning prompts. It differs from its neighbors mainly in who executes the steps and what happens when code cannot run.
| Technique | Form of reasoning | Execution | Behavior on non-executable steps |
|---|---|---|---|
| Chain-of-thought | Natural language | None, the model reasons in text | Handled in text |
| Program-aided language model | Python code | Interpreter only | Program fails |
| Program of thoughts | Python code | Interpreter only | Program fails |
| Chain-of-code | Code and pseudocode | Interpreter plus model emulation | Model simulates the line |
| Scratchpad prompting | Code-like traces in text | Model only | Handled by the model |
A useful way to see the difference is that program-aided methods treat code as a strict tool, whereas chain-of-code treats code as a flexible reasoning language that may contain informal steps. This flexibility is the source of both its gains and its risks.
Implementing chain-of-code in practice
A practical implementation needs a sandboxed interpreter, a loop that catches exceptions and a prompt that asks the model to return the value of the failed line given the current variables. The model’s answer is parsed, assigned to the target variable and execution resumes.
- Run code in an isolated sandbox with time and memory limits, because generated programs can contain infinite loops or unsafe calls.
- Pass the current program state to the model when it simulates a line, so its answer stays consistent with earlier values.
- Constrain the format of simulated values, for example a Boolean or a number, to keep the program type-consistent.
- Log every simulated line separately, so reviewers can see which results were computed and which were predicted.
Teams often start with a few-shot prompt of three to five demonstrations that show mixed code and pseudocode, then measure accuracy against chain-of-thought on their own task before adopting the more complex pipeline.
Limitations and common mistakes
Chain-of-code adds engineering overhead and new failure modes. The table below lists frequent problems and their usual remedies.
| Problem | Cause | Remedy |
|---|---|---|
| Confident wrong simulated values | Model guesses the result of a semantic line | Ask for constrained outputs and verify samples |
| State drift | Simulated value has the wrong type | Validate types before assignment |
| Security exposure | Generated code runs without isolation | Use a locked-down sandbox |
| Higher latency and cost | Many model calls for simulated lines | Batch or cache repeated calls |
| Little gain on simple tasks | Task needs no computation | Use plain chain-of-thought instead |
The most important caution is that simulated lines look like executed code but are not verified. A reader of the trace can mistake a guess for a computed fact, so production systems should mark emulated results clearly.
Stripped to the essentials
Chain-of-code asks an AI model to solve a problem by writing a small program. A computer runs the parts it can run. Those parts give exact answers.
Some steps need judgment, such as deciding whether a remark is sarcastic. A computer cannot run that step. So the AI model fills in the answer itself and the program continues. The computer does the counting and the model does the judging. Each side handles the part it does best.
Where it is applied
A customer support team wants to know how many of 200 product reviews mention a delivery complaint and what share of those also request a refund. A plain chain-of-thought prompt loses count after a few dozen reviews, and a pure Python script cannot judge what counts as a complaint.
With chain-of-code, the model writes a loop over the reviews that calls mentions_delivery_problem(review) and asks_for_refund(review), then increments two counters. The interpreter runs the loop and the arithmetic, while the model answers each undefined call. The analyst receives exact totals and a percentage, plus a log of every judgment the model made, which makes spot-checking the borderline reviews straightforward.