Chain-of-code

On this page 7

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 typeExampleWho evaluates it
Arithmetic and control flowtotal = total + 1Python interpreter
Standard library callssorted(values)Python interpreter
Undefined semantic functionis_sarcastic(sentence)Language model simulation
Ambiguous comparisonanswer = more_formal(a, b)Language model simulation
Line that fails at runtimeType error on a stringLanguage model simulation
How the LMulator handles different program lines

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 typeMain difficultyExpected benefit
Algorithmic tasksExact counting, sorting, tracking stateHigh, mostly from the interpreter
Mixed semantic and numeric tasksJudgments combined with arithmeticHigh, from the combination
Purely semantic tasksInterpretation, tone, world knowledgeSmall to moderate
Robotics and planningObject reasoning plus spatial logicModerate to high in reported tests
Task types and the expected benefit of chain-of-code

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.

TechniqueForm of reasoningExecutionBehavior on non-executable steps
Chain-of-thoughtNatural languageNone, the model reasons in textHandled in text
Program-aided language modelPython codeInterpreter onlyProgram fails
Program of thoughtsPython codeInterpreter onlyProgram fails
Chain-of-codeCode and pseudocodeInterpreter plus model emulationModel simulates the line
Scratchpad promptingCode-like traces in textModel onlyHandled by the model
Comparison with neighboring prompting techniques

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.

ProblemCauseRemedy
Confident wrong simulated valuesModel guesses the result of a semantic lineAsk for constrained outputs and verify samples
State driftSimulated value has the wrong typeValidate types before assignment
Security exposureGenerated code runs without isolationUse a locked-down sandbox
Higher latency and costMany model calls for simulated linesBatch or cache repeated calls
Little gain on simple tasksTask needs no computationUse plain chain-of-thought instead
Typical problems with chain-of-code and how to address them

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.