# API Reference

Comprehensive API documentation for LLM Sandbox.

## Core Classes

### SandboxSession

::: llm_sandbox.SandboxSession

### ArtifactSandboxSession

::: llm_sandbox.session.ArtifactSandboxSession

#### Plot Management

The `ArtifactSandboxSession` class provides built-in support for capturing and managing plots generated by your code. This section covers the plot management features:

**Supported Languages**: Python, R

**Supported Libraries**:

- **Python**: matplotlib, seaborn, plotly, bokeh
- **R**: base R graphics, ggplot2, plotly, lattice

**Key Features**:

1. **Automatic Plot Capture**: Plots are automatically captured and returned in the execution result
2. **Plot Accumulation**: By default, plots accumulate across multiple runs within the same session
3. **Manual Clearing**: Use `session.clear_plots()` to manually clear all plots
4. **Automatic Clearing**: Use `session.run(code, clear_plots=True)` to clear plots before execution
5. **Persistent Counter**: Plot numbering persists across runs for proper ordering

**Methods**:

- `run(code, libraries=None, timeout=None, clear_plots=False)`: Execute code and capture artifacts
- `clear_plots()`: Manually clear all plots and reset the plot counter

**Example - Plot Accumulation**:

```python
with ArtifactSandboxSession(lang="python", enable_plotting=True) as session:
    # Run 1: Generate 2 plots
    result1 = session.run("""
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.show()
plt.plot([4, 5, 6])
plt.show()
    """)
    print(len(result1.plots))  # Output: 2

    # Run 2: Generate 1 more plot (accumulates)
    result2 = session.run("""
import matplotlib.pyplot as plt
plt.plot([7, 8, 9])
plt.show()
    """)
    print(len(result2.plots))  # Output: 3 (accumulated)
```

**Example - Manual Clearing**:

```python
with ArtifactSandboxSession(lang="python", enable_plotting=True) as session:
    result1 = session.run("import matplotlib.pyplot as plt; plt.plot([1,2,3]); plt.show()")
    print(len(result1.plots))  # Output: 1

    # Manually clear plots
    session.clear_plots()

    result2 = session.run("import matplotlib.pyplot as plt; plt.plot([4,5,6]); plt.show()")
    print(len(result2.plots))  # Output: 1 (reset after clear)
```

**Example - Automatic Clearing**:

```python
with ArtifactSandboxSession(lang="r", enable_plotting=True) as session:
    result1 = session.run("plot(1:10)")
    print(len(result1.plots))  # Output: 1

    # Clear automatically before running
    result2 = session.run("hist(rnorm(100))", clear_plots=True)
    print(len(result2.plots))  # Output: 1 (automatically cleared)
```

### InteractiveSandboxSession

::: llm_sandbox.InteractiveSandboxSession

The `InteractiveSandboxSession` class provides a persistent Python execution environment where state is maintained across multiple `run()` calls. This is ideal for notebook-style workflows, AI agent interactions, and multi-step data analysis.

**Key Features**:

1. **State Persistence**: Variables, functions, and imports persist across runs
2. **IPython Support**: Full IPython kernel with magic commands
3. **Configurable Execution**: Customizable timeout, memory limits, and history size
4. **File-based Communication**: Uses a command/result queue system for reliability

**Usage Example**:

```python
from llm_sandbox import InteractiveSandboxSession

with InteractiveSandboxSession(lang="python") as session:
    # Define a variable
    session.run("x = 42")

    # Use the variable in next execution
    result = session.run("print(f'The answer is {x}')")
    print(result.stdout)  # Output: The answer is 42
```

**IPython Magic Commands**:

```python
with InteractiveSandboxSession(lang="python") as session:
    # List variables
    result = session.run("%who")

    # Execute shell commands
    result = session.run("!ls -la")

    # Time code execution
    result = session.run("%%timeit\nsum(range(1000))")
```

**Limitations**:
- Python language only
- IPython kernel only

For detailed usage examples, see the [Interactive Sessions Guide](interactive-sessions.md).

---

### InteractiveSettings

::: llm_sandbox.interactive.InteractiveSettings

Configuration class for interactive session behavior.

**Parameters**:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `kernel_type` | `KernelType` | `IPYTHON` | Type of kernel to use |
| `max_memory` | `str` | `"1GB"` | Memory limit for the session |
| `history_size` | `int` | `1000` | Number of execution results to cache |
| `timeout` | `int` | `300` | Per-cell timeout in seconds |
| `poll_interval` | `float` | `0.1` | Polling interval for results (seconds) |

**Usage Example**:

```python
from llm_sandbox import InteractiveSandboxSession, InteractiveSettings, KernelType

settings = InteractiveSettings(
    kernel_type=KernelType.IPYTHON,
    max_memory="2GB",
    history_size=500,
    timeout=600,
    poll_interval=0.1
)

with InteractiveSandboxSession(
    lang="python",
    interactive_settings=settings
) as session:
    result = session.run("print('Hello with custom settings!')")
```

---

### KernelType

::: llm_sandbox.interactive.KernelType

Enumeration of supported kernel types for interactive sessions.

