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();
}
}

参考资料

Springai文档

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

更新日志

  • 2026-08-12:初版发布