Documentation

Everything you need to run AI-generated code safely.

Installation

Python

pip install cerver

Node.js

npm install @cerver/sdk

Authentication

Set your API key as an environment variable:

export CERVER_API_KEY=sk_live_...

Or pass it directly:

from cerver import Sandbox

sandbox = Sandbox(api_key="sk_live_...")

Quick Start

Basic usage

from cerver import Sandbox

with Sandbox() as sandbox:
    result = sandbox.run("print('Hello from sandbox!')")
    print(result.output)  # Hello from sandbox!

Running multiple commands

with Sandbox() as sandbox:
    sandbox.run("x = 10")
    sandbox.run("y = 20")
    result = sandbox.run("print(x + y)")
    print(result.output)  # 30

Installing packages

with Sandbox() as sandbox:
    sandbox.run("!pip install pandas")
    result = sandbox.run("""
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
print(df.sum())
""")
    print(result.output)

AI Agent Integration

OpenAI Function Calling

from cerver import Sandbox
from openai import OpenAI

client = OpenAI()
sandbox = Sandbox()

tools = [{
    "type": "function",
    "function": {
        "name": "execute_code",
        "description": "Execute Python code in a sandbox",
        "parameters": {
            "type": "object",
            "properties": {
                "code": {"type": "string"}
            }
        }
    }
}]

def chat(user_message):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": user_message}],
        tools=tools
    )

    if response.choices[0].message.tool_calls:
        code = response.choices[0].message.tool_calls[0].function.arguments
        result = sandbox.run(code)
        return result.output

    return response.choices[0].message.content

print(chat("Calculate the factorial of 10"))

Anthropic Claude

from cerver import Sandbox
from anthropic import Anthropic

client = Anthropic()
sandbox = Sandbox()

tools = [{
    "name": "execute_code",
    "description": "Execute Python code in a sandbox",
    "input_schema": {
        "type": "object",
        "properties": {
            "code": {"type": "string"}
        }
    }
}]

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "Plot a sine wave"}]
)

for block in response.content:
    if block.type == "tool_use":
        result = sandbox.run(block.input["code"])
        print(result.output)

LangChain

from cerver import Sandbox
from langchain.tools import Tool
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI

sandbox = Sandbox()

code_tool = Tool(
    name="python_executor",
    description="Execute Python code. Input should be valid Python.",
    func=lambda code: sandbox.run(code).output
)

llm = ChatOpenAI(model="gpt-4")
agent = initialize_agent(
    [code_tool],
    llm,
    agent=AgentType.OPENAI_FUNCTIONS
)

result = agent.run("What's the 50th fibonacci number?")
print(result)

Advanced Usage

File operations

with Sandbox() as sandbox:
    # Write a file
    sandbox.write_file("data.txt", "Hello, World!")

    # Read a file
    content = sandbox.read_file("data.txt")
    print(content)  # Hello, World!

    # Upload a local file
    sandbox.upload("./local_data.csv", "data.csv")

    # Download a file
    sandbox.download("output.png", "./result.png")

Custom timeouts

with Sandbox(timeout=300) as sandbox:  # 5 minutes
    result = sandbox.run(long_running_code)

Streaming output

with Sandbox() as sandbox:
    for chunk in sandbox.run_stream("for i in range(10): print(i)"):
        print(chunk, end="")

Parallel execution

from cerver import Sandbox
import asyncio

async def run_parallel():
    tasks = []
    for i in range(10):
        sandbox = Sandbox()
        tasks.append(sandbox.run_async(f"print({i} ** 2)"))

    results = await asyncio.gather(*tasks)
    for r in results:
        print(r.output)

asyncio.run(run_parallel())

Configuration

Environment variables:

CERVER_API_KEY Your API key (required)
CERVER_TIMEOUT Default timeout in seconds (default: 60)
CERVER_REGION Preferred region: us, eu, asia (default: auto)

Response Object

result = sandbox.run("print('hello')")

result.output      # stdout as string
result.error       # stderr as string
result.exit_code   # 0 on success
result.duration    # execution time in ms

Error Handling

from cerver import Sandbox, CerverError, TimeoutError

try:
    with Sandbox() as sandbox:
        result = sandbox.run("import nonexistent")
        if result.exit_code != 0:
            print(f"Error: {result.error}")
except TimeoutError:
    print("Execution timed out")
except CerverError as e:
    print(f"Cerver error: {e}")