Search IOCombats

Search challenges, guides, questions and articles

How a Multi-Agent Research System Works: Lead Agent, Parallel Subagents and Citations
Case Study · AIDec 3, 202618 min read

How a Multi-Agent Research System Works: Lead Agent, Parallel Subagents and Citations

Follow one research question through a multi-agent system like Claude Research: how a lead agent plans and fans out parallel subagents, why each subagent returns a compressed summary instead of raw search results, and how a separate pass attaches citations before the answer reaches the browser.

By Ghazi Khan

aicase studysystem designmulti-agentai agentsvercel ai sdk

Architecture reconstructed from public sources. See Sources at the end.

Last week we looked at a single agent loop: one model, a list of tools, repeat until done. This week: what happens when one loop is not enough. The best documented example is the system behind Claude's Research feature, written up by Anthropic's engineering team. LangChain's open source Open Deep Research has a very similar shape, so I use it as the second reference point.

TL;DR

A multi-agent research system takes one open-ended question, has a lead agent plan the work, spawns several subagents that search the web in parallel, each in its own context window, then merges their findings into one report and runs a separate citation pass that ties each claim to a source. Anthropic reports that this setup beat a single Opus 4 agent by 90.2% on its internal research eval. The one design decision that makes it work: subagents return compressed summaries, not raw search results. Each subagent may read many pages, but the lead only sees a short answer per subtask, so its context stays small enough to reason about the whole picture.

What the user sees

From the browser, a deep research product behaves roughly like this:

  1. You type a broad question, for example "Which frontend frameworks added built-in AI features in 2026, and how do they compare?"
  2. The product may ask a clarifying question first (Open Deep Research does this explicitly in its scoping phase).
  3. A progress view appears. Instead of a single stream of text, you see activity: searches being run, sources being read, sometimes several threads at once.
  4. This takes minutes, not seconds.
  5. A long report streams in, with inline citations you can click to see the source.

So the frontend no longer renders one stream. It renders a tree of work that runs for minutes and ends in a cited document.

Requirements

If an interviewer asked you to design this, here is how I would frame it.

Functional

  • Accept an open-ended research question, optionally clarify scope.
  • Break it into subtasks and research them using web search (and other tools, for example MCP servers).
  • Produce a single coherent report where every factual claim links to a source.
  • Show live progress while the research runs, and let the user cancel.

Non-functional

  • Quality over latency: users accept minutes of waiting if the answer is better than what a single search gives.
  • Latency still matters: a 20-subtask question must not run serially. Parallelism is a requirement, not an optimisation.
  • Cost: Anthropic measured agents at about 4x the tokens of a chat, and multi-agent systems at about 15x. Effort must scale with the question, or simple questions burn money.
  • Context limits: no single context window can hold every page read during a large research task.
  • Reliability: a run has many steps and many tool calls. One failed search or crashed subagent must not throw away ten minutes of work.

High-level architecture

Diagram
100%
flowchart LR U["Browser"] --> API["Research API<br/>(long-running job)"] API --> L["Lead agent<br/>plan, delegate, synthesize"] L <--> MEM["Memory<br/>(saved plan)"] L -- "subtask 1" --> S1["Subagent 1"] L -- "subtask 2" --> S2["Subagent 2"] L -- "subtask 3" --> S3["Subagent 3"] S1 --> T["Tools<br/>web search, fetch, MCP"] S2 --> T S3 --> T S1 -- "compressed findings" --> L S2 -- "compressed findings" --> L S3 -- "compressed findings" --> L L -- "draft report + sources" --> C["Citation agent"] C -- "cited report" --> API API -- "progress + report stream" --> U
visualized byIOCombats

