最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
不用任何框架:从零手写一个 AI Agent
时间:2026-07-11 10:36:46 编辑:袖梨 来源:一聚教程网
不用任何框架,从零手写一个 AI Agent
什么是 Agent?跟普通 AI 有什么区别?
普通 AI:你问 → 它答,一问一答。

Agent:你给任务 → 它自己决定用什么工具 → 执行 → 看结果 → 不满意再调 → 直到完成任务。
普通AI:"1+1等于几" → "2"Agent: "帮我算 (15*8+200)/4" → 调计算器 → 拿结果 → "等于80"
Agent 的本质:一个 while 循环
Agent 的代码结构简单到离谱——你 Week 1 就写过:
# Week 1 的聊天机器人while True:user_input = input("你: ")reply = api.call(user_input)print(f"AI: {reply}")# Week 4 的 Agentwhile not done:response = api.call(messages, tools=[计算器, 读文件, Python沙箱...])if response wants to use tool:result = run_tool(response.tool_name, response.args)messages.append(result) # 把工具结果告诉 AIelse:print(response.content) # AI 给出最终答案done = True
多出来的只是"判断要不要调工具"这一步。
完整代码(150行核心逻辑)
import jsonfrom openai import OpenAItools = [{"type": "function","function": {"name": "calculator","description": "计算数学表达式","parameters": {"type": "object","properties": {"expression": {"type": "string"}},"required": ["expression"]}}}]def run_agent(client, task, max_iterations=8):messages = [{"role": "system", "content": "你是一个Agent,可以用工具完成任务。"},{"role": "user", "content": task}]for i in range(max_iterations):response = client.chat.completions.create(model="deepseek-chat",messages=messages,tools=tools,# ← 关键:告诉 AI 有哪些工具stream=False)msg = response.choices[0].messageif msg.tool_calls:# AI 决定调工具messages.append(msg)for tc in msg.tool_calls:args = json.loads(tc.function.arguments)result = eval(args["expression"])# 执行工具messages.append({"role": "tool","tool_call_id": tc.id,"content": str(result)})continue # 回到循环开头,让 AI 看结果return msg.content # AI 直接回答了return "达到最大循环次数"
这就是 Agent 的全部秘密——没有黑魔法,没有复杂框架。
我做了哪些工具
| 工具 | 能干什么 |
|---|---|
| calculator | 安全计算数学表达式 |
| read_file | 读本地文件 |
| write_file | 写入文件 |
| list_files | 列目录 |
| python_repl | 安全执行 Python(沙箱隔离) |
| get_current_time | 查时间 |
| search_docs | 在文档中语义搜索(接入了 RAG) |
多工具组合才见真章
Agent 真正厉害的不是单次工具调用,而是一次任务多次决策:
用户:"先看看项目目录有什么文件,读最大的那个,然后总结"→ Agent: list_files → 发现 plan.md 最大→ Agent: read_file("plan.md") → 获取内容→ Agent: 输出总结(全程自己决策,没问我"要读哪个文件")
关键要点
- Tool Calling 是 API 原生能力——DeepSeek/OpenAI 都支持,不需要框架
- 非流式获取 tool_calls——工具调用时不能用
stream=True - 温度设低点——Agent 决策要确定性,0.1-0.3 最合适
- 安全沙箱——Python 执行工具必须隔离,我用 AST 检查 + 黑名单
项目地址
GitHub:github.com/Speed-Fanta…
完整代码在 week04/ + week06/(Agent 升级版,加了文档检索)。
下一篇:Python 新手如何用 AI 辅助两个月做出 6 个项目
相关文章
- 普通人的找工作软件推荐 靠谱好用的求职APP排行榜 07-11
- 免费压缩软件推荐:好用又安全的压缩解压工具下载 07-11
- 情侣一起看电影的APP推荐 远距离同步观影与互动功能实用榜单 07-11
- 钓鱼天气APP推荐 钓鱼人常用精准天气软件排行榜 07-11
- 短时天气预报软件推荐:精准实时天气App排行榜 07-11
- 屏幕共享软件推荐 - 屏幕分享与远程控制APP对比评测 07-11