子图作为 CompiledGraph
在 Spring AI Alibaba 中,可以先编译 StateGraph 得到 CompiledGraph,然后在其他 Graph 中复用,这种方式性能更好且更灵活。
CompiledGraph vs StateGraph
| 特性 | StateGraph | CompiledGraph |
|---|---|---|
| 定义时机 | 构建时 | 编译后 |
| 性能 | 需要每次编译 | 预编译,性能更好 |
| 灵活性 | 可修改 | 不可修改 |
| 复用 | 可以但需重新编译 | 直接复用 |
基本用法
创建并编译子图
创建并编译子图查看完整代码
import com.alibaba.cloud.ai.graph.CompiledGraph;
import com.alibaba.cloud.ai.graph.KeyStrategy;
import com.alibaba.cloud.ai.graph.KeyStrategyFactory;
import com.alibaba.cloud.ai.graph.StateGraph;
import com.alibaba.cloud.ai.graph.exception.GraphStateException;
import com.alibaba.cloud.ai.graph.state.strategy.ReplaceStrategy;
import java.util.HashMap;
import java.util.Map;
import static com.alibaba.cloud.ai.graph.StateGraph.END;
import static com.alibaba.cloud.ai.graph.StateGraph.START;
import static com.alibaba.cloud.ai.graph.action.AsyncNodeAction.node_async;
/**
* 创建并编译子图
*/
public static CompiledGraph createAndCompileSubGraph() throws GraphStateException {
KeyStrategyFactory subKeyFactory = () -> {
HashMap<String, KeyStrategy> strategies = new HashMap<>();
strategies.put("input", new ReplaceStrategy());
strategies.put("output", new ReplaceStrategy());
return strategies;
};
// 定义并编译子图
StateGraph subGraphDef = new StateGraph(subKeyFactory)
.addNode("process", node_async(state -> {
String input = (String) state.value("input").orElse("");
String output = "Processed: " + input.toUpperCase();
return Map.of("output", output);
}))
.addEdge(START, "process")
.addEdge("process", END);
// 编译子图
return subGraphDef.compile();
}
在节点中使用 CompiledGraph
在节点中使用 CompiledGraph查看完整代码
import com.alibaba.cloud.ai.graph.CompiledGraph;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.RunnableConfig;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import java.util.Map;
/**
* 在节点中使用 CompiledGraph
*/
public static class CompiledSubGraphNode implements NodeAction {
private final CompiledGraph compiledGraph;
public CompiledSubGraphNode(CompiledGraph compiledGraph) {
this.compiledGraph = compiledGraph;
}
@Override
public Map<String, Object> apply(OverAllState state) {
// 从父状态提取输入
String input = (String) state.value("data").orElse("");
// 执行编译好的子图
Map<String, Object> subInput = Map.of("input", input);
OverAllState subResult = compiledGraph.invoke(subInput, RunnableConfig.builder().build()).orElseThrow();
// 提取子图输出
String output = (String) subResult.value("output").orElse("");
return Map.of("result", output);
}
}