# 使用 RL 训练 AI 智能体

“有代理性”的人工智能随时间变得越来越流行。在此语境中，“代理”是指被赋予高层目标和一组工具以实现该目标的大型语言模型（LLM）。代理通常也是“多回合”的——它们可以执行一个动作，查看该动作对环境的影响，然后重复执行另一个动作，直到实现目标或尝试失败。

不幸的是，即便是非常有能力的 LLM 在可靠地执行复杂的多回合代理任务时也可能遇到困难。有趣的是，我们发现使用一种名为 [GRPO（组相对策略优化）](https://unsloth.ai/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide/tutorial-train-your-own-reasoning-model-with-grpo) 的强化学习算法训练代理，可以使它们可靠性大大提高！在本指南中，你将学习如何使用开源工具构建可靠的 AI 代理。

## 🎨 使用 ART 训练强化学习代理

[ART（Agent Reinforcement Trainer，代理强化训练器）](https://github.com/openpipe/art) 构建于 [Unsloth](https://github.com/unslothai/unsloth)的 GRPOTrainer 之上，是一个使训练多回合代理变得可能且简单的工具。如果你已经在使用 Unsloth 的 GRPO 并需要训练能够处理复杂多回合交互的代理，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 训练的代理模型通常能够在代理工作流中超过基于提示的模型的表现。</p></figcaption></figure></div>

### ART + Unsloth

ART 建立在 Unsloth 的内存和计算高效的 GRPO 实现之上。此外，它还增加了以下功能：

#### 1. 多回合代理训练

ART 引入了“轨迹（trajectory）”的概念，该轨迹在代理执行过程中逐步构建。这些轨迹随后可以被评分并用于 GRPO。轨迹可以很复杂，甚至包含非线性的历史、子代理调用等。它们也支持工具调用和响应。

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

如果你已经有一个使用提示模型工作的代理，ART 会尽量减少你为将现有代理循环封装并用于训练而需要做的更改数量。

在架构上，ART 被分为一个驻留在你代码库中并通过 API 与实际进行训练的“后端”通信的“前端”客户端（如果你愿意使用 ART 的 `LocalBackend`）。这带来一些关键好处：

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

#### 3. RULER：零样本代理奖励

ART 还提供了一个内置的通用奖励函数，称为 [RULER](https://art.openpipe.ai/fundamentals/ruler) （相对通用的 LLM 触发奖励，Relative Universal LLM-Elicited Rewards），它可以消除手工编写奖励函数的需求。令人惊讶的是，使用 RULER 自动奖励函数进行强化学习训练的代理往往能匹配或超过使用手工奖励函数训练的代理的性能。这使得入门强化学习更加容易。

<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. **多步代理能力**：当你的用例涉及需要采取多次动作、使用工具或进行长时间对话的代理时
2. **无需奖励工程的快速原型开发**：RULER 的自动奖励评分可以将你项目的开发时间缩短 2-3 倍
3. **与现有系统的集成**：当你需要以最少的改动向现有代理代码库添加强化学习功能时

### 代码示例：ART 实战

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

# 使用 Unsloth 支持的基础模型初始化模型
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": "..."}
        ]
    )
    # 在此处添加你的代理逻辑...    
    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 的电子邮件检索代理
* 游戏代理（2048、井字棋、代号）
* 复杂推理任务（时间线索）


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

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

The question should be specific, self-contained, and written in natural language.
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.
