/ai-toolkit:reinforcement-learningfrom ai-toolkit
Builds, trains, and debugs reinforcement learning agents in Python using Gymnasium and Stable-Baselines3 (PPO, SAC, DQN, TD3, A2C). Includes scripts for environment validation, pre-training sanity checks, and policy evaluation reports.
Ships in ai-toolkit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Help the user get an agent that actually learns, and show that it did. Most RL failures come from the environment and the setup (observation scale, reward design, termination flags, evaluation mistakes) rather than from the algorithm, so check those before reaching for exotic fixes.
The ecosystem moves: Gymnasium 1.x replaced OpenAI Gym, and SB3 changes defaults between releases. Before writing code against a specific API, check what the user has installed (pip show gymnasium stable-baselines3) and match it. If a web or docs tool is available, look up any API you're unsure of rather than relying on the snippets here. Current as of October 2026: Gymnasium 1.4, Stable-Baselines3 2.9 (Gymnasium 1.x support needs SB3 2.4 or later).
Stable-Baselines3 is the default here: reliable implementations, good defaults, and the bundled scripts target it. CleanRL suits users who want to read and modify a single-file implementation; TorchRL suits custom research algorithms. For distributed training at scale, Ray RLlib is the usual choice, but this skill doesn't cover it.
| Situation | Start with | Why |
|---|---|---|
| Discrete actions, getting started | PPO | Stable with default settings |
| Discrete actions, environment steps are expensive | DQN | Off-policy, reuses experience |
| Continuous control | SAC (or TD3) | Sample-efficient; SAC tunes its own exploration |
| Image observations | PPO with CnnPolicy | Handles pixels well |
| Need fast iterations on a simple task | A2C | Simple, quick updates |
SB3's DQN is the vanilla algorithm; it has no Double or Dueling options. If the user needs those, they need a custom policy or sb3-contrib (which has QR-DQN).
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy
train_env = make_vec_env("CartPole-v1", n_envs=4, seed=0)
model = PPO("MlpPolicy", train_env, verbose=1, seed=0)
model.learn(total_timesteps=100_000)
model.save("ppo_cartpole")
eval_env = make_vec_env("CartPole-v1", n_envs=1, seed=123) # separate env for evaluation
mean, std = evaluate_policy(model, eval_env, n_eval_episodes=20, deterministic=True)
print(f"{mean:.1f} +/- {std:.1f}")
import gymnasium as gym
import numpy as np
from gymnasium import spaces
class CustomEnv(gym.Env):
metadata = {"render_modes": ["human", "rgb_array"]}
def __init__(self, render_mode=None):
super().__init__()
self.observation_space = spaces.Box(low=-1.0, high=1.0, shape=(4,), dtype=np.float32)
self.action_space = spaces.Discrete(2)
self.render_mode = render_mode
def reset(self, seed=None, options=None):
super().reset(seed=seed) # seeds self.np_random
self.state = self.np_random.uniform(-0.05, 0.05, size=(4,)).astype(np.float32)
self.steps = 0
return self.state, {}
def step(self, action):
self.steps += 1
# update self.state from the action here
reward = 0.0
terminated = False # the task ended (success or failure)
truncated = self.steps >= 500 # a time limit cut the episode short
return self.state, reward, terminated, truncated, {}
Keep terminated and truncated distinct: algorithms bootstrap the value of a truncated state but not a terminated one, and mixing them up quietly biases learning. Give every environment a time limit, or evaluation can loop forever.
The scripts live in this skill's scripts/ folder, which after install is ${CLAUDE_PLUGIN_ROOT}/skills/reinforcement-learning/scripts/. Run them from the user's project directory so a module.path:EnvClass spec such as src.env:MyEnv can be imported (the scripts add the current directory to the import path). Each also accepts a registered id such as CartPole-v1.
python3 …/validate_env.py src.env:MyEnv. It checks Gymnasium API compliance, spaces, NaNs, determinism and termination, and exits nonzero on failure (usable in CI).python3 …/pretrain_check.py src.env:MyEnv. It reports a random-policy baseline and warns about observation and reward scales, sparse rewards, and termination patterns. The trained agent has to beat this baseline clearly.tensorboard_log="runs/"). Save the VecNormalize statistics alongside the model if you normalize (env.save("models/vecnormalize.pkl")).references/debugging.md if learning stalls.python3 …/eval_report.py src.env:MyEnv --model models/best.zip --algo ppo --vecnormalize models/vecnormalize.pkl. Pass --vecnormalize whenever training used VecNormalize: without the statistics the agent sees unnormalized inputs and scores like a random policy, which looks exactly like "it learned nothing". It writes a Markdown report (to --output, default eval_report.md).references/deployment.md (ONNX is the main path).import optuna
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy
def objective(trial):
params = {
"learning_rate": trial.suggest_float("learning_rate", 1e-5, 1e-3, log=True),
"n_steps": trial.suggest_categorical("n_steps", [256, 512, 1024, 2048]),
"gamma": trial.suggest_float("gamma", 0.9, 0.9999),
}
model = PPO("MlpPolicy", make_vec_env("CartPole-v1", n_envs=4, seed=trial.number), verbose=0, **params)
model.learn(total_timesteps=50_000)
# Score on a separate env: scoring on the training env rewards overfitting to it.
eval_env = make_vec_env("CartPole-v1", n_envs=1, seed=10_000 + trial.number)
mean_reward, _ = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
return mean_reward
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=50)
print(study.best_params)
If training uses VecNormalize, evaluate with a VecNormalize-wrapped eval env that loads the training statistics with training=False and norm_reward=False. For pruning of bad trials, see references/training.md.
VecNormalize. The exception is image observations (uint8 pixels): CnnPolicy scales them to [0, 1] itself, and normalizing pixels with running statistics hurts.train/entropy_loss, which is the negative of the policy's entropy, so collapse shows as entropy_loss rising toward 0.references/algorithms.md: DQN, PPO, SAC, A2C, TD3 in depth, with SB3 defaultsreferences/environments.md: Gymnasium setup, custom environments, wrappers, Atari and MuJoCoreferences/training.md: hyperparameters, reward design, normalization, callbacksreferences/debugging.md: symptoms and fixes for agents that don't learnreferences/evaluation.md: metrics, logging, reproducibilityreferences/deployment.md: ONNX export, torch.export, quantization, inference safetypip install "stable-baselines3[extra]>=2.4" "gymnasium>=1.0" optuna # [extra] adds TensorBoard, progress bars, Atari wrappers
pip install "gymnasium[atari]" # Atari: ROMs ship with ale-py now; call gym.register_envs(ale_py) after import ale_py
pip install "gymnasium[mujoco]" # MuJoCo
Use a project virtual environment (python3 -m venv .venv or uv venv) rather than the system Python.
references/algorithms.md (opens in a new tab)references/debugging.md (opens in a new tab)references/deployment.md (opens in a new tab)references/environments.md (opens in a new tab)references/evaluation.md (opens in a new tab)references/training.md (opens in a new tab)scripts/eval_report.py (opens in a new tab)scripts/pretrain_check.py (opens in a new tab)scripts/validate_env.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
6 skills in this plugin
/cpp-reinforcement-learningReinforcement learning in C++ with LibTorch (the PyTorch C++ frontend) and C++20. Use when the user is implementing DQN, PPO or SAC in C++, building a replay buffer or rollout buffer in C++, fixing libtorch memory growth or GPU issues in a C++ agent, running environments in parallel threads, or loading a policy trained in Python into a C++ program (games, robotics, simulators). Not for Python RL with Gymnasium or Stable-Baselines3, including exporting a Python policy to ONNX (use reinforcement-learning), or for general deep learning (use deep-learning)./deep-learningBuild and train neural networks with Keras 3 on any backend (JAX, TensorFlow or PyTorch). Use when the user is writing Keras code or asks for a Keras model, wants to migrate tf.keras / Keras 2 code to Keras 3, or is working on image classification, segmentation, text classification, sequence-to-sequence, time-series forecasting, or generative models (VAE, GAN) in Keras, including custom training loops, callbacks, transfer learning, mixed precision and multi-GPU training. Not for plain PyTorch or JAX training loops without Keras, Hugging Face / LLM fine-tuning, or reinforcement learning (use reinforcement-learning)./openclaw-setupInstall, configure, secure and troubleshoot OpenClaw (formerly Clawdbot / Moltbot), the self-hosted personal AI assistant that answers through messaging apps. Covers installing on a Mac or Linux machine or a VPS with Docker (including Hostinger), Anthropic API setup and cost control, Telegram and iMessage channels, and hardening (gateway binding, pairing, tool limits). Use when the user mentions OpenClaw, Clawdbot or Moltbot, `openclaw onboard`, `openclaw doctor`, or setting up, fixing or hardening their OpenClaw gateway. Not for building an assistant from scratch with an SDK, generic VPS or SSH hardening unrelated to OpenClaw, or writing OpenClaw plugins. For a read-only security check of an existing install, /openclaw-audit runs the checklist./prompt-engineerWrite, review, debug, and migrate prompts for Claude models (Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5) using Anthropic's official prompt engineering guidance. Covers system prompts, agent and harness prompts, tool descriptions, few-shot examples, and effort/thinking settings. Use this whenever the user wants to create or improve a prompt or system prompt. Also use it when they ask why Claude is behaving a certain way: too verbose or too terse, stops early or asks permission mid-task, over-engineers, goes silent between tool calls, skips searches or tool calls, refuses benign requests, ignores mid-turn messages, or returns broken JSON. It also covers migrating prompts or API calls to a newer Claude model, choosing an effort level or thinking configuration, and writing instructions that another LLM agent will follow, even when the user never says "prompt engineering"./x402-paymentsBuild apps that charge for, or pay for, HTTP requests with the x402 protocol (HTTP 402 "Payment Required" plus stablecoin payments, usually USDC on Base or Solana). Covers paid API endpoints and middleware (Express, Hono, Next.js), clients and AI agents that pay for x402 resources with spending limits, MCP tools that charge or pay through x402, and moving from testnet to mainnet. Use when the user mentions x402, HTTP 402, per-request USDC payments, paywalled APIs for agents, or agent-to-agent payments. Not for card or Stripe billing, Coinbase Commerce checkout, smart-contract development, or general wallet and trading code. For a new project, /x402-scaffold generates a working testnet starter.npx claudepluginhub aznatkoiny/zai-skills --plugin ai-toolkitOther plugins' skills for the same job