第 11 课 · 造一个 Agent

把你学到的所有东西串起来——写一个能自动整理文件的 AI Agent

我们要造什么

一个 文件整理 Agent。给它一个文件夹路径,它会:

核心理念:AI 不是写死的程序,它会自己"看"文件夹内容,自己"想"怎么分类,然后动手。你只给目标,不给步骤。

Agent 的工具清单

给 Agent 三把"刀":

list_files列出文件夹里有什么文件
create_folder创建一个子文件夹
move_file把文件移动到指定文件夹

完整代码

创建 F:\aiagent学习\agent-file-organizer.py:

import os, json
from openai import OpenAI

client = OpenAI(api_key="sk-52c14...", base_url="https://api.deepseek.com")

# ============ 工具定义 ============
TOOLS = [{
    "type": "function",
    "function": {
        "name": "list_files",
        "description": "列出指定文件夹中的所有文件(递归)",
        "parameters": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        }
    }
}, {
    "type": "function",
    "function": {
        "name": "create_folder",
        "description": "创建一个文件夹(如果不存在)",
        "parameters": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        }
    }
}, {
    "type": "function",
    "function": {
        "name": "move_file",
        "description": "移动文件到目标文件夹",
        "parameters": {
            "type": "object",
            "properties": {
                "source": {"type": "string"},
                "destination": {"type": "string"}
            },
            "required": ["source", "destination"]
        }
    }
}]

SYSTEM_PROMPT = """你是一个文件整理助手。规则:
1. 先 list_files 看看有什么文件
2. 按类型分类:图片(.jpg/.png/.gif)放"图片"文件夹,文档(.pdf/.doc/.txt)放"文档",代码(.py/.js/.html)放"代码",视频(.mp4)放"视频",其他放"其他"
3. create_folder 创建分类文件夹,move_file 移动文件
4. 每移动一个文件后汇报进度
5. 全部完成后说"✅ 整理完成"并总结"""

def execute_tool(tool_call):
    """执行 AI 请求的工具"""
    name = tool_call.function.name
    args = json.loads(tool_call.function.arguments)

    if name == "list_files":
        files = []
        for root, dirs, filenames in os.walk(args["path"]):
            for f in filenames:
                files.append(os.path.join(root, f))
        return "\n".join(files) if files else "(空文件夹)"

    elif name == "create_folder":
        os.makedirs(args["path"], exist_ok=True)
        return f"已创建: {args['path']}"

    elif name == "move_file":
        import shutil
        os.makedirs(os.path.dirname(args["destination"]), exist_ok=True)
        shutil.move(args["source"], args["destination"])
        return f"已移动: {os.path.basename(args['source'])} → {args['destination']}"

def agent(task, max_steps=15):
    """核心 Agent 循环"""
    messages = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": task}
    ]

    for step in range(1, max_steps + 1):
        print(f"\n{'='*40}\n📍 Step {step}/{max_steps}\n")

        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            tools=TOOLS
        )
        msg = response.choices[0].message

        # AI 没有请求工具 → 任务完成
        if not msg.tool_calls:
            print(f"🤖 {msg.content}")
            return msg.content

        # 执行工具
        for tc in msg.tool_calls:
            print(f"🔧 {tc.function.name}: {tc.function.arguments}")
            result = execute_tool(tc)
            print(f"   → {result[:100]}")

            messages.append({"role": "assistant", "tool_calls": [tc]})
            messages.append({"role": "tool", "content": result})

            print(f"   💰 {response.usage.total_tokens} tokens this round")

    print("⚠️ 达到最大步数")

# ============ 运行 ============
if __name__ == "__main__":
    target = input("📂 要整理哪个文件夹?> ").strip()
    if os.path.isdir(target):
        agent(f"请整理文件夹: {target}")
    else:
        print("❌ 文件夹不存在")

跑起来

1. 创建 F:\aiagent学习\test-folder\,随便扔几个不同类型的文件进去

2. python agent-file-organizer.py

3. 输入 F:\aiagent学习\test-folder

4. 看 Agent 自己扫描、分类、移动文件

检验标准:Agent 自动把 test-folder 里的文件按类型分到不同子文件夹。过程中每一步都打印出来,你能看到它"思考→行动→观察→再思考"的完整过程。

这个 Agent 的局限(故意留的)

这是教学版,有几个故意没解决的问题,你以后可以自己改进:

1 没有安全检查——移动文件前不确认

2 Token 会膨胀——没有实现上下文压缩

3 分类规则太死——可以根据文件内容分类而不是只看后缀

4 没有"撤销"功能——移动错了回不去

这些就是 Level 4→进阶的路。真正的 Agent 开发就是不断解决这些问题。

你还能造什么 Agent

同样的循环(Think→Act→Observe),换上不同的工具和 System Prompt:

循环不变,工具决定能力。

你学完了全部 11 课。回头看:

你从一个"不知道 Token 是什么"的小白,变成了能写出自己 Agent 的人。

返回课程首页