查詢與回應
代理的圖已經設定完成,你的聊天機器人可以開始執行了!現在你要定義一個函式,讓聊天機器人能用 ChatGPT 回答提問。這個函式會即時串流圖中的事件,並將最後一則訊息作為對使用者提問的回應。
本練習屬於課程
Designing Agentic Systems with LangChain
練習說明
- 定義
stream_graph_updates()函式,接受字串參數user_input作為聊天機器人的輸入。 - 對
graph使用.stream()方法,將事件以串流方式輸出,並把user_input作為"messages"中的"user"訊息。 - 對於
event.values()中的每個item,使用item的"messages"索引鍵擷取並列印回應。 - 將
user_query傳入stream_graph_updates()函式以測試聊天機器人。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define a function to execute the chatbot based on user input
def stream_graph_updates(____: ____):
# Start streaming events from the graph with the user's input
for event in graph.____({"____": [("____", ____)]}):
# Retrieve and print the chatbot node responses
for ____ in event.values():
print("Agent:", ____["____"])
# Define the user query and run the chatbot
____ = "Who is Ada Lovelace?"
stream_graph_updates(____)