About this notebook

Companion to Module 8: Code execution and skills. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)

Until now every action an agent took was one call to one tool that you wrote in advance. This notebook lets the model write a small program instead, and builds the thing that makes that tolerable: a sandbox. You will

  1. solve a price comparison with ordinary JSON tool calls, and count what it costs;
  2. run code the naive way, with subprocess, and see what that code can reach;
  3. build a sandbox one layer at a time: folder, environment, time, CPU, memory, network, files and output size, and watch each layer stop something;
  4. wrap the sandbox as an execute_python tool and solve the same task with CodeAct;
  5. measure how both styles grow as the task gets bigger;
  6. see why a traceback is a useful observation.

Which model answers here?

With no MODEL set, the offline policy model answers: deterministic rules that read the request and reply the way a tool-calling model would. It is not a language model. In section 4 it fills a fixed program template from the question; a real model writes its own program, which may be better, worse or simply different. The sandbox, on the other hand, is real: every limit below is enforced by the operating system on this machine. Set MODEL (for example MODEL=anthropic/claude-sonnet-5-5) and re-run to see what a real model writes.

from agentlab.nbsetup import setup
 
nb = setup("08a_codeact_sandbox", packs=["codeact"])
llm = nb.llm

LLM backend

offline policy model (deterministic, rule-based, no API key used)

1. A task for tools: the cheapest store

A shopper wants three pairs of headphones delivered to Berlin and asks which of three online stores is cheapest, in euros. Each store prices in its own currency and charges its own shipping, so the answer needs three kinds of facts. Here they are as three plain functions. Their data lives inside the function bodies, which matters later: a function that needs nothing from outside can be copied into a sandbox and run there.

def get_price(store: str, item: str) -> dict:
    """Unit price of an item at one store, in that store's currency.
 
    Args:
        store: The store's name, for example "alpha".
        item: The product, for example "headphones".
    """
    catalogue = {
        "alpha": ("USD", 89.00), "berg": ("EUR", 84.50), "corso": ("GBP", 71.00),
        "delta": ("USD", 92.50), "elm": ("EUR", 86.00), "fjord": ("GBP", 69.50),
        "grove": ("USD", 87.00), "harbor": ("EUR", 88.90), "iris": ("GBP", 72.40),
        "juno": ("USD", 90.10), "kite": ("EUR", 83.90), "lumen": ("GBP", 70.80),
    }
    if item != "headphones":
        raise ValueError(f"{store} does not sell {item!r}; it only stocks headphones")
    currency, price = catalogue[store]
    return {"price": price, "currency": currency}
 
 
def get_shipping(store: str, city: str, units: int) -> float:
    """Shipping cost of one parcel, in the store's currency.
 
    Args:
        store: The store's name.
        city: Destination city: Berlin, Madrid or Paris.
        units: Number of items in the parcel.
    """
    base = {"alpha": 25.0, "berg": 12.0, "corso": 18.0, "delta": 19.0, "elm": 14.5,
            "fjord": 21.0, "grove": 23.0, "harbor": 9.9, "iris": 16.0, "juno": 20.0,
            "kite": 15.5, "lumen": 17.0}
    if city not in ("Berlin", "Madrid", "Paris"):
        raise ValueError(f"no shipping to {city!r}; we ship to Berlin, Madrid and Paris")
    return round(base[store] + 1.5 * (units - 1), 2)
 
 
def convert(amount: float, from_currency: str, to_currency: str) -> float:
    """Convert an amount between USD, EUR and GBP at fixed rates.
 
    Args:
        amount: The amount to convert.
        from_currency: Currency code of the amount: USD, EUR or GBP.
        to_currency: Currency code to convert to.
    """
    eur_per_unit = {"EUR": 1.0, "USD": 0.92, "GBP": 1.17}
    return round(amount * eur_per_unit[from_currency] / eur_per_unit[to_currency], 2)
 
 
QUESTION = ("Which of the stores alpha, berg and corso is cheapest for 3 headphones "
            "shipped to Berlin, in EUR?")

With JSON tool calling, each function becomes a tool and the model asks for one call at a time (or a batch of independent calls in one turn). Run the agent and print what happened.

from agentlab import Agent, FunctionTool, ToolCall, ToolResult
from agentlab.display import show_trajectory
 
JSON_PROMPT = ("Answer shopping questions with the tools. "
               "Quote final prices in the currency asked.")
