OpenClaw 工具编排:让 Agent 成为"乐队指挥"

一个工具是一把小提琴,两个工具是二重奏,三个以上的工具——那就是交响乐团。问题是,谁来指挥?答案是:工具编排(Tool Orchestration)。今天,我们聊聊如何让你的 Agent 从"独奏家"变成"指挥家"。

什么是工具编排?

工具编排是指 Agent 如何组织、调度、协调多个工具完成任务。就像厨师不会把所有食材一起倒进锅里,而是按照菜谱依次下料、控制火候、调整顺序。

编排模式一览:

顺序执行模式

最基础的编排方式,适用于有明确依赖关系的任务。

场景:数据分析报告生成

workflow:
  name: "data_analysis_report"
  steps:
    - id: "fetch_data"
      tool: "database.query"
      params:
        sql: "SELECT * FROM sales WHERE date >= '2026-01-01'"
        
    - id: "analyze"
      tool: "python.analyze"
      params:
        data: "${fetch_data.result}"
        methods: ["trend", "anomaly", "forecast"]
        
    - id: "generate_charts"
      tool: "chart.generator"
      params:
        analysis: "${analyze.result}"
        type: ["line", "bar", "pie"]
        
    - id: "write_report"
      tool: "document.writer"
      params:
        template: "monthly_report"
        data: "${analyze.result}"
        charts: "${generate_charts.result}"
        
    - id: "send_email"
      tool: "email.sender"
      params:
        to: "stakeholders@company.com"
        subject: "月度销售报告"
        attachment: "${write_report.file}"

并行执行模式

当多个任务相互独立时,并行执行可以显著提升效率。

场景:多源数据采集

workflow:
  name: "multi_source_collection"
  parallel:
    max_concurrency: 5  # 最大并行数
    
    tasks:
      - id: "fetch_news"
        tool: "web.scraper"
        params:
          url: "https://news.example.com/ai"
          
      - id: "fetch_social"
        tool: "twitter.api"
        params:
          query: "#AI"
          count: 100
          
      - id: "fetch_papers"
        tool: "arxiv.api"
        params:
          category: "cs.AI"
          max_results: 50
          
      - id: "fetch_github"
        tool: "github.api"
        params:
          query: "AI Agent"
          sort: "stars"
          
  merge:
    strategy: "concat"  # 合并策略
    output: "combined_results"

并行执行的性能对比

任务数 顺序执行 并行执行(5并发) 提升
5 个独立任务 25 秒 6 秒 76% ↓
10 个独立任务 50 秒 11 秒 78% ↓
20 个独立任务 100 秒 21 秒 79% ↓

条件分支模式

根据执行结果选择不同路径,实现智能决策。

场景:智能客服路由

workflow:
  name: "smart_customer_service"
  
  steps:
    - id: "classify_intent"
      tool: "llm.classify"
      params:
        input: "${user_message}"
        categories: ["order_query", "refund", "complaint", "general"]
        
    - id: "route"
      type: "switch"
      condition: "${classify_intent.result}"
      branches:
        - when: "order_query"
          steps:
            - tool: "database.query"
              params:
                sql: "SELECT * FROM orders WHERE user_id = ${user_id}"
            - tool: "response.template"
              params:
                template: "order_status"
                
        - when: "refund"
          steps:
            - tool: "refund.check_eligibility"
              params:
                order_id: "${extract_order_id.result}"
            - type: "switch"
              condition: "${eligibility}"
              branches:
                - when: true
                  steps:
                    - tool: "refund.process"
                    - tool: "response.template"
                      params:
                        template: "refund_success"
                - when: false
                  steps:
                    - tool: "response.template"
                      params:
                        template: "refund_not_eligible"
                        
        - when: "complaint"
          steps:
            - tool: "escalation.create"
              params:
                priority: "high"
            - tool: "response.template"
              params:
                template: "complaint_escalated"
                
        - when: "general"
          steps:
            - tool: "llm.chat"
              params:
                model: "claude-3-haiku"
                prompt: "${user_message}"

循环迭代模式

重复执行直到满足条件,适用于批量处理和迭代优化。

场景:批量邮件发送

workflow:
  name: "bulk_email"
  
  steps:
    - id: "fetch_recipients"
      tool: "database.query"
      params:
        sql: "SELECT email, name FROM users WHERE subscribed = true"
        
    - id: "send_loop"
      type: "foreach"
      source: "${fetch_recipients.result}"
      batch_size: 100  # 每批 100 封
      delay: 1000      # 批次间隔 1 秒(防止被标记为垃圾邮件)
      
      steps:
        - tool: "email.sender"
          params:
            to: "${item.email}"
            template: "newsletter"
            variables:
              name: "${item.name}"
              
        - type: "log"
          message: "已发送至 ${item.email}"
          
    - id: "summary"
      tool: "report.generate"
      params:
        total: "${send_loop.processed}"
        success: "${send_loop.success}"
        failed: "${send_loop.failed}"

场景:迭代优化

workflow:
  name: "iterative_refinement"
  
  steps:
    - id: "initial_draft"
      tool: "llm.generate"
      params:
        prompt: "${task_description}"
        
    - id: "refinement_loop"
      type: "while"
      condition: "${iteration < 3 AND score < 0.9}"
      max_iterations: 5
      
      steps:
        - tool: "quality.evaluate"
          id: "evaluate"
          params:
            content: "${previous_result}"
            criteria: ["clarity", "accuracy", "completeness"]
            
        - type: "if"
          condition: "${evaluate.score < 0.9}"
          steps:
            - tool: "llm.refine"
              params:
                content: "${previous_result}"
                feedback: "${evaluate.feedback}"

错误恢复编排

workflow:
  name: "robust_data_fetch"
  
  steps:
    - id: "primary_source"
      tool: "api.fetch"
      params:
        url: "https://primary-api.com/data"
      fallback:
        - tool: "api.fetch"
          params:
            url: "https://backup-api.com/data"
        - tool: "cache.get"
          params:
            key: "data_cache"
            ttl: 3600
      on_error:
        retry: 2
        delay: 1000

编排最佳实践

1. 合理设置并发数

并行不是越多越好。考虑因素:

建议:从 3-5 开始,逐步调优。

2. 设计幂等性

循环和重试要求操作幂等:

# 非幂等(不要这样做)
- tool: "email.sender"
  params:
    to: "user@example.com"
    content: "Hello"

# 幂等(推荐)
- tool: "email.sender"
  params:
    idempotency_key: "${task_id}"  # 幂等键
    to: "user@example.com"
    content: "Hello"

3. 记录执行轨迹

workflow:
  name: "audited_workflow"
  
  config:
    tracing:
      enabled: true
      level: "detailed"  # basic | detailed | full
      output: "opentelemetry"  # 可接入 Jaeger, Zipkin

4. 设置超时和熔断

steps:
  - tool: "slow_api"
    timeout: 30000  # 30 秒超时
    circuit_breaker:
      enabled: true
      failure_threshold: 3
      reset_timeout: 60000

相关资源