開始使用免費開始

加入節點與邊

現在你的 StateGraph() 已就緒,是時候把聊天機器人的節點加入圖形了!預先建好的 STARTEND 節點是直接從 LangGraph 匯入的,所以你只需要建立一個 chatbot 節點。你也會定義邊,以決定聊天機器人從開始到結束的對話流向。當節點與邊都加入後,編譯圖形,讓它準備好接受查詢並執行。

本練習屬於課程

Designing Agentic Systems with LangChain

檢視課程

練習說明

  • 定義 chatbot 函式:在 state 目前的 "messages" 上呼叫 llm.invoke(),並回傳其回應。
  • 使用 .add_node() 將名為 "chatbot"、參照 chatbot 函式的節點加入圖形。
  • 使用 .add_edge()START 節點連到 "chatbot" 節點,並將 "chatbot" 連到 END 節點,以定義對話的邊。
  • 使用 .compile() 編譯圖形,讓它準備好執行。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define chatbot function to respond with the model
def chatbot(state: State):
    return {"messages": [llm.____(____["____"])]}

# Add chatbot node to the graph
graph_builder.____("____", ____)

# Define the start and end of the conversation flow
graph_builder.____(____, "____")
graph_builder.____("____", ____)

# Compile the graph to prepare for execution
graph = graph_builder.____()
編輯並執行程式碼