【AgentScope Java新手村系列】(9)SpringBoot集成

简介: SpringBoot集成 — 工厂方法将 HarnessAgent 注册为单例 Bean,WebFlux 流式输出 streamEvents 到 SSE 端点。

第九章 Spring Boot 集成:工厂方法 + WebFlux 流式端点,手动配置 HarnessAgent 为单例 Bean

"1.x 时代有 agentscope-spring-boot-starter,2 行配置就能把 agent 注入到 Spring 容器里。2.0.0-RC2 没有官方 starter——这不是退步,而是模型本身的生命周期与 Spring Bean 生命周期(懒加载、scope、AOP)不匹配。2.0 推荐 『手动配置 + 工厂方法 + WebFlux』 三步集成。"

本章你将学到:如何把 HarnessAgent 注册成单例 Bean、如何在 Controller / Service 里注入它、如何用 WebFlux 流式输出 streamEvents()

9.1 为什么 2.0 没有官方 starter?

1.x 的 agentscope-spring-boot-starterReActAgent 注册成 singleton Bean。2.0 不再提供这个 starter,原因是:

  1. HarnessAgent 不便宜 —— 每次 .build() 会创建 model client、tool registry、workspace 句柄。Spring 容器默认 eager-instantiation 可能在没人用 agent 时就建立这些连接。
  2. 多用户隔离 —— 1.x 时代一个 Bean 服务所有用户;2.0 用 RuntimeContext 区分,HarnessAgent 内部需要 Session 后端支持,并发模型与 Spring MVC 的"每请求一线程"模型不匹配。
  3. 响应式 —— 2.0 的 streamEvents() 返回 Flux<AgentEvent>,天然适合 WebFlux。Starter 把所有响应式 API 包装成同步形式,反而抹掉了这个能力。

所以 2.0 推荐:

  • 生产用 WebFlux(响应式)
  • 小工具 / 批处理用 @Configuration + 工厂方法(手动)

9.2 添加依赖

pom.xml(仅核心 + WebFlux):

<dependencies>
    <dependency>
        <groupId>io.agentscope</groupId>
        <artifactId>agentscope-harness</artifactId>
        <version>2.0.0-RC2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

9.3 把 Model 注册成 Bean

模型对象是配置驱动的——交给 application.yml

agentscope:
  model:
    provider: dashscope
    api-key: ${
   DASHSCOPE_API_KEY}
    name: qwen-plus
  workspace: ./workspace

对应的 properties 类:

package demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "agentscope")
public class AgentScopeProperties {
   

    private Model model = new Model();
    private String workspace = "./workspace";

    public static class Model {
   
        private String provider = "dashscope";
        private String apiKey;
        private String name = "qwen-plus";
        // getter / setter ...
    }

    public Model getModel() {
    return model; }
    public String getWorkspace() {
    return workspace; }
    public void setModel(Model m) {
    this.model = m; }
    public void setWorkspace(String w) {
    this.workspace = w; }
}

Model 工厂:

package demo.config;

import io.agentscope.core.Model;
import io.agentscope.core.model.DashScopeChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ModelConfig {
   

    @Bean
    public Model chatModel(AgentScopeProperties props) {
   
        AgentScopeProperties.Model m = props.getModel();
        if (!"dashscope".equals(m.getProvider())) {
   
            throw new IllegalArgumentException("unsupported provider: " + m.getProvider());
        }
        return DashScopeChatModel.builder()
                .apiKey(m.getApiKey())
                .modelName(m.getName())
                .build();
    }
}

9.4 把 HarnessAgent 做成"工厂 Bean"

我们希望"按用途"区分 agent——比如天气 agent、翻译 agent、客服 agent。推荐用 @Bean 工厂方法 而不是把 HarnessAgent 自身注册成 Bean(避免 eager build):

package demo.config;

import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.UserMessage;
import io.agentscope.harness.HarnessAgent;
import org.springframework.stereotype.Component;

import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AgentFactory {
   

    private final Model model;
    private final Path workspace;
    private final ConcurrentHashMap<String, HarnessAgent> cache = new ConcurrentHashMap<>();

    public AgentFactory(Model model, AgentScopeProperties props) {
   
        this.model = model;
        this.workspace = Path.of(props.getWorkspace());
    }

    public HarnessAgent weatherAgent() {
   
        return cache.computeIfAbsent("weather", id ->
                HarnessAgent.builder()
                        .name("weather_bot")
                        .sysPrompt("你是一个中文天气助手,每次回答不超过 50 字。")
                        .model(model)
                        .workspace(workspace)
                        .build());
    }

    public HarnessAgent translatorAgent() {
   
        return cache.computeIfAbsent("translator", id ->
                HarnessAgent.builder()
                        .name("translator")
                        .sysPrompt("你是一个中英互译助手。")
                        .model(model)
                        .workspace(workspace)
                        .build());
    }
}