The walkthrough:

  • Research API. A request here is a job, not a quick HTTP call. It runs for minutes and pushes progress to the client. This part is my reconstruction; the sources describe the agents, not the serving layer.
  • Lead agent. Anthropic calls it the LeadResearcher. It reads the query, decides on a strategy, saves the plan to memory, creates subagents with specific tasks, reads their results and decides whether more research is needed. It is a normal agent loop whose main tool is "start a subagent".
  • Memory. An external store for the plan. Anthropic's reason is concrete: once a context goes past 200,000 tokens it gets truncated, and the lead must not lose its plan when that happens.
  • Subagents. Each one is its own agent loop with search tools and a fresh context. It searches, evaluates results, searches again and finally returns its findings. Anthropic describes them as intelligent filters.
  • Citation agent. After the lead decides it has enough, the documents and the draft report go to a separate agent that finds where citations belong and attributes each claim to a source.

In React terms, the lead is a parent and each subagent a child that fetches its own data and hands back a clean prop.

Deep dive 1: the lead agent and delegation

The lead is where most of the engineering effort went, and almost all of it is prompt design, not code.

Delegation needs a brief, not a topic. Anthropic found that short instructions like "research the semiconductor shortage" caused subagents to duplicate work or interpret the task differently. The fix was to have the lead give every subagent four things: an objective, an output format, guidance on which tools and sources to use, and clear task boundaries. It is the same as writing a good ticket for a teammate.

Effort must scale with the question. Early versions spawned 50 subagents for simple queries. The fix was to put scaling rules directly in the prompt:

Query typeSubagentsTool calls
Simple fact-finding13 to 10
Direct comparison2 to 410 to 15 each
Complex researchMore than 10Divided responsibilities

Open Deep Research made the same choice: its supervisor is prompted with heuristics on when to parallelise and when a single thread is enough, because a simple question should not take ten minutes.

Parallel at two levels. The lead starts 3 to 5 subagents at once instead of one after another, and each subagent calls 3 or more tools in parallel. Anthropic reports this cut research time by up to 90% for complex queries. In JS terms, it is the difference between awaiting in a for loop and Promise.all.

The loop decides when to stop. After each round, the lead reads the findings and either spawns more subagents for the gaps or exits. This is the agent loop from last week, with "spawn subagents" as the main tool.

Diagram
100%
flowchart TD Q["User query"] --> P["Lead: think, write plan,<br/>save to memory"] P --> D["Lead: write 1 to N subtask briefs"] D --> R["Subagents run in parallel"] R --> E{"Lead: enough<br/>information?"} E -- "no, gaps found" --> D E -- "yes" --> W["Lead: write draft report"] W --> C["Citation agent"] C --> A["Answer to user"]
visualized byIOCombats

One limitation Anthropic is open about: the lead waits for each batch of subagents to finish before moving on. It cannot steer a subagent mid-run, subagents cannot talk to each other, and one slow subagent blocks the batch. Async execution would fix that but adds hard problems with coordination, state consistency and error propagation.

Deep dive 2: subagents, context isolation and compression

Anthropic's post sums up the whole design in one line: "The essence of search is compression." A subagent might read twenty pages. The lead needs one paragraph.

Both systems enforce this explicitly:

  • Fresh context per subagent. A subagent does not inherit the lead's history. It gets its brief and nothing else. Open Deep Research goes further: a researcher only sees its own sub-topic, not the full research brief.
  • A compression step at the end. In Open Deep Research, when a researcher finishes, one more LLM call rewrites its raw tool output into a clean answer with cited sources. In LangChain's words: "We make an additional LLM call to clean sub-agent research findings." The reason is that scraped pages, failed calls and irrelevant sites would otherwise flood the supervisor's context.
  • References instead of copies. For large outputs, Anthropic suggests subagents write results to external storage and pass lightweight references back, instead of copying everything through the conversation like a game of telephone.

The cost: isolated subagents are blind to each other, so briefs must be precise. It is also why Open Deep Research does not let subagents write the report. Earlier versions wrote sections in parallel and the reports came out disjointed. The fix was multi-agent for research only, then one call that writes the report from all the findings.

The frontend analogy: a data-fetching hook can make five requests, retry and paginate, but it returns one clean shape. You would never pass raw Response objects up the tree.

Deep dive 3: the frontend, rendering a tree of agents

A chat UI renders one message stream. A research UI renders a parent stream with nested child streams, for minutes. The Vercel AI SDK has a documented pattern for exactly this, so I will use it as the reference implementation.

