When an agent writes Python as its action instead of JSON, it solved 74.4% of multi-tool tasks where JSON solved 52.4%, and used 5.5 turns instead of 7.6.
Pick an action format, slide the number of countries, and press Run. Count the turns. Then we build, piece by piece, why a program is a better action than a single tool call, and how the paper trains a small model to write one.
You need what a language model agent is (a model that calls tools in a loop) and a little Python. We build the rest from zero.
Based on Executable Code Actions Elicit Better LLM Agents by Xingyao Wang, Yangyi Chen, Lifan Yuan, Yizhe Zhang, Yunzhu Li, Hao Peng and Heng Ji (University of Illinois Urbana-Champaign and Apple), ICML 2024. Code, data and model: github.com/xingyaoww/code-act. A reading for Stanford CS 329Z, Lecture 6. Every idea is re-taught here in our own words and devices.
The bars and the average turns are the paper's, from Table 3 for gpt-4-1106-preview on M3 ToolEval: CodeAct 74.4% in 5.5 turns, JSON 52.4% in 7.6, text 53.7% in 7.7. The squares are a toy built from the paper's Figure 1 task. Each country needs its five tools (lookup_rates, lookup_phone_price, convert_and_tax, estimate_shipping_cost, estimate_final_price). JSON and text allow one tool per turn; CodeAct writes one loop. Real runs vary.
Chapter 0
See why an agent that must name each action in a fixed format burns turns, and how a program changes that
You ask an assistant a plain question. Which country is cheapest for buying the CodeAct 1 phone, with tax and shipping included? Check the USA, Japan, Germany and India.
A person would open a spreadsheet and fill in a table. An agent works another way. An agent is a language model inside a loop. It reads the task, picks something to do, sees what happened, and picks again. The thing it picks each time is an action.
This agent owns five tools. A tool is a function the agent may call, like a button it can press. These are the five from the paper’s first figure.
lookup_rates(country: str) -> (float, float) # exchange rate, tax rate lookup_phone_price(model: str, country: str) -> float convert_and_tax(price, exchange_rate, tax_rate) -> float estimate_shipping_cost(destination_country: str) -> float estimate_final_price(converted_price, shipping_cost) -> float
Most agents write an action as a line of JSON, a plain text format for structured data. The line names one tool and its inputs, like {"tool": "lookup_rates", "country": "Germany"}. The system runs the tool and sends the result back. One line calls one tool, and that costs one turn.
A turn is one trip around the loop: the model writes, then the world answers.
Now count. Each country needs all five tools: its rates, the phone price, the conversion with tax, the shipping cost and the final price. Four countries need 20 calls. Then the agent needs one more turn to give the answer. That makes 21 turns, and every turn is a full call to the model.
There is a second cost. At each turn the model reads the whole transcript again: the task, every action so far, and every result. Each turn adds two messages, one action and one result. So the reading does not grow in a straight line. Drag the slider and watch the bars climb.
Each bar is one turn. Its height is the number of earlier messages the model reads before it writes. Blue bars are JSON, one call per turn. The two warm bars are CodeAct, which stops after two turns.
Toy counts, not the paper’s. Every action and every result counts as one message. The model rereads all earlier messages at each turn, and the task text is left out. Five tools per country come from the paper’s Figure 1. For T turns the total is T(T − 1), which is exact under this counting.
With four countries, one call per turn makes the model read 420 earlier messages in all. The program version reads 2. These counts only show the shape of the cost. The paper measures the same pressure in real runs: on its benchmark, code needed up to 30% fewer actions.
What if the action were not one line that names one tool, but a small program? The agent could write a loop. The loop would visit each country, call the tools in order, keep the prices in variables, and pick the smallest. One action. One turn.
That is the paper’s idea, and it names it CodeAct. The agent’s action is executable Python code. A live interpreter runs it. An interpreter is a program that runs code and reports what happened. Here is the program that Figure 1 shows for our task, lightly tidied.
countries = ['USA', 'Japan', 'Germany', 'India'] final_prices = {} for country in countries: exchange_rate, tax_rate = lookup_rates(country) local_price = lookup_phone_price('CodeAct 1', country) converted_price = convert_and_tax(local_price, exchange_rate, tax_rate) shipping_cost = estimate_shipping_cost(country) final_price = estimate_final_price(converted_price, shipping_cost) final_prices[country] = final_price cheapest = min(final_prices, key=final_prices.get) print(cheapest, final_prices[cheapest])
Read it once. A for loop walks the four countries. Each pass makes the five calls and stores the result in final_prices. The last lines use Python’s own min to pick the cheapest country. The agent needs no tool called “find the smallest”. Python already has one.
The paper makes three claims, and this lesson checks each one against its tables. First, code is a better action than JSON or text, most of all when a task needs several tools. On the paper’s new benchmark, M3 ToolEval, code gave up to a 20% higher success rate. Second, error messages from the interpreter let an agent fix its own mistakes. Third, you can train an open model to act this way. The authors built CodeActInstruct, about 7,000 agent runs, and trained CodeActAgent on it.
Earlier work already used code to control robots and game characters. Those systems wrote one fixed program, ran it, and counted a failure as a failure. They could not adjust when the world answered. CodeAct keeps the loop: write code, run it, read the output, write more.
The instrument at the top of the page covers the whole lesson. Chapters 2 to 5 explain the squares. Chapter 6 explains the bars. Chapters 7 to 9 explain how a 7B model learns to act this way. Related lessons: ReAct (the think, act, observe loop that CodeAct builds on), Agents and Tool Use, Tool Use and Function Calling.
Chapter 1
Follow one turn of the loop between an agent, a user and an environment, and meet the action as the thing the agent emits
Picture a friend helping you with a homework problem. The problem: find the sum of the reciprocals of the roots of x2 − 13x + 4 = 0. Your friend has a laptop with a Python notebook open.
Your friend does not shout out the answer. They think for a moment, type a few lines into the notebook, press run, and read what comes back. Then they think again. That is the whole loop. The paper’s Figure 2 draws it, and so will we.
The paper names three roles. The agent is the language model: the friend. The user is the person with the problem: you. The environment is everything else the agent can touch, here the Python notebook. A role is a seat in the loop, not a kind of software.
The paper calls one exchange of information between the agent and another role an interaction. On each turn the agent gets an observation, its input. The observation comes from the user (a sentence in natural language) or from the environment (a code execution result). The agent may first write a plan. That is chain of thought: reasoning written out in words before acting, the way you show your working. Then the agent emits an action, its output. The action goes to the user as language, or to the environment.
Chapter 0 used the word loosely. Here is the exact version. The action is what the agent emits. The observation is what the agent receives. Everything in this lesson depends on what an action looks like.
Press Step. The device plays the start of the paper’s Figure 2 example. The figure shows only the start and elides the rest, so the device stops where the figure stops.
The three boxes are the three roles. The bright arrow shows who sends the next message, and the card shows what it says. Press Step to move one message along.
The task, the code and the first observation are the paper’s Figure 2, copied closely; the figure shortens the agent’s first message with […]. The paper does not show the final answer, so the device stops after four messages.
Three things happened. The user spoke in language. The agent replied to the environment in code, because code is how it touches the world. The environment answered in plain text: the output of the program.
That output was a surprise. The library sympy does symbolic maths, so it keeps square roots exact instead of turning them into decimals. The result was an expression, not a number. A fixed program would have failed here. This agent read the output and chose a different action: find the roots as numbers first. An action can depend on the last observation. That is why the loop matters.
Compare a recipe card with a cook. The card lists every step in advance. The cook tastes the soup and adds salt. The loop hands the agent a tasting spoon: each observation is a chance to change the plan. The paper says earlier code-for-robots systems lacked this. They “struggle to dynamically adjust or emit actions based on new environmental observation and feedback”.
Here is the same loop as code. It is the whole data flow of an agent. The model reads a list of messages, which is text in, and writes text out. A parser decides whether that text is an action. If it is, the environment runs it, and the result joins the list as the next message.
messages = [system_prompt, user_task] # everything the model will read while True: reply = model(messages) # text in, text out messages.append(reply) action = parse(reply) # None if the agent is just talking if action is None: break # the turn goes back to the user observation = environment.run(action) # the world answers messages.append(observation) # the next input
Two words to keep. The action space is the set of everything the agent can write that the environment will accept. A JSON agent has a fixed menu: a list of tool names and their input fields. A CodeAct agent can write any valid Python program. Chapter 2 asks which of these serves an agent better.
This think, act, observe loop is the pattern that our ReAct lesson teaches. CodeAct changes only one thing: what the action is.
We can find the answer without a notebook. For x2 − 13x + 4 = 0, the two roots add up to 13 and multiply to 4. (For x2 + bx + c = 0, they add to −b and multiply to c.) Call the roots r1 and r2. Put the two reciprocals over one denominator.
The agent in the figure does not know this shortcut. It works with numbers instead, and it should land on the same 3.25. The point is not the maths. The point is that the agent’s second move depended on what its first move returned.
Chapter 2
Compare three ways to write an action and see which jobs each one makes hard
A vending machine has a fixed row of buttons. Each press gets you one item. A kitchen has a stove, a knife and a cupboard. In a kitchen you can combine things, repeat a step for every guest, and use what the kitchen already owns.
The paper says that most agents live in the vending machine. They pick one button per turn from a menu somebody wrote in advance. This chapter shows what that menu costs.
First, the formats. The paper’s Table A.6 writes one call to an agenda tool in all three. A format is the exact layout the agent must follow so that the system can read its action. The system reads it by parsing: splitting the text into the tool name and its inputs.
| Format | The same call, as the agent writes it |
|---|---|
| CodeAct | AddAgenda(content="Meeting with John", time="2023-10-26 09:00:00") |
| JSON | {"action": "AddAgenda", "content": "Meeting with John", "time": "2023-10-26 09:00:00"} |
| Text | Action: AddAgenda, content: Meeting with John, time: 2023-10-26 09:00:00 |
For one call, the three are the same. All three name a tool and give it inputs. The differences show up the moment a task needs more than one call, or more than the tools somebody listed. The paper pins this on two limits of JSON and text. The scope is narrow, because the actions are usually built for one task. The flexibility is low, because one action cannot combine several tools.
The paper’s Table 1 compares CodeAct with JSON and text on four jobs. Pick each job in the device below. The left card says what JSON or text needs. The right card says what Python already gives you.
Choose a job. The cards show the paper’s Table 1 wording, then a small example of what that looks like in practice.
The card headlines are the paper’s Table 1 (and its footnotes). The examples under them are our own illustrations of each row, not figures from the paper.
Data. A model learns a format from examples. Code is everywhere in pre-training data, and that includes code that shows useful agent habits: splitting a task into steps and combining several function calls. A custom JSON or text format has no such crowd of examples. Someone must curate data for that one layout.
Complex operations. A loop, an if-statement, or a chain where one tool’s output feeds the next: code does these natively through control flow and data flow. Chapter 4 builds them. With JSON, you can fake an if-statement, but only by careful engineering, such as defining a new tool that mimics it.
Tools. Python has a huge public shelf of packages, listed on PyPI. A code agent can import one and use it. With JSON, a person must write each tool by hand, with its name and its input fields, or wrap an existing package one function at a time.
Feedback. When Python code fails, the interpreter prints a traceback: a report that says which line broke and why. Most programming languages do this already. A JSON system must decide by hand what to tell the agent when a call fails. Or it must pass on the error from whatever language the tools use inside. Chapter 5 shows how much an agent can do with a real traceback.
Take the phone task from Chapter 0 and follow Germany through the JSON column of the paper’s Figure 1. Each step is one turn, and each result is one observation.
{"tool": "lookup_rates", "country": "Germany"}. The environment returns 1.1, 0.19: an exchange rate of 1.1 and a tax rate of 0.19.lookup_phone_price for the model “CodeAct 1” in Germany. The environment returns 700, the price in local money.convert_and_tax: price 700, exchange rate 1.1, tax rate 0.19. It returns 916.3. The numbers fit price × rate × (1 + tax): 700 × 1.1 = 770, and 770 × 1.19 = 916.3.Notice step 3. The agent had to read three numbers off earlier results and type them again by hand. That is a quiet risk. One wrong digit changes the answer, and nothing in the format stops it. A program passes the values through variables instead, which is the subject of Chapter 4.
The paper picks Python for two reasons. It ranked first on the TIOBE index of language popularity in January 2024, and it has many open-source packages. The authors also note that today’s models see a lot of code in pre-training, so adopting CodeAct is cheap. The model already knows the format.
Code is not better at everything. The paper tests this directly. On a plain single call (Chapter 6, Table 2), the three formats are close. JSON even wins for several closed models: gpt-4-1106-preview scores 82.7 with JSON and 76.7 with CodeAct. The authors guess that closed models may have had targeted fine-tuning for JSON. The gap in favour of code opens up on tasks that need composition, and for open-source models, which saw more code than special JSON data.
Chapter 3
Run code in a live interpreter and read what comes back
Think of a scientist’s lab notebook with a calculator built in. You type a line, press run, and the answer appears under it. Type the next line, and it can use any name you made before. The notebook remembers.
CodeAct gives the agent that notebook. The paper says it uses “an interactive Python (Jupyter Notebook) environment”. A Jupyter notebook is a page of code cells that all run inside one Python process. The running process is called the kernel. It holds every variable you have made, until it restarts.
The paper’s Appendix E shows the zero-shot system prompt for a deployed CodeAct agent. “Zero-shot” means it holds no worked examples. It is five short rules, and each rule has a job.
| Rule in the prompt | What it does, in our words |
|---|---|
Put code inside <execute> tags. | Marks the part of the reply that the system will run. |
| Attempt fewer things at a time. | A short block fails in one clear place, so the error is easy to read. |
| Import packages and define variables before use. | Avoids the most common error, a name that does not exist yet. |
| Stop and answer once the output has the answer. | Ends the loop and saves turns. |
| Execute code for the user instead of only showing it. | Code that is shown but never run teaches the agent nothing. |
The first rule is the heart of it. Everything between the tags is the action. Everything outside the tags is talk. The system needs no JSON parser. It cuts out the tagged text and runs it.
Here is one turn, in code. The agent’s reply is a string. If the string holds an <execute> block, the system sends the code to the kernel and catches whatever happens. The result becomes the next observation.
def step(reply: str) -> str | None: code = between(reply, "<execute>", "</execute>") if code is None: return None # no action: the reply goes to the user try: out = kernel.run(code) # variables persist between calls except Exception: out = traceback.format_exc() # the error is just another observation return out # appended to the messages as the next input
Two details are worth a second look. First, the kernel keeps its variables, so a later action can use an earlier result by name. Second, a failure is not special. The traceback is text, and text is what the model reads. Chapter 5 turns this into self-debugging.
Here is what the messages list looks like after two turns of the Germany task. The text is our illustration, and the numbers are from Figure 1. Each line starts with a role. The model reads the whole list and writes only the next assistant message.
system: (the five rules above, plus the tool signatures) user: Is Germany cheap for the CodeAct 1 phone? assistant: I will fetch Germany’s rates first. <execute> rate, tax = lookup_rates('Germany') print(rate, tax) </execute> environment: 1.1 0.19 assistant: (the next message the model must write)
The input is a list of role-tagged strings. The output is one string. Nothing else crosses the boundary between the model and the world. Everything the agent knows about its state is either in the messages or in the kernel.
What about the tools? In CodeAct a tool is simply a Python function that already exists in the kernel. The M3 ToolEval prompt lists each one with its signature, for example click_url(url: str) -> str, and tells the agent that it may use for-loops and if-statements. The agent calls the function by name, as in any program.
Try the notebook below. It holds three cells from the Germany example. Run them in order. Then restart the kernel and run cell 3 first. See what the agent loses when the kernel forgets.
Left: three code cells. Middle: the kernel’s memory. Bottom: the last output. Each cell runs only when you press its button.
The numbers (rate 1.1, tax 0.19, price 700, result 916.3) come from the paper’s Figure 1 for Germany. The three cells and the restart button are our own toy of how a Jupyter kernel behaves.
After cells 1 and 2, the kernel holds three variables: rate, tax and price. Cell 3 can then read them and print 916.3. After a restart, the kernel holds none. Cell 3 fails, and the agent reads NameError. That is also why the prompt says to define variables before use.
The prompt also says that the agent “can install packages through PIP”. In a notebook, a line that starts with an exclamation mark goes to the shell, so !pip install fetches a package from the public shelf. The agent’s reach is then not limited to what the designers installed in advance. This is the “existing software packages” advantage from Chapter 2, made concrete.
It is also the safety question from Chapter 10. A package install runs a stranger’s code on your machine, which is why the sandbox matters.
The notebook matches how an agent works. Its actions come in small pieces, one after another. Each piece builds on the last. The state lives in the kernel, not in the agent’s memory, so the agent does not have to retype values. The model’s own context then holds only the code and the short outputs.
The paper also stresses what is not needed. No in-context demonstrations are given in its Figure 3, where a small 7B model imports pandas, trains a regression model and plots the result. The model already knows Python from pre-training. The prompt only has to say where the code starts and ends.
Chapter 4
Use loops, variables and conditions so that one action does the work of twenty
A cook is making soup for four guests. The cook does not write four separate recipe cards. One card says: “For each guest, chop, simmer, season, and serve.” The card also says where each result goes: the chopped onions go into the pot, and the broth goes into the bowl.
That card has two kinds of structure. The paper names them control flow and data flow. They are the main reason that code beats a menu of one-line actions.
If you code every day, skip to the next heading. If not, here are the four ideas, in plain words.
price = 700 puts 700 in a box named price. Later lines can read the box.for country in countries: runs its block four times if the list holds four countries.if final_price > 900: lets the program skip a country.final_prices["Japan"] = 904.0 adds one row.Control flow is the order of steps, including repeating and skipping them: loops and conditionals. Data flow is how values travel from one step to the next: variables, and the output of one function used as the input of another. The paper says code “inherently supports control and data flow”. A one-line JSON action supports neither.
The device below runs the program from Chapter 0, line by line, for four countries. Watch two counters. One counts tool runs. The other counts what a one-call-per-turn agent would have needed: one model turn for every tool run.
The bright line is the one that just ran. The right side shows what each variable holds right now. Press Step for one line, or Run all to watch the loop go.
Germany’s rate 1.1, tax 0.19, price 700 and converted price 916.3, and the final answer Japan at 904.00, are from the paper’s Figure 1. Every other number is invented so that the program has something to compute. We assume convert_and_tax multiplies price, rate and one plus tax, which fits the figure’s 700, 1.1 and 0.19 giving 916.3.
By the last line, the program has run 20 tools. It stored every result in a variable without retyping it. It used a loop to repeat the five calls, and a built-in min to pick the answer. The agent wrote one action.
Be careful here. The program still runs all 20 tools. The tool runs do not shrink. What shrinks is the number of times the model must write something and read the whole transcript again. Let k be the tools per country, N the number of countries, and r the number of repair rounds, which means extra turns after a mistake.
Worked numbers, with k = 5 and N = 4. JSON takes 5 × 4 + 1 = 21 turns. CodeAct with no errors takes 2. If the first program fails three times, r = 3 and CodeAct takes 5. Code costs more turns than JSON only when 2 + r > kN + 1, that is, when r > kN − 1 = 19 repairs. For one country (N = 1) the break-even is r > 4.
This is a toy formula, but the paper measures the real thing. On M3 ToolEval, gpt-4-1106-preview with CodeAct succeeded on 20.7 points more tasks than the next best format, text, and took 2.1 fewer turns on average. The paper adds that the gains widen as models get stronger. A stronger model writes a longer correct program in one go, so it saves more.
A loop works when the steps are known before the first result arrives. Many tasks are not like that. Take the web-browsing tools in the paper’s prompt: click_url, scroll_down and view. The agent cannot write a loop that clicks the right link before it has seen the page. It must act, read the page, and then decide. So CodeAct does not remove the loop between agent and environment. It removes the turns whose steps the agent could already predict. This reasoning is ours, but it matches the paper’s numbers: even the best model needs 5.5 turns on average, not 2.
There is a limit. When the program is long, one mistake spoils the whole block, and the agent sees the result only at the end. That is why the prompt asks the agent to “attempt fewer things at a time”. A good CodeAct agent writes blocks that are big enough to loop and compose, and small enough to fail in one clear place.
Chapter 5
Watch an agent read an error message and fix its own code
You write a line of code and press run. The screen turns red and says ValueError: could not convert string to float: '?'. You do not need a teacher. The last line names the problem. A question mark sits in a column of numbers. You fix it and run again.
The computer wrote that note for you. Nobody had to design it for this one task. It is part of what Python is. The paper’s fourth job, automated feedback, is exactly this: a code agent gets the note too.
An exception is what Python raises when a line cannot run. It has a type, such as ValueError or NameError, and a message. A traceback is the report Python prints. It lists the line that failed and ends with the type and the message.
In CodeAct the traceback is not hidden from the agent. It comes back as the next observation, like any output (Chapter 3). The agent reads it the way it reads everything else, as text. The paper calls the habit self-debugging: using the error message to repair its own earlier action.
Figure 3 shows a small model, CodeActAgent (Mistral, 7B), working with no demonstrations. The user asks for four things. Download a car dataset. Check it for missing values. Split it into train and test parts. Then train a model that predicts miles per gallon (mpg) from every column except mpg and car name. Step through the first episode.
Press Step to move one message along. Then flip the switch to see the same moment when the environment says only “Error”.
The task, the error line, the agent’s fix and the two scores are from the paper’s Figure 3 (the code lines are shortened). The “Only Error” switch is our own what-if. It shows what information is missing, not a result the paper measured.
Here is what happened, in order. The agent wrote its first program. It ran, and the model-fitting line failed with the ValueError above. The agent read the traceback and said that a '?' in the data blocked the conversion to numbers. It wrote a second action that replaced '?' with a missing-value marker and dropped those rows. The second run succeeded. The cost was one repair round, so r = 1.
The agent then reported the mean squared error and the R2 score. Both are standard ways to grade a model that predicts a number. We define them so that you can read the paper’s numbers.
Now the paper’s numbers. The agent reports an MSE of 10.711 and an R2 of 0.790. The square root of 10.711 is about 3.27, so a typical prediction is off by roughly 3.3 mpg. The R2 of 0.790 means the model explains about 79% of the variation. Working backwards, Var(y) = 10.711 / (1 − 0.790) ≈ 51.0, so the test cars’ mpg values spread about 7.1 mpg around their mean. This arithmetic is ours, drawn from the paper’s two numbers.
Figure 3 goes on. The user asks for a bar chart of the model’s coefficients, then for the x labels rotated by 45 degrees. The second request fails twice. The first error is unexpected keyword argument 'tick_labels', and the agent says that bar() does not take that argument. A later fix is wrong too: set_xticks() is not valid, and the agent switches to xticks(). The figure omits three further rounds of self-debugging for space.
So a repair is not always one round. Each round costs a turn, but each round also gives the agent new facts. This is where the r in Chapter 4’s formula comes from. It is also why the paper’s training data, in Chapter 7, keeps runs that fail first and then recover.
Compare the JSON side. A tool server that raises an error must decide what to send back: the exception text, a code, or nothing at all. Someone must build that. In Python the message already exists, and it is already written for a reader who is trying to fix a bug.
Chapter 6
Read the paper's two tables and see where code wins, where it ties and where it loses
Picture two driving tests. In the first you park once, in a marked bay. In the second you drive a route through town with five stops and a turn at each one. A car that parks well may still get lost on the route. The paper gives agents both tests.
A benchmark is a fixed set of tasks plus a rule for scoring each answer. The paper asks two questions. RQ1: does a model’s familiarity with code, from code in its pre-training data, make CodeAct a better format for a single tool call? RQ2: does CodeAct gain from Python’s control flow and data flow on harder tasks? Each question has its own test.
API-Bank is an existing benchmark of tool calls. The paper uses its level-1 instructions and its toolset, and asks the model for exactly one atomic call: one tool, once. The model writes that call in one of three formats, the ones from Chapter 2. A call counts as correct when running it gives the same output as the ground-truth call.
This test is deliberately unfair to code. One call needs no loop and no variable, so code’s best features are switched off. If CodeAct still holds up, the reason must be that models know the format well.
No existing benchmark fit the second question, so the authors built M3 ToolEval. The three Ms stand for multiple tools, multiple calls and multiple turns. It has 82 human-written tasks in web browsing, finance, travel planning, science and information processing. Each domain has its own set of hand-made tools. Tasks usually need several tools composed together.
The rules are strict. The prompt is simple and gives no examples. The paper calls this zero-shot. The model must use the tools on its own, like a new user who has never seen prompt tricks. In each turn the model may act or may propose an answer. An answer counts only if it matches the true solution exactly. The episode ends at 10 turns or on a correct answer. The paper reports the success rate (the share of proposed answers that were right) and the average number of turns.
One reading tip. An average close to 10 turns means the agent usually ran out of turns without solving the task.
The device holds the paper’s numbers for all 17 models. Switch between the single-call test and the two M3 ToolEval views. Filter by open-source and closed-source models. A dot marks the best format for each model, and ties mark every winner.
Each model has three bars: CodeAct, JSON, text. A dot marks the best format for that model.
All values are from the paper: Table 2 (API-Bank correctness, %) and Table 3 (M3 ToolEval success rate in % and average turns). The tallies are computed here from those tables, with ties counted for every tied format, and they match the paper’s own “frequency of best-performing format” rows.
On single calls, CodeAct matches or beats the other formats for most models. It is best for 8 of 17, JSON for 5 and text for 4. The gap is biggest for open-source models. Llama-2-13b scores 38.1 with CodeAct and only 8.5 with JSON. Llama-2-70b scores 35.6 and 14.3.
JSON does well on closed models. gpt-4-1106-preview scores 82.7 with JSON and 76.7 with CodeAct. The paper’s guess is that closed models may have had targeted fine-tuning for JSON tool calls. For open models, code is the easier road, because they already saw so much code.
On the route test, the picture is sharper. CodeAct has the best success rate for 12 of 17 models and the fewest turns for 12. The best model, gpt-4-1106-preview, solves 74.4% with CodeAct. That is 61 of 82 tasks, because one task is worth 100 / 82 ≈ 1.22 points. JSON solves 43 tasks (52.4%) and text 44 (53.7%). Code is 17 tasks, or 20.7 points, ahead of text, the next best format. It also needs 5.5 turns, against 7.6 for JSON.
The same table is also a warning. The best open-source model reaches 13.4%, while gpt-4-1106-preview reaches 74.4%. Many open models sit near 10 turns and near 0%. The paper blames weak task solving and an inability to follow complex instructions without demonstrations. That gap is what Chapters 7 to 9 try to narrow.
With 82 tasks, scores are coarse and noisy. A simple estimate of the noise in a success rate p measured on n tasks is the standard error.
For p = 0.5 and n = 82, SE = √(0.25 / 82) ≈ 0.055, about 5.5 points. This estimate is ours. The paper’s tables give single numbers, with no error bars. A 20.7-point gap is far larger than 5.5. A 2-point gap, such as 4.9 against 2.4 for CodeLlama-7b, is two tasks and tells you almost nothing. Read the big patterns, not single cells.
Chapter 7
Build training data from agent runs and keep only the runs that recover from errors
A master carpenter records every job on video. You want to train an apprentice from the tapes. Would you keep every tape? A tape where the carpenter cuts the board wrong, notices, and fixes it teaches more than a flawless one. A tape where every cut was wrong and the table came out right by luck teaches nothing good.
That is the idea behind the paper’s training data. Chapter 6 showed a hard fact: open models are far behind. The authors wanted to close the gap by training. They needed tapes. This chapter shows how they made and filtered them.
A trajectory is the full record of one agent run: every message in order, from the user’s task to the final answer. Instruction tuning (also called supervised fine-tuning, or SFT) teaches a model by showing it many example conversations and asking it to write the assistant’s side. A teacher model is a stronger model that creates the examples. Here the teachers are gpt-3.5-turbo-0613, claude-1-instant and claude-2, with gpt-4-0613 for the hardest problems.
The authors did not write problems by hand. They repurposed five existing datasets, grouped by what an agent does in Figure 2.
| Use case | Dataset | How the agent acts |
|---|---|---|
| Information seeking | HotpotQA | Calls a Wikipedia search function, written as Python. |
| Software packages | MATH, APPS | Imports packages such as sympy; writes and tests programs. |
| External memory | WikiTableQuestions | Queries a table with SQL (sqlite3) or with pandas. |
| Robot planning | ALFWorld | Calls robot-control functions in a household simulator. |
Easy problems teach little, and strong models already solve them. So the authors kept the hardest instances. Table A.9 gives the numbers. HotpotQA: 3,000 problems, picked from the 15,661 labelled “hard” (out of 90,447). MATH: 5,586 problems of difficulty 3 or higher. APPS: 4,439 problems that have test cases. WikiTableQuestions: 3,000 problems with the largest tables. ALFWorld: 3,553 problems. That is 19,578 problems in all.
Some of these are single-turn problems with one solution per task. Following MINT, the authors turned them into multi-turn tasks. The agent may interact with the environment for several turns before it submits a solution. For code problems, an in-context example tells the agent to test its code on the given test cases first.
The teachers ran on those problems. Only successful runs with more than two turns were candidates. Then three filters from the paper’s Appendix G.2 decided what to keep. Try them on a toy pool of twelve runs in the device below.
Each row is one successful run. A green square is a code action that ran. A red square is one that raised an error. Switch the three filters on and off and watch which runs survive.
The twelve runs are a toy pool we made up. The three filters follow the paper’s Appendix G.2. The paper’s real counts are 6,985 runs from gpt-3.5 and claude reduced to 6,728, and 413 runs from gpt-4-0613 reduced to 411.
The three filters, in the paper’s words. Code-as-actions: drop runs where the agent used a wrong API call or wrote an action in a format that cannot be parsed and executed. Self-improving: keep runs where the model first hits errors and then fixes them, and drop successful runs in which every code execution failed. The paper does not want the model to learn to run broken code and still hope for a right answer. Instruction-following: drop the rare runs where the agent never replied to the user, which shows up as an odd number of turns.
Two more details from the paper. The cheaper teachers ran first. gpt-4-0613 ran only on problems that none of them could solve, which is why just 411 of the 7,139 runs come from it. Also, a run needs more than two turns to be a candidate. A run of one or two turns has no room for an error and a repair, so there is nothing to learn from it. That reason is ours.
The result is CodeActInstruct: 6,728 runs from gpt-3.5 and claude plus 411 from gpt-4-0613, which makes 7,139.
Table 4 counts the runs and their tokens. A token is a small piece of text, often a word or part of one. The LLMs for Builders lesson explains tokens.
| Part | Runs | Tokens | Tokens per run |
|---|---|---|---|
| HotpotQA | 1,664 | 2,472,227 | 1,486 |
| MATH | 1,732 | 1,719,467 | 993 |
| APPS | 647 | 1,235,472 | 1,910 |
| WikiTableQuestions | 1,065 | 1,316,246 | 1,236 |
| ALFWorld | 2,031 | 3,838,269 | 1,890 |
| CodeActInstruct total | 7,139 | 10,581,681 | 1,482 |
Compare with earlier agent datasets. FireAct has 2,063 runs and 542,176 tokens, about 263 per run. AgentInstruct has 1,866 runs and 2,517,785 tokens. CodeActInstruct has 3.8 times the runs of AgentInstruct and 3.5 times those of FireAct. From Table 4 we get 4.2 times and 19.5 times the tokens. The paper’s text rounds these to 5 and 19. The long runs matter: an average run holds 1,482 tokens because it contains several rounds of action and observation.
A general-conversation set of 69,230 examples is added too (Chapter 8). So code-action runs are 7,139 of 76,369 examples, about 9.3%, and about 16.1% of the tokens.
Chapter 8
Fine-tune a 7B model so that it learns only the assistant side of the conversation
An actor learns a play from the whole script. But the director only grades the actor on the actor’s own lines. The other characters’ lines are read aloud as cues. If the actor were graded on those too, the actor would waste effort memorising lines that someone else will say.
Training CodeActAgent works the same way. The model reads a whole conversation, but it is graded on only one speaker. This chapter follows the data from raw text to the weight update.
CodeActAgent trains on a mixture. The first part is the 7,139 CodeActInstruct runs from Chapter 7. They teach the agent to act on an environment. The second part is general conversation data, 69,230 examples. In the paper’s Figure 2 this half covers the agent talking with the user.
| General set | Examples | What it adds |
|---|---|---|
| OpenOrca (chain of thought subset) | 50,000 | Single-turn reasoning. |
| ShareGPT, sub-sampled | 10,000 | Multi-turn chats; single-turn ones removed. |
| ShareGPT, GPT-4 only | 4,583 | Multi-turn chats from GPT-4. |
| CapyBara | 4,647 | Multi-turn reasoning. |
Why mix? Chapter 9 shows what happens without it. The ablation table says general conversations “are essential to maintain performance on general tasks”. Remove them and the model can still act, but it forgets how to chat.
Every conversation is written in ChatML, a plain layout where each message sits between start and end markers and carries a role: system, user or assistant. The model sees one long string, split into tokens. Environment observations arrive on the non-assistant side, because the model never writes them.
# one training example, as the model reads it (our shortened illustration) <|im_start|>system A chat between a curious user and an AI assistant ... <|im_end|> <|im_start|>user Find the sum of the reciprocals of the roots ... <|im_end|> <|im_start|>assistant <execute> import sympy ... </execute> <|im_end|> # graded <|im_start|>user 1/(3*sqrt(17)/2 + 13/2) + ... <|im_end|> # the world's reply <|im_start|>assistant The roots are symbolic, so ... <|im_end|> # graded
The model reads tokens and, at every position, gives a probability to the next token. (Our LLMs for Builders lesson builds this.) Training pushes up the probability of the correct next token. The measure of how badly it did is the loss. For one token, loss is −log of the probability the model gave to the right token. A confident right answer costs almost nothing. A wrong guess costs a lot.
The paper states that it “only calculate[s] and optimize[s] for loss on the assistant response”. Write A for the set of positions that belong to assistant messages.
The skipped tokens still matter as context. They are cues, not lines. Our reading of why: the environment’s output comes from a real interpreter. A model trained to predict it would practise guessing what code prints, which is the habit the paper warns about in its limits (Chapter 10).
Top: one toy conversation as tokens. A warm block carries loss. A grey block is only context. Bottom: a 4,096-token window holding the paper’s average examples, with and without packing.
The conversation’s token counts are a toy. The window is the paper’s 4,096 tokens for Llama-2, and the example sizes are the paper’s Table 4 averages: 1,482.24 tokens per CodeActInstruct example and 796.57 per general example. The padding shares are computed from those averages.
Look at the bottom panel. A CodeActInstruct example averages 1,482 tokens, so alone it fills 36% of a 4,096-token window. The other 64% would be padding, empty space that the hardware still pays for. The paper “pack[s] short instances into longer ones”: it joins several examples into one window. General examples are even shorter, at 797 tokens, so unpacked they would waste about 81%. The paper also uses flash attention, a faster way to compute attention, for training efficiency. Attention is the step where each token looks back at the earlier tokens.
The authors fine-tune every weight (full-parameter fine-tuning), starting from the base Llama-2 7B and Mistral 7B models. The sequence length is 4,096 tokens for Llama-2 and 16,384 for Mistral. The learning rate is the size of each weight update. It starts at 1e-5 after 50 warm-up steps, then decays along a cosine curve to 1e-6. The batch size is 32: each weight update uses 32 examples. Training runs for five epochs, and an epoch is one full pass over the data. All experiments use the checkpoint from the third epoch. One node with four A100 40GB GPUs trains at around 9,000 tokens per second.
Our arithmetic from Table 4. The mixture holds 65,728,007 tokens. At 9,000 tokens per second, one epoch takes about 7,300 seconds, a little over 2 hours. Three epochs take about 6 hours. Move the slider to see the schedule.
The curve is the learning rate over training. Drag the step. The dashed line marks the end of epoch 3, the checkpoint the paper uses.
The peak 1e-5, the 50 warm-up steps, the end value 1e-6, the batch size 32 and the five epochs are the paper’s (Appendix D). The total of 2,507 steps is our assumption: 65.7 million tokens, packed into 4,096-token sequences, in batches of 32 sequences, for five epochs. Packing and padding in the real run may change it.
Chapter 9
Read Table 5 and the ablations to see what each ingredient adds
You train an apprentice for a month on one kind of job. Three questions follow. Did the apprentice learn that job? Can the apprentice do a nearby job that was not on the training list? And did the month of narrow practice make the apprentice worse at everything else?
The paper asks the same three questions of CodeActAgent. It tests on many tasks, and we need a few words to read the tables.
In-domain (ID) means the test comes from a kind of task that the training data covered. Out-of-domain (OD) means it did not. The paper tests agent skill with MINT, a multi-turn benchmark whose tasks include ALFWorld and MATH, both of which are in CodeActInstruct. So the paper reports MINT twice: ID for the overlap and OD for the rest. Tasks are scored at k = 5 turns.
The other columns are these. M3 ToolEval is Chapter 6’s test, OD. MiniWob++ (computer tasks) and ScienceWorld (a text-based science simulator) are agent tests in which the model must act with text actions, a format it was never trained on. MMLU is multiple-choice knowledge. HumanEval is writing a single function. GSM8K is school maths word problems, solved without tools. MT-Bench checks instruction following, on a scale up to 10. The last column averages them. It excludes in-domain tasks, and it rescales MT-Bench to fit.
Pick a backbone and a comparison. The bars are Table 5 and the ablation Table A.8. Each bar is a score where higher is better.
Warm bars are CodeActAgent. Grey bars are the model you compare it with. Change either control.
All scores are from the paper: Table 5 for the baselines and the two closed models, and Table A.8 for the two ablations. MT-Bench is shown as its 10-point score times ten, so its bar fits the 100-point scale. The ablation table has no M3 ToolEval column, and its overall average (35.1 for Llama-2, 46.8 for Mistral) leaves M3 out, so it differs from Table 5.
The agent skill is real. On MINT in-domain, CodeActAgent (Mistral) scores 57.4, against 18.8 for Mistral Instruct. On MINT out-of-domain it scores 32.4 against 9.7. The two CodeActAgent models beat every open-source model in the table on both MINT columns. On the in-domain column the Mistral version also tops gpt-3.5-turbo (57.4 against 33.9), but it falls short of gpt-4-0613 (68.6).
It transfers, with a catch. On M3 ToolEval, CodeActAgent (Mistral) reaches 12.2. That is close to the two 70B open models in Table 3, which score 11.0 and 13.4. The Llama-2 version scores 0.0 and shows no gain. Appendix H looks at its outputs and finds strange artifacts, such as the line “nobody is here to check your work, you can do whatever you want” after a wrong answer. The authors guess these come from Llama-2’s pre-training data, or from a weaker base model. They do not prove it.
It carries over to text actions. CodeActAgent (Llama-2) was never trained on text actions. It scores 25.5 on MiniWob++, close to AgentLM’s 28.9, a model tuned for that format. On ScienceWorld it scores 17.6, above AgentLM’s 13.7.
General skill holds up. Both models improve on HumanEval, GSM8K and MT-Bench over their Instruct or Chat versions. MMLU slips slightly for Mistral: 59.1, against the base model’s 60.1. The overall average rises from 21.1 (Llama-2 Chat) to 30.7, and from 25.6 (Mistral Instruct) to 42.5. To compare with other agent-tuned models, the paper reports a relative improvement, which we write as follows.
Against AgentLM (24.8): (30.7 − 24.8) / 24.8 = 0.238, a 24% relative gain. Against FireAct (14.0): (30.7 − 14.0) / 14.0 = 1.19, a 119% gain. These are the paper’s two figures for CodeActInstruct against earlier agent data, and the arithmetic reproduces them.
Training beats size only inside the domain. Pick gpt-3.5-turbo-0613 in the device. On MINT in-domain, the 7B CodeActAgent (Mistral) scores 57.4 against 33.9. On MINT out-of-domain it scores 32.4 against 38.2, and on M3 ToolEval 12.2 against 51.2. Training on a domain can beat a bigger model on that domain. It does not give the bigger model’s breadth. That is also why the paper reports in-domain and out-of-domain scores in separate columns.
Choose the ablation comparisons in the device. “Without CodeActInstruct” trains on the general conversations alone. MINT in-domain falls from 51.3 to 17.0 for Llama-2 and from 57.4 to 32.9 for Mistral. The agent data is the source of the agent skill.
“Without general conversations” trains on the 7,139 runs alone. The agent skill survives, but everything else breaks. For Mistral, GSM8K falls from 58.0 to 26.8 and MT-Bench from 8.2 to 2.6. MiniWob++ falls from 46.2 to 0.0: without conversational data the model no longer follows the text format. So the mix matters in both directions. One caution: on MiniWob++, the model without CodeActInstruct scores a little higher (36.4 against 25.5 for Llama-2, and 47.8 against 46.2 for Mistral). Code actions help code tasks. They do not help every text task.
Chapter 10
Name what the paper did not show, and what can go wrong when an agent can run code
A drill is stronger than a screwdriver. It is also easier to hurt yourself with. Giving an agent a code interpreter is the same kind of trade. The agent gets a far wider reach, and so does every mistake it makes.
A good reader asks what a paper does not show. This chapter lists what the authors say about their own limits, what the numbers cannot tell us, and what stays open.
The paper calls CodeActAgent “an initial prototype of an autonomous agent”. Its listed problem is hallucination: a model states something false as if it were fact. The paper’s example is specific to code agents. The agent may “imagine the content of a variable without actually printing it out”. It then acts on a made-up value. The authors suggest alignment training, such as learning from human feedback, as a fix.
The self-debugging skill is also called “limited”. Chapter 5 showed why: repairs can take several rounds, and each round can go wrong. The paper’s future work is to let agents interact more with an environment and bootstrap their own improvement from past mistakes. That is an idea, not a result.
The paper is direct about one risk. CodeAct gives the agent the power to run code “freely” in a sandbox. A sandbox is a fenced area of a computer where code can run without touching anything outside. The worst case, in the authors’ words, is an agent that breaks out of the sandbox and does harm, for example by cyber-attack. They call for better safety mechanisms in future work.
The paper offers no design for that. Our practical reading, not the paper’s: treat model-written code like code from a stranger. Run it in a container with no secrets, limit its network and its time, and log each action. Our lessons on Code as Agent Harness and Harness Engineering go deeper on this.
The authors also note a wider effect: a fully autonomous agent may change the labour market and affect existing jobs.
Choose a limit in the device. Four of them are about numbers, and two are about what the paper says in words.
Pick a limit. The picture shows the paper’s numbers where it has them, and the paper’s words where it does not.
Bars use the paper’s Table 3 and Table 5 (CodeAct format on M3 ToolEval). The 82-task grid uses the gpt-4-1106-preview results from Table 3: 61, 43 and 44 solved. The noise whiskers are our estimate, the standard error of a proportion from Chapter 6, not a figure from the paper.
Small tests. M3 ToolEval has 82 tasks. One task is worth 1.2 points, and a rough standard error is about 4 or 5 tasks. The headline gap of 17 tasks stands out. Gaps of two or three tasks do not. The paper reports single numbers and no error bars.
Zero-shot only. The test prompt is deliberately plain, with no examples. That models a novice user. It does not show what a tuned prompt could do for JSON or text. A strong JSON agent with a good prompt might close part of the gap. The paper does not test it.
Teacher data. Every one of the 7,139 training runs came from a stronger teacher: gpt-3.5, claude or gpt-4. Our reading is that the student inherits the teacher’s habits and mistakes, and that a teacher’s licence terms may limit how the data can be used. The paper does not discuss either point.
One example of failure. The Llama-2 version scored 0.0 on M3 ToolEval. The authors checked their training mix, found no match for the odd text, and guessed pre-training artifacts. A real cause stays unknown.
Exact-match scoring. M3 ToolEval counts an answer only if it matches the true solution exactly, and the prompt asks for a fixed layout such as “xx.xx”. Our reading: a model that finds the right number but writes it in the wrong layout scores zero for that task. The score then mixes two skills, solving the task and following the answer format.
Several earlier systems also let models write code: Code as Policies for robots, PAL for maths, Voyager for games. The paper’s Appendix A says most of them write one static program in a single try. A failed first attempt counts as a failure. Voyager does iterate, but it rewrites whole functions, so it cannot adjust one atomic step on the fly. CodeAct works one small action at a time, with no hand-built prompts for each domain. TaskWeaver, a concurrent project, had only a few qualitative examples with closed models. CodeAct adds a benchmark, a dataset and an open model.
Chapter 11
Carry the numbers, the terms, the core loop and the next readings away on one page
CodeAct lets an agent write its action as Python and run it in a live notebook. One program can loop, store values and call many tools, so the agent needs fewer turns. Errors come back as tracebacks, so the agent can repair its own code. The authors collected 7,139 agent runs, kept the ones that show good recovery, mixed them with 69,230 general conversations, and fine-tuned two 7B models. The result is a small open model that is far better at agent tasks, though still behind the closed models.
| Number | What it is | Where |
|---|---|---|
| 74.4 / 52.4 / 53.7 | M3 ToolEval success for gpt-4-1106-preview: CodeAct, JSON, text | Table 3 |
| 5.5 / 7.6 / 7.7 | Average turns for the same three | Table 3 |
| 82 | Human-written tasks in M3 ToolEval, 10 turns at most | Section 2.3 |
| up to 20 / up to 30 | Points of higher success, and percent fewer actions | Abstract, Section 1 |
| 8 / 5 / 4 | Models with the best single-call format: CodeAct, JSON, text (17 models) | Table 2 |
| 12 / 5 / 4 | Models with the best M3 success: CodeAct, JSON, text | Table 3 |
| 7,139 | CodeActInstruct runs (6,728 + 411), 10,581,681 tokens, 1,482 per run | Table 4, G.2 |
| 69,230 | General conversation examples, 55,146,326 tokens | Table 4 |
| 1e-5 to 1e-6 | Learning rate with 50 warm-up steps; batch 32; 5 epochs, checkpoint 3 | Appendix D |
| 4,096 / 16,384 | Sequence length for Llama-2 and for Mistral | Section 3.2 |
| 57.4 / 32.4 / 12.2 | CodeActAgent (Mistral): MINT in-domain, MINT out-of-domain, M3 ToolEval | Table 5 |
| 42.5 vs 25.6 | Overall average, CodeActAgent (Mistral) against Mistral Instruct | Table 5 |
| 24% / 119% | Relative gain of CodeActAgent (Llama-2) over AgentLM and FireAct | Table 5 |
Try the numbers in the device. It shows the headline pairs, including one where CodeAct loses.
Choose a headline. The warm bar is CodeAct or CodeActAgent. The others are what it was compared with.
Every value is the paper’s. The first three headlines use gpt-4-1106-preview. The last two use CodeActAgent (Mistral, 7B) against Mistral Instruct 7B.
| Term | Meaning | Ch. |
|---|---|---|
| agent, action, observation | A model in a loop; what it emits; what it receives. | 1 |
| action space | Everything the agent can write that the environment accepts. | 1 |
| CodeAct | Executable Python as the action, run in a live interpreter. | 3 |
| kernel | The running process that keeps variables between actions. | 3 |
| control flow, data flow | Order and repetition of steps; values passed between steps. | 4 |
| traceback, self-debugging | Python’s error report; using it to repair the next action. | 5 |
| atomic call | One tool, called once. The API-Bank test. | 6 |
| M3 ToolEval | 82 tasks needing multiple tools, calls and turns. | 6 |
| trajectory, teacher | One full agent run; the stronger model that writes it. | 7 |
| CodeActInstruct | 7,139 filtered runs for instruction tuning. | 7 |
| loss mask, packing | Grade only assistant tokens; fill each window with several examples. | 8 |
| in-domain, out-of-domain | Covered by the training data, or not. | 9 |
| sandbox, hallucination | A fenced place to run code; a confident false statement. | 10 |
This is our sketch of the whole method, not the authors’ code. It has the agent loop, the filter from Chapter 7 and the loss mask from Chapter 8. The value -100 is the label that PyTorch’s cross-entropy loss skips by default.
import re, io, contextlib, traceback def run_in_kernel(code, ns): # ns = the kernel's memory buf = io.StringIO() try: with contextlib.redirect_stdout(buf): exec(code, ns) # variables persist in ns return buf.getvalue() or "(no output)" except Exception: return traceback.format_exc(limit=1) # the error is an observation def codeact_agent(model, task, tools, max_turns=10): ns = dict(tools) # tool functions live in the kernel messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": task}] for turn in range(max_turns): # M3 ToolEval allows 10 reply = model(messages) # list of messages in, one string out messages.append({"role": "assistant", "content": reply}) m = re.search(r"<execute>(.*?)</execute>", reply, re.S) if m is None: return reply, messages # no action: the answer goes to the user obs = run_in_kernel(m.group(1), ns) messages.append({"role": "user", "content": obs}) return None, messages # out of turns def keep(t): # Chapter 7: the three filters if not t.success or t.n_turns <= 2: return False if not t.code_format_ok: return False # code-as-actions if t.runs and not any(ok for _, ok in t.runs): return False # self-improving return t.n_turns % 2 == 0 # instruction-following def labels(tokens, roles): # Chapter 8: loss on assistant tokens only return [tok if r == "assistant" else -100 for tok, r in zip(tokens, roles)]
CodeAct sits between two older ideas. One is the tool-calling loop, in which a model picks one function per turn. Our ReAct, Agents and Tool Use and Tool Use and Function Calling lessons teach that. The other is code generation for control, such as Code as Policies, PAL and Voyager, where the model writes a program and runs it once. CodeAct keeps the loop and changes the action to code. The wider question of how to build the system around the model is the topic of Harness Engineering and Code as Agent Harness.
Cite as: Xingyao Wang, Yangyi Chen, Lifan Yuan, Yizhe Zhang, Yunzhu Li, Hao Peng and Heng Ji. “Executable Code Actions Elicit Better LLM Agents.” Proceedings of the 41st International Conference on Machine Learning, PMLR 235, 2024. arXiv:2402.01030.
Now try Teach mode: explain the loop from a blank whiteboard, then go back to the instrument at the top and count the turns again, this time knowing why.