首页/评测文章/入门教程

从零写你的第一个 AI Agent:不依赖框架的 100 行实现

所有 Agent 框架的文档都很长,但 Agent 的本质循环只有五行伪代码:

while 没有完成:
    把历史和可用工具告诉模型
    模型决定: 直接回答 / 调用某个工具
    如果调用工具: 执行并把结果追加到历史
    如果直接回答: 结束

这篇教程不用任何框架,100 行以内把这个循环写出来。写完之后再看 LangGraph、AutoGen,你会发现它们做的一切都是给这个循环加工程化外壳。

第一步:定义工具

工具就是一个普通函数,外加一份给模型看的说明书:

TOOLS = {}

def tool(desc):
    def deco(fn):
        TOOLS[fn.__name__] = {"fn": fn, "desc": desc}
        return fn
    return deco

@tool("查询城市当前天气,参数:城市名")
def get_weather(city: str) -> str:
    # 实际项目里这里调天气 API
    return {"北京": "晴 12℃", "上海": "小雨 15℃"}.get(city, "未收录")

@tool("计算器,参数:数学表达式")
def calc(expr: str) -> str:
    try:
        return str(eval(expr))    # 演示用,生产禁用 eval
    except Exception as e:
        return f"计算失败: {e}"

第二步:把工具说明书翻译成模型协议

主流模型都支持 function calling,我们把 TOOLS 转成它要的格式:

def tool_specs():
    return [{
        "type": "function",
        "function": {
            "name": n,
            "description": t["desc"],
            "parameters": {
                "type": "object",
                "properties": {
                    k: {"type": "string"} for k in t["fn"].__annotations__ if k != "return"
                }
            }
        }
    } for n, t in TOOLS.items()]

第三步:核心循环

from openai import OpenAI
import json

llm = OpenAI()

def run(goal, max_turns=8):
    messages = [
        {"role": "system", "content": "你是勤快的助手,能用工具就别猜。"},
        {"role": "user", "content": goal}
    ]
    for _ in range(max_turns):
        resp = llm.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            tools=tool_specs()
        )
        msg = resp.choices[0].message
        messages.append(msg)

        if not msg.tool_calls:            # 模型不再调工具 → 最终回答
            return msg.content

        for call in msg.tool_calls:        # 逐个执行工具
            args = json.loads(call.function.arguments)
            result = TOOLS[call.function.name]["fn"](**args)
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": str(result)
            })
    return "达到最大轮数,任务中断。"

print(run("北京和上海今天差几度?"))

运行它,你会看到模型连续调用两次 get_weather,再调用一次 calc,最后给出「差 3 度」——什么时候调什么工具,全是模型自己决定的,这就是 Agent。

这 100 行里藏着 Agent 的四要素

  1. 工具注册:说明书(description)质量决定模型调用准确率,值得反复打磨
  2. 循环控制:max_turns 是防失控的安全带,生产必加
  3. 记忆:messages 列表就是短期记忆,长了要做裁剪或摘要
  4. 终止条件:模型不再发起工具调用即结束,也可以设计显式的「DONE」信号

从玩具到生产还差什么

  • 错误处理:工具抛异常时把错误信息回传给模型让它自我修正,而不是直接崩
  • 可观测:每一轮的输入输出都打日志(生产用 AgentOps/Phoenix)
  • 沙箱:涉及代码执行的工具必须隔离(容器/子进程+超时)
  • 结构化流程:任务变复杂后需要分支与循环编排——这正是 LangGraph 的用武之地

学习建议

把这 100 行跑通之后,按这个顺序扩展认知:

  1. 给 calc 加危险操作拦截,体会工具安全设计
  2. 加一个「写文件」工具,观察模型怎么组合工具
  3. 读 Pocket Flow 源码(真的只有 100 行框架)对照思想
  4. 最后再学 LangGraph/AutoGen,你会秒懂每个 API 在四要素里对应什么
相关资源:本站收录 LangGraph、AutoGen、smolagents、Pocket Flow 等框架详情页,均附生产级上手步骤。
本文基于公开资料整理,版本迭代较快,请以官方文档为准。 ← 返回文章列表

相关资源

L
Agent

LangGraph 精选

基于图(状态机)的 Agent 编排框架,擅长多 Agent 协作、循环与人工介入流程,是 LangChain 官方推荐的复杂 Agent 生产方案。Graph-based agent orchestration from the LangChain team. Ideal for multi-agent collaboration, loops and human-in-the-loop workflows in production.

热度 86 详情 →
A
Agent

AutoGen

微软开源的多 Agent 对话框架,让多个 Agent 通过对话协作完成复杂任务,支持人机混合参与,学术与工业界应用广泛。Microsoft's open-source framework where multiple agents converse to solve complex tasks, with human-in-the-loop support.

热度 70 详情 →
S
Agent

smolagents

HuggingFace 出品的极简 Agent 库:主打 CodeAgent——让模型直接写 Python 代码作为行动(比 JSON 工具调用更灵活),几行代码即可搭建带工具的 Agent。HuggingFace's minimalist agent library featuring CodeAgents that write Python code as actions, more flexible than JSON tool calls.

热度 82 详情 →
P
Agent

Pocket Flow

号称「100 行」的极简 Agent 工作流框架:只抽象节点与共享存储两个概念,其余全部交给提示词,配套大量「从零实现 XX Agent」教程,极适合学习原理。A minimalist agent workflow framework in ~100 lines: only nodes and shared store abstractions, plus tons of build-from-scratch tutorials.

极简工作流教程友好轻量
热度 74 详情 →
C
编程

Claude Code 精选

Anthropic 官方终端编程 Agent:理解整个代码库、跨文件修改、执行命令与 Git 操作,支持 MCP 与自定义 Skills 扩展。Anthropic's official terminal coding agent: codebase-aware edits, shell commands and git workflows, extensible via MCP and Skills.

热度 86 详情 →
F
MCP

FastMCP

最流行的 Python MCP Server 开发框架,几行装饰器即可把函数发布为 MCP 工具,开发效率极高。The popular Pythonic framework for building MCP servers — expose functions as tools with a few decorators.

MCP开发框架Python
热度 72 详情 →
↑