In AI SDK 7, a subagent is a ToolLoopAgent wrapped in a normal tool. If the tool's execute is an async generator, every yield sends a preliminary tool result to the client. Each yield replaces the previous one; it does not append. The docs stream the subagent's own UI messages through the tool:

execute: async function* ({ task }, { abortSignal }) {
  const result = await researchSubagent.stream({ prompt: task, abortSignal });
  for await (const message of readUIMessageStream({
    stream: toUIMessageStream({ stream: result.stream }),
  })) {
    yield message; // full accumulated UIMessage so far
  }
},
toModelOutput: ({ output: message }) => {
  const last = message?.parts.findLast((p) => p.type === 'text');
  return { type: 'text', value: last?.text ?? 'Task completed.' };
},

That pair is the compression idea expressed in code. The user sees every subagent step (each search, each source), because the whole nested message streams to the UI. The lead model only receives the final text, because toModelOutput strips everything else. Two audiences, two views of the same data.

On the client, each subagent is a tool part on the lead's message, with states input-streaming, input-available, output-available and output-error. A preliminary output and a final output share the output-available state, and the preliminary flag tells them apart:

const hasOutput = part.state === 'output-available';
const isStreaming = hasOutput && part.preliminary === true;
const isComplete = hasOutput && !part.preliminary;

Practical lessons for the UI:

  • Render a card per subagent, keyed by tool call id. Parallel subagents update in any order. Stable keys stop React from remounting cards as updates arrive.
  • Collapse finished work. Show the active search for running cards and a one-line summary for completed ones. Ten expanded subagents is a wall of text.
  • Wire cancel through abortSignal. The tool's execute receives the parent's abortSignal; pass it to the subagent and a Stop button cancels the whole tree. The docs note an aborted subagent leaves an incomplete tool call, and recommend convertToModelMessages(messages, { ignoreIncompleteToolCalls: true }) on the next turn.
  • Citations are data, not text. Render the report's citation markers as components linked to a source list, not as raw [1] strings. That lets you show hover previews and mark dead links.
  • Plan for reconnects. A run that lasts minutes will meet a sleeping laptop, so the stream must be resumable.

The docs also note that subagent tools cannot use approval flows, which is a good reason to keep subagents read-only.

Data flow: one request, end to end

The question: "Compare how React, Vue and Svelte handle server-side streaming in 2026."

Diagram
100%
sequenceDiagram participant B as Browser participant A as Research API participant L as Lead agent participant M as Memory participant S as Subagents (x3) participant W as Web search participant C as Citation agent B->>A: POST question A->>L: start lead loop L->>M: save plan (3 subtasks) par React L->>S: brief: React streaming S->>W: parallel searches W-->>S: results and Vue L->>S: brief: Vue streaming S->>W: parallel searches W-->>S: results and Svelte L->>S: brief: Svelte streaming S->>W: parallel searches W-->>S: results end S-->>B: preliminary progress (via API) S-->>L: three compressed summaries + source URLs L->>L: enough? yes L->>C: draft report + sources C-->>L: report with citations L-->>A: final report A-->>B: stream cited report
visualized byIOCombats

