翻篇收录说明
翻篇网页快照

Principles of AI Agents and Tool Calling | Easy-Vibe Tutorial

https://datawhalechina.github.io/easy-vibe/en/appendix/8-artificial-intelligence/ai-agents.html

最近抓取:2026-12-04 05:56:49(北京时间)

最近内容变化:2026-12-01 04:56:55(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn Vibe Coding from Zero to Advanced - Master AI programming with Claude Code, Cursor, and other AI IDE tools

正文摘录

Principles of AI Agents and Tool Calling ​💡 Learning Guide: This chapter requires no programming background. Through interactive demos, you'll gain a deep understanding of how AI Agents work. We'll start from the basics of "tool calling" and work our way up to how Agents plan, remember, and collaborate.🤖 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. Introduction: From "Talking" to "Doing" ​You've probably used chatbots like ChatGPT or Claude. They're powerful, but have one obvious limitation:They can only "talk," not "do"You: Check today's weather in Beijing for me ChatGPT: I cannot access real-time weather information. I suggest you check a weather forecast website...ChatGPT is like a knowledgeable but immobile scholar — it knows a lot, but can't execute any actual operations for you.0.1 Core Challenge: Approach to making AI Go from "Chatting" to "Acting" ​To achieve this goal, we need to solve three core challenges:Tools: How to let AI call external tools (search, calculate, file operations)?Planning: How to let AI break down complex tasks into executable steps?Memory: How to let AI remember context and avoid "goldfish memory"?This tutorial will guide you step by step through the process of building an Agent from scratch.1. First Step: Tool Calling ​Computers can do many things: search the web, run code, manipulate files, send emails...But LLMs inherently do not have these capabilities. Its core ability is just one thing: generating text.1.1 Motivation for Caning 't LLMs Execute Operations Directly ​An LLM is a pure text processor:Input: Text (your question)Processing: Internal computation, predicting the next tokenOutput: Text (the response)It runs in an isolated environment, unable to access the internet, execute code, or read your local files.1.2 Solution: Tool Calling ​To make LLMs "take action," we invented the Tool Calling mechanism:Core idea: The LLM doesn't execute operations directly, but instead generates "call instructions" for external systems to execute.User: What's the weather like in Beijing today? LLM thinks: The user is asking about weather, I should call the weather API LLM generates call instruction: { "tool": "weather_api", "params": { "city": "Beijing", "date": "today" } } External system executes tool → Returns result: "Sunny, 25°C" LLM generates final answer: "The weather in Beijing today is sunny, temperature is 25 degrees..."🔧 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.Key point: The essence of Tool Calling is that the LLM generates structured text telling the external system what to do.2. Core Challenge: Approach to completing Complex Tasks ​Tool calling gives LLMs the ability to "act," but real-world tasks are often complex:User: Research the latest trends in AI Agents and write a brief reportThis task involves multiple steps:Search for the latest informationRead relevant articlesExtract key informationOrganize and analyzeWrite the report2.1 Motivation for Planninging Needed ​If you let the LLM generate a report "in one shot," the results are often:Incomplete information: Only based on training data, missing the latest informationDisorganized structure: No clear logical frameworkUncontrollable quality: No way to verify the correctness of intermediate steps2.2 Solution: Planning ​An Agent acts like a project manager, first breaking down the big task into small steps:📋 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 resultsCore planning process:Understand the goal: Analyze user requirementsTask decomposition: Break complex tasks into atomic operationsStep execution: Call tools one by one to completeDynamic adjustment: Adjust subsequent plans based on intermediate results3. Memory System: Beyond the Current Conversation ​Humans can remember things from long ago, but an LLM's "memory" is very limited:Context window limit: Usually only a few thousand to tens of thousands of charactersSession isolation: Each conversation is a fresh startNo persistence: Close the page and it "forgets everything"3.1 Motivation for Memorying Needed ​Imagine this scenario:User: My name is Zhang San Agent: Hello Zhang San, nice to meet you! ... (chatting about many other topics) ... User: What did I say my name was? Agent: Sorry, I don't remember...Without memory, an Agent cannot provide personalized services.3.2 Solution: Three-Layer Memory Architecture ​Agents typically use three types of memory working together:💾 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 knowledgeDivision of labor among three types of memory:Memory TypePurposeStored ContentPersistenceShort-term MemoryCurrent conversation contextComplete conversation history❌ Cleared when session endsWorking MemoryTemporary variables and stateTask progress, user preferences❌ Cleared when task endsLong-term MemoryCross-session knowledgeUser profiles, historical records✅ Persistent storage4. The Core Loop of an Agent ​Now let's integrate the three core capabilities and look at the complete workflow of an 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. The perceive-decide-act-observe loop continues until the task is complete.5. Agent Capability Levels ​Not all Agents are equally powerful. Based on their capabilities, Agents can be divided into multiple levels: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 + summarizeDescription of each level:LevelNameCore CapabilityTypical ApplicationL0No ToolsConversation only, cannot executeChatbotsL1Single ToolUses one fixed toolCode interpreterL2Multi-ToolCan select from multiple toolsWeb AgentL3Multi-StepCan plan complex tasksData analysis AgentL4Autonomous IterationSelf-reflection and improvementResearch AgentL5Multi-Agent CollaborationMultiple Agents working togetherEnterprise systems6. Core Architecture of an Agent ​A typical Agent consists of the following modules: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 answerDetailed explanation of each module:1. LLM (Brain) ​Responsible for understanding goals, generating plans, selecting actions, and organizing language output.Input: User goal + current state + available tools listOutput: Next step plan / tool call parameters / final answer2. Tools (Hands) ​Responsible for actually "doing things": searching, reading/writing files, calling APIs, running commands.Input: tool_name + input_schema parametersOutput: Tool execution results (text/data/file changes)3. Memory ​Stores "what has been done and what results were obtained" to avoid repetition and going off-track.Input: Conversation history / tool results / current task stateOutput: Searchable context (short-term/long-term/working memory)4. Planning ​Breaks big goals into small steps and changes plans when failures occur.Input: Goal + constraints (budget/time/safety) + current progressOutput: Step list / next action / stop condition5. Guardrails ​Limits risks: permission allowlists, budget caps, confirmation for sensitive operations, sandbox execution.7. Framework Comparison ​There are many mainstream Agent development frameworks today, including LangChain, LlamaIndex, CrewAI, AutoGen, and Anthropic's official Claude Agent SDK. Each has its own characteristics and is suited for different scenarios.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 ente