AI项目博客
记录 AI 工程实践与大模型应用

Spring AI Alibaba 99|Graph Core · 子图作为 CompiledGraph · 带 Checkpoint 的子图

CompiledGraph 可以有自己独立的 checkpoint:

import com.alibaba.cloud.ai.graph.checkpoint.MemorySaver;
import com.alibaba.cloud.ai.graph.CompileConfig;

// 子图使用独立的 checkpoint
var subCheckpointer = new MemorySaver();
var subCompileConfig = CompileConfig.builder()
  .checkpointSaver(subCheckpointer)
  .build();

CompiledGraph compiledSubGraph = subGraphDef.compile(subCompileConfig);

// 执行时指定子图的 threadId
public class CheckpointedSubGraphNode implements NodeAction {

  private final CompiledGraph compiledGraph;
  private final String subThreadIdPrefix;

  public CheckpointedSubGraphNode(
      CompiledGraph compiledGraph,
      String subThreadIdPrefix
  ) {
      this.compiledGraph = compiledGraph;
      this.subThreadIdPrefix = subThreadIdPrefix;
  }

  @Override
  public Map<String, Object> apply(OverAllState state) {
      String input = (String) state.value("input").orElse("");

      // 为子图创建独立的运行配置
      var subConfig = RunnableConfig.builder()
          .threadId(subThreadIdPrefix + "-" + System.currentTimeMillis())
          .build();

      // 执行子图
      OverAllState result = compiledGraph.invoke(
          Map.of("input", input),
          subConfig
      );

      return Map.of("output", result.value("output").orElse(""));
  }
}

预编译策略

// 服务启动时预编译所有子图
@Configuration
public class GraphConfiguration {

  @Bean
  public CompiledGraph validationGraph() {
      StateGraph def = createValidationGraph();
      return def.compile();  // 启动时编译一次
  }

  @Bean
  public CompiledGraph transformGraph() {
      StateGraph def = createTransformGraph();
      return def.compile();
  }

  @Bean
  public CompiledGraph aggregationGraph() {
      StateGraph def = createAggregationGraph();
      return def.compile();
  }
}

// 在运行时直接使用预编译的图
@Service
public class WorkflowService {

  @Autowired
  private CompiledGraph validationGraph;

  @Autowired
  private CompiledGraph transformGraph;

  @Autowired
  private CompiledGraph aggregationGraph;

  public void processData(String data) {
      // 直接使用,无需重新编译
      var result1 = validationGraph.invoke(Map.of("input", data));
      var result2 = transformGraph.invoke(Map.of("input", data));
      var result3 = aggregationGraph.invoke(Map.of("input", data));
  }
}

本文整理自 Spring AI Alibaba 官方文档《子图作为 CompiledGraph》:https://java2ai.com/docs/frameworks/graph-core/examples/subgraph-as-compiledgraph

赞(0)
未经允许不得转载:AI项目博客 » Spring AI Alibaba 99|Graph Core · 子图作为 CompiledGraph · 带 Checkpoint 的子图

评论 抢沙发

AI项目博客

专注 AI 工程化落地 —— 覆盖智能体、大模型、Java AI 与 Python 的学习笔记,以及 AI 平台的项目实战记录。

关于本站文章归档

登录

找回密码

注册