你已经掌握了"文档自动化工厂"的核心模式。现在我们来看看怎么把这个模式扩展到更多真实场景。

第 9 课:进阶扩展


学完了,然后呢?

你已经掌握了"文档自动化工厂"的核心模式。现在我们来看看怎么把这个模式扩展到更多真实场景。

扩展一:公司调研报告生成器

把"搜人名生成简历"改成"搜公司名生成调研报告"。

改什么?

code
// 系统提示词改一下
const SYSTEM_PROMPT = `You are a professional business analyst.
Research a company and create a comprehensive analysis report as .docx.

WORKFLOW:
1. WebSearch for the company (official site, news, financial data)
2. WebFetch key pages for detailed information
3. Create a .docx report using the docx library

OUTPUT:
- Script: agent/custom_scripts/generate_report.js
- Report: agent/custom_scripts/company_report.docx

REPORT STRUCTURE:
- Company Overview (1 paragraph)
- Key Products/Services (bullet list)
- Financial Highlights (table if data available)
- Competitive Landscape (2-3 competitors)
- SWOT Analysis (4 sections)
- Conclusion & Outlook (1 paragraph)

FORMAT: Arial font, 1-inch margins, max 3 pages`;

// 用户提示词改一下
const prompt = `Research "${companyName}" and create a professional
                company analysis report as a .docx file.`;

核心代码几乎不变

bash
// 只改了变量名和文案,逻辑完全一样
async function generateReport(companyName: string) {
  const outputDir = path.join(process.cwd(), 'agent', 'custom_scripts');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const q = query({
    prompt: `Research "${companyName}" and create a professional
             company analysis report as a .docx file.`,
    options: {
      maxTurns: 30,
      cwd: process.cwd(),
      model: 'sonnet',
      allowedTools: ['Skill', 'WebSearch', 'WebFetch', 'Bash', 'Write', 'Read', 'Glob'],
      settingSources: ['project'],
      systemPrompt: SYSTEM_PROMPT,
    },
  });

  // 消息处理逻辑完全一样...
  for await (const msg of q) {
    // 和 resume-generator 一模一样的处理逻辑
  }
}

你看,代码框架不变,只改提示词和输出路径。这就是 Agent 编程的威力。

扩展二:合同模板生成器

code
const SYSTEM_PROMPT = `You are a legal document specialist.
Create a contract template based on user requirements.

WORKFLOW:
1. Analyze the contract type and key terms provided
2. Create a .docx contract using the docx library

OUTPUT:
- Script: agent/custom_scripts/generate_contract.js
- Contract: agent/custom_scripts/contract.docx

CONTRACT FORMAT:
- Title: 16pt bold centered
- Section headers: 12pt bold
- Body: 11pt, justified alignment
- 1-inch margins
- Page numbers in footer
- Signature block at the end`;

// 用法
const prompt = `Create a ${contractType} contract with these terms:
  - Parties: ${partyA} and ${partyB}
  - Duration: ${duration}
  - Key terms: ${keyTerms}`;

这个场景不需要 WebSearch(合同内容是用户提供的),可以从 allowedTools 里去掉:

bash
allowedTools: ['Skill', 'Bash', 'Write', 'Read', 'Glob']
// 不需要搜索和抓网页了

扩展三:批量处理

如果你要给一组人生成简历:

code
const people = ["Tim Cook", "Satya Nadella", "Jensen Huang"];

for (const person of people) {
  console.log(`\n>>> Processing: ${person}`);
  await generateResume(person);
  console.log(`<<< Done: ${person}\n`);
}

注意这里是串行执行(一个一个来),因为每次 query() 都要调用 AI,并行的话成本会很高。

扩展四:添加更多技能

你可以在 .claude/skills/ 目录下添加新的技能。比如加一个 PDF 技能:

code
.claude/skills/
├── docx/
│   ├── SKILL.md
│   └── docx-js.md
└── pdf/                ← 新增
    ├── SKILL.md        ← PDF 技能说明
    └── pdf-lib.md      ← PDF 库参考

