Spring AI 架构解析

理解 Spring AI 的整体设计


整体架构图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
┌─────────────────────────────────────────────────┐
│ 应用层 (Your Code) │
│ @Controller / @Service / ChatClient │
└─────────────────────┬───────────────────────────┘

┌─────────────────────▼───────────────────────────┐
│ ChatModel / EmbeddingModel │
│ (模型抽象层,统一接口) │
└─────────────────────┬───────────────────────────┘

┌─────────────────────▼───────────────────────────┐
│ Model Provider 层 │
│ OpenAI / Azure / Anthropic / Ollama / 百度... │
└─────────────────────────────────────────────────┘

核心模块

模块说明
spring-ai-core核心抽象,定义 Model 接口
spring-ai-model-openaiOpenAI 的具体实现
spring-ai-model-anthropicAnthropic (Claude) 实现
spring-ai-model-ollama本地模型实现
spring-ai-starter自动配置

模型抽象层

ChatModel 接口

1
2
3
4
public interface ChatModel {
ChatResponse call(ChatRequest request);
Flux<ChatResponse> stream(ChatRequest request);
}

所有模型实现(OpenAI、Azure、Ollama)都实现此接口,互换成本低。


自动配置原理

spring-ai-starter 通过 spring.factories / META-INF/spring 注册自动配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
@EnableConfigurationProperties(OpenAiProperties.class)
public class OpenAiAutoConfiguration {

@Bean
public OpenAiApi openAiApi(OpenAiProperties properties) {
return new OpenAiApi(properties.getApiKey(), ...);
}

@Bean
public ChatModel openAiChatModel(OpenAiApi api) {
return new OpenAiChatModel(api);
}
}

配置优先级

1
2
3
4
5
6
7
application.yml / application.properties
↓ (覆盖)
application-{profile}.yml
↓ (覆盖)
环境变量 SPRING_AI_OPENAI_API_KEY
↓ (覆盖)
命令行参数 --spring.ai.openai.api-key=xxx