json_tools = [FunctionTool(f) for f in (get_price, get_shipping, convert)]
json_agent = Agent(llm, tools=json_tools, instructions=JSON_PROMPT, max_steps=40,
                   name="json")
result = await json_agent.run(QUESTION)
show_trajectory(result, width=84)
print("\nanswer:", result.output)
[user] Which of the stores alpha, berg and corso is cheapest for 3 headphones shipped to...
[json -> get_price] {"store": "alpha", "item": "headphones"}
[json -> get_price] {"store": "berg", "item": "headphones"}
[json -> get_price] {"store": "corso", "item": "headphones"}
    [get_price ok] {"price": 89.0, "currency": "USD"}
    [get_price ok] {"price": 84.5, "currency": "EUR"}
    [get_price ok] {"price": 71.0, "currency": "GBP"}
[json -> get_shipping] {"store": "alpha", "city": "Berlin", "units": 3}
[json -> get_shipping] {"store": "berg", "city": "Berlin", "units": 3}
[json -> get_shipping] {"store": "corso", "city": "Berlin", "units": 3}
    [get_shipping ok] 28.0
    [get_shipping ok] 15.0
    [get_shipping ok] 21.0
[json -> convert] {"amount": 295.0, "from_currency": "USD", "to_currency": "EUR"}
[json -> convert] {"amount": 234.0, "from_currency": "GBP", "to_currency": "EUR"}
    [convert ok] 271.4
    [convert ok] 273.78
