Spring AI Alibaba Graph 初探

1,347 阅读4分钟

Spring AI Alibaba Graph 初探

目录

  1. 框架概述
  2. 核心概念与架构
  3. 核心组件详解
  4. 节点类型与操作
  5. 实际应用案例
  6. 最佳实践

框架概述

Spring AI Alibaba Graph 是一个面向 Java 开发者的工作流和多智能体框架,专门用于构建由多个 AI 模型或步骤组成的复杂应用 1 。该框架基于 Spring Boot 生态深度集成,提供声明式 API 来编排工作流,让开发者能将 AI 应用的各个步骤抽象为节点(Node),并通过有向图(Graph)的形式连接这些节点 。

与传统单 Agent(一问一答式)方案相比,Spring AI Alibaba Graph 支持更复杂的多步骤任务流程,有助于解决单一大模型对复杂任务力不从心的问题。

核心概念与架构

基础架构图

graph TD
    A["StateGraph"] --> B["Node"]
    A --> C["Edge"]
    A --> D["OverAllState"]
    A --> E["CompiledGraph"]
    
    B --> F["LlmNode"]
    B --> G["ToolNode"]
    B --> H["HumanNode"]
    B --> I["Custom Node"]
    
    C --> J["Direct Edge"]
    C --> K["Conditional Edge"]
    
    E --> L["Execution Engine"]
    E --> M["State Management"]
    E --> N["Streaming Support"]

核心组件关系

框架的核心包括以下几个关键组件:

  1. StateGraph(状态图):定义整个工作流的主类,支持添加节点和边
  2. Node(节点):表示工作流中的单个步骤,可封装模型调用或自定义逻辑
  3. Edge(边):表示节点之间的转移关系,支持条件分支
  4. OverAllState(全局状态):贯穿整个工作流的可序列化状态对象
  5. CompiledGraph(已编译图):StateGraph 的可执行版本

核心组件详解

StateGraph - 状态图核心

StateGraph 是框架的核心类,负责定义和管理整个工作流 :

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();
}

CompiledGraph - 执行引擎

CompiledGraph 是 StateGraph 编译后的可执行版本,负责实际的节点执行和状态流转 :

public class CompiledGraph {
    public final StateGraph stateGraph;
    final Map<String, AsyncNodeActionWithConfig> nodes = new LinkedHashMap<>();
    final Map<String, EdgeValue> edges = new LinkedHashMap<>();
}

编译过程

StateGraph 通过 compile() 方法转换为 CompiledGraph :

public CompiledGraph compile() throws GraphStateException {
    SaverConfig saverConfig = SaverConfig.builder()
        .register(SaverConstant.MEMORY, new MemorySaver()).build();
    return compile(CompileConfig.builder().saverConfig(saverConfig).build());
}

节点类型与操作

内置节点类型

框架提供了三种预定义的节点类型,每种都针对特定的 AI 工作流模式进行了优化:

1. LlmNode - 大语言模型节点

LlmNode 专门处理与大语言模型的交互,支持同步和流式执行模式。该节点通过 Spring AI 的 ChatClient 与各种 LLM 服务通信。

核心配置选项:

  • chatClient: Spring AI 聊天客户端
  • systemPromptTemplate: 系统提示模板
  • userPromptTemplate: 用户提示模板
  • messagesKey: 对话消息的状态键
  • stream: 启用流式响应模式
  • toolCallbacks: 可用工具列表
2. ToolNode - 工具执行节点

ToolNode 负责执行 LLM 响应中的工具调用,处理 AssistantMessage.ToolCall 对象并返回 ToolResponseMessage 结果。

核心配置选项:

  • toolCallbacks: 直接工具列表
  • toolCallbackResolver: 动态工具解析器
  • llmResponseKey: LLM 响应的状态键
  • outputKey: 工具结果的自定义输出键
3. HumanNode - 人机交互节点

HumanNode 实现人机交互功能,通过中断图执行等待人工反馈。支持无条件和条件中断策略。

中断策略:

  • "always": 每次执行都中断
  • "conditioned": 基于函数结果的条件中断

自定义节点创建

Lambda 表达式方式
// 基础状态转换节点
var simpleNode = node_async(state -> {
    log.info("Processing in simple node");
    return Map.of("messages", "Node executed");
});

// 带配置访问的节点
var configNode = AsyncNodeActionWithConfig.node_async((state, config) -> {
    String threadId = config.threadId().orElse("default");
    return Map.of("threadId", threadId, "processed", true);
});
自定义类实现
public class CustomProcessingNode implements AsyncNodeActionWithConfig {
    private final SomeService service;
    
    @Override
    public CompletableFuture<Map<String, Object>> apply(OverAllState state, RunnableConfig config) {
        return CompletableFuture.supplyAsync(() -> {
            String input = (String) state.value("input").orElseThrow();
            String result = service.process(input);
            return Map.of("output", result, "timestamp", System.currentTimeMillis());
        });
    }
}

