> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# A code interpreter for your AI app

> Let a model write Python and run it safely: one sandbox per conversation, packages installed once, variables kept between turns, charts and files returned to your app.

Imagine your users asking questions about their own data, such as *"which region grew fastest last quarter?"*. A
language model gives much better answers when it can **write code and run it**: it calculates the answer instead
of guessing, and it can draw a chart to show it. This is often called a *code interpreter*.

The code the model writes should never run on your own servers, because you cannot know in advance what it will
do. Instead, **give each conversation its own sandbox.** The model's code runs there, next to the user's files, and
nothing it does can reach your systems or any other user.

This page builds a working code interpreter, step by step, and then connects it to a model.

```mermaid theme={null}
sequenceDiagram
  participant U as User
  participant A as Your app
  participant M as Model
  participant S as Sandbox (one per conversation)
  U->>A: "Which region grew fastest?"
  A->>M: question + run_python tool
  M->>A: run_python(code)
  A->>S: run the code
  S->>A: output, chart.png
  A->>M: the output
  M->>A: "South grew 38%." + chart
  A->>U: answer and chart
```

## What you build

The interpreter is made of a few simple pieces:

| Piece | How |
| - | - |
| One sandbox per conversation | Create on the first message, find it again by label on the next |
| Packages ready | Install once per sandbox (or start from a [snapshot](https://docs.fibre.dev/setup/snapshots.md) with them installed) |
| **State between turns** | A Python process that stays alive, so `df` defined in turn 1 is still there in turn 3 |
| Charts and files | The code saves to `/work/out`; your app reads them back |
| Safety | Only PyPI reachable, a short idle timeout, a lifetime that ends forgotten conversations |

## The interpreter

**1. A sandbox for the conversation**

First, a function that returns the sandbox for a conversation, creating it the first time. The conversation's ID
is stored as a label, so the next message finds the same sandbox again. **The sandbox goes to sleep two minutes
after the last message**, and wakes up with everything still in memory when the user writes again. Its network only
allows installing Python packages, so the code cannot send data anywhere else.

```typescript title="TypeScript" run theme={null}
import { Sandbox } from "@fibre-dev/sdk";

async function sandboxFor(conversationId: string): Promise<Sandbox> {
  for await (const s of Sandbox.list({ labels: { conversation: conversationId } })) return s;
  return Sandbox.create({
    labels: { app: "analyst", conversation: conversationId },
    network: { allow: ["pypi.org", "files.pythonhosted.org"] },   // installs only: nowhere to send data
    idleTimeout: 120,
    lifetime: 86400,
  });
}

const sbx = await sandboxFor("conv-1234");
```

```python title="Python" run theme={null}
from fibre import Sandbox


def sandbox_for(conversation_id: str) -> Sandbox:
    for s in Sandbox.list(labels={"conversation": conversation_id}):
        return s
    return Sandbox.create(
        labels={"app": "analyst", "conversation": conversation_id},
        network={"allow": ["pypi.org", "files.pythonhosted.org"]},  # installs only: nowhere to send data
        idle_timeout=120,
        lifetime=86400,
    )


sbx = sandbox_for("conv-1234")
```

**2. A Python process that keeps its variables**

Next, the part that remembers variables between turns. If every piece of code ran as a separate program, a variable
created in one turn would be gone in the next. So instead we start **one long-running Python process** (a
*kernel*) and send it each piece of code, called a *cell*, as the conversation goes on.

This kernel is deliberately tiny. It reads a cell from its standard input, runs it in the same namespace as every
earlier cell, and prints a marker when it has finished, so we know when to stop reading its output:

```typescript title="TypeScript" run theme={null}
await sbx.run(
  "python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pandas matplotlib",
  { timeout: 600 },
);

await sbx.files.write("/work/kernel.py", `
import sys, traceback, matplotlib
matplotlib.use("Agg")
namespace = {}
buffer = []
for line in sys.stdin:
    if line.strip() != "#--END--":
        buffer.append(line); continue
    try:
        exec("".join(buffer), namespace)
    except Exception:
        traceback.print_exc(file=sys.stdout)
    buffer = []
    print("#--DONE--", flush=True)
`);

const kernel = await sbx.spawn(["/work/.venv/bin/python", "-u", "/work/kernel.py"], { cwd: "/work", stdin: true });
```

```python title="Python" run theme={null}
sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pandas matplotlib", timeout=600)

sbx.files.write("/work/kernel.py", """
import sys, traceback, matplotlib
matplotlib.use("Agg")
namespace = {}
buffer = []
for line in sys.stdin:
    if line.strip() != "#--END--":
        buffer.append(line); continue
    try:
        exec("".join(buffer), namespace)
    except Exception:
        traceback.print_exc(file=sys.stdout)
    buffer = []
    print("#--DONE--", flush=True)
""")

kernel = sbx.spawn(["/work/.venv/bin/python", "-u", "/work/kernel.py"], cwd="/work", stdin=True)
```

**3. Run a cell, collect output and charts**

```typescript title="TypeScript" run theme={null}
let seen = 0;

async function runCell(code: string): Promise<{ output: string; files: string[] }> {
  await sbx.run("mkdir -p /work/out && rm -f /work/out/*");
  await kernel.write(code + "\n#--END--\n");

  let output = "";
  for await (const chunk of kernel.output()) {
    output += chunk.data;
    if (output.includes("#--DONE--", seen)) break;
  }
  const fresh = output.slice(seen).replace("#--DONE--\n", "");
  seen = output.length;

  const { entries } = await sbx.files.list("/work/out");
  return { output: fresh, files: entries.map((e) => `/work/out/${e.name}`) };
}
```

```python title="Python" run theme={null}
seen = 0


def run_cell(code: str) -> dict:
    global seen
    sbx.run("mkdir -p /work/out && rm -f /work/out/*")
    kernel.write(code + "\n#--END--\n")

    output = ""
    for chunk in kernel.output():
        output += chunk.data
        if output.find("#--DONE--", seen) >= 0:
            break
    fresh = output[seen:].replace("#--DONE--\n", "")
    seen = len(output)

    entries = sbx.files.list("/work/out")["entries"]
    return {"output": fresh, "files": [f"/work/out/{e['name']}" for e in entries]}
```

**4. Try it with what a model would write**

Here are two cells like the ones a model would write. The first loads the data into a table called `df`. **The
second uses `df` without loading it again**, because the kernel remembers it, and saves a chart to `/work/out`.

```typescript title="TypeScript" run theme={null}
await sbx.files.write("/work/sales.csv",
  "quarter,region,revenue\nQ1,north,120\nQ1,south,90\nQ1,west,70\nQ2,north,130\nQ2,south,124\nQ2,west,72\n");

const turn1 = await runCell(`
import pandas as pd
df = pd.read_csv("/work/sales.csv")
print(df.groupby("region").revenue.sum().to_string())
`);
console.log(turn1.output);
// north    250
// south    214
// west     142

const turn2 = await runCell(`
growth = df.pivot(index="region", columns="quarter", values="revenue")
growth["pct"] = (growth.Q2 / growth.Q1 - 1) * 100
print(growth.pct.round(1).sort_values(ascending=False).to_string())
ax = growth[["Q1", "Q2"]].plot.bar(title="Revenue by region")
ax.figure.savefig("/work/out/growth.png")
`);
console.log(turn2.output);
// south    37.8
// north     8.3
// west      2.9
console.log(turn2.files); // [ '/work/out/growth.png' ]

const png = await sbx.files.readBytes(turn2.files[0]);
console.log(`chart: ${png.byteLength} bytes`); // send it to the user
```

```python title="Python" run theme={null}
sbx.files.write("/work/sales.csv",
                "quarter,region,revenue\nQ1,north,120\nQ1,south,90\nQ1,west,70\nQ2,north,130\nQ2,south,124\nQ2,west,72\n")

turn1 = run_cell("""
import pandas as pd
df = pd.read_csv("/work/sales.csv")
print(df.groupby("region").revenue.sum().to_string())
""")
print(turn1["output"])
# north    250
# south    214
# west     142

turn2 = run_cell("""
growth = df.pivot(index="region", columns="quarter", values="revenue")
growth["pct"] = (growth.Q2 / growth.Q1 - 1) * 100
print(growth.pct.round(1).sort_values(ascending=False).to_string())
ax = growth[["Q1", "Q2"]].plot.bar(title="Revenue by region")
ax.figure.savefig("/work/out/growth.png")
""")
print(turn2["output"])
# south    37.8
# north     8.3
# west      2.9
print(turn2["files"])  # ['/work/out/growth.png']

png = sbx.files.read_bytes(turn2["files"][0])
print(f"chart: {len(png)} bytes")  # send it to the user
```

## Connect a model

To connect a model, give it one tool, `run_python`, and run whatever code it sends through `runCell`. The loop
keeps going until the model answers without asking to run more code. Here it is with the Anthropic SDK:

```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null}
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();
const tools = [{
  name: "run_python",
  description: "Run Python in a persistent session. pandas and matplotlib are installed. /work/sales.csv holds the user's data. Save charts to /work/out.",
  input_schema: { type: "object", properties: { code: { type: "string" } }, required: ["code"] },
}];

const messages: any[] = [{ role: "user", content: "Which region grew fastest from Q1 to Q2? Show a chart." }];
for (;;) {
  const reply = await anthropic.messages.create({ model: "claude-opus-5-5", max_tokens: 2048, tools, messages });
  messages.push({ role: "assistant", content: reply.content });
  const calls = reply.content.filter((b) => b.type === "tool_use");
  if (calls.length === 0) break;                                   // the model has its answer

  const results = [];
  for (const call of calls) {
    const { output, files } = await runCell((call.input as any).code);
    results.push({ type: "tool_result", tool_use_id: call.id, content: output + (files.length ? `\nfiles: ${files}` : "") });
  }
  messages.push({ role: "user", content: results });
}
```

```python title="Python" norun reason="needs your Anthropic API key" theme={null}
import anthropic

client = anthropic.Anthropic()
tools = [{
    "name": "run_python",
    "description": "Run Python in a persistent session. pandas and matplotlib are installed. /work/sales.csv holds the user's data. Save charts to /work/out.",
    "input_schema": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]},
}]

messages = [{"role": "user", "content": "Which region grew fastest from Q1 to Q2? Show a chart."}]
while True:
    reply = client.messages.create(model="claude-opus-5-5", max_tokens=2048, tools=tools, messages=messages)
    messages.append({"role": "assistant", "content": reply.content})
    calls = [b for b in reply.content if b.type == "tool_use"]
    if not calls:
        break  # the model has its answer

    results = []
    for call in calls:
        cell = run_cell(call.input["code"])
        files = f"\nfiles: {cell['files']}" if cell["files"] else ""
        results.append({"type": "tool_result", "tool_use_id": call.id, "content": cell["output"] + files})
    messages.append({"role": "user", "content": results})
```

## Clean up

```typescript title="TypeScript" run theme={null}
await kernel.kill();
await sbx.delete();
```

```python title="Python" run theme={null}
kernel.kill()
sbx.delete()
```

In a real app, **there is no need to delete the sandbox after each answer.** It sleeps between turns and costs
nothing for compute while it does. Let its lifetime end it, or delete it when the user deletes the conversation.

## What it costs

Take a conversation with 6 turns, each running for 5 seconds on the `small` size. The sandbox is awake for about
**30 seconds** in total, plus the time it takes to install packages once. At \$0.015 an hour, that is a fraction of
a cent per conversation. If you start from a [snapshot](https://docs.fibre.dev/setup/snapshots.md) with pandas already installed, the
install time disappears too.

## Make it production-ready

A few improvements take this from an example to a product:

* **Make the kernel a snapshot.** Save a sandbox with the packages installed and the kernel already running. Each
  conversation then starts from it, ready in seconds.
* **Upload the user's files** with the [files API](https://docs.fibre.dev/sandboxes/files.md) before the first turn.
* **Limit how long each cell can run.** If a cell takes too long, stop the kernel with `kill()` and start a fresh
  one.
* **Send the charts back to the model** as well as to the user, so the model can describe its own chart.

## Related

> [card] [Run commands](https://docs.fibre.dev/sandboxes/running-commands.md)
>
> `spawn`, standard input and streaming output, all used above.

> [card] [Network access](https://docs.fibre.dev/production/network.md)
>
> How the sandbox is limited to installing packages, and nothing else.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.