> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/training-ai-agents-with-rl.md).

# 使用 RL 训练 AI Agent

了解如何使用强化学习（RL）训练用于现实任务的 AI Agent。

“Agentic” AI 正在变得越来越流行。在这个语境中，“agent” 指的是一个被赋予高级目标和一组工具来实现该目标的 LLM。Agent 通常也是“多轮”的——它们可以执行一个动作，查看它对环境产生了什么影响，然后反复执行另一个动作，直到达成目标或尝试失败。

不幸的是，即使是能力很强的 LLM，也很难可靠地执行复杂的多轮 agentic 任务。有趣的是，我们发现使用一种名为 [GRPO（Group Relative Policy Optimization，组相对策略优化）](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/tutorial-train-your-own-reasoning-model-with-grpo.md) 可以让它们可靠得多！在本指南中，你将学习如何使用开源工具构建可靠的 AI agent。

## 🎨 使用 ART 训练 RL Agent

[ART（Agent Reinforcement Trainer）](https://github.com/openpipe/art) 构建于 [Unsloth](https://github.com/unslothai/unsloth)Unsloth 的 GRPOTrainer 是一个让多轮 agent 训练变得可能且简单的工具。如果你已经在用 Unsloth 进行 GRPO，并且需要训练能够处理复杂多轮交互的 agent，ART 会简化这一过程。

<div align="left"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-c97e63a69ecd17685c6e09cb41fd625d43a3545d%2FScreenshot_2025-07-19_at_1.23.18_PM.webp?alt=media" alt="" width="375"><figcaption><p>使用 Unsloth+ART 训练的 agent 模型，往往能在 agentic 工作流上胜过通过提示词驱动的模型。</p></figcaption></figure></div>

### ART + Unsloth

ART 基于 Unsloth 内存和算力高效的 GRPO 实现之上构建。此外，它还增加了以下能力：

#### 1. 多轮 Agent 训练

ART 引入了“轨迹（trajectory）”这一概念，它会随着 agent 的执行而累积。随后，这些轨迹可以被打分并用于 GRPO。轨迹可以很复杂，甚至包含非线性历史、子 agent 调用等。它们还支持工具调用和响应。

#### 2. 灵活集成到现有代码库中

如果你已经有一个与提示词模型配合工作的 agent，ART 会尽量减少你需要做出的修改，以便包装你现有的 agent 循环并将其用于训练。

从架构上看，ART 被拆分为一个位于你代码库中的“前端”客户端，它通过 API 与一个“后端”通信，实际训练就在后端进行（如果你更喜欢使用 ART 的 `LocalBackend`）。这带来了一些关键优势：

* **所需设置最少**：ART 前端依赖极少，可以轻松添加到现有的 Python 代码库中。
* **随时随地训练**：你可以在笔记本电脑上运行 ART 客户端，让 ART 服务器启动一个临时的、支持 GPU 的环境，或者在本地 GPU 上运行
* **兼容 OpenAI 的 API**：ART 后端通过一个兼容 OpenAI 的 API 提供正在训练中的模型，这与大多数现有代码库兼容。

#### 3. RULER：零样本 Agent 奖励

ART 还提供了一个内置的通用奖励函数，称为 [RULER](https://art.openpipe.ai/fundamentals/ruler) （Relative Universal LLM-Elicited Rewards，相对通用的 LLM 诱导奖励），它可以消除对手工设计奖励函数的需求。令人惊讶的是，使用 RULER 自动奖励函数进行 RL 训练的 agent，往往能达到或超越使用人工编写奖励函数训练的 agent 的表现。这让 RL 入门更容易。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-b4168c3c380f6c8258c31083dcb65a5fcd2308b8%2FScreenshot_2025-07-19_at_1.21.08_PM.webp?alt=media" alt="" width="375"><figcaption></figcaption></figure>

```python
# 之前：数小时的奖励设计
def complex_reward_function(trajectory):
    # 50 多行精心设计的评分逻辑...
    pass

# 之后：一行 RULER
judged_group = await ruler_score_group(group, "openai/o3")
```

### 何时选择 ART

ART 可能很适合需要以下内容的项目：

1. **多步骤 agent 能力**：当你的用例涉及需要执行多个动作、使用工具或进行长时间对话的 agent 时
2. **无需奖励设计的快速原型开发**：RULER 的自动奖励评分可以将你的项目开发时间缩短 2-3 倍
3. **与现有系统集成**：当你需要以最小改动为现有的 agentic 代码库添加 RL 能力时

### 代码示例：ART 实战

```python
import art
from art.rewards import ruler_score_group

# 使用 Unsloth 支持的 base model 初始化模型
model = art.TrainableModel(
    name="agent-001",
    project="my-agentic-task",
    base_model="Qwen/Qwen2.5-14B-Instruct",  # 任何 Unsloth 支持的模型
)

# 定义你的 rollout 函数
async def rollout(model: art.Model, scenario: Scenario) -> art.Trajectory:
    openai_client = model.openai_client()
    trajectory = art.Trajectory(
        messages_and_choices=[
            {"role": "system", "content": "..."},
            {"role": "user", "content": "..."}
        ]
    )
    # 你的 agent 逻辑在这里...    
    return trajectory

# 使用 RULER 进行自动奖励训练
groups = await art.gather_trajectory_groups(
    (
        art.TrajectoryGroup(rollout(model, scenario) for _ in range(8))
        for scenario in scenarios
    ),
    after_each=lambda group: ruler_score_group(
        group,
        "openai/o3",
        swallow_exceptions=True
    )
)

await model.train(groups)
```

### 开始使用

要将 ART 添加到基于 Unsloth 的项目中：

```bash
pip install openpipe-art # 或 `uv add openpipe-art`
```

然后查看 [示例笔记本](https://art.openpipe.ai/getting-started/notebooks) 了解 ART 在以下任务中的实际应用：

* 表现优于 o3 的邮件检索 agent
* 游戏对战 agent（2048、井字棋、Codenames）
* 复杂推理任务（Temporal Clue）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide/training-ai-agents-with-rl.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
