SpringAI上

前言

之前学习了python的langchain,一直觉得学得模模糊糊的,本来对python的使用比较陌生,还是干回java老本行吧学起来都要顺手一些
这篇文章是学习springai的上半部分,主要是学习时遇到的问题解决还有自己对springai的理解如有错误请指正

springai项目的搭建问题

在项目初期搭建的时候,配置依赖的时候遇到依赖冲突的问题,我们当前使用的时Spring AI 2.0.1 版本,在构建maven的时候使用的是3.5.11版本进行统一的构建。根据官方参考文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Spring AI 2.0.x 支持 Spring Boot 4.0.x 和 4.1.x。
``
可见Spring AI 2.0.x 支持 Spring Boot 4.0.x 和 4.1.x,同时这里注意,根据官方要求jdk版本在jdk21以上,这里我使用的是jdk21版本
读者如果需要选择合适的版本,需要去官网https://docs.spring.io/spring-ai/reference/getting-started.html查看支持的版本避免出现同样的错误
查看当前springai版本号https://spring.io/projects/spring-ai#overview
同时根据spring官方文档推荐,构建项目时推荐使用BOM统一管理spring-ai的所有子模块的版本
```xml
<!-- Spring AI BOM:统一管理 spring-ai 所有子模块的版本 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

ChatModel理解

ChatModel是springai的一个核心组件,它负责与大模型进行交互,返回模型的响应。在springai中,ChatModel的实现类是ChatOpenAI,它基于OpenAI的API进行交互。
ChatModel源文档

1
2
3
4
5
6
7
public interface ChatModel extends Model<Prompt, ChatResponse>, StreamingChatModel {
default @Nullable String call(String message) {
Prompt prompt = new Prompt(new UserMessage(message));
Generation generation = this.call(prompt).getResult();
return generation != null ? generation.getOutput().getText() : "";
}
}

这里大致分为两块:

  • Prompt: 构建用户的消息,例如用户的提示词 user,系统提示词system同时包括历史消息的构建等
  • ChatModel : 负责将 Prompt 发送给大模型并获取响应。在 Spring AI 中,最常用的实现是 ChatOpenAI(基于 OpenAI API)
  • ChatResponse: 模型响应,封装了模型返回的完整信息
  • Generation: 单个生成结果
  • StreamingChatModel 流式交互
  1. 这里可以看出,ChatModel与大模型进行交互返回模型的响应流程为,Prompt用户提示词,系统提示词,历史记录等进行构建->将构建完成的Prompt交给call 这里核心就是交给ChatResponse
    源码:
    1
    ChatResponse call(Prompt prompt);
  2. 返回的结果由Generation接住
    1
    Generation generation = this.call(prompt).getResult();
  3. 完整示例代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    @Service
    public class ChatService {
    private final ChatModel chatModel;
    private final List<Message> conversationHistory = new ArrayList<>();

    public ChatService(ChatModel chatModel) {
    this.chatModel = chatModel;
    // 初始化系统提示
    conversationHistory.add(new SystemMessage("你是一个友好的AI助手"));
    }

    public String chat(String userMessage) {
    // 添加用户消息到历史
    conversationHistory.add(new UserMessage(userMessage));

    // 构建 Prompt
    Prompt prompt = new Prompt(conversationHistory);

    // 调用模型
    ChatResponse response = chatModel.call(prompt);
    String assistantReply = response.getResult().getOutput().getText();

    // 将 AI 回复添加到历史
    conversationHistory.add(new AssistantMessage(assistantReply));

    return assistantReply;
    }
    }
    由此可以看出,ChatModel进行了整体流程的封装,但是也能看出在实际场景中,使用ChatModel较为复杂,这里由此引出了ChatClient

ChatClient

根据上文,ChatModel的使用很复杂,这里springai为我们提供了封装以后的ChatClient能够更为简单的使用

简单调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
@RequestMapping("/chatClientDemo")
public class ChatClientDemoController {
private final ChatClient chatClient;
//构建ChatModel
public ChatClientDemoController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping
public String msg(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.call()
.content();
}
}

通过配置文件配置多个聊天模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
class ChatClientConfig {

@Bean
ChatClient defaultChatClient(ChatClient.Builder builder) {
return builder.build();
}

@Bean
ChatClient colorChatClient(ChatClient.Builder builder) {
//默认系统提示词
return builder.defaultSystem("You are a color assistant.").build();
}
}

默认元数据支持(这里用户元数据和系统元数据同理)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
class Config {
@Bean
ChatClient chatClient(ChatClient.Builder builder) {
return builder
.defaultSystem(s -> s.text("You are a helpful assistant")
//这里也可以传入param
.metadata("assistantType", "general")
.metadata("version", "1.0"))
.defaultUser(u -> u.text("Default user context")
.metadata("sessionId", "default-session"))
.build();
}
}

提示词模板与消息类型(基础知识)

Spring AI 中一次对话的最小单元是 Message,一共有三种角色:

  • SystemMessage:系统提示词,定义 AI 的身份和行为边界
  • UserMessage:用户输入
  • AssistantMessage:AI 的回复,主要用在多轮对话的历史记录里

Prompt 就是这些消息的有序集合。除此之外 Spring AI 还提供了 PromptTemplate 做提示词模板,把”提示词结构”和”动态数据”分开管理,避免字符串拼接拼出一堆 bug:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Service
public class PromptTemplateService {
private final PromptTemplate promptTemplate;

public PromptTemplateService() {
this.promptTemplate = new PromptTemplate("""
你是一名资深Java工程师。
请用通俗的语言解释下面的概念:{concept}
面向的读者水平:{level}
""");
}

public String explain(String concept, String level) {
Prompt prompt = promptTemplate.create(Map.of(
"concept", concept,
"level", level
));
return chatModel.call(prompt).getResult().getOutput().getText();
}
}

{concept}、{level} 就是占位符,create() 的时候传 Map 填充。提示词写长了以后维护模板比到处 String.format 舒服很多。

多模态消息(图片输入)

大模型不只能处理文字,UserMessage 支持携带附件(Media),最常用的就是传图片让模型看图说话:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Service
public class MultiModalService {
private final ChatModel chatModel;

public MultiModalService(ChatModel chatModel) {
this.chatModel = chatModel;
}

public String describeImage(String imageUrl, String question) {
Media media = Media.builder()
.mimeType(MimeTypeUtils.IMAGE_PNG)
.url(imageUrl) // 也支持 base64 data URL 或本地资源
.build();

UserMessage userMessage = new UserMessage(question, List.of(media));
Prompt prompt = new Prompt(List.of(userMessage));

return chatModel.call(prompt).getResult().getOutput().getText();
}

调用:

1
2
3
4
String result = describeImage(
"https://example.com/cat.png",
"这张图片里有什么?详细描述一下颜色和构图"
);

Media 同样可以传音频、视频,关键是 mimeType 要标对,标错了模型会直接报格式错误。

ChatMemory 会话记忆(以及最大的坑)

上文 ChatService 手动维护 List<Message> 实现多轮对话,能跑,但代码很丑还容易出问题。Spring AI 提供了 ChatMemory 帮我们管理历史:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
public class ChatMemoryConfig {

@Bean
public ChatMemory chatMemory() {
// MessageWindowChatMemory:保留窗口内最近的 N 条消息,超出自动丢弃最早的
return MessageWindowChatMemory.builder()
.maxMessages(20)
.build();
}

@Bean
public ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultSystem("你是一个友好的AI助手")
.defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory))
.build();
}
}

Controller 层:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
public class MemoryChatController {
private final ChatClient chatClient;

public MemoryChatController(ChatClient chatClient) {
this.chatClient = chatClient;
}

@GetMapping("/chat")
public String chat(@RequestParam String sessionId,
@RequestParam String message) {
return chatClient.prompt()
.user(message)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, sessionId))
.call()
.content();
}
}

坑:ChatMemory 是按 conversationId(sessionId)组织记忆的,不传 sessionId 时所有请求都会落到默认会话里。多用户场景下不传 sessionId,A 用户和 B 用户的对话会互相”看到”,轻则上下文混乱,重则泄露他人对话内容。多人共用的服务一定要把用户ID当 sessionId 传进去。

另外 MessageWindowChatMemory 只是内存实现,应用重启记忆就没了。生产环境要么自己基于 ChatMemoryRepository 接口实现 JDBC/Redis 版本,要么接受”重启即失忆”。

Tool Calling 函数调用(核心重点)

Tool Calling(有的地方叫 Function Calling)是让大模型调用你写的 Java 方法的能力——模型不生成答案,而是生成”我要调用 getWeather(北京)”的指令,Spring AI 负责真正执行方法,再把结果喂回模型生成最终回答。

Spring AI 1.0 之后推荐用 @Tool 注解定义工具:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class WeatherTools {

@Tool(description = "查询指定城市的实时天气,city参数为城市中文名,例如:北京")
public String getWeather(String city) {
// 真实场景里调用天气API
return switch (city) {
case "北京" -> "晴,气温 22°C";
case "成都" -> "多云,气温 20°C";
default -> "未找到该城市天气信息";
};
}

@Tool(description = "查询列车时刻表,参数from为出发城市,to为到达城市")
public List<String> queryTrain(String from, String to) {
return List.of(
"G1234 " + from + " 08:00 → " + to + " 12:30",
"G5678 " + from + " 14:00 → " + to + " 18:20"
);
}
}

挂载到 ChatClient:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Service
public class WeatherChatService {
private final ChatClient chatClient;

public WeatherChatService(ChatClient.Builder builder, WeatherTools weatherTools) {
this.chatClient = builder
.defaultSystem("你是一个出行助手,必须使用提供的工具查询真实数据")
.defaultTools(weatherTools) // 也可以调用时动态传 .tools(weatherTools)
.build();
}

public String ask(String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}

问”北京今天天气怎么样,帮我查一下去上海的高铁”,模型会自动连续调用 getWeather 和 queryTrain 两个工具,最后把结果组织成自然语言回复。

几个容易踩的点:

  1. 工具描述(description)就是模型的说明书。模型决定调不调用、传什么参数,全靠 description 和参数名。描述写得含糊,模型就会瞎调或者干脆不调。
  2. 工具执行是 Spring AI 干的,不是模型干的。模型只输出调用意图,真正的 Java 方法调用在你本地执行,有副作用的工具(写数据库、删文件)一定要做好防护。
  3. 返回值会被序列化成 JSON 喂回模型。返回复杂对象可以,但字段越乱模型越难理解,尽量返回结构清晰的数据。
  4. 模型不一定每次都调用工具。是否调用由模型自行判断,重要场景要靠提示词强调”必须查询工具获取实时数据”。

结构化输出(核心)

默认拿到的都是纯文本,想要直接得到 Java 对象,用 entity():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public record Weather(String city, String condition, int temperature) {}

@Service
public class StructuredOutputService {
private final ChatClient chatClient;

public StructuredOutputService(ChatClient.Builder builder) {
this.chatClient = builder
.defaultSystem("你是天气播报员,输出天气信息")
.build();
}

public Weather getWeather(String city) {
return chatClient.prompt()
.user("查询{0}今天的天气", city)
.call()
.entity(Weather.class); // 直接反序列化成 record
}
}

它的原理并不神秘:entity(Weather.class) 时,Spring AI 会用 BeanOutputConverter 生成一段 JSON 格式说明(包含每个字段名和类型)拼进提示词,要求模型只输出符合该结构的 JSON,拿到回复后再 Jackson 反序列化。

所以这里也有个坑:record 字段名最好有意义。字段叫 a、b、c 的话,模型不知道哪个对应哪个语义,容易张冠李戴。如果一次 entity() 反序列化失败,Spring AI 会把错误信息和原始格式要求再发给模型重试一次,这个自动重试机制默认是开着的。

Advisor 机制(进阶核心,类比 AOP)

Advisor 是 Spring AI 里我认为最有设计感的部分,定位类似 Spring MVC 的拦截器 / AOP 的环绕通知:在 Prompt 发给模型之前、响应返回之后插入自定义逻辑,用于实现日志、审计、RAG 检索、记忆注入等横切功能。

前面用到的 MessageChatMemoryAdvisor 就是官方实现——它把 ChatMemory 里的历史消息自动拼进 Prompt,所以多轮对话才能记住上下文。

自己写一个日志 Advisor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class LoggingAdvisor implements CallAdvisor {

private static final Logger log = LoggerFactory.getLogger(LoggingAdvisor.class);

@Override
public ChatResponse adviseCall(ChatRequest request, CallAdvisorChain chain) {
long start = System.currentTimeMillis();

// 打印发给模型的消息
request.getInstructions().forEach(m ->
log.info("[{}] {}", m.getMessageType(), m.getText()));

// 放行到下一个环节(可能是其他 Advisor,最终到 ChatModel)
ChatResponse response = chain.nextCall(request);

long cost = System.currentTimeMillis() - start;
log.info("耗时: {}ms, tokens: {}", cost,
response.getMetadata().getUsage());

return response;
}

@Override
public int getOrder() {
return 0; // 值越小越靠近请求方向,越大越靠近模型
}
}

挂载:

1
2
3
4
5
chatClient.prompt()
.user("你好")
.advisors(new LoggingAdvisor())
.call()
.content();

调用链是这样的:你的 Advisor →(可能存在的其他 Advisor)→ ChatModel → 原路返回。多个 Advisor 按 getOrder() 排序形成责任链,这就是 RAG(检索增强生成)在 Spring AI 里的标准实现方式——官方的 QuestionAnswerAdvisor 就是在调用前检索知识库、把相关文档塞进 Prompt。

流式输出(SSE)

长回答如果等完整生成完再返回,用户体验很差。流式返回用 stream():

1
2
3
4
5
6
7
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> stream(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.stream()
.content(); // 返回 Flux<String>,逐块推送
}

前端用 EventSource 或 fetch + ReadableStream 接收即可。

坑:stream() 返回的是 Reactor 的 Flux,要求项目里有 WebFlux 依赖。传统 Spring MVC(Servlet 栈)项目需要额外引入 spring-boot-starter-webflux,且 Controller 返回 Flux 时 Spring MVC 会自动切换到异步处理模式。另外流式接口一定要设置合理的超时,模型卡住时不然连接会一直挂着。

项目搭建与配置踩坑合集

把学习过程中踩过的坑汇总一下:

1. 版本对应问题(开头提过,再强调一次)

Spring AI 版本必须和 Spring Boot、JDK 版本对齐,错配的典型症状是启动报 NoSuchMethodError 或依赖冲突。对照官方 compatibility 页面选版本,BOM 统一管理子模块版本,不要手动给每个 spring-ai 依赖写 version。

2. 配置文件写法

1
2
3
4
5
6
7
8
9
spring:
ai:
openai: # 换成其他供应商就是 alibaba / ollama 等对应前缀
api-key: ${AI_API_KEY} # 密钥走环境变量,不要硬编码
base-url: https://api.openai.com/ # 国内中转/代理改这里
chat:
options:
model: gpt-4o-mini
temperature: 0.7

三个要点:api-key 必须用 ${} 引环境变量;换供应商(通义、DeepSeek、Ollama 本地模型)主要就是换依赖 + 换这个配置前缀,代码层 ChatModel、ChatClient 的抽象完全不用动——这是 Spring AI 抽象做得好的地方;base-url 国内直连经常超时,中转服务改这里。

3. @Tool 方法注册后没生效

检查工具类有没有加 @Component(或手动 new 传入),以及调用处 .tools() / defaultTools() 有没有挂上。另外模型侧要开启工具能力,部分国产模型的兼容接口不支持 tools 字段,调用会直接报错。

4. 中文乱码

接口直接返回中文偶发乱码,一般是 Web 层响应没指定 produces = "text/plain;charset=UTF-8",和 Spring AI 本身无关,但用它写 Demo 接口时经常撞上。

5. token 超限

历史消息越攒越长,MessageWindowChatMemory 不设 maxMessages 的话,聊久了必然超出模型上下文窗口报 400 错误。窗口大小要根据模型的上下文长度留好余量。

小结

到这里 Spring AI 的核心链路就过了一遍:ChatModel(底层交互)→ ChatClient(流式 API 封装)→ Advisor(横切增强)→ ChatMemory(会话记忆)/ Tool Calling(工具调用)/ 结构化输出。

整体感觉 Spring AI 相比 LangChain 的 Java 端各种轮子,抽象层次更清晰:模型层用接口隔离不同供应商,换厂商不改业务代码;Advisor 的责任链设计把 RAG、记忆、审计这些横切能力解耦得很干净。后续有时间再写下半部分,把 RAG(向量库 + 检索)和多模型编排的内容补上。

参考资料

Springai文档

版权声明:本文为原创文章,转载请注明出处。

更新日志:

  • 2026-10-26:补充完整版:提示词模板、多模态、ChatMemory、Tool Calling、结构化输出、Advisor机制、流式输出及踩坑合集
  • 2026-08-12:初版发布