开始使用免费开始使用

基于对话历史提问

在 LangChain 中使用基础的 ReAct 代理,您可以通过保留代理的对话历史来继续追问。由于 LLM 可以访问之前的所有消息,您现在可以提出新问题,代理会利用完整的消息上下文来回答。

接下来,您将就另一个三角形的边继续提问。

为便于使用 HumanMessage 和 AIMessage 的功能,以下模块已为您导入:HumanMessageAIMessage

本练习是课程的一部分

使用 LangChain 设计 Agentic 系统

查看课程

练习说明

  • 将给定的自然语言问题赋给 new_query
  • 调用 app 对象,传入所有消息,包括 message_historynew_query
  • 使用列表推导,从 response["messages"] 中提取标记为 HumanMessageAIMessage 的消息。
  • 将新问题作为输入,并通过将消息类传给 "agent_output" 来打印提取的消息。

交互式实操练习

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

message_history = response["messages"]
____ = "What about one with sides 12 and 14?"

# Invoke the app with the full message history
response = app.____({"messages": ____ + [("human", ____)]})

# Extract the human and AI messages from the result
filtered_messages = [msg for msg in ____["____"] if isinstance(msg, (____, ____)) and msg.content.strip()]

# Pass the new query as input and print the final outputs
print({
    "user_input": ____,
    "agent_output": [f"{msg.____.____}: {msg.content}" for msg in ____]
})
编辑并运行代码