Spring AI实战:构建企业级智能对话系统
2026/9/14 8:48:12 网站建设 项目流程

1. Spring AI实战:构建智能对话系统的完整指南

在当今企业级应用开发中,整合AI能力已成为提升产品竞争力的关键。Spring AI作为Spring生态中的AI集成框架,为Java开发者提供了便捷的大模型接入方案。本文将深入探讨如何基于Spring AI构建具备对话交互、提示词优化、API调用和文件处理能力的智能系统。

2. 环境准备与基础配置

2.1 项目初始化

首先创建一个标准的Spring Boot项目,推荐使用Spring Initializr(https://start.spring.io)生成项目骨架。关键依赖包括:

<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-core</artifactId> <version>0.8.1</version> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai-spring-boot-starter</artifactId> <version>0.8.1</version> </dependency>

2.2 配置API密钥

在application.yml中配置大模型服务凭证:

spring: ai: openai: api-key: ${OPENAI_API_KEY} base-url: https://api.openai.com/v1

提示:实际项目中建议使用Vault或配置中心管理敏感信息,不要将密钥硬编码在配置文件中

3. 核心功能实现

3.1 基础对话服务

创建ChatService实现基础对话功能:

@Service public class ChatService { private final ChatClient chatClient; public ChatService(ChatClient chatClient) { this.chatClient = chatClient; } public String generate(String message) { Prompt prompt = new Prompt(new UserMessage(message)); return chatClient.call(prompt).getResult().getOutput().getContent(); } }

3.2 提示词工程实践

Spring AI提供了强大的提示词模板功能:

@Bean public PromptTemplate customerServicePrompt() { return new PromptTemplate(""" 你是一名专业的客服代表,请用{language}回答关于{product}的问题。 用户问题:{question} 回答时要遵守以下规则: 1. 保持友好和专业 2. 不超过100字 3. 包含至少一个使用场景示例 """); }

使用方式:

Map<String, Object> params = new HashMap<>(); params.put("language", "中文"); params.put("product", "智能手表"); params.put("question", "如何设置心率监测?"); String response = customerServicePrompt().render(params); String result = chatClient.call(new Prompt(response)).getResult().getOutput().getContent();

4. 高级功能实现

4.1 文件内容处理

Spring AI支持多种文档格式的解析:

@Service public class DocumentService { private final VectorStore vectorStore; private final EmbeddingClient embeddingClient; public DocumentService(VectorStore vectorStore, EmbeddingClient embeddingClient) { this.vectorStore = vectorStore; this.embeddingClient = embeddingClient; } public void processDocument(Resource document) { // 文档解析和向量化 DocumentReader reader = new PdfDocumentReader(document); List<Document> documents = reader.get(); // 存储向量化结果 vectorStore.add(documents.stream() .map(doc -> new Embedding(doc.getContent(), embeddingClient.embed(doc.getContent()))) .collect(Collectors.toList())); } public List<String> searchDocument(String query) { // 语义搜索 return vectorStore.similaritySearch(query).stream() .map(Embedding::getContent) .collect(Collectors.toList()); } }

4.2 自定义API调用

对于需要直接调用大模型API的场景:

@RestController @RequestMapping("/api/ai") public class AIController { @PostMapping("/complete") public ResponseEntity<String> completeText(@RequestBody CompletionRequest request) { OpenAiApi openAiApi = new OpenAiApi("https://api.openai.com/v1"); CompletionRequest apiRequest = new CompletionRequest.Builder() .withModel(request.getModel()) .withPrompt(request.getPrompt()) .withMaxTokens(request.getMaxTokens()) .build(); CompletionResult result = openAiApi.createCompletion(apiRequest).block(); return ResponseEntity.ok(result.getChoices().get(0).getText()); } }

5. 性能优化与最佳实践

5.1 对话历史管理

实现有记忆的对话系统:

@Service @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public class SessionChatService { private final List<Message> history = new ArrayList<>(); public String chat(String message) { history.add(new UserMessage(message)); Prompt prompt = new Prompt(history); ChatResponse response = chatClient.call(prompt); history.add(response.getResult().getOutput()); return response.getResult().getOutput().getContent(); } }

5.2 流式响应处理

对于长文本生成场景,使用流式响应提升用户体验:

@GetMapping("/stream") public SseEmitter streamCompletion(@RequestParam String prompt) { SseEmitter emitter = new SseEmitter(); Flux<ChatResponse> flux = chatClient.stream(new Prompt(prompt)); flux.subscribe( response -> { try { emitter.send(response.getResult().getOutput().getContent()); } catch (IOException e) { emitter.completeWithError(e); } }, emitter::completeWithError, emitter::complete ); return emitter; }

6. 常见问题排查

6.1 性能问题诊断

当遇到响应延迟时,可按照以下步骤排查:

  1. 检查网络延迟:记录API调用往返时间
  2. 分析提示词复杂度:过长的提示词会增加处理时间
  3. 监控Token使用量:大模型通常按Token计费和处理
  4. 检查模型选择:较大模型虽然能力强但响应慢

6.2 错误处理策略

实现全局异常处理器:

@ControllerAdvice public class AIExceptionHandler { @ExceptionHandler(ApiException.class) public ResponseEntity<ErrorResponse> handleApiException(ApiException ex) { return ResponseEntity.status(ex.getStatusCode()) .body(new ErrorResponse(ex.getMessage())); } @ExceptionHandler(RateLimitException.class) public ResponseEntity<ErrorResponse> handleRateLimit(RateLimitException ex) { return ResponseEntity.status(429) .header("Retry-After", String.valueOf(ex.getRetryAfter())) .body(new ErrorResponse("请求过于频繁,请稍后再试")); } }

7. 部署与扩展

7.1 容器化部署

创建Dockerfile实现容器化:

FROM eclipse-temurin:17-jdk-jammy WORKDIR /app COPY target/spring-ai-demo.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]

7.2 水平扩展策略

当需要处理高并发请求时:

  1. 使用Redis实现对话状态共享
  2. 配置API网关的限流规则
  3. 考虑使用消息队列异步处理非实时请求
  4. 对大模型响应实现本地缓存

8. 安全注意事项

  1. 输入验证:所有用户输入都应进行严格的验证和清理
  2. 输出过滤:对模型生成内容进行适当过滤
  3. 权限控制:敏感操作需要身份验证
  4. 日志审计:记录所有AI交互的关键信息

在实际项目中,我发现Spring AI的PromptTemplate对中文支持需要特别注意标点符号的处理。建议在复杂提示词中使用"""多行字符串语法,可以避免很多格式问题。另外,对于文件处理功能,PDF解析对中文文档的兼容性最好,而Word文档需要注意不同版本间的格式差异。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询