Why sandboxes for agent tool execution
Training code agents with RL requires executing tool calls (bash commands, file operations) in isolated environments. Untrusted model-generated code can modify the host filesystem, hit the network, or produce non-deterministic results. Sandboxes give you isolated, ephemeral environments where tool calls run without affecting the host or other rollouts. In a training loop, the model generates actions (tool calls), the sandbox executes them, and observations flow back to the model. The sandbox persists across tool calls within an episode, so file changes and installed packages carry over between steps. Reward comes from the final sandbox state (for example, tests passing) or trajectory quality. The tagging and listing APIs make it practical to clean up and monitor training runs with thousands of sandboxes.Prerequisites
Before you begin, complete the following setup steps. Set yourCWSANDBOX_API_KEY to a
CoreWeave API Access Token:
Core pattern
The core setup is an agent loop that runs on your training infrastructure, with tool calls that execute in a sandbox.Training step with parallel episodes
Process a batch of tasks with one sandbox per episode:Tagging for job metadata
Tags let you filter and find sandboxes created by your training jobs, which becomes essential when a single run can spawn thousands of sandboxes. Include metadata that helps identify sandboxes when debugging or cleaning up:
Sandbox tags become Kubernetes pod labels, which the CoreWeave observability platform uses for filtering and dashboards.
Try the reward function example
A minimal integration that computes code execution rewards with parallel sandbox execution. What it does:- Executes a set of toy code completions (arithmetic, string operations, syntax errors, runtime errors).
- Creates one sandbox per completion for isolation.
- Computes binary rewards: 1.0 for successful execution, 0.0 for failure.
- Shows progress as results arrive (faster executions complete first).
cwsandbox.wait() to process results as they complete:
TRL GRPOTrainer integration
TRL uses a reward function interface where completions map directly to rewards. The agent generates a completion, and the reward function executes it in a sandbox. The standard pattern uses<answer> XML tags for code extraction (matching the format used in GRPO math examples with \boxed{}):
Try the TRL GRPO integration example
Uses CoreWeave sandboxes with TRL’s GRPOTrainer for code execution rewards. What it does:- Loads a small model (
Qwen/Qwen2.5-0.5B-Instruct). - Creates a toy dataset of simple coding problems.
- Trains the model using GRPO with sandbox-based reward computation.
- Runs 10 training steps to demonstrate the integration.
<answer> tags (the standard GRPO pattern), creates sandboxes in parallel through a Session, executes each completion, and returns binary rewards:
<answer> tags:
extract_xml_answer() finds extractable code in the model’s completion. When the model generates text without the expected <answer>...</answer> tags, that completion is skipped and receives a reward of 0.0.
2 sandboxes, 0/2 passed: Model generated 2 code blocks, both failed execution.1 sandboxes, 0/1 passed, 1 skipped (no code): Model generated 1 code block (failed) and 1 text-only completion.0 sandboxes, 0/0 passed, 2 skipped (no code): Model generated no extractable code in either completion.
Error handling in agent episodes
Sandbox operations can fail (timeouts, missing files, sandbox termination), and how you surface those failures shapes what the agent learns. Return observations that describe what went wrong:W&B metrics integration
When you use W&B for training, cwsandbox Sessions log sandbox usage metrics to your active wandb run automatically. This lets you correlate sandbox health (startup time, execution failures, tool calls per rollout) with your training metrics in the same dashboard. The following sections describe how auto-detection works, how to control reporting explicitly, and which metrics are tracked.Auto-detection
IfWANDB_API_KEY is set and a wandb run is active (wandb.run exists), metrics logging is enabled automatically:
Explicit control
Control metrics reporting with thereport_to parameter:
Metrics
Execution metrics are tracked automatically whenexec() completes:
Tracking is automatic. Call
exec() on any sandbox associated with a session. Call session.log_metrics(step=N) to log at specific training steps:
exec_stats property:
Per-sandbox exec metrics
Sessions with W&B integration also track per-sandbox metrics:
What these tell you about agent behavior:
- High avg_execs_per_sandbox may indicate verbose agents that make many tool calls per episode.
- Large variance (max-min) may indicate inconsistent rollout behavior across episodes.
- Trends over training steps show how agent behavior evolves as the policy improves.
- Plot
avg_execs_per_sandboxversus training step to see tool usage trends over training. - Alert if
max_execs_per_sandboxexceeds a threshold (runaway agent making excessive tool calls). - Compare min/max spread to detect episodes where agents get stuck in loops versus complete quickly.
log_metrics() resets the counters after logging. Set reset=False to keep accumulating:
Monitoring and debugging
The following patterns help you observe what your training run is doing in real time and capture details that make failures easier to diagnose.Counting active sandboxes
Monitor sandbox usage during training:Logging execution details
Capture execution details for debugging reward computation:Multi-step rollouts with ART
The preceding TRL example uses sandboxes for single-shot execution: one sandbox per completion, execute once, return a reward. This works for training models to generate correct code in one attempt. Stateful multi-step rollouts are different: the agent takes multiple actions within a single sandbox, and the sandbox maintains state between actions. The agent can write a file, run it, observe the error, edit the file, and try again, all within the same sandbox. Theexamples/rl_training/art/ directory demonstrates this pattern on the MBPP benchmark. When a solution fails, the agent receives error feedback and can iterate on its approach.
Overview
The remainder of this section walks through what ART is, the training approach the example uses, prerequisites, installation, how to run the example, and how the components fit together. ART (Agent Reinforcement Trainer) is an open source RL framework by OpenPipe for training multi-step agents using GRPO. This example integrates CoreWeave sandboxes with ART:- Uses the
artpackage (openpipe-art) for trajectory collection and training. - Supports two backends:
LocalBackend(requires GPU) orTinkerBackend(no GPU). - Executes code through tool calling in CoreWeave sandbox.
- Computes binary rewards based on MBPP test case results.
Training approach with GRPO and distillation
This example uses distillation with reinforcement learning: a stronger model generates demonstrations, and a smaller model learns to replicate the successful ones. Two models are involved:-
Inference model (
--model, default:gpt-5.1-codex-mini): Generates trajectories during rollouts. This model makes tool calls, sees sandbox results, iterates on errors, and submits solutions. It does not get trained. -
Base model (
--base-model, default:Qwen/Qwen3-8B): The model being trained. It receives the trajectories generated by the inference model and learns from them through GRPO (Group Relative Policy Optimization).
- The inference model generates multiple trajectories per problem, each with tool calls executed in a CoreWeave sandbox.
- Each trajectory receives a binary reward: 1.0 if tests pass, 0.0 otherwise.
- Trajectories for the same problem form a group, and GRPO compares trajectories within each group.
- The base model (Qwen3-8B) is trained to prefer higher-reward trajectories over lower-reward ones.
Prerequisites
Environment variables:
Installation
Running the example
Configuration options
Architecture
art.Trajectory:
execute_code: Test code in sandbox, returns stdout/stderr.submit_solution: Final submission, runs all test cases.
Data flow
The training pipeline has several components:-
Local machine: The training script (
train.py) runs on your machine or training server. It loads problems from the MBPP dataset and orchestrates the training loop. - OpenAI API (inference): During trajectory collection, the rollout code calls the OpenAI API (or compatible endpoint) to generate model responses. The model receives tool definitions and returns tool calls that the rollout executes.
-
CoreWeave sandbox (code execution): Each rollout uses a single CoreWeave sandbox that persists across all tool calls. When the model calls
execute_codeorsubmit_solution, the code runs in that sandbox. This means file changes and state accumulate as the agent iterates: it can write a file, run it, observe an error, and fix it. The sandbox provides isolation so untrusted model-generated code can’t affect the host. Results (stdout, stderr, exit code) flow back to the rollout. -
Trajectory collection: The rollout accumulates the conversation history (messages and tool results) along with the final reward into an
art.Trajectoryobject. Multiple trajectories for the same problem form anart.TrajectoryGroup. -
Training backend: The collected trajectory groups are sent to the training backend. With
LocalBackend, training happens on your local GPU. WithTinkerBackend, trajectories are uploaded to Thinking Machines’s Tinker service, which handles training remotely. No local GPU is required.