# Code interpreter

Send Python cells to a persistent sandbox. Each cell runs in a long-lived kernel inside the sandbox, so variables, imports and loaded data are still there for the next call. You get back the value of the cell's last expression, the charts it drew, and its output and errors. This is the tool a ChatGPT-style data-analysis agent needs.

## Run a cell

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"template":"python","persistent":true}'
# {"sandbox":{"id":"sbx_…","persistent":true,…}}

curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/code \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"code":"x = 40\nprint(\"hello\")\nx + 2"}'
# {"context":"default","execution_count":1,"results":[{"type":"text","data":"42"}],
#  "stdout":"hello\n","stderr":""}

curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/code \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"code":"x * 10"}'
# {"context":"default","execution_count":2,"results":[{"type":"text","data":"400"}],…}
```

- **code**: up to 40 KiB of Python. For a longer program, write it to a file with the files API and `exec(open(…).read())` it.

- **context** (optional, default `default`): which kernel runs the cell. Each context has its own variables.

- **timeout_s** (optional, default 30, at most 80): when time runs out, the cell is interrupted with a `TimeoutError`. The context keeps running, with everything the cell set before it was stopped.

## What comes back

- **results**: the value of the last expression, then anything passed to `display(obj)`, then every matplotlib figure left open. Each item has a `type`: `image/png` (base64), `image/svg+xml`, `html` (a pandas DataFrame, for example), `json` or `text`. Rich types come first, then a `text` form of the same value. Figures are closed after each cell, as in Jupyter.

- **stdout** and **stderr**: captured at the file descriptor, so output from subprocesses is included. Each keeps up to 256 KiB.

- **error**: `{name, value, traceback}` when the cell raised an exception. The traceback starts at the cell's own lines (`<cell-N>`). The HTTP status is still 200: the cell ran, and it failed.

- Results over 1 MiB in total are cut off, and `truncated: true` is set. Save large outputs to a file instead.

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/code \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"code":"import matplotlib.pyplot as plt\nplt.plot([1, 3, 2])\nplt.title(\"demo\")"}'
# {"results":[{"type":"text","data":"Text(0.5, 1.0, 'demo')"},
#             {"type":"image/png","data":"iVBORw0KGgo…","name":"figure-1.png"}],…}
```

## Contexts

```
POST   /v1/sandboxes/{id}/code/contexts {"name":"analysis"}   # start one (a cell to a new name starts it too)
GET    /v1/sandboxes/{id}/code/contexts                      # [{name, execution_count}]
POST   /v1/sandboxes/{id}/code/contexts/analysis/reset       # forget its variables
DELETE /v1/sandboxes/{id}/code/contexts/analysis             # end its process
```

## How it works, and what it needs

- **A persistent sandbox** (`"persistent": true`). Each context is a Python process that keeps running in the sandbox's long-lived container between calls. Any other sandbox answers `409 not_persistent`.

- **python3 in the image.** Use the `python` template, the universal image, or any image with Python. Without it, the call answers `409 no_python`. Install packages with a cell (`import subprocess; subprocess.run(["pip", "install", "pandas"])`) or with exec. Network access follows the sandbox's egress policy.

- **It runs through exec.** Each call is a command in the sandbox, so the same rules apply. A sleeping sandbox is woken first, after the same payment checks. The call can last at most 90 seconds. It needs a key with `sandboxes:write`, and each cell is in the audit log as `sandbox.code_run` with its context and size, never its code.

- **Contexts survive sleep.** A sleeping sandbox keeps its memory and processes, so the variables are still there after it wakes. A checkpoint and rewind take them back to that point too.

- On first use the kernel is written to `/tmp/kosa8-kernel/` in the sandbox. Its sockets are there as well, readable only by the sandbox's user. Anything that runs in the sandbox can talk to its contexts. They are your code's, not a boundary.

---
Source: https://docs.kosa8.com/guides/cloud-code-interpreter/
