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

AI项目博客






