Skip to main content
이 가이드에서는 모델이 격리된 환경에서 도구 Call을 실행하는 강화 학습(RL) 트레이닝 워크플로에서 서버리스 샌드박스를 사용하는 방법을 설명합니다. 모델이 생성한 액션을 평가하고 보상을 계산할 수 있는 안전한 임시 환경이 필요한 에이전트 트레이닝 파이프라인을 구축하는 ML 엔지니어와 연구자를 위한 가이드입니다.

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. WANDB_API_KEY를 W&B API 키로 설정하세요.
Install the Python SDK:
이 페이지의 예시는 SandboxDefaults를 기반으로 샌드박스를 생성합니다. W&B API 키로 인증하려면 cwsandbox에서 AuthStrategy를 임포트하고 각 SandboxDefaults(...)에 auth=AuthStrategy.WANDB를 추가하세요.

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:
실행 방법: 스크립트를 실행하기 전에 스크립트의 SandboxDefaults(...) 호출에 auth=AuthStrategy.WANDB를 추가하고 cwsandbox에서 AuthStrategy를 임포트하세요. 이 스크립트는 W&B 인증을 자동으로 사용하도록 설정되어 있지 않습니다.
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. 실행 방법: 스크립트를 실행하기 전에 스크립트의 SandboxDefaults(...) 호출에 auth=AuthStrategy.WANDB를 추가하고 cwsandbox에서 AuthStrategy를 임포트하세요. 이 스크립트는 W&B 인증을 자동으로 사용하도록 설정되어 있지 않습니다.
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.

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

If WANDB_API_KEY is set and a wandb run is active (wandb.run exists), metrics logging is enabled automatically:

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 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.
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:

Installation

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

예시 실행하기

train.py를 실행하기 전에 해당 스크립트의 SandboxDefaults(...) 호출에 auth=AuthStrategy.WANDB를 추가하고, cwsandbox에서 AuthStrategy를 임포트하세요. 스크립트 자체에서는 W&B 인증을 선택하지 않습니다.
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.
마지막 수정일 2026년 10월 5일