---
title: Deep-research agent with cited reports
url: https://gurkanozkan.ai/learn/design/applied-llm-sd-09/
markdown: https://gurkanozkan.ai/learn/design/applied-llm-sd-09.md
kind: design
role: Applied LLM
json: https://gurkanozkan.ai/api/learn/design/applied-llm-sd-09.json
---

# Deep-research agent with cited reports

Design an agent that takes a research question, searches the web and internal documents, and produces a cited multi-page report within ten minutes.

## What to cover

- **Requirements**: sources allowed; freshness; depth vs time budget; cost per report; how users judge quality; safety (untrusted web content)
- **Estimates**
- **API**
- **Data model**
- **Architecture**: planner that decomposes into sub-questions; parallel sub-agents with search/fetch tools and own context; source quality scoring and dedup; notes store with citations; synthesis/writer; citation verification; budget manager (time, tokens, tool calls); streaming progress to user; eval with expert-graded reports and claim-level citation checks
- **Deep dives**: a fetched page contains injected instructions — what happens?; How do you grade a 10-page report automatically?
- **Trade-offs**: breadth (more sub-agents) vs cost and coordination; depth of reading vs latency; single writer vs section writers
- **Evaluation**: clear budgets and stopping; context isolation; citation verification; injection handling for web content; evaluation strategy beyond vibes

## Reference design

### Requirements

**Functional**: accept a research question (with optional clarifying exchange), search the web and permitted internal documents, read sources, and deliver a structured multi-page report with inline citations to exact passages, within ten minutes, streaming progress throughout.

**Assumptions to confirm**
- **Sources allowed**: public web via a search API and our own fetcher (respecting robots and terms; no paywall circumvention); internal collections through a permission-aware search tool; user uploads.
- **Freshness**: news-sensitive questions need sources from the last few hours; every citation shows its publication and access date.
- **Depth vs time budget**: quick (~3 minutes), standard (~7 minutes), deep (hard cap 10 minutes); the agent stops at the budget and says what it did not cover.
- **Cost per report**: target ≤ $2 at standard depth.
- **How users judge quality**: correctness, coverage of the important angles, trustworthy citations, synthesis rather than a list of summaries, clear structure.
- **Safety**: web content is untrusted (prompt injection, SEO spam, misinformation); the agent only reads — it never sends messages, submits forms or writes anywhere except the report; internal data must not leak into web requests.
- **Volume**: ~10k reports/day, peaking at ~2k/hour.


### Estimates

- **Concurrency**: 2k reports/h ÷ 60 × 8 min ≈ **270 reports in flight**, × 6 sub-agents ≈ 1,600 concurrent sub-agents.
- **Tool traffic**: ~40 searches and ~60 fetches per report over ~6 minutes of research → 270 × 60 / 360 s ≈ **45 fetches/s** and ~30 searches/s at peak.
- **Tokens per report**:
  - sub-agents (cheaper model, ~$0.5/M in, $2/M out): 6 × ~130k input ≈ 800k → $0.40; 30k output → $0.06;
  - planner and writer (strong model, $3/M in, $15/M out): ~70k input → $0.21; ~8k output → $0.12;
  - citation verification (cheaper judge model): ~150 claims × 2k tokens = 300k → $0.15;
  - search API: 40 × an assumed ~$0.005 per query = $0.20.
  - **≈ $1.15 per report**, ~$11.5k/day at 10k reports.
- **Time budget (standard)**: plan 30 s → parallel research 5 min → section drafting 1.5 min → verification 1 min (overlapping drafting) → editor pass 30 s; ~1.5 min slack for slow fetches and retries → **p95 under 10 minutes**.
- **Storage**: ~60 fetched sources × ~50 KB extracted text = 3 MB per report → 30 GB/day; cached by URL and content hash for 24 hours and shared across reports.


### API

```
POST /v1/research   {question, sources: {web: true, internal: ["policies", "market-notes"]},
                     depth: "quick"|"standard"|"deep", budget: {minutes: 10, usd: 2},
                     format: "report"|"brief", clarify: true}
                    → {report_id} | {clarifying_questions: [...]}
GET  /v1/research/{id}/events      (SSE)
     plan {sub_questions[]} · subtask_started {id, query} · source_found {title, url}
     · progress {pct, eta_s} · section_drafted {title} · done {report_id}
GET  /v1/research/{id}  → {markdown, citations: [{n, url | doc_id, title, quote, published_at,
                           accessed_at}], claims: [{text, citations[], verified}], cost, coverage_notes}
POST /v1/research/{id}/feedback {rating, issues: ["wrong_fact", "bad_citation", "missing_angle"]}
POST /v1/research/{id}/cancel
```
Runs are server-side jobs: if the client disconnects, the SSE stream replays from `Last-Event-ID`, and the report is still delivered. Internal collections are searched with the caller's identity, so citations never include documents the user cannot open.


### Data model