然后在系统提示词里告诉 AI 可以生成 PDF:

code
const SYSTEM_PROMPT = `You are a document specialist.
Create documents in the format requested by the user.
Supported formats: .docx (Word), .pdf (PDF)`;

AI 会根据任务需要自动选择读取哪个技能。

扩展五:加入 Hooks 监控

SDK 支持 Hooks(钩子),让你在 AI 使用工具前后做一些额外操作。比如记录日志:

code
// 这是概念示意,具体 API 请参考 SDK 文档
const q = query({
  prompt,
  options: {
    // ...其他配置...
    hooks: {
      preToolUse: (toolName, input) => {
        console.log(`[LOG] AI is about to use: ${toolName}`);
        console.log(`[LOG] Input: ${JSON.stringify(input)}`);
        // 你还可以在这里拦截某些危险操作
        // 比如阻止 AI 删除文件
      },
      postToolUse: (toolName, result) => {
        console.log(`[LOG] ${toolName} returned: ${result}`);
      }
    }
  },
});

Hooks 的常见用途:

Hook 用途
preToolUse 记录日志、拦截危险操作、修改参数
postToolUse 记录结果、统计工具使用次数

扩展六:切换到 Python SDK

这个教程的例子用的是 TypeScript SDK,但同样的模式可以用 Python SDK 实现:

bash
from claude_agent_sdk import query

SYSTEM_PROMPT = """You are a professional resume writer..."""

async def generate_resume(person_name: str):
    q = query(
        prompt=f'Research "{person_name}" and create a resume...',
        options={
            "max_turns": 30,
            "model": "sonnet",
            "allowed_tools": ["Skill", "WebSearch", "WebFetch",
                              "Bash", "Write", "Read", "Glob"],
            "system_prompt": SYSTEM_PROMPT,
        }
    )

    async for msg in q:
        # 处理消息流...
        pass

核心概念完全一样,只是语法从 TypeScript 换成了 Python。

你学到的核心模式

回顾整套教程,你学到了一个通用的"文档自动化"框架:

graph TD A["输入:用户需求(人名/公司名/合同要点等)"] --> B["1. 系统提示词<br>定义角色、流程、输出格式、约束条件"] B --> C["2. 工具箱<br>搜索、写文件、执行代码等"] C --> D["3. 技能系统<br>docx/pdf/xlsx 等操作手册"] D --> E["4. query 启动 AI<br>AI 自主完成任务"] E --> F["输出:格式精美的文档文件"] style A fill:#f9f,stroke:#333 style F fill:#9f9,stroke:#333

行动建议

  1. 先跑通原项目:确保 resume-generator 能正常工作
  2. 改一个场景试试:比如改成公司调研报告
  3. 设计自己的技能:如果需要新的文档格式
  4. 加入错误处理:实际项目需要更健壮的错误处理
  5. 考虑成本:每次 query() 都会消耗 API 额度,批量处理要注意

总结

9 课教程,我们从"这玩意是什么"到"怎么自己扩展"走了一个完整闭环:

课次 学了什么 关键词
01 项目全貌 搜索→写代码→生成文档
02 环境搭建 Node.js, npm, API Key
03 query() 核心 prompt, model, maxTurns, allowedTools
04 工具系统 WebSearch, Bash, Write, Read, Skill, Glob, WebFetch
05 技能系统 SKILL.md, docx-js.md, settingSources
06 系统提示词 角色、流程、输出、约束
07 代码生成模式 AI 写代码 → 执行 → 产出文件
08 完整实战 98 行代码逐行解读
09 进阶扩展 调研报告、合同、批量、Hooks

记住核心公式:好的提示词 + 合适的工具 + 专业的技能 = AI 帮你干活

祝你搭建出自己的文档自动化工厂!


沿着当前专题继续,或返回课程目录重新整理阅读顺序。

返回课程目录