Spring AI Alibaba 1.1.2.2 完整知识点库

第一章:项目基础

1.1 项目元数据

属性 说明
GroupId com.alibaba.cloud.ai Maven坐标
ArtifactId spring-ai-alibaba 项目名称
Version 1.1.2.2 当前版本
Packaging pom 聚合项目
JDK 17+ 最低JDK版本
Spring Boot 3.5.8 基础框架版本
Spring AI 1.1.2 AI框架版本
DashScope SDK 2.15.1 阿里云SDK版本

1.2 源码目录结构

复制代码
spring-ai-alibaba-1.1.2.2/
├── pom.xml                              # 父POM
├── spring-ai-alibaba-bom/               # BOM模块
│   └── pom.xml
├── spring-ai-alibaba-graph-core/        # 状态图核心
│   ├── pom.xml
│   └── src/main/java/com/alibaba/cloud/ai/graph/
│       ├── StateGraph.java              # 状态图定义
│       ├── CompiledGraph.java           # 编译后图
│       ├── OverAllState.java            # 状态容器
│       ├── CompileConfig.java           # 编译配置
│       ├── action/                      # 动作定义
│       │   ├── NodeAction.java
│       │   ├── AsyncNodeAction.java
│       │   ├── EdgeAction.java
│       │   └── Command.java
│       ├── checkpoint/                  # 检查点
│       │   ├── BaseCheckpointSaver.java
│       │   ├── Checkpoint.java
│       │   └── savers/
│       ├── internal/                    # 内部实现
│       │   ├── node/
│       │   └── edge/
│       ├── serializer/                  # 序列化
│       │   ├── StateSerializer.java
│       │   └── plain_text/
│       ├── state/                       # 状态管理
│       │   ├── AgentStateFactory.java
│       │   ├── KeyStrategy.java
│       │   └── strategy/
│       ├── store/                       # 存储
│       │   ├── Store.java
│       │   └── stores/
│       └── observation/                 # 可观测性
├── spring-ai-alibaba-agent-framework/   # Agent框架
│   └── src/main/java/com/alibaba/cloud/ai/graph/agent/
│       ├── ReactAgent.java              # ReAct代理
│       ├── BaseAgent.java               # 代理基类
│       ├── Agent.java                   # 代理接口
│       ├── Builder.java                 # 构建器接口
│       ├── hook/                        # 钩子
│       │   ├── Hook.java
│       │   ├── AgentHook.java
│       │   └── modelcalllimit/
│       ├── interceptor/                 # 拦截器
│       │   ├── Interceptor.java
│       │   ├── ModelInterceptor.java
│       │   └── toolretry/
│       ├── node/                        # 节点
│       │   ├── AgentLlmNode.java
│       │   └── AgentToolNode.java
│       ├── tool/                        # 工具
│       │   ├── AsyncToolCallback.java
│       │   └── StateAwareToolCallback.java
│       └── flow/                        # 流程编排
├── spring-ai-alibaba-studio/            # Studio模块
│   └── src/main/java/com/alibaba/cloud/ai/agent/studio/
├── spring-ai-alibaba-sandbox/           # 沙箱
│   └── src/main/java/com/alibaba/cloud/ai/sandbox/
├── spring-ai-alibaba-admin/             # Admin模块
│   ├── spring-ai-alibaba-admin-server-core/
│   ├── spring-ai-alibaba-admin-server-openapi/
│   ├── spring-ai-alibaba-admin-server-runtime/
│   └── spring-ai-alibaba-admin-server-start/
└── spring-boot-starters/                # Starters
    ├── spring-ai-alibaba-starter-a2a-nacos/
    ├── spring-ai-alibaba-starter-config-nacos/
    ├── spring-ai-alibaba-starter-graph-observation/
    ├── spring-ai-alibaba-starter-builtin-nodes/
    └── spring-ai-alibaba-starter-agentscope/

1.3 核心依赖关系

