Sub topic 2
The Orchestrator-Worker Pattern
Assume you know basic Python, Git, and how an agent uses tools. This chapter shows how one agent coordinates several specialized agents without losing control of the work.
Orchestrator and workers
An orchestrator plans work, starts subagents, collects their results, and performs final verification. A worker is a subagent that receives one focused task in a separate context.
The worker does not automatically see the parent agent's conversation. The orchestrator must pass the relevant context explicitly.
flowchart TD
A[Orchestrator] --> B[Worker: update documentation]
A --> C[Worker: add tests]
A --> D[Worker: review changes]
B --> E[Results]
C --> E
D --> E
E --> AWriting a good delegation brief
A brief should make the task independently checkable. Include:
- Goal: the specific result the worker must produce.
- Context: files, interfaces, and conventions it needs.
- Scope: files or components it may change.
- Constraints: dependencies, runtime, security, or style limits.
- Done condition: a test or command that proves completion.
- Return format: the summary and evidence the worker should report.
Goal: Add unit tests for parse_args in src/cli.py.
Context: parse_args supports --verbose and --output. Tests use pytest.
Scope: Edit only tests/test_cli.py.
Constraints: Add no dependencies. Tests must run offline.
Done when: pytest tests/test_cli.py passes.
Return: Summarize the tests, command, and result. Do not paste the file.Give workers only required tools
Tool permissions should match the task. A documentation worker may need read and write access to Markdown files but not deployment credentials. A test worker may need to run tests but should not modify application code.
Use separate workspaces or branches when workers can edit files. Restrict network access and secrets unless the task requires them.
Parallel or sequential execution
Run independent tasks in parallel to reduce latency. Run dependent tasks sequentially when one worker needs another worker's output.
import asyncio
async def run_worker(name: str) -> str:
await asyncio.sleep(0.1)
return f"{name} finished"
async def main() -> None:
results = await asyncio.gather(
run_worker("docs"),
run_worker("tests"),
)
print(results)
asyncio.run(main())Avoiding file conflicts
Parallel workers should not edit the same checkout. Git worktrees provide separate directories with branches:
git worktree add ../wt-docs -b agent/docs
git worktree add ../wt-tests -b agent/testsReview and test each branch before merging. The orchestrator should treat worker output as untrusted until checks pass.
Exercise
Should documentation and test updates run in parallel if both edit the same file?
Show answer
No. Run them sequentially, or give each worker an isolated worktree and resolve the changes before merging.