开始使用免费开始使用

在对话中使用图的记忆功能

现在聊天机器人已经具备记忆能力,您可以将其对追问的回复进行流式输出。请注意,追问无需额外上下文,因为机器人可以访问存储在其记忆中的完整对话。这些问题已经为您准备好。

本练习是课程的一部分

使用 LangChain 设计 Agentic 系统

查看课程

练习说明

  • 创建一个包含 "configurable"config 字典,其中将 "thread_id" 设为 "single_session_memory"
  • 遍历每个图 event,对 graph 应用 .stream() 方法,传入一个字典,其中 "messages" 包含标记为 "user"user_input,以及 config 字典。
  • 通过 value 遍历 event.values(),如果 value 中存在且非空的 "messages",则打印 "Agent:",随后输出该 "messages"

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Set up a streaming function for a single user
def stream_memory_responses(user_input: str):
    ____ = {"____": {"____": "____"}}
    
    # Stream the events in the graph
    for ____ in graph.____({"messages": [("user", ____)]}, ____):
        
        # Return the agent's last response
        for ____ in event.____():
            if "messages" in ____ and value["____"]:
                print("Agent:", value["messages"])

stream_memory_responses("Tell me about the Eiffel Tower.")
stream_memory_responses("Who built it?")
编辑并运行代码