Spring AI 教程

一、Spring AI 是什么?

一句话概括:Spring AI 是 Spring 官方推出的 AI 框架,让你像操作数据库一样,用统一接口调用大模型(LLM)、向量数据库、嵌入模型等 AI 组件。

核心价值

  • 统一 API:一套代码对接 OpenAI、Azure、Ollama(本地)、阿里通义、智谱等

  • Spring 生态整合 :天然支持 @Autowired、配置注入、starter 自动配置

  • 结构化输出 :将 AI 回复直接映射成 Java 对象(如 UserOrder


二、快速上手(15分钟跑通)

1. 环境准备

  • JDK 17+

  • Spring Boot 3.2+

  • 一个 AI 厂商的 API Key(推荐用 Ollama 本地跑,免费且无需联网)

2. 创建项目

Spring Initializr 选择依赖:

  • Spring Web

  • Spring AI OpenAI(或 Ollama)

3. 配置(以 Ollama 本地为例)

bash 复制代码
spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        model: qwen2.5:7b  # 或 llama3.2

4. 编写最简代码

java 复制代码
@RestController
public class AiController {
    
    @Autowired
    private ChatClient chatClient;  // 核心聊天客户端

    @GetMapping("/ai")
    public String chat(@RequestParam String msg) {
        return chatClient.prompt()
                .user(msg)
                .call()
                .content();
    }
}

启动服务 ,访问 http://localhost:8080/ai?msg=你好,即可收到 AI 回复。


三、核心模块速览

模块 作用 常用类
Spring AI Core 核心抽象(ChatClient、EmbeddingClient) ChatClient, Prompt
Spring AI OpenAI OpenAI / Azure 适配器 OpenAiChatModel
Spring AI Ollama 本地 Ollama 适配器 OllamaChatModel
Spring AI PGVector PostgreSQL 向量存储(RAG) PgVectorStore
Spring AI MCP 模型上下文协议(函数调用) FunctionCallback

四、5个必学核心功能

1. 结构化输出(最实用)

java 复制代码
record Person(String name, int age) {}

Person person = chatClient.prompt()
    .user("介绍一个叫张三的25岁程序员")
    .call()
    .entity(Person.class);  // 直接转成对象

2. 系统提示词(角色设定)

java 复制代码
String response = chatClient.prompt()
    .system("你是资深Spring技术专家,回答必须简洁")
    .user("什么是AOP?")
    .call()
    .content();

3. 流式输出(打字机效果)

java 复制代码
chatClient.prompt()
    .user("写一首诗")
    .stream()
    .content()
    .subscribe(System.out::print);  // 逐字输出

4. RAG(检索增强生成)核心流程

java 复制代码
// 1. 文档加载 → 2. 分块 → 3. 向量化存储 → 4. 相似度检索
@Autowired
VectorStore vectorStore;

public String ragChat(String question) {
    List<Document> docs = vectorStore.similaritySearch(
        SearchRequest.query(question).withTopK(3)
    );
    String context = docs.stream().map(Document::getText).collect(Collectors.joining());
    
    return chatClient.prompt()
        .system("参考以下资料回答:\n" + context)
        .user(question)
        .call()
        .content();
}

5. 函数调用(AI调用外部接口)

java 复制代码
@Bean
public Function<WeatherRequest, WeatherResponse> getWeather() {
    return req -> weatherService.query(req.city());
}

// 调用时自动识别
chatClient.prompt()
    .user("北京天气如何?")
    .functions("getWeather")  // 自动调用
    .call();

五、常见坑与解决方案

问题 解决
连接超时 增加超时配置:spring.ai.openai.chat.options.timeout=60s
中文乱码 检查模型是否支持中文(Ollama 用 qwen 系列)
Token 超限 使用 maxTokens 限制输出长度
返回格式不对 使用 entity() 前先 .call().content() 打印原始返回值检查
本地 Ollama 慢 使用量化版本(如 qwen2.5:7b-q4_0