Skip to content
ImagineWorld

Multi-Agent Solutions and Advanced Agent Frameworks

node_idnode-book_mastering-nlp-from-foundations-to-agents_chapter-11-multi-agent-solutions-and-advanced-agent-frameworks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleMulti-Agent Solutions and Advanced Agent Frameworks
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Multi-Agent Solutions and Advanced Agent Frameworks

Section titled “Chapter 11 — Multi-Agent Solutions and Advanced Agent Frameworks”

At this point in the book, we have seen how language models answered our questions. We will now use agents to pursue our goals. This chapter is our bridge from clever prompts and tidy chains to systems that can plan, choose tools, adapt, and stop on their own, reliably and within budget. We encourage agentic design where real work is messy: multi-step, tool-heavy, and sensitive to context. Rather than adding more LLM calls, we introduce a structure that makes autonomy reproducible, auditable, and cost-aware.

We will set up a clear mental model in this chapter for when agents help and how they work, the core topologies and interaction protocols that keep teams of agents coordinated, and a concrete orchestration runtime in Microsoft Agent Framework (MAF). We will translate the ideas into a running blueprint, an executive-brief system, with explicit roles, typed tools, checkpointing, human-in-the-loop (HITL) gates, and OpenTelemetry tracing. Along the way, we will show how collaboration, negotiation, and constructive competition raise quality and safety without runaway spend. By the end, you will be ready to build the full multi-agent solution and measure exactly what each design choice buys you.

In a nutshell, here’s what you’ll learn in this chapter:

  • Single-agent and multi-agent systems: overview and core concepts
  • Deep dive into MAF and advanced orchestration frameworks
  • Building multi-agent solutions with MAF
  • Strategies for agent collaboration, negotiation, and competition

For this chapter, the following will be necessary:

  • Programming knowledge: Familiarity with Python programming is a must since the open source models, OpenAI’s API, and LangChain are all illustrated using Python code.
  • Access to OpenAI’s API: An API key from OpenAI will be required if looking to explore closed source models. This can be obtained by creating an account with OpenAI and agreeing to their terms of service.
  • Open source models: Local free LLMs will be used as well. Ollama will be leveraged for that through the LLMPop Python library. LLMPop will require a Linux-based operating system, preferably with a GPU. For that, free access to Google Colab would be ideal.
  • Local development environment: A local development environment setup with Python installed is required. An integrated development environment (IDE) such as PyCharm, Jupyter Notebook, or a simple text editor can be used. Note that we recommend a free Google Colab notebook, as it encapsulates all these requirements in a seamless web interface.
  • Ability to install libraries: You must have permission for the installation of the required Python libraries, such as NumPy, agent-framework, pandas, SentenceTransformers, OpenAI, and LLMPop. Note that the code we provide includes the required installations, so you won’t have to install them ahead of time. We simply stress that you should have permission to do so, which we expect you would. Specifically, using a free Google Colab notebook would suffice.
  • Hardware requirements: Depending on the complexity and size of the models you’re working with, a computer with sufficient processing power (potentially including a good GPU for ML tasks) and ample memory will be required.

Security disclaimer

The security-related practices in this chapter are illustrative design suggestions enabled by agentic architectures. They are not formal cybersecurity guidance, standards, or legal/compliance advice. Your implementation should be reviewed and adapted by qualified security professionals and aligned with your organization’s policies, risk posture, and regulatory obligations.

We will start our agentic journey with an overview of the core concepts, and later dive into novel methods and coding.

This chapter marks a step up the abstraction ladder. In earlier chapters, we began from classic NLP pipelines:

Figure 11.1 – Classic NLP pipeline

Then, we progressed to modern transformer-based LLMs, then to prompt-and-tool patterns and retrieval-augmented workflows:

Figure 11.2 - Prompt-and-tool pattern

That trajectory naturally leads to the idea of agents: systems that can pursue goals across multiple steps, choose tools as needed, maintain state over time, and decide when to stop.

In this book, an agent is a program whose decisions are made by a language model, not by a fixed, hardcoded rule chain. Concretely, the LLM plans the next step, chooses whether and which tool to call and with what arguments, observes the result, and then revises its plan in a loop until a stop condition is met. This aligns with Hugging Face’s framing of agents as systems where LLM outputs control the workflow and decide tool use and sequencing. Agency can vary depending on how much control we hand over to the model.

Let’s review the following workflow:

Figure 11.3 – Prompt-and-tool pattern with autonomous loop

Prompts give us a way to ask models for work. Chains stabilize repeatable sequences (e.g., draft → critique → revise). Tools use grounds models in external capabilities such as search, code execution, databases, and calculators. The next step is autonomy: let the system decide which sub-steps to execute, which tools to use, and how to adapt based on intermediate results. An agent is simply an LLM-centered program with a policy for deciding what to do next, memory for carrying context across steps, and the ability to act and reflect.

Agents excel when tasks are as follows:

  • Compositional and open-ended: Multi-step objectives that can’t be solved in one pass, as in this example:
    Analyze a batch of documents, extract structured facts, verify them, then draft a brief with citations.
  • Tool-heavy: Problems that require choosing and sequencing specialized tools, such as vector search, SQL, web calls, code execution, and policy checks.
  • Long-running or stateful: Work that spans multiple contexts or interactions, such as monitoring a source for updates or running a research loop until quality thresholds are met.
  • Ambiguous but decomposable: Objectives that benefit from dynamic planning, such as if X fails, try Y, or split into subtasks A, B, C, then integrate.

So, when does a single LLM call or simple chain suffice? Not every solution needs an agentic approach. In many cases, a single LLM invocation or a simple chain is the most effective and robust choice.

Prefer simpler patterns when the following applies:

  • The task is well-specified and short-lived, such as Summarize this one document in 5 bullets
  • Latency or cost constraints are tight and do not allow for iterative reasoning or tool use
  • The domain is predictable, and a static pipeline covers the vast majority of cases
  • Observability is limited, and we can’t inspect or trace multi-step behavior, as agents without observability are hard to debug

A practical rule of thumb is that if we can write down the exact sequence of steps and it doesn’t need to adapt based on the data it sees, then we should start with a chain. If the step order, tool choice, or stopping conditions depend on what happens along the way, consider an agent to assert decision-making in real time.

Understanding the core concepts of single-agent and multi-agent systems

Section titled “Understanding the core concepts of single-agent and multi-agent systems”

This section marks a conceptual transition point in the book. Up to now, we have focused on how to make language models useful through prompts, tools, retrieval, and structured orchestration. Those techniques showed us how to extend a model’s reach. What they did not fully address is how systems decide what to do next when the path forward is not predetermined.

The objective of this section is to introduce the mental model required to move from scripted workflows to decision-making systems. Agents represent that shift. Instead of encoding control flow entirely in code, we allow a language model to participate in planning, execution, and revision across multiple steps. This is the foundation that enables autonomy, adaptation, and sustained problem solving.

We begin with single-agent systems because they capture the core ideas in their simplest form. By understanding how policy, memory, tools, and feedback loops work together inside one agent, we gain clarity on where agents add value, where they introduce risk, and how to design them responsibly. These concepts recur throughout the chapter and later chapters, regardless of whether the system contains one agent or many.

Only after establishing these fundamentals do we expand outward to multi-agent systems. Multi-agent designs do not introduce fundamentally new building blocks. Instead, they introduce coordination challenges. They amplify both the strengths and the failure modes of agents through specialization, interaction, and negotiation. That is why the discussion starts with anatomy and guardrails, then builds toward collaboration patterns, protocols, and trade-offs.

In short, this section exists to give you a durable framework. One that helps you decide when an agent is the right abstraction, how to design it cleanly, and how to reason about scaling from a single decision-maker to coordinated systems without losing control.

A single agent wraps four pillars: policy, memory, tools, and an observe-act loop governed by explicit termination criteria. The observe-act loop is the mechanism that lets the agent iteratively take actions, inspect their outcomes, update its internal state, and decide what to do next. Termination criteria define when this loop must stop. They encode the conditions under which the agent considers its objective complete, its budget exhausted, or further progress unlikely. Making these stop conditions explicit is essential. Without them, agents risk running indefinitely, revisiting the same states, or accumulating unnecessary cost and latency. Understanding these components clearly will save us time, money, and headaches.

The policy decides what to do next. At the preliminary and basic level, it maps the (goal, current state) pair to the next action. In LLM systems, the policy is often implemented with a prompt-conditioned model call plus a compact, structured schema for the action space, such as the following:

call search(query=...)

Here is another example:

draft(answer=...) and stop.

Here are some points to keep in mind for maintaining a robust design.

We may constrain the agent’s actions with JSON schemas or function-calling specs to prevent hallucinations around the tool names or the names of their arguments. We can also assert guardrails, such as allowing or denying tools based on data sensitivity and user permissions. Applying budget-aware planning could be a useful approach as we include tokens, cost, or latency in the prompt so the agent plans within limits.

Agents need a defined state to avoid going in circles and to improve over time. Let’s review several approaches to handle such states. A short-term scratchpad can be employed for step-by-step notes, intermediate results, partial hypotheses, and pending sub-goals. Conversation and session memory will externalize history across the current run. It will include messages, tool outputs, and decisions made. On the other hand, long-term memory is where we log facts worth reusing across runs, such as a user’s style guide, project glossary, or validated citations. Broader memory configurations may include domain memory stores, which include vector databases for RAG, relational databases for facts and metrics, or key-value caches for context on recent answers, and cost usage.

A tip for managing all these is to keep the working set small and relevant. Use methods to reduce the scope of content, such as summarization and state compaction to prevent context bloat, and build a memory hygiene routine that handles expiration, deduplication, and perhaps Personally Identifiable Information (PII) minimization.

Tools turn a model from just processing text into a capability router. They enable it to search a corpus, run code, hit an API, execute SQL, check policy, fetch exchange rates, use a math engine, or invoke a secondary model. For best practice, a robust tool layer includes several design properties that directly affect reliability, safety, and cost control:

  • Typed arguments and explicit return schemas are used to constrain calls and make outputs machine-checkable.
  • Idempotent or retry-safe operations ensure thattransient failures can be retried without duplicate side effects. We prefer reads and UPSERT semantics, require idempotency keys for mutating actions, and auto-retry with exponential backoff when the operation is safe to repeat.
  • Quotas and rate limits act as safeguards to prevent runaway loops from draining budgets and to enforce fairness under load.
  • As a good practice, side-effect containment is achieved through sandboxing, least-privilege credentials, and a clear separation between read-only and mutating tools.

Observation loop (act → observe → revise)

Section titled “Observation loop (act → observe → revise)”

After each action, the agent observes (tool output and environment change), updates state/memory, and replans. This loop enables reflective patterns (e.g., “self-critique” before finalizing) and adaptive routing (e.g., “fallback to local model if the API is down”). Ensure that each loop step logs what happened (action, parameters, result, time, and cost), as we’ll need these traces for debugging and evaluation.

Autonomy needs brakes. To keep agent behavior predictable, safe, and cost-bound, we define explicit stop conditions. These conditions determine when the observe-act loop must halt, even if the agent could technically continue reasoning or acting. Common termination criteria include the following:

  • Goal is achieved
  • Budget exhausted: Triggered when hitting token/cost/latency ceilings
  • Max depth/hops: Enforced based on the number of actions or planner cycles
  • No progress: Applied to detect repeated states or oscillation and bail early
  • Human checkpoint: Used in high-risk domains, requires approval before final action

Let’s observe some common issues and how to mitigate them. In practice, these failure modes tend to surface once agents operate autonomously over multiple steps, making it essential to pair agentic flexibility with explicit guardrails. Tool loops and thrashing occur when an agent repeatedly invokes the same actions without making progress. Some possible practices include loop detectors, capping the number of retries, and penalizing revisiting identical states. In such cases, we could incorporate action diversity prompts of the “try a different tool or plan” kind.

Goal drift is another frequent issue where the agent gradually deviates from the original objective. To ensure that the goal is kept in focus, we can try regrounding on the original objective at each step. We can do that by keeping a goal reminder visible in the prompt.

Latency and cost blow-ups often emerge as a side effect of unconstrained planning or excessive tool use. This may be directly linked to system constraints that we must meet. For that, we could set budgets, surface them to the policy, and build short-circuit paths.

Unverifiable outputs pose a different class of risk, particularly in production or high-stakes settings. We can reduce risks by mandating structured outputs with evidence and validators: syntax/consistency checks, unit tests for code, and schema validators for data.

A single agent gives us adaptive sequencing and tool choice. Multiple agents give us specialization and interaction. The design space is rich, but most real systems boil down to three topologies and a handful of interaction protocols.

Topologies describe the shape of coordination among agents and determine how decisions, data, and accountability flow. We choose a topology to balance control, adaptability, and failure blast radius while keeping latency and cost predictable. We treat the topology as an explicit graph so we can test each edge and node, trace outcomes, and evolve the design as requirements change. We often begin with a simple shape that fits the constraint we care about most, then introduce hybrid patterns as the system matures, for example, a hub orchestrating a few peer exchanges inside one stage. We also plan for migration paths so a pipeline can gain peer review at a critical step or a peer network can add a coordinator/planner during peak-load periods:

  • Hub-and-spoke (planner + executors): A planner decomposes the problem and delegates to specialized executor agents that take on the role of specialists, such as a researcher, analyst, editor, and auditor. The planner aggregates, resolves conflicts, and decides to stop or continue. The pros are clear control, easier observability, and scalable specialization. The con, however, is the risk of forming a bottleneck, as the planner may create a single point of failure.
  • Peer-to-peer (role specialists): Here, the agents converse as equals, each with a defined role. Work emerges from their negotiation. One common scenario is a programmer-reviewer duo. The pros here come from the way the agents complement each other’s roles, and so they tend to be more resilient to failures, they tend to derive more creative solutions, and they can achieve more validated results. The cons could be a challenge around bounding costs and the need for stronger protocols.
  • The pipeline/assembly line: In this setting, the work passes through fixed stages, such as the following:

