构建由 LLM 驱动的自动化工作流:进阶模式

使用 LLM 构建自动化与传统脚本编写有着本质区别。你不再是编写僵化的逻辑,而是在搭建能够适应新情况、理解上下文并做出细致决策的智能代理。
本指南涵盖了区分可用原型与生产级自动化的各种模式。
范式转变:从逻辑到推理
团队讨论想法——示意图
传统自动化使用流程图:如果 X,则 Y。LLM 自动化的工作方式则不同。你无需设定僵化的条件,只需描述目标,让 Claude 推理出最佳方案。
传统方式:
- 客户取消 → 发送模板 3 → 标记为停用
- 95% 的情况下有效,遇到特殊情况就会失效
LLM 驱动:
- 客户请求取消 → Claude 分析请求并以同理心作出回应
- 提供替代方案、挽留激励或体面退出
- 在 95% 以上的情况下有效,并能适应上下文
这种转变要求你重新思考自动化架构。
工作流模式 1:输入 → 分析 → 行动
人工智能图形
每个 LLM 自动化都遵循这一核心模式:
Input (email, form, file)
↓
Claude analysis (understand intent, extract data, reason about next step)
↓
Action (send response, trigger tool, update system)
示例:处理客服邮件
async function processEmail(email) {
// INPUT: Get the email
const content = email.body;
// ANALYSIS: Claude understands the issue
const analysis = await claude.ask(`
Analyze this support email:
- What is the customer's main issue?
- What information are we missing?
- What should we do next?
Email: ${content}
`);
// ACTION: Execute based on analysis
if (analysis.includes("missing info")) {
sendEmail(email.from, "We need more details...");
} else if (analysis.includes("bug")) {
createBugTicket(analysis.details);
} else {
sendResponse(analysis.suggestedResponse);
}
}
这一模式适用于各种场景:客户请求、内容审核、数据分类、研究摘要。
工作流模式 2:带状态的多步骤推理
团队讨论想法——示意图
真实的工作流包含多个阶段。使用 Claude 来决定下一步该做什么:
const workflow = {
stages: {
analyze: "Understand the request",
enrichData: "Gather additional context",
validate: "Check feasibility",
execute: "Perform the action",
confirm: "Report results"
},
async run(input) {
let state = { stage: "analyze", data: input };
while (state.stage !== "complete") {
const nextStep = await claude.ask(`
Current stage: ${state.stage}
Data: ${JSON.stringify(state.data)}
What should we do next? (respond with stage name)
`);
state = await this[nextStep](state);
}
return state;
}
};
这样无需硬编码每一条决策路径,就能实现智能路由。
工作流模式 3:工具使用与函数调用
电脑上的软件代码——示意图
当 Claude 能够调用工具时,真正的威力才会显现。定义 Claude 能做什么,然后让它自行决定使用哪个工具:
const tools = [
{
name: "search_knowledge_base",
description: "Search internal documentation",
parameters: { query: "string" }
},
{
name: "create_ticket",
description: "Create support ticket in system",
parameters: { title: "string", priority: "enum" }
},
{
name: "send_email",
description: "Send email to customer",
parameters: { to: "string", body: "string" }
}
];
async function automateWithTools(userRequest) {
let response = await claude.ask(userRequest, { tools });
// Claude might ask to use a tool
while (response.type === "tool_use") {
const result = await executeToolCall(response.toolName, response.args);
response = await claude.continue(result);
}
return response.text;
}
Claude 会决定使用哪些工具、传入什么参数以及何时停止。你定义能力,由它决定策略。
工作流模式 4:错误处理与恢复
健壮的工作流会预判故障,并借助 Claude 来决定恢复策略
LLM 工作流的故障方式有所不同。网络问题、API 限制、无效响应——你需要智能化的恢复机制:
async function robustAutomation(input) {
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
// Main workflow
const result = await executeWorkflow(input);
return result;
} catch (error) {
attempt++;
// Use Claude to decide if we should retry
const shouldRetry = await claude.ask(`
Automation failed with: ${error.message}
Attempt: ${attempt} of ${maxRetries}
Should we retry, or is this a permanent failure?
Explain your reasoning.
`);
if (!shouldRetry.includes("retry")) {
// Permanent failure—escalate
await escalateToHuman(input, error);
return null;
}
// Wait before retry (exponential backoff)
await sleep(Math.pow(2, attempt) * 1000);
}
}
}
当 Claude 检测到无法恢复的错误时,不要悄无声息地失败,而应升级交由人工处理。
优化:Token 管理
笔记本电脑上的分析仪表板——示意图
随着工作流规模扩大,token 成本会激增。优化方法如下:
1. 批量处理相似请求 不要为每个条目都调用 Claude——一次处理 10 个:
// Bad: 100 API calls
items.forEach(item => processWithClaude(item));
// Good: 5 API calls
const batches = chunk(items, 20);
for (const batch of batches) {
processBatchWithClaude(batch);
}
2. 使用缓存上下文 如果您需要反复分析同一个知识库,请将其缓存:
const knowledgeBase = `... 50KB of documentation ...`;
// First call: processes full docs (counted in tokens)
await claude.ask(`Using this knowledge base: ${knowledgeBase}. Answer: ${q1}`);
// Subsequent calls: reuse cache (cheaper)
await claude.ask(`Answer: ${q2}`); // Already has context
3. 精确指定输出格式 模糊的输出需要后续追问。格式清晰 = 一次请求搞定:
// Bad: requires follow-up to get structured data
"Analyze this customer feedback"
// Good: get structured output immediately
"Analyze this feedback. Respond in JSON: { sentiment, topics: [], actionItems: [] }"
4. 简单任务使用更便宜的模型 并非所有任务都需要 Claude 3 Opus。Haiku 足以胜任分类任务:
if (isComplexReasoning) {
response = await claudeOpus.ask(prompt); // $15/M in tokens
} else {
response = await claudeHaiku.ask(prompt); // $0.80/M in tokens
}
成本节省会随规模叠加。一个 10 步的工作流使用最优模型组合,相比全部使用 Opus:成本降低 90%。
工作流模式 5:异步处理与 Webhook
团队讨论想法——示意图
有些工作流需要数分钟。请使用异步模式:
// User submits request
app.post("/analyze", async (req, res) => {
const jobId = generateId();
// Don't wait—start background job
startBackgroundJob(jobId, req.body);
// Return immediately
res.json({ jobId, status: "processing" });
});
// Background job runs independently
async function startBackgroundJob(jobId, data) {
const result = await complexAnalysis(data);
// Call webhook when done
await fetch(callbackUrl, {
method: "POST",
body: JSON.stringify({ jobId, result })
});
}
// Client polls or receives webhook
app.get("/jobs/:id", (req, res) => {
const job = getJobStatus(req.params.id);
res.json(job); // { status: "completed", result: ... }
});
对于长时间运行的工作流,请始终使用异步方式。用户不会为了一个响应等待 5 分钟。
生产环境检查清单
人工智能图形
部署到生产环境之前:
- ☐ 使用边界情况进行测试(空输入、超长输入、特殊字符)
- ☐ 设置 API 速率限制和配额
- ☐ 实现日志记录和监控
- ☐ 创建成功率、成本和延迟的仪表板
- ☐ 为错误设置告警
- ☐ 规划每月的 token 预算并据此优化
- ☐ 对高风险决策建立人工审核流程
- ☐ 测试 API 宕机时的回退行为
- ☐ 为您的团队编写工作流文档
- ☐ 对所有提示词和配置进行版本控制
- ☐ 从小流量开始,逐步提升
结论
笔记本电脑上的分析仪表板——示意图
LLM 自动化不仅仅是自动执行任务——而是用智能推理取代僵化的逻辑。本指南中的模式可以从每周运行一次的脚本,扩展到每天处理数千个请求的系统。
从简单开始:输入 → Claude 分析 → 执行操作。随着复杂度增加,再加入状态管理、工具使用和错误恢复。毫不留情地优化 token。监控一切。
率先落地 LLM 自动化的团队并不是在构建更好的算法,而是在围绕推理而非逻辑重新思考他们的工作流。这种转变解锁了传统自动化无法企及的能力。
常见问题
问:工作流和智能体(agent)有什么区别? A:工作流是线性的(按顺序执行步骤)。智能体是自主的(自行决定步骤)。已定义的流程使用工作流;开放式任务使用智能体。
问:我应该使用 OpenClaw 还是自己构建? 答:OpenClaw 正是为此而生。从零开始构建意味着要重写监控、日志、调度和错误处理。除非你有 OpenClaw 无法满足的特殊需求,否则请使用 OpenClaw。
问:在 LLM 工作流中如何处理敏感数据? 答:切勿将真正敏感的数据发送到 API。请先进行假名化、令牌化或哈希处理。处理个人身份信息(PII)时,请查阅 API 文档中的数据驻留要求。
问:运行一个典型的工作流需要多少费用? 答:差异很大。每日邮件摘要:每月 $0.10。处理 10,000 个客服工单:每月 $200。请根据你的 token 用量和模型定价进行估算。
问:如果 Claude 分析出错怎么办? 答:对关键决策加入人工审核。记录所有 Claude 的回复。持续监控成功率。当准确率下降时调整提示词。
更多文章
OpenClaw AWS 终极设置指南

在 AWS 上设置 OpenClaw 的权威指南。包括竞价实例配置、成本优化以及分步说明。
在 OpenClaw 中使用工具链构建 AI 工作流
掌握串联工具和函数调用的技巧,构建强大的多步骤 AI 自动化工作流——从数据提取到内容生成和部署。
自托管 AI 助手成本优化指南:低预算运行 Claude
降低自托管 AI 助手 API 成本的实用策略——智能模型路由、缓存、批处理,以及针对 OpenClaw 的优化,让 Claude 的运行更经济实惠。