惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
罗磊的独立博客
S
SegmentFault 最新的问题
V
V2EX
V
Visual Studio Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
美团技术团队
博客园 - 三生石上(FineUI控件)
Stack Overflow Blog
Stack Overflow Blog
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
D
Docker
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
M
Microsoft Research Blog - Microsoft Research
Martin Fowler
Martin Fowler
S
Secure Thoughts
B
Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog
C
Cisco Blogs
C
CERT Recently Published Vulnerability Notes
T
True Tiger Recordings
GbyAI
GbyAI
P
Proofpoint News Feed
P
Privacy International News Feed
Jina AI
Jina AI
The Cloudflare Blog
I
Intezer
AWS News Blog
AWS News Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Security Archives - TechRepublic
NISL@THU
NISL@THU
The Register - Security
The Register - Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
P
Palo Alto Networks Blog
S
Schneier on Security
L
LINUX DO - 热门话题
C
CXSECURITY Database RSS Feed - CXSecurity.com
Security Latest
Security Latest
C
Cybersecurity and Infrastructure Security Agency CISA

掘金

“杀!杀!杀!”、“我最讨厌事后道歉”——骂“杀哥”之前,谁还没当过情绪崩溃的人 juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn Crawlee StagehandCrawler:自然语言点 Load More 的工程化爬虫 juejin.cn juejin.cn juejin.cn juejin.cn 人人都在鼓吹的OPC,我想给你泼盆冷水 juejin.cn juejin.cn juejin.cn Redis内存用爆了,原来我们都忽略了这个配置 juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn Android 专家岗 Kotlin 面试题:能答出这些,说明你对语言设计有自己的理解 juejin.cn juejin.cn 业务系统集成 OpenClaw 多 Agent 方案:从架构到落地的完整指南 juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn 四、Agent 评估与可观测性:LangSmith 与客服 A/B 测试 🍃 MongoDB 从入门到上手:一篇写给新手的科普指南 juejin.cn juejin.cn juejin.cn juejin.cn RAG 系列(十九):增量更新——知识库如何保持新鲜 juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn 当 00 后开始用 token 给学校送礼 juejin.cn SwiftUI 多线程与并发编程深度总结 juejin.cn juejin.cn juejin.cn Combine 架构模式:构建响应式应用的蓝图 Combine 高级实践:多线程调度、调试与测试 SSE(Server-Sent Events)完全指南 juejin.cn juejin.cn juejin.cn 阿里云峰会 Agent Native 基础设施专场邀您参加! juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn TRAE SOLO 移动版的安装与测试 juejin.cn Vue 的 template 标签不能用 v-show?底层机制+踩坑复盘+生产级解决方案 juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn everything-claude-code 在 Codex 的应用:不要照搬全家桶,而是做一套更聪明的增强层 juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn juejin.cn 阻塞队列之SynchronousQueue juejin.cn juejin.cn 小程序成长计划正式接入Hy3 preview juejin.cn juejin.cn juejin.cn juejin.cn
一文搞懂 Spring AI 核心接口,轻松对接所有大模型
行走的蜗牛 · 2026-05-17 · via 掘金

一、Spring AI 核心设计理念是什么?

简单说,它就是 Spring 官方为 Java 开发者打造的 AI 应用开发框架

它借鉴了 LangChain 等 Python 项目的设计思路,但更强调 Spring 生态的核心哲学:可移植性、模块化设计、约定优于配置

不同 AI 厂商的 API 千差万别,切换模型往往意味着重写大片调用代码。Spring AI 的解法是:定义一套统一的抽象接口,让不同厂商去实现它。业务代码只依赖抽象层,底层模型切换时,代码零改动。

本文目标:从顶层 ChatClient 到底层 Model,逐层拆解 Spring AI 的核心接口设计,帮你彻底理清这套"万能转接头"的工作原理。


二、最底层:Generic Model API(通用模型 API)

这是整个 Spring AI 的基石,定义了与 AI 模型交互的最基本规范。

1. Model 接口

public interface Model<TReq extends ModelRequest<?>, TRes extends ModelResponse<?>> {
    TRes call(TReq request);
}

这是所有模型接口的顶级父接口。无论是聊天、文生图还是嵌入模型,都继承自它。

2. StreamingModel 接口

public interface StreamingModel<TReq extends ModelRequest<?>, TResChunk extends ModelResponse<?>> {
    Flux<TResChunk> stream(TReq request);
}

提供流式响应能力,返回 Reactor 的 Flux,支持打字机效果。

3. ModelRequest 接口

封装请求参数,包含指令(Instructions)和模型选项(ModelOptions)两部分。

4. ModelResponse 接口

封装响应结果,包含主要输出、结果列表和响应元数据(如 token 使用量)。


三、核心业务接口

1. ChatModel —— 聊天模型接口

这是最常用的接口,负责与 LLM 进行对话交互。

public interface ChatModel extends Model<Prompt, ChatResponse> {
    default String call(String message) {
        // 简化调用,实际返回完整响应
    }
    
    ChatResponse call(Prompt prompt);
    Flux<ChatResponse> stream(Prompt prompt);
}

大白话解释ChatModel 就是一个"智能对话机器人",你给它发消息,它回复你答案。

使用示例

