☰
第四单元——第四课:让 LangGraph 记住同一段对话的状态
2026/10/8 18:52:25 网站建设 项目流程

让 LangGraph 记住同一段对话的状态。我们用“会员身份”做实验,不需要调用模型。

新建unit4_lesson4_memory.py:

from typing import NotRequired, TypedDict from langgraph.checkpoint.memory import InMemorySaver from langgraph.graph import START, END, StateGraph class BookstoreState(TypedDict): message: str is_member: NotRequired[bool] reply: NotRequired[str] def respond(state: BookstoreState) -> dict: message = state["message"] if "我是会员" in message: return {"is_member": True, "reply": "好的,记住你是会员了。"} if "优惠" in message: if state.get("is_member", False): return {"reply": "会员买书享受八折优惠。"} return {"reply": "请先告诉我你是否是会员。"} return {"reply": "请问有什么可以帮你?"} builder = StateGraph(BookstoreState) builder.add_node("respond", respond) builder.add_edge(START, "respond") builder.add_edge("respond", END) graph = builder.compile(checkpointer=InMemorySaver()) customer_a = {"configurable": {"thread_id": "customer-a"}} customer_b = {"configurable": {"thread_id": "customer-b"}} print("A 第一次:", graph.invoke( {"message": "我是会员"}, customer_a )["reply"]) print("A 第二次:", graph.invoke( {"message": "买书有什么优惠?"}, customer_a )["reply"]) print("B 第一次:", graph.invoke( {"message": "买书有什么优惠?"}, customer_b )["reply"])

运行python unit4_lesson4_memory.py。你应看到:A 第二次提问时,图记得他是会员;B 用不同的thread_id,不会继承 A 的身份。

关键是compile(checkpointer=InMemorySaver())保存状态,thread_id指定是哪段对话。这里的记忆只在本次程序运行期间有效;关掉程序再运行,就会清空。LangGraph 记忆文档

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询