使用记忆启用多轮对话
您已经可以把更新后的聊天机器人分享给学校管理部门了!为了让学生获得顺畅的学习体验,支持他们追问后续问题非常重要。这样一来,如果机器人在第一次回答中遗漏信息,学生就可以通过继续对话来补充或修改问题。现在,您将改造机器人的流式函数以支持多轮交互,打印用户的查询以及机器人的回答。为启用记忆,LangGraph 会在用户提出追问时,将完整对话发送给 LLM。首先,您的 config 参数已为一位用户设置好:
config = {"configurable": {"thread_id": "1"}}
本练习是课程的一部分
使用 LangChain 设计 Agentic 系统
练习说明
- 每一轮开始时,先打印
queries列表中的用户query。 - 使用
app.stream()迭代msg和metadata,将query作为HumanMessage的content并传入config,同时拼接msg.content的值。 - 为提取机器人的回复,打印
msg.content,但排除被标记为HumanMessage的msg,并在下一条查询前添加换行符。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Print the user query first for every interaction
def user_agent_multiturn(queries):
for ____ in ____:
print(f"User: {____}")
# Stream through messages corresponding to queries, excluding metadata
print("Agent: " + "".join(____.____ for ____, ____ in app.____(
{"messages": [____(____=_____)]}, config, stream_mode="messages")
# Filter out the human messages to print agent messages
if ____.____ and not isinstance(____, ____)) + "____")
queries = ["Is `stressed desserts?` a palindrome?", "What about the word `kayak`?",
"What happened on the May 8th, 1945?", "What about 9 November 1989?"]
user_agent_multiturn(queries)