Figure 11.4 – The pipeline/assembly line design

Each stage is an agent with clear I/O contracts. Here, the pros come from the predictable pattern. It is easier to plan and anticipate latency and cost, and it lends itself to forming tests for each stage in the process. The analogous cons are that it is less adaptive and is sensitive to unexpected inputs.

If we want control and cost predictability, we will start with a hub-and-spoke or a pipeline topology. If we want diverse reasoning and resilience, we will consider a peer-to-peer topology and add strong stop rules.

Interaction protocols are the rules of engagement that keep multiple agents from talking past each other. They define the sequencing of who speaks when, the state and evidence for what is shared, designate who has authority, and define what must hold true, such as budgets, stop rules, and SLAs. Picking an explicit protocol turns a free-form LLM conversation into a reproducible, auditable, and budget-bounded workflow. We can trace decisions, replay from checkpoints, and enforce guardrails. In practice, we may wish to choose the lightest protocol that satisfies our constraints.

In practice, the goal is to adopt the lightest protocol that still satisfies our constraints. The simplest place to start is structured turn-taking. In this setting, the agents speak in rounds, often with a moderator enforcing order and even the time or budget limits. This approach is good for peer-to-peer debates or programmer-reviewer loops.

As coordination needs grow, turn-taking alone can become inefficient, particularly when agents need to reference shared facts or intermediate results. In these cases, a shared blackboard provides a natural extension. Designated agents write to a common scratchpad that holds facts, partial results, or open questions. Other agents read, update, or resolve items. This reduces redundant work and supports asynchronous contributions if needed.

For production systems that require loose coupling, concurrency, and stronger observability guarantees, interaction often shifts again toward message buses or event-driven designs. Instead of calling each other directly, agents publish events and subscribe to the types they care about. This enables concurrency, natural fan-out/fan-in, and easy scaling, while the event stream doubles as an audit trail. We keep events small but structured, and make consumers idempotent so retries don’t create duplicate side effects. We pair the bus with a shared blackboard like this: a state is written to the blackboard, then an event is published pointing to the update, while keeping sensitive data out of the bus.

Task decomposition breaks a high-level goal into discrete, prescribed sub-tasks, each with clear inputs/outputs and success predicates, so agents can work in parallel, be tested in isolation, and recombine results deterministically.

A common starting point is role prompting. Here, each agent is given an explicit mission along with well-defined inputs and expected outputs, often enforced through schemas. This keeps responsibilities clear, reduces ambiguity in handoffs, and makes individual steps easier to test and evaluate.

Once roles are defined, we can further refine execution through skill routing. Instead of sending every sub-task to the same agent or model, we route work to the most appropriate capability based on heuristics or learned policies. For example, short code transformations may go to a small local model, complex database joins to a SQL tool, and open-ended synthesis to a larger, more capable model. This improves both cost efficiency and quality without changing the overall workflow.

In more adaptive systems, roles themselves do not have to remain fixed. With dynamic role assignment, the coordinator can initiate, retire, or reassign roles on the fly based on intermediate results, confidence signals, or budget pressure.

Figure 11.5 portrays the entire flow of an agentic design with the components that we covered:

Figure 11.5 – Agent stack

Table 11.1 lays out the differences between setting up a single agent versus multiple agents:

DimensionSingle agentMulti-agent
QualityGood for well-scoped tasks, may miss cross-checksCan improve through specialization, debate, and auditing
LatencyLowerHigher unless constrained
CostLower baselineHigher, must budget per agent/tool
RobustnessSensitive to single failuresResilient if agents cross-verify, risk of coordination bugs
ObservabilityEasier to traceRequires structured traces and per-agent spans
ComplexitySimpler to build/maintainMore moving parts, needs protocols and governance

Table 11.1 - Single-agent vs. multi-agent trade-offs

At this point, we have all the conceptual pieces on the table. In the next section, we will walk through a concrete, end-to-end multi-agent setup in code, showing how planners, executors, protocols, memory, and termination criteria come together in practice, and how the abstract trade-offs discussed previously translate into concrete design and engineering decisions.

Building an executive brief assistant from end to end

Section titled “Building an executive brief assistant from end to end”

To make the agentic routing concepts concrete, we’ll build a simple pipeline that produces an executive briefing from a small folder of PDF/HTML/TXT/Markdown files. The pipeline is rule-based: it selects a model at runtime and orchestrates a sequence of tools and agents to transform raw text into a concise, cited brief. The following is a step-by-step guide with code excerpts demonstrating how to assemble this system.

The full implementation for this example is available in the accompanying GitHub repository, Ch11_Executive_Brief_Assistant.ipynb, for readers who want to explore the code in full.

Let’s begin by preparing our environment, installing any missing dependencies, and importing the necessary libraries. The notebook uses LLMPop for model initialization, SentenceTransformers for embedding, FAISS for similarity search, Beautiful Soup and PyMuPDF for parsing, and pandas for tabular output.

Next, choose which LLM you want to use and initialize it via LLMPop. The provider can be OpenAI or a local Ollama model. For OpenAI, the notebook prompts you for an API key. LLMPop returns a LangChain chat model, which we wrap to provide a consistent .chat() interface:

# Choose a provider and model, fallback to environment defaults
PROVIDER_NAME = os.environ.get(“LLMPOP_PROVIDER”, “openai”) # “openai” or “ollama”
MODEL_NAME = os.environ.get(“LLMPOP_MODEL”, “gpt-5.2-2025-12-11”)

Build helper classes for metering and logging

Section titled “Build helper classes for metering and logging”

To monitor usage and cost, create a simple meter that counts tokens, estimates latency, and accumulates cost per call. We also wrap the LLM in an LLMWrapper class instance that uses this meter and exposes a single chat() method for later reuse:

@dataclass
class Meter:
model: str
provider: str
input_cost_per_1k: Optional[float] = None
output_cost_per_1k: Optional[float] = None
total_tokens_in: int = 0
total_tokens_out: int = 0
total_cost: float = 0.0
timings: List[Tuple[str, float]] = field(default_factory=list)
def __post_init__(self):
if (self.provider or “”).lower() == “ollama”:
self.input_cost_per_1k = 0.0
self.output_cost_per_1k = 0.0
else:
self.input_cost_per_1k = 0.00025 # Placeholder rates
self.output_cost_per_1k = 0.002
def enc(self):
try:
return tiktoken.encoding_for_model(self.model)
except Exception:
return tiktoken.get_encoding(“cl100k_base”)
def count_tokens(self, text: str) -> int:
return len(self.enc().encode(text or “”))
def log_call(self, name: str, prompt: str, output: str, dt: float):
tin = self.count_tokens(prompt)
tout = self.count_tokens(output)
self.total_tokens_in += tin
self.total_tokens_out += tout
self.total_cost += (tin / 1000.0) * self.input_cost_per_1k + (tout / 1000.0) * self.output_cost_per_1k
self.timings.append((name, dt))
def snapshot(self) -> Dict[str, Any]:
return {
“model”: self.model,
“tokens_in”: self.total_tokens_in,
“tokens_out”: self.total_tokens_out,
“cost_usd”: round(self.total_cost, 4),
“steps”: len(self.timings),
“durations”: self.timings,
}
# Wrap the LLM and meter together
class LLMWrapper:
def __init__(self, llm_obj, model_name: str):
self.llm = llm_obj
self.meter = Meter(model=model_name, provider=PROVIDER_NAME)
def chat(self, system: str, user: str, **kwargs) -> str:
messages = [
{“role”:”system”,”content”:system},
{“role”:”user”,”content”:user}]
t0 = time.time()
out = self.llm.chat(messages, **kwargs)
dt = time.time() - t0
self.meter.log_call(kwargs.get(“name”,”chat”), user, out, dt)
return out
LLM = LLMWrapper(_llm, MODEL_NAME)

