iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
生成式 AI

30 天打造你的 AI Agent:LangChain × n8n 實戰系列 第 16

進階推理:ReAct 架構與多步驟思考

  • 分享至 

  • xImage
  •  

昨天我們讓 Agent 學會使用工具,能做查詢或計算。
但如果問題需要「多步驟思考」才能完成,單純呼叫工具就不夠了。
今天,我們要讓 Agent 更像一個真正的思考者 —— 引入 ReAct(Reason + Act)架構


一、什麼是 ReAct?

ReAct 是一種 多步推理框架,核心概念是:

  1. Reason(思考) → LLM 判斷接下來該做什麼
  2. Act(行動) → 根據推理結果選擇工具、查資料或運算

這樣,Agent 就能處理 需要拆解任務 的情境,例如:

  • 多步數學計算
  • 查詢後再比較/彙整結果
  • 需要依序呼叫多個工具的任務

二、實作範例:多步數學問題

from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.agents import initialize_agent, Tool, AgentType
from langchain.agents import AgentType
import os

# -------------------------------
# 1. API Key 設定
# -------------------------------

# Gemini LLM API Key
os.environ["GOOGLE_API_KEY"] = ""

# 計算工具
def calculate(expression: str) -> str:
    try:
        return str(eval(expression))
    except:
        return "計算錯誤"

calc_tool = Tool(
    name="Calculator",
    func=calculate,
    description="計算數學題,例如 12*8+5"
)

# 初始化 LLM
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", temperature=0)

# 初始化 ReAct Agent
agent = initialize_agent(
    tools=[calc_tool],
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,  # <- 改成有效類型
    verbose=True
)

# 測試
question = "請先算 12*8,再加上 5,最後乘以 2"
response = agent.run(question)
print(response)

💡 ReAct Agent 的運作流程會是:

  1. Reason:思考「12*8=96,再加5=101,最後乘2」
  2. Act:一步步使用計算器工具完成
  3. Answer:最終輸出 202

三、今日小結

  • ReAct = Reason + Act,讓 Agent 先思考,再採取行動
  • 能處理 多步推理與工具整合 的任務
  • 是之後進階應用(例如規劃型 Agent、Tool Chaining)的基礎

上一篇
LLM Agent 的開發流程:從基礎到互動式 UI
系列文
30 天打造你的 AI Agent:LangChain × n8n 實戰16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言