Spring AI Alibaba入门教程 - 通义千问集成与AI应用开发完整指南
大约 17 分钟
Spring AI Alibaba入门教程 - 从零开始构建AI应用
目录
- Spring AI Alibaba简介
- 环境准备与项目搭建
- 快速开始第一个AI应用
- 通义千问大模型集成
- 向量数据库集成
- 提示词工程与优化
- 对话记忆与上下文管理
- 工具调用(Tool Calling)
- 多智能体架构
- RAG检索增强生成
- 实际应用案例
- 性能优化与最佳实践
- 总结与进阶学习
1. Spring AI Alibaba简介
Spring AI Alibaba(简称SAA)是基于Spring AI框架构建的开源AI应用开发框架,深度集成了阿里巴巴的AI技术和服务。它提供了高层次的AI API抽象,帮助Java开发者快速构建AI应用。
- ✅ 大模型集成:深度集成通义千问(Qwen)等阿里巴巴大模型
- ✅ 向量数据库支持:集成阿里云向量数据库,支持语义检索
- ✅ Spring生态集成:与Spring Boot无缝集成,利用Spring的依赖注入和配置管理
- ✅ 多智能体架构:支持多智能体协作,构建复杂AI应用
- ✅ RAG支持:支持检索增强生成(Retrieval-Augmented Generation)
- ✅ 工具调用:支持Function Calling,扩展AI能力
- ✅ 对话管理:内置对话记忆和上下文管理
| 特性 | Spring AI | Spring AI Alibaba |
|---|---|---|
| 大模型支持 | 通用模型(OpenAI、Anthropic等) | 通义千问等阿里模型 |
| 向量数据库 | 通用向量数据库 | 阿里云向量数据库 |
| 云服务集成 | 通用云服务 | 深度集成阿里云服务 |
| 适用场景 | 国际化应用 | 国内应用、阿里云用户 |
- 智能客服系统:构建自动问答系统
- 内容生成:文章、代码、文档自动生成
- 知识问答:基于知识库的智能问答
- 代码助手:AI代码生成和优化
- 数据分析:自然语言数据分析
- 多智能体系统:构建协作式AI应用
2. 环境准备与项目搭建
- JDK版本:JDK 17或更高版本(推荐JDK 17+)
- 构建工具:Maven 3.6+ 或 Gradle 7.0+
- 开发工具:IntelliJ IDEA、Eclipse或VS Code
- 阿里云账号:用于获取API Key和访问通义千问服务
注册阿里云账号
- 访问:https://www.aliyun.com/
- 完成注册和实名认证
开通通义千问服务
- 登录阿里云控制台
- 搜索"通义千问"或"DashScope"
- 开通服务并获取API Key
获取API Key
- 进入DashScope控制台
- 在API-KEY管理中创建新的API Key
- 妥善保存API Key(后续配置需要)
方式一:使用Spring Initializr
- 访问:https://start.spring.io/
- 选择以下配置:
- Project: Maven
- Language: Java
- Spring Boot: 3.2.0+
- Packaging: Jar
- Java: 17
- 添加依赖:
- Spring Web
- Spring Boot DevTools
- 点击"Generate"下载项目
方式二:使用IDE创建
IntelliJ IDEA:
- File → New → Project
- 选择Spring Initializr
- 配置项目信息
- 添加Spring Web依赖
- 点击Finish
在pom.xml中添加依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-ai-alibaba-demo</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
<spring-ai.version>1.0.0-M4</spring-ai.version>
</properties>
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI Alibaba -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-cloud-starter-alibaba-ai</artifactId>
<version>2023.0.1.0</version>
</dependency>
<!-- Spring AI Core -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-core</artifactId>
<version>${spring-ai.version}</version>
</dependency>
<!-- Spring AI OpenAI (用于兼容性) -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>${spring-ai.version}</version>
</dependency>
<!-- Lombok (可选,简化代码) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Spring Boot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>2.5 项目目录结构
创建标准的Spring Boot项目结构:
spring-ai-alibaba-demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── ai/
│ │ │ ├── SpringAiAlibabaApplication.java
│ │ │ ├── controller/
│ │ │ │ └── ChatController.java
│ │ │ ├── service/
│ │ │ │ └── ChatService.java
│ │ │ └── config/
│ │ │ └── AiConfig.java
│ │ └── resources/
│ │ └── application.yml
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └── ai/
│ └── ChatServiceTest.java
└── pom.xml3. 快速开始第一个AI应用
创建src/main/resources/application.yml:
spring:
application:
name: spring-ai-alibaba-demo
# Spring AI Alibaba配置
ai:
alibaba:
# 通义千问API Key
api-key: ${ALIBABA_API_KEY:your-api-key-here}
# API端点(可选,使用默认值)
# base-url: https://dashscope.aliyuncs.com/api/v1
# 模型名称(可选,默认使用qwen-turbo)
# model: qwen-turbo
# 温度参数(0-1,控制随机性)
temperature: 0.7
# 最大token数
max-tokens: 2000
# 日志配置
logging:
level:
com.example.ai: DEBUG
org.springframework.ai: DEBUGpackage com.example.ai;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringAiAlibabaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiAlibabaApplication.class, args);
}
}package com.example.ai.service;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ChatService {
@Autowired
private ChatClient chatClient;
/**
* 简单对话
*/
public String chat(String userMessage) {
return chatClient.call(userMessage);
}
/**
* 获取完整响应(包含元数据)
*/
public ChatResponse chatWithResponse(String userMessage) {
Prompt prompt = new Prompt(new UserMessage(userMessage));
return chatClient.call(prompt);
}
/**
* 带系统提示词的对话
*/
public String chatWithSystemPrompt(String systemPrompt, String userMessage) {
Prompt prompt = new Prompt(
new UserMessage(userMessage),
new SystemMessage(systemPrompt)
);
ChatResponse response = chatClient.call(prompt);
return response.getResult().getOutput().getContent();
}
}package com.example.ai.controller;
import com.example.ai.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/chat")
public class ChatController {
@Autowired
private ChatService chatService;
/**
* 简单对话接口
*/
@PostMapping("/simple")
public String simpleChat(@RequestBody ChatRequest request) {
return chatService.chat(request.getMessage());
}
/**
* 带系统提示词的对话
*/
@PostMapping("/with-prompt")
public String chatWithPrompt(@RequestBody ChatRequest request) {
String systemPrompt = "你是一个专业的Java开发助手,擅长解答编程问题。";
return chatService.chatWithSystemPrompt(systemPrompt, request.getMessage());
}
/**
* 请求DTO
*/
public static class ChatRequest {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}使用curl测试
# 简单对话
curl -X POST http://localhost:8080/api/chat/simple \
-H "Content-Type: application/json" \
-d '{"message": "你好,请介绍一下Java8的新特性"}'
# 带提示词的对话
curl -X POST http://localhost:8080/api/chat/with-prompt \
-H "Content-Type: application/json" \
-d '{"message": "如何优化Java代码性能?"}'使用Postman测试
- 创建POST请求
- URL:
http://localhost:8080/api/chat/simple - Headers:
Content-Type: application/json - Body (JSON):
{
"message": "你好,请介绍一下Spring框架"
}# 方式1:使用Maven
mvn spring-boot:run
# 方式2:打包后运行
mvn clean package
java -jar target/spring-ai-alibaba-demo-1.0.0.jar
# 方式3:在IDE中直接运行
# 运行SpringAiAlibabaApplication类的main方法4. 通义千问大模型集成
通义千问是阿里巴巴推出的大语言模型,支持多种模型规格:
- qwen-turbo:快速响应,适合实时对话
- qwen-plus:平衡性能和效果
- qwen-max:最强性能,适合复杂任务
- qwen-vl:多模态模型,支持图像理解
在application.yml中配置:
spring:
ai:
alibaba:
api-key: ${ALIBABA_API_KEY}
# 指定模型
model: qwen-plus
# 或使用环境变量
# model: ${ALIBABA_MODEL:qwen-turbo}@Service
public class ModelService {
@Autowired
private ChatClient chatClient;
/**
* 使用默认模型
*/
public String chatWithDefault(String message) {
return chatClient.call(message);
}
/**
* 指定模型(需要在配置中设置)
*/
public String chatWithModel(String model, String message) {
// 通过配置切换模型
// 或使用不同的ChatClient实例
return chatClient.call(message);
}
}spring:
ai:
alibaba:
api-key: ${ALIBABA_API_KEY}
model: qwen-plus
# 温度参数(0-2),控制随机性
# 0: 完全确定性,1: 平衡,2: 高度随机
temperature: 0.7
# Top-p采样(0-1)
top-p: 0.9
# 最大输出token数
max-tokens: 2000
# 停止词
stop-sequences:
- "\n\n"
- "用户:"@Service
public class StreamingChatService {
@Autowired
private ChatClient chatClient;
/**
* 流式响应(适合长文本生成)
*/
public Flux<String> streamChat(String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return chatClient.stream(prompt)
.map(response -> response.getResult().getOutput().getContent());
}
}
@RestController
@RequestMapping("/api/stream")
public class StreamingController {
@Autowired
private StreamingChatService streamingService;
@GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamChat(@RequestParam String message) {
return streamingService.streamChat(message)
.map(content -> ServerSentEvent.<String>builder()
.data(content)
.build());
}
}5. 向量数据库集成
向量数据库用于存储和检索高维向量数据,在AI应用中常用于:
- 语义搜索
- 相似度匹配
- RAG(检索增强生成)
<!-- 阿里云向量数据库 -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-cloud-starter-alibaba-vector-store</artifactId>
<version>2023.0.1.0</version>
</dependency>
<!-- 或使用其他向量数据库 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-pgvector-store</artifactId>
<version>${spring-ai.version}</version>
</dependency>spring:
ai:
vectorstore:
# 阿里云向量数据库配置
alibaba:
endpoint: ${VECTOR_DB_ENDPOINT}
api-key: ${VECTOR_DB_API_KEY}
# 集合名称
collection-name: documents
# 向量维度(根据模型确定)
dimension: 1536@Service
public class VectorStoreService {
@Autowired
private VectorStore vectorStore;
/**
* 添加文档到向量数据库
*/
public void addDocument(String content) {
Document document = new Document(content);
vectorStore.add(List.of(document));
}
/**
* 相似度搜索
*/
public List<Document> searchSimilar(String query, int topK) {
return vectorStore.similaritySearch(query, topK);
}
/**
* 批量添加文档
*/
public void addDocuments(List<String> contents) {
List<Document> documents = contents.stream()
.map(Document::new)
.collect(Collectors.toList());
vectorStore.add(documents);
}
}@Service
public class RAGService {
@Autowired
private ChatClient chatClient;
@Autowired
private VectorStore vectorStore;
/**
* RAG检索增强生成
*/
public String ragChat(String userQuery) {
// 1. 从向量数据库检索相关文档
List<Document> relevantDocs = vectorStore.similaritySearch(userQuery, 3);
// 2. 构建上下文
String context = relevantDocs.stream()
.map(Document::getContent)
.collect(Collectors.joining("\n\n"));
// 3. 构建提示词
String prompt = String.format(
"基于以下上下文回答问题:\n\n%s\n\n问题:%s\n\n回答:",
context,
userQuery
);
// 4. 调用大模型生成回答
return chatClient.call(prompt);
}
}6. 提示词工程与优化
提示词工程是通过优化输入提示词来获得更好的AI输出结果的技术。
@Service
public class PromptTemplateService {
@Autowired
private ChatClient chatClient;
/**
* 使用提示词模板
*/
public String chatWithTemplate(String userInput, Map<String, Object> variables) {
String template = """
你是一个专业的{role}助手。
请根据以下要求回答问题:
{requirement}
用户问题:{question}
请提供详细、准确的回答。
""";
String prompt = template
.replace("{role}", variables.getOrDefault("role", "技术").toString())
.replace("{requirement}", variables.getOrDefault("requirement", "").toString())
.replace("{question}", userInput);
return chatClient.call(prompt);
}
}String goodPrompt = """
你是一位经验丰富的Java架构师,擅长系统设计和性能优化。
请分析以下代码的性能问题,并提供优化建议:
{code}
""";String contextualPrompt = """
背景:我们正在开发一个电商系统,使用Spring Boot框架。
问题:如何实现分布式事务?
要求:
1. 考虑高并发场景
2. 保证数据一致性
3. 提供代码示例
""";String fewShotPrompt = """
请将以下自然语言转换为SQL查询:
示例1:
输入:查询所有年龄大于25的用户
输出:SELECT * FROM users WHERE age > 25
示例2:
输入:统计每个部门的员工数量
输出:SELECT department, COUNT(*) FROM employees GROUP BY department
现在请转换:
输入:{userInput}
输出:
""";@Service
public class OptimizedPromptService {
@Autowired
private ChatClient chatClient;
/**
* 优化的提示词示例
*/
public String optimizedChat(String userQuery) {
// 1. 结构化提示词
String prompt = String.format("""
# 任务描述
%s
# 输出要求
1. 回答要准确、详细
2. 提供代码示例(如适用)
3. 说明注意事项
# 输出格式
使用Markdown格式,包含标题和代码块
""", userQuery);
return chatClient.call(prompt);
}
/**
* 链式提示词(Chain of Thought)
*/
public String chainOfThought(String problem) {
String prompt = String.format("""
请按以下步骤解决这个问题:
问题:%s
步骤1:分析问题的关键点
步骤2:列出可能的解决方案
步骤3:评估每个方案的优缺点
步骤4:选择最佳方案并详细说明
""", problem);
return chatClient.call(prompt);
}
}7. 对话记忆与上下文管理
在多轮对话中,AI需要记住之前的对话内容,才能提供连贯的回答。
@Service
public class MemoryChatService {
@Autowired
private ChatClient chatClient;
@Autowired
private ChatMemory chatMemory;
/**
* 带记忆的对话
*/
public String chatWithMemory(String userId, String userMessage) {
// 添加用户消息到记忆
chatMemory.add(new UserMessage(userMessage));
// 获取对话历史
List<Message> history = chatMemory.get(userId);
// 构建包含历史的提示词
Prompt prompt = new Prompt(history);
// 获取AI回复
ChatResponse response = chatClient.call(prompt);
String aiMessage = response.getResult().getOutput().getContent();
// 添加AI回复到记忆
chatMemory.add(new AssistantMessage(aiMessage));
return aiMessage;
}
}@Component
public class CustomChatMemory implements ChatMemory {
private final Map<String, List<Message>> memoryStore = new ConcurrentHashMap<>();
@Override
public void add(String userId, Message message) {
memoryStore.computeIfAbsent(userId, k -> new ArrayList<>())
.add(message);
}
@Override
public List<Message> get(String userId) {
return memoryStore.getOrDefault(userId, new ArrayList<>());
}
@Override
public void clear(String userId) {
memoryStore.remove(userId);
}
}@Service
public class PersistentChatService {
@Autowired
private ChatMemoryRepository memoryRepository;
@Autowired
private ChatClient chatClient;
/**
* 持久化对话记忆
*/
public String chatAndSave(String userId, String userMessage) {
// 从数据库加载历史
List<Message> history = memoryRepository.findByUserId(userId);
// 添加新消息
history.add(new UserMessage(userMessage));
// 调用AI
Prompt prompt = new Prompt(history);
ChatResponse response = chatClient.call(prompt);
String aiMessage = response.getResult().getOutput().getContent();
// 保存到数据库
history.add(new AssistantMessage(aiMessage));
memoryRepository.save(userId, history);
return aiMessage;
}
}8. 工具调用(Tool Calling)
工具调用允许AI模型调用外部函数或API,扩展AI的能力。
@Component
public class WeatherTool {
/**
* 获取天气信息
*/
@Tool("获取指定城市的天气信息")
public String getWeather(@P("城市名称") String city) {
// 模拟天气API调用
return String.format("%s的天气:晴天,温度25°C", city);
}
/**
* 计算器工具
*/
@Tool("执行数学计算")
public double calculate(
@P("第一个数字") double a,
@P("运算符") String operator,
@P("第二个数字") double b
) {
return switch (operator) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> b != 0 ? a / b : 0;
default -> throw new IllegalArgumentException("不支持的运算符");
};
}
}@Service
public class ToolCallingService {
@Autowired
private ChatClient chatClient;
@Autowired
private List<Object> tools;
/**
* 带工具调用的对话
*/
public String chatWithTools(String userMessage) {
// 配置工具
Prompt prompt = new Prompt(
new UserMessage(userMessage),
new SystemMessage("你可以使用工具来帮助回答问题。")
);
// 调用AI(会自动识别是否需要调用工具)
ChatResponse response = chatClient.call(prompt);
return response.getResult().getOutput().getContent();
}
}9. 多智能体架构
多智能体系统由多个AI智能体协作完成复杂任务,每个智能体负责不同的子任务。
@Component
public class CodeReviewAgent {
@Autowired
private ChatClient chatClient;
public String reviewCode(String code) {
String prompt = """
你是一个代码审查专家,请审查以下代码:
{code}
请指出:
1. 潜在的bug
2. 性能问题
3. 代码风格问题
4. 改进建议
""".replace("{code}", code);
return chatClient.call(prompt);
}
}
@Component
public class DocumentationAgent {
@Autowired
private ChatClient chatClient;
public String generateDoc(String code) {
String prompt = """
你是一个技术文档编写专家,请为以下代码生成文档:
{code}
包括:
1. 功能说明
2. 参数说明
3. 返回值说明
4. 使用示例
""".replace("{code}", code);
return chatClient.call(prompt);
}
}@Service
public class MultiAgentService {
@Autowired
private CodeReviewAgent codeReviewAgent;
@Autowired
private DocumentationAgent documentationAgent;
/**
* 多智能体协作
*/
public AgentResult processCode(String code) {
// 1. 代码审查
String review = codeReviewAgent.reviewCode(code);
// 2. 生成文档
String documentation = documentationAgent.generateDoc(code);
// 3. 综合结果
return new AgentResult(review, documentation);
}
public static class AgentResult {
private String review;
private String documentation;
// 构造方法和getter/setter...
}
}10. RAG检索增强生成
@Service
public class CompleteRAGService {
@Autowired
private ChatClient chatClient;
@Autowired
private VectorStore vectorStore;
@Autowired
private EmbeddingClient embeddingClient;
/**
* 完整的RAG流程
*/
public String ragQuery(String userQuery) {
// 1. 将用户查询转换为向量
List<Double> queryVector = embeddingClient.embed(userQuery);
// 2. 向量相似度搜索
List<Document> relevantDocs = vectorStore.similaritySearch(
SearchRequest.builder()
.query(userQuery)
.topK(5)
.build()
);
// 3. 构建上下文
String context = relevantDocs.stream()
.map(Document::getContent)
.collect(Collectors.joining("\n\n---\n\n"));
// 4. 构建RAG提示词
String ragPrompt = String.format("""
基于以下文档内容回答问题。如果文档中没有相关信息,请说明。
文档内容:
%s
问题:%s
回答:
""", context, userQuery);
// 5. 生成回答
return chatClient.call(ragPrompt);
}
/**
* 文档预处理和向量化
*/
public void indexDocuments(List<String> documents) {
List<Document> docs = documents.stream()
.map(Document::new)
.collect(Collectors.toList());
// 添加到向量数据库
vectorStore.add(docs);
}
}11. 实际应用案例
@RestController
@RequestMapping("/api/customer-service")
public class CustomerServiceController {
@Autowired
private ChatService chatService;
@PostMapping("/ask")
public ResponseEntity<ChatResponse> askQuestion(@RequestBody QuestionRequest request) {
String systemPrompt = """
你是一个专业的客服助手,负责回答客户关于产品的问题。
请保持友好、专业的语气,提供准确的信息。
""";
String answer = chatService.chatWithSystemPrompt(
systemPrompt,
request.getQuestion()
);
return ResponseEntity.ok(new ChatResponse(answer));
}
}@Service
public class CodeGenerationService {
@Autowired
private ChatClient chatClient;
public String generateCode(String requirement) {
String prompt = String.format("""
请根据以下需求生成Java代码:
需求:%s
要求:
1. 代码要规范、可读性强
2. 包含必要的注释
3. 遵循最佳实践
4. 使用Spring Boot框架(如适用)
请只返回代码,不要其他说明。
""", requirement);
return chatClient.call(prompt);
}
}@Service
public class DocumentationService {
@Autowired
private ChatClient chatClient;
public String generateApiDoc(String code) {
String prompt = String.format("""
请为以下代码生成API文档:
%s
文档格式要求:
1. 使用Markdown格式
2. 包含接口说明、参数说明、返回值说明
3. 提供请求示例和响应示例
""", code);
return chatClient.call(prompt);
}
}12. 性能优化与最佳实践
@Service
public class CachedChatService {
@Autowired
private ChatClient chatClient;
@Cacheable(value = "chatCache", key = "#message")
public String cachedChat(String message) {
return chatClient.call(message);
}
}@Service
public class AsyncChatService {
@Autowired
private ChatClient chatClient;
@Async
public CompletableFuture<String> asyncChat(String message) {
String response = chatClient.call(message);
return CompletableFuture.completedFuture(response);
}
}@Service
public class BatchChatService {
@Autowired
private ChatClient chatClient;
public List<String> batchChat(List<String> messages) {
return messages.parallelStream()
.map(chatClient::call)
.collect(Collectors.toList());
}
}API Key安全
- 使用环境变量存储API Key
- 不要在代码中硬编码
- 使用配置中心管理密钥
错误处理
@Service public class RobustChatService { @Autowired private ChatClient chatClient; public String safeChat(String message) { try { return chatClient.call(message); } catch (Exception e) { log.error("AI调用失败", e); return "抱歉,服务暂时不可用,请稍后重试。"; } } }限流和熔断
@Service public class RateLimitedChatService { private final RateLimiter rateLimiter = RateLimiter.create(10.0); // 每秒10次 @Autowired private ChatClient chatClient; public String rateLimitedChat(String message) { rateLimiter.acquire(); // 获取许可 return chatClient.call(message); } }监控和日志
@Aspect @Component public class ChatMonitoringAspect { @Around("execution(* com.example.ai.service.*.chat*(..))") public Object monitor(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); try { Object result = joinPoint.proceed(); long duration = System.currentTimeMillis() - start; log.info("AI调用耗时: {}ms", duration); return result; } catch (Exception e) { log.error("AI调用异常", e); throw e; } } }
13. 总结与进阶学习
通过本教程,你已经掌握了:
- ✅ Spring AI Alibaba的基本概念和配置
- ✅ 通义千问大模型的集成和使用
- ✅ 向量数据库和RAG应用
- ✅ 提示词工程和优化技巧
- ✅ 对话记忆和上下文管理
- ✅ 工具调用和多智能体架构
- ✅ 实际应用案例和最佳实践
深入理解Spring AI架构
- 学习Spring AI的核心抽象
- 理解不同AI提供商的适配器
- 自定义AI客户端
高级RAG技术
- 多阶段检索
- 重排序(Re-ranking)
- 混合检索策略
多模态AI应用
- 图像理解
- 语音处理
- 视频分析
生产环境部署
- 容器化部署
- 负载均衡
- 高可用架构
成本优化
- Token使用优化
- 缓存策略
- 模型选择优化
- 官方文档:https://spring.io/projects/spring-ai
- 阿里云文档:https://help.aliyun.com/product/2402380.html
- 通义千问文档:https://help.aliyun.com/zh/dashscope/
- Spring AI GitHub:https://github.com/spring-projects/spring-ai
- 智能问答系统:基于RAG的知识问答系统
- 代码审查助手:自动代码审查和优化建议
- 文档生成工具:自动生成API文档和技术文档
- 智能客服机器人:多轮对话的客服系统
- 数据分析助手:自然语言数据分析
结语
Spring AI Alibaba为Java开发者提供了强大的AI应用开发能力。通过本教程的学习,相信你已经掌握了构建AI应用的核心技能。
记住:
- 多实践:通过实际项目加深理解
- 关注性能:注意API调用成本和响应时间
- 持续学习:AI技术发展迅速,保持学习
- 安全第一:注意API Key安全和数据隐私
祝你学习愉快,AI应用开发顺利! 🚀
本教程由Java突击队学习社区编写,如有问题欢迎反馈。