How to give a LangChain agent a code execution sandbox
Wrap Runtime's sandbox_tools(sbx) with LangChain's tool and pass them to create_agent; commands then run in a microVM.
On Runtime the whole integration is one list comprehension, and the machine
behind it is a full Linux microVM for $0.03125 an hour while the agent waits.
sandbox_tools(sbx) returns four typed Python functions with docstrings, which
LangChain turns into tools as it does any function. Each command runs in a
Firecracker microVM with its own kernel, with Python 3.12, Node.js 24, git and
gcc installed and pip install allowed. langchain 1.4.2 was the current PyPI
release on 25 September 2026; the tools ran in LangChain's own agent loop with
LangChain 1.4 on 23 September 2026.
Install
Terminalpip install -U langchain langchain-anthropic withruntimenpx withruntime loginThe login approves this machine in your browser. On a server, set
RUNTIME_API_KEY instead. Any LangChain chat model works; this page uses the
model string LangChain's own quickstart shows.
An agent that runs code
Pythonfrom langchain.agents import create_agentfrom langchain_core.tools import toolfrom withruntime import Sandboxfrom withruntime.tools import sandbox_toolsdef solve(model, task: str) -> str: with Sandbox.create() as sbx: agent = create_agent(model, tools=[tool(f) for f in sandbox_tools(sbx)]) result = agent.invoke({"messages": [{"role": "user", "content": task}]}) return result["messages"][-1].contentprint(solve("claude-sonnet-4-6", "Fetch nothing. Fit a line to (1,2), (2,4.1), (3,6.2) with numpy and give the slope."))The with block stops the sandbox when solve returns, even after an
exception. The four tools the model sees:
| Tool | Arguments | Returns |
|---|---|---|
runtime_exec |
command, cwd, timeout_seconds |
exit_code, stdout, stderr, timed_out |
runtime_read_file |
path |
The file's text |
runtime_write_file |
path, content |
How many bytes were written, and where |
runtime_list_files |
path, depth |
Each entry's path, type and size |
Relative paths are under /workspace. Commands run under bash -c and stop
after 300 seconds unless the model asks for another limit. Output past 20,000
characters is cut from the front, so the end of a long log, where the error is,
reaches the model.
Tune the tools
sandbox_tools takes three keyword arguments, and AsyncSandbox gives
coroutine tools for agent.ainvoke:
Pythonimport asynciofrom langchain.agents import create_agentfrom langchain_core.tools import toolfrom withruntime import AsyncRuntimefrom withruntime.tools import sandbox_toolsasync def analyse(model, question: str) -> str: async with AsyncRuntime() as runtime: async with await runtime.sandboxes.create(timeout_seconds=900) as sbx: tools = sandbox_tools(sbx, root="/workspace/job", timeout_seconds=60, max_output_chars=5_000) agent = create_agent(model, tools=[tool(f) for f in tools]) result = await agent.ainvoke({"messages": [{"role": "user", "content": question}]}) return result["messages"][-1].contentprint(asyncio.run(analyse("claude-sonnet-4-6", "How many primes are below one million?")))LangChain's own code interpreter integrations
LangChain has no code runner in its core package. Its tools directory lists code interpreter integrations, read on 25 September 2026:
| Integration | Languages | Session lifetime | Self-hosted |
|---|---|---|---|
| Amazon Bedrock AgentCore Code Interpreter | Python, JavaScript, TypeScript | Configurable, up to 8 hours | No |
| Azure Container Apps dynamic sessions | Python | 1 hour | No |
| Capsule Code Interpreter | Python, JavaScript | Stateless or session-based | Yes |
Runtime sandbox_tools |
Any program Linux runs | Your lease, paused 1–365 days | No |
Those three are interpreters: the model hands over code and gets output. The
Runtime tools give the model a shell and a filesystem, so it can install a
package, write a module, run the tests and read the failure, which is what a
coding or data agent spends most of its turns on. The interpreter style is on
Runtime too: sbx.interpreter.run(code) keeps variables between calls in
Python, JavaScript, TypeScript, R, Java, Bash and Go.
What the agent can reach beyond the four tools
Your code holds sbx, so between turns it can use the rest of the SDK:
- Share a web app the agent started:
sbx.previews.create(8000)returns a private HTTPS address (previews). - Park a session with
sbx.pause(): files, memory and processes are kept and compute billing stops; any later call wakes it. - Branch with
sbx.fork(count=2), two running copies with the memory included, to let two agents try different fixes (images, volumes and snapshots). - Start ready from a custom image with your packages installed:
Sandbox.create(image="data").
Keep keys and spending safe
The model key stays in the Python process that runs the agent; the sandbox only receives commands. The sandbox's reach is set when you create it:
Pythonfrom withruntime import Sandboxwith Sandbox.create( timeout_seconds=600, on_lease_end="stop", max_cost_micros=25_000, # refuse a first lease over $0.025 network={"internet": True, "allow": ["pypi.org", "*.pythonhosted.org"]},) as sbx: sbx.exec("pip install --quiet pandas", check=True, timeout_ms=180_000) sbx.network.set(internet=False) # the agent's own code runs offline- Daily spending limit. Set one on the key the agent uses. A create, wake or
extension past it fails with
spending_limit_reachedand costs nothing; the agent cannot raise it (limits). - Read-only key for dashboards or cron checks that list sandboxes and their costs without starting anything.
- Secrets. A database URL or API token the code needs is stored once; the sandbox holds a placeholder, and the host adds the value only on HTTPS requests to the hosts you name (secrets).
What it costs
Runtime bills CPU as it is used, $0.025 per vCPU-hour with a floor of a twentieth of a vCPU, and reserved memory at $0.0075 per GiB-hour. With both CPUs busy, 2 vCPU and 4 GiB is $0.08 an hour. New accounts get 50 free sandbox hours, no card (pricing).
For graphs with a tool node, see LangGraph; for LangChain's planning agents with a sandbox backend, see Deep Agents. A full analysis agent is in data analysis agent.
Sources
Checked 25 September 2026.
- LangChain quickstart:
pip install -U langchainandcreate_agent(model="claude-sonnet-4-6", ...) - LangChain tools: a function's docstring becomes the tool's description
- LangChain tool integrations: the code interpreter table
- langchain on PyPI: version 1.4.2
Facts on this page were checked on 25 September 2026.