
AgentScope Agentic RL:基于 Trinity-RFT 的在线强化学习微调导读:Agent 可以通过强化学习持续进化。AgentScope 集成了 Trinity-RFT 框架,支持在线训练、对话数据自动采集和模型权重热更新。本文详解 RL 集成架构、典型场景案例(数学 Agent、Email Search、Werewolf Game)和生产注意事项。一、RL 集成架构1.1 核心设计理念AgentScope 的 Agentic RL 机制让 Agent 能够:在线训练:在 Runtime 内嵌训练循环数据采集:自动收集对话和工具调用数据热更新:模型权重无缝更新,无需重启持续优化:基于用户反馈和环境奖励持续改进┌─────────────────────────────────────────────────────────┐ │ AgentScope Agentic RL 架构 │ ├─────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────┐│ │ │ Agent Runtime (推理) ││ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐│ │ │ │ Agent │ │ Tools │ │ Memory ││ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘│ │ └─────────┼─────────────────┼─────────────────┼───────┘│ │ │ │ │ │ │ │ 1. 采集数据 │ │ │ │ ▼ │ │ │ │ ┌─────────────────────────────────────────────────────┐│ │ │ Data Collector (数据采集) ││ │ │ - 对话历史 ││ │ │ - 工具调用 ││ │ │ - 推理过程 ││ │ │ - 用户反馈 ││ │ └─────────────────────────────────────────────────────┘│ │ │ │ │ │ │ 2. 构建训练样本 │ │ │ ▼ │ │ │ ┌─────────────────────────────────────────────────────┐│ │ │ Trinity-RFT Framework (训练框架) ││ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐│ │ │ │ PPO │ │ DPO │ │ RFT ││ │ │ │ (强化学习) │ │ (偏好优化) │ │ (监督微调) ││ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘│ │ └─────────┼─────────────────┼─────────────────┼───────┘│ │ │ │ │ │ │ │ 3. 训练模型 │ │ │ ▼ │ │ │ ┌─────────────────────────────────────────────────────┐│ │ │ Model Weights (模型权重) ││ │ │ - 在线更新 ││ │ │ - 版本管理 ││ │ │ - A/B 测试 ││ │ └─────────────────────────────────────────────────────┘│ │ │ │ │ │ │ 4. 热更新 │ │ │ └─────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────┘1.2 训练循环设计fromagentscope.rlimportOnlineTrainer,TrinityRFT# 创建在线训练器trainerOnlineTrainer(agentmy_agent,frameworkTrinityRFT(algorithmppo,# ppo/dpo/rftmodel_config{base_model:Qwen/Qwen2.5-0.6B-Instruct,lora_rank:8},training_config{learning_rate:1e-5,batch_size:16,gradient_accumulation_steps:4}))# 训练循环whileTrue:# 1. 运行 Agent,收集数据trajectoryagent.run_and_collect(user_input)# 2. 添加到训练缓冲区trainer.add_trajectory(trajectory)# 3. 训练iflen(trainer.buffer)trainer.config.min_samples:trainer.train_step()# 4. 热更新模型iftrainer.should_update():trainer.update_agent_model()二、在线训练模式2.1 Runtime 内嵌训练fromagentscope.runtimeimportRLRuntime# 创建支持 RL 的 RuntimeruntimeRLRuntime(agentmy_agent,trainer_config{algorithm:ppo,train_interval:10,# 每 10 次推理后训练update_interval:100,# 每 100 次训练后更新模型checkpoint_dir:./checkpoints})# 启动服务runtime.start()# 自动:# - 采集对话数据# - 执行训练# - 更新模型2.2 对话数据自动采集fromagentscope.rlimportDataCollector# 数据采集器collectorDataCollector(collect_fields{messages:True,# 对话消息thoughts:True,# 推理过程tool_calls:True,# 工具调用rewards:True,# 奖励信号user_feedback:True# 用户反馈})# 采集单次对话trajectorycollector.collect(agentmy_agent,user_input用户问题,user_feedback{rating:4,comment:回答准确})# 数据格式{conversation_id:conv_001,messages:[{role:user,content:...},{role:assistant,content:...}],thoughts:[{step:1,content:需要调用工具...}],tool_calls:[{tool:search,args:{...},result:...}],rewards:{task_completion:0.8,efficiency:0.6,user_satisfaction:0.8},total_reward:2.2}2.3 模型权重热更新fromagentscope.rlimportHotUpdater# 热更新器updaterHotUpdater(agentmy_agent,update_config{strategy:rolling,# rolling/canarycanary_ratio:0.1,# 金丝雀比例 10%check_after_updates:5# 更新 5 次后检查})# 检查新模型ifupdater.has_new_model():# 金丝雀测试canary_resultupdater.test_canary(test_casessample_questions)ifcanary_result[success_rate]0.9:# 滚动更新updater.rollout_update()else:# 回滚updater.rollback()三、典型场景案例3.1 Math Agent:多步推理准确率提升场景:数学多步推理问题数据:5000 道数学题基线模型:Qwen3-0.6B训练配置:fromagentscope.rlimportMathAgentTrainer trainerMathAgentTrainer(algorithmppo,model_config{base_model:Qwen/Qwen3-0.6B-Instruct,lora_rank:16},reward_function{correctness:3.0,# 正确答案奖励steps_penalty:-0.1,# 步数过多惩罚format_bonus:0.5# 格式正确奖励},training_config{learning_rate:5e-6,batch_size:32,epochs:10})训练效果:指标训练前训练后提升准确率75%85%10%平均步数8.56.2-27%格式正确率60%92%32%关键改进:# 训练后的 Agent 能:# 1. 更快找到解题思路# 2. 减少无效推理步骤# 3. 规范输出格式responsemath_agent.run(求解: (x1)² 16)# 输出:# 思考:这是一个二次方程求解问题# 步骤1:展开 (x1)² x² 2x 1 16# 步骤2:整理得 x² 2x - 15 0# 步骤3:因式分解 (x5)(x-3) 0# 步骤4:解得 x -5 或 x 3# 答案: x -5, 33.2 Email Search:工具调用准确率优化场景:邮件搜索工具调用问题:Agent 经常调用错误的工具或参数训练策略:fromagentscope.rlimportToolUseTrainer trainerToolUseTrainer(algorithmdpo,# 偏好优化model_config{base_model:Qwen/Qwen3-0.6B-Instruct},reward_function{correct_tool:1.0,# 工具选择正确correct_args:0.5,# 参数正确tool_success:1.0,# 工具执行成功invalid_tool:-2.0# 无效工具调用})训练流程:# 1. 收集工具调用样本foremailintest_emails:trajectoryagent.run_and_collect(f搜索:{email[subject]})trainer.add_trajectory(trajectory)# 2. 训练trainer.train()# 3. 评估evaluatorToolUseEvaluator()resultsevaluator.evaluate(agentagent,test_casestest_emails)print(f工具调用准确率:{results[tool_accuracy]}%)print(f参数正确率:{results[arg_accuracy]}%)训练效果:指标初始训练 5 轮训练 10 轮工具准确率60%78%85%参数正确率45%65%80%平均召回3.24.85.53.3 Werewolf Game:多 Agent 博弈策略训练场景:狼人杀游戏,6 名 Agent(2 狼人,4 村民)训练目标:提高狼人胜率架构设计:fromagentscope.rlimportMultiAgentGame# 创建游戏环境gameMultiAgentGame(roles{werewolf:2,villager:4},agents{werewolf_1:werewolf_agent_1,werewolf_2:werewolf_agent_2,villager_1:villager_agent_1,villager_2:villager_agent_2,villager_3:villager_agent_3,villager_4:villager_agent_4})# 训练狼人 Agentwerewolf_trainerGameTrainer(agents[werewolf_agent_1,werewolf_agent_2],reward_function{team_win:10.0,# 团队胜利individual_survive:5.0,# 个人存活successfully_blame:2.0,# 成功嫁祸exposed_penalty:-5.0# 暴露惩罚})训练过程:# 1. 自我对弈forepisodeinrange(1000):# 运行游戏game_resultgame.run_episode()# 收集数据foragentingame_result[agents]:trajectoryagent.get_trajectory()werewolf_trainer.add_trajectory(trajectory)# 训练ifepisode%100:werewolf_trainer.train()# 评估ifepisode%1000:win_rateevaluate_win_rate(werewolf_agents[werewolf_agent_1,werewolf_agent_2],episodes100)print(fEpisode{episode}, Win Rate:{win_rate}%)训练效果:阶段狼人胜率关键能力初始50%随机策略100 局55%学会隐藏身份500 局70%学会嫁祸村民1000 局80%掌握团队协作四、反馈信号设计4.1 环境奖励fromagentscope.rlimportRewardFunctionclassTaskReward(RewardFunction):defcompute(self,trajectory):计算任务完成奖励# 任务完成度completionself.check_completion(trajectory)# 效率efficiency1.0/(len(trajectory[tool_calls])1)# 准确性accuracyself.check_accuracy(trajectory)# 综合奖励reward(completion[score]*2.0efficiency*1.0accuracy*1.5)returnreward4.2 LLM-as-a-Judge 评估fromagentscope.rlimportLLMJudge# 创建评估器judgeLLMJudge(modelgpt-4,criteria{relevance:回答是否相关,accuracy:内容是否准确,completeness:回答是否完整})# 评估evaluationjudge.evaluate(user_input如何使用 Python 读取 CSV?,agent_response使用 pandas.read_csv()...)print(f相关性:{evaluation[relevance]}/5)print(f准确性:{evaluation[accuracy]}/5)print(f完整性:{evaluation[completeness]}/5)print(f总评:{evaluation[total]}/5)# 作为奖励rewardevaluation[total]/5.04.3 人类偏好对齐fromagentscope.rlimportHumanPreferenceCollector# 收集人类偏好collectorHumanPreferenceCollector()# 展示两个回答response_aagent_v1.run(question)response_bagent_v2.run(question)# 收集偏好preferencecollector.collect(questionquestion,response_aresponse_a,response_bresponse_b)# 使用偏好数据训练 DPOtrainerDPOTrainer()trainer.add_preference(preference)trainer.train()五、生产注意事项5.1 训练与推理资源隔离# 部署架构services:# 推理服务(在线)agent-inference:resources:cpu:2memory:4Ggpu:1# 训练服务(离线)agent-training:resources:cpu:8memory:16Ggpu:2# 数据采集data-collector:resources:cpu:1memory:2G5.2 模型版本回滚fromagentscope.rlimportModelManager# 模型管理器managerModelManager(checkpoint_dir./checkpoints)# 版本控制manager.create_version(v1.0)# 基线模型manager.create_version(v1.1)# 训练后模型# 回滚到 v1.0manager.rollback(v1.0)# A/B 测试ab_testmanager.create_ab_test(version_av1.0,version_bv1.1,traffic_ratio{a:0.7,b:0.3})5.3 A/B 测试框架fromagentscope.rlimportABTestFramework# A/B 测试abABTestFramework(model_av1.0,model_bv1.1,traffic{a:0.8,b:0.2},metrics[accuracy,latency,user_satisfaction])# 运行测试resultsab.run(test_duration_days7)# 分析结果ifresults[b][accuracy]results[a][accuracy]0.05:# v1.1 显著更好,切换流量ab.switch_traffic(b,1.0)else:# 回滚到 v1.0ab.switch_traffic(a,1.0)六、总结AgentScope 通过集成 Trinity-RFT 框架,实现了 Agent 的持续进化:在线训练:Runtime 内嵌训练循环,无缝集成数据采集:自动收集对话、工具调用、用户反馈热更新:模型权重无缝更新,支持 A/B 测试典型场景:Math Agent(75%→85%)、Email Search(60%→优化)、Werewolf(50%→80%)生产就绪:资源隔离、版本管理、回滚机制Agentic RL 让 Agent 从固定模型变为持续进化,适应不断变化的场景和需求。延伸阅读:Trinity-RFT 文档PPO 算法详解DPO 偏好优化