Python Code Interpreter Sandbox
When no predefined tool exists for an analytical, mathematical, or data-processing task, the agent can synthesize and execute Python or shell commands inside an isolated CodeInterpreterTool.
Security & Isolation
The code interpreter executes within an isolated, session-scoped sandbox backend:
- Pluggable Isolation Runtimes:
NsjailRuntime(Linux namespaces + cgroups for single-host deployments),K8sRuntime(dedicated Kubernetes sandbox pods with gVisor RuntimeClass), orInProcessRuntime(for fast unit testing). - Zero Network Egress: Network policy defaults to
NetworkPolicy.DENYto prevent data exfiltration. - Resource Limits: Configurable memory limits (default 2GB) and execution timeouts (default 60s).
- Workspace Scoping: The interpreter runs inside the conversation's own isolated workspace—files written during execution persist across turns.
Usage Example
import asyncio
from substrate.agents import ReActAgent
from substrate.integrations.tools.code_interpreter import (
CodeInterpreterTool,
NsjailRuntime,
NetworkPolicy,
)
from substrate.runtime import Runtime
from substrate.tools import AutoApprove, ToolRisk
async def main() -> None:
# 1. Initialize the sandbox runtime
sandbox = NsjailRuntime()
# 2. Configure the tool with strict isolation
interpreter = CodeInterpreterTool(
runtime=sandbox,
network=NetworkPolicy.DENY,
default_timeout_s=30,
memory_bytes=512 * 1024 * 1024, # 512 MB
)
# 3. Code execution is marked ToolRisk.CRITICAL
agent = ReActAgent(
"data_analyst",
model=my_chat_model,
tools=[interpreter],
system_instructions="Write Python code using polars or pandas to analyze data.",
approval_handler=AutoApprove(), # or DurableApproval for human sign-off
approval_required_risk=ToolRisk.CRITICAL,
)
async with Runtime.open("./.substrate") as runtime:
outcome = await runtime.run(
agent,
"Compute the median and standard deviation of [12, 45, 67, 89, 23, 56, 78]."
)
print(outcome.output)
if __name__ == "__main__":
asyncio.run(main())Was this page helpful?