复制代码
spring-ai-alibaba (Parent)
    ├── spring-ai-alibaba-bom
    │       └── 管理所有子模块版本
    ├── spring-ai-alibaba-graph-core
    │       ├── spring-ai-core (Spring AI)
    │       ├── dashscope-sdk-java (阿里云)
    │       └── reactor-core (响应式)
    ├── spring-ai-alibaba-agent-framework
    │       ├── spring-ai-alibaba-graph-core
    │       └── spring-ai-core
    └── spring-boot-starters/*
            └── 对应核心模块 + Spring Boot

第二章:架构设计

2.1 分层架构

复制代码
┌────────────────────────────────────────────────────────────┐
│  Layer 4: Application Layer                                │
│  - Admin管理后台                                            │
│  - Studio可视化IDE                                          │
│  - Sandbox代码执行                                          │
└────────────────────────────────────────────────────────────┘
                              ↓
┌────────────────────────────────────────────────────────────┐
│  Layer 3: Framework Layer                                   │
│  ┌─────────────────────┐  ┌─────────────────────┐         │
│  │ Agent Framework     │  │ Graph Core          │         │
│  │ - ReactAgent        │  │ - StateGraph        │         │
│  │ - Hooks             │  │ - CompiledGraph     │         │
│  │ - Interceptors      │  │ - Checkpoint        │         │
│  └─────────────────────┘  └─────────────────────┘         │
└────────────────────────────────────────────────────────────┘
                              ↓
┌────────────────────────────────────────────────────────────┐
│  Layer 2: Integration Layer                                 │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐       │
│  │  A2A     │ │  Config  │ │  Graph   │ │ Builtin  │       │
│  │  Nacos   │ │  Nacos   │ │  Observe │ │  Nodes   │       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘       │
└────────────────────────────────────────────────────────────┘
                              ↓
┌────────────────────────────────────────────────────────────┐
│  Layer 1: Foundation Layer                                  │
│  - Spring AI Core                                           │
│  - DashScope SDK                                            │
│  - Spring Boot                                              │
│  - Reactor                                                  │
└────────────────────────────────────────────────────────────┘

2.2 核心组件交互

复制代码
User Request
     ↓
Controller (Spring Web)
     ↓
Service Layer
     ↓
ReactAgent / ChatClient
     ↓
┌─────────────┐    ┌─────────────┐
│  AgentLlmNode│←→→│ AgentToolNode│
└─────────────┘    └─────────────┘
     ↓                    ↓
ChatModel            ToolCallback
     ↓                    ↓
DashScope API        External API

2.3 数据流

复制代码
Input (String/Map)
     ↓
Prompt (Spring AI)
     ↓
Request (DashScope SDK)
     ↓
HTTP Client
     ↓
DashScope Server
     ↓
Response (JSON)
     ↓
ChatResponse/EmbeddingResponse
     ↓
Output (String/Vector)

第三章:核心模块详解

3.1 spring-ai-alibaba-graph-core

3.1.1 核心类全览
类名 类型 路径 职责 线程安全
StateGraph Class graph/StateGraph.java 状态图定义 构建后只读
CompiledGraph Class graph/CompiledGraph.java 编译后执行
OverAllState Class graph/OverAllState.java 状态容器
CompileConfig Class graph/CompileConfig.java 编译配置
Node Class internal/node/Node.java 节点定义
Edge Class internal/edge/Edge.java 边定义
NodeAction Interface action/NodeAction.java 节点动作 -
EdgeAction Interface action/EdgeAction.java 边动作 -
BaseCheckpointSaver Interface checkpoint/BaseCheckpointSaver.java 检查点存储 -
StateSerializer Interface serializer/StateSerializer.java 状态序列化 -
KeyStrategy Interface state/KeyStrategy.java 状态策略 -
Store Interface store/Store.java 存储接口 -
3.1.2 StateGraph详解

类定义:

java 复制代码
public class StateGraph {
    // 常量定义
    public static final String END = "__END__";
    public static final String START = "__START__";
    public static final String ERROR = "__ERROR__";
    
    // 核心属性
    final Nodes nodes = new Nodes();
    final Edges edges = new Edges();
    private final KeyStrategyFactory keyStrategyFactory;
    private final StateSerializer stateSerializer;
    private final String name;
    
    // 构造方法
    public StateGraph(String name, KeyStrategyFactory keyStrategyFactory, StateSerializer stateSerializer)
}

核心方法:

java 复制代码
// 添加节点
public StateGraph addNode(String id, NodeAction action)
public StateGraph addNode(String id, AsyncNodeAction action)
public StateGraph addNode(String id, AsyncNodeActionWithConfig action)
​
// 添加边
public StateGraph addEdge(String sourceId, String targetId)
​
// 添加条件边
public StateGraph addConditionalEdges(String sourceId, EdgeAction condition, String... targets)
public StateGraph addConditionalEdges(String sourceId, EdgeAction condition, Map<String, String> mappings)
​
// 编译
public CompiledGraph compile()
public CompiledGraph compile(CompileConfig compileConfig)

内部类:

java 复制代码
// 节点集合
public static class Nodes implements Iterable<Node> {
    private final LinkedHashMap<String, Node> elements = new LinkedHashMap<>();
    
    public Optional<Node> get(String id)
    public boolean has(String id)
    public Stream<Node> stream()
}
​
// 边集合
public static class Edges implements Iterable<Edge> {
    private final List<Edge> elements = new ArrayList<>();
}
3.1.3 CompiledGraph详解

执行流程:

复制代码
1. 接收输入Map
2. 初始化OverAllState
3. 找到START节点
4. while循环执行:
   a. 通过ActionFactory创建NodeAction
   b. 执行NodeAction.apply(state)
   c. 获取输出并更新state
   d. 通过Edge决定下一个节点
   e. 检查是否到达END或ERROR
   f. 检查迭代次数限制
5. 返回GraphResponse

线程安全机制:

java 复制代码
// 使用Factory而非实例,确保每次执行创建新实例
final Map<String, Node.ActionFactory> nodeFactories = new LinkedHashMap<>();
​
// 执行时动态创建
AsyncNodeActionWithConfig action = factory.apply(compileConfig);
3.1.4 检查点存储实现清单
实现类 存储介质 适用场景 持久化
MemorySaver ConcurrentHashMap 开发测试
FileSystemSaver 本地文件 单机部署
RedisSaver Redis 分布式
MysqlSaver MySQL 企业应用
PostgresSaver PostgreSQL 企业应用
OracleSaver Oracle 企业应用
MongoSaver MongoDB 文档存储
3.1.5 序列化实现
实现类 格式 特点
SpringAIJacksonStateSerializer JSON 默认,跨语言兼容
ObjectStreamStateSerializer Java二进制 Java内部高效

3.2 spring-ai-alibaba-agent-framework

3.2.1 Agent类层次
复制代码
Agent (Abstract)
    ↑
BaseAgent (Abstract)
    ↑
ReactAgent (Concrete)

Agent:

java 复制代码
public abstract class Agent {
    protected final String name;
    protected final String description;
    
    public abstract Node asNode();
}

BaseAgent:

java 复制代码
public abstract class BaseAgent extends Agent {
    protected String inputSchema;
    protected Type inputType;
    protected String outputSchema;
    protected Class<?> outputType;
    protected String outputKey;
    protected KeyStrategy outputKeyStrategy;
    protected boolean includeContents;
    protected boolean returnReasoningContents;
}

ReactAgent:

java 复制代码
public class ReactAgent extends BaseAgent {
    private final ConcurrentMap<String, Map<String, Object>> threadIdStateMap;
    private final AgentLlmNode llmNode;
    private final AgentToolNode toolNode;
    private List<? extends Hook> hooks;
    private List<ModelInterceptor> modelInterceptors;
    private List<ToolInterceptor> toolInterceptors;
    private String instruction;
    private StateSerializer stateSerializer;
    private final Boolean hasTools;
}
3.2.2 ReAct执行循环
复制代码
User Input
    ↓
[Loop Start]
    ↓
AgentLlmNode.call(state)
    ↓
LLM Generate Response
    ↓
[Has Tool Calls?]
    ├─ Yes → AgentToolNode.call(state)
    │           ↓
    │       Execute Tools
    │           ↓
    │       Update State with Results
    │           ↓
    │       [Continue Loop]
    │
    └─ No → Return AssistantMessage
                  ↓
              [Loop End]
3.2.3 节点类型
节点类 职责 输入 输出
AgentLlmNode 调用LLM生成响应 messages, tools assistant_message, tool_calls
AgentToolNode 执行工具调用 tool_calls tool_results
3.2.4 Hook类型全览
HOOK接口 触发时机 用途
AgentHook Agent启动/结束 资源初始化/清理
ModelHook 模型调用前后 请求/响应修改
InstructionAgentHook 指令处理 动态提示词
MessagesAgentHook 消息处理 消息拦截修改
HumanInTheLoopHook 人机交互点 人工审核
SummarizationHook 上下文压缩 Token优化
ToolInjection 工具注入 动态工具
TokenCounter Token计算 用量监控
3.2.5 拦截器类型全览

模型拦截器:

拦截器 功能 优先级
ModelRetryInterceptor 失败重试 HIGH
ModelFallbackInterceptor 模型降级 MEDIUM
ContextEditingInterceptor 上下文编辑 NORMAL
SkillsInterceptor 技能注入 NORMAL

工具拦截器:

拦截器 功能 优先级
ToolRetryInterceptor 工具重试 HIGH
ToolErrorInterceptor 错误处理 MEDIUM
ToolSelectionInterceptor 工具选择 NORMAL
TodoListInterceptor 任务列表 LOW

第四章:接口与抽象体系

4.1 Spring AI标准接口

4.1.1 Model接口体系
java 复制代码
// 顶层模型接口
public interface Model<TReq extends ModelRequest<?>, TRes extends ModelResponse<?>> {
    TRes call(TReq request);
    Flux<TRes> stream(TReq request);
}

// 对话模型
public interface ChatModel extends Model<Prompt, ChatResponse> {
    // 继承call和stream
}

// 嵌入模型
public interface EmbeddingModel extends Model<EmbeddingRequest, EmbeddingResponse> {
    default float[] embed(String text);
    default float[] embed(Document document);
}

// 图像模型
public interface ImageModel extends Model<ImagePrompt, ImageResponse> {
}
4.1.2 Prompt相关类
java 复制代码
// 提示词
public class Prompt implements ModelRequest<List<Message>> {
    private final List<Message> messages;
    private final ChatOptions modelOptions;
}

// 消息类型
public interface Message {
    String getContent();
    MessageType getMessageType();
}

// 具体消息类型
public class UserMessage implements Message
public class AssistantMessage implements Message
public class SystemMessage implements Message
public class ToolResponseMessage implements Message
4.1.3 Tool回调体系
java 复制代码
// 工具回调
public interface ToolCallback {
    ToolDefinition getToolDefinition();
    String call(String functionInput);
    String call(String functionInput, ToolContext toolContext);
}

// 工具定义
public interface ToolDefinition {
    String name();
    String description();
    String inputSchema();
}

4.2 Alibaba扩展接口

4.2.1 Graph核心接口
java 复制代码
// 节点动作
@FunctionalInterface
public interface NodeAction {
    Map<String, Object> apply(OverAllState state) throws Exception;
}
​
// 异步节点动作
@FunctionalInterface
public interface AsyncNodeAction {
    CompletableFuture<Map<String, Object>> apply(OverAllState state);
}
​
// 带配置的异步节点动作
@FunctionalInterface
public interface AsyncNodeActionWithConfig {
    CompletableFuture<Map<String, Object>> apply(OverAllState state, RunnableConfig config);
}
​
// 边动作
@FunctionalInterface
public interface EdgeAction {
    String apply(OverAllState state) throws Exception;
}
4.2.2 状态策略接口
java 复制代码
// 键策略
@FunctionalInterface
public interface KeyStrategy {
    Object apply(Object oldValue, Object newValue);
}
​
// 状态工厂
@FunctionalInterface
public interface AgentStateFactory<T> extends Function<Map<String, Object>, T> {
}
​
// 键策略工厂
@FunctionalInterface
public interface KeyStrategyFactory {
    Map<String, KeyStrategy> apply();
}
4.2.3 钩子接口
java 复制代码
// 基础钩子
public interface Hook extends Prioritized {
    String getName();
    void setAgentName(String agentName);
    String getAgentName();
    ReactAgent getAgent();
    void setAgent(ReactAgent agent);
    List<ModelInterceptor> getModelInterceptors();
    List<ToolInterceptor> getToolInterceptors();
}

// Agent钩子
public interface AgentHook extends Hook {
    void onAgentStart(OverAllState state);
    void onAgentEnd(OverAllState state);
}

// 模型钩子
public interface ModelHook extends Hook {
    void onModelStart(ModelRequest request);
    void onModelEnd(ModelResponse response);
}
4.2.4 拦截器接口
java 复制代码
// 基础拦截器
public interface Interceptor extends Prioritized {
    InterceptorType getType();
}

// 模型拦截器
public abstract class ModelInterceptor implements Interceptor {
    public abstract ModelResponse interceptModel(ModelRequest request, ModelCallHandler handler);
    public List<ToolCallback> getTools() { return Collections.emptyList(); }
}

// 工具拦截器
public abstract class ToolInterceptor implements Interceptor {
    public abstract ToolCallResponse interceptTool(ToolCallRequest request, ToolCallHandler handler);
}

// 处理器接口
public interface ModelCallHandler {
    ModelResponse handle(ModelRequest request);
}

public interface ToolCallHandler {
    ToolCallResponse handle(ToolCallRequest request);
}

第五章:自动配置机制

5.1 自动配置原理

5.1.1 配置加载流程
复制代码
Spring Boot启动
    ↓
@SpringBootApplication
    ↓
@EnableAutoConfiguration
    ↓
读取 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    ↓
条件评估(@ConditionalOnClass, @ConditionalOnProperty等)
    ↓
实例化配置类
    ↓
@Bean方法执行
    ↓
Bean注册到ApplicationContext
    ↓
依赖注入
    ↓
初始化完成
5.1.2 条件注解详解
注解 条件 示例
@ConditionalOnClass 类存在 @ConditionalOnClass(ChatModel.class)
@ConditionalOnMissingClass 类不存在 @ConditionalOnMissingClass("com.deprecated.Class")
@ConditionalOnBean Bean存在 @ConditionalOnBean(ChatModel.class)
@ConditionalOnMissingBean Bean不存在 @ConditionalOnMissingBean(ChatModel.class)
@ConditionalOnProperty 配置属性匹配 @ConditionalOnProperty(prefix="ai", name="enabled", havingValue="true")
@ConditionalOnWebApplication Web应用 @ConditionalOnWebApplication(type=SERVLET)
@ConditionalOnExpression SpEL表达式 @ConditionalOnExpression("${feature.enabled:false}")

5.2 核心自动配置类

5.2.1 GraphObservationAutoConfiguration
java 复制代码
@AutoConfiguration
@ConditionalOnClass({ StateGraph.class, ObservationRegistry.class })
@EnableConfigurationProperties(GraphObservationProperties.class)
@ConditionalOnProperty(
    prefix = GraphObservationProperties.CONFIG_PREFIX, 
    name = "enabled", 
    havingValue = "true", 
    matchIfMissing = true
)
public class GraphObservationAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public GraphObservationLifecycleListener graphObservationLifecycleListener(
            ObjectProvider<ObservationRegistry> observationRegistry) {
        return new GraphObservationLifecycleListener(
            observationRegistry.getIfUnique(() -> ObservationRegistry.NOOP)
        );
    }
    
    @Bean
    @ConditionalOnMissingBean
    public CompileConfig observationGraphCompileConfig(
            ObjectProvider<ObservationRegistry> observationRegistry,
            ObjectProvider<GraphObservationLifecycleListener> listeners) {
        CompileConfig.Builder builder = CompileConfig.builder()
            .observationRegistry(observationRegistry.getIfUnique(() -> ObservationRegistry.NOOP));
        listeners.ifUnique(builder::withLifecycleListener);
        return builder.build();
    }
    
    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(MeterRegistry.class)
    @ConditionalOnBean(MeterRegistry.class)
    static class ObservationHandlersConfiguration {
        @Bean
        @ConditionalOnMissingBean
        public GraphObservationHandler graphObservationHandler(MeterRegistry meterRegistry) {
            return new GraphObservationHandler(meterRegistry);
        }
    }
}

5.3 配置属性类

5.3.1 GraphObservationProperties
java 复制代码
@ConfigurationProperties(prefix = GraphObservationProperties.CONFIG_PREFIX)
public class GraphObservationProperties {
    
    public static final String CONFIG_PREFIX = "spring.ai.alibaba.graph.observation";
    
    private boolean enabled = true;
    private Metrics metrics = new Metrics();
    private Tracing tracing = new Tracing();
    
    public static class Metrics {
        private boolean enabled = true;
    }
    
    public static class Tracing {
        private boolean enabled = true;
    }
}
5.3.2 配置属性绑定流程
复制代码
application.yml
    ↓
@ConfigurationProperties
    ↓
Java Bean
    ↓
@EnableConfigurationProperties
    ↓
Spring Environment
    ↓
PropertySource (系统属性、环境变量、配置文件)

第六章:设计模式全解

6.1 构建者模式(Builder)

应用场景: ReactAgent、StateGraph、CompileConfig等复杂对象创建

实现结构:

java 复制代码
// 产品类
public class ReactAgent extends BaseAgent {
    private ReactAgent(Builder builder) {
        // 私有构造,通过Builder创建
    }
    
    public static Builder builder() {
        return new DefaultAgentBuilderFactory().builder();
    }
    
    // Builder接口
    public interface Builder {
        Builder name(String name);
        Builder instruction(String instruction);
        Builder model(ChatModel model);
        Builder tools(List<ToolCallback> tools);
        Builder hooks(List<Hook> hooks);
        ReactAgent build();
    }
}
​
// 默认实现
public class DefaultBuilder implements ReactAgent.Builder {
    private String name;
    private String instruction;
    
    @Override
    public Builder name(String name) {
        this.name = name;
        return this;
    }
    
    @Override
    public ReactAgent build() {
        validate();
        return new ReactAgent(this);
    }
}

使用示例:

java 复制代码
ReactAgent agent = ReactAgent.builder()
    .name("my-agent")
    .instruction("你是一个助手...")
    .model(chatModel)
    .tools(tools)
    .build();

6.2 策略模式(Strategy)

应用场景: 状态更新策略

实现结构:

java 复制代码
// 策略接口
public interface KeyStrategy {
    Object apply(Object oldValue, Object newValue);
}
​
// 具体策略
public class AppendStrategy implements KeyStrategy {
    public Object apply(Object oldValue, Object newValue) {
        List<Object> list = new ArrayList<>();
        if (oldValue instanceof Collection) {
            list.addAll((Collection<?>) oldValue);
        }
        if (newValue instanceof Collection) {
            list.addAll((Collection<?>) newValue);
        } else {
            list.add(newValue);
        }
        return list;
    }
}
​
public class ReplaceStrategy implements KeyStrategy {
    public Object apply(Object oldValue, Object newValue) {
        return newValue;
    }
}
​
public class MergeStrategy implements KeyStrategy {
    public Object apply(Object oldValue, Object newValue) {
        Map<String, Object> result = new HashMap<>();
        if (oldValue instanceof Map) {
            result.putAll((Map<String, Object>) oldValue);
        }
        if (newValue instanceof Map) {
            result.putAll((Map<String, Object>) newValue);
        }
        return result;
    }
}

6.3 责任链模式(Chain of Responsibility)

应用场景: 拦截器链

实现结构:

java 复制代码
// 处理器接口
public interface ModelCallHandler {
    ModelResponse handle(ModelRequest request);
}

// 拦截器抽象类
public abstract class ModelInterceptor {
    public abstract ModelResponse interceptModel(ModelRequest request, ModelCallHandler handler);
}

// 链式调用
ModelResponse response = interceptor1.interceptModel(
    request,
    req1 -> interceptor2.interceptModel(
        req1,
        req2 -> interceptor3.interceptModel(
            req2,
            finalReq -> baseHandler.handle(finalReq)
        )
    )
);

6.4 工厂模式(Factory)

应用场景: ActionFactory、AgentBuilderFactory

实现结构:

java 复制代码
// 工厂接口
public interface ActionFactory {
    AsyncNodeActionWithConfig apply(CompileConfig config);
}

// 使用Lambda实现
Node node = new Node("llm", config -> {
    return (state, runnableConfig) -> {
        // 创建动作逻辑
        return CompletableFuture.completedFuture(result);
    };
});

6.5 观察者模式(Observer)

应用场景: Graph生命周期监听

实现结构:

java 复制代码
// 主题接口
public interface GraphRunnerContext {
    void addLifecycleListener(GraphLifecycleListener listener);
    void removeLifecycleListener(GraphLifecycleListener listener);
}
​
// 观察者接口
public interface GraphLifecycleListener {
    void onGraphStart(GraphRunnerContext context);
    void onNodeStart(String nodeId, NodeOutput nodeOutput);
    void onNodeEnd(String nodeId, NodeOutput nodeOutput);
    void onGraphEnd(GraphResponse response);
}
​
// 通知机制
for (GraphLifecycleListener listener : listeners) {
    listener.onNodeStart(nodeId, output);
}

6.6 模板方法模式(Template Method)

应用场景: BaseCheckpointSaver、ModelInterceptor

实现结构:

java 复制代码
public abstract class ModelInterceptor implements Interceptor {
    // 模板方法
    public final ModelResponse intercept(ModelRequest request, ModelCallHandler handler) {
        // 前置处理
        ModelRequest processedRequest = beforeHandle(request);
        
        // 调用处理器
        ModelResponse response = handler.handle(processedRequest);
        
        // 后置处理
        return afterHandle(response);
    }
    
    // 钩子方法
    protected abstract ModelRequest beforeHandle(ModelRequest request);
    protected abstract ModelResponse afterHandle(ModelResponse response);
}

第七章:配置体系

7.1 配置层级

复制代码
spring:                              # 根
  ai:                                # AI模块
    alibaba:                         # Alibaba实现
      dashscope:                     # DashScope提供商
        api-key: xxx                 # 认证
        chat:                        # 聊天模型
          options:                   # 模型参数
            model: qwen-max
            temperature: 0.7
        embedding:                   # 嵌入模型
          options:
            model: text-embedding-v3
        image:                       # 图像模型
          options:
            model: wanx-v1
      graph:                         # Graph配置
        observation:                 # 可观测性
          enabled: true
          metrics:
            enabled: true

7.2 配置属性映射表

YAML配置路径 属性类 字段 默认值
spring.ai.alibaba.dashscope.api-key DashScopeConnectionProperties apiKey null
spring.ai.alibaba.dashscope.chat.options.model DashScopeChatOptions model qwen-max
spring.ai.alibaba.dashscope.chat.options.temperature DashScopeChatOptions temperature 0.7
spring.ai.alibaba.dashscope.chat.options.max-tokens DashScopeChatOptions maxTokens 2048
spring.ai.alibaba.dashscope.chat.options.top-p DashScopeChatOptions topP 0.9
spring.ai.alibaba.dashscope.embedding.options.model DashScopeEmbeddingOptions model text-embedding-v3
spring.ai.alibaba.dashscope.embedding.options.dimensions DashScopeEmbeddingOptions dimensions 1536
spring.ai.alibaba.graph.observation.enabled GraphObservationProperties enabled true
spring.ai.alibaba.graph.observation.metrics.enabled GraphObservationProperties.Metrics enabled true
spring.ai.alibaba.graph.observation.tracing.enabled GraphObservationProperties.Tracing enabled true

7.3 多环境配置

Lua 复制代码
# application.yml (公共配置)
spring:
  profiles:
    active: ${SPRING_PROFILES_ACTIVE:dev}
​
---
# application-dev.yml (开发环境)
spring:
  ai:
    alibaba:
      dashscope:
        api-key: ${DEV_API_KEY}
        chat:
          options:
            model: qwen-turbo          # 轻量级模型
            temperature: 0.9           # 高创造性
​
---
# application-test.yml (测试环境)
spring:
  ai:
    alibaba:
      dashscope:
        api-key: ${TEST_API_KEY}
        chat:
          options:
            model: qwen-plus
            temperature: 0.5
​
---
# application-prod.yml (生产环境)
spring:
  ai:
    alibaba:
      dashscope:
        api-key: ${PROD_API_KEY}
        chat:
          options:
            model: qwen-max            # 最强模型
            temperature: 0.3           # 确定性回答
        client:
          max-connections: 200
          connect-timeout: 10

第八章:高级特性实现

8.1 Function Calling实现

8.1.1 工具定义
java 复制代码
@Component
public class WeatherTools {
    
    @Tool(name = "get_weather", description = "获取指定城市的天气")
    public String getWeather(
        @ToolParam(description = "城市名称,如:北京、上海") String city
    ) {
        // 实现
        return weatherService.getCurrentWeather(city);
    }
    
    @Tool(name = "get_forecast", description = "获取天气预报")
    public String getForecast(
        @ToolParam(description = "城市名称") String city,
        @ToolParam(description = "天数,1-7") int days
    ) {
        return weatherService.getForecast(city, days);
    }
}
8.1.2 工具注册
java 复制代码
@Configuration
public class ToolConfiguration {
    
    @Bean
    public ChatClient chatClient(
            ChatClient.Builder builder,
            WeatherTools weatherTools,
            CalculatorTools calculatorTools) {
        
        return builder
            .defaultTools(
                ToolCallbacks.from(weatherTools),
                ToolCallbacks.from(calculatorTools)
            )
            .build();
    }
}
8.1.3 调用流程
复制代码
User: 北京今天天气怎么样?
    ↓
LLM分析:需要调用get_weather工具
    ↓
生成ToolCall请求:{"name": "get_weather", "arguments": {"city": "北京"}}
    ↓
执行工具调用
    ↓
获取结果:"北京今天晴,25°C"
    ↓
将结果加入上下文
    ↓
LLM生成最终回答:"北京今天天气晴朗,气温25°C..."

8.2 RAG实现原理

8.2.1 文档处理流程
复制代码
Document (PDF/Word/TXT)
    ↓
DocumentReader (读取)
    ↓
Text (原始文本)
    ↓
TokenTextSplitter (切分)
    ↓
Chunks (文本块)
    ↓
EmbeddingModel (向量化)
    ↓
Vectors (向量)
    ↓
VectorStore (存储)
8.2.2 检索流程
复制代码
User Query
    ↓
EmbeddingModel (查询向量化)
    ↓
VectorStore.similaritySearch()
    ↓
Top-K Documents
    ↓
Prompt构造(Query + Documents)
    ↓
LLM Generate
    ↓
Answer

8.3 流式输出实现

java 复制代码
@Service
public class StreamService {
    
    private final ChatClient chatClient;
    
    public Flux<String> stream(String message) {
        return chatClient.prompt()
            .user(message)
            .stream()
            .content();
    }
}
​
// Controller
@RestController
public class StreamController {
    
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> stream(@RequestParam String message) {
        return streamService.stream(message);
    }
}

SSE响应格式:

复制代码
event: message
data: {"content": "今天"}
​
event: message
data: {"content": "天气"}
​
event: message
data: {"content": "很好"}
​
event: complete
data: [DONE]

8.4 可观测性实现

8.4.1 Metrics指标
指标名 类型 说明
ai.graph.calls Counter Graph调用次数
ai.graph.duration Timer Graph执行耗时
ai.node.calls Counter 节点调用次数
ai.node.duration Timer 节点执行耗时
ai.llm.tokens.input Counter 输入Token数
ai.llm.tokens.output Counter 输出Token数
8.4.2 Tracing链路
复制代码
[Graph Execution]
    ├── [Node: agent_llm]
    │       ├── [Model Call]
    │       └── [Tool Calls]
    ├── [Node: agent_tool]
    │       └── [Tool Execution]
    └── [Node: agent_llm]
            └── [Model Call]

第九章:扩展机制

9.1 自定义Hook

java 复制代码
@Component
public class MetricsHook implements AgentHook {
    
    private final MeterRegistry meterRegistry;
    
    @Override
    public String getName() {
        return "metrics-hook";
    }
    
    @Override
    public void onAgentStart(OverAllState state) {
        meterRegistry.counter("agent.calls", "agent", getAgentName()).increment();
    }
    
    @Override
    public void onAgentEnd(OverAllState state) {
        // 记录结束指标
    }
    
    @Override
    public int getPriority() {
        return Prioritized.NORMAL;
    }
}

9.2 自定义拦截器

java 复制代码
@Component
public class LoggingModelInterceptor extends ModelInterceptor {
    
    private static final Logger log = LoggerFactory.getLogger(LoggingModelInterceptor.class);
    
    @Override
    public ModelResponse interceptModel(ModelRequest request, ModelCallHandler handler) {
        log.info("Model request: {}", request);
        
        long startTime = System.currentTimeMillis();
        try {
            ModelResponse response = handler.handle(request);
            log.info("Model response time: {}ms", System.currentTimeMillis() - startTime);
            return response;
        } catch (Exception e) {
            log.error("Model call failed", e);
            throw e;
        }
    }
    
    @Override
    public int getPriority() {
        return Prioritized.HIGH;
    }
}

9.3 自定义CheckpointSaver

java 复制代码
@Component
public class CustomCheckpointSaver implements BaseCheckpointSaver {
    
    private final JdbcTemplate jdbcTemplate;
    
    @Override
    public Collection<Checkpoint> list(RunnableConfig config) {
        return jdbcTemplate.query(
            "SELECT * FROM checkpoints WHERE thread_id = ?",
            new CheckpointRowMapper(),
            config.getThreadId()
        );
    }
    
    @Override
    public Optional<Checkpoint> get(RunnableConfig config) {
        // 实现
    }
    
    @Override
    public RunnableConfig put(RunnableConfig config, Checkpoint checkpoint) {
        jdbcTemplate.update(
            "INSERT INTO checkpoints (thread_id, checkpoint_data, created_at) VALUES (?, ?, ?)",
            config.getThreadId(),
            serialize(checkpoint),
            Timestamp.from(Instant.now())
        );
        return config;
    }
    
    @Override
    public Tag release(RunnableConfig config) {
        // 实现
    }
}

第十章:类与接口全索引

10.1 spring-ai-alibaba-graph-core

10.1.1 核心类
类名 包路径 类型 说明
StateGraph com.alibaba.cloud.ai.graph Class 状态图
CompiledGraph com.alibaba.cloud.ai.graph Class 编译图
OverAllState com.alibaba.cloud.ai.graph Class 状态容器
CompileConfig com.alibaba.cloud.ai.graph Class 编译配置
GraphResponse com.alibaba.cloud.ai.graph Class 图响应
GraphRunner com.alibaba.cloud.ai.graph Class 图运行器
RunnableConfig com.alibaba.cloud.ai.graph Class 运行配置
KeyStrategy com.alibaba.cloud.ai.graph Interface 键策略
KeyStrategyFactory com.alibaba.cloud.ai.graph Interface 策略工厂
10.1.2 Action包
类名 包路径 类型 说明
NodeAction action Interface 节点动作
AsyncNodeAction action Interface 异步节点动作
AsyncNodeActionWithConfig action Interface 带配置异步动作
EdgeAction action Interface 边动作
AsyncEdgeAction action Interface 异步边动作
Command action Interface 命令
CommandAction action Interface 命令动作
MultiCommand action Class 多命令
10.1.3 Checkpoint包
类名 包路径 类型 说明
BaseCheckpointSaver checkpoint Interface 检查点存储接口
Checkpoint checkpoint Class 检查点
SaverConfig checkpoint.config Class 存储配置
SaverEnum checkpoint.constant Enum 存储类型枚举
MemorySaver checkpoint.savers Class 内存存储
FileSystemSaver checkpoint.savers.file Class 文件存储
RedisSaver checkpoint.savers.redis Class Redis存储
MysqlSaver checkpoint.savers.mysql Class MySQL存储
PostgresSaver checkpoint.savers.postgresql Class PG存储
10.1.4 State包
类名 包路径 类型 说明
AgentStateFactory state Interface 状态工厂
Channel state Interface 状态通道
AppenderChannel state Class 追加通道
Reducer state Interface 归约器
AppendStrategy state.strategy Class 追加策略
ReplaceStrategy state.strategy Class 替换策略
MergeStrategy state.strategy Class 合并策略
10.1.5 Store包
类名 包路径 类型 说明
Store store Interface 存储接口
StoreItem store Class 存储项
StoreSearchRequest store Class 搜索请求
StoreSearchResult store Class 搜索结果
BaseStore store.stores Abstract 存储基类
MemoryStore store.stores Class 内存存储
FileSystemStore store.stores Class 文件存储
RedisStore store.stores Class Redis存储
MongoStore store.stores Class Mongo存储
10.1.6 Serializer包
类名 包路径 类型 说明
StateSerializer serializer Interface 状态序列化
Serializer serializer Interface 序列化器
CheckPointSerializer serializer.check_point Class 检查点序列化
JacksonStateSerializer serializer.plain_text.jackson Class Jackson序列化
SpringAIJacksonStateSerializer serializer.plain_text.jackson Class SpringAI Jackson
SpringAIStateSerializer serializer.std Class 标准序列化

10.2 spring-ai-alibaba-agent-framework

10.2.1 Agent包
类名 包路径 类型 说明
Agent agent Abstract 代理基类
BaseAgent agent Abstract 基础代理
ReactAgent agent Class ReAct代理
Builder agent Interface 构建器
DefaultBuilder agent Class 默认构建器
AgentTool agent Class 代理工具
AgentBuilderFactory agent.factory Interface 构建器工厂
DefaultAgentBuilderFactory agent.factory Class 默认工厂
10.2.2 Hook包
类名 包路径 类型 说明
Hook agent.hook Interface 钩子接口
AgentHook agent.hook Interface 代理钩子
ModelHook agent.hook Interface 模型钩子
HookPosition agent.hook Enum 钩子位置
Prioritized agent Interface 优先级接口
InstructionAgentHook agent.hook Class 指令钩子
HumanInTheLoopHook agent.hook.hip Class 人机交互钩子
SummarizationHook agent.hook.summarization Class 摘要钩子
ToolInjection agent.hook Interface 工具注入
TokenCounter agent.hook Interface Token计数
10.2.3 Interceptor包
类名 包路径 类型 说明
Interceptor agent.interceptor Interface 拦截器接口
ModelInterceptor agent.interceptor Abstract 模型拦截器
ToolInterceptor agent.interceptor Abstract 工具拦截器
ModelCallHandler agent.interceptor Interface 模型处理器
ToolCallHandler agent.interceptor Interface 工具处理器
ModelRequest agent.interceptor Class 模型请求
ModelResponse agent.interceptor Class 模型响应
ToolCallRequest agent.interceptor Class 工具调用请求
ToolCallResponse agent.interceptor Class 工具调用响应
ModelRetryInterceptor agent.interceptor.modelretry Class 模型重试拦截器
ToolRetryInterceptor agent.interceptor.toolretry Class 工具重试拦截器
ModelFallbackInterceptor agent.interceptor.modelfallback Class 模型降级拦截器
SkillsInterceptor agent.interceptor.skills Class 技能拦截器
10.2.4 Node包
类名 包路径 类型 说明
AgentLlmNode agent.node Class 代理LLM节点
AgentToolNode agent.node Class 代理工具节点
10.2.5 Tool包
类名 包路径 类型 说明
AsyncToolCallback agent.tool Interface 异步工具回调
StateAwareToolCallback agent.tool Interface 状态感知回调
CancellableAsyncToolCallback agent.tool Interface 可取消异步回调
CancellationToken agent.tool Interface 取消令牌
ToolStateCollector agent.tool Class 工具状态收集器

附录:版本特性矩阵

特性 1.0.0 1.1.0 1.1.2
ChatModel
EmbeddingModel
ImageModel -
ReactAgent -
StateGraph -
Nacos Config -
Graph Observation - -
A2A Protocol - -
相关推荐
深念Y2 小时前
豆包AI能力集成方案:基于会话管理的API网关设计
人工智能
龙文浩_2 小时前
Attention Mechanism: From Theory to Code
人工智能·深度学习·神经网络·学习·自然语言处理
ulimate_2 小时前
八卡算力、三个Baseline算法(WALLOSS、pi0、DreamZero)
人工智能
深小乐2 小时前
AI 周刊【2026.04.06-04.12】:Anthropic 藏起最强模型、AI 社会矛盾激化、"欢乐马"登顶
人工智能
微臣愚钝2 小时前
prompt
人工智能·深度学习·prompt
是小蟹呀^3 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
深小乐3 小时前
从 AI Skills 学实战技能(六):让 AI 帮你总结网页、PDF、视频
人工智能
宝贝儿好3 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别