開始使用免費開始

建立 ReAct 代理

現在你已經學會 LangChain 的基本元件,接下來就直接動手建立一個 ReAct 代理,使用工具 count_r_in_word 來計算任一單字中含有多少個 r。

下列物件已為你載入:toolChatOpenAIcreate_react_agentmath、以及 model

本練習屬於課程

Designing Agentic Systems with LangChain

檢視課程

練習說明

  • 使用 create_react_agent(),將 modelcount_r_in_word 加入工具清單,設定代理 app
  • 定義一個 query 變數,將使用者的問題作為字串接收。
  • .invoke() 呼叫 app,並傳入一個字典,包含 "messages" 鍵,將 query 標記為 "human"
  • 取得 response 中最後一則訊息,列印其 .content 屬性,以取得代理的回答。

動手互動練習

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

# Create the agent
____ = ____(model=____, tools=[____])

# Create a query
____ = "How many r's are in the word 'Terrarium'?"

# Invoke the agent and store the response
response = app.____({"messages": [("human", ____)]})

# Print the agent's response
print(____['messages'][____].____)
編輯並執行程式碼