页面简介
從零到一學習 Vibe Coding - 零基礎學會用 AI 編程,掌握 Claude Code、Cursor 等 AI IDE 工具
正文摘录
AI Agent 原理與工具呼叫 💡 學習指南:本章節無需程式設計基礎,透過互動式演示帶你深入瞭解 AI Agent(智慧體)的工作原理。我們將從最基本的「工具呼叫」開始,一直到 Agent 是如何規劃、記憶和協作的。🤖 Agent first experience: from “can say” to “can do”See how an Agent automatically calls tools to complete tasks🌤️Weather🧮Calculation📈Stock analysis✈️Travel plan🛒Shopping📊Research report💻Code run📉Data analysis 👤 What is the weather in Beijing today? What should I wear? 🤖 Plain LLMI cannot fetch live weather. Beijing is usually mild in spring, so a light jacket is a reasonable guess. 🦾 Agent▶ Let the Agent run💡 Core difference:The Agent calls a weather API for live data, while the LLM can only infer from training data.0. 引言:從「能說」到「能做」 你一定用過 ChatGPT、Claude 這樣的聊天機器人。它們很強大,但有一個明顯的限制:只能「說」,不能「做」你:幫我查一下今天北京的天氣 ChatGPT:我無法即時獲取天氣資訊。建議您查看天氣預報網站...ChatGPT 就像一個知識淵博但行動不便的智者——它知道很多,但無法幫你執行任何實際操作。0.1 核心挑戰:讓 AI 從「聊天」變成「行動」的方法 為了實現這個目標,我們需要解決三個核心挑戰:工具:如何讓 AI 呼叫外部工具(搜尋、計算、檔案操作)?規劃:如何讓 AI 將複雜任務分解為可執行的步驟?記憶:如何讓 AI 記住上下文,避免「金魚記憶」?本教學將帶你從零開始,一步步拆解 Agent 的建構過程。1. 第一步:工具呼叫機制 電腦可以做很多事情:搜尋網頁、執行程式碼、操作檔案、傳送郵件...但 LLM 本身沒有這些能力。它的核心能力只有一件事:生成文字。1.1 LLM 不能直接執行操作的動機 LLM 是一個純文字處理器:輸入:文字(你的問題)處理:內部計算,預測下一個詞輸出:文字(回答內容)它運行在隔離的環境中,無法存取網際網路、無法執行程式碼、無法讀取你的本機檔案。1.2 解決方案:Tool Calling(工具呼叫) 為了讓 LLM 「動手」,我們發明了 Tool Calling 機制:核心思想:LLM 不直接執行操作,而是生成「呼叫指令」,由外部系統來執行。使用者:北京今天天氣怎麼樣? LLM 思考:使用者詢問天氣,我應該呼叫天氣 API LLM 生成呼叫指令: { "tool": "weather_api", "params": { "city": "北京", "date": "today" } } 外部系統執行工具 → 回傳結果:「晴,25°C」 LLM 生成最終回答:「北京今天天氣晴朗,氣溫25度...」🔧 How does an Agent call tools?🌤️Check weather🧮Calculate🔍Search👤"Will I need an umbrella in Shanghai tomorrow?" 1 Analyze need → 2 Choose tool → 3 Build parameters → 4 Execute and return▶ Start demo💡Tool Calling means the LLM generates structured text (JSON), then an external system executes it and returns the result.關鍵點:Tool Calling 的本質是 LLM 生成結構化文字,告訴外部系統該做什麼。2. 核心難題:完成複雜任務的方法 工具呼叫讓 LLM 具備了「行動能力」,但現實中的任務往往很複雜:使用者:幫我調研一下最近 AI Agent 的發展趨勢,寫一份簡要報告這個任務包含多個步驟:搜尋最新資訊閱讀相關文章提取關鍵資訊整理分析撰寫報告2.1 需要規劃的動機 如果讓 LLM 「一步到位」生成報告,結果往往是:資訊不全:只基於訓練資料,缺少最新資訊結構混亂:沒有清晰的邏輯框架品質不可控:無法驗證中間步驟的正確性2.2 解決方案:Planning(規劃能力) Agent 會像專案經理一樣,先把大任務拆解成小步驟:📋 Agent Planning Ability🌤️Check weatherEasy📊Data analysisMedium🔬Research reportComplex🎯Check today’s weather in Beijing1Call weather API2Format result📝 Execution logClick “Start execution” to see the process▶ Start execution💡Planning means splitting complex tasks into atomic operations, then dynamically adjusting later steps based on previous results規劃的核心流程:理解目標:分析使用者需求任務分解:將複雜任務拆分為原子操作步驟執行:逐一呼叫工具完成動態調整:根據中間結果調整後續計畫3. 記憶系統:不止於當前上下文 人類可以記住很久以前的事情,但 LLM 的「記憶」很有限:上下文視窗限制:通常只有幾千到幾萬字會話隔離:每次對話都是全新的開始無法持久化:關掉頁面就「失憶」3.1 需要記憶的動機 想像這樣一個場景:使用者:我叫張三 Agent:你好張三,很高興認識你! ...(聊了很多其他話題)... 使用者:我之前說過我叫什麼? Agent:抱歉,我不記得了...沒有記憶,Agent 就無法提供個人化的服務。3.2 解決方案:三層記憶架構 Agent 通常採用三種記憶類型協同工作:💾 Agent Memory SystemMy name is Zhang SanI like PythonRecommend a programming bookWhat is my name?🔄 Reset💬 ConversationClick a button above to start the conversation⏱️ Short-term memory0Empty📝 Working memory0Empty🗄️ Long-term memory0Empty💡Short-term=current conversation, working=temporary variables, long-term=cross-session knowledge三種記憶的分工:記憶類型作用儲存內容持久化短期記憶當前對話上下文完整對話歷史❌ 會話結束清空工作記憶臨時變數和狀態任務進度、使用者偏好❌ 任務結束清空長期記憶跨會話知識使用者畫像、歷史記錄✅ 持久化儲存4. Agent 的核心循環 現在我們把三個核心能力整合起來,看看 Agent 的完整工作流程:Try it first: an Agent is not chat, it is an action loopIt repeats: observe → plan → use tools → check results.ResetNext round (1/3)👀Observe🧩Plan🔧Act✅CheckTaskFind 3 beginner articles about “Agent” and output: title + one-sentence summary.What happened in this round?Saw the user goal: 3 beginner articles plus short summaries.Agent run log (example)--- Round 1 --- OBS: Saw the user goal: 3 beginner articles plus short summaries. PLAN: Plan: 1) search keywords 2) open top results 3) extract titles and key points. ACT: Call tool: web_search(query="agent introduction"). CHECK: Check: 3 usable links found, but one-sentence summaries are still missing. 感知—決策—行動—觀察的循環會持續進行,直到任務完成。5. Agent 的能力分級 不是所有 Agent 都一樣強大。根據能力不同,Agent 可以分為多個等級:Agent Capability Levels: from chat to collaborationDrag the slider: higher levels feel more like an independent coworker.Current: L2: multiple tools012345What it can doChoose among toolsCombine calls as neededCommon problemsTool choice may be unstablePermissions and safety need controlTypical taskSearch + open web page + summarize各級別說明:級別名稱核心能力典型應用L0無工具只能對話,不能執行聊天機器人L1單工具使用一個固定工具程式碼直譯器L2多工具可以選擇多個工具Web AgentL3多步驟可以規劃複雜任務資料分析 AgentL4自主迭代主動反思和改進研究 AgentL5多 Agent 協作多個 Agent 配合企業級系統6. Agent 的核心架構 一個典型的 Agent 由以下模組組成:What modules make up an Agent?Click a module to see what it is responsible for.🧠LLM (brain)🔧Tools (hands)💾Memory🧩Planning🛡️GuardrailsUser goal → plan → tool call → result → re-plan…(Memory runs through the whole process)🧠 LLM (brain)Understands goals, generates plans, chooses actions, and writes final responses.Typical inputUser goal + current state + available tool listTypical outputNext-step plan / tool call arguments / final answer各模組詳解:1. LLM(大腦) 負責理解目標、生成計畫、選擇動作、組織語言輸出。輸入:使用者目標 + 當前狀態 + 可用工具列表輸出:下一步計畫 / 工具呼叫參數 / 最終回答2. Tools(手腳) 負責真正「做事」:搜尋、讀寫檔案、呼叫 API、執行命令。輸入:tool_name + input_schema 參數輸出:工具執行結果(文字/資料/檔案變更)3. Memory(記憶) 把「已經做過什麼、得到什麼結果」存起來,避免重複與跑偏。輸入:對話歷史 / 工具結果 / 當前任務狀態輸出:可檢索的上下文(短期/長期/工作記憶)4. Planning(規劃) 把大目標拆成小步驟,並在失敗時改計畫。輸入:目標 + 約束(預算/時間/安全) + 當前進度輸出:步驟清單 / 下一步動作 / 停止條件5. Guardrails(護欄) 限制風險:權限白名單、預算上限、敏感操作確認、沙箱執行。7. 主流框架對比 目前主流的 Agent 開發框架有很多,包括 LangChain、LlamaIndex、CrewAI、AutoGen,以及 Anthropic 官方推出的 Claude Agent SDK。它們各有特色,適用於不同的場景。Mainstream framework comparison: start with fitChoose your priority first, then read the recommendation.Quick startControl/debuggingMulti-Agent collaborationFrameworkLearningControlMulti-AgentBest forLangChain / LangGraphMediumHighMediumControllable tool calls, workflows, and enterprise integrationAutoGenMediumMediumHighMulti-agent conversation, programming, and analysis assistantsCrewAILowMediumHighTeam tasks with clear role divisionRecommended now: LangChain / LangGraphRepresenting flows as graphs or steps makes debugging, launch, and maintenance easier.7.1 核心差異:官方原生 vs 第三方封裝 對比項Claude Agent SDKLangChain / LlamaIndex / CrewAI 等開發方Anthropic 官方第三方開源社群模型最佳化為 Claude 深度最佳化多模型通用,需要自行調優內建工具讀寫檔案、Bash、搜尋等開箱即用需要自行整合或設定Agent Loop內建,無需實作需要自己組裝或依賴框架抽象程式碼生成品質針對程式碼場景專項最佳化通用設計,程式碼能力依賴模型本身學習曲線低,API 簡潔中高,概念多、抽象層複雜7.2 Claude Agent SDK vs LangChain LangChain 是最流行的 Agent 框架之一,提供了豐富的元件和鏈式呼叫能力:python# LangChain:需要組裝多個元件 from langchain.agents import AgentExecutor, create_react_agent from langchain.tools import tool from langchain import hub @tool def read_file(path: str) -> str: """讀取檔案內容""" with open(path) as f: return f.read() # 需要自己定義 prompt、組裝 agent、處理工具循環 prompt = hub.pull("hwchase17/react") agent = create_react_agent(llm, [read_file], prompt) agent_executor = AgentExecutor(agent=agent, tools=[read_file]) result = agent_executor.invoke({"input": "修復 auth.py 的 bug"})python# Claude Agent SDK:一行搞定,工具內建 from claude_agent_sdk import query, ClaudeAgentOptions async for message in query( prompt="修復 auth.py 的 bug", options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]), ): print(message)關鍵區別:LangChain 是工具箱,你需要自己挑選元件、組裝流程Agent SDK 是成品,針對程式碼場景已經調優好,拿來即用7.3 Claude Agent SDK vs CrewAI CrewAI 專注於多 Agent 協作,強調角色扮演和任務分配:python# CrewAI:定義多個角色協作 from crewai import Agent, Task, Crew coder = Agent(role="程式設計師", goal="編寫程式碼", backstory="...") reviewer = Agent(role="審查員", goal="審查程式碼", backstory="...") task = Task(description="開發功能", agent=coder) crew = Crew(agents=[coder, reviewer], tasks=[task]) result = crew.kickoff()關鍵區別:CrewAI 擅長角色扮演和協作流程設計,適合模擬團隊工作流Agent SDK 專注於程式碼執行和工具呼叫,適合實際開發任務7.4 Claude Agent SDK vs LlamaIndex LlamaIndex 核心是 RAG(檢索增強生成),專注於連接 LLM 與外部資料:python# LlamaIndex:建構知識庫查詢 from llama_index import VectorStoreIndex, SimpleDirectoryReader documents = SimpleDirectoryReader("data").load_data() index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() response = query_engine.query("總結這份文件")關鍵區別:LlamaIndex 是資料連接器,解決「如何讓 LLM 存取我的資料」Agent SDK 是任務執行器,解決「如何讓 LLM 完成複雜開發任務」7.5 綜合對比表 特性Claude Agent SDKLangChainCrewAILlamaIndexAutoGen開發方Anthropic 官方第三方第三方第三方微軟核心定位程式碼開發 Agent通用 LLM 框架角色驅動團隊資料檢索增強多 Agent 協作學習曲線平緩中等平緩中等較陡內建工具✅ 豐富(檔案、Bash、搜尋)需設定需設定需設定✅ 程式碼執行多 Agent✅ 支援透過 LangGraph✅ 原生❌✅ 原生程式碼場景✅ 深度最佳化一般一般不適用✅ 程式設計支援模型綁定Claude 專用多模型多模型多模型多模型適用場景自動化開發、CI/CD企業級客製內容創作/研究知識庫問答程式設計/資料分析7.6 框架選擇建議 如果你的需求是...推薦框架程式碼開發、自動化修復、CI/CD 整合Claude Agent SDK高度自訂流程、多模型支援LangChain多 Agent 角色扮演、模擬團隊協作CrewAI建構企業知識庫、文件問答LlamaIndex程式設計任務、資料分析、多 Agent 協作AutoGen研究性專案、探索完全自主 AIAutoGPT8. 實戰:建構你的第一個 Agent 讓我們用 Python 建構一個簡單的 Agent:8.1 基礎版本:單工具 Agent pythonimport json class SimpleAgent: """最簡單的 Agent:理解意圖 → 選擇工具 → 執行 """ def __init__(self): self.tools = { "weather": self.get_weather, "calculate": self.calculate } def get_weather(self, city): # 模擬天氣查詢 return f"{city}今天天氣晴朗,25°C" def calculate(self, expression): # 安全計算(實際應用中需要更嚴格的沙箱) try: result = eval(expression, {"__builtins__": {}}, {}) return f"計算結果:{result}" except: return "計算出錯" def decide_tool(self, user_input): """簡單的意圖辨識""" if "天氣" in user_input: return "weather", user_input.split("天氣")[0].strip() elif any(op in user_input for op in ["+", "-", "*", "/"]): return "calculate", user_input return None, None def run(self, user_input): tool_name, params = self.decide_tool(user_input) if tool_name: result = self.tools[tool_name](params) return f"[呼叫 {tool_name}] {result}" else: return "我不確定如何幫你,試試問天氣或計算" # 使用 agent = SimpleAgent() print(agent.run("北京天氣怎麼樣?")) # 輸出: [呼叫 weather] 北京今天天氣晴朗,25°C8.2 進階版本:多工具 + 規劃 pythonimport re class PlanningAgent: """具備規劃能力的 Agent:分解任務 → 逐步執行 """ def __init__(self): self.tools = { "search": self.web_search, "read": self.read_page, "summarize": self.summarize } self.memory = [] def web_search(self, query): # 模擬搜尋 return [f"關於'{query}'的文章1", f"關於'{query}'的文章2"] def read_page(self, url): # 模擬閱讀 return f"{url} 的內容摘要..." def summarize(self, texts): # 模擬總結 return "總結:" + "; ".join(texts)[:100] + "..." def plan(self, goal): """根據目標生成執行計畫""" if "搜尋" in goal or "查" in goal: return [ ("search", goal), ("read", "result_0"),