Design: deep research agent

In one sentence

An async job clarifies and plans, fans out sub-agents with search and fetch in clean contexts, writes one cited report from their compressed findings, and verifies every citation, under token, time and dollar budgets.

The lead only ever sees compressed findings; raw pages live in the page store, where the citation verifier reads them back.

How it works

  • Scale: ~100k reports/day of ~5–20 min each means ~700 jobs in flight, each under a hard budget.
  • Sub-agents compress ~50k tokens of reading into ~1–2k of findings, so the lead's context stays small.
  • Run each report as a durable workflow with checkpoints, so a crash resumes instead of re-spending dollars.
  • The worst failure is a polished report with a wrong citation: cite passage ids, never URLs from memory.
  • Start evals with ~20 real queries and one LLM judge scoring factual and citation accuracy.

Check yourself

Answer to mark it learned; your answers aren't scored.

Each research report runs as one long HTTP request on a worker. After every deploy, in-flight reports die around minute 12, and the client's retry starts from zero, paying for every token again. What do you change?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: take an open-ended question (a market scan, a vendor comparison, a literature review), ask up to ~3 clarifying questions, research the public web (optionally internal docs through connectors) and return a 2–5k-word report in which every factual claim cites a source. Users watch progress live, can close the tab and come back, and can cancel. Non-functional: ~5–20 min per report, a hard budget per report (tokens, minutes, dollars), survive worker crashes and deploys without starting over, ~100k reports/day, and no data leaving through injected pages.

Questions I'd ask:

  1. What is a report worth: a consumer chat feature or an analyst seat? That sets the dollar budget.
  2. Public web only, or also the user's Drive, email or Slack? That changes the security model.
  3. Is 10–20 minutes acceptable if progress is visible?
  4. Which sources are preferred or banned: papers, filings, paywalls, forums?
  5. Output: prose only, or tables, charts and exports?

The highest-cost failure is a polished report with a wrong citation: it looks verified, so nobody checks it before it reaches a VP. With private connectors, a close second is an injected page that exfiltrates data.

High-level design

The request becomes a job in a durable workflow (Durable execution for agents), never a long HTTP call; the client gets a job id and an SSE progress stream. Scope: a small model asks the clarifying questions and writes a research brief. Plan: a lead agent on a strong reasoning model splits the brief into sub-questions and sizes the effort: one agent for a fact, 2–4 for a comparison, 10+ for broad research. Research: the lead (Pattern: orchestrator–workers) spawns sub-agents in parallel, each with a written brief, a clean context and web_search / fetch_page tools; each runs a ReAct: the agent loop loop of ~5–15 calls and compresses ~50k tokens of reading into ~1–2k tokens of findings with source ids. Raw pages stay in a page store, out of the lead's context (Context engineering). The lead reads the findings, spawns a second round for gaps, and stops at saturation or budget. Write: one synthesis pass drafts the report from the brief and findings. Verify: a checker tests each claim against its cited passage; unsupported claims are re-sourced, dropped or flagged. Every step checkpoints, so a crash resumes from the last finished step.

Code Orchestrator loop with budgets and checkpoints
pythonOrchestrator loop with budgets and checkpoints
import asyncio

BUDGET = Budget(usd=5.00, seconds=20 * 60, max_subagents=12)  # per report, set by tier

async def research(job: Job) -> Report:
    st = job.state  # durable: reloaded after a crash or a deploy
    st.brief = st.brief or await write_brief(job.question, job.clarifications)  # small model
    while not job.meter.near_limit(BUDGET, frac=0.8):  # code enforces budgets, not the prompt
        tasks = await lead_plan(st.brief, st.findings, max_new=4)  # gaps -> sub-questions
        if not tasks:  # saturation: nothing left worth reading
            break
        results = await asyncio.gather(
            *(run_subagent(t, tools=[web_search, fetch_page], max_calls=15) for t in tasks),
            return_exceptions=True,  # one failed branch must not kill the job
        )
        # Findings are ~1-2k tokens with passage ids; raw pages stay in the page store
        st.findings += [r for r in results if not isinstance(r, BaseException)]
        await job.checkpoint()  # step boundary: resume from here
        job.emit("progress", sources=st.n_sources(), spent_usd=job.meter.usd)
    draft = await synthesize(st.brief, st.findings)  # one pass keeps the report coherent
    report = await verify_citations(draft, page_store)  # re-source, drop or flag unsupported claims
    await job.checkpoint(report=report)
    return report