@Resource
private ChatModel chatModel;

public String chat(String msg) {
    return chatModel.call(msg);
}

自动配置原理:不同的 AI 厂商各自提供 Starter 依赖和自动配置类来实现这个接口:

Starter 依赖自动配置类所需配置项
spring-ai-alibaba-starter-dashscopeDashScopeChatAutoConfigurationspring.ai.dashscope.api-key
spring-ai-starter-model-openaiOpenAiChatAutoConfigurationspring.ai.openai.api-key

切换模型只需改依赖和配置,业务代码零改动。

2. EmbeddingClient —— 嵌入模型接口

将文本转换为向量,是 RAG(检索增强生成)的基础。

public interface EmbeddingClient extends Model<EmbeddingRequest, EmbeddingResponse> {
    List<Double> embed(String text);
    EmbeddingResponse embedForResponse(List<String> texts);
}

典型应用:将用户问题和知识库文档都转换成向量,通过相似度检索相关内容。

3. ImageModel —— 图像生成接口

用于文本生成图片。

public interface ImageModel extends Model<ImageGenerationRequest, ImageGenerationResponse> {
    ImageGenerationResponse call(ImageGenerationRequest request);
}

4. AudioModel —— 音频处理接口

支持语音转文字(STT)和文字转语音(TTS)。

public interface SpeechModel extends Model<SpeechPrompt, SpeechResponse> {
    SpeechResponse call(SpeechPrompt request);
}

public interface TranscriptionModel extends Model<TranscriptionPrompt, TranscriptionResponse> {
    TranscriptionResponse call(TranscriptionPrompt request);
}

四、数据层接口

1. VectorStore —— 向量数据库接口

这是做 RAG 的核心接口,抽象了所有向量数据库的操作。

public interface VectorStore {
    void add(List<Document> documents);
    List<Document> similaritySearch(SearchRequest request);
}

支持的主流向量数据库包括:PGVector、Milvus、Chroma、Pinecone、Qdrant、Redis、Elasticsearch 等。

2. Document —— 文档抽象

表示一个待处理的文档,包含内容和元数据。

public class Document {
    private String id;
    private String content;
    private Map<String, Object> metadata;
    // getters/setters
}

配合 ETL 框架,可以从 PDF、Markdown、HTML 等格式读取文档。


五、高级 API 接口

1. ChatClient —— 流式 API(强推)

这是构建在 ChatModel 之上的高级 API,提供链式调用,用起来非常舒服。

String response = chatClient.prompt()
    .system("你是一个专业的Java助手")
    .user("介绍一下Spring AI")
    .call()
    .content();

对比理解

  • ChatModel = 功能手机(能打电话就行)
  • ChatClient = 智能手机(自带通讯录、应用商店、相机)

2. CallAdvisor —— 顾问接口

拦截和增强 AI 交互,封装常见模式。

public interface CallAdvisor {
    ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain);
    int getOrder();  // 控制执行顺序
}

内置顾问类型

  • 对话记忆顾问:自动维护多轮对话上下文
  • RAG 顾问:自动检索相关知识库
  • 日志顾问:记录请求/响应日志

3. 函数调用接口(Function Calling)

允许 AI 模型主动调用你注册的工具函数。

@Bean
public ToolCallback weatherTool() {
    return FunctionToolCallback.builder("getWeather", (Request request) -> {
        return "15.0°C";  // 返回天气信息
    })
    .description("获取指定地点的天气")
    .inputType(Request.class)
    .build();
}

这让模型不光能"说",还能真正"做"事情——查数据库、调 API、执行业务逻辑。

4. ETL 相关接口

DocumentReader:从各种源读取文档

public interface DocumentReader {
    List<Document> read();
}

DocumentTransformer:文档转换和分块

public interface DocumentTransformer {
    List<Document> transform(List<Document> documents);
}

DocumentWriter:将处理后的文档写入向量存储

public interface DocumentWriter {
    void accept(List<Document> documents);
}

六、一张图看懂 Spring AI 接口体系

image.png Spring AI 的接口设计采用经典的五层架构,每一层都有明确的职责边界:

层级名称核心接口一句话职责
L1开发者使用层ChatClient给你最丝滑的编码体验
L2高级能力层CallAdvisorFunction Calling、ETL 接口封装 AI 应用中的常见模式
L3核心抽象层ChatModelEmbeddingClientVectorStore按功能领域划分的核心能力
L4基础层ModelStreamingModelModelRequestModelResponse定义所有模型调用的统一规范
L5厂商实现层OpenAI、通义千问、Anthropic 等实现可插拔,按需引入

七、总结

三条核心链路

场景调用链路
简单对话ChatClient → ChatModel → Model → 厂商实现
RAG 问答ChatClient → CallAdvisor → VectorStore → ChatModel → Model → 厂商实现
函数调用ChatClient → Function Calling → ChatModel → Model → 厂商实现

设计精髓

  1. 接口与实现分离:L1-L4 定义"是什么",L5 负责"怎么做"
  2. 自动配置驱动:引入 Starter 后,Spring Boot 自动装配正确的实现类
  3. 可观测性内置:每一层都可插拔日志、监控、追踪能力
  4. Java 生态优先:拥抱 Reactor 响应式编程,与 Spring 生态无缝集成