**Values**:

- `IPYTHON`: IPython kernel (currently the only supported option)

---

## Data Classes

### ConsoleOutput

::: llm_sandbox.data.ConsoleOutput

### ExecutionResult

::: llm_sandbox.data.ExecutionResult

### PlotOutput

::: llm_sandbox.data.PlotOutput

---

## Security Classes

### SecurityPolicy

::: llm_sandbox.security.SecurityPolicy

### SecurityPattern

::: llm_sandbox.security.SecurityPattern

### RestrictedModule

::: llm_sandbox.security.RestrictedModule

### SecurityIssueSeverity

::: llm_sandbox.security.SecurityIssueSeverity

---

## Enumerations

### SandboxBackend

::: llm_sandbox.const.SandboxBackend

### SupportedLanguage

::: llm_sandbox.const.SupportedLanguage

### FileType

::: llm_sandbox.data.FileType

---

## Functions

### create_session

::: llm_sandbox.create_session

---

## Exceptions

The library defines a base exception `llm_sandbox.exceptions.SandboxError` and various specific exceptions that inherit from it. Please refer to the `llm_sandbox.exceptions` module for a complete list.

### SandboxTimeoutError

::: llm_sandbox.exceptions.SandboxTimeoutError

Common exceptions include:
- `ContainerError`
- `SecurityError`
- `ResourceError`
- `ValidationError`
- `LanguageNotSupportedError`
- `ImageNotFoundError`
- `SandboxTimeoutError` - Raised when operations exceed configured timeout limits

---

## Language Handlers

### AbstractLanguageHandler

::: llm_sandbox.language_handlers.base.AbstractLanguageHandler

### LanguageConfig

::: llm_sandbox.language_handlers.LanguageConfig

---

## Backend-Specific APIs

### Docker Backend

::: llm_sandbox.docker.SandboxDockerSession

### Kubernetes Backend

::: llm_sandbox.kubernetes.SandboxKubernetesSession

### Podman Backend

::: llm_sandbox.podman.SandboxPodmanSession

### Micromamba Backend

::: llm_sandbox.micromamba.MicromambaSession

---

## Type Hints

### Protocol Types

```python
class ContainerProtocol(Protocol):
    """Protocol for container objects"""

    def execute_command(self, command: str, workdir: str | None = None) -> Any:
        ...

    def get_archive(self, path: str) -> tuple:
        ...

    def run(self, code: str, libraries: list | None = None) -> Any:
        ...
```

---

## Complete Example

```python
from llm_sandbox import (
    SandboxSession,
    SandboxBackend,
    ArtifactSandboxSession,
    get_security_policy,
    SecurityPolicy,
    SecurityPattern,
    SecurityIssueSeverity
)
from llm_sandbox.exceptions import SandboxTimeoutError
import base64

# Basic usage
with SandboxSession(lang="python") as session:
    result = session.run("print('Hello, World!')")
    print(result.stdout)

# With timeout configuration
with SandboxSession(
    lang="python",
    execution_timeout=30.0,  # 30 seconds for code execution
    session_timeout=300.0,   # 5 minutes session lifetime
    default_timeout=10.0     # Default timeout for operations
) as session:
    try:
        # This will use the execution_timeout (30s)
        result = session.run("print('Normal execution')")

        # Override timeout for specific execution
        result = session.run("""
import time
time.sleep(5)
print('Long operation completed')
        """, timeout=15.0)  # Override with 15 seconds

    except SandboxTimeoutError as e:
        print(f"Operation timed out: {e}")

# With security policy
policy = get_security_policy("production")
policy.add_pattern(SecurityPattern(
    pattern=r"requests\.get\(.*internal\.company",
    description="Internal network access",
    severity=SecurityIssueSeverity.HIGH
))

with SandboxSession(
    lang="python",
    security_policy=policy,
    runtime_configs={
        "cpu_count": 2,
        "mem_limit": "512m",
        "timeout": 30
    }
) as session:
    # Check code safety
    code = "import requests; requests.get('https://api.example.com')"
    is_safe, violations = session.is_safe(code)

    if is_safe:
        result = session.run(code, libraries=["requests"])
        print(result.stdout)
    else:
        print("Code failed security check")

# With artifact extraction
with ArtifactSandboxSession(
    lang="python",
    backend=SandboxBackend.DOCKER
) as session:
    result = session.run("""
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('Sine Wave')
plt.show()
    """, libraries=["matplotlib", "numpy"])

    # Save plots
    for i, plot in enumerate(result.plots):
        with open(f"plot_{i}.{plot.format.value}", "wb") as f:
            f.write(base64.b64decode(plot.content_base64))

# Kubernetes backend
with SandboxSession(
    backend=SandboxBackend.KUBERNETES,
    lang="python",
    kube_namespace="default",
    pod_manifest={
        "spec": {
            "containers": [{
                "resources": {
                    "limits": {
                        "memory": "512Mi",
                        "cpu": "1"
                    }
                }
            }]
        }
    }
) as session:
    result = session.run("print('Running in Kubernetes!')")
    print(result.stdout)
```
