Spring AI Alibaba 学习路线图:从入门到精通
·
Spring AI Alibaba 学习路线图:从入门到精通
一、学习路径总览
入门阶段 → 进阶阶段 → 高级阶段 → 实战阶段
↓ ↓ ↓ ↓
基础概念 核心特性 架构设计 企业应用
环境搭建 多模型集成 性能优化 生产部署
简单对话 高级功能 安全认证 监控运维
二、入门阶段:基础概念与环境搭建
2.1 核心概念理解
什么是Spring AI?
Spring AI是Spring生态系统中的AI应用框架,提供统一的API接口来集成各种大语言模型(LLM)。
核心特性:
- 统一的ChatClient API
- 支持多种AI提供商(OpenAI、Azure、Ollama、阿里云百炼等)
- 支持对话、嵌入、图像生成等多种AI能力
- 与Spring生态无缝集成
Spring AI Alibaba vs Spring AI
| 特性 | Spring AI | Spring AI Alibaba |
|---|---|---|
| 提供商 | Spring官方 | 阿里云 |
| 主要集成 | OpenAI、Azure等 | 阿里云百炼(DashScope) |
| 模型 | GPT系列等 | 通义千问系列 |
| 优势 | 国际化、多平台 | 中文优化、国内访问快 |
| Starter | spring-ai-openai-spring-boot-starter | spring-ai-alibaba-starter |
关键术语
LLM (Large Language Model) - 大语言模型
ChatModel - 对话模型接口
Embedding - 向量化/嵌入
Prompt - 提示词/提示模板
Token - 词元(文本最小单位)
Temperature - 创造性参数(0-1)
Stream - 流式响应
Function Calling - 函数调用
RAG (Retrieval-Augmented Generation) - 检索增强生成
2.2 环境搭建
- ✅ JDK 17+ 安装配置
- ✅ Maven 3.6+ 配置
- ✅ Ollama本地部署
- ✅ SpringBoot项目创建
- ✅ 基础对话接口实现
2.3 基础知识学习
1. Spring AI核心API
// ChatClient - 核心对话客户端
ChatClient chatClient = ChatClient.builder(chatModel).build();
// 简单对话
String response = chatClient.prompt()
.user("你好")
.call()
.content();
// 带参数的对话
String response = chatClient.prompt()
.user("介绍一下{topic}")
.system("你是一个专业的AI助手")
.param("topic", "机器学习")
.options(ChatOptions.builder()
.temperature(0.8)
.maxTokens(2048)
.build())
.call()
.content();
2. Prompt提示工程基础
// 系统提示词
String response = chatClient.prompt()
.system("你是一个专业的Java开发专家")
.user("请解释Spring Boot的优势")
.call()
.content();
// 多轮对话
String response = chatClient.prompt()
.messages(
new UserMessage("你好"),
new AssistantMessage("你好!有什么可以帮助你的?"),
new UserMessage("Java和Python哪个更适合AI开发?")
)
.call()
.content();
三、进阶阶段:核心特性与高级功能
3.1 多模型集成
学习阿里云百炼集成
<!-- pom.xml -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>1.0.0-M5.1</version>
</dependency>
# application.yml
spring:
ai:
dashscope:
api-key: your-api-key
chat:
options:
model: qwen-max # 或 qwen-plus, qwen-turbo
模型对比学习
| 模型 | 特点 | 适用场景 | 价格 |
|---|---|---|---|
| qwen-max | 最强性能,复杂任务 | 深度分析、代码生成 | 高 |
| qwen-plus | 平衡性能和成本 | 通用对话、文本生成 | 中 |
| qwen-turbo | 速度快,成本低 | 简单问答、快速响应 | 低 |
| qwen-long | 长文本处理 | 文档摘要、长文分析 | 中 |
多模型动态切换
@RestController
public class MultiModelController {
private final Map<String, ChatClient> chatClients;
public MultiModelController(Map<String, ChatModel> chatModels) {
this.chatClients = chatModels.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> ChatClient.builder(e.getValue()).build()
));
}
@PostMapping("/ai/chat/{model}")
public String chat(@PathVariable String model,
@RequestParam String message) {
return chatClients.get(model)
.prompt()
.user(message)
.call()
.content();
}
}
3.2 流式响应(Streaming)
基础流式响应
@GetMapping(value = "/ai/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.stream()
.content();
}
Server-Sent Events实现
@GetMapping("/ai/sse")
public SseEmitter sseChat(@RequestParam String message) {
SseEmitter emitter = new SseEmitter();
chatClient.prompt()
.user(message)
.stream()
.content()
.subscribe(
content -> {
try {
emitter.send(SseEmitter.event()
.name("message")
.data(content));
} catch (IOException e) {
emitter.completeWithError(e);
}
},
error -> emitter.completeWithError(error),
() -> emitter.complete()
);
return emitter;
}
前端配合示例
const eventSource = new EventSource('/ai/sse?message=你好');
eventSource.addEventListener('message', (event) => {
console.log('收到数据:', event.data);
// 逐字显示AI回复
appendToChatBox(event.data);
});
eventSource.onerror = (error) => {
console.error('连接错误:', error);
eventSource.close();
};
3.3 Function Calling(函数调用)
什么是Function Calling?
让AI模型能够调用预定义的Java方法,实现与外部系统的交互。
基础实现
@Service
public class WeatherService {
@Description("查询指定城市的天气信息")
public String getWeather(
@Param("city") String city) {
// 模拟天气查询
return city + "今天天气晴朗,温度25°C";
}
}
@RestController
public class FunctionCallingController {
private final ChatClient chatClient;
private final WeatherService weatherService;
public FunctionCallingController(ChatClient.Builder builder,
WeatherService weatherService) {
this.chatClient = builder.build();
this.weatherService = weatherService;
}
@GetMapping("/ai/weather-chat")
public String chatWithWeather(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.functions("getWeather")
.call()
.content();
}
}
多函数调用
@Service
public class ToolService {
@Description("查询当前时间")
public String getCurrentTime() {
return LocalDateTime.now().toString();
}
@Description("计算数学表达式")
public String calculate(@Param("expression") String expression) {
// 实现计算逻辑
return "计算结果: " + expression;
}
@Description("查询用户信息")
public String getUserInfo(@Param("userId") String userId) {
return "用户" + userId + "的信息";
}
}
3.4 Embedding(向量化)
基础向量化
@RestController
public class EmbeddingController {
private final EmbeddingModel embeddingModel;
public EmbeddingController(EmbeddingModel embeddingModel) {
this.embeddingModel = embeddingModel;
}
@PostMapping("/ai/embedding")
public List<Double> embed(@RequestParam String text) {
return embeddingModel.embed(text);
}
}
相似度计算
@Service
public class SimilarityService {
private final EmbeddingModel embeddingModel;
public double calculateSimilarity(String text1, String text2) {
List<Double> embedding1 = embeddingModel.embed(text1);
List<Double> embedding2 = embeddingModel.embed(text2);
// 计算余弦相似度
return cosineSimilarity(embedding1, embedding2);
}
private double cosineSimilarity(List<Double> vec1, List<Double> vec2) {
double dotProduct = 0.0;
double normA = 0.0;
double normB = 0.0;
for (int i = 0; i < vec1.size(); i++) {
dotProduct += vec1.get(i) * vec2.get(i);
normA += Math.pow(vec1.get(i), 2);
normB += Math.pow(vec2.get(i), 2);
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
}
四、高级阶段:RAG与架构设计
4.1 RAG(检索增强生成)
RAG架构理解
用户问题 → 向量化 → 向量数据库检索 → 相关文档
↓ ↓
└──── 结合Prompt ────→ LLM生成回答 ←─┘
实现RAG系统
1. 文档处理
@Service
public class DocumentService {
private final EmbeddingModel embeddingModel;
private final VectorStore vectorStore;
private final DocumentReader documentReader;
// 导入文档
public void importDocuments(MultipartFile file) {
// 1. 读取文档
List<Document> documents = documentReader.read(file);
// 2. 文档分块
List<Document> chunks = TokenTextSplitter.create().apply(documents);
// 3. 向量化并存储
vectorStore.add(chunks);
}
}
2. 检索增强对话
@RestController
public class RAGController {
private final ChatClient chatClient;
private final VectorStore vectorStore;
@GetMapping("/ai/rag")
public String ragChat(@RequestParam String question) {
// 1. 检索相关文档
List<Document> relevantDocs = vectorStore.similaritySearch(
SearchRequest.builder()
.query(question)
.topK(5)
.build()
);
// 2. 构建增强Prompt
String context = relevantDocs.stream()
.map(Document::getText)
.collect(Collectors.joining("\n\n"));
String prompt = String.format("""
基于以下参考信息回答问题:
%s
问题:%s
如果参考信息中没有相关内容,请说明无法回答。
""", context, question);
// 3. 生成回答
return chatClient.prompt()
.user(prompt)
.call()
.content();
}
}
4.2 向量数据库集成
支持的向量数据库
| 数据库 | 特点 | 适用场景 |
|---|---|---|
| Redis | 高性能,成熟生态 | 已有Redis基础设施 |
| Milvus | 专为向量设计 | 大规模向量检索 |
| Chroma | 轻量级,易用 | 小型项目、原型 |
| PostgreSQL | 关系型+向量 | 混合查询需求 |
ChromaDB集成示例
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-chroma-store-spring-boot-starter</artifactId>
</dependency>
spring:
ai:
vectorstore:
chroma:
client:
host: localhost
port: 8000
collection-name: my-documents
4.3 Memory(对话记忆)
会话记忆管理
@RestController
public class MemoryChatController {
private final ChatClient chatClient;
private final ChatMemory chatMemory;
@PostMapping("/ai/memory-chat")
public String chat(@RequestParam String message,
@RequestParam String sessionId) {
// 添加用户消息到记忆
chatMemory.add(sessionId, new UserMessage(message));
// 获取历史消息
List<Message> history = chatMemory.get(sessionId);
// 生成回复
String response = chatClient.prompt()
.messages(history)
.call()
.content();
// 添加AI回复到记忆
chatMemory.add(sessionId, new AssistantMessage(response));
return response;
}
}
记忆持久化
@Configuration
public class ChatMemoryConfig {
@Bean
public ChatMemory chatMemory() {
// 使用Redis持久化对话记忆
return new RedisChatMemory(redisConnectionFactory);
}
}
4.4 提示词模板工程
模板管理
@Service
public class PromptTemplateService {
private final PromptTemplate promptTemplate;
public PromptTemplateService() {
String template = """
你是一个{role},专门负责{task}。
请按照以下要求回答:
1. {requirement1}
2. {requirement2}
3. {requirement3}
用户问题:{question}
""";
this.promptTemplate = new PromptTemplate(template);
}
public String createPrompt(Map<String, Object> variables) {
return promptTemplate.create(variables).getContents();
}
}
五、实战阶段:企业级应用
5.1 智能客服系统
系统架构
用户 → Web界面 → SpringBoot后端 → AI服务
↓
知识库检索
↓
业务系统对接
核心实现
@Service
public class CustomerServiceAI {
private final ChatClient chatClient;
private final KnowledgeBaseService knowledgeBase;
private final OrderService orderService;
public String handleCustomerQuery(String query, String customerId) {
// 1. 意图识别
String intent = recognizeIntent(query);
// 2. 根据意图路由
return switch (intent) {
case "order_query" -> handleOrderQuery(query, customerId);
case "product_info" -> handleProductInfo(query);
case "complaint" -> handleComplaint(query);
default -> generalChat(query);
};
}
@Function("查询订单状态")
public String handleOrderQuery(String query, String customerId) {
// 调用业务系统
Order order = orderService.getLatestOrder(customerId);
return "您的订单" + order.getId() + "当前状态:" + order.getStatus();
}
}
5.2 智能文档助手
文档问答系统
@RestController
public class DocumentQAController {
private final DocumentService documentService;
private final ChatClient chatClient;
@PostMapping("/docs/upload")
public String uploadDocument(@RequestParam("file") MultipartFile file) {
documentService.importDocuments(file);
return "文档上传成功";
}
@PostMapping("/docs/ask")
public String askQuestion(@RequestParam String question) {
return documentService.queryAndAnswer(question);
}
}
5.3 代码生成助手
@Service
public class CodeGenerationService {
private final ChatClient chatClient;
public String generateCode(String requirement, String language) {
String prompt = String.format("""
你是一个专业的{language}开发工程师。
需求描述:{requirement}
请生成:
1. 完整的代码实现
2. 必要的注释
3. 使用说明
代码:
""", language, requirement);
return chatClient.prompt()
.system("你是一名资深开发工程师")
.user(prompt)
.call()
.content();
}
}
5.4 数据分析助手
@Service
public class DataAnalysisService {
private final ChatClient chatClient;
public String analyzeData(String data, String question) {
String prompt = String.format("""
分析以下数据并回答问题。
数据:
%s
问题:%s
请提供:
1. 数据洞察
2. 趋势分析
3. 建议行动
""", data, question);
return chatClient.prompt()
.user(prompt)
.call()
.content();
}
}
六、性能优化与最佳实践
6.1 性能优化策略
1. 缓存策略
@Service
public class CachedChatService {
private final Cache<String, String> responseCache;
private final ChatClient chatClient;
public String chatWithCache(String message) {
return responseCache.get(message,
() -> chatClient.prompt()
.user(message)
.call()
.content());
}
}
2. 异步处理
@Service
public class AsyncChatService {
@Async
public CompletableFuture<String> asyncChat(String message) {
String response = chatClient.prompt()
.user(message)
.call()
.content();
return CompletableFuture.completedFuture(response);
}
}
3. 批量处理
public List<String> batchChat(List<String> messages) {
return messages.parallelStream()
.map(msg -> chatClient.prompt()
.user(msg)
.call()
.content())
.collect(Collectors.toList());
}
6.2 成本控制
Token使用监控
@Service
public class TokenUsageService {
private final AtomicLong totalTokens = new AtomicLong(0);
public String chatWithTracking(String message) {
ChatResponse response = chatClient.prompt()
.user(message)
.call()
.chatResponse();
long usedTokens = response.getMetadata().getUsage().getTotalTokens();
totalTokens.addAndGet(usedTokens);
log.info("本次使用Token: {}, 累计: {}", usedTokens, totalTokens.get());
return response.getResult().getOutput().getContent();
}
}
配额管理
@Service
public class QuotaService {
private final Map<String, Long> userUsage = new ConcurrentHashMap<>();
private static final long DAILY_QUOTA = 10000;
public boolean checkQuota(String userId) {
return userUsage.getOrDefault(userId, 0L) < DAILY_QUOTA;
}
public void recordUsage(String userId, long tokens) {
userUsage.merge(userId, tokens, Long::sum);
}
}
6.3 安全最佳实践
1. Prompt注入防护
@Service
public class PromptSecurityService {
public String sanitizeInput(String input) {
// 移除潜在的恶意指令
return input.replaceAll("(?i)(ignore previous|system:|override)", "");
}
public boolean validateInput(String input) {
// 检查输入长度
if (input.length() > 2000) {
return false;
}
// 检查特殊字符
return !input.contains("<script>");
}
}
2. API Key管理
@Configuration
public class AiConfig {
@Value("${spring.ai.dashscope.api-key}")
private String apiKey;
@Bean
public ChatModel chatModel() {
// 使用加密的API Key
return DashScopeChatModel.builder()
.apiKey(decryptApiKey(apiKey))
.build();
}
}
七、生产部署与运维
7.1 生产环境配置
# application-prod.yml
spring:
ai:
dashscope:
api-key: ${DASHSCOPE_API_KEY} # 从环境变量读取
chat:
options:
model: qwen-max
temperature: 0.7
retry:
max-attempts: 3
backoff:
initial-interval: 1000
max-interval: 5000
# 超时配置
spring.ai.client.timeout.connect: 10s
spring.ai.client.timeout.read: 30s
7.2 监控与日志
Actuator监控
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
metrics:
tags:
application: ${spring.application.name}
自定义指标
@Component
public class AiMetrics {
private final MeterRegistry meterRegistry;
private final Timer chatTimer;
private final Counter chatCounter;
public AiMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.chatTimer = Timer.builder("ai.chat.duration")
.description("AI chat response time")
.register(meterRegistry);
this.chatCounter = Counter.builder("ai.chat.requests")
.description("Total AI chat requests")
.register(meterRegistry);
}
public String chatWithMetrics(String message) {
chatCounter.increment();
return chatTimer.record(() ->
chatClient.prompt()
.user(message)
.call()
.content()
);
}
}
7.3 错误处理
@RestControllerAdvice
public class AiExceptionHandler {
@ExceptionHandler(AiException.class)
public ResponseEntity<ErrorResponse> handleAiException(AiException e) {
ErrorResponse error = new ErrorResponse(
"AI_SERVICE_ERROR",
e.getMessage(),
LocalDateTime.now()
);
return ResponseEntity.status(503).body(error);
}
@ExceptionHandler(RateLimitException.class)
public ResponseEntity<ErrorResponse> handleRateLimit(RateLimitException e) {
ErrorResponse error = new ErrorResponse(
"RATE_LIMIT_EXCEEDED",
"请求频率超限,请稍后重试",
LocalDateTime.now()
);
return ResponseEntity.status(429).body(error);
}
}
八、学习资源推荐
8.1 官方文档
- Spring AI官方文档:https://docs.spring.io/spring-ai/reference/
- Spring AI Alibaba:https://sca.aliyun.com/ai/
- 阿里云百炼:https://help.aliyun.com/zh/model-studio/
8.2 学习路线
第1-2周:基础入门
├─ 搭建开发环境
├─ 实现简单对话
└─ 理解核心概念
第3-4周:进阶功能
├─ 流式响应
├─ Function Calling
└─ Embedding向量化
第5-6周:高级特性
├─ RAG检索增强
├─ 向量数据库
└─ 对话记忆
第7-8周:实战项目
├─ 智能客服
├─ 文档助手
└─ 代码生成
第9-10周:生产实践
├─ 性能优化
├─ 安全加固
└─ 监控运维
8.3 实战项目建议
初级项目
- 个人AI助手:日常问答、翻译、写作
- 代码解释器:解释代码片段
- 文本摘要器:长文自动摘要
中级项目
- 智能客服系统:结合业务知识库
- 文档问答系统:RAG实现
- 多模型对比平台:同时调用多个模型
高级项目
- AI Agent系统:自主任务规划
- 企业知识库:大规模文档管理
- 智能数据分析:自动化报告生成
九、知识点总结清单
核心概念
- Spring AI架构理解
- ChatClient API使用
- Prompt工程基础
- Token概念理解
基础功能
- 简单对话实现
- 流式响应实现
- 多模型集成
- 参数调优(temperature、max-tokens等)
进阶特性
- Function Calling
- Embedding向量化
- 相似度计算
- 对话记忆管理
高级应用
- RAG架构实现
- 向量数据库集成
- 提示词模板工程
- 多轮对话管理
企业特性
- 性能优化
- 缓存策略
- 异步处理
- 批量处理
安全运维
- Prompt安全防护
- API Key管理
- 配额控制
- 监控告警
生产部署
- 环境配置管理
- 日志记录
- 错误处理
- 健康检查
学习建议:
- 理论与实践结合,每个知识点都要动手实践
- 从小项目开始,逐步增加复杂度
- 关注官方文档更新,Spring AI还在快速发展中
- 加入社区,参与讨论和贡献
注:
博客:https://blog.csdn.net/badao_liumang_qizhi
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)