建立 ReAct 代理
現在你已經學會 LangChain 的基本元件,接下來就直接動手建立一個 ReAct 代理,使用工具 count_r_in_word 來計算任一單字中含有多少個 r。
下列物件已為你載入:tool、ChatOpenAI、create_react_agent、math、以及 model。
本練習屬於課程
Designing Agentic Systems with LangChain
練習說明
- 使用
create_react_agent(),將model與count_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'][____].____)