👁️ 代码协作训练

看得懂 · 判得准 · 说得清

👁️ 模块一:读代码训练

拿到一段 Agent 代码,先别跑。用笔标注每个变量的输入输出、数据怎么流转、哪里可能炸。

import json

def run_agent(task, memory=[]):
    # 简单的 ReAct 循环
    prompt = f"任务:{task}\n历史:{memory}"
    resp = call_llm(prompt)
    thought = resp["thought"]
    action = resp["action"]
    if action == "search":
        result = search_web(resp["query"])
        memory.append(str(result))
    elif action == "done":
        return resp["answer"]
    return run_agent(task, memory)

📋 练习要求

  • 标注每行的输入 / 输出变量
  • 画出数据流转路径:task → ? → ? → 返回
  • 找出至少 2 个潜在错误,说明触发条件

✅ 参考答案

  • 数据流:task+memory → prompt → LLM → thought/action → 分支(search 存 memory / done 返回)→ 递归
  • Bug 1:memory=[] 可变默认参数,多次调用共享同一列表,记忆会"串号"
  • Bug 2:递归无最大轮数限制,LLM 一直不返回 done 会爆栈 / 烧钱
  • Bug 3:resp["thought"] 直接取键,LLM 返回格式异常会 KeyError

✂️ 模块二:拆函数训练

一段 25 行能跑但难读的脚本。目标:拆成职责单一的小函数,并画出数据流箭头。

import csv, json

def process(path):
    rows = []
    with open(path) as f:
        for r in csv.DictReader(f):
            if r["age"].isdigit() and int(r["age"]) > 0:
                rows.append({"name": r["name"].strip(),
                             "age": int(r["age"])})
    total = sum(x["age"] for x in rows)
    avg = total / len(rows) if rows else 0
    adults = [x for x in rows if x["age"] >= 18]
    report = {
        "count": len(rows),
        "avg_age": round(avg, 1),
        "adults": len(adults),
        "names": [x["name"] for x in adults]
    }
    out = path.replace(".csv", "_report.json")
    with open(out, "w") as f:
        json.dump(report, f, ensure_ascii=False)
    return out

📋 练习要求

  • 拆成 4 个函数,每个只做一件事
  • 用箭头画出数据流:原始 CSV → … → 报告文件
  • 给每个函数写一句 docstring,说清输入输出

✅ 参考拆法

  • load_valid_rows(path) -> list:读取并清洗数据
  • calc_stats(rows) -> dict:算总数/均龄/成年人数
  • build_report(rows, stats) -> dict:组装报告
  • save_report(report, path) -> str:写 JSON 文件
  • 数据流:csv 文件 → 清洗后 rows → stats+report → json 文件路径

📦 模块三:调包训练

面对需求,三步走:选对库 → 查准方法签名 → 验证 AI 给的代码是否真的对。

📋 练习场景

  • 场景 A:给 1000 个 PDF 批量提取文本,挑库并写出核心调用
  • 场景 B:把 Excel 报表按「部门」分组求和并画图,说明用哪个库的哪个方法
  • 场景 C:调用一个 REST API 并处理超时重试,验证 AI 写的 requests 代码参数是否正确

✅ 参考思路

  • A:选 pypdfpdfplumber;核心签名 page.extract_text();注意扫描件无文本层需 OCR
  • B:pandasdf.groupby("部门").sum() + matplotlibplt.bar();验证 AI 是否用了已废弃的 pd.read_excel 旧参数
  • C:requests.get(url, timeout=10) + 重试用 urllib3.Retry 挂载到 Session;检查 AI 是否漏了 timeout(最常见的坑)
  • 通用验证法:让 AI 给官方文档链接 → 对照签名 → 写最小可跑样例实测
「K3/Claude 写代码比你快 100 倍,
看得懂、判得准的能力,只有自己能长。」