实际应用案例

案例1:客户反馈处理系统

这是一个典型的两级分类工作流,展示了条件路由和状态管理的核心概念 :

工作流架构图
graph TD
    START["__START__"] --> FC["feedback_classifier"]
    FC --> Decision1{"正面/负面判断"}
    Decision1 -->|"positive"| Recorder["recorder"]
    Decision1 -->|"negative"| SQC["specific_question_classifier"]
    SQC --> Decision2{"问题分类"}
    Decision2 -->|"after-sale"| Recorder
    Decision2 -->|"transportation"| Recorder
    Decision2 -->|"quality"| Recorder
    Decision2 -->|"others"| Recorder
    Recorder --> END["__END__"]
核心实现代码

状态定义:

OverAllStateFactory stateFactory = () -> {
    OverAllState state = new OverAllState();
    state.registerKeyAndStrategy("input", new ReplaceStrategy());
    state.registerKeyAndStrategy("classifier_output", new ReplaceStrategy());
    state.registerKeyAndStrategy("solution", new ReplaceStrategy());
    return state;
};

节点定义:

// 正负面分类节点
QuestionClassifierNode feedbackClassifier = QuestionClassifierNode.builder()
    .chatClient(chatClient)
    .inputTextKey("input")
    .categories(List.of("positive feedback", "negative feedback"))
    .classificationInstructions(
        List.of("Try to understand the user's feeling when giving feedback."))
    .build();

// 负面反馈细分节点
QuestionClassifierNode specificQuestionClassifier = QuestionClassifierNode.builder()
    .chatClient(chatClient)
    .inputTextKey("input")
    .categories(List.of("after-sale service", "transportation", "product quality", "others"))
    .classificationInstructions(List.of(
        "What kind of service or help the customer is trying to get from us?"))
    .build();

图构建:

StateGraph graph = new StateGraph("Consumer Service Workflow Demo", stateFactory)
    .addNode("feedback_classifier", node_async(feedbackClassifier))
    .addNode("specific_question_classifier", node_async(specificQuestionClassifier))
    .addNode("recorder", node_async(recorderNode))
    .addEdge(START, "feedback_classifier")
    .addConditionalEdges("feedback_classifier",
        edge_async(new FeedbackQuestionDispatcher()),
        Map.of("positive", "recorder", "negative", "specific_question_classifier"))
    .addConditionalEdges("specific_question_classifier",
        edge_async(new SpecificQuestionDispatcher()),
        Map.of("after-sale", "recorder", "transportation", "recorder", 
               "quality", "recorder", "others", "recorder"))
    .addEdge("recorder", END);

案例2:DeepResearch 深度研究系统

DeepResearch 是一个基于 Spring AI Alibaba Graph 开发的深度研究智能体,展示了复杂多智能体协作的实现 。

系统架构
graph TD
    START --> Coordinator["coordinator"]
    Coordinator --> Decision1{"协调决策"}
    Decision1 -->|"background_investigator"| BI["background_investigator"]
    Decision1 -->|"planner"| Planner["planner"]
    Decision1 -->|"END"| END
    
    BI --> Planner
    Planner --> Information["information"]
    Information --> Decision2{"信息处理决策"}
    Decision2 -->|"reporter"| Reporter["reporter"]
    Decision2 -->|"human_feedback"| HF["human_feedback"]
    Decision2 -->|"research_team"| RT["research_team"]
    Decision2 -->|"planner"| Planner
    Decision2 -->|"END"| END
    
    HF --> Decision3{"人工反馈决策"}
    Decision3 -->|"planner"| Planner
    Decision3 -->|"research_team"| RT
    Decision3 -->|"END"| END
    
    RT --> Decision4{"研究团队决策"}
    Decision4 -->|"reporter"| Reporter
    Decision4 -->|"parallel_executor"| PE["parallel_executor"]
    Decision4 -->|"END"| END
    
    Reporter --> END
核心配置实现

状态策略配置:

KeyStrategyFactory keyStrategyFactory = () -> {
    HashMap<String, KeyStrategy> keyStrategyHashMap = new HashMap<>();
    // 条件边控制
    keyStrategyHashMap.put("coordinator_next_node", new ReplaceStrategy());
    keyStrategyHashMap.put("planner_next_node", new ReplaceStrategy());
    keyStrategyHashMap.put("information_next_node", new ReplaceStrategy());
    // 用户输入
    keyStrategyHashMap.put("query", new ReplaceStrategy());
    keyStrategyHashMap.put("thread_id", new ReplaceStrategy());
    // 节点输出
    keyStrategyHashMap.put("background_investigation"new ReplaceStrategy());
    }