**Harnessing the Power of Code-Executing LLM Agents with Docker**
The ability for an LLM agent to write and execute code is a transformative capability. Once an agent moves beyond text generation to code execution, it can inspect datasets, write sophisticated data processing logic, and produce tangible artifacts ready for downstream use. This opens the door to a vast new realm of autonomous agent applications.
In this guide, we’ll walk through building a practical coding agent using the OpenAI Agents SDK and Docker. We’ll move from a foundational mental model to a full case study, where an agent analyzes a CSV file and generates a detailed report complete with charts. By the end, you’ll understand the key components needed to build and reuse this pattern.
—
### 1. How Code-Executing Agents Work
A code-executing LLM agent is composed of three primary components: the model, the workspace, and the execution environment. Let’s break down each one.
#### 1.1 The Model
At the heart of the system is the LLM itself. The model is responsible for inspecting available files, determining the necessary analysis, writing the appropriate code, reviewing execution results, and iterating on its approach as needed.
#### 1.2 Workspace
The workspace acts as the agent’s operational space. Input files, such as CSVs, PDFs, or document folders, are staged here. The agent works within this environment and outputs its generated artifacts back into it.
#### 1.3 Execution Environment
The agent writes code but does not run it. Therefore, an execution environment is required. This can be a hosted solution or, more commonly, a locally controlled sandbox. Docker is the standard tool for packaging such a runtime, providing isolation and reproducibility.
#### 1.4 Cross-Cutting Concern: Control
A crucial design decision involves control at three levels:
* **Model Layer:** Defining instructions and desired artifacts.
* **Workspace Layer:** Managing input and output files.
* **Execution Layer:** Specifying dependencies and access permissions.
#### 1.5 OpenAI Agents SDK
The OpenAI Agents SDK provides a `SandboxAgent` that perfectly encapsulates this pattern. Configuration involves defining a `Manifest` to stage local files and then instantiating the agent with specific instructions and a model.
“`python
from pathlib import Path
from agents.sandbox import LocalFile, Manifest
manifest = Manifest(
entries={
“input/data.csv”: LocalFile(src=Path(“data/data.csv”)),
},
)
from agents.sandbox import SandboxAgent
agent = SandboxAgent(
name=”coding agent”,
instructions=”Inspect the input files, write and run code when useful, and save requested artifacts.”,
model=”gpt-5.4″,
default_manifest=manifest,
)
“`
To execute, a Docker sandbox session is created and linked to the agent at runtime.
“`python
import docker
from agents.sandbox.sandboxes.docker import DockerSandboxClient
from agents.sandbox.sandboxes.docker import DockerSandboxClientOptions
docker_client = DockerSandboxClient(docker.from_env())
sandbox_options = DockerSandboxClientOptions(image=”my-agent-sandbox:latest”)
sandbox_session = await docker_client.create(
manifest=manifest,
options=sandbox_options,
)
await sandbox_session.apply_manifest()
from agents import Runner, RunConfig
from agents.sandbox import SandboxRunConfig
result = await Runner.run(
agent,
“Analyze input/data.csv and save a short report under output/report.md.”,
run_config=RunConfig(
sandbox=SandboxRunConfig(session=sandbox_session),
),
)
“`
The results, including any output files, can then be persisted as a tar archive and extracted locally.
> **Alternative Approaches:** The SDK also supports `CodeInterpreterTool` for OpenAI-managed execution or `ShellTool` for command-line workflows, providing flexibility beyond Docker.
—
### 2. Case Study: An Agent That Analyzes a CSV
Let’s put theory into practice with a data analysis task.
#### 2.1 The Setup
We tasked the agent with analyzing an hourly building energy dataset to identify anomalies. The input is a CSV with columns: `timestamp`, `energy_kwh`, and `outdoor_temp_c`. The agent must produce an anomalies CSV, a visualization, and a markdown report.
#### 2.2 Prepare the Docker Runtime
The agent needs a Python environment with data science libraries. We define this in a `Dockerfile`.
“`dockerfile
FROM python:3.12-slim
ENV MPLBACKEND=Agg
RUN pip install –no-cache-dir numpy scipy pandas matplotlib
WORKDIR /workspace
“`
After building the image with `subprocess.run([“docker”, “build”, “-t”, “energy-agent-sandbox:latest”, “.”])`, it is passed to the sandbox client.
#### 2.3 Define and Run the Agent
The agent is configured with a manifest pointing to the input file and specific instructions.
“`python
from pathlib import Path
from agents.sandbox import LocalFile, Manifest
manifest = Manifest(
entries={
“input/building_energy.csv”: LocalFile(src=Path(“data/building_energy.csv”)),
},
)
INSTRUCTIONS = “””
You are a practical data analyst.
Use the sandbox workspace to inspect files, write and run code when useful,
and save clear artifacts.
Keep conclusions grounded in computed evidence.
The sandbox has Python with numpy, scipy, pandas, and matplotlib available.
“””.strip()
agent = SandboxAgent(
name=”Energy anomaly analyst”,
instructions=INSTRUCTIONS,
model=”gpt-5.4″,
default_manifest=manifest,
)
“`
The prompt explicitly requests specific output files and a tone-free analysis. The agent is then run inside the Docker session.
#### 2.4 Inspect the Results
After completion, the workspace is archived, and the output files are extracted locally.
The agent successfully identified a clear anomaly event and generated all requested artifacts. By reviewing the agent’s internal steps, we see it loaded the data with pandas, performed statistical analysis, and generated the report and chart.
—
### 3. Practical Things To Keep In Mind
Building an effective code-executing agent involves careful planning:
1. **Be Explicit in Instructions:** Clearly define the agent’s role, task, and expected output.
2. **Curate the Workspace:** Only stage the files the agent needs to work on.
3. **Choose the Right Runtime:** Install all necessary libraries in the Docker image beforehand for efficiency.
4. **Specify Outputs:** Clearly state the names and locations of output files to simplify extraction.
Once these principles are set, this pattern becomes a powerful and reusable workflow for countless agentic tasks.
—
### FAQ
**What do I need to run this example?**
You need Python, Docker, and the OpenAI Agents SDK (`openai-agents[docker]`). Ensure Docker is installed and running on your machine.
**What is the purpose of the `MPLBACKEND=Agg` environment variable?**
It allows `matplotlib` to generate plots in a headless environment (without a display), which is essential for Docker containers.
**Can I use a different runtime instead of Docker?**
Yes. The SDK supports alternatives like `CodeInterpreterTool` for cloud-based execution or `ShellTool` for local command-line tasks.
**How do I extract the output files?**
The example code uses `persist_workspace()` to create a tar archive, which is then extracted locally using Python’s `tarfile` module.
—
### Conclusion
Code-executing agents, powered by tools like Docker and the OpenAI Agents SDK, unlock a new dimension of autonomous capability. By guiding an LLM to write, execute, and validate code within a secure sandbox, we can automate complex data analysis and processing workflows. This guide provides a foundational pattern you can adapt and extend for your own intelligent agent projects. The future of agentic applications is not just in thinking—but in doing.