关键:业务方调 factory.weatherAgent() 才创建 agent;ConcurrentHashMap 保证单例;按用途区分,内存可控。

9.5 Controller:用 WebFlux 暴露流式端点

package demo.web;

import demo.config.AgentFactory;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.UserMessage;
import io.agentscope.core.event.AgentEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/agent")
public class AgentController {
   

    private final AgentFactory factory;

    public AgentController(AgentFactory factory) {
   
        this.factory = factory;
    }

    /**
     * 流式 SSE 端点
     */
    @GetMapping(value = "/weather/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<AgentEvent> stream(
            @RequestParam String sessionId,
            @RequestParam String userId,
            @RequestParam String text) {
   

        return Mono.fromFuture(
                        factory.weatherAgent()
                                .streamEvents(
                                        List.of(new UserMessage("user", text)),
                                        RuntimeContext.builder()
                                                .sessionId(sessionId)
                                                .userId(userId)
                                                .traceId(UUID.randomUUID().toString())
                                                .build())
                                .toFuture())
                .flatMapMany(flux -> flux);
    }

    /**
     * 一次性同步端点
     */
    @PostMapping("/weather/once")
    public Mono<Map<String, String>> once(
            @RequestParam String sessionId,
            @RequestParam String userId,
            @RequestBody Map<String, String> body) {
   

        return Mono.fromFuture(
                        factory.weatherAgent()
                                .call(
                                        List.of(new UserMessage("user", body.get("text"))),
                                        RuntimeContext.builder()
                                                .sessionId(sessionId)
                                                .userId(userId)
                                                .build())
                                .toFuture())
                .map(msg -> Map.of("reply", msg.getTextContent()));
    }
}

前端用 EventSource 订阅:

const es = new EventSource(
  `/api/agent/weather/stream?sessionId=s-1&userId=u-1&text=${
     encodeURIComponent('杭州今天多少度')}`
);
es.onmessage = (e) => console.log(e.data);

9.6 与 Spring Session 协作

如果前端用 spring-session-data-redis,把 sessionId 与 Spring Session 的 Session.Id 绑定,让 2.0 的 RedisSession 与 Spring Session 共享 Redis 实例:

RuntimeContext.builder()
        .sessionId(httpSession.getId())   // 复用 Spring Session ID
        .userId(currentUser.getId())
        .build();

这样 Spring Session 里只放 HTTP 层的 attribute,agent state 由 RedisSession 单独管理——互不污染。

9.7 完整工程结构

src/main/java/demo/
├── DemoApplication.java
├── config/
│   ├── AgentScopeProperties.java
│   ├── ModelConfig.java
│   └── AgentFactory.java
└── web/
    └── AgentController.java
src/main/resources/
└── application.yml

DemoApplication.java

package demo;

import demo.config.AgentScopeProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(AgentScopeProperties.class)
public class DemoApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(DemoApplication.class, args);
    }
}

9.8 本章小结

  • 2.0 没有官方 starter——HarnessAgent 不适合直接做 Spring Bean,由 AgentFactory 工厂按需创建。
  • Model 走 @ConfigurationProperties + @Bean 工厂。
  • Controller 用 WebFlux:streamEvents() → SSE、call() → 一次性。
  • sessionId 可以与 Spring Session ID 复用,agent state 单独走 RedisSession
