import com.alibaba.cloud.ai.graph.*;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
public class PersistenceExample {
private static final Logger log = LoggerFactory.getLogger(PersistenceExample.class);
public static void main(String[] args) {
// 1. 配置状态策略
KeyStrategyFactory keyStrategyFactory = () -> {
HashMap<String, KeyStrategy> strategies = new HashMap<>();
strategies.put("messages", new AppendStrategy());
strategies.put("user_name", new ReplaceStrategy());
return strategies;
};
// 2. 创建工具和节点
SearchTool searchTool = new SearchTool();
ChatClient.Builder builder = ChatClient.builder(chatModel);
var agentNode = nodeasync(new AgentNode(builder, searchTool));
// 3. 构建 Graph
StateGraph workflow = new StateGraph(keyStrategyFactory)
.addNode("agent", agentNode)
.addEdge(StateGraph.START, "agent")
.addEdge("agent", StateGraph.END);
// 4. 配置持久化
var checkpointer = new MemorySaver();
var compileConfig = CompileConfig.builder()
.checkpointSaver(checkpointer)
.build();
CompiledGraph graph = workflow.compile(compileConfig);
// 5. 测试持久化对话
var config = RunnableConfig.builder()
.threadId("demo-session")
.build();
// 第一轮对话
graph.invoke(Map.of("messages", "Hi, I'm Charlie"), config);
// 第二轮对话 - 能记住名字
var result = graph.invoke(Map.of("messages", "What's my name?"), config);
log.info("Response: {}", result.data().get("messages"));
// 第三轮对话 - 使用工具
result = graph.invoke(Map.of("messages", "What's the weather like?"), config);
log.info("Response: {}", result.data().get("messages"));
// 查看状态历史
List<StateSnapshot> history = graph.getStateHistory(config);
log.info("Total conversation steps: {}", history.size());
}
}