A minimal, secure Python sandbox for AI agents
Project description
A minimal, secure Python sandbox written in Rust for use by AI agents.
Littrs avoids the cost, latency, and complexity of using full container-based sandboxes for running LLM-generated code. Instead, it lets you safely run Python code written by an LLM embedded directly in your agent, with startup times measured in milliseconds and zero external dependencies.
The core idea is simple: LLMs work faster, cheaper, and more reliably when they write Python code instead of relying on traditional structured tool calling. Littrs makes that possible without spinning up containers or risking arbitrary code execution on the host. You register Python functions as callable tools, hand the sandbox some LLM-generated code, and get back a result — safely.
Installation
pip install littrs
Quick Start
from littrs import Sandbox
sandbox = Sandbox()
# Execute Python code
result = sandbox.execute("2 + 2")
assert result == 4
# Variables persist across calls
sandbox.execute("x = 10")
sandbox.execute("y = 20")
result = sandbox.execute("x + y")
assert result == 30
Registering Tools
Register Python functions that LLM-generated code can call. The sandbox code calls them like normal Python functions, and you handle them on the host side.
from littrs import Sandbox
def fetch_data(args):
id = args[0] if args else 0
return {"id": id, "name": "Example"}
sandbox = Sandbox()
sandbox.register_function("fetch_data", fetch_data)
result = sandbox.execute("""
data = fetch_data(42)
data["name"]
""")
assert result == "Example"
Resource Limits
Prevent runaway code from consuming unbounded resources:
sandbox = Sandbox()
sandbox.set_limits(max_instructions=10_000, max_recursion_depth=50)
# This will raise an error, not hang forever
try:
sandbox.execute("while True: pass")
except RuntimeError as e:
print(e) # "Instruction limit exceeded (limit: 10000)"
Resource limit errors are uncatchable — try/except in the sandbox code cannot suppress them. This is by design: the host must always be able to regain control.
Capturing Print Output
result, printed = sandbox.execute_with_output("""
for i in range(5):
print(i)
"done"
""")
# printed == ["0", "1", "2", "3", "4"]
# result == "done"
Setting Variables
Inject values into the sandbox from the host:
sandbox = Sandbox()
sandbox.set_variable("config", {"model": "claude", "temperature": 0.7})
result = sandbox.execute('config["model"]')
assert result == "claude"
WASM Sandbox (Stronger Isolation)
For use cases requiring stronger isolation guarantees, Littrs includes a WASM-based sandbox that runs the interpreter inside a WebAssembly guest module. This provides memory isolation and fuel-based computation limits at the WASM level:
from littrs import WasmSandbox, WasmSandboxConfig
config = WasmSandboxConfig() \
.with_fuel(1_000_000) \
.with_max_memory(32 * 1024 * 1024) # 32MB
sandbox = WasmSandbox(config)
result = sandbox.execute("sum(range(100))")
assert result == 4950
What Littrs Can Do
- Run a reasonable subset of Python — variables, control flow, functions (with defaults,
*args,**kwargs), list comprehensions, f-strings, try/except, and all the built-in types an LLM needs - Completely block access to the host environment — no filesystem, no network, no environment variables, no
import, no standard library. The sandbox has zero ambient capabilities - Call functions on the host — only functions you explicitly register as tools. The LLM code calls them like normal Python functions, and you handle them in Python
- Control resource usage — set instruction limits and recursion depth limits per execution call. Resource limit violations are uncatchable (they bypass
try/except) - Capture stdout —
print()output is collected and returned to the caller - Start up fast — no interpreter boot, no WASM runtime to load (unless you want it). Create a
Sandbox, register tools, execute code
What Littrs Cannot Do
- Use the standard library — there is no
import. Noos,sys,json,re, or anything else - Use third-party libraries — no
pip install, nonumpy, norequests - Define classes —
classdefinitions are not supported - Use async/await — no coroutines, no
asyncio - Use
finallyblocks — onlytry/except/else - Use
matchstatements - Snapshot/resume execution state — execution runs to completion in a single call
Supported Python Features
Types
None, bool, int, float, str, list, dict (string keys)
Operators
| Category | Operators |
|---|---|
| Arithmetic | +, -, *, /, //, %, ** |
| Comparison | ==, !=, <, <=, >, >=, in, not in, is, is not |
| Boolean | and, or, not |
| Bitwise | |, ^, &, <<, >>, ~ |
| Assignment | =, +=, -=, *=, /=, //=, %=, **= |
Control Flow
if/elif/elseforloops over lists, strings, ranges,dict.items(), etc. — withbreak/continuewhileloops withbreak/continue- Ternary expressions:
x if condition else y - List comprehensions with filters:
[x*2 for x in items if x > 0]
Functions
defwith positional parameters, default values,*args,**kwargs- Keyword arguments at call sites:
f(x=1, y=2) - Recursive and nested function definitions
- Implicit
return Nonefor functions without a return statement
Error Handling
try/exceptwith typed handlers:except ValueError as e:- Bare
except:to catch all exceptions elseclause on try blocksraise ValueError("message")and bareraiseto re-raise
F-strings
name = "world"
f"hello {name}!" # "hello world!"
String Methods
.upper(), .lower(), .strip(), .split(), .join(), .replace(), .startswith(), .endswith(), .find(), .count(), .format()
List/Dict Methods
.append(), .pop(), .extend(), .insert(), .remove(), .keys(), .values(), .items(), .get(), .update(), .clear()
Slicing
items = [1, 2, 3, 4, 5]
items[1:3] # [2, 3]
items[::2] # [1, 3, 5]
items[::-1] # [5, 4, 3, 2, 1]
Built-in Functions
len(), str(), int(), float(), bool(), list(), range(), abs(), min(), max(), sum(), print(), type(), isinstance(), enumerate(), zip(), sorted(), reversed(), dict(), tuple(), set(), round(), map(), filter(), any(), all(), chr(), ord()
Citation
If you use Littrs in your research, please cite it as:
@software{littrs,
title = {Littrs: A Minimal, Secure Python Sandbox for AI Agents},
author = {Chonkie Inc.},
url = {https://github.com/chonkie-inc/littrs},
license = {Apache-2.0},
year = {2025}
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file littrs-0.4.1-cp312-cp312-win_amd64.whl.
File metadata
- Download URL: littrs-0.4.1-cp312-cp312-win_amd64.whl
- Upload date:
- Size: 7.9 MB
- Tags: CPython 3.12, Windows x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
92d543f001200b8fc61cd2759f9a5e7d4e6ae7eafd3a7b1f685bf771cf507a72
|
|
| MD5 |
7b60401e0b2cc5d1121673b98bfe1934
|
|
| BLAKE2b-256 |
25e0726c8783a152b2caf44b33bf82b3808382dd8750c6a3236f1a571255424b
|
File details
Details for the file littrs-0.4.1-cp312-cp312-manylinux_2_34_x86_64.whl.
File metadata
- Download URL: littrs-0.4.1-cp312-cp312-manylinux_2_34_x86_64.whl
- Upload date:
- Size: 9.0 MB
- Tags: CPython 3.12, manylinux: glibc 2.34+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ff8f63755769fa57c48d63ac7559e26058e6fea41657b6ede164cd2fe6597ddb
|
|
| MD5 |
9c3271a97174969e98653db4f4dfded5
|
|
| BLAKE2b-256 |
9a46f9c8764ee33053186716cb9d8b33a4c1b81189cc3f9255ce5da9eb0746b9
|
File details
Details for the file littrs-0.4.1-cp312-cp312-macosx_11_0_arm64.whl.
File metadata
- Download URL: littrs-0.4.1-cp312-cp312-macosx_11_0_arm64.whl
- Upload date:
- Size: 7.8 MB
- Tags: CPython 3.12, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
34ab6343e9eb3b430dbb4eddda72089e070900fea6abbeab66072af0748c6702
|
|
| MD5 |
bd4bc594ac9aa2fa812689da7009ccb4
|
|
| BLAKE2b-256 |
6cd69c23d2a2f6dc0dbfed0373cd62fffdf830d3385453abe754c801a4020b0a
|