Skip to main content
This guide shows how to use serverless sandboxes for reinforcement learning (RL) training workflows where models execute tool calls in isolated environments. It’s intended for ML engineers and researchers building agent training pipelines who need safe, ephemeral environments to evaluate model-generated actions and compute rewards.

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 CWSANDBOX_API_KEY to a CoreWeave API access token:
Install the Python SDK:
The examples on this page create sandboxes from SandboxDefaults and use CoreWeave authentication by default. To use a Forge API key, follow the explicit authentication setup in Get started and pass the resulting auth value to each SandboxDefaults(...).

Core pattern

The core setup is an agent loop that runs on your training infrastructure, with tool calls that execute in a sandbox.
The sandbox persists across tool calls within an episode, so file changes accumulate as the agent works.

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:
Useful metadata to include in tags: 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).
How it uses CoreWeave sandboxes: The example uses cwsandbox.wait() to process results as they complete:
Run it:
No additional dependencies required. No GPU needed. Expected output: Results arrive as executions complete, so faster problems finish first:

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{}):
This pattern works for training models to generate correct code in a single turn.

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.
How it uses CoreWeave sandboxes: The reward function extracts code from <answer> tags (the standard GRPO pattern), creates sandboxes in parallel through a Session, executes each completion, and returns binary rewards:
The prompts use a system message instructing the model to format code with <answer> tags:
The Session tracks sandboxes and cleans them up when it closes. Run it:
GPU is recommended for reasonable performance. Without one, training works but is slow. Expected output:
Understanding the output: The number of sandboxes varies per step because the script only creates sandboxes when 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.
Expected with a small, untrained model. As training progresses, you should see fewer skipped completions and more passes.

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:
For reward computation, catch exceptions and return a fallback reward instead of propagating to the training loop.

Weights & Biases metrics integration

When you use Weights & Biases 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

If the wandb package is installed and a Weights & Biases run is active (wandb.run exists), metrics logging is enabled automatically. Install the optional package and set a Forge API key for experiment tracking:
Pass the key explicitly to wandb.login(). FORGE_API_KEY is read by this example; it isn’t automatically detected by the SDK. Sandbox authentication continues to use CWSANDBOX_API_KEY:

Explicit control

Control metrics reporting with the report_to parameter:

Metrics

Execution metrics are tracked automatically when exec() 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:
You can also access per-sandbox statistics through the exec_stats property:

Per-sandbox exec metrics

Sessions with Weights & Biases 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.
Example dashboard usage:
  • Plot avg_execs_per_sandbox versus training step to see tool usage trends over training.
  • Alert if max_execs_per_sandbox exceeds a threshold (runaway agent making excessive tool calls).
  • Compare min/max spread to detect episodes where agents get stuck in loops versus complete quickly.
By default, log_metrics() resets the counters after logging. Set reset=False to keep accumulating:
Metrics are also logged automatically when the session closes, so you get final summary metrics even without explicit logging.

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. The examples/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 art package (openpipe-art) for trajectory collection and training.
  • Supports two backends: LocalBackend (requires GPU) or TinkerBackend (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:
  1. 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.
  2. 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).
How it works:
  1. The inference model generates multiple trajectories per problem, each with tool calls executed in a CoreWeave sandbox.
  2. Each trajectory receives a binary reward: 1.0 if tests pass, 0.0 otherwise.
  3. Trajectories for the same problem form a group, and GRPO compares trajectories within each group.
  4. The base model (Qwen3-8B) is trained to prefer higher-reward trajectories over lower-reward ones.
After training, you deploy Qwen3-8B with the same tool definitions. It has learned to make similar tool calls by imitating the successful trajectories from the inference model.

Prerequisites

Environment variables:
For optional Weights & Biases logging, set a Forge API key:
ART 0.5.7 checks the legacy WANDB_API_KEY variable before enabling its logging integration. Add this compatibility mapping to train.py before it creates the backend. The key is a Forge API key:

Installation

This installs:
For LocalBackend with GPU support, also install:

Running the example

Expected output:

Configuration options

Architecture

Key ART imports:
Rollout returns art.Trajectory:
Tool-calling pattern: The rollout uses OpenAI-compatible tool calling with two tools:
  • execute_code: Test code in sandbox, returns stdout/stderr.
  • submit_solution: Final submission, runs all test cases.
Sandboxes are tagged for tracking:

Data flow

The training pipeline has several components:
  1. 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.
  2. 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.
  3. CoreWeave sandbox (code execution): Each rollout uses a single CoreWeave sandbox that persists across all tool calls. When the model calls execute_code or submit_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.
  4. Trajectory collection: The rollout accumulates the conversation history (messages and tool results) along with the final reward into an art.Trajectory object. Multiple trajectories for the same problem form an art.TrajectoryGroup.
  5. Training backend: The collected trajectory groups are sent to the training backend. With LocalBackend, training happens on your local GPU. With TinkerBackend, trajectories are uploaded to Thinking Machines’s Tinker service, which handles training remotely. No local GPU is required.
Last modified on October 14, 2026