[json] berg is the cheapest: EUR 268.50 for 3 headphones shipped to Berlin (then alpha E...
--- status: complete, steps: 4

answer: berg is the cheapest: EUR 268.50 for 3 headphones shipped to Berlin (then alpha EUR 271.40, corso EUR 273.78).

Four model calls and eight tool calls for a question a person would answer with one short calculation. Look at what happened between the calls, too. After the shipping results came back, something had to compute 3 * 89.00 + 28.0 = 295.0 before asking for a conversion. That something was the model, doing arithmetic in text. The offline model adds exactly because it is Python; a real model usually gets such sums right and occasionally does not, and nothing checks it.

Hur and Song name three limits of predefined tools that this example shows in miniature:

  • the action space is fixed: the model can only do what some tool already does (there is no “add these up” tool, so it adds in its head);
  • one call does one thing: a loop over stores becomes a round trip per batch, and every result is pasted back into the context;
  • tools multiply: covering each new need with a new tool makes the tool list, and the prompt that describes it, longer for every request.

The alternative is to let the model write the loop. In the CodeAct pattern (Wang et al., 2024) the action is a program, the functions are a library it can call, and the observation is whatever the program prints.

  JSON tool calls                         CodeAct
  model -> get_price x3      -> results   model -> one program  ----------+
  model -> get_shipping x3   -> results              for each store:      |
  (model adds totals in text)                          price, shipping,   | sandbox
  model -> convert x2        -> results                total, convert     |
  model -> answer                                     print the totals   -+
                                          model -> answer (from the printout)

A program is also arbitrary code. Before handing the model a Python interpreter, we need somewhere safe to run what it writes.

2. Running code the naive way

The obvious implementation is subprocess.run([sys.executable, "-c", code]). To see what such code can reach, set a fake secret in the notebook’s environment (it is not a real key) and run a small probe that prints only yes or no answers.

import os
import subprocess
import sys
 
from agentlab.config import repo_root
 
os.environ["DEMO_API_KEY"] = "demo-not-a-real-key"
HERE, PYPROJECT = os.getcwd(), str(repo_root() / "pyproject.toml")
PROBE = f"""
import os
 
def can_read(path):
    try:
        with open(path) as f:
            f.read(1)
        return True
    except OSError:
        return False
 
print("sees DEMO_API_KEY:", "DEMO_API_KEY" in os.environ)
print("runs in the notebook's folder:", os.getcwd() == {HERE!r})
print("can read the course's pyproject.toml:", can_read({PYPROJECT!r}))
"""
naive = subprocess.run([sys.executable, "-c", PROBE], capture_output=True, text=True,
                       timeout=30)
print(naive.stdout)
sees DEMO_API_KEY: True
runs in the notebook's folder: True
can read the course's pyproject.toml: True

Yes to everything. The child process inherits the notebook’s environment (real API keys included, if you have set any), its working directory and its access to every file you can read. It would also inherit the right to open network connections, to delete files, to loop forever and to allocate memory until the machine swaps. A model does not need to be malicious for this to matter: a confused rm -rf build/ from the wrong folder, a while True without a break, or code copied from a document that was written by someone else (Module 12 looks at that case) are enough.

3. A sandbox, layer by layer

agentlab.sandbox.LocalSandbox runs a command in a child process wrapped in several independent layers. No layer is enough alone, and each one fails differently, so the goal is that every likely accident hits at least one of them.

layerwhat it stopshow
fresh folderwrites into your projectthe process starts in its own work directory
clean environmentleaked secretsonly PATH, HOME, locale and Python settings are passed
wall-clock timeoutwaiting foreverthe whole process group is killed after timeout_s
CPU limitbusy loopsthe kernel stops the process after cpu_s CPU-seconds
memory watchdogrunaway allocationresident memory is polled and the group killed past mem_mib
file-size limitfilling the diskno single file larger than fsize_mib
sandbox-exec (macOS)network, writes elsewhere, reading your home foldera kernel policy
output capflooding the model’s contextstdout and stderr are cut at a fixed size

The same probe, inside a sandbox:

from agentlab.sandbox import LocalSandbox, fresh_dir, jail
 
SBX = nb.workdir / "sandboxes"
fresh_dir(SBX)
sbx = LocalSandbox(workdir=SBX / "probe", timeout_s=10, cpu_s=5, mem_mib=512)
print(sbx.run_python(PROBE).stdout)
print("isolation:", sbx.isolation)
sees DEMO_API_KEY: False
runs in the notebook's folder: False
can read the course's pyproject.toml: False

isolation: sandbox-exec: no network (loopback included); writes only inside the work directory; home directory unreadable except the work directory and Python

On macOS the last answer is False because of the kernel policy, not because the file is missing; on Linux this local sandbox cannot hide your files and says so in isolation.

Time: the wall clock and the CPU

Two kinds of “forever” need two limits. A program that waits (on sleep, on a socket, on input that never comes) uses no CPU, so only a wall-clock timeout catches it. A busy loop burns CPU; the kernel’s RLIMIT_CPU stops it even if the parent process is itself stuck.

waiting = LocalSandbox(workdir=SBX / "time", timeout_s=1.0, cpu_s=5)
r = waiting.run_python("import time\nwhile True:\n    time.sleep(0.1)")
print("sleep loop:", r.killed_by, "| exit code", r.returncode, "| timed out:", r.timed_out)
 
spinning = LocalSandbox(workdir=SBX / "cpu", timeout_s=10.0, cpu_s=1)
r = spinning.run_python("while True:\n    pass")
print("busy loop: ", r.killed_by, "| exit code", r.returncode, "| timed out:", r.timed_out)
sleep loop: timeout | exit code -9 | timed out: True
busy loop:  cpu | exit code -24 | timed out: False

Exit code -9 is SIGKILL, sent by the sandbox when the clock ran out; -24 is SIGXCPU, sent by the kernel. The timeout kills the whole process group, so a child that the code started in the background dies with it instead of running on after the tool returned.

Memory

The kernel limit on address space (RLIMIT_AS) is not enforced on macOS, so the sandbox watches instead: a thread sums the resident memory of the process tree every 50 ms and kills the group once it passes mem_mib. The program below grows by 16 MiB every 20 ms toward 768 MiB; the cap is 256 MiB.

hungry = LocalSandbox(workdir=SBX / "memory", timeout_s=10.0, mem_mib=256)
GROW = """
import time
chunks = []
for _ in range(48):
    chunks.append(bytearray(16 * 2**20))
    time.sleep(0.02)
print("allocated 768 MiB")
"""
r = hungry.run_python(GROW)
print("killed by:", r.killed_by, "| finished:", "allocated" in r.stdout)
print("what the model would see:", r.to_text().splitlines()[0])
killed by: memory | finished: False
what the model would see: killed: memory limit

A watchdog that polls is a weaker guarantee than a kernel limit: a process that allocates faster than one poll interval overshoots the cap before it is caught. While building this sandbox, a one-shot 1 GiB allocation under a 512 MiB cap reached about 800 MiB before it died. That is fine for catching accidents and useless against an adversary; containers (cgroups on Linux) enforce memory in the kernel.

Network and files

On macOS, sandbox-exec applies a kernel policy to the process: no network at all, writes only inside the work directory, and no reading of your home folder apart from that directory and the Python installation. To test the network rule without the internet, start a tiny web server inside this notebook on 127.0.0.1 and let sandboxed code try to reach it, once with the network denied and once allowed.

import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
 
 
class Hello(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"hello from the notebook")
 
    def log_message(self, *args):
        pass
 
 
server = ThreadingHTTPServer(("127.0.0.1", 0), Hello)
threading.Thread(target=server.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{server.server_port}/"
FETCH = f"import urllib.request\nprint(urllib.request.urlopen({URL!r}).read().decode())"
 
if jail.available():
    for allowed in (False, True):
        box = LocalSandbox(workdir=SBX / f"net-{allowed}", network=allowed)
        r = box.run_python(FETCH)
        last = (r.stdout or r.stderr).strip().splitlines()[-1]
        print(f"network={allowed}: {last}")
else:
    print("no sandbox-exec here:", LocalSandbox(workdir=SBX / "net").isolation)
server.shutdown()
network=False: urllib.error.URLError: <urlopen error [Errno 1] Operation not permitted>
network=True: hello from the notebook

Even the loopback interface is closed: the jail does not know that 127.0.0.1 is harmless, and that is the right default. Now the file system. The notebook writes a file next to the sandbox’s folder; sandboxed code tries to read it and to write beside it.

(SBX / "secret.txt").write_text("for the notebook only\n")
ESCAPE = """
for action, run in [("read ../secret.txt", lambda: open("../secret.txt").read()),
                    ("write ../escape.txt", lambda: open("../escape.txt", "w").write("x")),
                    ("write ./inside.txt", lambda: open("inside.txt", "w").write("x"))]:
    try:
        run()
        print(action, "-> allowed")
    except OSError as e:
        print(action, "->", type(e).__name__)
"""
box = LocalSandbox(workdir=SBX / "files")
if jail.available():
    print(box.run_python(ESCAPE).stdout)
    print("escape.txt exists:", (SBX / "escape.txt").exists())
    print("files in the sandbox folder:", box.files())
else:
    print("no sandbox-exec here:", box.isolation)
read ../secret.txt -> PermissionError
write ../escape.txt -> PermissionError
write ./inside.txt -> allowed

escape.txt exists: False
files in the sandbox folder: ['inside.txt']

Output size

Whatever the program prints goes back into the model’s context, and a stray print(dataframe) can be megabytes. The sandbox keeps the first max_output_chars characters and says how much it dropped, so the model knows the output was cut.

chatty = LocalSandbox(workdir=SBX / "output", max_output_chars=2000)
r = chatty.run_python("print('x' * 50_000)")
print("truncated:", r.truncated)
print(r.stdout.splitlines()[-1])
truncated: True
[sandbox: output cut at 2000 characters; 48001 more dropped]

What this sandbox does not do

It is a teaching sandbox for code that is probably fine. It shares the kernel with your machine, so a kernel bug is an escape; on macOS it can still read world-readable files outside your home folder (/etc, /tmp); off macOS it has no network or file isolation at all; and its memory limit can be overshot. For code you have reason to distrust, use a container with no network and a read-only root, a microVM (such as Firecracker or gVisor), or a hosted sandbox. The book uses E2B, a hosted sandbox that also keeps variables alive between calls; ours starts a fresh process every time, so only files persist.

4. Code as the action: execute_python

PythonTool turns a sandbox into a tool with a single argument, code. Given plain functions, it copies their source into the sandbox ahead of the model’s code, so the program can call them, and lists their signatures in the tool description (the book calls this tool portability). Here is the description the model reads:

from agentlab.sandbox import PythonTool
 
codeact_box = LocalSandbox(workdir=SBX / "codeact", timeout_s=10, cpu_s=5, mem_mib=512)
python_tool = PythonTool(codeact_box, functions=[get_price, get_shipping, convert])
print(python_tool.tool_definition["function"]["description"])
Run Python 3 code in a fresh sandboxed process and return its exit status, stdout and stderr. Print every value you need to see; nothing else is returned. Variables do not persist between calls, files in the working directory do.
These functions are already defined and can be called from your code:
- get_price(store: str, item: str) -> dict: Unit price of an item at one store, in that store's currency.
- get_shipping(store: str, city: str, units: int) -> float: Shipping cost of one parcel, in the store's currency.
- convert(amount: float, from_currency: str, to_currency: str) -> float: Convert an amount between USD, EUR and GBP at fixed rates.

One tool replaces three, and the prompt tells the model the two rules of this environment: print what you want to see, and expect a fresh process each time.

CODEACT_PROMPT = ("Solve the task by writing Python and running it with execute_python. "
                  "Print every value you need. "
                  "Answer in plain text once you have the result.")
codeact = Agent(llm, tools=[python_tool], instructions=CODEACT_PROMPT, max_steps=8,
                name="codeact")
result = await codeact.run(QUESTION)
first_call = next(c for c in result.context.contents() if isinstance(c, ToolCall))
program = first_call.arguments["code"]
print(program)
print("observation:")
print(python_tool.last_result.to_text())
print("answer:", result.output)
stores = ['alpha', 'berg', 'corso']
totals = {}
for store in stores:
    price = get_price(store, 'headphones')
    shipping = get_shipping(store, 'Berlin', 3)
    local = 3 * price["price"] + shipping
    totals[store] = convert(local, price["currency"], 'EUR')
for store, total in sorted(totals.items(), key=lambda kv: kv[1]):
    print(f"{store}: EUR {total:.2f}")

observation:
exit code 0
stdout:
berg: EUR 268.50
alpha: EUR 271.40
corso: EUR 273.78
answer: berg is the cheapest: EUR 268.50 for 3 headphones shipped to Berlin (then alpha EUR 271.40, corso EUR 273.78).

Two model calls. The loop, the arithmetic and the conversions happened in Python, where 3 * 89.0 + 28.0 is not a judgement call, and only the five-line printout went back into the context. Wang et al. (2024) compared action formats on M3ToolEval, a benchmark of tasks that need several tools: 12 of the 17 models they tested solved the most tasks when they acted in code, and GPT-4 went from about 52% of tasks with JSON actions to about 74% with code, in fewer turns. Two reasons are visible above: control flow (a for loop instead of a round trip per batch) and data flow (one function’s output feeds the next without passing through the model’s context).

5. How the two styles grow

The interesting question is what happens as the task grows. Ask the same question about 3, 6, 9 and 12 stores and count, for each style, the model calls and the input tokens the model has to read (every request resends the whole conversation so far). There are now three contestants: JSON calls one at a time (what a model without parallel calls does), JSON calls batched per turn, and CodeAct.

from agentlab.tracing import usage_of
 
STORES = ["alpha", "berg", "corso", "delta", "elm", "fjord", "grove", "harbor", "iris",
          "juno", "kite", "lumen"]
 
 
def question(n: int) -> str:
    names = STORES[:n]
    return (f"Which of the stores {', '.join(names[:-1])} and {names[-1]} is cheapest for "
            "3 headphones shipped to Berlin, in EUR?")
 
 
async def measure(agent: Agent, text: str) -> dict:
    start = len(agent.model.calls)
    result = await agent.run(text)
    calls = agent.model.calls[start:]
    return {"model calls": len(calls),
            "tool calls": sum(len(resp.tool_calls) for _, resp in calls),
            "input tokens": sum(usage_of(req, resp)[0] for req, resp in calls),
            "answer": result.output}
 
 
styles = {
    "JSON, one call per turn": Agent(
        llm, tools=json_tools, max_steps=60, name="json1",
        instructions=JSON_PROMPT + " Call one tool at a time."),
    "JSON, batched calls": json_agent,
    "CodeAct": codeact,
}
SIZES = [3, 6, 9, 12]
rows = {name: [await measure(agent, question(n)) for n in SIZES]
        for name, agent in styles.items()}
 
print(f"{'stores':>6}  " + "  ".join(f"{name:>24}" for name in styles))
for i, n in enumerate(SIZES):
    cells = [f"{r[i]['model calls']:>3} calls {r[i]['input tokens']:>7,} tok" for r in
             rows.values()]
    print(f"{n:>6}  " + "  ".join(f"{c:>24}" for c in cells))
answers = {r[-1]["answer"] for r in rows.values()}
print("\nsame answer from all three for 12 stores:", len(answers) == 1)
print(answers.pop())
stores   JSON, one call per turn       JSON, batched calls                   CodeAct
     3       9 calls   5,390 tok       4 calls   2,371 tok       2 calls     736 tok
     6      17 calls  13,713 tok       4 calls   3,173 tok       2 calls     763 tok
     9      25 calls  25,418 tok       4 calls   3,986 tok       2 calls     796 tok
    12      33 calls  40,395 tok       4 calls   4,788 tok       2 calls     823 tok

same answer from all three for 12 stores: True
grove is the cheapest: EUR 264.04 for 3 headphones shipped to Berlin (then berg EUR 268.50, juno EUR 269.84, kite EUR 270.20, alpha EUR 271.40, lumen EUR 271.91, fjord EUR 272.02, corso EUR 273.78, elm EUR 275.50, delta EUR 275.54, iris EUR 276.35, harbor EUR 279.60).
import matplotlib.pyplot as plt
 
colours = {"JSON, one call per turn": "#b5523b", "JSON, batched calls": "#2c5f9e",
           "CodeAct": "#2c7d54"}
fig, ax = plt.subplots(figsize=(6.4, 3.6))
for name, r in rows.items():
    tokens = [x["input tokens"] for x in r]
    ax.plot(SIZES, tokens, marker="o", color=colours[name], label=name)
ax.set_xlabel("stores compared")
ax.set_ylabel("input tokens (estimated)")
ax.set_xticks(SIZES)
ax.set_yscale("log")
ax.set_ylim(400, 300_000)  # head room so the legend sits above the lines
ax.legend(frameon=False, loc="upper left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Input tokens the model reads to answer the shopping question, by number of stores (estimated, offline model). One call per turn grows fastest, because both the number of turns and the length of each request grow with the task; batching helps; CodeAct stays almost flat because only the program and its printout enter the context.

Input tokens the model reads to answer the shopping question, by number of stores (estimated, offline model). One call per turn grows fastest, because both the number of turns and the length of each request grow with the task; batching helps; CodeAct stays almost flat because only the program and its printout enter the context.

The gap is mostly context. With one call per turn, a 12-store comparison resends a growing conversation more than thirty times. Batching cuts the number of turns to four, but every price and shipping result is still pasted into the context. The CodeAct requests grow only because the question names more stores. These are token estimates for the offline model’s trajectories; a real model would take a similar number of turns for the JSON styles and might need an extra round in CodeAct to fix a bug, which is the next section.

CodeAct is not free either. The code runs on your machine (hence sections 2 and 3), the model must write correct Python, and a hundred-line program is harder for a person to review than a list of tool calls. Small, frequent, well-defined actions are often better as tools; open-ended data work is often better as code. Module 13’s coding agent uses both.

6. A traceback is a good observation

When a program fails, the sandbox returns the exit code and the traceback, trimmed to the model’s own code and numbered by its own lines. To stage that exactly we use a ScriptedLLM whose first program has a bug (it reads price["cost"], a key that does not exist) and whose second program fixes it. The script is fixed in advance: this shows what the agent sees, not how a model reasons.

from agentlab.llm.scripted import ScriptedLLM, ToolCallSpec
 
buggy = program.replace('price["price"]', 'price["cost"]')
staged = nb.track(ScriptedLLM([
    ToolCallSpec("execute_python", {"code": buggy}),
    ToolCallSpec("execute_python", {"code": program}),
    "berg is the cheapest: EUR 268.50.",
]))
debugger = Agent(staged, tools=[python_tool], instructions=CODEACT_PROMPT, name="codeact")
result = await debugger.run(QUESTION)
first_observation = next(c for c in result.context.contents() if isinstance(c, ToolResult))
first_observation = first_observation.content[0]
print(first_observation)
exit code 1
stderr:
Traceback (most recent call last):
  File "<code>", line 6, in <module>
    local = 3 * price["cost"] + shipping
                ~~~~~^^^^^^^^
KeyError: 'cost'

The observation names the line (line 6 of the model’s program), the expression and the missing key. A model can fix that in one more turn, and good models usually do. They can also repeat the same mistake, which is one more reason the agent keeps a step budget (max_steps=8 here).

print("model calls:", len(staged.calls), "| answer:", result.output)
model calls: 3 | answer: berg is the cheapest: EUR 268.50.

Try this

  • Ask for 3 headphones shipped to Lisbon. How does each style report the ValueError, and how many model calls does each spend on it?
  • Lower mem_mib to 64 and timeout_s to 0.2 in the CodeAct sandbox. Which limit trips first on the shopping program, and what does the model see?
  • Give the sandbox network=True and run the fetch cell again. Then think about which tasks justify that, and what else you would add first (an allow-list of hosts?).
  • Set MODEL and re-run section 4. Compare the real model’s program with the template: does it print more than it needs? Does it check for errors?
nb.usage()
model callsinput tokensoutput tokenscost
117 (fake: 114, scripted: 3)≈ 106,851≈ 3,432≈ USD 0.1206 (reference price)