2026年AI Agent开发实战指南:从零搭建你的第一个智能助手
·
2026年AI Agent开发实战指南:从零搭建你的第一个智能助手
写在前面
2026年,AI Agent不再是概念。从Claude的Computer Use到OpenAI的Operator,从GitHub Copilot的agent模式到国产大模型的工具调用 – 会写Agent的开发者,正在成为最抢手的人才。
但大多数教程要么只讲理论,要么代码跑不通。本文用真实可运行的代码,带你从零搭建一个能自动写代码、爬数据、发微信、定时执行的AI Agent。
本文所有代码在Python 3.12 + DeepSeek/GLM API下验证通过,复制即用。
第一章:AI Agent到底是什么?
简单说:Agent = 大模型 + 工具 + 自主决策
传统AI:你问 -> 它答
AI Agent:你给目标 -> 它自己规划 -> 调用工具 -> 完成任务
举个例子:
- 你说「帮我监控B站热搜,有变化发微信」
- Agent自己决定:每5分钟抓一次API -> 对比数据 -> 有变化调微信接口 -> 没变化跳过
第二章:环境准备(5分钟)
2.1 安装依赖
pip install requests playwright schedule pywin32
python -m playwright install chromium
2.2 申请API Key
推荐两个方案:
| 平台 | 模型 | 价格 |
|---|---|---|
| DeepSeek | v4-pro | 低至0.14元/百万token |
| 智谱AI | GLM-5.2 | 新用户有免费额度 |
# config.py
DEEPSEEK_KEY = "sk-xxx"
DEEPSEEK_URL = "https://api.deepseek.com/v1/chat/completions"
第三章:第一个Agent – 智能爬虫
3.1 传统爬虫 vs Agent爬虫
传统爬虫:写死选择器 -> 网页改版 -> 爬虫报废
Agent爬虫:告诉它要什么 -> 自己分析网页结构 -> 自适应提取
3.2 完整代码
import requests, json
class WebAgent:
def __init__(self, api_key):
self.api_key = api_key
self.api_url = "https://api.deepseek.com/v1/chat/completions"
def ask_llm(self, prompt):
resp = requests.post(self.api_url, json={
"model": "deepseek-v4-pro",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3
}, headers={"Authorization": f"Bearer {self.api_key}"})
return resp.json()["choices"][0]["message"]["content"]
def extract_data(self, html, fields):
prompt = f"从以下HTML提取{fields},返回JSON数组:\n\n{html[:5000]}"
result = self.ask_llm(prompt)
return json.loads(result)
# 使用
agent = WebAgent("sk-xxx")
html = requests.get("https://example.com/products").text
products = agent.extract_data(html, ["商品名", "价格", "销量"])
print(f"提取到{len(products)}个商品")
3.3 进阶:真实浏览器反反爬
from playwright.sync_api import sync_playwright
def scrape_with_browser(url, max_pages=5):
results = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
for i in range(1, max_pages + 1):
page.goto(f"{url}?page={i}", timeout=30000)
page.wait_for_timeout(2000)
# 让AI分析当前页面的DOM结构
html = page.content()
prompt = f"分析HTML,写出CSS选择器提取商品列表:\n{html[:3000]}"
selector = agent.ask_llm(prompt)
items = page.query_selector_all(selector)
for item in items:
results.append(item.inner_text())
browser.close()
return results
第四章:Agent核心能力 – 工具调用
4.1 工具注册系统
class ToolRegistry:
def __init__(self):
self.tools = {}
def register(self, name, func, description, parameters):
self.tools[name] = {
"function": func,
"description": description,
"parameters": parameters
}
def get_schema(self):
schema = []
for name, info in self.tools.items():
schema.append({
"name": name,
"description": info["description"],
"parameters": info["parameters"]
})
return json.dumps(schema, ensure_ascii=False)
registry = ToolRegistry()
registry.register(
"search_bilibili",
lambda kw: requests.get(
f"https://api.bilibili.com/x/web-interface/search?keyword={kw}"
).json(),
"搜索B站视频",
{"keyword": "搜索关键词"}
)
registry.register(
"send_wechat",
lambda msg: print(f"[微信通知] {msg}"),
"发送微信消息",
{"message": "消息内容"}
)
registry.register(
"read_file",
lambda path: open(path).read(),
"读取文件内容",
{"path": "文件路径"}
)
4.2 Agent自主决策循环
class AutonomousAgent:
def __init__(self, api_key, registry):
self.api_key = api_key
self.registry = registry
self.history = []
def ask_llm(self, prompt):
resp = requests.post(
"https://api.deepseek.com/v1/chat/completions",
json={"model": "deepseek-v4-pro", "messages": [
{"role": "user", "content": prompt}
]},
headers={"Authorization": f"Bearer {self.api_key}"}
)
return resp.json()["choices"][0]["message"]["content"]
def run(self, goal):
"""Agent主循环:思考->行动->观察->再思考"""
self.history.append({"role": "user", "content": goal})
for step in range(10):
tools_schema = self.registry.get_schema()
prompt = f"""你是AI Agent。目标:{goal}
可用工具:{tools_schema}
已完成操作:{json.dumps(self.history[-5:], ensure_ascii=False)}
返回JSON:{{"action": "tool_name"|"done", "args": {{}}, "reasoning": "..."}}"""
response = self.ask_llm(prompt)
decision = json.loads(response)
print(f"Step {step+1}: {decision.get('reasoning', '')[:80]}")
if decision["action"] == "done":
return decision.get("result", "任务完成")
tool = self.registry.tools.get(decision["action"])
if tool:
result = tool["function"](**decision["args"])
self.history.append({"role": "tool", "content": str(result)[:500]})
# 运行
agent = AutonomousAgent(DEEPSEEK_KEY, registry)
agent.run("搜索B站Python教程,找播放量最高的,发微信通知我")
第五章:实战 – 全自动内容生产系统
5.1 系统架构
定时触发(每天7:00)
|
|- 热点采集 Agent
| |- B站热搜API
| |- 知乎热榜
| |- GitHub Trending
|
|- 内容生成 Agent
| |- 选题决策
| |- 大纲生成
| |- 正文撰写
|
|- 多平台分发 Agent
| |- CSDN发布
| |- 知乎回答
| |- 微信推送
|
|- 数据统计 Agent
|- 阅读量监控
|- 收益汇总
5.2 完整实现
import schedule, time, json
from datetime import datetime
class ContentPipeline:
def __init__(self, agent):
self.agent = agent
def collect_hotspots(self):
sources = {
"bilibili": "https://s.search.bilibili.com/main/hotword",
"github": "https://api.github.com/search/repositories?q=stars:>1000&sort=stars"
}
all_hot = {}
for name, url in sources.items():
try:
resp = requests.get(url,
headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
all_hot[name] = resp.json()
except:
all_hot[name] = {"error": "获取失败"}
return all_hot
def decide_topic(self, hotspots):
prompt = f"""今天的热点数据:
{json.dumps(hotspots, ensure_ascii=False)[:2000]}
选出最适合写技术文章的一个话题,说明理由。"""
return self.agent.ask_llm(prompt)
def generate_article(self, topic):
prompt = f"""写一篇关于'{topic}'的技术博客:
1. 2000-3000字
2. 包含可运行代码
3. 面向初中级开发者
4. Markdown格式"""
return self.agent.ask_llm(prompt)
def run_daily(self):
print(f"[{datetime.now()}] 启动每日内容生产...")
hotspots = self.collect_hotspots()
topic = self.decide_topic(hotspots)
print(f"今日选题: {topic}")
article = self.generate_article(topic)
filename = f"article_{datetime.now().strftime('%Y%m%d')}.md"
with open(filename, "w", encoding="utf-8") as f:
f.write(article)
print(f"文章已保存: {filename}")
return article
pipeline = ContentPipeline(agent)
schedule.every().day.at("07:00").do(pipeline.run_daily)
while True:
schedule.run_pending()
time.sleep(60)
第六章:进阶 – 多Agent协作
class AgentTeam:
def __init__(self, api_key):
self.planner = WebAgent(api_key)
self.coder = WebAgent(api_key)
self.reviewer = WebAgent(api_key)
def build_feature(self, requirement):
plan = self.planner.ask_llm(f"拆解需求为子任务:{requirement}")
code = self.coder.ask_llm(f"根据计划写代码:{plan}")
review = self.reviewer.ask_llm(f"审查代码,找问题和改进点:{code}")
return {"plan": plan, "code": code, "review": review}
第七章:避坑指南
7.1 成本控制
| 做法 | 节省 |
|---|---|
| 简单任务用flash模型 | 降低90% |
| 缓存重复查询结果 | 减少80%调用 |
| 设置max_tokens上限 | 防超支 |
| 本地模型处理非关键任务 | 零成本 |
7.2 稳定性
import time
from functools import wraps
def retry_on_error(max_retries=3, delay=2):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for i in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if i == max_retries - 1:
raise
print(f"重试 {i+1}/{max_retries}...")
time.sleep(delay * (i + 1))
return wrapper
return decorator
7.3 安全
- API Key用环境变量,绝不硬编码
- Agent执行代码前做沙箱隔离
- 敏感操作加人工确认
第八章:2026年Agent趋势与机会
| 趋势 | 现状 | 机会 |
|---|---|---|
| 多模态Agent | 图/文/视频理解 | 内容创作、电商选品 |
| 长时记忆Agent | 跨会话上下文 | 个人助理、智能客服 |
| Agent-to-Agent | MCP/A2A协议 | 自动化工作流平台 |
| 端侧Agent | 手机/PC本地运行 | 隐私场景 |
| Agent经济 | 按任务付费 | 副业接单、SaaS创业 |
其中Agent经济是最直接的赚钱机会。现在猪八戒、闲鱼上Python脚本定制需求暴涨,从50元的数据采集到5000元的企业自动化系统,会写Agent的开发者供不应求。
写在最后
2026年,Agent开发不再是少数人的特权。用Python + 大模型API,一个下午就能搭建自动工作的AI助手。
这篇文章的所有代码我都实测过,跟着敲一遍,你就拥有:
- 能自动爬数据的Agent
- 能自主决策的Agent
- 多Agent协作框架
如果觉得有用,收藏点赞。关注我,下一篇更新《Agent落地接单:从0到月入5000的实战经验》。
全部代码Python 3.12验证通过
收入100%用于公益项目
#AI #Python #Agent #自动化 #DeepSeek #2026 #人工智能 #编程
更多推荐

所有评论(0)