模型抽象层

ChatModel / EmbeddingModel 接口设计及实现


ChatModel — 对话模型核心接口

1
2
3
4
5
6
7
8
9
10
package org.springframework.ai.model;

public interface ChatModel extends Model {

// 同步调用
ChatResponse call(ChatRequest request);

// 流式调用
Flux<ChatResponse> stream(ChatRequest request);
}

Request / Response 结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ChatRequest 核心字段
public class ChatRequest {
List<Message> messages; // 对话历史
ChatOptions options; // 模型参数 (temperature, maxTokens...)
String model; // 模型名称 (可选)
}

// ChatResponse 核心字段
public class ChatResponse {
String id;
String model;
List<Choice> choices; // 返回的选项
Usage usage; // Token 消耗统计
}

Message 类型

1
2
3
4
5
6
7
8
9
10
11
public interface Message {
String getContent();
Role getRole();
}

public enum Role {
SYSTEM, // 系统提示
USER, // 用户消息
ASSISTANT, // AI 回复
FUNCTION // 函数返回
}

EmbeddingModel — 向量化模型接口

1
2
3
4
5
6
7
public interface EmbeddingModel {

EmbeddingResponse embed(Request<EmbeddingOptions> request);

// 返回向量的维度
int dimensions();
}

使用场景:RAG 的文档向量化存储、相似度搜索。

1
2
3
4
@Autowired
private EmbeddingModel embeddingModel;

float[] vector = embeddingModel.embed("Spring AI 是什么");

主流实现

实现类模型
OpenAiChatModelGPT-4o / GPT-4o-mini
AzureOpenAiChatModelAzure OpenAI
AnthropicChatModelClaude 3/4
OllamaChatModelLlama / Qwen 本地模型
BambuChatModel阿里云通义