Build an Orchestrator-Worker System in Python
This post builds a complete orchestrator-worker system in under 100 lines. A planner turns a question into a list of subtasks, workers answer each subtask in parallel, and a synthesizer merges the answers. You can run it as is with the Anthropic SDK and then extend it.
Design
Three roles, three prompts. The planner returns JSON so code can iterate over it. Workers return short plain text. The synthesizer receives the original question plus all worker results.
The shared helper
import json
import re
from concurrent.futures import ThreadPoolExecutor
import anthropic
client = anthropic.Anthropic()
def call(system: str, user: str, model: str = "claude-sonnet-5-5") -> str:
response = client.messages.create(
model=model,
max_tokens=3000,
system=system,
messages=[{"role": "user", "content": user}],
)
return "".join(b.text for b in response.content if b.type == "text").strip()
The planner
The planner must return something the code can loop over. Ask for a JSON array of strings, cap the count, and extract the array defensively.
PLANNER = (
"You break a question into 2 to 4 independent research subtasks. "
"Each subtask must be answerable on its own. "
"Reply with a JSON array of strings and nothing else."
)
def plan(question: str) -> list[str]:
text = call(PLANNER, question)
match = re.search(r"\[.*\]", text, re.DOTALL)
subtasks = json.loads(match.group(0)) if match else [question]
return [str(s) for s in subtasks][:4]
If parsing fails, the code falls back to a single subtask equal to the question. That keeps the system working in degraded form instead of crashing.
Workers and synthesizer
WORKER = (
"You answer one focused subtask. Be accurate and brief (max 120 words). "
"If you are unsure, say so instead of guessing."
)
SYNTH = (
"You combine worker answers into one clear answer to the original question. "
"Use only the worker answers. Mention disagreements between workers."
)
def run_worker(subtask: str) -> str:
return call(WORKER, subtask)
def synthesize(question: str, subtasks: list[str], results: list[str]) -> str:
parts = []
for i, (task, result) in enumerate(zip(subtasks, results), start=1):
parts.append("Subtask " + str(i) + ": " + task + "\nAnswer: " + result)
return call(SYNTH, "Question: " + question + "\n\n" + "\n\n".join(parts))
The orchestrator
Workers are independent, so run them in a thread pool. The SDK client is safe to share between threads, and the calls spend their time waiting on the network.
def orchestrate(question: str) -> str:
subtasks = plan(question)
print("Plan:", subtasks)
with ThreadPoolExecutor(max_workers=len(subtasks)) as pool:
results = list(pool.map(run_worker, subtasks))
return synthesize(question, subtasks, results)
if __name__ == "__main__":
print(orchestrate("What are the main trade-offs between SQL and NoSQL databases?"))
Expect a printed plan such as three or four subtasks (consistency, scaling, schema flexibility, query power), followed by one combined answer. pool.map keeps results in the same order as the subtasks, which the synthesizer relies on.
What to improve next
- Validation. Check that the planner's output is a non-empty list of non-empty strings.
- Errors. If one worker raises, return an error string for that subtask and let the synthesizer note the gap.
- Cost. Use a smaller model for workers when the subtasks are simple.
- Logging. Print the time each worker took. You will find one slow worker dominates total latency.
Common mistakes
- Letting the synthesizer use outside knowledge. Tell it to use only worker answers, or hallucinated facts slip in at the last step.
- Giving workers the whole original question. They then overlap. Give each one only its subtask.
- Not capping the number of subtasks. A planner can return twenty, and you pay for twenty calls.
Walking through a run
Let us trace the example question about SQL and NoSQL. The planner returns a list such as: compare consistency guarantees, compare horizontal scaling, compare schema flexibility, compare query capabilities. That is four subtasks, so the thread pool starts four workers at once. Each worker sends one request to the model and waits. Since they run concurrently, total time is close to the slowest single call rather than the sum of four. When all four return, the synthesizer receives a prompt with the original question and the four labelled answers, and writes the final comparison.
If you add timing prints around each stage, you will typically see three phases: a short planning call, a parallel phase, and a synthesis call that is often the longest because it writes the final answer. This is useful when you later optimise latency: the planner and synthesizer are on the critical path and cannot be parallelised, while the workers can.
Testing it without spending money
Because call is a single function, you can replace it with a fake during tests. Patch it to return fixed JSON for the planner and canned text for the workers, then assert that orchestrate calls the synthesizer with the right inputs. Testing orchestration logic with fake agents is covered in its own post later in the course, and it is one of the best reasons to keep the model call behind one function.
Comments
No comments yet. Have a question or a tip? Be the first to share it.