Multi-Agent Collaboration Frameworks: A Deep Dive into the ai-agent-book Repository
The ai-agent-book repository provides a modular, provider-agnostic architecture for building multi-agent systems with four core collaboration patterns: sequential delegation, parallel ensemble, hierarchical tree, and feedback loop.
This living textbook demonstrates how to orchestrate multiple AI agents using a clean separation between agent logic and backend resolution. Every chapter showcases a different multi-agent collaboration strategy while reusing a common core of provider management, state handling, and prompt templating utilities.
Core Provider Resolution System
The foundation of every multi-agent workflow in ai-agent-book is the backend resolution layer. Located in agentbook/providers/, this system decouples agent code from credential management—enabling the same agent to run against OpenAI, Ollama, Claude, or any other supported provider without modification.
Provider Data Models and Registry
| Component | Purpose | Key Source File |
|---|---|---|
Provider / Backend data classes |
Describe provider capabilities and API configuration | agentbook/providers/models.py |
lookup() function |
Central registry mapping provider names to specifications | agentbook/providers/registry.py |
resolve_backend() |
Deterministic resolution policy with fallback chain | agentbook/providers/resolution.py |
The resolve_backend function implements a precedence chain that handles credential routing automatically:
# From agentbook/providers/resolution.py
def resolve_backend(provider: str, model: str | None = None, api_key: str | None = None) -> Backend:
spec = lookup(provider) # find provider spec
resolved_model = model or spec.default_model
key = (api_key or "").strip() or spec.api_key()
# 1️⃣ gpt‑5 → OpenRouter if possible
if openrouter_key() and _needs_openrouter_for_gpt5(spec, resolved_model):
return build_openrouter_backend(resolved_model, openrouter_key(), spec.name)
# 2️⃣ Use provider's own credential (or none required)
if key or not spec.requires_key:
return Backend(api_key=key or "_PLACEHOLDER_", base_url=spec.resolved_base_url(),
model=resolved_model, provider=spec.name,
using_openrouter=spec.name == "openrouter")
# 3️⃣ Fallback to OpenRouter
if openrouter_key():
return build_openrouter_backend(resolved_model, openrouter_key(), spec.name)
# 4️⃣ No credentials → raise
raise _missing_key_error(spec)
This resolution policy is critical for multi-agent collaboration frameworks because each agent in a workflow can independently resolve its preferred backend while the orchestration code remains completely provider-agnostic.
Agent Execution Skeleton
Every agent in ai-agent-book inherits a common three-concept pattern from chapter1/web-search-agent/agent.py:
state– A mutable dictionary persisting across execution turnsplan– A list of sub-tasks that may spawn child agentsrun– The main async loop resolving backends, calling LLMs, and delegating
# Simplified skeleton from chapter1/web-search-agent/agent.py
class WebSearchAgent:
def __init__(self, config):
self.config = config
self.state = {}
async def run(self, query: str) -> str:
backend = resolve_backend(self.config.provider, self.config.model)
response = await backend.call(messages=[{"role": "user", "content": query}])
# Parse response → maybe create child agents
return response["choices"][0]["message"]["content"]
Concrete agents throughout the repository—search-codegen, trajectory-verifier, Xlerobot tele-operation—reuse this skeleton, swapping only prompt templates and post-processing logic.
Four Multi-Agent Collaboration Patterns
The ai-agent-book demonstrates multi-agent collaboration frameworks through four composable patterns, all built atop the same provider resolution and agent skeleton.
Sequential Delegation
One agent completes its sub-task, then passes output to the next agent. This linear chain appears in chapter1/search-codegen/agent.py where the web-search agent hands retrieved snippets to a code-generation agent.
Parallel Ensemble
Multiple agents execute simultaneously with merged results. The chapter8/trajectory-verifier/llm_judge.py implementation runs three independent LLM judges on the same plan, then aggregates their ratings for consensus decisions.
Hierarchical Tree
A root agent spawns specialized child agents for problem branches. In chapter9/xlerobot-teleoperation/teleop.py, separate perception, planning, and actuation agents form a control tree for robotic tele-operation.
Feedback Loop
Agents iteratively refine output until validation passes. The trajectory verifier in chapter8/trajectory-verifier/calibration.py repeatedly prompts the LLM to improve plans until they satisfy safety constraints.
| Pattern | Source Location | Ideal Use Case |
|---|---|---|
| Sequential Delegation | chapter1/search-codegen/agent.py |
Data transformation pipelines |
| Parallel Ensemble | chapter8/trajectory-verifier/llm_judge.py |
Consensus-based evaluation |
| Hierarchical Tree | chapter9/xlerobot-teleoperation/teleop.py |
Complex task decomposition |
| Feedback Loop | chapter8/trajectory-verifier/calibration.py |
Quality assurance loops |
Practical Implementation Examples
Example 1: Instantiate a Standalone Web-Search Agent
from agentbook.providers.resolution import resolve_backend
from chapter1.web-search-agent.agent import WebSearchAgent
from chapter1.web-search-agent.config import Config
# Configure provider (OpenAI, Ollama, OpenRouter, etc.)
cfg = Config(provider="openai", model="gpt-4o")
# Initialize and run
agent = WebSearchAgent(cfg)
result = await agent.run("What are the latest developments in multi-agent systems?")
print(result)
The resolve_backend call inside WebSearchAgent.run automatically selects the correct API endpoint and authentication.
Example 2: Chain Two Agents (Sequential Delegation)
from chapter1.web-search-agent.agent import WebSearchAgent
from chapter1.search-codegen.agent import CodeGenAgent
from chapter1.web-search-agent.config import Config as SearchCfg
from chapter1.search-codegen.config import Config as CodeCfg
search = WebSearchAgent(SearchCfg(provider="openrouter"))
codegen = CodeGenAgent(CodeCfg(provider="openrouter"))
async def search_then_codegen(query: str) -> str:
snippet = await search.run(query) # Step 1: Gather information
code = await codegen.run(snippet) # Step 2: Generate implementation
return code
State isolation between agents ensures clean boundaries; only explicit outputs propagate through the chain.
Example 3: Execute Parallel LLM Judges
import asyncio
from chapter8.trajectory-verifier.llm_judge import LLMJudge
from chapter8.trajectory-verifier.config import Config as JudgeCfg
judge_cfg = JudgeCfg(provider="openai", model="gpt-4")
judges = [LLMJudge(judge_cfg) for _ in range(3)] # Three independent instances
async def ensemble_judge(plan: str) -> list[str]:
tasks = [judge.run(plan) for judge in judges]
results = await asyncio.gather(*tasks) # Concurrent execution
return results
Each judge resolves its backend independently, enabling heterogeneous provider configurations within the same ensemble.
Key Source Files Reference
| File Path | Description |
|---|---|
agentbook/providers/models.py |
Provider and Backend dataclasses |
agentbook/providers/registry.py |
Static provider registry with lookup() |
agentbook/providers/resolution.py |
resolve_backend() with deterministic fallback chain |
agentbook/providers/openrouter.py |
OpenRouter ID mapping and URL construction |
chapter1/web-search-agent/agent.py |
Base agent skeleton reused across chapters |
chapter1/search-codegen/agent.py |
Sequential delegation example |
chapter8/trajectory-verifier/llm_judge.py |
Parallel ensemble implementation |
chapter8/trajectory-verifier/calibration.py |
Feedback loop with iterative refinement |
chapter9/xlerobot-teleoperation/teleop.py |
Hierarchical tree of specialized agents |
tests/test_providers.py |
Deterministic unit tests mocking LLM calls |
All files are accessible via https://github.com/bojieli/ai-agent-book/blob/main/[path].
Summary
The ai-agent-book repository demonstrates a production-ready approach to multi-agent collaboration frameworks:
- Provider-agnostic resolution lets every agent switch LLM vendors without code changes via
resolve_backend()inagentbook/providers/resolution.py - Minimal agent skeleton in
chapter1/web-search-agent/agent.pyprovides reusable state management and execution loops - Composable collaboration patterns—sequential, parallel, hierarchical, and iterative—build upon the same core utilities
- Deterministic testing through mocked provider calls ensures reliable multi-agent orchestration
Frequently Asked Questions
How does ai-agent-book handle different LLM providers in the same multi-agent workflow?
Each agent calls resolve_backend() independently with its own configuration. The resolution policy in agentbook/providers/resolution.py handles credential lookup, OpenRouter fallback, and model-specific routing transparently. This lets one agent use OpenAI while another uses Ollama, with zero changes to agent logic.
What is the simplest way to create a new agent type in this framework?
Subclass the skeleton from chapter1/web-search-agent/agent.py, implement your run() method to call resolve_backend(), and supply a custom prompt template. The framework handles all provider authentication and API formatting automatically.
Can agents share state with each other?
Agents maintain isolated state dictionaries by default. For explicit state sharing, pass outputs directly between agent run() calls as shown in the sequential delegation example, or implement a shared context object that multiple agents reference.
Where can I find a complete hierarchical multi-agent example?
The Xlerobot tele-operation demo in chapter9/xlerobot-teleoperation/teleop.py implements a full tree with perception, planning, and actuation agents. This file demonstrates how a root agent orchestrates specialized children for complex robotic control tasks.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →