建立能回傳 LLM 回應的函式
你的聊天機器人現在已經有許多可用的工具了。不過,當問題與你加到聊天機器人的任何工具都無關時,直接呼叫 LLM 仍然很有用。你現在要定義一個函式,檢查對話中的最後一則訊息是否包含可能的工具呼叫。如果沒有,聊天機器人就會單純使用 LLM 來回覆答案。為了同時處理使用者的提問與聊天機器人的回應,以下模組已為你匯入,用來處理不同型別的訊息。
from langchain_core.messages import AIMessage, HumanMessage
本練習屬於課程
Designing Agentic Systems with LangChain
練習說明
- 透過
"messages"從state取得最後一則訊息。 - 撰寫條件判斷,檢查
last_message是否為AIMessage,且該訊息同時具有tool_calls。 - 若條件成立,從
last_message的tool_calls取出第一個"response",並將其放入AIMessage的content欄位回傳。 - 若條件不成立,對
model_with_tools呼叫.invoke()產生回應,並傳入完整對話紀錄state["messages"]。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Extract the last message from the history
def call_model(state: MessagesState):
____ = ____["____"][____]
# If the last message has tool calls, return the tool's response
if isinstance(____, ____) and ____.____:
# Return only the messages from the tool call
return {"messages": [____(content=____.____[0]["____"])]}
# Otherwise, proceed with a regular LLM response
return {"messages": [____.____(____["____"])]}