拆解它的本質:大模型 + 工具呼叫 + 控制流程 + 狀態記憶 + 安全機制
AI Agent 並不是一個神祕的新物種,通常就是把「大模型 + 工具呼叫 + 控制流程 + 狀態記憶 + 安全機制」組合起來。
比較白話地說,它像一個會思考的「主任」:大模型負責理解任務與決策,工具負責真正做事,程式框架負責讓它反覆執行「思考 → 選工具 → 執行 → 讀結果 → 再決策」這個循環。
OpenAI Agents SDK 的官方說明把核心概念整理成 agents、tools、handoffs、guardrails、sessions、tracing 等幾個部分;LangGraph 也把 agent 描述成一種可長時間執行、可保存狀態的工作流/圖結構。
它的 quickstart 很乾淨,最適合拿來看「AI Agent 到底怎麼 implement」。官方 quickstart 直接展示三件事:定義 agent(name + instructions)、用 Runner.run() 執行、加入 tools 或 handoffs 讓 agent 不只會回答,還會做事、會轉交專家。
可以把它想成這 6 層:
Agent(...) 定義,核心是 name 與 instructions。這一層本質上就是 system prompt + agent metadata。from agents import Agent
agent = Agent(
name="History Tutor",
instructions="You answer history questions clearly and concisely.",
)
Runner.run(agent, user_input),執行後拿到 result.final_output。agent 本身像設定檔,Runner 才是實際讓它運轉的引擎。import asyncio
from agents import Agent, Runner
agent = Agent(
name="History Tutor",
instructions="You answer history questions clearly and concisely.",
)
async def main():
result = await Runner.run(agent, "When did the Roman Empire fall?")
print(result.final_output)
@function_tool 包一個 Python 函式,再放進 tools=[...]。from agents import Agent, Runner, function_tool
@function_tool
def history_fun_fact() -> str:
"""Return a short history fact."""
return "Sharks are older than trees."
agent = Agent(
name="History Tutor",
instructions="Answer history questions clearly. Use history_fun_fact when it helps.",
tools=[history_fun_fact],
)
history_fun_fact()handoffs 把任務委派給另一個專家 agent。在系統裡,handoff 是以 tool 的形式表現,讓多 agent 協作成為可能。實作上,AI Agent 很少是「模型只回答一次」;比較像這樣:
OpenAI 官方文件提到,runner 會處理 agent 執行、handoffs、tool calls;results 文件也提到一次 run 可能包含多個 response,因為中間可能經過「模型 → 工具 → 模型」或 handoff 的多步循環。
Agent 的本質,不是某個特定模型,而是這個可以反覆迭代、能調用能力、能保存狀態的控制回路。
OpenAI quickstart 示範了很典型的模式:一個分流 agent + 多個專家 agent。
history_tutor_agent = Agent(
name="History Tutor",
handoff_description="Specialist agent for historical questions",
instructions="You answer history questions clearly and concisely.",
)
math_tutor_agent = Agent(
name="Math Tutor",
handoff_description="Specialist agent for math questions",
instructions="You explain math step by step and include worked examples.",
)
triage_agent = Agent(
name="Triage Agent",
instructions="Route each homework question to the right specialist.",
handoffs=[history_tutor_agent, math_tutor_agent],
)
result = await Runner.run(
triage_agent,
"Who was the first president of the United States?",
)
print(result.final_output)
print(result.last_agent.name) # → "History Tutor"
如果問題是歷史類,最終就會被轉給 History Tutor。文件明講:handoff 是把任務委派給另一個 agent,而且在系統裡是以 tool 的形式表現。
因為它把複雜問題拆成三層,每層各司其職:
如果你自己要從零 implement,一般會有這幾個模組:
AI Agent 的核心不神祕——它是一個可反覆迭代的控制回路,讓大模型不再只是「回答問題的機器」,而是能規劃、能執行、能學習的「數位員工」。框架幫你搭好了骨架,你需要做的是定義好每一層的規則與工具。