就對話紀錄提出問題
在 LangChain 中,使用基本的 ReAct 代理(agent)時,只要保留代理的對話紀錄,就能追問後續問題。由於 LLM 可以存取所有先前的訊息,你現在可以提出新問題,而代理能利用完整的訊息脈絡來回應。
接下來你會就另一個三角形的邊長提出追問。
為了能使用 HumanMessage 和 AIMessage 的功能,以下模組已替你匯入:HumanMessage、AIMessage。
本練習屬於課程
Designing Agentic Systems with LangChain
練習說明
- 將給定的自然語言問題指定給
new_query。 - 呼叫
app物件,並傳入所有訊息,包括message_history與new_query。 - 使用列表生成式,從
response["messages"]中擷取標記為HumanMessage或AIMessage的訊息。 - 將新問題作為輸入,並將訊息類別傳入
"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 ____]
})