- **Report**: id, user, question, depth, budget and spend (time, tokens, tool calls, $), status, plan, final markdown, coverage notes.
- **SubQuestion**: id, report_id, text, status, assigned agent, budget share, findings summary.
- **Source**: canonical URL or doc_id, content hash, fetched_at, published_at, domain, type (primary, news, blog, forum, internal), quality score, injection flag, extracted text pointer.
- **Note**: id, sub_question, claim text, verbatim quote with character offsets, source_id, confidence. Notes are the only channel from research to writing.
- **Section**: outline position, draft text, note ids used.
- **Claim**: sentence in the report, cited note ids, verification verdict (supported | partial | unsupported), action taken.
- **Trace**: every model call and tool call with inputs, outputs, tokens and latency.

Postgres for reports and notes; object storage for fetched pages; a shared fetch cache; ClickHouse for traces.


### Architecture

```
User ─► API ─► Orchestrator + Budget manager (wall clock, tokens, tool calls, $)
   ─► Planner (strong model): scope, sub-questions (4–8), report outline
   ─► Sub-agents in parallel (cheaper model, isolated contexts):
         search(web | internal) ─► fetch ─► extract ─► write Notes (claim + quote)
         ├─ Fetch service: sandboxed headless browser, HTML→text, strips hidden
         │  text and scripts, size caps, robots, shared cache, SSRF protection
         ├─ Source scorer: domain reputation, primary vs secondary, recency,
         │  near-duplicate removal (MinHash), syndicated-copy detection
         └─ Injection classifier on fetched text → flag / down-weight
   ─► Notes store (claims with quotes and source ids)
   ─► Gap check (planner): missing angles → spawn more subtasks if budget allows
   ─► Writer: sections drafted in parallel from notes only, inline [n]
   ─► Citation verifier: claim vs quoted span → keep / rewrite / drop
   ─► Editor pass: coherence, contradictions, executive summary, limitations
   ─► Report + bibliography; progress streamed over SSE throughout
```


### Deep dives

**A fetched page contains injected instructions.** Capability limits carry the defence: sub-agents only have read tools (search, fetch, internal search), so there is no email, form or write action to hijack. Fetched text enters context inside clear delimiters marked as untrusted, and the extraction step strips hidden text. A classifier flags injection patterns; flagged sources are down-weighted, quoted only if essential and logged. Research flows to the writer only as structured notes (claim plus verbatim quote), so imperatives in a page do not become instructions to the writer. To stop exfiltration, a sub-agent that has read internal documents loses web fetch, and fetch refuses URLs built from internal content; the fetcher blocks private IP ranges.

**Grading a 10-page report automatically.** Decompose. (1) Citation precision: extract atomic claims and check each against its cited passage with an entailment judge — target ≥ 95% supported. (2) Coverage: experts write a key-points rubric per benchmark question; a judge scores recall of key points. (3) Accuracy: questions with verifiable answers. (4) Structure and usefulness: rubric-based judge plus pairwise preference against the previous version. Calibrate every judge against ~50 expert-graded reports per release and report scores with confidence intervals.


### Trade-offs

- **Breadth (more sub-agents) vs cost and coordination**: more sub-agents cover more angles but duplicate searches and overload synthesis; start with 4–8, let the gap check spawn more only when budget remains, and dedupe sources globally.
- **Depth of reading vs latency**: skimming many pages finds breadth, reading a few primary sources fully finds substance; extract and score first, then read in full only the top sources per sub-question.
- **Single writer vs section writers**: one writer is coherent but slow and strains its context on long reports; section writers in parallel are faster but repeat and contradict each other. Use a shared outline, parallel section drafting, then one editor pass for consistency.
- **Cheaper sub-agent model vs quality**: research tasks tolerate a cheaper model; planning and writing get the strong model, and claim verification uses a cheaper judge only after it is calibrated against expert labels (on the strong model it would add ~$0.75 per report).


### Evaluation

- **Clear budgets and stopping**: per-report budget manager enforcing time, tokens and tool calls; budget-overrun rate and p95 completion time monitored; reports state what was not covered when the budget ran out.
- **Context isolation**: sub-agents with separate contexts and structured notes as the only hand-off; verified in tests by planting injected pages in a sandboxed web corpus.
- **Citation verification**: claim-level support rate, unsupported-claim rate shown to users and tracked per release.
- **Injection handling**: red-team corpus of malicious pages (hidden text, instructions in alt text, exfiltration URLs) run in CI; zero tool misuse allowed.
- **Beyond vibes**: benchmark of ~200 questions across domains with expert rubrics; per-dimension scores with CIs; pairwise preference vs incumbent; latency and cost per report.
- **Online**: ratings and issue tags, follow-up question rate, export and share rate, abandonment mid-run, citation click-through; sampled reports reviewed weekly by experts and failures added to the benchmark.


## What a strong design shows

- Has an explicit budget manager (time, tokens, tool calls, money) with graceful stopping and honest coverage notes.
- Isolates sub-agent contexts and passes only structured, quoted notes to the writer.
- Verifies citations claim by claim before the report ships.
- Defends against injection through capabilities (read-only tools, no exfiltration path), not just prompt wording.
- Evaluates with decomposed, calibrated graders (citation precision, key-point coverage, accuracy, preference) instead of overall impressions.

---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