Separate prompt strings by intent so that each step of the pipeline can reuse them. Our assistant must be concise, cite sources inline ([S#]), and call a policy gate to append a risk note when necessary:

SYSTEM_BASE = (
“You are an Executive Brief Assistant. Be concise, factual, and cite sources inline like [S1], [S2].\\n”
“Prefer bullet points. Extract metrics (numbers, dates, percentages) explicitly.”
)
PROMPT_DRAFT = “””
You are drafting a 1 page executive brief from provided EVIDENCE.
Return:
1) “Key Takeaways” — 5 8 bullets
2) “Key Metrics” — bullet list of numbers & dates with % or units
3) “Details with Inline Citations” — short bullets, each ending with [S#]
Keep total under ~250 words.
EVIDENCE (JSON list of {{id, source, text}}):
{evidence_json}
“””
PROMPT_SELF_CRITIQUE = “””
Check the DRAFT for completeness and unsupported claims.
– List missing topics if any.
– Mark any bullet that lacks evidence.
Output JSON: {{“missing_topics”: [...], “unsupported”: [“...excerpt...”]}}
DRAFT:
{draft}
“””
PROMPT_EDITOR = “””
Edit for executive tone, clarity, and brevity.
– Preserve citations like [S#].
– Keep to ~1 page total.
INPUT:
{draft}
“””
PROMPT_POLICY = “””
Act as a policy gate. If text mentions sensitive terms (investment advice, medical advice, PII, legal directives),
add a short “Risk Note” with safe language guidance. Else say “No material risk”.
TEXT:
{final_text}
“””

The pipeline must parse documents from a folder, break them into overlapping chunks, embed them using SentenceTransformers, and store them in a FAISS vector index for retrieval. The following helper functions load PDF, HTML, or text files, slice them into chunks, and build the index:

DOC_DIR = “/content/docs”
os.makedirs(DOC_DIR, exist_ok=True)
CHUNK_SIZE = 700
CHUNK_OVERLAP = 100
model_embed = SentenceTransformer(“all-MiniLM-L6-v2”)
index = None
store: List[Dict[str, Any]] = []
def _chunks(text: str, size=CHUNK_SIZE, overlap=CHUNK_OVERLAP):
text = re.sub(r”\\s+”, “ “, text).strip()
i = 0
while i < len(text):
yield text[i:i+size]
i += size - overlap
def load_pdf(path: str) -> str:
doc = fitz.open(path)
return “\\n”.join(page.get_text(“text”) for page in doc)
def load_html(path: str) -> str:
with open(path, “r”, encoding=”utf-8”, errors=”ignore”) as f:
soup = BeautifulSoup(f.read(), “html.parser”)
return soup.get_text(“ “)
def load_txt(path: str) -> str:
with open(path, “r”, encoding=”utf-8”, errors=”ignore”) as f:
return f.read()
def ingest_folder(folder: str = DOC_DIR):
global index, store
docs = []
pid = 1
for fp in glob.glob(os.path.join(folder, “**/*”), recursive=True):
if os.path.isdir(fp):
continue
ext = os.path.splitext(fp)[1].lower()
try:
if ext == “.pdf”:
raw = load_pdf(fp)
elif ext in [“.html”, “.htm”]:
raw = load_html(fp)
else:
raw = load_txt(fp)
except Exception:
continue
for ch in _chunks(raw):
store.append(
{“id”: pid, “source”: os.path.basename(fp), “text”: ch})
docs.append(ch)
pid += 1
embs = model_embed.encode(
docs, convert_to_numpy=True, show_progress_bar=False)
dim = embs.shape[1]
idx = faiss.IndexFlatIP(dim)
faiss.normalize_L2(embs)
idx.add(embs)
index = (idx, embs)
print(f”✅ Ingested {len(docs)} chunks from {len(set(d[‘source’] for d in store))} files.”)
# Call once after placing your files into DOC_DIR
ingest_folder(DOC_DIR)

Retrieval is a simple top-K nearest neighbor search over the indexed embeddings:

def retrieve(query: str, k: int = 6) -> List[Dict[str, Any]]:
if index is None:
return []
idx, embs = index
q = model_embed.encode([query], convert_to_numpy=True)
faiss.normalize_L2(q)
D, I = idx.search(q, k)
out = []
for rank, j in enumerate(I[0], 1):
out.append({
“id”: int(store[j][“id”]),
“source”: store[j][“source”],
“text”: store[j][“text”],
“score”: float(D[0][rank-1])
})
return out

Two helper functions ensure that each bullet in our draft is grounded in evidence. The citation_checker() function tests whether a claim is sufficiently similar to any evidence chunk and whether numeric values match. The coverage_score() function calculates what fraction of bullets pass the citation check:

NUMERIC_RE = re.compile(r”[-+]?\\d[\\d,]*(?:\\.\\d+)?%?”)
def citation_checker(claim: str, evidence_chunks: List[Dict[str,Any]], threshold: float = 0.75) -> bool:
if not claim or not evidence_chunks:
return False
vec_claim = model_embed.encode([claim], convert_to_numpy=True)
faiss.normalize_L2(vec_claim)
vec_e = model_embed.encode(
[c[“text”] for c in evidence_chunks],
convert_to_numpy=True)
if vec_e.size == 0:
return False
faiss.normalize_L2(vec_e)
sims = (vec_claim @ vec_e.T).flatten()
if sims.max() < threshold:
return False
nums = NUMERIC_RE.findall(claim)
if nums:
best = evidence_chunks[int(np.argmax(sims))][“text”]
for n in nums:
if n.replace(“,”, “”) not in best.replace(“,”, “”):
return False
return True
def coverage_score(
draft_text: str, evidence_chunks: List[Dict[str,Any]]
) -> float:
bullets = [b.strip(“ -•\\t”) for b in draft_text.split(“\\n”) if b.strip().startswith((“-”, “•”))]
if not bullets:
return 0.0
ok = sum(1 for b in bullets if citation_checker(b, evidence_chunks))
return ok / max(1, len(bullets))

A minimal agent can handle the full pipeline by itself. SingleAgent retrieves evidence, drafts the brief, critiques itself to identify missing topics, optionally redrafts with additional evidence, edits for tone, and finally calls the policy gate. A configuration class controls k search, coverage thresholds, and maximum rounds:

@dataclass
class SingleAgentConfig:
k: int = 8
coverage_threshold: float = 0.6
max_rounds: int = 2
@dataclass
class SingleAgent:
llm: LLMWrapper
cfg: SingleAgentConfig
def run(self, question: str) -> Dict[str,Any]:
log = {“question”: question, “rounds”: []}
evidence = retrieve(question, k=self.cfg.k)
evidence_json= json.dumps(
[{k:v for k,v in e.items() if k!=”score”} for e in evidence],
ensure_ascii=False)
draft = self.llm.chat(
SYSTEM_BASE, PROMPT_DRAFT.format(evidence_json=evidence_json),
name=”draft”)
for r in range(self.cfg.max_rounds):
critique = self.llm.chat(
SYSTEM_BASE, PROMPT_SELF_CRITIQUE.format(draft=draft),
name=”critique”)
try:
findings = json.loads(critique)
except Exception:
findings = {“missing_topics”: [], “unsupported”: []}
add_q = “; “.join(findings.get(“missing_topics”, []) or [])
if add_q:
evidence += retrieve(add_q, k=4)
evidence_json = json.dumps(
[
{k:v for k,v in e.items() if k!=”score”}
for e in evidence
],
ensure_ascii=False)
draft = self.llm.chat(
SYSTEM_BASE,
PROMPT_DRAFT.format(evidence_json=evidence_json),
name=”redraft”)
cov = coverage_score(draft, evidence)
log[“rounds”].append({“critique”: findings, “coverage”: cov})
if cov >= self.cfg.coverage_threshold:
break
edited = self.llm.chat(
SYSTEM_BASE, PROMPT_EDITOR.format(draft=draft), name=”edit”)
policy = self.llm.chat(
SYSTEM_BASE, PROMPT_POLICY.format(final_text=edited),
name=”policy”)
return {
“brief”: edited,
“risk_note”: policy,
“evidence”: evidence,
“meter”: self.llm.meter.snapshot(),
“log”: log,
}

To run the baseline, instantiate the agent and call run() with your question:

BASELINE_CFG = SingleAgentConfig(
k=8, coverage_threshold=0.6, max_rounds=2)
BASELINE = SingleAgent(LLM, BASELINE_CFG)
question = “Summarize the key developments and metrics across the documents, focusing on timelines, budgets, and outcomes.”
result = BASELINE.run(question)
print(result[“brief”])
print(“Risk note:”, result[“risk_note”])
print(“Meter:”, result[“meter”])

While the single-agent baseline works, a multi-agent approach mirrors our earlier design discussion and supports specialization. Here, each agent handles a specific role:

  • Coordinator: Defines the plan and monitors budgets
  • Researcher: Retrieves evidence
  • Analyst: Proposes claims from the evidence
  • Auditor: Verifies each claim using the citation checker
  • Editor: Assembles a concise draft from the surviving claims
  • PolicyGate: Appends a risk note if needed

The blackboard shares the state among all agents. A simple Budget class stops execution after too many steps or seconds:

@dataclass
class Blackboard:
question: str
evidence: List[Dict[str,Any]] = field(default_factory=list)
claims: List[Dict[str,Any]] = field(default_factory=list)
draft: str = “”
final: str = “”
logs: List[str] = field(default_factory=list)
def add_log(self, msg):
ts = time.strftime(“%H:%M:%S”)
self.logs.append(f”[{ts}] {msg}”)
@dataclass
class Budget:
max_steps: int = 8
max_seconds: float = 60

Each agent’s act() method updates the blackboard:

class Coordinator:
def __init__(self, llm: LLMWrapper, budget: Budget):
self.llm = llm
self.budget = budget
def plan(self, bb: Blackboard) -> List[str]:
bb.add_log(“Coordinator: plan Research → Analyst → Auditor → Editor → Policy”)
return [“research”, “analyze”, “audit”, “edit”, “policy”]
class Researcher:
def __init__(self, k=10):
self.k = k
def act(self, bb: Blackboard):
found = retrieve(bb.question, k=self.k)
bb.evidence.extend(found)
bb.add_log(f”Researcher: added {len(found)} chunks”)
class Analyst:
def __init__(self, llm: LLMWrapper):
self.llm = llm
def act(self, bb: Blackboard):
evidence_json = json.dumps(
[
{k:v for k,v in e.items() if k!=”score”}
for e in bb.evidence
],
ensure_ascii=False)
prompt = (“From EVIDENCE, propose 6 9 concise claims with 0 1 numeric metric each. “
“Return JSON list of {text, confidence:0 1, cites:[S# indices]}.\\nEVIDENCE:\\n” + evidence_json)
out = self.llm.chat(SYSTEM_BASE, prompt, name=”claims”)
try:
bb.claims = json.loads(out)
bb.add_log(f”Analyst: proposed {len(bb.claims)} claims”)
except Exception:
bb.claims = []
bb.add_log(“Analyst: failed to parse claims JSON”)
class Auditor:
def act(self, bb: Blackboard):
passed = []
for c in bb.claims:
ok = citation_checker(c.get(“text”,””), bb.evidence)
if ok:
passed.append(c)
bb.claims = passed
bb.add_log(f”Auditor: {len(passed)} claims passed citation check”)
class Editor:
def __init__(self, llm: LLMWrapper):
self.llm = llm
def act(self, bb: Blackboard):
# fallback if no claims remain
if not bb.claims:
evidence_json = json.dumps(
[
{k:v for k,v in e.items() if k!=”score”}
for e in bb.evidence
],
ensure_ascii=False)
draft = self.llm.chat(
SYSTEM_BASE,
PROMPT_DRAFT.format(evidence_json=evidence_json),
name=”draft_fallback”)
draft = self.llm.chat(
SYSTEM_BASE, PROMPT_EDITOR.format(draft=draft),
name=”edit_fallback”)
bb.draft = draft
bb.add_log(“Editor: fallback draft assembled (no claims available)”)
return
# format claims with citations
def _fmt_cites(cites):
try:
ints = [int(c) for c in cites]
return “ “ + “ “.join(f”[S{i}]” for i in ints) if ints else “ [S1]”
except Exception:
return “ [S1]”
claims_txt = “\\n”.join(
[f”- {c.get(‘text’,’’).strip()}{_fmt_cites(c.get(‘cites’, []))}”
for c in bb.claims if c.get(‘text’)])
if not claims_txt.strip():
# fallback again if formatting produced nothing
evidence_json = json.dumps(
[
{k:v for k,v in e.items() if k!=”score”}
for e in bb.evidence
], ensure_ascii=False)
draft = self.llm.chat(
SYSTEM_BASE,
PROMPT_DRAFT.format(evidence_json=evidence_json),
name=”draft_fallback2”)
draft = self.llm.chat(
SYSTEM_BASE, PROMPT_EDITOR.format(draft=draft),
name=”edit_fallback2”)
bb.draft = draft
bb.add_log(“Editor: secondary fallback draft assembled (empty claims after formatting)”)
return
draft = self.llm.chat(
SYSTEM_BASE, PROMPT_EDITOR.format(draft=claims_txt),
name=”edit2”)
bb.draft = draft
bb.add_log(“Editor: draft assembled from claims”)
class PolicyGate:
def __init__(self, llm: LLMWrapper):
self.llm = llm
def act(self, bb: Blackboard):
note = self.llm.chat(
SYSTEM_BASE, PROMPT_POLICY.format(final_text=bb.draft),
name=”policy2”)
bb.final = bb.draft + “\\n\\nRisk Note: “ + note
bb.add_log(“Policy: risk note appended”)

The Orchestrator class holds the shared budget and coordinates the steps. After each agent’s action, it checks whether coverage meets a threshold; if not, it loops back to research/analysis/audit/edit once more. Execution stops when the budget of steps or seconds is exhausted:

@dataclass
class Orchestrator:
llm: LLMWrapper
budget: Budget = field(default_factory=Budget)
coverage_threshold: float = 0.7
def run(self, question: str) -> Dict[str,Any]:
if index is None or not store:
return {
“final”: “⚠️ No documents indexed. Upload files to /content/docs and re-run ingest_folder() first.”,
“blackboard”: {“evidence”: [], “claims”: [], “logs”: [“No docs available”]},
“meter”: self.llm.meter.snapshot(),
}
bb = Blackboard(question=question)
steps = 0
t0 = time.time()
coord = Coordinator(self.llm, self.budget)
researcher = Researcher(k=12)
analyst = Analyst(self.llm)
auditor = Auditor()
editor = Editor(self.llm)
policy = PolicyGate(self.llm)
for stage in coord.plan(bb):
if time.time() - t0 > self.budget.max_seconds or steps >= self.budget.max_steps:
bb.add_log(“Budget hit → early good enough release”)
break
if stage == “research”:
researcher.act(bb)
elif stage == “analyze”:
analyst.act(bb)
elif stage == “audit”:
auditor.act(bb)
elif stage == “edit”:
editor.act(bb)
cov = coverage_score(bb.draft, bb.evidence)
bb.add_log(f”Coverage={cov:.2f}”)
if cov < self.coverage_threshold:
bb.add_log(“Coverage below threshold → refining query & looping”)
researcher.act(bb)
analyst.act(bb)
auditor.act(bb)
editor.act(bb)
elif stage == “policy”:
policy.act(bb)
steps += 1
return {
“final”: bb.final or bb.draft,
“blackboard”: {
“evidence”: bb.evidence,
“claims”: bb.claims,
“logs”: bb.logs,
},
“meter”: self.llm.meter.snapshot(),
}

To run the multi-agent system, instantiate Orchestrator and call run():

ORCH = Orchestrator(LLM, Budget(max_steps=8, max_seconds=60))
ma_result = ORCH.run(“Produce an executive brief with metrics, trends, and timelines across the corpus.”)
print(ma_result[“final”])
print(“Meter:”, ma_result[“meter”])

Finally, it’s helpful to compare cost, token usage, and latency between the baseline and the hub-and-spoke implementation. The following helper builds a pandas DataFrame from the meter snapshots and displays it:

def meter_to_rows(tag: str, m: Dict[str,Any]):
dur = sum(t for _,t in m.get(“durations”, []))
return {
“run”: tag,
“tokens_in”: m.get(“tokens_in”, 0),
“tokens_out”:m.get(“tokens_out”, 0),
“cost_usd”: m.get(“cost_usd”, 0.0),
“steps”: m.get(“steps”, 0),
“latency_s”: round(dur, 2),
}
df = pd.DataFrame([
meter_to_rows(“single_agent”, result[“meter”]),
meter_to_rows(“multi_agent”, ma_result[“meter”]),
])
# Use display_dataframe_to_user() if running in Colab
from IPython.display import display
display(df)

That sums up our first complete agentic process. We will now learn about new capabilities with agentic design.

Deep dive into MAF and advanced orchestration frameworks

Section titled “Deep dive into MAF and advanced orchestration frameworks”

The goal of this section is to bridge the conceptual foundations of agentic systems with a production-grade implementation that you can reason about, extend, and operate in real-world environments. Earlier in the chapter, we focused on what agents are, when they help, and how single- and multi-agent designs behave at an architectural level. Here, we turn those abstractions into concrete engineering practice.

This section moves from what agents are to how to build, orchestrate, and operate them. Specifically, we focus on how modern agent frameworks encode policy, memory, tools, orchestration loops, observability, and guardrails in code, and how these design choices influence reliability, cost, and governance. We now introduce what we feel is one of the most significant code bases for agentic design: MAF.

This deep dive serves two purposes in the context of the book. First, it provides a realistic reference implementation that reflects the design principles discussed throughout the chapter. Second, it prepares the ground for the hands-on multi-agent system we will build later, where concepts such as planners, executors, protocols, checkpoints, and termination criteria must work together under real constraints.

In this book’s previous edition, we capitalized on Microsoft’s AutoGen as the agentic design code base. AutoGen was released several months before our first edition, and since then, it has gotten a lot of support and enhancements from Microsoft. Simultaneously, Microsoft developed another code base that’s dedicated to designing solutions with LLMs, called Semantic Kernel. MAF represents the convergence of these efforts. MAF is the successor framework with official migration guides from both AutoGen and Semantic Kernel.

Over the remainder of this section, we will build a working mental model of MAF, examine its core abstractions, understand how it supports both autonomous agents and deterministic workflows, and evaluate how it compares to other orchestration frameworks such as LangGraph. The emphasis is not on API memorization, but on understanding how architectural choices in the framework map to the agent design patterns discussed earlier in the chapter.

At a glance, MAF gives us the following:

  • Agents that could run on various provider backends: Azure AI, Azure OpenAI, OpenAI, custom chat clients, and local models, such as Ollama, and can call tools and MCP servers, which we covered in Chapter 9
  • Graph-based workflows with checkpointing, streaming, HITL, and time-travel debugging, designed for multi-agent orchestration
  • Observability via OpenTelemetry, plus a middleware pipeline for retries, error handling, rate limiting, and policy controls
  • Connectors to enterprise systems such as Microsoft Graph, Fabric, SharePoint, Oracle, Bedrock, MongoDB, and Logic Apps, to wire agents to real business data

Let’s review the core abstractions:

  • Agent: In MAF, agents work over mainstream providers, such as Azure, OpenAI, and so on, and can also run over any chat client that implements the appropriate interface, which is fantastic for looking to work with local LLMs.
  • State: Each agent maintains conversation/session state and can participate in workflows where state is checkpointed and replayed.
  • Plans: A plan is the agent’s working idea for what to do next, updated by the plan → act → observe → revise loop, which we will look deeper into next. Plans frequently involve tool invocations, sub-goal creation, or hand-offs to other agents in a workflow.
  • Tools/functions/MCP servers: Tools can be functions that are described by JSON schema or external services exposed via MCP. For robust tool use, we want typed arguments and explicit return shapes. The framework encourages this approach as it relies on provider capabilities that support function calling.
  • Memory: This addresses all types of memory: short-term scratchpads, long-term stores, and workflow-level checkpoints. In MAF, checkpointing elevates memory from “prompt context” to a managed runtime feature.
  • Connectors: MAF introduces built-in integrations to business systems and data planes such as Microsoft Graph, Fabric, SharePoint, Oracle, Bedrock, and MongoDB. These let agents work with enterprise data.

Orchestration loop: plan → act → observe → revise

Section titled “Orchestration loop: plan → act → observe → revise”

MAF treats orchestration as more than just chaining model calls. In the typical cycle, the agent plans (chooses an action/tool or delegates), acts (executes a tool call or emits a message), observes (records outputs, updates state), then revises (updates plan or terminates). The framework provides both agent orchestration (LLM-driven autonomy) and workflow orchestration (deterministic, graph-based routing), allowing us to mix creative reasoning with production guardrails.

It is worth stressing how well MAF lends itself to testing and observing. In prior chapters, we stressed testability and observability. A plan/act loop with structured state and tool schemas is testable. We can trace actions, inputs, outputs, time, and cost, then replay the run later to debug or improve prompts/tools.

Observability in MAF is built directly into the runtime through a combination of telemetry, tracing, and control points. Telemetry and tracing are provided through OpenTelemetry integration, so every action, tool call, and handoff can emit spans and metrics. This pairs with the DevUI for debugging complex runs.

At the workflow level, control is further enforced through checkpointing and HITL gates, which are built into the graph runtime. This allows us to pause or approve high-risk steps, then resume from a checkpoint if needed.

MAF has some great features that are worth highlighting before we start developing.

Function calling, with typed arguments and fixed return shapes, is our primary defense against hallucinated tool names/parameters, which is an evident risk. When our model supports function calling, we expose tools with schemas. This way, the agent runtime and provider client ensure only recognized tools are invoked, and only with valid arguments.

Here are some design tips we’ll implement later in the chapter:

  • Validate tool arguments server-side and reject unknown tools.
  • Keep tool outputs structured to feed downstream evaluators.
  • Enforce allow/deny lists at the middleware layer.

MAF supports both agent-driven planning, where an LLM decides the next step, and workflow-driven planning, where a graph path decides the next node. Its workflow engine supports sequential, concurrent, handoff, and magnetic styles. These are all patterns we’ll use in the multi-agent build, and we will review them.

While “critique” is a pattern rather than a single MAF API, the framework makes it easy to attach critics because we can model a critic agent in the workflow graph to validate outputs such as facts, schema, and style. We can route through critics only on certain conditions, such as low confidence or expensive queries, using graph type-based routing and HITL gates to keep latency and cost on budget. Labs and samples cover benchmarking hooks so we can measure deltas after adding critics.

We’ll apply this pattern later by inserting an Auditor node that enforces evidence coverage before the final draft is emitted.

Eventing and callbacks for tracing and audit

Section titled “Eventing and callbacks for tracing and audit”

We’ll often need to hook into steps for compliance logs, tokens/cost metering, or dynamic budget cuts. With MAF’s OpenTelemetry traces and middleware pipeline, we can add callbacks that stamp each tool call with correlation IDs and user/session metadata. We can set them to short-circuit loops when budgets are at, say, 80%. Or we can emit audit artifacts such as inputs, outputs, and evidence IDs into our data plane.

Figure 11.6 captures the plan, act, observe loop with MAF.

Figure 11.6 – The plan, act, observe loop with MAF

Think of MAF and LangGraph as complementary approaches that can both model agentic systems. They prioritize different ergonomics.

InLangGraph’s graph-oriented orchestration, the philosophy is that we design an explicit state machine/DAG. Agents and tools are nodes/edges, and control flow is deterministic unless we give a node autonomy. Its strengths are its persistence, streaming, debugability, and deployment ergonomics, which are the headline features in LangGraph’s docs. It is excellent when we need precise control over topology and state. The trade-off is that it requires the graph to be thought of up front, as exploratory autonomy patterns such as free-form debates need more scaffolding.

Conversely, with MAF’s unified model, it explicitly supports agent orchestration and workflow orchestration in one runtime. The former is LLM-driven, while the latter is deterministic multi-agent graphs. This way, we can start dynamically and gradually lock down critical paths with graphs, HITL gates, and checkpoints. With regards to interoperability and connectors, rich enterprise connectors and compatibility with any IChatClient interface (including Ollama) mean we can wire local models and enterprise data planes into the same system. Ops and governance are manifested in the form of built-in OpenTelemetry, middleware for retries/limits/policies, and documentation that centers operational concerns such as rate limits, caching, and graceful degradation.

Table 11.2 covers the main takeaways of this section.

CapabilityMicrosoft Agent FrameworkLangGraph
Primary mental modelUnified agents + workflows, autonomous loops with graph constraints when neededGraph/DAG/state-machine first, agents as nodes with persistence/streaming
State and recoveryCheckpointing, time-travel, and HITL gates built into workflowsPersistence, streaming, and debug tools emphasized
InteroperabilityWorks with Azure AI, Azure OpenAI, OpenAI, and IChatClientWorks with many providers via the LangChain ecosystem
ObservabilityOpenTelemetry integrated, middleware for retries/limits/policiesDebugability and deployment features, persistence, and streaming
ConnectorsEnterprise connectors (Graph, Fabric, SharePoint, Oracle, Bedrock, etc.)Integrates with tools in the LangChain ecosystem
Best fitMixed autonomy + governance, enterprise data, unified.NET/Python storyPrecise graph control, state-machine workflows, rich debugging

Table 11.2 – Reviewing the differences between MAF and LangGraph

As we review those differences, we can form some intuition for which approach to go for. For greenfield projects that need fast iteration, we will start with MAF’s agent orchestration + a thin workflow spine. As requirements stabilize, we will introduce graph constraints (either MAF workflows or LangGraph) around high-risk segments and add HITL gates and checkpointing.

Implementing a simple agent using MAF and Ollama

Section titled “Implementing a simple agent using MAF and Ollama”

To make the agentic protocol concepts tangible, let’s walk through a minimal example using MAF with a local Ollama model. In just a few dozen lines of code, we’ll show how an agent can plan, act, observe, and revise once, calling a single read-only tool. This demonstration stays self-contained and cloud-free, focusing on the control flow rather than performance.

Readers who want to run this example locally can refer to the accompanying GitHub repository (Ch11_Microsoft_Agent_Framework_Ollama_Agent.ipynb) for the full implementation.

We begin by spinning up a local model and wrapping it in an OpenAI-style chat client. LLMPop abstracts over model providers, so you can switch between Ollama and OpenAI by changing one variable. Here we default to a small llama3.2:1b model:

PROVIDER_NAME = os.environ.get(“LLMPOP_PROVIDER”, “ollama”)
MODEL_NAME = os.environ.get(“LLMPOP_MODEL”, “llama3.2:1b”)

We then initiate the model:

chat_model = init_llm(
model=MODEL_NAME, provider=PROVIDER_NAME,
temperature=0.0, verbose=True)

The call to init_llm returns a LangChain‐style chat model. Setting temperature=0.0 makes outputs deterministic for this demo.

MAF expects an OpenAI-like interface. To avoid rewriting downstream code, we wrap the LangChain chat model with a tiny adapter class that exposes a.chat.completions.create method. It accepts a list of messages, each with a role and content, and returns an object with a .choices list, just like the OpenAI API:

class OpenAICompatClient:
class _Chat:
def __init__(self, lc_chatmodel):
self.lc = lc_chatmodel
class completions:
@staticmethod
def create(
model: str, messages: list[dict[str, str]], **kwargs
):
from langchain_core.messages import (
SystemMessage, HumanMessage)
lc_msgs = []
for m in messages:
role = m.get(“role”, “user”)
content = m.get(“content”, “”)
if role == “system”:
lc_msgs.append(SystemMessage(content=content))
else:
lc_msgs.append(HumanMessage(content=content))
resp = chat_model.invoke(lc_msgs)
# wrap the result to match OpenAI’s interface
class Choice:
def __init__(self, content):
self.message = type(
“_M”, (),
{“content”: content})
return type(
“_R”, (),
{“choices”: [Choice(
getattr(resp, “content”, str(resp))) ]
})
def __init__(self, lc_chatmodel):
self.chat = self._Chat(lc_chatmodel)
openai_like_client = OpenAICompatClient(chat_model)

This shim is intentionally minimal; its only job is to translate LangChain messages into a format that MAF can consume, and vice versa.

Define a read-only tool with a tight JSON schema

Section titled “Define a read-only tool with a tight JSON schema”

Next, we define a single tool that the agent can call. In this example, the tool returns a mock currency exchange rate. A JSON schema enforces valid arguments, ensuring that the agent can only request supported currency pairs:

SUPPORTED_CURRENCIES = [“USD”,”EUR”,”GBP”,”JPY”]
TOOL_SCHEMA = {
“name”: “get_exchange_rate”,
“description”: “Return a mock FX rate for base→quote (read only).”,
“input_schema”: {
“type”: “object”,
“properties”: {
“base”: {“type”: “string”, “enum”: SUPPORTED_CURRENCIES},
“quote”: {“type”: “string”, “enum”: SUPPORTED_CURRENCIES},
},
“required”: [“base”,”quote”],
“additionalProperties”: False
}
}
MOCK_RATES = {
(“USD”,”EUR”): 0.92, (“EUR”,”USD”): 1.09,
(“USD”,”GBP”): 0.78, (“GBP”,”USD”): 1.28,
(“USD”,”JPY”): 151.0, (“JPY”,”USD”): 0.0066,
(“EUR”,”GBP”): 0.85, (“GBP”,”EUR”): 1.17,
}
def get_exchange_rate(base: str, quote: str) -> dict[str, float]:
“””Return a mock FX rate for a supported currency pair.”””
if base == quote:
return {“rate”: 1.0, “base”: base, “quote”: quote}
key = (base, quote)
if key not in MOCK_RATES:
raise ValueError(f”Unsupported pair {base}/{quote}”)
return {“rate”: MOCK_RATES[key], “base”: base, “quote”: quote}

Using an explicit schema is important: it lets the agent framework validate inputs before executing the tool and prevents unexpected key/value pairs.

Add lightweight middleware for safety and telemetry

Section titled “Add lightweight middleware for safety and telemetry”

Even simple agents benefit from basic governance. We implement three small mechanisms:

  • Allow list: Only pre-approved tool names can be invoked
  • Token cap: Roughly limit the total message length to avoid runaway loops
  • OpenTelemetry spans: Wrap each stage of the loop in a span so that traces are emitted to the console

Here is the code:

resource = Resource.create({“service.name”: “maf-hello-agent”})
provider = TracerProvider(resource=resource)
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
ALLOWED_TOOLS = {“get_exchange_rate”}
TOKEN_CAP = 4000 # coarse limit (illustrative)
def guard_tool_call(tool_name: str, args: dict[str, str]):
“””Check tool name and argument types before execution.”””
if tool_name not in ALLOWED_TOOLS:
raise PermissionError(f”Tool ‘{tool_name}’ not allowed”)
base = args.get(“base”); quote = args.get(“quote”)
if not isinstance(base, str) or not isinstance(quote, str):
raise ValueError(“Invalid types for base/quote”)
if base not in SUPPORTED_CURRENCIES or quote not in SUPPORTED_CURRENCIES:
raise ValueError(“Unsupported currency in args”)

For counting tokens, we use TikToken if available, and if not, we fall back to a rough estimate of characters/4.

The heart of the demo is the single plan → act → observe → revise loop. The agent first decides whether to call a tool or answer directly. If it proposes a tool call, we validate and execute it, then feed the observation back to the model for a final reply:

SYSTEM_PROMPT = (
“You are a tool using agent. You have EXACTLY ONE tool:\n”
“ get_exchange_rate(base, quote) → returns the FX rate for base→quote.\n”
“Supported currencies: USD, EUR, GBP, JPY.\n”
“\n”
“DECISION RULES (follow strictly):\n”
“1) If the user asks about an exchange rate, conversion, FX price, or a pair among the supported currencies,\n”
“ you MUST call the tool instead of guessing.\n”
“2) Otherwise, answer briefly in ≤25 words.\n”
“\n”
“FORMAT:\n”
“- To call the tool, output ONE JSON object ONLY:\n”
“ {\”tool_name\”:\”get_exchange_rate\”,\”args\”:{\”base\”:\”USD\”,\”quote\”:\”EUR\”}}\n”
“- To answer without tools, output ONLY the short sentence.\n”
)
USER = “What’s the USD to EUR rate right now?”
messages = [
{“role”: “system”, “content”: SYSTEM_PROMPT},
{“role”: “user”, “content”: USER},
]
# plan + act
with tracer.start_as_current_span(
“agent.plan_act”,
attributes={“agent_role”:”chat”, “strategy”:”single-hop”}
):
prompt_tokens = sum(len(m[“content”]) // 4 for m in messages) # naive token estimate
if prompt_tokens > TOKEN_CAP:
raise RuntimeError(“token cap exceeded before first hop”)
rsp = openai_like_client.chat.completions.create(
model=MODEL_NAME, messages=messages)
content = rsp.choices[0].message.content.strip()
# observe: did the model propose a tool call?
observation = None
if content.startswith(“{“):
try:
j = json.loads(content)
tool_name = j.get(“tool_name”)
args = j.get(“args”, {})
guard_tool_call(tool_name, args)
with tracer.start_as_current_span(
“tool.execute”, attributes={“tool”: tool_name}
):
if tool_name == “get_exchange_rate”:
observation = get_exchange_rate(
args[“base”], args[“quote”])
except Exception as e:
observation = {“error”: str(e)}
# revise once with observation and stop
final_messages = [
{“role”: “system”, “content”:
“You will receive an Observation JSON with keys rate, base, quote. “
“Return ONE short sentence like ‘USD→EUR ≈ 0.92’. “
“Do NOT include JSON, examples, or ‘User:’ lines.”
},
{“role”: “user”, “content”: f\”Observation: {json.dumps(observation) if observation is not None else ‘{}’}”}
]
with tracer.start_as_current_span(
“agent.revise”,
attributes={“agent_role”:”chat”, “strategy”:”single-hop”}
):
final_rsp = openai_like_client.chat.completions.create(
model=MODEL_NAME, messages=final_messages)
final_text = final_rsp.choices[0].message.content.strip()
print(“\\n--- RESULT ---\\n”)
print(final_text)

This loop enforces the agentic pattern in a transparent way:

  1. Plan/Act: The model is prompted with decision rules and returns either a tool call or a direct answer.
  2. Observe: We parse and validate the tool call, execute the function, and record an observation.
  3. Revise: The observation is appended as a final user message, and the model produces a concise answer based on the observed data.

If you run this code, you should see the mock exchange rate printed, along with telemetry spans logged to the console.

This Hello Agent example condenses Microsoft’s agentic protocol into its simplest executable form. It demonstrates how to do the following:

  1. Wrap a local or cloud model behind a unified chat interface.
  2. Define a deterministic, type-safe tool with a JSON schema.
  3. Add minimal middleware for governance and observability.
  4. Implement a basic plan → act → observe → revise loop without relying on the full MAF runtime.

In the next section, we’ll build on these foundations, moving from a singletool agent to multi-agent orchestration and graph-based workflows. We’ll also show how to integrate more realistic tools and data sources while preserving testability and operational safety.

Building coordinated multi-agent workflows with MAF

Section titled “Building coordinated multi-agent workflows with MAF”

To bridge the gap between theory and practice, this section shows how to build a complete multi-agent pipeline using the MAF. We start from the problem definition and design principles introduced earlier, then walk through a working implementation step by step. The goal is to produce an executive brief from a folder of documents while enforcing budgets, evidentiality, and governance. Each numbered step explains what the code does and why it’s needed, followed by a short code snippet.

As usual, a complete, runnable version of this multi-agent setup is provided in the accompanying GitHub repository (Ch11_MultiAgent_Marathon.ipynb).

Formalize the business task and acceptance criteria

Section titled “Formalize the business task and acceptance criteria”

Before writing code, we define what success looks like. Our running example is an executivebrief assistant: given 10–30 documents (press releases, blog posts, and product sheets), the system should generate a one-page brief consisting of the following:

  • 5–8 bullet-point takeaways
  • Key metrics (numbers or dates) with inline citations
  • A short risk note
  • A one-sentence recommendation

Every claim must be supported by at least one evidence snippet (a filename and line span or chunk ID). If evidence is lacking, the agent must either ask for more retrieval or flag the gap and stop. The run must respect global token, latency, and cost budgets and output both human-readable text and a machine-readable JSON list of claims and evidence.

Choose a model provider and initialize the chat client

Section titled “Choose a model provider and initialize the chat client”

MAF doesn’t prescribe which language model to use. We follow the pattern introduced in earlier chapters: obtain a chat client through LLMPop, a wrapper that supports local and hosted models. This lets us switch between Ollama and OpenAI by changing environment variables without altering the orchestration logic:

PROVIDER_NAME = os.environ.get(“LLMPOP_PROVIDER”, “openai”) # “openai” or “ollama”
MODEL_NAME = os.environ.get(“LLMPOP_MODEL”, “gpt-5.2-2025-12-11”)

We wrap the LangChain model returned by LLMPop with a minimal shim, just like with the past notebooks in this chapter.

To make execution visible and debuggable, we instrument every agent step with OpenTelemetry. A TracerProvider class instance and a simple console exporter record spans for each phase. In production, you might export to Jaeger or Datadog instead. Here, console spans illustrate latency and errors during development:

resource = Resource.create({“service.name”: “maf-marathon”})
provider = TracerProvider(resource=resource)
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)

Each role invocation (researcher, analyst, auditor, and editor) will run inside a span. Coupled with LLMPop’s token/cost meter, these traces let us measure time-to-first-token, total latency, and cost per brief.

Ingest the document corpus and build a vector index

Section titled “Ingest the document corpus and build a vector index”

Our agents need a retrieval substrate. We ingest the folder of documents into an in-memory vector store. For reproducibility, the demo uses local files under /content/marathon_docs, but this could point to an S3 bucket or a database in production. We parse PDFs with PyMuPDF, strip HTML with Beautiful Soup, and treat plain text and Markdown as simple files. Text is chunked into overlapping windows (e.g., 800 characters with 120character overlaps) and encoded with a compact sentence transformer. These embeddings populate a FAISS index for efficient cosine similarity search:

EMBED = SentenceTransformer(“all-MiniLM-L6-v2”)
store = [] # list of {id, source, text}
index = None # (faiss_index, embeddings)
CHUNK_SIZE = 800
CHUNK_OVERLAP = 120
# Helper to split text into overlapping chunks
def chunks(text: str, size=CHUNK_SIZE, overlap=CHUNK_OVERLAP):
text = re.sub(r”\s+”, “ “, text).strip()
i = 0
while i < len(text):
yield text[i:i+size]
i += max(1, size - overlap)
# Ingest documents into the vector store
for pid, fp in enumerate(
glob.glob(os.path.join(DOC_DIR, “**/*”), recursive=True), 1
):
if os.path.isdir(fp): continue
if fp.lower().endswith(“.pdf”):
raw = fitz.open(fp)
text = “\n”.join(p.get_text(“text”) for p in raw)
elif fp.lower().endswith((‘.html’, ‘.htm’)):
soup = BeautifulSoup(
open(fp, encoding=”utf-8”, errors=”ignore”).read(),
“html.parser”)
text = soup.get_text(“ “)
else:
text = open(fp, encoding=”utf-8”, errors=”ignore”).read()
for ch in chunks(text):
store.append(
{“id”: pid, “source”: os.path.basename(fp), “text”: ch})
pid += 1
# Build FAISS index
embs = EMBED.encode([s[“text”] for s in store], convert_to_numpy=True)
faiss.normalize_L2(embs)
faiss_index = faiss.IndexFlatIP(embs.shape[1])
faiss_index.add(embs)
index = (faiss_index, embs)

This retrieval layer is deliberately light: it normalizes vectors for innerproduct search and stores chunk metadata in a simple list. Production systems often add caching, sharding, or search engine backends, but the principle remains: retrieval is deterministic, testable, and side-effect-free, aligning with MAF’s emphasis on typed, idempotent tools.

Agents interact with the environment through tools. We define three pure functions with lightweight JSON schemas:

  1. search: Given a query and k, return the top k chunk identifiers from the FAISS index.
  2. excerpt: Fetch the full text of a chunk by its ID.
  3. cite_check: Verify whether a claim is supported by the current evidence set. It uses a semantic similarity score and an exact numeric match heuristic to ensure that numbers in the claim appear verbatim in the evidence:
TOOLS = {
“search”: {
“description”: “Return top k chunks for a query”,
“schema”: {“type”: “object”,
“properties”: {“query”: {“type”: “string”},
“k”: {“type”: “integer”, “minimum”: 1, “maximum”: 20}
}, “required”: [“query”], “additionalProperties”: False
}
},
“excerpt”: {
“description”: “Fetch chunk text by id”,
“schema”: {“type”: “object”,
“properties”: {“id”: {“type”: “integer”, “minimum”: 1}},
“required”: [“id”], “additionalProperties”: False
}
},
“cite_check”: {
“description”: “Check whether a claim is supported by current evidence set”,
“schema”: {“type”: “object”,
“properties”: {“claim”: {“type”: “string”},
“threshold”: {“type”: “number”,
“minimum”: 0, “maximum”: 1
}
}, “required”: [“claim”], “additionalProperties”: False
}
}
}
# Tool implementations
def tool_search(args):
query = args.get(“query”, “”); k = int(args.get(“k”, 8))
idx, embs = index
q_vec = EMBED.encode([query], convert_to_numpy=True)
faiss.normalize_L2(q_vec)
D, I = idx.search(q_vec, k)
return {“results”: [{“id”: int(store[j][“id”]), “source”: store[j][“source”]} for j in I[0]]}
def tool_excerpt(args):
cid = int(args.get(“id”, -1))
for e in store:
if e[“id”] == cid:
return {“id”: cid, “text”: e[“text”]}
return {“error”: f”id {cid} not found”}
NUMERIC_RE = re.compile(r”[-+]?\d[\d,]*(?:\.\d+)?%?”)
def citation_checker(
claim: str, evidence: List[Dict[str,Any]], threshold: float
) -> bool:
“””Return True if claim is supported by any evidence chunk above threshold and numeric values match.”””
if not claim or not evidence:
return False
vec_c = EMBED.encode([claim], convert_to_numpy=True)
faiss.normalize_L2(vec_c)
vec_e = EMBED.encode(
[e[“text”] for e in evidence], convert_to_numpy=True)
if vec_e.size == 0:
return False
faiss.normalize_L2(vec_e)
sims = (vec_c @ vec_e.T).flatten()
if sims.max() < threshold:
return False
nums = NUMERIC_RE.findall(claim)
if nums:
best = evidence[int(np.argmax(sims))][“text”]
for n in nums:
if n.replace(“,”, “”) not in best.replace(“,”, “”):
return False
return True
def tool_cite_check(args):
claim = args.get(“claim”, “”)
thr = float(args.get(“threshold”, 0.65))
ok = citation_checker(claim, current_evidence, thr)
return {“claim”: claim, “supported”: bool(ok)}

These tools are stateless and safe to retry, which aligns with best practices discussed earlier: avoid side effects, restrict inputs to known schemas, and fail fast when validation fails.

Each agent plays a specialized role in the hub-and-spoke topology:

  • Researcher: Given a question, decide what to search. It must return a JSON object specifying the search tool and its arguments.
  • Analyst: Transform evidence into a list of candidate claims. Claims should be concise (≤ 25 words) and reuse numbers and names verbatim.
  • Auditor: Verify claims using the citation checker. It returns two lists: passed and failed claims.
  • Editor: Assemble the final brief with bullets, metrics, and inline citations.

Figure 11.7 captures the design of the flow in its simplest form, illustrating the basic flow of work.

Figure 11.7 – Visualizing the simplest form of flow of the roles

We encode these instructions as succinct system prompts, keeping output formats strictly defined to ease parsing and evaluation:

PROMPTS = {
“researcher”: “””
You are the Researcher. Given a QUESTION, call the \`search\` tool with a focused query.
Return ONLY ONE JSON object: {“tool_name”: “search”, “args”: {“query”: “...”, “k”: N}}.
“””,
“analyst”: “””
You are the Analyst. Given EVIDENCE (list of {id,source,text}), propose at most 6 concise claims.
Each claim should be short (≤25 words) and include at most one metric.
Paraphrase evidence closely! Reuse numbers and named entities verbatim.
Return ONLY a JSON array of objects with a single key \`text\`: {“text”: “...”}.
“””,
“auditor”: “””
You are the Auditor. For each claim, decide whether it is supported by the current EVIDENCE via \`cite_check\`.
Return ONLY ONE JSON with fields: {“passed”: [“claim1”, ...], “failed”: [“claimX”, ...]}. No prose.
“””,
“editor”: “””
You are the Editor. Write a one page executive brief:
- 5–8 bullet key takeaways
- Key metrics bullets
- Brief bullets with inline citations like [S#]
Keep under ~250 words. Input CLAIMS (passed) and EVIDENCE (ids+sources only). Output plain text.
Return ONLY the brief text; no headers; bullets start with ‘- ‘; preserve [S#] citations.
“””,
}

These prompts enforce deterministic output schemas, which makes it straightforward to parse responses, retry failures, and measure quality. They also constrain verbosity to keep costs predictable.

Implement the workflow and the coordinator logic

Section titled “Implement the workflow and the coordinator logic”

The coordinator orchestrates the pipeline. It holds a blackboard, a shared scratchpad with the question, evidence, claims, the draft brief, and logs. It enforces a budget of maximum hops and wallclock time.

To support this, we first define the lightweight runtime structures that manage shared state, checkpointing, and execution limits:

@dataclass
class Budget:
max_hops: int = 10
max_seconds: float = 90
token_cap: int = 12000 # reserved for future use
@dataclass
class Checkpoint:
step: str
blackboard: Dict[str,Any]
t: float
@dataclass
class Blackboard:
question: str
evidence: List[Dict[str,Any]] = field(default_factory=list)
claims: List[str] = field(default_factory=list)
brief: str = “”
logs: List[str] = field(default_factory=list)
checkpoints: List[Checkpoint] = field(default_factory=list)
def log(self, msg):
self.logs.append(f”[{time.strftime(‘%H:%M:%S’)}] {msg}”)
def snap(self, step: str):
# Store a compact snapshot for debugging/replay
self.checkpoints.append(
Checkpoint(
step=step,
blackboard={
“evidence”: [
{“id”: e[“id”], “source”: e[“source”]}
for e in self.evidence],
“claims”: list(self.claims),
“brief_present”: bool(self.brief),
“logs_len”: len(self.logs),
}, t=time.time())
)
# Control toggles
RETRY_IDEMPOTENT = True # allow one structured retry on parse errors
BYPASS_MODE = False # skip auditor and accept analyst claims as-is
@tracer.start_as_current_span(“workflow.run”)
def run_workflow(question: str, budget: Budget) -> Dict[str,Any]:
global current_evidence
bb = Blackboard(question=question)
t0 = time.time()
hops = 0

Then with this context in place, at each phase, the coordinator does the following:

  1. Calls the researcher to plan a search tool invocation and fetches evidence using the excerpt tool:
    # Phase 1: Researcher plans search and we ingest evidence
    with tracer.start_as_current_span(“role.researcher”):
    sys = PROMPTS[“researcher”]
    user = f”QUESTION: {question}\nReturn JSON only.”
    plan = CHAT.ask(sys, user).strip()
    try:
    j = json.loads(re.search(r”\{[\s\S]*\}”, plan).group(0))
    if j.get(“tool_name”) != “search”: raise ValueError(“bad tool”)
    res = tool_search(j.get(“args”, {}))
    ids = [r[“id”] for r in res.get(“results”, [])]
    ev = []
    for cid in ids:
    ex = tool_excerpt({“id”: cid})
    if “text” in ex:
    src = next(
    s[“source”] for s in store if s[“id”] == cid)
    ev.append(
    {“id”: cid, “source”: src,
    “text”: ex[“text”]}
    )
    current_evidence = ev
    bb.evidence = ev
    bb.log(f”Researcher: {len(ev)} chunks”)
    except Exception as e:
    bb.log(f”Researcher failed: {e}”)
    bb.snap(“research”)
    hops += 1
    if time.time() - t0 > budget.max_seconds or hops >= budget.max_hops:
    return {“blackboard”: bb}
  2. Feeds the evidence to the analyst and collects proposed claims:
    # Phase 2: Analyst proposes claims
    with tracer.start_as_current_span(“role.analyst”):
    sys = PROMPTS[“analyst”]
    ev_json = json.dumps(bb.evidence[:12], ensure_ascii=False)
    out = CHAT.ask(sys, f”EVIDENCE: {ev_json}\nReturn JSON only.”)
    claims = extract_first_json_array(out)
    if not claims and RETRY_IDEMPOTENT:
    retry_prompt = (
    “Return EXACTLY a JSON array of objects with a single key \`text\`.\n”
    “Example: [{\”text\”:\”...\”},{\”text\”:\”...\”}]\n”
    f”EVIDENCE: {ev_json}\nNo prose. JSON array only.”
    )
    out2 = CHAT.ask(sys, retry_prompt)
    claims = extract_first_json_array(out2)
    if claims:
    bb.claims = [
    c.get(“text”, “”)[:400]
    for c in claims if isinstance(c, dict)
    and c.get(“text”)
    ]
    bb.log(f”Analyst: {len(bb.claims)} claims”)
    else:
    # Fallback: derive short sentences from evidence to avoid empty pipeline
    bb.log(“Analyst: no parseable claims; falling back to evidence-based stubs”)
    bb.claims = [
    (e[“text”].split(“.”)[0] + “.”)[:200]
    for e in bb.evidence[:4]
    if e.get(“text”, “”).strip()
    ]
    bb.snap(“analyst”)
    hops += 1
    if time.time() - t0 > budget.max_seconds or hops >= budget.max_hops:
    return {“blackboard”: bb}
  3. Runs the auditor to filter claims. If no claims pass and backoff is enabled, it retains a few original claims to avoid empty output.
    # Phase 3: Auditor verifies claims unless bypass mode is active
    with tracer.start_as_current_span(“role.auditor”):
    original = list(bb.claims)
    if BYPASS_MODE:
    passed = original
    else:
    passed = []
    for c in original:
    ok = tool_cite_check(
    {
    “claim”: c,
    “threshold”: 0.65
    }
    ).get(“supported”, False)
    if ok:
    passed.append(c)
    # If nothing passes, degrade gracefully
    if not passed:
    if original:
    passed = original[:min(4, len(original))]
    bb.log(“Auditor: 0 supported → retaining original claims as fallback”)
    else:
    passed = [
    (e[“text”].split(“.”)[0] + “.”)[:200]
    for e in bb.evidence[:4] if e.get(“text”, “”).strip()
    ]
    bb.log(“Auditor: no claims parsed → evidence-based stub claims”)
    bb.claims = passed
    bb.log(f”Auditor: {len(bb.claims)} claims retained”)
    bb.snap(“auditor”)
    hops += 1
    if time.time() - t0 > budget.max_seconds or hops >= budget.max_hops:
    return {“blackboard”: bb}
  4. Invokes the editor to assemble the brief from the surviving claims and evidence references.
    # Phase 4: Editor produces final brief
    with tracer.start_as_current_span(“role.editor”):
    # Map evidence ids to citation numbers [S1], [S2], …
    ids_map = {
    e[“id”]: i+1 for i, e in enumerate(
    sorted(bb.evidence, key=lambda x: x[“id”]))}
    def cites(_):
    return f” [S{ids_map.get(bb.evidence[0][‘id’], 1)}]”
    if ids_map
    else “”
    claims_txt = “\n”.join(f”- {c}{cites(c)}” for c in bb.claims)
    sys = PROMPTS[“editor”]
    srcs = sorted(
    set((e[‘id’], e[‘source’]) for e in bb.evidence))
    user = f”CLAIMS:\n{claims_txt}\n\nEVIDENCE SOURCES (ids only): {srcs}”
    brief = CHAT.ask(sys, user)
    bb.brief = brief
    bb.snap(“editor”)
    # Return the result package
    return {
    “brief”: bb.brief,
    “claims”: bb.claims,
    “evidence”: [
    {
    “id”: e[“id”], “source”: e[“source”],
    “text”: e[“text”]
    } for e in bb.evidence],
    “blackboard”: {
    “logs”: bb.logs,
    “checkpoints”: [
    {“step”: c.step, “t”: c.t, “bb”: c.blackboard}
    for c in bb.checkpoints
    ],
    },
    }
  5. Optionally inserts an HITL gate before releasing the result (not shown in code but easy to add).

All phases are wrapped in telemetry spans, and the budget stops execution if the hop or time limits are exceeded. Checkpoints capture the blackboard state after each phase for replay and debugging.

The coordinator encapsulates our hub-and-spoke topology. Each role writes to the blackboard. The coordinator reads the state, decrements budgets, and either loops or stops. Because MAF supports checkpointing, the snap method captures minimal state after every phase, enabling time-travel debugging and regression testing. You could easily add an HITL gate before releasing the brief by inserting an approval step between the editor and the return.

With the workflow defined, we can run it on a local corpus. The top-level function ingests documents (if not already done), creates a budget, and calls run_workflow. We print the brief, the structured JSON of claims and evidence, and a note that spans were printed to the console by OpenTelemetry:

_ing_ok = ingest(DOC_DIR)
if not _ing_ok:
print(“⚠️ Skipping run — no documents indexed.”)
else:
BUDGET = Budget(max_hops=8, max_seconds=90, token_cap=12000)
t_start = time.time()
with tracer.start_as_current_span(“marathon.execute”):
result = run_workflow(“Summarize key developments and metrics with citations.”, BUDGET)
total_time = time.time() - t_start
# Display results
print(“\n=== BRIEF ===\n”)
print(result.get(“brief”, “<no brief>”))
print(“\n=== STRUCTURED JSON (claims + evidence) ===\n”)
print(json.dumps({“claims”: result.get(“claims”, []), “evidence”: result.get(“evidence”, [])}, ensure_ascii=False, indent=2))
print(“\n=== TRACE NOTE ===\nOpenTelemetry spans were printed above by the Console exporter.”)

Running this cell in the notebook yields a human-readable brief with inline citations such as [S1], a JSON list of the claims and their evidence, and a stream of span logs showing the time spent in each role. You can adjust the budget, model, and prompts to explore the trade-offs between quality, cost, and latency.

The pipeline finishes by validating each claim against the evidence using the same citation checker and printing a tick or cross next to each claim. A tiny evaluation harness loops over multiple “golden” corpora, runs the workflow, and computes precision@evidence, the fraction of claims that truly match their cited evidence. This metric plus spans gives a quantitative basis for improving prompts, thresholds, and routing policies. You can compare runs under different models, budgets, or retry strategies without changing the core design.

Goldens, spot checks, and performance signals

Section titled “Goldens, spot checks, and performance signals”

Once we have a structured artifact, we can treat quality as a regression problem. Maintain a small set of “golden” corpora (10–20 is usually enough) and rerun them on every prompt/tool change. For live systems, sample a small fraction of runs for human spot checks, especially when confidence is low, or the pipeline falls back. Alongside quality, we track operational metrics: time-to-first-token (TTFT) and time-per-output-token (TPOT) for responsiveness, throughput for capacity planning, and cost per brief for budget predictability. OpenTelemetry spans give us the raw timing breakdowns. The key is to make these measures part of the system’s feedback loop, not an afterthought.

To sum up, this is what we mean by marathon: an end-to-end, inspectable run that exercises the full path from retrieval to brief with measurable quality, cost, and time. Ready to graduate into a production workflow?

Strategies for agent collaboration, negotiation, and competition

Section titled “Strategies for agent collaboration, negotiation, and competition”

The previous sections established agent anatomy and multi-agent topologies and showed how we implement them. Here, we introduce the interaction mechanics that drive quality and reliability, not by adding more agents, but by orchestrating them. We’ll learn when to prefer shared scratchpads or mediated summaries, how to design handoffs with explicit contracts and SLAs, and when to use consensus, debate, or adjudication. We’ll also model bidding/auctions for task selection, and we’ll show how competitive setups such as red-team versus builder, duel-of-explanations, and budget-aware contests can raise quality and safety. Finally, we’ll close with practical governance hooks around policy agents, tool sandboxes, and HITL gates that lead into Chapter 12.

We continue to leverage MAF in this section, as all the points and methods discussed map to MAF’s two pillars: agents and workflows.

Collaboration mechanics are the rules and structures that let multiple agents contribute to one goal without stepping on each other. They decide what gets shared, who owns a decision at each stage, and how work moves forward when there is uncertainty or disagreement. The aim is not to add more agents but to create predictable handoffs, traceable evidence, and measurable gains in quality. We will start by introducing simple patterns and then add rigor where it pays off in reliability and cost control.

A shared scratchpad, also called a blackboard, gives every agent a common working surface for facts, partial results, open questions, and confidence scores. This reduces duplicate effort and makes parallel work possible because each role can read and extend what others have written. In MAF, we model the scratchpad as a workflow state and checkpoint it after major phases so the system can branch, replay, or resume without repeating previous steps.

Mediated summaries take a lighter approach. Instead of exposing raw intermediate artifacts, a coordinator or mediator emits concise digests that link back to evidence. We use mediated summaries when inputs are noisy or high volume and downstream roles do not need full detail, and when we want to stabilize context size and prevent low-confidence content from propagating. As a rule of thumb, we start with a shared scratchpad during research and extraction, then switch to mediated summaries as we converge. In both cases, we keep evidence identifiers so later verification and audit are straightforward.

Every handoff should behave like an interface rather than a vague suggestion. We define the minimal inputs the next role needs, for example, claim text, a list of evidence identifiers, a required confidence threshold, and a deadline. We define the outputs as structured results that include a clear pass or fail signal, a list of gaps that require action, and the citations that support the decision. We define an SLA that sets a token budget, a time budget, and a maximum number of hops the receiving role may spend. In MAF, we encode these contracts as typed messages or workflow state and checkpoint at each boundary so we can roll back or retry without re-running upstream work.

Consensus protocols: majority vote, weighted expertise, debate, then decide

Section titled “Consensus protocols: majority vote, weighted expertise, debate, then decide”

The majority vote asks several agents to propose answers independently and then selects the modal result. It is often the strongest baseline for accuracy in reasoning tasks, though cost and latency grow roughly with the number of proposals.

Weighted expertise improves on plain voting when agents have known strengths. We assign a higher weight to the specialist that has demonstrated accuracy on similar problems, for example, a finance-tuned model for profit and loss (P&L) questions or a compliance-tuned model for policy interpretation. We start by calibrating weights on a small golden set, and we refresh them as we collect new results.

Debate then decide emphasizes explanation. Proposers present arguments and critiques, after which an adjudicator chooses the final answer using a rubric that values factual support, completeness, and clarity. In practice, well-tuned voting covers many gains, while debate shines when we must show the reasoning or break ties on ambiguous prompts.

To implement any of these in MAF, we model proposals as parallel workflow branches and checkpoint each branch. We use a reducing node to compute the vote or to run the judge agent. Then we merge to emit the selected answer while archiving the alternates for audit.

In this section, we explain how to make agents negotiate productively under real constraints. We begin with a tight proposer-critic loop that drives quick improvements. When multiple specialists are available, we switch to a lightweight auction so the right agent wins the work. When answers still diverge, we resolve conflicts with a clear adjudication step backed by evidence. Throughout, we keep budgets visible, checkpoint each stage, and preserve a rationale for audit.

We first ask a proposer to draft the answer. We then have a critic enumerate issues and confidence gaps using a fixed schema so the feedback is actionable. The proposer revises or requests more evidence, and we repeat this exchange for a small number of rounds while shrinking the available budget each time to prevent endless polishing. In MAF, we connect the two agents in a short cycle, store a round counter in the workflow state, and checkpoint after every pass so a human reviewer can take over if the loop exceeds our limit. We label critiques with categories such as missing citation, number mismatch, and style violation, and we only accept the draft when all blocking items are cleared.

When we have several capable specialists, we ask each to submit a bid for the subtask. Each bid states the expected quality, the expected cost, the expected latency, and the agent’s confidence. We score the bids with a simple objective that favors quality per dollar and adds a penalty for slow responses, then we award the task to the highest score. We record the decision, checkpoint, and let the winner execute while the others stand down. This method shines when budgets are tight and when the cost profiles differ, for example, when a local model is cheap but weaker, while a hosted model is stronger but expensive. In MAF, we deliver bids as typed messages, let the coordinator perform deterministic selection, and create checkpoints before and after execution to make the process reproducible.

Even with careful design, agents will disagree. We establish tie-break rules up front so decisions are predictable. For example, we prefer answers grounded in verified numeric sources over narrative claims. When a tie remains, we appoint an adjudicator who applies a rubric that weighs factual support, completeness, and clarity, and that references the traces and evidence created earlier. We compute a final confidence by combining the agent’s self-reported confidence with the breadth and quality of the supporting evidence. In MAF, we model the adjudicator as a single judge node with access to blackboard snapshots of arguments and citations, and we require it to write a short rationale alongside the decision so the next reader can understand why the system chose that outcome.

Here, we explain how we use constructive competition to raise quality, expose failure modes, and harden safety. We stage controlled contests between agents, and we measure outcomes under the same budgets, so improvements are real and repeatable. We run these competitions inside the workflow, so every attempt is traced, checkpointed, and easy to audit.

We first generate a draft with a builder agent. We then unleash a dedicated red team agent whose sole purpose is to probe the draft and its planned tool calls for prompt injections, jailbreaks, and data exfiltration tricks. We capture every finding and require the builder to produce targeted mitigations or clarifications, after which we run another red team pass to verify the fix. We place a policy gate after this cycle so a policy agent evaluates the final state against allow lists, deny lists, and safety filters, and only then do we release the result. In MAF, we model the red team as its own role that consumes the latest draft and traces, and we route the outcome to a policy node before completion. We keep an HITL available at the gate, and we rely on checkpoints so we can resume from the last safe point.

We ask two independent builders to produce complete answers that include explicit evidence references and short rationales. We require each explanation to link every claim to evidence identifiers, and we ask for a brief statement of reasoning. We then appoint a judge that compares the two submissions on factual alignment, coverage of the question, and clarity of presentation, and selects the winner with a short written rationale. We keep both the losing and winning traces for audit, so we can study where one approach outperformed the other. In MAF, we run the two builders as parallel branches, we checkpoint both outputs, and we reduce them through a judge node that emits the final selection together with its justification.

We evaluate alternative configurations under the same fixed budget, so the results are comparable. We might pit a small local model against a hosted large model, or a short-context configuration against a long-context configuration, or a fast retrieval setting against a thorough one. We score each run by accuracy per dollar and accuracy per second, and we select the champion for production while recording the runner-up as a fallback. We schedule these contests as periodic audits rather than on every request, which keeps daily latency and cost predictable while still detecting drift. In MAF, we express each variant as a branch with its own budget cap, we merge through a selector node that applies the chosen metric, and we persist the full traces so later analysis can confirm that the choice held up over time.

In this section, we describe how we make governance a built-in property of the system rather than an afterthought. We begin by formalizing policies as executable checks that run alongside the agents. We then confine what tools and data each agent can touch. Finally, we add human checkpoints at the points of highest risk so approvals and overrides become part of the workflow, not ad-hoc decisions.

Policy agents, allow and deny lists, tool sandboxes, and data-scope constraints

Section titled “Policy agents, allow and deny lists, tool sandboxes, and data-scope constraints”

We first introduce a policy agent that evaluates both content and planned tool calls against explicit rules. We encode requirements such as no personal data in outputs, use only approved data for financial calculations, and block unsafe instructions. We then establish allow and deny lists so each role can invoke only the tools that are appropriate for its mission and for the current context. We tighten the boundary further by placing tools in sandboxes and by using scoped connectors, which means we run read-only modes where possible and we attach isolated credentials where writes are required. We also limit where retrieval is allowed. We constrain the agent to whitelisted indices, we tag sources by sensitivity, and we require an approval step when a request crosses into a higher-risk tag. In MAF, we implement these controls as middleware that runs before and after actions and as workflow gates that enforce policy nodes. Because approvals are part of the workflow, checkpointing and HITL support make those approvals durable, traceable, and easy to resume after an intervention.

We place a human checkpoint just before release when the task carries material risk. We present the reviewer with the current draft, the linked evidence, the changes since the last approval, and the cost and latency that the run has accumulated so far. We then offer three clear paths. The reviewer can approve, request additional evidence, or stop the run. We record the decision, write a checkpoint, and continue or halt accordingly. Because the checkpoint preserves state, we can resume from the exact point of review, and we avoid repeating upstream work.

Table 11.3 lays out the different traits of the different strategies we covered.

StrategyTypical quality upliftLatency impactCost impactWhen it shines
Solo (baseline)———Well-scoped tasks with low risk
Majority voteHeightened in reasoning tasksMediumHigher (N× inference)Tasks where accuracy matters most
Weighted voteHeightenedMediumMedium-highTeams with known specialist strengths
Debate then decideMedium-high, as explainability improvesHighHigherAmbiguous tasks that need rationale
Proposer/criticMedium, as precision improvesLow-mediumLow-mediumEditorial/refinement workflows
Auction (bidding)Medium, as it provides an improved cost trade-offLow-mediumOptimizedMixed costs of models/tools
Red team roundSafety is emphasizedMediumMediumPre-release gates, compliance use cases

Table 11.3 – Reviewing the quality/latency/cost impacts of different strategies

Implementing collaboration and competition strategies in multi-agent systems

Section titled “Implementing collaboration and competition strategies in multi-agent systems”

The previous section explored the theoretical foundations of agent collaboration, negotiation, and competition. Now, we turn those ideas into a reproducible, local experiment. The notebook we walk through here provides a sandbox for comparing different strategies on identical tasks while recording quality, latency, and cost under full observability.

The full implementation of these strategies is available in the accompanying GitHub repository (Ch11_Strategies_of_collaboration_and_competition.ipynb).

The notebook begins by installing the necessary libraries, just like prior notebooks in this chapter.

Setup: providers, model, telemetry, and index

Section titled “Setup: providers, model, telemetry, and index”

This phase sets environment variables to choose the model provider and model name and then initializes a chat model:

PROVIDER_NAME = os.environ.get(“LLMPOP_PROVIDER”, “openai”)
MODEL_NAME = os.environ.get(“LLMPOP_MODEL”, “gpt-5.2-2025-12-11”)

It also creates an OpenTelemetry tracer and cost estimators:

resource = Resource.create({“service.name”: “coop-comp-sim”})
provider = TracerProvider(resource=resource)
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
# Token and cost estimators
PRICE_PER_1K = 0.0 if PROVIDER_NAME == “ollama” else 0.0005
_enc = tiktoken.get_encoding(“cl100k_base”)
def tok_len(s: str) -> int:
return len(_enc.encode(s or “”))
def est_cost(tokens: int, price_per_1k: float = PRICE_PER_1K) -> float:
return (tokens / 1000.0) * price_per_1k

The telemetry setup ensures that every strategy run logs spans with durations, token counts, and cost estimates. The token/cost functions let us compute cost per call for fair comparisons.

To evaluate collaboration strategies without side effects, the notebook defines two lightweight tools: search_ctx and cite_check. These simulate retrieval and citation verification in a controlled environment. When a strategy needs evidence, it uses search_ctx to score context passages by lexical overlap. When it needs to verify a numeric claim, it uses cite_check to ensure that numbers appear in the provided support passages:

NUMERIC_RE = re.compile(r”[-+]?\d[\d,]*(?:\.\d+)?%?”)
def search_ctx(context_passages: List[str], query: str, k: int = 3) -> List[Tuple[int, str, float]]:
q = query.lower().split()
scored = []
for i, p in enumerate(context_passages):
toks = p.lower().split()
overlap = len(set(q) & set(toks))
scored.append((i, p, overlap / (len(set(q)) + 1e-9)))
scored.sort(key=lambda x: x[2], reverse=True)
return scored[:max(1, min(k, len(scored)))]
def cite_check(
claim: str, supports: List[str], require_numeric_match: bool = True
) -> bool:
if not supports: return False
claim_l = (claim or “”).lower()
has_overlap = any(sum(w in s.lower() for w in claim_l.split()) >= 3
for s in supports)
if not has_overlap: return False
if not require_numeric_match: return True
nums = NUMERIC_RE.findall(claim or “”)
if not nums: return True
joined = “ || “.join(supports)
for n in nums:
if n.replace(“,”, “”) not in joined.replace(“,”, “”):
return False
return True

These tools provide a deterministic, side-effect-free evaluation environment. The search_ctx function rewards lexical overlap, encouraging the model to use context. The cite_check function punishes numeric hallucination by requiring that numbers in the answer appear verbatim in the support text.

The notebook uses a compact suite of 10 heterogeneous tasks. Each task specifies an ID, a type (short QA, extract, numeric, or reconcile), a prompt, a list of context passages, and, for about half of them, a golden answer or regex. The tasks are declared via a dataclass:

@dataclass
class Task:
id: str
kind: str # “short_qa” | “extract” | “numeric” | “reconcile”
prompt: str
context: List[str]
golden: Optional[Dict[str, Any]] = None # e.g. {“answers”: [“answer”]}
TASKS: List[Task] = [
Task(
id=”t1_short_qa”,
kind=”short_qa”,
prompt=”Who founded PyTorch? Give the primary person’s last name.”,
context=[
“PyTorch is an open source machine learning framework...”,
“PyTorch was developed primarily by Meta AI (formerly Facebook AI Research). Soumith Chintala is widely credited...”
],
golden={“answers”: [“chintala”]}
),
# ... (nine more tasks covering extraction, numeric retrieval, reconciliation, and synonyms)
]

A diverse set of tasks ensures that the strategies are evaluated across different query types: exact answer extraction, numeric retrieval, reconciliation, and short factual questions. Some tasks are judged by exact answers, while others rely on the citation checker. This dual scoring mechanism reflects the mix of well-defined and open-ended tasks encountered in practice.

All model calls are made through a single helper, call_llm, which wraps the chat client and returns the response text, its latency, and token count. This wrapper also records tracing attributes for later analysis. A simple canonicalizer and scoring function judge whether answers are correct:

SYSTEM_BASE = “You are a careful assistant. Be concise. If unsure, say you are unsure.”
def call_llm(system: str, user: str) -> Tuple[str, float, int]:
with tracer.start_as_current_span(“llm.call”) as sp:
sp.set_attribute(“model”, MODEL_NAME)
sp.set_attribute(“provider”, PROVIDER_NAME)
rsp = client.chat.completions.create(model=MODEL_NAME, messages=[
{“role”:”system”,”content”: system},
{“role”:”user”,”content”: user}
])
text = rsp.choices[0].message.content.strip()
latency = getattr(rsp, “latency_s”, 0.0)
tokens = tok_len(system) + tok_len(user) + tok_len(text)
sp.set_attribute(“latency_ms”, round(latency*1000,2))
sp.set_attribute(“tokens_total_est”, tokens)
return text, latency, tokens
# Canonicalization and scoring
CANON_MAP = {“blackboard”: {“blackboard”, “shared scratchpad”, “scratchpad”, “shared memory”}}
def canonicalize(a: str) -> str:
a = (a or “”).strip().lower()
a_norm = re.sub(r”[\s\W]+”, “ “, a).strip()
for canon, syns in CANON_MAP.items():
if any(s in a_norm for s in syns): return canon
return a_norm
def score_answer(task: Task, answer: str) -> bool:
a = canonicalize(answer)
if task.golden:
if “answers” in task.golden:
golds = {canonicalize(g) for g in task.golden[“answers”]}
return any(g in a for g in golds)
if “regex” in task.golden:
return re.search(task.golden[“regex”], answer or “”) is not None
# fallback: overlap
ctx = canonicalize(“ “.join(task.context))
return sum(w in ctx for w in a.split()) >= 2

Centralizing model invocation in call_llm keeps latency and token counting consistent. The scoring functions allow quick evaluation: exact string matches or regular expressions for tasks with known answers. Otherwise, we fall back to lexical overlap plus the citation checker. Canonicalization maps synonyms (e.g., shared memory → blackboard), preventing false negatives.

Each collaboration or competition strategy is implemented as a function returning RunResult. Every strategy records telemetry spans with key attributes (provider, tokens, cost, and correctness) and uses the same scoring rubric. We summarize the strategies next.

The baseline simply calls the model once with the task prompt and context. The result provides a floor for cost, latency, and quality:

def strat_solo(task: Task) -> RunResult:
with tracer.start_as_current_span(“strategy.solo”) as sp:
q = f”{task.prompt}\n\nContext:\n” + “\n”.join(task.context)
t0 = time.time()
out, ttft, toks = call_llm(SYSTEM_BASE, q)
ttot = time.time() - t0
ok = score_answer(task, out)
return RunResult(
task.id, “solo”, out, ok, ttft, ttot, toks, est_cost(toks))

The solo agent provides a baseline for accuracy and cost. It is useful for well-scoped tasks but lacks the robustness improvements that other strategies offer.

Three independent prompts produce three answers. We normalize them and pick the most frequent result. The aggregated token cost reflects all three calls:

def strat_majority(task: Task, n=3) -> RunResult:
with tracer.start_as_current_span(“strategy.majority”) as sp:
answers, times, total_tokens = [], [], 0
for i in range(n):
out, ttft, toks = call_llm(SYSTEM_BASE,
f”[Specialist {i+1}]\n{task.prompt}\n\nContext:\n” + “\n”.join(task.context))
answers.append(out.strip().lower())
times.append(ttft)
total_tokens += toks
norm = [re.sub(r”\W+”, “”, a) for a in answers]
champion = max(set(norm), key=norm.count) if norm else “”
picked = answers[norm.index(champion)] if norm else “”
ok = score_answer(task, picked)
return RunResult(task.id, “majority_vote”, picked, ok,
min(times), max(times), total_tokens,
est_cost(total_tokens), notes={“alts”: answers})

Majority voting often improves reliability by leveraging the wisdom of multiple agents. The cost is approximately three times that of the baseline, so we use it when accuracy is more valuable than cost.

This strategy is similar to the majority vote, but the tie breaker chooses the response from the specialist with the highest historical weight. We pass weights into the function, such as {"A":1.0, "B":0.9, "C":0.7}:

def strat_weighted(task: Task, weights: Dict[str,float]) -> RunResult:
roles = list(weights.keys()) or [“A”,”B”,”C”]
answers, toks_total, ttft_list = [], 0, []
for r in roles:
out, ttft, toks = call_llm(SYSTEM_BASE,
f”[Specialist {r}]\n{task.prompt}\n\nContext:\n” + “\n”.join(task.context))
answers.append(out)
ttft_list.append(ttft)
toks_total += toks
best_role = max(roles, key=lambda r: weights.get(r, 1.0))
pick = answers[roles.index(best_role)]
ok = score_answer(task, pick)
return RunResult(task.id, “weighted_vote”, pick, ok,
min(ttft_list), max(ttft_list), toks_total,
est_cost(toks_total),
notes={“weights”: weights,
“roles”: roles, “alts”: answers})

Weighted voting injects prior knowledge about specialist reliability. If domain‐specific models (e.g., finance-tuned) have known strengths, weighting helps break ties appropriately.

Two proposers generate answers along with support bullets, then a judge agent selects the better one. All three calls contribute to the total token and latency budget. We enforce that the judge returns JSON with an answer field, and we fall back gracefully if parsing fails:

DEBATE_SYS = “You are debating peers. Produce crisp points. Keep citations to provided context only.”
JUDGE_SYS = “You are a strict judge. Choose the better answer based on factual support from context.”
def strat_debate(task: Task) -> RunResult:
q_ctx = “Context:\n” + “\n”.join(f”- {c}” for c in task.context) + “\n\nAnswer succinctly.”
p1, t1, k1 = call_llm(DEBATE_SYS, f”[Proposer A]\n{task.prompt}\n{q_ctx}\nProvide an answer + 2 bullets of support.”)
p2, t2, k2 = call_llm(DEBATE_SYS, f”[Proposer B]\n{task.prompt}\n{q_ctx}\nProvide an answer + 2 bullets of support.”)
judge_q = (
“Compare A vs B and PICK ONE based on factual support from the context, numeric fidelity, and clarity.\n”
“Return ONLY valid JSON as: {\”answer\”:\”<final short answer>\”}. No labels, no bullets, no prose.\n”
f”A:\n{p1}\n\nB:\n{p2}\n”
)
pick_raw, tj, kj = call_llm(JUDGE_SYS, judge_q)
try:
pick_json = json.loads(pick_raw)
pick = (pick_json.get(“answer”, “”) or “”).strip()
except Exception:
first = (pick_raw or “”).strip().splitlines()[0] if pick_raw else “”
pick = re.sub(
r”^(answer|a|b)\s*[:\-]\s*”, “”,
first, flags=re.I
).strip()
ok = score_answer(task, pick)
total_tokens = k1+k2+kj
return RunResult(task.id, “debate_then_decide”, pick, ok,
min(t1,t2), max(t1,t2)+tj, total_tokens,
est_cost(total_tokens), notes={“A”: p1, “B”: p2})

Debate encourages explanation and comparison. It costs more than voting but yields human-readable reasoning, which is useful when one must justify decisions or break ties on ambiguous questions.

This pattern iteratively improves a draft through a bounded exchange between a proposer and a critic. The critic flags blocking issues (missing citations, number mismatches, logic errors, or style violations) and the proposer revises to address them. A brevity cap prevents runaway polishing:

CRITIC_SYS = “You are a strict critic. List blocking issues using tags: [citation], [number], [logic], [style].”
PROP_SYS = (
“Revise the draft to fix the critic’s blocking issues. “
“Keep it short. Return ≤12 tokens; one sentence; no preamble. “
“Preserve all key NUMBERS and NAMED ENTITIES from the draft/context.”
)
def strat_critique(task: Task, rounds=2) -> RunResult:
draft, t_init, k_init = call_llm(SYSTEM_BASE,
f”Draft:\n{task.prompt}\n\nContext:\n” + “\n”.join(task.context))
toks_total, ttft_best = k_init, t_init
for r in range(rounds):
crit, t_c, k_c = call_llm(CRITIC_SYS,
f”Draft:\n{draft}\n\nContext bullets:\n” + “\n”.join(task.context) + “\nList blocking issues.”)
if all(tag not in crit.lower() for tag in [“[citation]”, “[number]”, “[logic]”]):
break
draft_raw, t_p, k_p = call_llm(PROP_SYS,
f”Critic says:\n{crit}\n\nRevise this draft:\n{draft}\nKeep to one sentence.”)
# Truncate to guard token budgets
words = (draft_raw or “”).strip().split()
draft = “ “.join(words[:12])
toks_total += (k_c + k_p)
ttft_best = min(ttft_best, t_c, t_p)
ok = score_answer(task, draft)
return RunResult(task.id, “critic_proposer”, draft, ok,
ttft_best, 0.0, toks_total,
est_cost(toks_total), notes={“rounds”: r+1})

Critic-proposer loops are powerful for editing and summarizing tasks. They gradually refine a draft until no blocking issues remain or the round limit is reached. The brevity cap enforces conciseness.

In an auction, several “bidders” declare their expected quality, latency, and cost. We score them using a simple objective (quality divided by cost and latency penalties) and then choose the winner to execute the task. The winning agent then runs the solo baseline:

def strat_auction(task: Task) -> RunResult:
AUCTION_BIDDERS = [
{“name”:”Local-8B”, “exp_quality”:0.82, “cost_per_1k”:0.0, “lat_ms”: 800},
{“name”:”Local-3B”, “exp_quality”:0.75, “cost_per_1k”:0.0, “lat_ms”: 500},
{“name”:”Hosted”, “exp_quality”:0.90, “cost_per_1k”:0.0005, “lat_ms”: 700},
]
bidders = [dict(b) for b in AUCTION_BIDDERS]
for b in bidders:
b[“score”] = b[“exp_quality”] / (1.0 + (b[“cost_per_1k”]*0.5) + (b[“lat_ms”]/2000.0))
winner = max(bidders, key=lambda x: x[“score”])
out, ttft, toks = call_llm(
SYSTEM_BASE,
f”[{winner[‘name’]} executes]\n{task.prompt}\n\nContext:\n” + “\n”.join(task.context))
ok = score_answer(task, out)
return RunResult(
task.id, “auction”, out, ok, ttft, ttft,
toks, est_cost(
toks, price_per_1k=winner[“cost_per_1k”]
),
notes={“bidders”: bidders, “winner”: winner}
)

Auctions allow us to formalize cost/quality trade-offs. A local model may be cheap but less accurate, while a hosted model may be more expensive and slower. The strategy is chosen based on expected quality per dollar and per second.

This strategy adds a safety layer. A builder agent first drafts an answer. A red team agent then probes the draft for prompt injections, unsafe content, or factual errors. A fixer revises the draft in strict JSON, returning final_answer and audit_notes. Finally, a policy agent approves or rejects the answer. If the policy rejects it, we fall back to the original draft:

RED_SYS = “You are a red-team agent. Probe for issues: prompt injection, unsafe content, data exfiltration, and factual errors. Output a bulleted list.”
POL_SYS = “You are a policy gate. Reject outputs with PII, unsafe instructions, or unverifiable claims without citations to the provided context.”
def strat_redteam(task: Task) -> RunResult:
draft, t0, k0 = call_llm(
SYSTEM_BASE,
f”[Builder] {task.prompt}\n\nContext:\n” + “\n”.join(task.context)
)
red, tr, kr = call_llm(
RED_SYS,
“Draft:\n” + draft + “\n\nContext bullets:\n” + “\n”.join(task.context)
)
fix_prompt = (
“Red-team found:\n{issues}\n\n”
“Revise the draft to mitigate issues. Use ONLY the provided context. “
“Return STRICT JSON as: {\”final_answer\”:\”...\”,\”audit_notes\”:[\”...\”]}. “
“Keep final_answer concise; preserve numbers/entities.”
).format(issues=red)
fix_raw, tf, kf = call_llm(PROP_SYS, fix_prompt)
try:
j = json.loads(fix_raw)
final_answer = (j.get(“final_answer”, “”) or “”).strip()
audit_notes = j.get(“audit_notes”, []) or []
except Exception:
final_answer = fix_raw.strip()
audit_notes = []
pol, tp, kp = call_llm(
POL_SYS,
“Context:\n” + “\n”.join(task.context) + f”\n\nOutput:\n{final_answer}\n” +
“Decide: APPROVE or REJECT and explain shortly.”)
approved = “approve” in (pol or “”).lower()
final = final_answer if approved else draft
ok = score_answer(task, final)
toks_total = k0 + kr + kf + kp
return RunResult(task.id, “redteam_round”, final, ok,
min(t0, tr, tf, tp), t0 + tr + tf + tp, toks_total,
est_cost(toks_total),
notes={“red_findings”: red,
“audit_notes”: audit_notes,
“policy_decision”: pol[:160]
}
)

Red team and policy gates ensure that answers comply with safety and governance standards. They are particularly valuable before releasing content for regulated domains (e.g., finance or medical questions).

A small runner iterates over the task set for each strategy. It collects RunResult objects, records telemetry spans, and summarizes accuracy, latency, token usage, and estimated cost. You can run the notebook with multiple strategies to compare their trade-offs:

plans = [
(“solo”, None),
(“majority”, None),
(“weighted”, {“A”:1.0, “B”:0.9, “C”:0.7}),
(“debate”, None),
(“critic”, None),
(“auction”, None),
(“redteam”, None),
]
all_rows = []
for name, weight_cfg in plans:
results = run_plan(TASKS, name, weights=weight_cfg)
summarize(results, name)
all_rows.extend(tabulate(results))
print(“\n=== PER-TASK RESULTS ===”)
for row in all_rows:
print(row)

The summarize function prints totals and medians, while tabulate displays per-task results with correctness flags, token counts, estimated cost, and answer previews. Because all strategies share the same scoring rubric and token counting, their outputs are comparable.

This experiment provides evidence-based guidance for selecting collaboration and competition strategies:

  • Solo is sufficient for well-scoped tasks where cost must remain minimal, and quality is acceptable
  • Majority vote offers a strong reliability boost at roughly three times the baseline cost, making it a good default for highaccuracy requirements
  • Weighted vote fine-tunes voting when some specialists are known to be more accurate
  • Debate trades additional latency and cost for transparency, making it ideal when explanations matter
  • Critic/proposer loops are effective for editorial improvements and allow budget control through round limits
  • Auctions allow cost/quality trade-offs when multiple model configurations are available
  • Red team rounds add safety checks and should be used when outputs can cause harm or violate policy

Because the notebook records OpenTelemetry spans for every call, practitioners can inspect latency and token counts at a fine level of granularity. The approach also demonstrates how to embed safety and governance into agentic workflows while keeping experiments reproducible. When moving to production, one can swap the search_ctx and cite_check tools for enterprise retrieval and evaluation, but keep the orchestration patterns and evaluation harness intact.

In this section, we bridged the theoretical foundations of collaboration and competition with an executable demonstration. The key takeaways are as follows:

  • Consistent infrastructure: A single initialization of model, provider, and telemetry supports multiple strategies without code duplication
  • Deterministic evaluation: Read-only tools and a mixed dataset enable fair, reproducible comparisons across strategies
  • Unified scoring: Canonicalization, regex matching, and citation checking provide a common rubric for measuring correctness
  • Strategy variety: We implemented seven distinct patterns: solo, majority vote, weighted vote, debate, critic/proposer, auction, and red team, each with its own cost/quality trade-offs
  • Observability: OpenTelemetry spans and token/cost estimators make budgets explicit and allow post-run analysis

These methods equip practitioners to make informed design choices about collaboration and negotiation in multi-agent systems.

In this chapter, we defined an agent as a program where the language model chooses the next step, selects and calls tools with structured arguments, observes results, and revises until explicit stop conditions are met. We then zoomed out to multi-agent design. We compared the three dominant topologies and introduced the interaction protocols and task decomposition methods.

We introduced and focused on MAF as a practical orchestration substrate. We observed and contrasted this with graph-first orchestrators such as LangGraph and positioned MAF’s “autonomy + graph” blend as a strong default for enterprise work that must be debuggable, governed, and cost-aware.

We translated design into a working blueprint: a hub-and-spoke system that turns a small document set into an executive brief with cited claims. We specified roles (coordinator, researcher, analyst, auditor, and editor), plus a shared blackboard, acceptance criteria, and control levers. We showed how those control levers make our agentic design production-ready by enabling stop rules, budgets and quotas, idempotent or retry-safe tools, exponential backoff, model escalation when justified, bypass mode, and caching. We embedded safety and governance through policy agents, allow/deny lists, sandboxes, scoped data access, and HITL approval points. Finally, we instrumented the system for observability and evaluation with per-agent spans, checkpointed state, structured claim-and-evidence JSON for offline scoring, golden tasks, spot checks, and product-grade performance metrics such as TTFT, TPOT, throughput, and cost per brief.

We closed by showing that collaboration, negotiation, and competition are levers as well. We discussed how scratchpads and mediated summaries keep work synchronized. Explicit handoff contracts convert vibes into interfaces. You now have a design playbook for agentic systems: when to escalate to agents, how to pick a topology and protocol, how to wire tools safely, and how to operate the whole thing with guardrails, telemetry, and tests. You also have a practical runtime, MAF, that maps each idea to a concrete abstraction and comes with the operational plumbing needed for real deployments.

In the next chapter, we will shift focus from coordination to control. We will examine the technical guardrails required to deploy agentic systems responsibly, including safety layers, policy enforcement, risk classification, and runtime constraints.

  1. What is an agent in this book’s framing, and how does it differ from a single prompt or chain-based pipeline?
  2. When do we prefer a simple LLM call or chain over agents, and what rule of thumb guides that choice?
  3. What are the core components of an agent loop, and what role does each play?
  4. How do hub-and-spoke, peer-to-peer, and pipeline topologies compare in terms of control and cost predictability?
  5. How do interaction protocols like turn-taking, a shared blackboard, and message bus eventing affect coordination and observability?
  6. What does the Microsoft Agent Framework (MAF) provide, and why does the chapter position it as a strong default?
  7. In the executive brief running example, what are the agent roles, and what acceptance criteria define success?
  8. Which production control levers does the chapter emphasize, and what reliability problems do they address?
  9. How does the chapter recommend instrumenting observability and evaluation for multi-agent runs?
  10. What collaboration, negotiation, and competition strategies are compared, and what trade-offs do they illustrate?

You’re not the only one navigating fragmented tools, constant updates, and unclear best practices. Join a growing community of professionals exchanging insights that don’t make it into documentation.

Join our Discord at or scan the QR code below: Follow us on Reddit at or scan the QR code below: