ChatModel
ChatModel
ChatModel是SpringAI调用大模型的底层实现,可以使用ChatModel修改一些模型调用的参数,比如base_url、api_key、temperature、model等。
ChatModel是自动装配的,当ChatModel有多个实现类需要指定,否则会冲突:多模型配置冲突解析
可以使用OpenAiApi和ChatOptions来创建ChatModel;
OpenAiApi可以更改Base_Url,ApiKey;
Options可以更改model、temprature、topP等参数。
OpenAiApi openAiApi = new OpenAiApi("https://api.openai.com/v1", "sk-proj-...");
ChatCompletionModel chatCompletionModel = new ChatCompletionModel(openAiApi);ChatClient
ChatClient是对ChatModel的进一步封装,提供了一个流畅的 API 与 AI 模型的通信。它支持同步和流式编程模式。
ChatClient官方文档
使用
ChatClient 是通过ChatClient.Builder对象创建的,ChatClient.Builder 和 ChatClient 也都是自动装配的,但是依赖ChatModel,所以ChatModel必须存在且唯一。
通过builder创建的ChatClient对象,因为要指定系统提示词等。也可以使用create方法创建,传参传入ChatModel即可。
这就意味着可以使用不同的模型去实现多模型对话。但是注意注入时候要用@Qualifier指定。
// 方式1:使用构造器注入
@Service
public class ChatService {
private final ChatClient chatClient;
public ChatService(ChatClient.Builder builder) {
this.chatClient = builder
.defaultSystem("你是恋爱顾问")
.build();
}
}
// 方式2:使用建造者模式
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultSystem("你是恋爱顾问")
.build();Response
Response是ChatClient的响应对象,可以通过Response获取响应结果。
通过查看源码,看到了有token等信息,可以获取本次对话消耗的token量
// ChatClient支持多种响应格式
// 1. 返回 ChatResponse 对象(包含元数据如 token 使用量)
ChatResponse chatResponse = chatClient.prompt()
.user("Tell me a joke")
.call()
.chatResponse();
// 2. 返回实体对象(自动将 AI 输出映射为 Java 对象)
// 2.1 返回单个实体
record ActorFilms(String actor, List<String> movies) {}
ActorFilms actorFilms = chatClient.prompt()
.user("Generate the filmography for a random actor.")
.call()
.entity(ActorFilms.class);
// 2.2 返回泛型集合
List<ActorFilms> multipleActors = chatClient.prompt()
.user("Generate filmography for Tom Hanks and Bill Murray.")
.call()
.entity(new ParameterizedTypeReference<List<ActorFilms>>() {});
// 3. 流式返回(适用于打字机效果)
Flux<String> streamResponse = chatClient.prompt()
.user("Tell me a story")
.stream()
.content();
// 也可以流式返回ChatResponse
Flux<ChatResponse> streamWithMetadata = chatClient.prompt()
.user("Tell me a story")
.stream()
.chatResponse();还可以给ChatClient设置默认参数,比如系统提示词;还可以在对话中动态更改提示词
// 定义默认系统提示词
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultSystem("You are a friendly chat bot that answers question in the voice of a {voice}")
.build();
// 对话时动态更改系统提示词的变量
chatClient.prompt()
.system(sp -> sp.param("voice", voice))
.user(message)
.call()
.content());此外,还支持指定默认对话选项、默认拦截器、默认函数调用等。
Advisors
Advisors是SpringAI的拦截器,可以通过Advisors拦截对话请求和响应,对对话进行处理。
ChatMemory
ChatMemory是SpringAI的对话记忆组件,可以通过ChatMemory实现对话记忆。
