LangGraph(三)——添加记忆

目录

  • 1. 创建MemorySaver检查指针
  • 2. 构建并编译Graph
  • 3. 与聊天机器人互动
  • 4. 问一个后续问题
  • 5. 检查State
  • 参考

1. 创建MemorySaver检查指针

  创建MemorySaver检查指针:

from langgraph.checkpoint.memory import MemorySaver

memory = MemorySaver()

  这是位于内存中的检查指针,仅适用于QuickStart教程。在实际生产应用程序中,建议将其更改为SqliteSaver或PostgresSaver并连接数据库。

2. 构建并编译Graph

  Graph的构建如下:

from typing import Annotated

from langchain.chat_models import init_chat_model
from typing_extensions import TypedDict

from langgraph.graph import StateGraph, START
from langgraph.graph.message import add_messages


class State(TypedDict):
    messages: Annotated[list, add_messages]


graph_builder = StateGraph(State)


llm = init_chat_model("deepseek:deepseek-chat")


def chatbot(state: State):
    return {"messages": [llm.invoke(state["messages"])]}


# The first argument is the unique node name
# The second argument is the function or object that will be called whenever
# the node is used.
graph_builder.add_node("chatbot", chatbot)
graph_builder.add_edge(START, "chatbot")

  使用提供的检查指针编译Graph,它将在图遍历每个节点时检查State:

graph = graph_builder.compile(checkpointer=memory)

3. 与聊天机器人互动

  选择一个线程作为这个对话的标签:

config = { "configurable": { "thread_id": "1" } }

  与聊天机器人聊天:

user_input = "Hi there! My name is Will."

events = graph.stream(
	{ "messages": [ { "role": "user", "content": user_input } ] },
	config,
	stream_mode="values"
)

for event in events:
	event["messages"][-1].pretty_print()

  运行结果为:
LangGraph(三)——添加记忆_第1张图片

4. 问一个后续问题

  问一个后续问题:

user_input = "What is My Name?"

events = graph.stream(
	{ "messages": [ { "role": "user", "content": user_input } ] },
	config,
	stream_mode="values"
)

for event in events:
	event["messages"][-1].pretty_print()

  运行结果为:
LangGraph(三)——添加记忆_第2张图片
  注意,上面的代码没有使用外部列表来存储内存。下面尝试使用不同的配置:

events = graph.stream(
	{ "messages": [ { "role": "user", "content": user_input } ] },
	{ "configurable": { "thread_id": "2" } },
	stream_mode="values"
)

for event in events:
	event["messages"][-1].pretty_print()

  运行结果为:
LangGraph(三)——添加记忆_第3张图片
  注意,上面的代码仅更改了配置中的thread_id。

5. 检查State

  到目前为止,我们已经跨两个不同的线程设置了几个检查点。但是什么会进入检查点呢?要在任何时候检查给定配置的图State,调用get_state(config):

snapshot = graph.get_state(config)
snapshot

  输出如下:
LangGraph(三)——添加记忆_第4张图片
LangGraph(三)——添加记忆_第5张图片

参考

https://langchain-ai.github.io/langgraph/tutorials/get-started/3-add-memory/

你可能感兴趣的:(AI,Agent,LangGraph)