AI Sandbox & Code Interpreter
Overview
The AI Sandbox module (nala.athomic.ai.sandbox) provides a secure and isolated environment for executing code generated by LLMs. It enables AI Agents to perform complex computational tasks—such as mathematical calculations, data analysis, or chart generation—without compromising the security of the host server.
Key Features
- Strong Isolation: Executes code within ephemeral containers (Docker) with a Read-Only file system and networking disabled by default.
- Code Interpreter Tool: A ready-to-use tool (
CodeInterpreterTool) that sanitizes stdout/stderr and formats file references for the LLM. - Execution Profiles: Support for different profiles (e.g., "Standard", "Data Science") with configurable limits for CPU, RAM, and allowed libraries.
- Security Policies: Static analysis (AST) to block dangerous imports (e.g.,
os,subprocess) before execution starts. - Artifact Management: Secure support for generating files (images, CSVs) using in-memory volumes (
tmpfs).
Architecture
The subsystem acts as a secure orchestration layer on top of the generic Execution engine.
- [cite_start]Service Layer: The
AISandboxServicereceives the code and the desired profile[cite: 122]. - Policy Enforcement: Before any execution, the code is validated by the policy registry:
- [cite_start]
ForbiddenImportsPolicy: Ensures only allowed modules (e.g.,math,json,pandas) are imported[cite: 112]. - [cite_start]
ResourceQuotaPolicy: Validates that requested timeouts are within allowed limits[cite: 117].
- [cite_start]
- [cite_start]Infrastructure Layer: The code is sent to the
ExecutionManager, which provisions a container (Docker or E2B)[cite: 122].- [cite_start]Code is streamed via
stdinto avoid disk writes[cite: 223]. - [cite_start]The root filesystem is mounted as Read-Only[cite: 133, 230].
- [cite_start]The
/tmpfolder is mounted as a volatile volume (tmpfs) to allow temporary artifact creation[cite: 230].
- [cite_start]Code is streamed via
Usage Example
As an Agent Tool (Recommended)
The most common way to use the Sandbox is via the CodeInterpreterTool, which can be attached to any Agent.
from nala.athomic.ai.sandbox.factory import AISandboxFactory
from nala.athomic.ai.sandbox.tool import CodeInterpreterTool
async def run_agent_with_coding_skills(user_query: str):
# 1. Initialize the Sandbox Service
sandbox_service = AISandboxFactory.create_default()
await sandbox_service.connect()
# 2. Create the Tool
code_tool = CodeInterpreterTool(sandbox_service=sandbox_service)
# 3. Execute (Simulation of an LLM call)
# The LLM would send: {"code": "print(10 * 10)", "language": "python"}
result = await code_tool.execute(
code="import math; print(math.sqrt(144))",
language="python"
)
print(result)
# Formatted Output:
# STDOUT:
# 12.0
Direct Service Usage
from nala.athomic.ai.sandbox.domain.entities import SandboxRequest
from nala.athomic.enums import PlatformLanguage
async def execute_script():
service = AISandboxFactory.create_default()
await service.connect()
request = SandboxRequest(
code="print('Hello from Secure Container')",
language=PlatformLanguage.PYTHON,
profile="data_science" # Uses higher memory limits
)
result = await service.execute(request)
if result.is_success:
print(f"Output: {result.stdout}")
for artifact in result.artifacts:
print(f"File generated: {artifact.file_name}")
Configuration
Configuration is managed in settings.toml under the [ai.sandbox] section. It is tightly coupled with the execution infrastructure ([execution]).
[default.ai.sandbox]
enabled = true
default_profile = "standard"
max_output_length = 2000 # Truncates long logs to save context
# --- Profile Definitions ---
[default.ai.sandbox.profiles.standard]
timeout_seconds = 30
max_memory_mb = 128
network_enabled = false
read_only = true # Mandatory for security
strict_mode = true
enabled_policies = ["forbidden_imports", "resource_quota"]
# Docker Image and Entrypoint
[default.ai.sandbox.profiles.standard.runtime]
image = "python:3.11-slim"
command = ["python"]
# Whitelist of allowed modules
[default.ai.sandbox.profiles.standard.policies.forbidden_imports]
allowed_modules = ["math", "datetime", "json", "random", "string"]
[default.ai.sandbox.profiles.data_science]
timeout_seconds = 60
max_memory_mb = 512
read_only = true
# Less restrictive policy (allows numpy, pandas, etc.)
enabled_policies = ["resource_quota"]
[default.ai.sandbox.profiles.data_science.runtime]
image = "python:3.11-data-science" # Custom image required
command = ["python"]
API Reference
nala.athomic.ai.sandbox.service.AISandboxService
Bases: BaseService
Service responsible for the secure execution of code generated by AI Agents.
This service acts as a polymorphic orchestrator. It adapts the execution environment (RAM, Network, Timeouts, Policies) based on the requested 'Profile' in the SandboxRequest, while providing full observability via Prometheus metrics and OpenTelemetry traces.
__init__(settings, execution_manager, policy_registry)
Initializes the AISandboxService.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
AISandboxSettings
|
Global configuration including profile definitions. |
required |
execution_manager
|
ExecutionManager
|
Low-level container execution provider. |
required |
policy_registry
|
Any
|
Injected registry for looking up security policies. |
required |
execute(request, context=None)
async
Executes code using the configuration defined by the request's profile.
The execution flow resolves the profile, enforces security policies, provisions the specific runtime infrastructure, and sanitizes the output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
SandboxRequest
|
Domain entity containing code and desired profile. |
required |
context
|
Optional[Any]
|
Tracing/Auth context for policy enforcement. |
None
|
Returns:
| Type | Description |
|---|---|
SandboxResult
|
Sanitized execution result. |
Raises:
| Type | Description |
|---|---|
SecurityViolationError
|
If policies block the execution. |
SandboxConfigurationError
|
If profile or policies are malformed. |
health_extra()
Provides service-specific health details.
nala.athomic.ai.sandbox.tool.CodeInterpreterTool
Bases: AIToolProtocol
Exposes the Secure Sandbox as a standardized AI Tool.
This class serves as the Adapter Layer between the generic AI Tooling System (nala.athomic.ai.tools) and the specific Sandbox Domain logic. It translates LLM function calls into strongly-typed domain requests, executes them via the AISandboxService, and formats the output for optimal LLM comprehension.
__init__(sandbox_service)
Initializes the tool with the backend service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sandbox_service
|
AISandboxService
|
The orchestrated service instance responsible for executing the code. |
required |
execute(**kwargs)
async
Executes the tool logic compliant with AIToolProtocol.
It parses the input arguments, validates the language support, invokes the sandbox service, and returns a formatted string report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Arguments provided by the LLM matching CodeInterpreterSchema. Expected keys: 'code', 'language', 'timeout'. |
{}
|
Returns:
| Type | Description |
|---|---|
Union[str, Dict[str, Any]]
|
A string representation of the execution result, optimized for |
Union[str, Dict[str, Any]]
|
LLM context window consumption. |
nala.athomic.ai.sandbox.domain.entities.SandboxRequest
Bases: BaseModel
Internal execution request used by the Service layer.
This entity carries both the code to be executed and the configuration overrides (Profile) required for the Execution Engine.
nala.athomic.ai.sandbox.domain.entities.SandboxResult
Bases: BaseModel
The outcome of a sandbox execution.
is_success
property
True if the process exited with code 0.