ANALYSIS
OpenClaw 工作流的用法,实现多 Agent 协作
概述
工作流是 OpenClaw 中实现多 Agent 协作的核心机制。通过定义工作流,可以让多个 Agent 按照预定的逻辑协同工作,完成复杂的任务。本文将详细介绍工作流的使用方法和多 Agent 协作的最佳实践。
工作流基础概念
什么是工作流
工作流是一系列有序的任务步骤,每个步骤可以由不同的 Agent 执行。工作流定义了:
- 任务的执行顺序
- Agent 之间的协作方式
- 数据的流转路径
- 错误处理机制
工作流的优势
| 优势 | 说明 | 示例 |
|---|---|---|
| 职责分离 | 每个 Agent 专注于特定领域 | 代码审查 Agent 只处理代码 |
| 并行执行 | 多个任务同时进行 | 同时搜索多个数据源 |
| 复用性 | 工作流模板可重复使用 | 标准化的研究流程 |
| 可维护性 | 清晰的流程结构 | 易于调试和优化 |
| 可扩展性 | 灵活添加新步骤 | 集成新的技能和工具 |
工作流配置基础
工作流文件结构
PRTCL // YAML
name: "基础工作流"id: "basic-workflow"version: "1.0.0"description: "一个简单的工作流示例"
# 触发条件triggers: - type: "manual" # 手动触发 - type: "command" # 命令触发 command: "/workflow basic" - type: "schedule" # 定时触发 cron: "0 9 * * *" # 每天 9:00
# 全局变量variables: projectName: "my-project" maxRetries: 3 timeout: 300
# 执行步骤steps: - id: "step1" name: "数据收集" agent: "data-collector" action: "collect_data" inputs: source: "web" query: "{{ variables.projectName }}" outputs: - name: "raw_data" type: "array"
- id: "step2" name: "数据分析" agent: "data-analyst" action: "analyze_data" inputs: data: "{{ steps.step1.outputs.raw_data }}" outputs: - name: "insights" type: "object"
- id: "step3" name: "报告生成" agent: "tech-writer" action: "generate_report" inputs: insights: "{{ steps.step2.outputs.insights }}" format: "markdown" outputs: - name: "report" type: "string"
# 错误处理errorHandling: enabled: true strategy: "continue" # continue, stop, retry maxRetries: 3 notifyOnFailure: true
# 完成后的操作onComplete: - type: "notification" channel: "telegram" message: "工作流 {{ workflow.name }} 已完成" - type: "log" level: "info" message: "工作流执行成功"步骤类型
.2.1 Agent 执行步骤
PRTCL // YAML
- id: "agent_step" type: "agent" name: "执行 Agent 任务" agent: "code-reviewer" action: "review_code" inputs: code: "{{ inputs.sourceCode }}" rules: ["quality", "security"] outputs: - name: "reviewResult" type: "object" timeout: 120 retry: maxAttempts: 3 backoff: "exponential".2.2 并行执行步骤
PRTCL // YAML
- id: "parallel_search" type: "parallel" name: "并行搜索" branches: - id: "search_google" agent: "web-searcher" action: "search" inputs: engine: "google" query: "{{ inputs.query }}" - id: "search_baidu" agent: "web-searcher" action: "search" inputs: engine: "baidu" query: "{{ inputs.query }}" - id: "search_bing" agent: "web-searcher" action: "search" inputs: engine: "bing" query: "{{ inputs.query }}" outputs: - name: "searchResults" type: "array" merge: true.2.3 条件执行步骤
PRTCL // YAML
- id: "conditional_step" type: "conditional" name: "条件执行" condition: "{{ inputs.complexity > 5 }}" then: - id: "complex_analysis" agent: "analyst" action: "deep_analysis" else: - id: "simple_analysis" agent: "analyst" action: "quick_analysis".2.4 循环执行步骤
PRTCL // YAML
- id: "loop_step" type: "loop" name: "批量处理" iterateOver: "{{ inputs.items }}" steps: - id: "process_item" agent: "processor" action: "process" inputs: item: "{{ item }}" index: "{{ index }}" outputs: - name: "processedItems" type: "array".2.5 子工作流步骤
PRTCL // YAML
- id: "subworkflow" type: "subworkflow" name: "执行子工作流" workflow: "research-workflow" inputs: topic: "{{ inputs.topic }}" depth: 3 outputs: - name: "researchResult" type: "object"多 Agent 协作模式
管道模式
Agent 按顺序处理数据,每个 Agent 的输出成为下一个 Agent 的输入。
PRTCL // YAML
name: "数据处理管道"id: "pipeline-workflow"description: "使用管道模式处理数据"
steps: - id: "extract" name: "数据提取" agent: "data-extractor" action: "extract" inputs: source: "{{ inputs.source }}" outputs: - name: "rawData"
- id: "transform" name: "数据转换" agent: "data-transformer" action: "transform" inputs: data: "{{ steps.extract.outputs.rawData }}" format: "normalized" outputs: - name: "normalizedData"
- id: "validate" name: "数据验证" agent: "data-validator" action: "validate" inputs: data: "{{ steps.transform.outputs.normalizedData }}" schema: "{{ inputs.schema }}" outputs: - name: "validatedData"
- id: "load" name: "数据加载" agent: "data-loader" action: "load" inputs: data: "{{ steps.validate.outputs.validatedData }}" destination: "{{ inputs.destination }}"协作模式
多个 Agent 共同协作完成一个任务,可能存在交叉引用和相互依赖。
PRTCL // YAML
name: "协作代码审查"id: "collaborative-workflow"description: "多个 Agent 协作进行代码审查"
steps: - id: "initial_review" name: "初步审查" agent: "code-reviewer" action: "quick_review" inputs: code: "{{ inputs.code }}" outputs: - name: "initialFindings" - name: "complexityScore"
- id: "parallel_review" type: "parallel" name: "并行深度审查" branches: - id: "security_review" agent: "security-analyst" action: "security_check" inputs: code: "{{ inputs.code }}" findings: "{{ steps.initial_review.outputs.initialFindings }}" outputs: - name: "securityIssues"
- id: "performance_review" agent: "performance-analyst" action: "performance_check" inputs: code: "{{ inputs.code }}" complexity: "{{ steps.initial_review.outputs.complexityScore }}" outputs: - name: "performanceIssues"
- id: "style_review" agent: "style-analyst" action: "style_check" inputs: code: "{{ inputs.code }}" outputs: - name: "styleIssues"
- id: "consolidate" name: "整合结果" agent: "review-coordinator" action: "consolidate_findings" inputs: security: "{{ steps.parallel_review.branches.security_review.outputs.securityIssues }}" performance: "{{ steps.parallel_review.branches.performance_review.outputs.performanceIssues }}" style: "{{ steps.parallel_review.branches.style_review.outputs.styleIssues }}" initial: "{{ steps.initial_review.outputs.initialFindings }}" outputs: - name: "finalReport"
- id: "generate_fixes" name: "生成修复建议" agent: "code-generator" action: "generate_fixes" inputs: report: "{{ steps.consolidate.outputs.finalReport }}" outputs: - name: "fixSuggestions"监督模式
一个监督 Agent 协调多个工作 Agent,负责任务分配、进度跟踪和结果整合。
PRTCL // YAML
name: "监督式研究"id: "supervisor-workflow"description: "使用监督 Agent 协调研究任务"
steps: - id: "supervisor_init" name: "初始化任务" agent: "research-supervisor" action: "initialize" inputs: topic: "{{ inputs.topic }}" objectives: "{{ inputs.objectives }}" outputs: - name: "researchPlan" - name: "tasks"
- id: "assign_tasks" name: "分配任务" agent: "research-supervisor" action: "assign_tasks" inputs: tasks: "{{ steps.supervisor_init.outputs.tasks }}" availableAgents: ["researcher-a", "researcher-b", "researcher-c"] outputs: - name: "assignments"
- id: "execute_tasks" type: "parallel" name: "执行研究任务" branches: - id: "task_a" agent: "{{ steps.assign_tasks.outputs.assignments[0].agent }}" action: "execute_task" inputs: task: "{{ steps.assign_tasks.outputs.assignments[0].task }}" outputs: - name: "result_a"
- id: "task_b" agent: "{{ steps.assign_tasks.outputs.assignments[1].agent }}" action: "execute_task" inputs: task: "{{ steps.assign_tasks.outputs.assignments[1].task }}" outputs: - name: "result_b"
- id: "task_c" agent: "{{ steps.assign_tasks.outputs.assignments[2].agent }}" action: "execute_task" inputs: task: "{{ steps.assign_tasks.outputs.assignments[2].task }}" outputs: - name: "result_c"
- id: "monitor_progress" name: "监控进度" agent: "research-supervisor" action: "monitor" inputs: tasks: "{{ steps.assign_tasks.outputs.assignments }}" parallel: true # 与 execute_tasks 并行执行
- id: "consolidate_results" name: "整合结果" agent: "research-supervisor" action: "consolidate" inputs: results: - "{{ steps.execute_tasks.branches.task_a.outputs.result_a }}" - "{{ steps.execute_tasks.branches.task_b.outputs.result_b }}" - "{{ steps.execute_tasks.branches.task_c.outputs.result_c }}" outputs: - name: "finalReport"
- id: "quality_check" name: "质量检查" agent: "quality-reviewer" action: "review" inputs: report: "{{ steps.consolidate_results.outputs.finalReport }}" criteria: ["accuracy", "completeness", "clarity"] outputs: - name: "qualityScore" - name: "feedback"对话模式
Agent 之间通过对话交换信息,进行迭代式的协作。
PRTCL // YAML
name: "对话式协作"id: "conversation-workflow"description: "Agent 通过对话协作完成复杂任务"
steps: - id: "initiate_conversation" name: "发起对话" agent: "coordinator" action: "initiate" inputs: topic: "{{ inputs.topic }}" participants: ["expert-a", "expert-b", "expert-c"] outputs: - name: "conversationId"
- id: "discussion_rounds" type: "loop" name: "多轮讨论" maxIterations: 5 condition: "{{ steps.discussion_rounds.iteration < variables.maxRounds }}" steps: - id: "collect_opinions" name: "收集意见" agent: "coordinator" action: "collect_opinions" inputs: conversationId: "{{ steps.initiate_conversation.outputs.conversationId }}" round: "{{ steps.discussion_rounds.iteration }}" outputs: - name: "opinions"
- id: "synthesize" name: "综合意见" agent: "coordinator" action: "synthesize" inputs: opinions: "{{ steps.collect_opinions.outputs.opinions }}" previousContext: "{{ steps.discussion_rounds.context }}" outputs: - name: "synthesis" - name: "needsMoreDiscussion"
- id: "check_convergence" name: "检查收敛" agent: "coordinator" action: "check_convergence" inputs: synthesis: "{{ steps.synthesize.outputs.synthesis }}" outputs: - name: "converged" onCondition: condition: "{{ outputs.converged }}" action: "break"
- id: "final_conclusion" name: "得出结论" agent: "coordinator" action: "conclude" inputs: conversationId: "{{ steps.initiate_conversation.outputs.conversationId }}" finalSynthesis: "{{ steps.discussion_rounds.steps.synthesize.outputs.synthesis }}" outputs: - name: "conclusion" - name: "agreement"高级工作流特性
事件驱动
PRTCL // YAML
name: "事件驱动工作流"id: "event-driven-workflow"description: "基于事件触发的工作流"
triggers: - type: "event" event: "code_push" filters: - field: "branch" value: "main" - field: "repository" value: "my-project"
- type: "event" event: "issue_created" filters: - field: "labels" contains: ["bug", "critical"]
steps: - id: "handle_event" name: "处理事件" agent: "event-handler" action: "process" inputs: event: "{{ trigger.event }}" payload: "{{ trigger.payload }}" outputs: - name: "actionRequired"
- id: "conditional_action" type: "conditional" condition: "{{ steps.handle_event.outputs.actionRequired }}" then: - id: "execute_action" agent: "action-executor" action: "execute" inputs: action: "{{ steps.handle_event.outputs.action }}"动态分支
PRTCL // YAML
name: "动态分支工作流"id: "dynamic-branch-workflow"description: "根据条件动态创建分支"
steps: - id: "analyze_input" name: "分析输入" agent: "analyzer" action: "analyze" inputs: data: "{{ inputs.data }}" outputs: - name: "categories"
- id: "dynamic_parallel" type: "dynamic_parallel" name: "动态并行处理" branches: source: "{{ steps.analyze_input.outputs.categories }}" template: id: "{{ item.id }}" agent: "processor" action: "process" inputs: category: "{{ item.name }}" data: "{{ item.data }}" outputs: - name: "result" outputs: - name: "allResults"状态持久化
PRTCL // YAML
name: "有状态工作流"id: "stateful-workflow"description: "可以暂停和恢复的工作流"
state: enabled: true storage: "redis" ttl: 86400 # 24 小时
checkpoints: - step: "data_collection" name: "数据收集完成" - step: "analysis" name: "分析完成" - step: "report_generation" name: "报告生成完成"
steps: - id: "data_collection" name: "数据收集" agent: "data-collector" action: "collect" inputs: source: "{{ inputs.source }}" outputs: - name: "data"
- id: "manual_review" name: "人工审核" type: "manual" description: "请审核收集的数据" waitForApproval: true timeout: 3600
- id: "analysis" name: "分析" agent: "analyst" action: "analyze" inputs: data: "{{ steps.data_collection.outputs.data }}" approved: "{{ steps.manual_review.outputs.approved }}"事务处理
PRTCL // YAML
name: "事务工作流"id: "transaction-workflow"description: "支持事务的工作流"
transaction: enabled: true isolation: "serializable" timeout: 300
steps: - id: "operation_1" name: "操作 1" agent: "database-agent" action: "update" inputs: table: "users" record: "{{ inputs.user }}" transactional: true
- id: "operation_2" name: "操作 2" agent: "database-agent" action: "update" inputs: table: "audit_log" record: action: "user_update" timestamp: "{{ now() }}" transactional: true
- id: "operation_3" name: "操作 3" agent: "notification-agent" action: "send" inputs: recipient: "{{ inputs.user.email }}" message: "Your profile has been updated" transactional: true
onFailure: action: "rollback" notify: true工作流管理
部署工作流
PRTCL // BASH
# 复制工作流文件cp workflow.yaml ~/.openclaw/workspace/workflows/
# 重新加载工作流docker compose exec openclaw npm run reload-workflows
# 验证工作流docker compose exec openclaw npm run validate-workflow --id=my-workflow执行工作流
PRTCL // BASH
# 手动触发docker compose exec openclaw npm run execute-workflow --id=my-workflow
# 带参数触发docker compose exec openclaw npm run execute-workflow --id=my-workflow --params='{"topic":"AI","depth":3}'
# 查看执行状态docker compose exec openclaw npm run workflow-status --execution-id=exec-123
# 暂停工作流docker compose exec openclaw npm run pause-workflow --execution-id=exec-123
# 恢复工作流docker compose exec openclaw npm run resume-workflow --execution-id=exec-123
# 取消工作流docker compose exec openclaw npm run cancel-workflow --execution-id=exec-123监控工作流
PRTCL // BASH
# 查看工作流列表docker compose exec openclaw npm run list-workflows
# 查看工作流历史docker compose exec openclaw npm run workflow-history --id=my-workflow
# 查看实时日志docker compose exec openclaw npm run workflow-logs --execution-id=exec-123 --follow
# 查看性能指标docker compose exec openclaw npm run workflow-metrics --id=my-workflow最佳实践
设计原则
- 模块化:将复杂工作流分解为可复用的子工作流
- 单一职责:每个步骤只做一件事
- 可测试性:每个步骤应该可以独立测试
- 错误处理:完善的错误处理和重试机制
- 可观测性:详细的日志和监控
性能优化
- 并行执行:尽可能使用并行步骤
- 缓存:缓存中间结果
- 批处理:批量处理相似任务
- 资源管理:合理分配资源
安全建议
- 输入验证:验证所有输入
- 权限控制:限制 Agent 访问权限
- 审计日志:记录所有操作
- 敏感数据:加密敏感信息
故障排查
工作流卡住
可能原因:
- 等待外部输入
- 资源不足
- 死锁
解决方案:
PRTCL // BASH
# 查看工作流状态docker compose exec openclaw npm run workflow-status --execution-id=exec-123
# 查看详细日志docker compose exec openclaw npm run workflow-logs --execution-id=exec-123 --verbose
# 强制终止docker compose exec openclaw npm run cancel-workflow --execution-id=exec-123 --forceAgent 协作失败
检查项:
- Agent 是否可用
- 依赖关系是否正确
- 数据格式是否匹配
性能问题
排查步骤:
- 查看性能指标
- 识别瓶颈步骤
- 优化并行执行
- 调整资源分配
资源链接
- OpenClaw 工作流文档: https://docs.openclaw.ai/workflows
- 工作流模式: https://www.workflowpatterns.com/
- Multi-Agent 系统论文: https://arxiv.org/list/cs.MA/recent
最后更新: 2026-03-12 作者: EchoHaoRan
R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.04.08
Auth_Verified: 2026.04.08
