# Building a coding agent that runs tests in a sandbox



Learn how to build a self-correcting coding agent using LLMs and Podstack's on-demand GPU jobs to securely execute and test code in a sandboxed environment.



Agents · 2026-11-05 · 4 min read



Building an AI agent that writes code is a popular weekend project, but building one that writes *working* code is a significant engineering challenge. The gap between a hallucinated snippet and a functional script is usually a feedback loop: the agent needs to run its code, observe the stack trace, and iterate until the tests pass.

However, executing LLM-generated code on your local machine or a production server is a major security risk. To build a robust coding agent, you need a secure, isolated sandbox that can be spun up instantly, execute arbitrary logic, and provide the results back to the agent.

In this guide, we’ll walk through the architecture of a coding agent that utilizes a sandboxed environment to validate its work before delivering a final solution.

## The Architecture of a Coding Agent

A functional coding agent requires three core components:
1.  **The Planner:** An LLM that decomposes a task into functions and tests.
2.  **The Executor:** A secure sandbox environment where the code is actually run.
3.  **The Feedback Loop:** A mechanism to pipe `stderr` and test failures back to the LLM for self-correction.

For ML-heavy tasks—such as optimizing a PyTorch kernel or running a data science pipeline—the executor needs more than just a CPU. It needs a GPU-accelerated environment that is billed only for the seconds the code is actually running.

## Step 1: Defining the Sandbox Environment

Your agent needs a consistent environment. Instead of managing complex Dockerfiles locally, you can define a remote environment that includes your necessary dependencies (like `pytest`, `numpy`, or `torch`).

When the agent generates code, we don't just want the source; we want a test suite. The agent should be prompted to output two files: `solution.py` and `test_solution.py`.

## Step 2: Implementing the Execution Logic

Using the Podstack Python SDK, we can trigger a remote "job" that acts as our sandbox. This allows us to spin up a GPU-enabled container, run the tests, and tear it down immediately, paying only for the execution time.

Here is a conceptual implementation of how the agent interacts with the sandbox:

```python
import os
from podstack import Podstack

# Initialize the client using your API Key
client = Podstack(api_key=os.getenv("PODSTACK_API_KEY"))

def run_in_sandbox(code: str, tests: str):
    """
    Deploys the generated code to a secure Podstack job 
    to validate execution.
    """
    # Combine code and tests into a single execution script
    full_script = f"{code}\n\n{tests}"
    
    # Run a serverless GPU job
    job = client.jobs.run(
        image="pytorch/pytorch:latest",
        command=["python3", "-c", full_script],
        gpu="A10",  # Request a specific GPU for ML tasks
    )
    
    # Wait for the result and capture logs
    result = job.wait()
    
    return {
        "status": result.status,
        "logs": result.logs,
        "exit_code": result.exit_code
    }

# Example LLM-generated content
generated_code = "def add(a, b): return a + b"
generated_tests = "assert add(2, 3) == 5"

output = run_in_sandbox(generated_code, generated_tests)

if output["exit_code"] != 0:
    print(f"Tests failed. Feed this back to the LLM: {output['logs']}")
else:
    print("Code validated successfully.")
```

## Step 3: The Self-Correction Loop

Once the sandbox returns the logs, the agent enters the "Refinement Phase." If the `exit_code` is non-zero, the agent receives the full traceback. 

Modern LLMs are remarkably good at debugging when provided with the exact error message. By repeating this loop (usually 2-3 times), the success rate of the agent increases drastically compared to a single-shot generation.

## Practical Tips for Sandboxing

*   **Set Timeouts:** Always set a maximum duration for your sandbox jobs. Coding agents can occasionally write infinite loops.
*   **Dependency Management:** If your agent needs specific libraries, pre-build a container image. Pulling `pip` packages inside the sandbox for every run adds latency.
*   **Minimal Permissions:** Ensure the sandbox has no access to your environment variables or internal network. Podstack jobs are isolated by default, providing an extra layer of security against malicious code generation.
*   **State Persistence:** If the agent is working on a large project, use a persistent volume to mount the codebase into the sandbox so the agent can see the entire context.

## Scaling with Podstack

The bottleneck for most coding agents is the infrastructure. Setting up a fleet of GPU nodes to handle simultaneous agent requests is an operations nightmare. 

Podstack simplifies this by treating GPU functions as serverless primitives. You don't need to manage a cluster; you simply define the task and run it. Whether you are building an agent that writes high-performance CUDA kernels or a simple data processing script, you can use the Podstack API to monitor your jobs in real-time:

```text
Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.
```

By offloading the execution to Podstack's on-demand GPU infrastructure, your agent remains fast, secure, and cost-effective, billing you only for the seconds it takes to run the tests. This allows you to scale from a local prototype to a production-grade coding assistant without changing your backend architecture.