Real example

A product lead asks: "Compare managed vector databases for a 1B-vector, multi-tenant workload on AWS." The clarifier asks two questions (budget? latency target?) and writes a brief. The lead plans 4 sub-questions (scale limits, tenant isolation, pricing at 1B vectors, outage history) and spawns 4 sub-agents. Each runs ~12 tool calls, reads ~50k tokens and returns ~1.5k tokens of findings with 6–10 sources. Round two fills one gap (pricing tiers) with one more sub-agent. Synthesis reads ~12k tokens and writes 3,000 words with 41 citations. The verifier rejects 3: two are re-pointed to the right passage, one claim is dropped. Elapsed: ~11 min; spend: ~1.2M tokens, ~$2.40 at assumed prices, under a $5 budget.

Trade-offs +4 · −4

+ You gain

  • Parallel sub-agents cut wall-clock time (Anthropic: up to 90% on complex queries) and keep each context focused.
  • A durable, checkpointed job survives crashes and deploys; users leave and come back without losing work or money.
  • Compress-then-synthesize keeps the writer's context small however many pages were read.
  • Citation verification makes every claim checkable, which is the product's whole value.

− You pay

  • Token-hungry: multi-agent runs used ~15× chat tokens at Anthropic; a report costs dollars, not cents.
  • Compression loses nuance: the writer only sees what each sub-agent chose to keep.
  • Long, non-deterministic traces are hard to debug and eval; one bad brief poisons a whole branch.
  • Every fetched page is untrusted input to an agent that holds tools.

Use it when

Open-ended questions that need breadth (many sources, comparisons, market or literature reviews) where minutes of latency and dollars per answer are fine for a report a person would spend hours on.

Avoid it when

Single-fact or single-hop questions (Design: AI answer engine (search + LLM) replies in ~2 s for about a cent), tightly coupled write-heavy work such as coding, or anything that must answer in seconds.

