Java AI框架:Spring AI 与 AgentScope 实战指南
本指南涵盖Java生态中最主流的两个AI框架:Spring AI用于企业级AI应用开发,AgentScope用于构建多智能体系统。
第一部分:Spring AI
Spring AI是Spring生态中用于构建AI应用的官方框架,为Java开发者提供原生的LLM集成。
快速开始
Maven配置
xml
1<dependency>2 <groupId>org.springframework.ai</groupId>3 <artifactId>spring-ai-openai-spring-boot-starter</artifactId>4 <version>1.0.0-M1</version>5</dependency>基础配置
yaml
1spring:2 ai:3 openai:4 api-key: ${OPENAI_API_KEY}5 chat:6 options:7 model: gpt-48 temperature: 0.7核心功能
1. ChatClient - 对话接口
java
1@RestController2public class ChatController {3 4 private final ChatClient chatClient;5 6 public ChatController(ChatClient.Builder builder) {7 this.chatClient = builder.build();8 }9 10 @GetMapping("/chat")11 public String chat(@RequestParam String message) {12 return chatClient.prompt()13 .user(message)14 .call()15 .content();16 }17}2. Streaming响应
java
1@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)2public Flux<String> stream(@RequestParam String message) {3 return chatClient.prompt()4 .user(message)5 .stream()6 .content();7}3. RAG实现
java
1@Service2public class RAGService {3 4 private final VectorStore vectorStore;5 private final ChatClient chatClient;6 7 public String query(String question) {8 // 检索文档9 List<Document> docs = vectorStore.similaritySearch(10 SearchRequest.query(question).withTopK(5)11 );12 13 // 构建上下文14 String context = docs.stream()15 .map(Document::getContent)16 .collect(Collectors.joining("\n\n"));17 18 // 生成答案19 return chatClient.prompt()20 .user(\"基于上下文: {context}\n问题: {question}\")21 .param("context", context)22 .param("question", question)23 .call()24 .content();25 }26}4. Function Calling
java
1@Configuration2public class FunctionConfig {3 4 @Bean5 @Description("获取天气信息")6 public Function<WeatherRequest, WeatherResponse> weatherFunction() {7 return request -> {8 // 调用天气API9 return new WeatherResponse(request.city(), "晴天", 25);10 };11 }12}1314record WeatherRequest(String city) {}15record WeatherResponse(String city, String condition, int temp) {}实战项目:企业知识库
java
1@Service2public class KnowledgeBaseService {3 4 private final VectorStore vectorStore;5 private final ChatClient chatClient;6 7 @PostConstruct8 public void loadDocuments() {9 // 加载文档10 Resource[] resources = resourceLoader.getResources("classpath:docs/**/*.md");11 12 for (Resource resource : resources) {13 List<Document> docs = new TextReader(resource).get();14 vectorStore.add(docs);15 }16 }17 18 public KnowledgeResponse query(String question) {19 List<Document> docs = vectorStore.similaritySearch(20 SearchRequest.query(question).withTopK(3)21 );22 23 if (docs.isEmpty()) {24 return new KnowledgeResponse("未找到相关信息", List.of());25 }26 27 String context = docs.stream()28 .map(Document::getContent)29 .collect(Collectors.joining("\n\n"));30 31 String answer = chatClient.prompt()32 .user(\"基于知识库回答: {context}\n问题: {question}\")33 .param("context", context)34 .param("question", question)35 .call()36 .content();37 38 return new KnowledgeResponse(answer, extractSources(docs));39 }40}第二部分:AgentScope
AgentScope是阿里达摩院开源的多智能体框架,专注于构建复杂的智能体协作系统。
核心概念
- Agent(智能体):独立的AI实体
- Message(消息):智能体间的通信单元
- Pipeline(流水线):智能体的执行流程
- Service(服务):智能体可调用的工具
快速开始
Maven依赖
xml
1<dependency>2 <groupId>com.alibaba</groupId>3 <artifactId>agentscope-core</artifactId>4 <version>0.5.0</version>5</dependency>基础Agent
java
1public class SimpleAgent extends AgentBase {2 3 private final ChatClient llm;4 5 public SimpleAgent(String name, ChatClient llm) {6 super(name);7 this.llm = llm;8 }9 10 @Override11 public Message reply(Message input) {12 String response = llm.prompt()13 .user(input.getContent())14 .call()15 .content();16 17 return new Message(getName(), response);18 }19}多Agent协作
对话Agent系统
java
1public class MultiAgentSystem {2 3 public void runConversation() {4 // 创建智能体5 Agent researcher = new ResearchAgent("研究员", llm);6 Agent coder = new CoderAgent("程序员", llm);7 Agent reviewer = new ReviewAgent("审查员", llm);8 9 // 执行对话流程10 Message task = new Message("user", "开发一个快速排序算法");11 12 Message research = researcher.reply(task);13 Message code = coder.reply(research);14 Message review = reviewer.reply(code);15 16 System.out.println("最终结果: " + review.getContent());17 }18}1920class ResearchAgent extends AgentBase {21 public Message reply(Message input) {22 String result = llm.prompt()23 .user("作为研究员,分析需求: " + input.getContent())24 .call()25 .content();26 return new Message(getName(), result);27 }28}2930class CoderAgent extends AgentBase {31 public Message reply(Message input) {32 String code = llm.prompt()33 .user("基于分析编写代码: " + input.getContent())34 .call()35 .content();36 return new Message(getName(), code);37 }38}Pipeline模式
java
1public class AgentPipeline {2 3 public Message execute(Message input, List<Agent> agents) {4 Message current = input;5 6 for (Agent agent : agents) {7 current = agent.reply(current);8 System.out.println(agent.getName() + ": " + current.getContent());9 }10 11 return current;12 }13}1415// 使用16AgentPipeline pipeline = new AgentPipeline();17Message result = pipeline.execute(18 new Message("user", "任务描述"),19 List.of(researchAgent, coderAgent, reviewAgent)20);实战项目:智能代码审查系统
java
1@Service2public class CodeReviewSystem {3 4 private final ChatClient llm;5 6 public CodeReviewResult review(String code, String language) {7 // Agent 1: 语法检查8 Agent syntaxChecker = new Agent("语法检查器", llm) {9 public Message reply(Message input) {10 return new Message(getName(), 11 llm.prompt()12 .user("检查代码语法: " + input.getContent())13 .call()14 .content()15 );16 }17 };18 19 // Agent 2: 安全审查20 Agent securityAuditor = new Agent("安全审查", llm) {21 public Message reply(Message input) {22 return new Message(getName(),23 llm.prompt()24 .user("审查安全问题: " + input.getContent())25 .call()26 .content()27 );28 }29 };30 31 // Agent 3: 性能分析32 Agent performanceAnalyzer = new Agent("性能分析", llm) {33 public Message reply(Message input) {34 return new Message(getName(),35 llm.prompt()36 .user("分析性能: " + input.getContent())37 .call()38 .content()39 );40 }41 };42 43 // Agent 4: 综合评估44 Agent reviewer = new Agent("综合评估", llm) {45 public Message reply(Message input) {46 return new Message(getName(),47 llm.prompt()48 .user("综合以上评审给出建议: " + input.getContent())49 .call()50 .content()51 );52 }53 };54 55 // 执行Pipeline56 Message input = new Message("user", code);57 Message syntax = syntaxChecker.reply(input);58 Message security = securityAuditor.reply(input);59 Message performance = performanceAnalyzer.reply(input);60 61 // 汇总结果62 String summary = String.join("\n\n",63 "语法: " + syntax.getContent(),64 "安全: " + security.getContent(),65 "性能: " + performance.getContent()66 );67 68 Message finalReview = reviewer.reply(new Message("system", summary));69 70 return new CodeReviewResult(71 syntax.getContent(),72 security.getContent(),73 performance.getContent(),74 finalReview.getContent()75 );76 }77}7879record CodeReviewResult(String syntax, String security, String performance, String summary) {}框架对比
| 特性 | Spring AI | AgentScope |
|---|---|---|
| 定位 | 企业级AI应用开发 | 多智能体系统 |
| 学习曲线 | 低(Spring开发者友好) | 中等 |
| RAG支持 | ✅ 原生支持 | ⚠️ 需自行实现 |
| 多Agent | ⚠️ 基础支持 | ✅ 核心功能 |
| 生态 | Spring全家桶 | 独立框架 |
| 适用场景 | 企业应用、知识库、客服 | 复杂协作、多角色系统 |
最佳实践
1. 错误处理
java
1@ControllerAdvice2public class AIExceptionHandler {3 4 @ExceptionHandler(OpenAiApiException.class)5 public ResponseEntity<ErrorResponse> handleAIException(Exception ex) {6 return ResponseEntity7 .status(HttpStatus.SERVICE_UNAVAILABLE)8 .body(new ErrorResponse("AI服务暂时不可用"));9 }10}2. 缓存优化
java
1@Service2public class CachedChatService {3 4 @Cacheable(value = "chatCache", key = "#message")5 public String chat(String message) {6 return chatClient.prompt().user(message).call().content();7 }8}3. 配置管理
java
1@ConfigurationProperties(prefix = "app.ai")2@Configuration3public class AIConfig {4 private String model = "gpt-4";5 private double temperature = 0.7;6 private int maxTokens = 2000;7}总结
- Spring AI:适合需要快速集成LLM功能的企业级Java应用
- AgentScope:适合构建复杂的多智能体协作系统
选择建议:
- 企业知识库、智能客服 → Spring AI
- 多角色协作、复杂决策流程 → AgentScope
- 两者结合使用可以发挥最大价值
评论区 / Comments