编排者-执行者模式
一个编排者分配任务给多个工作者 Agent
🌐 查看英文原文 | 源码 Notebook
编排者-执行者工作流
简介
你是否曾经需要对同一任务获得多个视角,但无法预先预测哪些视角最有价值?编排者-执行者模式通过让一个中央 LLM 分析每个独特的任务并动态确定要委派给专业执行者 LLM 的最佳子任务来解决这个问题。
传统方法要么需要多次手动提示,要么使用无论上下文如何都生成相同变体的硬编码并行化。
使用此方法,编排者 LLM 分析任务,确定针对此特定情况最有价值的变体,然后委派给生成每个变体的执行者 LLM。
你将构建什么
一个接受产品描述请求的系统,它:
- 分析哪些类型的营销文案有价值
- 为执行者动态生成专门的子任务描述
- 生成针对不同受众优化的多种内容变体
- 返回所有执行者的协调结果
前置条件
- Python 3.9 或更高版本
- 设置为环境变量的 Anthropic API 密钥:
export ANTHROPIC_API_KEY='your-key' - 对提示工程的基本理解
- 熟悉 Python 类和类型提示
何时使用此工作流
此工作流适用于无法预先预测所需子任务的复杂任务。与简单并行化的关键区别在于其灵活性——子任务不是预定义的,而是由编排者根据具体输入确定的。
使用此模式的情况:
- 任务需要多种不同的方法或视角
- 最佳子任务取决于具体输入
- 你需要比较不同的策略或风格
不使用此模式的情况:
- 你有简单的单输出任务(不必要的复杂性)
- 延迟至关重要(多次 LLM 调用会增加开销)
- 子任务是可预测的且可以预定义(使用更简单的并行化)
工作原理
编排者-执行者模式分两个阶段运行:
分析和规划阶段:编排者 LLM 接收任务和上下文,分析哪些方法有价值,并以 XML 格式生成结构化的子任务描述。
执行阶段:每个执行者 LLM 接收:
- 原始任务作为上下文
- 其特定的子任务类型和描述
- 提供的任何额外上下文
编排者在运行时决定创建哪些子任务,这使得它比预定义的并行工作流更具适应性。
环境配置
安装
pip install anthropic辅助函数
此示例使用 util.py 中的辅助函数来进行 LLM 调用和解析 XML 响应:
llm_call(prompt, system_prompt="", model="claude-sonnet-4-6"):向 Claude 发送提示并返回文本响应extract_xml(text, tag):使用正则表达式从 XML 标签中提取内容
这些工具处理 API 认证(从环境变量读取 ANTHROPIC_API_KEY),并为编排者-执行者模式提供简单的接口。你可以在 util.py 中查看完整实现。
实现
FlexibleOrchestrator 类协调两个阶段的工作流:
关键设计决策: - 提示是接受运行时变量(task、context)的模板,以确保灵活性 - 使用 XML 进行结构化输出解析(可靠且对语言模型友好的格式) - 执行者同时接收原始任务和其特定指令,以获得更好的上下文 - 错误处理验证执行者返回非空响应
实现包括: - parse_tasks():将编排者的 XML 输出解析为结构化的任务字典 - FlexibleOrchestrator.process():调用编排者然后调用执行者的主要协调逻辑 - 响应验证以捕获和处理空的执行者输出
from util import extract_xml, llm_call
# Model configuration
MODEL = "claude-sonnet-4-6" # Fast, capable model for both orchestrator and workers
def parse_tasks(tasks_xml: str) -> list[dict]:
"""Parse XML tasks into a list of task dictionaries."""
tasks = []
current_task = {}
for line in tasks_xml.split("\n"):
line = line.strip()
if not line:
continue
if line.startswith("<task>"):
current_task = {}
elif line.startswith("<type>"):
current_task["type"] = line[6:-7].strip()
elif line.startswith("<description>"):
current_task["description"] = line[12:-13].strip()
elif line.startswith("</task>"):
if "description" in current_task:
if "type" not in current_task:
current_task["type"] = "default"
tasks.append(current_task)
return tasks
class FlexibleOrchestrator:
"""Break down tasks and run them in parallel using worker LLMs."""
def __init__(
self,
orchestrator_prompt: str,
worker_prompt: str,
model: str = MODEL,
):
"""Initialize with prompt templates and model selection."""
self.orchestrator_prompt = orchestrator_prompt
self.worker_prompt = worker_prompt
self.model = model
def _format_prompt(self, template: str, **kwargs) -> str:
"""Format a prompt template with variables."""
try:
return template.format(**kwargs)
except KeyError as e:
raise ValueError(f"Missing required prompt variable: {e}") from e
def process(self, task: str, context: dict | None = None) -> dict:
"""Process task by breaking it down and running subtasks in parallel."""
context = context or {}
# Step 1: Get orchestrator response
orchestrator_input = self._format_prompt(self.orchestrator_prompt, task=task, **context)
orchestrator_response = llm_call(orchestrator_input, model=self.model)
# Parse orchestrator response
analysis = extract_xml(orchestrator_response, "analysis")
tasks_xml = extract_xml(orchestrator_response, "tasks")
tasks = parse_tasks(tasks_xml)
print("\n" + "=" * 80)
print("ORCHESTRATOR ANALYSIS")
print("=" * 80)
print(f"\n{analysis}\n")
print("\n" + "=" * 80)
print(f"IDENTIFIED {len(tasks)} APPROACHES")
print("=" * 80)
for i, task_info in enumerate(tasks, 1):
print(f"\n{i}. {task_info['type'].upper()}")
print(f" {task_info['description']}")
print("\n" + "=" * 80)
print("GENERATING CONTENT")
print("=" * 80 + "\n")
# Step 2: Process each task
worker_results = []
for i, task_info in enumerate(tasks, 1):
print(f"[{i}/{len(tasks)}] Processing: {task_info['type']}...")
worker_input = self._format_prompt(
self.worker_prompt,
original_task=task,
task_type=task_info["type"],
task_description=task_info["description"],
**context,
)
worker_response = llm_call(worker_input, model=self.model)
worker_content = extract_xml(worker_response, "response")
# Validate worker response - handle empty outputs
if not worker_content or not worker_content.strip():
print(f"⚠️ Warning: Worker '{task_info['type']}' returned no content")
worker_content = f"[Error: Worker '{task_info['type']}' failed to generate content]"
worker_results.append(
{
"type": task_info["type"],
"description": task_info["description"],
"result": worker_content,
}
)
# Display results
print("\n" + "=" * 80)
print("RESULTS")
print("=" * 80)
for i, result in enumerate(worker_results, 1):
print(f"\n{'-' * 80}")
print(f"Approach {i}: {result['type'].upper()}")
print(f"{'-' * 80}")
print(f"\n{result['result']}\n")
return {
"analysis": analysis,
"worker_results": worker_results,
}示例用例:营销文案变体生成
现在让我们通过一个实际示例来看看编排者-执行者模式的实际应用:为产品生成多种风格的营销文案。
为什么这个示例很好地展示了该模式: - 不同的产品受益于不同的营销角度 - “最佳”变体取决于具体的产品特点和目标受众 - 编排者可以根据输入调整其策略,而不是使用固定模板
提示设计说明: - 编排者提示要求 2-3 种方法,并提供 XML 结构指导 - 执行者提示为执行者提供完整的上下文(原始任务、其风格和指南) - 两个提示都使用清晰的 XML 格式以确保可靠解析
ORCHESTRATOR_PROMPT = """
Analyze this task and break it down into 2-3 distinct approaches:
Task: {task}
Return your response in this format:
<analysis>
Explain your understanding of the task and which variations would be valuable.
Focus on how each approach serves different aspects of the task.
</analysis>
<tasks>
<task>
<type>formal</type>
<description>Write a precise, technical version that emphasizes specifications</description>
</task>
<task>
<type>conversational</type>
<description>Write an engaging, friendly version that connects with readers</description>
</task>
</tasks>
"""
WORKER_PROMPT = """
Generate content based on:
Task: {original_task}
Style: {task_type}
Guidelines: {task_description}
Return your response in this format:
<response>
Your content here, maintaining the specified style and fully addressing requirements.
</response>
"""
orchestrator = FlexibleOrchestrator(
orchestrator_prompt=ORCHESTRATOR_PROMPT,
worker_prompt=WORKER_PROMPT,
)
results = orchestrator.process(
task="Write a product description for a new eco-friendly water bottle",
context={
"target_audience": "environmentally conscious millennials",
"key_features": ["plastic-free", "insulated", "lifetime warranty"],
},
)
================================================================================
ORCHESTRATOR ANALYSIS
================================================================================
This task requires creating marketing copy for an eco-friendly water bottle. The core challenge is balancing product information with persuasive messaging while highlighting the environmental benefits. Different approaches would serve distinct marketing channels and audience segments:
1. A **feature-focused technical approach** would appeal to detail-oriented consumers who make purchasing decisions based on specifications, materials, and measurable environmental impact. This serves e-commerce listings and comparison shopping.
2. A **lifestyle-oriented emotional approach** would connect with values-driven consumers through storytelling and aspirational messaging, emphasizing how the product fits into an eco-conscious lifestyle. This serves social media and brand-building content.
3. A **benefit-driven practical approach** would focus on solving everyday problems while weaving in sustainability advantages, appealing to mainstream consumers who want both functionality and environmental responsibility. This serves broad retail contexts.
Each approach addresses the "eco-friendly" aspect differently—through data, values, or practical advantages—making them valuable for different marketing contexts.
================================================================================
IDENTIFIED 3 APPROACHES
================================================================================
1. TECHNICAL-SPECIFICATIONS
>Write a detailed, feature-focused description emphasizing materials, construction, environmental certifications, and measurable sustainability metrics (recyclability percentages, carbon footprint reduction, etc.)<
2. LIFESTYLE-EMOTIONAL
>Write an inspirational, story-driven description that connects the product to environmental values, personal identity, and the broader movement toward sustainable living<
3. BENEFIT-PRACTICAL
>Write a problem-solution focused description highlighting everyday usability benefits (temperature retention, durability, convenience) while naturally integrating eco-friendly advantages<
================================================================================
GENERATING CONTENT
================================================================================
[1/3] Processing: technical-specifications...
[2/3] Processing: lifestyle-emotional...
[3/3] Processing: benefit-practical...
================================================================================
RESULTS
================================================================================
--------------------------------------------------------------------------------
Approach 1: TECHNICAL-SPECIFICATIONS
--------------------------------------------------------------------------------
# EcoFlow Pro™ Insulated Water Bottle - Technical Specifications
## Product Overview
Model: EF-750-INS | Capacity: 750ml (25.4 fl oz) | Weight: 285g ±5g
## Material Composition & Construction
### Primary Body
- **Material**: 18/8 (304) food-grade stainless steel
- **Wall Thickness**: 0.6mm inner wall, 0.5mm outer wall
- **Surface Treatment**: Powder-coated finish using water-based, VOC-free coating
- **BPA/BPS/Phthalate Status**: Certified free of all endocrine-disrupting compounds
### Insulation System
- **Technology**: Double-wall vacuum insulation with copper lining
- **Vacuum Pressure**: <0.001 Pa
- **Thermal Performance**:
- Cold retention: 24 hours (maintains <10°C)
- Hot retention: 12 hours (maintains >65°C)
- **Condensation**: Zero external condensation at all temperatures
### Cap & Seal Assembly
- **Cap Material**: 100% post-consumer recycled polypropylene (rPP)
- **Seal Gasket**: Medical-grade silicone (FDA 21 CFR 177.2600 compliant)
- **Thread Design**: 3.5-turn precision threading for leak-proof seal (tested to 50 PSI)
## Environmental Certifications & Standards
- **ISO 14001**: Environmental Management System certified manufacturing facility
- **Cradle to Cradle Certified®**: Silver level
- **Carbon Neutral Certified**: Through verified offset programs (Climate Neutral Certified)
- **NSF/ANSI 61**: Drinking water system components certification
- **REACH Compliant**: European chemical safety regulation adherent
## Sustainability Metrics
### Carbon Footprint
- **Manufacturing Emissions**: 2.8 kg CO₂e per unit (68% reduction vs. industry average of 8.7 kg CO₂e)
- **Transportation Impact**: Optimized packaging reduces shipping emissions by 42%
- **Lifecycle Offset**: Replaces approximately 217 single-use plastic bottles annually (based on average daily consumption)
- **Net Carbon Savings**: 156 kg CO₂e per year of use vs. disposable bottle equivalent
### Recyclability & Circularity
- **End-of-Life Recyclability**: 95% by weight
- **Stainless Steel**: 100% infinitely recyclable without quality degradation
- **Plastic Components**: 89% recyclable (rPP cap and silicone gasket)
- **Disassembly Time**: <45 seconds for complete material separation
- **Take-Back Program**: Available for responsible recycling through manufacturer
### Resource Efficiency
- **Recycled Content**: 73% post-consumer recycled materials by weight
- **Water Usage in Production**: 4.2L per unit (industry average: 12.8L)
- **Energy Consumption**: 18.5 MJ per unit manufactured using 100% renewable energy
- **Packaging**: 100% recycled cardboard, soy-based inks, zero plastic components
## Durability & Longevity Specifications
- **Impact Resistance**: Survives 2-meter drop test onto concrete (maintains vacuum seal)
- **Corrosion Resistance**: 1,000+ hour salt spray test (ASTM B117)
- **Cycle Testing**: 10,000+ open/close cycles without seal degradation
- **Warranty Period**: Lifetime warranty against manufacturing defects
- **Expected Lifespan**: 15+ years under normal use conditions
## Physical Specifications
- **Dimensions**: Height: 265mm | Diameter: 73mm (body), 48mm (cap)
- **Mouth Opening**: 42mm wide-mouth design (ice cube compatible)
- **Base Diameter**: 68mm (fits standard cup holders)
- **Volume Markings**: Laser-etched ml/oz graduations (50ml increments)
- **Color Options**: 8 powder-coated finishes (all VOC-free)
## Compliance & Safety Testing
- **FDA Approved**: All food-contact materials
- **LFGB Certified**: German food safety standards
- **Proposition 65**: Compliant (no listed chemicals)
- **Lead Content**: <0.01 ppm (non-detectable)
- **Microplastic Shedding**: Zero detected in 90-day leaching study
## Performance Advantages
- **Single-Use Bottle Replacement Rate**: 1:217 annually
- **Cost Recovery Period**: 2.3 months (vs. purchasing disposable bottles)
- **Plastic Waste Prevention**: 1.89 kg per year per user
- **Water Quality Preservation**: No taste transfer, maintains pH neutrality (±0.1)
## Manufacturing & Supply Chain
- **Production Facility**: Solar-powered, zero-waste-to-landfill certified plant
- **Supply Chain Transparency**: Full material traceability via blockchain verification
- **Fair Trade Certified**: Ethical labor practices throughout supply chain
- **Local Sourcing**: 67% of materials sourced within 500km of manufacturing facility
--------------------------------------------------------------------------------
Approach 2: LIFESTYLE-EMOTIONAL
--------------------------------------------------------------------------------
**More Than Hydration. A Daily Ritual of Change.**
Every morning, you make a choice. Not just about what you drink, but about who you are and the world you're creating.
This isn't just a water bottle—it's your companion in a quiet revolution. Crafted from 100% recycled ocean-bound plastic, each bottle tells a story of transformation: waste that once threatened our seas, now reimagined as something beautiful, functional, and enduring in your hands.
Feel the smooth, cool surface against your palm. Notice its weight—substantial enough to remind you it's built to last decades, not days. This is the bottle that replaces hundreds of single-use plastics, the one that travels with you through morning commutes, mountain trails, and late-night creative sessions. It becomes part of your story, collecting scratches and memories like badges of honor.
But here's what really matters: You're not alone in this. You're joining millions who understand that sustainability isn't about perfection—it's about progress. Every refill is a small act of defiance against throwaway culture. Every sip connects you to a global community choosing differently, living intentionally, proving that our daily choices ripple outward in ways we can't always see but can always feel.
Your hydration. Your values. Your legacy.
Because the future isn't something that happens to us—it's something we carry with us, one conscious choice at a time.
**Welcome to the movement. Welcome home.**
--------------------------------------------------------------------------------
Approach 3: BENEFIT-PRACTICAL
--------------------------------------------------------------------------------
**Stay Hydrated All Day with the EcoFlow Bottle – Built for Your Active Life**
Tired of lukewarm coffee by mid-morning or water that tastes like plastic after a few months? The EcoFlow Bottle solves the everyday frustrations that come with typical water bottles while helping you make a positive environmental impact.
**Keeps Drinks at the Perfect Temperature**
Double-wall vacuum insulation maintains cold drinks icy for 24 hours and hot beverages steaming for 12 hours. Your morning coffee stays hot through your commute, and your water remains refreshingly cold during afternoon meetings or workouts.
**Built to Last Through Daily Wear and Tear**
Constructed from premium 18/8 stainless steel with a powder-coated finish, this bottle withstands drops, bumps, and the chaos of daily life. The leak-proof lid means you can toss it in your bag without worry—no more soggy papers or ruined electronics.
**Designed for Real Convenience**
The wide mouth opening fits ice cubes easily and makes cleaning simple (no hard-to-reach corners). It fits standard cup holders in your car, and the ergonomic design is comfortable to carry whether you're commuting, hiking, or running errands.
**Better for Your Wallet and the Planet**
By switching to a reusable bottle, you'll save hundreds of dollars annually on disposable bottles while eliminating plastic waste. The durable construction means you're buying one bottle that lasts for years, not replacing cheap alternatives every few months. Plus, you'll avoid the chemicals found in many plastic bottles, ensuring cleaner-tasting water every time.
**Your Reliable Hydration Companion**
The EcoFlow Bottle adapts to your lifestyle—whether you need hot tea for early mornings, cold water for the gym, or room-temperature drinks throughout the workday. It's the practical solution that makes staying hydrated effortless while naturally reducing your environmental footprint.
总结
你现在已经实现了一个编排者-执行者模式,它可以根据具体输入动态调整任务分解。此模式生成了多种营销文案变体——每种都针对不同的受众和场景——而无需你预定义这些变体应该是什么。
关键要点
模式优势: - 适应性:编排者为每个独特的输入确定最佳方法 - 灵活性:通过更改提示即可轻松应用于不同领域 - 结构化协调:基于 XML 的通信确保可靠解析 - 错误韧性:验证捕获并处理执行者失败
此模式擅长的场景: - 需要多个视角的内容生成(营销、文档、创意写作) - 受益于不同分析视角的分析任务 - 分解策略取决于问题的解决问题场景
限制与注意事项
成本和延迟: - 需要 N+1 次 LLM 调用(1 个编排者 + N 个执行者) - 此实现中的顺序处理(执行者逐个运行) - 为获得更好性能,考虑使用 asyncio 或线程池并行化执行者调用
不使用此模式的情况: - 具有单一明确输出的简单任务(增加的复杂性不合理) - 延迟敏感的应用(多次 API 调用增加开销) - 子任务始终相同的任务(改用预定义并行化)
需要考虑的失败模式: - 编排者可能无法最佳地分解任务(提示工程至关重要) - 执行者可能返回空或格式错误的响应(我们通过验证来处理) - 如果模型不完全遵循格式,XML 解析可能失败(考虑使用 JSON 作为替代方案)
后续步骤
增强此实现: 1. 使用 asyncio 添加并行执行者执行以获得更好性能 2. 为失败的执行者实现重试逻辑 3. 添加一个综合阶段,让 LLM 合并执行者输出 4. 尝试不同的编排者策略(例如,要求更多/更少的子任务)
适配你的用例: - 修改编排者提示以指导你的领域的任务分解 - 调整执行者提示以提供特定领域的指令 - 添加与应用相关的上下文参数 - 考虑使用 Claude Opus 作为编排者,Claude Haiku 作为执行者,以优化成本与质量
中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。