目录
相关文章
|
5天前
|
缓存 测试技术 API
Qwen 3.7 Plus 与 Max 实测:性价比与多模态能力差异解析(2026)
2026 年 6 月 1 日,阿里悄无声息地发布了 Qwen 3.7 Plus,距 Qwen 3.7 Max 上线刚好 11 天。同样的 1M 上下文,同样的 35 小时自治上限。但价格才是头条:Plus 是 0.40/M输入,Max是 2.50/M——便宜约 6 倍——并且还能看图、看视频。Vision Arena 上 Plus 已经排到 #16。所以这周真正值得讨论的问题不是”要不要为视觉能力买单”,而是”Max 凭什么用 6 倍价格换来 2 个百分点的 benchmark 领先”。
|
6天前
|
人工智能 自然语言处理 文字识别
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
Qwen3.7-Max是阿里云百炼面向智能体时代推出的新一代旗舰模型,对标GPT-5.5、Claude Opus 4.7等闭源旗舰。该模型支持百万级token上下文窗口,具备顶级推理能力、多模态搜索与视觉理解增强、流式输出低延迟响应等核心优势,覆盖编程、办公、长周期自主执行等复杂场景。同时支持OpenAI接口兼容,便于系统快速迁移。用户可通过Token Plan团队或节省计划等订阅方式灵活调用,适合企业级高要求场景使用。
8672 37
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
|
6天前
|
JavaScript 定位技术 API
CodeGraph 爆火:编程 Agent 需要的不是更多上下文,而是一张提前画好的代码地图
CodeGraph 是一款爆火的本地代码智能工具,通过 tree-sitter 解析 AST 构建结构化知识图谱(存于 SQLite),为编程 Agent 提前生成“代码地图”。它显著降低 Agent 在中大型项目中的探索成本——实测工具调用减少71%、Token 降57%、速度提升46%,支持19+语言及主流框架路由识别,完全离线、无需 API Key。
673 5
CodeGraph 爆火:编程 Agent 需要的不是更多上下文,而是一张提前画好的代码地图
|
6天前
|
人工智能 运维 JavaScript
阿里云Qoder CN(原通义灵码)全解析 产品形态、版本划分与技术适配说明
在AI辅助开发与智能办公工具持续普及的当下,阿里云旗下原通义灵码正式更名为Qoder CN,同时延伸出QoderWork CN、Qoder CN CLI、Qoder CN Mobile等多款配套产品,形成覆盖代码开发、日常办公、终端交互、移动端使用的完整工具矩阵。Qoder CN核心定位为AI智能编码助手,深度适配主流代码编辑器、集成开发环境以及终端场景;QoderWork CN则偏向桌面端综合办公辅助,二者面向不同使用场景,划分了多个版本档位,搭配差异化资源配额、功能权限与计费规则,同时兼容多款主流大模型。
671 5
|
6天前
|
数据采集 人工智能 前端开发
让 Coding Agent 从黑盒到透明:阿里云 Agent 观测审计数据采集实践
AI Agent 规模化落地带来执行黑盒、行为难追溯、成本难度量三大难题。阿里云基于 OTel 标准,面向 Coding Agent、个人通用助理和框架型 Agent,推出 LoongSuite Pilot、插件及探针等无侵入采集方案,让 Agent 实现可看见、可分析、可审计、可治理。
734 148
|
6天前
|
存储 安全 Java
AgentScope Java 2.0:打造分布式、企业级智能体底座
AgentScope 2.0 面向分布式部署、稳定运行、权限安全等企业级需求全面升级,打造支持多租户隔离与长期稳定运行的企业级智能体底座。
|
6天前
|
人工智能 运维 自然语言处理
阿里云百炼Qwen3.7-Max模型详解:综合能力、核心优势与订阅计划参考指南
2026年,大模型技术持续向通用化、高性能、场景化方向迭代,阿里云百炼作为一站式大模型服务平台,持续推出迭代升级的模型产品,Qwen3.7-Max便是当前主力旗舰级大模型之一。该模型依托深度优化的底层架构与大规模训练数据,在文本理解、逻辑推理、多模态交互、代码生成、长文本处理等多个维度实现能力升级,同时搭配灵活的订阅计划体系,能够适配个人开发者、中小企业、大型企业、政企机构等不同类型用户的使用需求。
575 2
|
6天前
|
人工智能 缓存 自然语言处理
阿里Qwen3.7-Max评测:Agent能力显著提升,耗时与调用成本大幅下降
阿里云百炼推出面向智能体的旗舰大模型Qwen3.7-Max,具备长周期自主执行能力,显著提升编程、办公自动化等复杂任务处理水平;支持MCP集成与多框架兼容,并以限时5折+100万Tokens免费试用大幅降低使用门槛,助力企业高效落地AI应用。在阿里云百炼平台快速体验:https://t.aliyun.com/U/fPVHqY
1964 10
|
6天前
|
JSON 缓存 安全
通过 CC Switch 本地路由让 Codex CLI 接入 DeepSeek 等第三方模型
CC Switch 通过本地路由(`127.0.0.1:15721`)实现协议转换:将 Codex 的 Responses API 请求自动映射为 DeepSeek 等厂商的 Chat Completions 接口,兼容流式响应与工具调用,无需修改 Codex 源码,安全隔离 API Key。(239字)
1691 3
通过 CC Switch 本地路由让 Codex CLI 接入 DeepSeek 等第三方模型
|
6天前
|
人工智能 运维 API
2026年阿里云百炼通义千问Qwen3.7-plus深度介绍 功能特性、使用优势及618大促订阅方案指南
大模型技术的普及,让AI能力逐步融入个人办公、内容创作、代码编写、企业运营、教育培训等各类场景。不同定位的模型对应不同使用需求,旗舰级模型性能强劲但使用成本偏高,轻量化模型价格低廉却难以胜任复杂任务,而介于两者之间的中端主力模型,凭借均衡的能力、亲民的定价、广泛的场景适配性,成为绝大多数个人用户、小型团队、中小企业的首选。
780 1

热门文章

最新文章