啟用具記憶的多輪對話
你已經準備好把更新後的聊天機器人分享給學校行政單位了!為了讓學生有順暢的學習體驗,最好能讓他們提出追問。這樣一來,如果聊天機器人的第一個回答有遺漏,學生就能透過對話來調整問題。你現在要調整聊天機器人的串流函式,讓它支援多輪互動,同時印出使用者的查詢與聊天機器人的回答。為了啟用記憶,當有追問時,LangGraph 會把完整對話送給 LLM。首先,你的 config 參數已經替單一使用者設定好:
config = {"configurable": {"thread_id": "1"}}
本練習屬於課程
Designing Agentic Systems with LangChain
練習說明
- 每一輪先從
queries串列中印出使用者的query。 - 使用
app.stream()迭代msg與metadata,將query作為HumanMessage的content並連同config傳入,然後串接各個msg.content值。 - 為了擷取聊天機器人的回應,排除標記為
HumanMessage的msg,印出其餘的msg.content,並在下一個查詢前新增一行。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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)