Skip to main content

How it works

The pattern is the same regardless of which LLM you use:
  1. Define a run_code tool — tell the LLM it can call a function that accepts a code string and returns stdout/stderr.
  2. Create a sandbox once and keep it alive across the agent loop — reusing one sandbox preserves state between tool calls (installed packages, files written to disk). Each run_code call is a fresh Python process, so variables and imports must be redefined in each call.
  3. Execute the tool call — when the LLM invokes run_code, pass the code into sandbox.run() and return the result.
  4. Clean up — terminate the sandbox when the agent session ends.

TypeScript SDK starter

If your agent loop already runs in Node.js, keep one connected sandbox alive for the session and wrap it as a tool:
Use this runCode() helper as the implementation behind your OpenAI or Anthropic tool/function call.

Claude (Anthropic SDK)

Prerequisites

Full example

What happens step by step


OpenAI (function calling)

Prerequisites

Full example


Using OpenAI Agents SDK

If you are using the newer OpenAI Agents SDK, you can wrap the sandbox as a FunctionTool directly:

Prerequisites

Full example


Production tips

Reuse one sandbox per session, not per call

Creating a new sandbox on every tool call adds cold-start latency and loses any state (installed packages, files written to disk) from prior calls. Create the sandbox before the agent loop and close it afterward.

Pre-install dependencies with Snapshots

If your agent always needs the same libraries (pandas, numpy, matplotlib, etc.), install them once, snapshot the sandbox, and boot future sandboxes from that snapshot. This avoids re-running pip install on every session.
See the Snapshots guide for details.

Let the agent install packages on demand

If your agent may need arbitrary or unknown packages, tell it in the system prompt that it can install them with pip. Because sandbox state persists across tool calls, a package installed in one call is available in all subsequent calls.
Use this approach when dependencies are unpredictable. For a known set of dependencies, pre-installing via Snapshots is faster since it avoids repeating pip install on every session.

Lock down the network

By default, sandboxes have internet access. For agents executing untrusted or LLM-generated code, disable it:
If the agent needs outbound access, keep internet enabled or use deny_out to block destinations you know should be unreachable. See the Networking guide.

What to build next

  • Data Analysis — spin up sandboxes with data science libraries to analyze complex datasets and stream results back in real time.
  • Snapshots — pre-install dependencies so agent sessions start instantly.