Step by step:

  1. The browser posts the question and opens a stream for progress. The server starts the lead agent.
  2. The lead thinks through the question, recognises it as a direct comparison (2 to 4 subagents by its scaling rules) and saves a three-part plan to memory.
  3. It writes three briefs, each with an objective, an output format ("bullet summary with source URLs"), suggested sources (official docs first) and a boundary ("only streaming SSR, not hydration").
  4. Three subagents start at the same time, each with an empty context and its brief.
  5. Each subagent starts with short, broad searches and narrows down, which Anthropic recommends because agents tend to write overly long, specific queries.
  6. While they work, preliminary updates flow to the browser, so the user sees three cards making progress.
  7. Each subagent ends by writing a compressed summary. Only that summary enters the lead's context.
  8. The lead reads the three summaries. If a gap appears (say, nothing on Vue's latest release), it spawns one more subagent. Here it decides it has enough.
  9. The lead writes a draft report. The draft and the collected sources go to the citation agent, which attaches a source to each claim.
  10. The cited report streams to the browser and the job ends.

Trade-offs

DecisionWhat it gives upWhy it is still worth it
Many agents instead of oneTokens: about 15x a chat, per AnthropicAnthropic's eval showed a large quality gain on research, where breadth matters
Fresh context per subagentShared knowledge between subagents; risk of duplicated workEach subagent can go deep without polluting the lead's context
Summaries instead of raw resultsDetail the lead might have wantedThe lead can reason over the whole task in one window
Synchronous batchesSpeed; one slow subagent blocks the batchMuch simpler coordination and state handling
One-shot report writingSpeed of parallel section writingCoherent reports; parallel writers produced disjointed output
Separate citation passAn extra model call and latencyAttribution is checked as its own focused task
Prompt-encoded scaling rulesPredictability compared with hard-coded limitsSimple questions stay cheap without a separate router

Anthropic also says when not to do this: tasks where agents need shared context or depend heavily on each other. Most coding tasks fall here, since they have fewer parallel parts than research.

Confirmed vs inferred

Confirmed by sources

  • The orchestrator-worker design: a lead agent, parallel subagents with their own context windows, a memory store for the plan and a citation agent at the end.
  • The seven-step request flow, including the lead deciding whether to run another round.
  • The 90.2% result (Opus 4 lead with Sonnet 4 subagents, versus single-agent Opus 4, internal eval), token usage explaining 80% of BrowseComp variance, the 4x and 15x token figures, up to 90% faster research with parallelism, 3 to 5 parallel subagents and 3 or more parallel tool calls.
  • The scaling rules, the 50-subagent failure, the four-part delegation brief and the 200,000 token truncation reason for memory.
  • Synchronous batches and their limits; resuming from the failure point; rainbow deployments; storing large outputs externally and passing references.
  • Open Deep Research: scope, research and write phases; supervisor with isolated sub-agents; the compression call; one-shot writing after disjointed parallel sections.
  • AI SDK 7: ToolLoopAgent, subagents as tools, async generator preliminary results, toModelOutput, abortSignal passthrough, fresh context per invocation, no approval flows in subagent tools.

Inferred or reconstructed

  • The Research API as a long-running job with a progress stream. The sources describe the agents, not the serving layer or transport.
  • How Claude's own Research UI renders progress. The "What the user sees" section describes deep research products in general.
  • That subagents send their source URLs to the lead along with the summary, and that the citation agent gets the pages the subagents read.
  • The Memory store's implementation and the tool the lead uses to spawn subagents: not published.
  • The model versions in Claude Research today. Anthropic's figures are from June 2025 (Opus 4 and Sonnet 4) and have likely changed.
  • The latency of a typical run: [N], not published.

Build a mini version in JS/TS

The smallest version: a researcher subagent with web search, a delegate tool that runs several of them in parallel, a lead agent and a citation pass. It uses AI SDK 7, zod and the Vercel AI Gateway, whose built-in perplexitySearch tool works with any model routed through the gateway. If you want the bigger picture of when to use the AI SDK versus Mastra or LangGraph.js, this week's post on choosing a TypeScript agent framework covers it.

First, the researcher. Note the instructions ask for a compressed summary, because that summary is all the lead will see:

// researcher.ts
import { ToolLoopAgent, gateway, isStepCount } from 'ai';

export const MODEL = 'anthropic/claude-sonnet-5.5';

export const researcher = new ToolLoopAgent({
  model: MODEL,
  instructions: [
    'You are a research subagent. Research only the task you are given.',
    'Start with short, broad searches, then narrow down.',
    'Prefer official docs and engineering blogs over SEO content.',
    'Finish with a summary under 200 words: key findings as bullets,',
    'each bullet ending with the source URL in brackets.',
  ].join('\n'),
  tools: {
    search: gateway.tools.perplexitySearch({ maxResults: 5 }),
  },
  stopWhen: isStepCount(8), // guardrail: no runaway subagents
});

Next, the delegation tool. The lead calls it once with a list of briefs and Promise.all runs the subagents in parallel. The max(5) cap is the code version of Anthropic's "do not spawn 50 subagents" lesson:

// delegate.ts
import { tool } from 'ai';
import { z } from 'zod';
import { researcher } from './researcher';

const Brief = z.object({
  objective: z.string().describe('What to find out, in one sentence'),
  boundaries: z.string().describe('What is out of scope'),
});

export const delegate = tool({
  description: 'Run 1 to 5 research subagents in parallel, one per brief.',
  inputSchema: z.object({ briefs: z.array(Brief).min(1).max(5) }),
  execute: async ({ briefs }, { abortSignal }) => {
    const results = await Promise.all(
      briefs.map(async (b, i) => {
        try {
          const prompt = `Objective: ${b.objective}\nOut of scope: ${b.boundaries}`;
          const r = await researcher.generate({ prompt, abortSignal });
          return `## Subtask ${i + 1}: ${b.objective}\n${r.text}`;
        } catch (err) {
          // One failed subagent should not sink the whole run
          return `## Subtask ${i + 1}: failed (${String(err)})`;
        }
      }),
    );
    return results.join('\n\n');
  },
});

The lead agent and the citation pass. The lead plans, delegates, checks for gaps and writes a draft. A second, tool-free agent then fixes attribution:

// research.ts
import { ToolLoopAgent, isStepCount } from 'ai';
import { delegate } from './delegate';
import { MODEL } from './researcher';

const lead = new ToolLoopAgent({
  model: MODEL,
  instructions: [
    'You lead a research team. Plan first, then call delegate.',
    'Simple facts: 1 brief. Comparisons: 2 to 4 briefs.',
    'If findings have gaps, call delegate again for the gaps only.',
    'Then write a structured draft report using only the findings.',
  ].join('\n'),
  tools: { delegate },
  stopWhen: isStepCount(6),
});

const citer = new ToolLoopAgent({
  model: MODEL,
  instructions:
    'Add numbered citations [n] to each factual claim using only the URLs ' +
    'in the findings. Remove claims with no source. End with a Sources list.',
});

export async function research(question: string) {
  const draft = await lead.generate({ prompt: question });
  const findings = draft.steps
    .flatMap((s) => s.toolResults)
    .map((r) => String(r.output))
    .join('\n\n');
  const cited = await citer.generate({
    prompt: `Findings:\n${findings}\n\nDraft report:\n${draft.text}`,
  });
  return cited.text;
}

console.log(await research(process.argv.slice(2).join(' ')));

Run it in an ESM project with AI_GATEWAY_API_KEY in .env.local: node --env-file=.env.local --import tsx research.ts "compare streaming SSR in React, Vue and Svelte". Next steps: the async generator form from deep dive 3 for a live useChat UI, and a KV store for the lead's plan.

Interview angle

If the frontend system design round says "design a deep research feature", here is the order I would answer in:

  1. Clarify scope. How long can a run take? Which sources (web, internal docs, MCP tools)? Is there a cost cap per question? Must every claim be cited?
  2. Justify multi-agent before drawing it. Research is broad and parallel, and the reading does not fit one context window. Say out loud that it costs many times the tokens of a chat, and that you would route simple questions to a single agent.
  3. Draw the orchestrator-worker shape. Lead agent with memory, parallel subagents with fresh contexts, a compression step on each subagent's output, a citation pass at the end.
  4. Define the contracts. The subagent brief (objective, output format, sources, boundaries) and the subagent result (short summary plus source URLs). These two shapes are the API between agents.
  5. Design the client. A long-running job with a progress stream, one card per subagent keyed by tool call id, preliminary vs final states, cancel through AbortController, reconnect after refresh, citations as components.
  6. Cover failure and cost. Per-subagent step limits, a cap on subagent count, one failed subagent returns an error result instead of failing the run, checkpoints so a crash resumes instead of restarting.
  7. Close with evaluation. Start with around 20 real queries, score outputs with an LLM judge on accuracy, citation accuracy, completeness and source quality, and keep humans in the loop to catch problems like agents preferring SEO content farms.

Sources

Advertisement