Numbers to know 5
  • Tokens per report (assumed): 5 sub-agents × ~12 turns × ~17k tokens of context re-read per turn ≈ 1M in; with lead, synthesis and checks ≈ 1.2M in, ~60k out.
  • Cost at an assumed $3/$15 per M (Nov 2026), plus ~60 searches at an assumed $5/1k: ~$4.80 uncached, ~$2.50 with ~70% of input as cache reads at ~10% price. At 100k reports/day: ~$250k/day.
  • Concurrency (Little's law): 100k reports/day ≈ 1.2 starts/s × ~600 s each ≈ 700 jobs in flight, ~1.4k at a 2× peak, each with up to ~5 live agent loops.
  • Wall clock: plan ~30 s + 2 research rounds × ~3 min + synthesis ~2 min + verification ~1 min ≈ 9–10 min, plus the user's time answering clarifications.
  • Anthropic (Jun 2025): multi-agent research used ~15× the tokens of chat; token usage alone explained ~80% of performance variance on BrowseComp.
Common pitfalls 4
  • Fan-out without limits: dozens of sub-agents for a one-fact question. Encode effort scaling in the lead's prompt and cap sub-agents and tool calls in code.
  • Passing raw pages up to the lead: its context fills and rots, and cost grows with every turn. Return compressed findings with source ids; keep pages in the store.
  • Citing from memory: the writer attaches a plausible URL to a claim it learned in pretraining. Cite only passage ids from the store, and verify support.
  • Treating the job as a request: a 15-minute HTTP call dies at the load balancer timeout or the next deploy, and the retry spends the money again.
Interview questions 3

Answer out loud first, then reveal.

A report cites a page that doesn't say what the report claims. How do you fix that class of bug?Show answer

I'd fix it at generation and at verification. At generation, the writer can only cite passage ids from the page store, never URLs, so a citation can't come from the model's memory, and each finding carries the exact quote it relied on. At verification, a cheap model checks every claim–passage pair for support; failures get one repair round, re-pointing to another passage or dropping the claim, and anything still doubtful is flagged in the report instead of shipped silently. Then I measure it: citation precision on a labeled set in CI, plus human review of ~1% of production reports, because judges miss subtle misreadings like a figure taken from the wrong year.

How do you keep a single report from costing $50?Show answer

Budgets live in the orchestrator, not the prompt. Each job gets a token, time and dollar budget by tier, each sub-agent a cap on tool calls and tokens, and the lead can ask for more but code decides. At ~80% of budget the lead stops spawning and synthesizes, so the user gets a report that states its gaps, not a timeout. The cheaper levers come first: effort scaling so a simple question runs one agent, prompt caching on agent loops where re-read input dominates, and small models for compression and checks. I alert on p99 cost per report, because runaway loops hide in the tail, not the average.

The agent reads arbitrary web pages. What changes if it can also read the user's email and Drive?Show answer

Then it has the lethal trifecta: private data, untrusted content and an exfiltration channel, and a fetch tool is a channel because the URL itself can carry data. ShadowLeak showed exactly this against ChatGPT's Deep Research with a Gmail connector in 2025. I'd split capabilities: sub-agents that read the web never see private data, and agents holding private data can only fetch URLs returned verbatim by search, through an egress proxy that logs and rate-limits. Hidden text is stripped before any model reads a page. I'd still red-team it continuously, because no prompt-level filter is reliable; the guarantee has to come from the architecture.

Deep dive 5

Orchestration and context isolation

Each sub-agent brief states an objective, an output format, the tools to use and what is out of scope; vague briefs make agents duplicate each other. Encode effort scaling in the lead's prompt and in code: Anthropic's early lead agents spawned 50 sub-agents for simple queries, and its system now spins up 3–5 in parallel. Sub-agents return compressed findings (claims, quotes, source ids), not pages; raw text stays in the page store, reachable by reference, so the lead's context stays near ~20–30k tokens however much was read. Write the report in one pass: LangChain's Open Deep Research first wrote sections in parallel and got disjointed reports. Put a strong model on the lead and synthesis, a cheaper one on sub-agents, and a small one on compression and checks (Model routing & cascades).

Long-running job: queue, checkpoints, progress

Run the job on a durable workflow engine such as Temporal: each LLM call, search and fetch is an activity with retries and an idempotency key, and plan, findings and spend are persisted after every step. A worker crash or a deploy resumes from the last checkpoint instead of re-spending dollars. Google describes Gemini Deep Research the same way: an asynchronous task manager keeps shared state between planner and task models, so one failure doesn't restart the task. Version the workflow code so in-flight jobs finish on the old version (Anthropic uses rainbow deployments). Progress is an append-only event log streamed over SSE; the client reconnects with the last event id, and a push or email fires when the report is ready. Cancellation is a signal checked between steps.

Budgets and stopping

Three budgets per job, set by tier: tokens, wall-clock and dollars. They live in the orchestrator, not the prompt: the model can ask for more, code decides. Each sub-agent also gets a cap on tool calls (~15) and tokens. The meter updates as calls finish; at ~80% of budget the lead stops spawning and moves to synthesis, so the user gets a report that names its gaps instead of a timeout. Stop earlier on saturation: a round whose findings add no new claims or sources. Agent loops re-read their whole context every turn, so input tokens dominate cost: Prompt caching on the stable prefix and trimming old tool results are the biggest levers. Alert on p99 cost per report; runaways hide in the tail.

Untrusted pages: injection and source quality

Every fetched page is attacker-controlled input to an agent with tools (Prompt injection (direct & indirect)). Add private connectors and you have the The lethal trifecta: in ShadowLeak (Radware, Sep 2025), hidden text in an email made ChatGPT's Deep Research agent send Gmail data to an attacker's URL. Strip hidden text and scripts, wrap page content as data, keep web-reading sub-agents away from private data, let agents that hold private data fetch only URLs returned verbatim by search, and send all egress through a logging proxy. On quality, Anthropic's human testers caught agents preferring SEO content farms over academic PDFs. Add per-domain authority priors, prefer primary sources (papers, filings, official docs), collapse syndicated copies to the original, and flag claims backed by a single weak source.

Citations and evaluation

Citations point to passage ids in the page store, never to URLs the model writes from memory. Anthropic runs a separate CitationAgent pass to attach sources to claims; I'd also score each claim–passage pair for support, give failures one repair round, then drop or flag them (Citations & grounding). Start evaluation small: Anthropic began with ~20 real queries and one LLM judge scoring factual accuracy, citation accuracy, completeness, source quality and tool efficiency (0.0–1.0 plus pass/fail). Add human review for what judges miss, external checks such as BrowseComp (1,266 hard-to-find facts) and DeepResearch Bench (100 PhD-level tasks, 22 fields), and trace metrics: wasted searches, duplicate sub-agents, budget-hit rate (Evaluating agents). Online: completion, saves, shares and follow-up questions.