微信扫码
添加专属顾问
我要投稿
AgentScope Java 在线训练插件让智能体持续进化,打破传统训练-部署分离的瓶颈,实现 Java 生态下的高效优化。 核心内容: 1. 传统 Agent 优化面临的训练-部署环境分离与 Java 生态支持缺失两大挑战 2. AgentScope Java + Trinity-RFT 在线训练方案的核心优势与特性 3. 如何实现生产环境中的实时数据闭环与持续优化
背景与挑战
Cloud Native
随着大模型能力的成熟,智能体(Agent)正从实验性原型快速走向生产级应用。在客服自动化、运维诊断、数据查询、业务流程编排等场景中,Agent 通过调用工具、规划任务、与用户多轮交互,展现出显著的生产力价值。为适配特定业务需求,开发者普遍基于开源大语言模型(LLM),采用监督微调(SFT)、强化微调(RFT)等技术对 Agent 进行定制化优化,在推理成本、响应延迟与任务成功率之间寻求最佳平衡。
然而,模型一旦部署上线,其能力便趋于静态。若无法持续从真实用户交互中学习,Agent 很难适应业务变化、工具演进或用户行为漂移,长期效果将逐渐退化。
当前 Agent 优化面临两大关键瓶颈:
传统的微调流程高度依赖离线数据集:开发者需先积累大量历史交互日志,再经过人工清洗、标注,并构建静态训练集;同时,为在隔离环境中进行训练,还需额外开发模拟工具链(如 Mock API、虚拟数据库等)来复现线上行为。这一过程不仅周期长、反馈滞后,更关键的是,仿真环境往往难以准确还原生产系统中真实的工具响应、状态流转与边界条件——例如内部 API 的延迟特性、数据库的并发行为或业务系统的上下文依赖。这种“训练-部署”之间的环境差异,容易导致模型在离线评估中表现良好,却在真实场景中出现行为偏差甚至失效。
无论哪种方式,都迫使 Java 开发者额外承担算法理解与分布式训练工程的复杂性,增加开发负担,降低迭代效率,阻碍了训练能力在 Java 生态中的落地与普及。
要实现“Agent 越用越聪明”的自进化目标,必须打通从生产环境到训练系统的全链路数据闭环。理想方案应具备以下特征:
基于此,我们提出面向 Java Agent 的端到端在线训练方案,以 AgentScope Java + Trinity-RFT 为核心,构建一条高效、安全、可落地的持续优化路径。
AgentScope Java × Trinity-RFT 在线训练
Cloud Native
在线训练(Online Training)是一种在生产环境的实时系统中,利用真实用户交互数据持续优化智能体(Agent)行为的训练范式。与传统离线训练——即先收集历史日志、构建静态数据集,再于隔离环境中进行模型微调——不同,在线训练强调与真实工具链(如 API、数据库、业务系统)和用户行为的深度耦合,实现“边运行、边学习、边优化”的闭环。
其核心流程为:系统从线上真实请求中自动筛选高质量样本,由 Agent 使用待训练模型处理这些请求,并直接调用生产环境中的真实工具完成任务;整个交互过程被完整记录,并结合预设规则或用户反馈生成对应的奖励信号;当积累足够数量的带奖励轨迹后,系统自动触发训练,利用这些真实、高保真的数据对模型进行增量优化,从而真正实现“使用即学习,越用越聪明”的自进化能力。
本方案通过在 AgentScope Java 中原生集成在线训练能力,为 Java Agent 开发者提供以下关键价值:
本方案采用解耦式架构,将在线训练流程划分为三个独立组件,支持灵活部署与弹性扩展:
三者通过轻量级协议协同工作:
Agent Runner、Explorer 和 Trainer 可以部署在不同的服务器上。其中 Agent Runner 由用户自行管理,只需要保证网络与 Explorer 互通,无需 GPU 资源。而 Explorer 和 Trainer 需要通过 Trinity-RFT 部署在 GPU 服务器上,且需要保证两者可以访问同一个共享文件系统,以便 Trainer 保存的模型检查点可以被 Explorer 读取。
为保障生产环境稳定性,在线训练当前默认仅支持只读工具调用。若涉及写操作(如创建订单、发送消息),需由开发者通过幂等设计、沙箱机制或人工审核等方式确保重放安全。
此外,当前训练范式原生支持单轮用户-Agnet 交互。对于多轮对话或复杂任务流,需开发者显式建模状态转移或采样策略。
快速开始
Cloud Native
<dependency> <groupId>io.agentscope</groupId> <artifactId>agentscope-extensions-training</artifactId> <version>${agentscope.version}</version></dependency>请求筛选逻辑用于筛选出需要用于训练的请求。
SamplingRateStrategy - 随机采样。所有线上请求按照百分比进行筛选。
TrainingSelectionStrategy strategy = SamplingRateStrategy.of(0.1); // 10%
ExplicitMarkingStrategy - 用户显式标记重要请求。
TrainingSelectionStrategy strategy = ExplicitMarkingStrategy.create();// 在你的应用代码中显示标记请求用于训练TrainingContext.mark("high-quality", "user-feedback");agent.call(msg).block(); // 这个请求会被用于训练您可以参考 SamplingRateStrategy(基于固定采样率的随机筛选)或 ExplicitMarkingStrategy(基于显式标记的主动筛选)的实现方式,自行实现 TrainingSelectionStrategy 接口,并在 shouldSelect 方法中嵌入符合您业务场景的请求筛选逻辑。该方法在每次 Agent 处理用户请求前被调用,您可以基于以下维度动态决定是否将本次交互纳入训练数据集:
通过自定义筛选策略,您可以在控制训练数据规模的同时,显著提升样本的相关性与训练效率,避免将大量低价值或噪声数据引入训练流程。尤其在在线训练资源有限或强调数据隐私的场景下,精细化的筛选机制是保障训练效果与系统稳定性的关键环节。
您可以实现 RewardCalculator 接口,并在 calculate 方法中根据您的业务需求自定义您的奖励计算逻辑。该方法的参数是 Agent,你可以从中获取 Agent 相关的所有信息,例如 Memory、Context 等。通过利用用户输入、Agent 的响应、工具调用序列、工具返回结果等信息,基于实际业务指标(如任务完成度、响应准确性等)动态评估 Agent 行为的质量。
一般而言,奖励值归一化到 0 到 1 之间的浮点数:
典型实现方式包括:
在安装之前,请确保您的系统满足以下要求,推荐使用源码安装:
git clone https://github.com/agentscope-ai/Trinity-RFTcd Trinity-RFTpip install -e ".[dev]"pip install flash-attn==2.8.1
mode: serve # set to 'serve' for online inference serviceproject: test # set your project namename: test # set your experiment namecheckpoint_root_dir: CHECKPOINT_ROOT_DIR # set the root directory for checkpoints, must be an absolute path, and should be on a shared filesystemmodel: model_path: /path/to/your/model # set the path to your base model max_model_len: 8192 max_response_tokens: 2048 temperature: 0.7algorithm: algorithm_type: "ppo" # current version only supports ppo for online training (group is not supported yet)cluster: node_num: 1 gpu_per_node: 4 # suppose you have 4 GPUs on the nodeexplorer: rollout_model: engine_num: 2 tensor_parallel_size: 2 # make sure tensor_parallel_size * engine_num <= node_num * gpu_per_node enable_openai_api: true enable_history: true enable_auto_tool_choice: true tool_call_parser: hermes # reasoning_parser: DeepSeek_r1 # if using Qwen3 series models, uncomment this line dtype: bfloat16 seed: 42 service_status_check_interval: 10 # check new checkpoints and update data every 10 seconds proxy_port: 8010 # set the port for Explorer service# trainer:# save_interval: 1 # save checkpoint every step# ulysses_sequence_parallel_size: 2 # set according to your model and hardwarebuffer: train_batch_size: 16 trainer_input: experience_buffer: name: exp_buffer # table name in the database storage_type: sql # path: your_db_url # if not provided, use a sqlite database in checkpoint_root_dir/project/name/buffersynchronizer: sync_method: checkpoint sync_interval: 1monitor: monitor_type: tensorboard
mode: train # set to 'train' for training serviceproject: test # set your project name, must be the same as in Explorername: test # set your experiment name, must be the same as in Explorercheckpoint_root_dir: CHECKPOINT_ROOT_DIR # set the root directory for checkpoints, must be the same as in Explorermodel: model_path: /path/to/your/model # set the path to your base model, must be the same as in Explorer max_model_len: 8192 # must be the same as in Explorer max_response_tokens: 2048 # must be the same as in Explorer temperature: 0.7 # must be the same as in Exploreralgorithm: algorithm_type: "ppo" # current version only supports ppo for online training (group is not supported yet)cluster: node_num: 1 gpu_per_node: 4 # suppose you have 4 GPUs on the nodebuffer: train_batch_size: 32 # trainer consumes samples per step trainer_input: experience_buffer: name: exp_buffer # table name in the database, must be the same as in Explorer storage_type: sql # path: your_db_url # if not provided, use a sqlite database in checkpoint_root_dir/project/name/buffertrainer: save_interval: 16 # save checkpoint every step ulysses_sequence_parallel_size: 1 # set according to your model and hardware save_hf_checkpoint: always max_checkpoints_to_keep: 5 trainer_config: trainer: balance_batch: false max_actor_ckpt_to_keep: 5 max_critic_ckpt_to_keep: 5synchronizer: sync_method: checkpoint sync_interval: 1 monitor: monitor_type: tensorboard
启动 Explorer 和 Trainer 服务前需要启动 ray 集群。
ray start --head
分别启动 Explorer 与 Trainner 服务。
trinity run --config explorer.yamltrinity run --config trainer.yaml
TrainingRunner trainingRunner = TrainingRunner.builder() .trinityEndpoint(TRINITY_ENDPOINT) //Trinity Explorer服务地址 .modelName(TRAINING_MODEL_NAME)//对应Trinity配置中model_path .selectionStrategy(new CustomStrategy()) .rewardCalculator(new CustomReward()) .commitIntervalSeconds(60*5)//训练数据提交时间间隔 .repeatTime(1)//每一个训练请求被训练次数 .build();trainingRunner.start();
import io.agentscope.core.training.runner.TrainingRunner;import io.agentscope.core.training.strategy.SamplingRateStrategy;// 1. 启动训练 runner(无需 Task ID/Run ID!)TrainingRunner runner = TrainingRunner.builder() .trinityEndpoint("http://trinity-backend:8010") .modelName("/path/to/model") .selectionStrategy(SamplingRateStrategy.of(0.1)) // 10% 采样 .rewardCalculator(new CustomReward()) // 自定义奖励计算逻辑 .commitIntervalSeconds(300) // 每 5 分钟 commit 一次 .build();runner.start();// 2. 正常使用你的 Agent - 完全无感知训练!ReActAgent agent = ReActAgent.builder() .name("Assistant") .sysPrompt("You are a helpful AI assistant. Be friendly and concise.") .model( DashScopeChatModel.builder() .apiKey(apiKey) .modelName("qwen-plus") .stream(true) .formatter(new DashScopeChatFormatter()) .build()) .memory(new InMemoryMemory()) .toolkit(new Toolkit()) .build();// 用户请求正常处理(使用 GPT-4),自动采样10%请求用于训练Msg response = agent.call(Msg.userMsg("搜索 Python 教程")).block();// 3. 训练完成后停止runner.stop();训练效果
Cloud Native
下面的 Demo 中,通过在线训练的方式,使用 PPO 强化学习算法优化 SQL Agent。
用户向 SQL Agent 发送请求,例如:
DB: department_management
Question: List the creation year, name and budget of each department.
Agent 基于自然语言问题和目标数据库的 schema 生成一条 SELECT 语句,并通过execute_query 工具在真实数据库中执行,以验证其可执行性与结果正确性。
若 SQL 执行成功且返回结果符合语义预期,则直接返回;否则,Agent 将结合执行错误信息与数据库 schema 进行迭代修正。
整个过程最多重试 N 轮(如 3 轮),当 SQL 验证通过或达到最大重试次数时,Agent 终止循环,返回当前最优 SQL。
为确保安全性,execute_query 工具严格限制仅允许执行 SELECT 语句,禁止任何数据修改操作,从而有效防止对数据库造成意外破坏。
在该场景下,提升 Qwen2.5-Coder-1.5B-Instruct 的 SQL 生成准确率。
奖励函数关注两个方面:
1)SQL Agent 生成的 SQL 语句是否语法正确且可成功执行?
通过代码实际执行 SQL 语句。
2)SQL Agent 生成的 SQL 语句能够满足用户的需求?
LLM 评判:将用户的问题,数据库表的定义、生成的 SQL 语句、SQL 语句的执行结果在 SyStemPrompt 拼装后,传递给 LLM(qwen-max),让 LLM 判定 SQL 语句是否符合用户意图。
trainingRunner = TrainingRunner.builder() .trinityEndpoint(TRINITY_ENDPOINT) .modelName(TRAINING_MODEL_NAME) .selectionStrategy(SamplingRateStrategy.of(1.0)) .rewardCalculator( new SqlAgentReward()) .commitIntervalSeconds(60*5) # 每五分钟commit一次 .build();
由于数据集的数据可以视为筛选后的优质数据集,因为采用采样方式筛选请求时采样频率为 1.0,所有请求都将被用于训练。
SQL 难度基于三个维度的得分来判定:
由于 SQL 语句有多种等效写法,需要根据实际的数据库执行结果是否准确判定 SQL 语句的正确性。
二元判定准确性:生成 SQL 与 Ground Truth SQL 在目标数据库上执行结果是否一致。
本 Demo 采用 Spider 数据集中的测试集部分进行评估。测试集中共有 1000 条数据,评估脚本会并行发送测试请求,获取 SQL Agent 的真实返回。
训练前 Agent 性能表现
在 FC 上部署 Qwen/Qwen2.5-Coder-1.5B-Instruct 模型,Agent 使用该模型对外提供服务,1000 条测试数据评估指标结果如下:
## Summary- **Total Samples:** 1000- **Execution Accuracy:** 47.60%## Scores by Difficulty| Difficulty | Count | Exec Accuracy | Percentage ||------------|-------|---------------|------------|| easy | 327 | 0.612 | 61.16% || medium | 445 | 0.449 | 44.94% || hard | 140 | 0.357 | 35.71% || extra | 88 | 0.295 | 29.55% || all | 1000 | 0.476 | 47.60% |---
训练后 Agent 性能表现
将训练后的模型通过 NAS 部署至 FC 上,Agent 使用训练后的模型对外提供服务,1000 条测试数据评估指标结果如下:
## Summary- **Total Samples:** 1000- **Success Count:** 1000- **Error Count:** 0- **Success Rate:** 100.00%- **Execution Accuracy:** 65.70% (based on 1000 successful evaluations)## Scores by Difficulty| Difficulty | Count | Exec Accuracy | Percentage ||------------|-------|---------------|------------|| easy | 327 | 0.844 | 84.40% || medium | 445 | 0.616 | 61.57% || hard | 140 | 0.529 | 52.86% || extra | 88 | 0.375 | 37.50% || all | 1000 | 0.657 | 65.70% |---
经过训练后,SQL Agent 在四种不同难度的 SQL 语句下准确率均有提升,easy 难度下准确率提升 23.24%,medium 难度下准确率提升 16.63%,hard 难度下准确率提升 17.15%,extra 难度下准确率提升 7.95%,整体执行准确率提升 18.1%。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2026-03-21
马斯克再次站台Kimi,扒掉了Cursor 500亿估值的底裤
2026-03-19
MiniMax M2.7 炸场!自己训自己,8 项基准硬刚 GPT-5 和 Opus 4.6
2026-03-17
【淘宝直播数字人互动LLM】告别AI感:基于真人ASR数据的拟人化探索
2026-03-03
罕见!Meta、OpenAI、xAI联合分享了用生产环境提升LLM的最佳实践!
2026-02-13
工具调用准确率从60%飙到95%?我用这个‘解耦微调’把Qwen-7B救活了
2026-02-05
普林斯顿大学RLAnything:AI学会一边学习一边给自己打分
2026-01-30
Oxygen 9N-LLM生成式推荐训练框架
2026-01-29
自然·通讯:如何挖掘复杂系统中的三元交互
2026-01-04
2026-01-18
2026-01-02
2026-01-01
2026-02-04
2026-01-19
2026-01-03
2025-12-30
2026-01-07
2026-01-10
2026-01-02
2025-11-19
2025-09-25
2025-06-20
2025-06-17
2025-05-21
2025-05-17
2025-05-14