Time Travel:时空旅行

假设你有一个购买动车票的agent.
你:"明天帮我订一个从温州到去杭州的动车"
agent:"好的,明天12.00这张票非常不错,过去你都是选这班车,已经帮你跳转到支付界面"
你:"这一次计划有变,帮我订一个更早的"
这个时候agent需要重新走流程,因为是线性的,但是如果你有时空旅行,他就可以直接回到订票的时候,直接重新帮你买票

一.所以时空旅行是什么?

顾名思义,能让agent回到前面几步的一个思维方式和技术栈

二.具体如何实现?

from langgraph.checkpoint.memory import MemorySaver
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END

#count是第几步,history是历史存放
class HistoryState(TypedDict):
    count: int
    history: list

#插入数据的节点
def increment_node(state: HistoryState) -> dict:
    new_count=state.get("count")+1
    return {
        "count": new_count,
        "history": state.get("history",[])+[f"Incremented to {new_count}"]
    }

#增加节点
graph=StateGraph(HistoryState)
graph.add_node("inc1",increment_node)
graph.add_node("inc2",increment_node)
graph.add_node("inc3",increment_node)

#增加边
graph.add_edge(START,"inc1")
graph.add_edge("inc1","inc2")
graph.add_edge("inc2","inc3")
graph.add_edge("inc3",END)



if __name__ == '__main__':
    #存放记忆
    app = graph.compile(checkpointer=MemorySaver())
    config = {"configurable": {"thread_id": "history-demo"}}
    result=app.invoke({"count":0,"history":[]},config)
    print(f"最终结果:{result}")

    #查看历史
    history=app.get_state_history(config)
    for i,checkpoint in enumerate(history):
        print(f"i={i},checkpoint={checkpoint}")
        print(f"\nCheckpoint {i + 1}:")
        print(f"  State: {checkpoint.values}")
        print(f"  Next: {checkpoint.next}")
        print(f"  Checkpoint ID: {checkpoint.config['configurable'].get('checkpoint_id')}")

    history_list = list(app.get_state_history(config))
    target_checkpoint=history_list[3]
    print(f"\n回溯到:{target_checkpoint.values}")
    new_config = {
        "configurable": {
            "thread_id": "history-demo",
            "checkpoint_id": target_checkpoint.config["configurable"]["checkpoint_id"]
        }
    }
    # 继续执行
    result = app.invoke(None, new_config)
    print(f"从历史继续的结果: {result}")
posted @ 2026-06-03 17:20  Alfred404  阅读(11)  评论(0)    收藏  举报