---
title: "Deep Research Retrieval Agent"
domain: "Research & Retrieval"
summary: "Patterns for agents that search in many rounds, read large documents on demand, and verify each claim they report."
url: "https://agentic-patterns.com/packs/deep-research-retrieval-agent"
markdown_url: "https://agentic-patterns.com/packs/deep-research-retrieval-agent.md"
pattern_count: 5
---

# Deep Research Retrieval Agent

> Patterns for agents that search in many rounds, read large documents on demand, and verify each claim they report.

**Domain:** Research & Retrieval

## How to apply this stack with a coding agent

```text
Apply the "Deep Research Retrieval Agent" pattern pack to this repository.
Check each pattern's "Use when" and "Avoid when" conditions against our codebase,
identify gaps in order of risk, and list the files to update before making edits.
```

## Patterns in this pack

1. **Agent-Driven Research** — Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report ([page](https://agentic-patterns.com/patterns/agent-driven-research) | [.md](https://agentic-patterns.com/patterns/agent-driven-research.md))
2. **Agentic Search Over Vector Embeddings** — Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively ([page](https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings) | [.md](https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings.md))
3. **Progressive Disclosure for Large Files** — Puts only file metadata in the prompt and gives the agent load, peek, and extract tools to pull file content into context on demand ([page](https://agentic-patterns.com/patterns/progressive-disclosure-large-files) | [.md](https://agentic-patterns.com/patterns/progressive-disclosure-large-files.md))
4. **Semantic Context Filtering Pattern** — Extracts only the semantic or interactive parts of raw data, such as accessibility trees or relevant fields, before sending it to the LLM ([page](https://agentic-patterns.com/patterns/semantic-context-filtering) | [.md](https://agentic-patterns.com/patterns/semantic-context-filtering.md))
5. **Output Verification Loop** — Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the result. ([page](https://agentic-patterns.com/patterns/output-verification-loop) | [.md](https://agentic-patterns.com/patterns/output-verification-loop.md))

---

## Agent-Driven Research

- URL: https://agentic-patterns.com/patterns/agent-driven-research
- Markdown: https://agentic-patterns.com/patterns/agent-driven-research.md
- Category: Orchestration & Control | Status: production

> Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report

### Use when

- Open-ended research question needs multiple search rounds
- Answer needs synthesis across many sources
- Answers need source citations or information beyond the training cutoff

### Avoid when

- A single retrieval round or internal model knowledge answers the question
- Token cost or latency budget is tight

<details>
<summary>Full pattern specification</summary>

---
title: "Agent-Driven Research"
summary: "Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report"
status: "production"
category: "Orchestration & Control"
url: "https://agentic-patterns.com/patterns/agent-driven-research"
source: "https://eu.36kr.com/en/p/3352908436796289"
authors: ["Nikola Balic (@nibzard)"]
tags: ["research","information retrieval","iterative process","autonomous search","web-search","parallel-agents","query-translation","grounding","citations"]
signals: ["Open-ended research question needs multiple search rounds","Answer needs synthesis across many sources","Answers need source citations or information beyond the training cutoff"]
anti_signals: ["A single retrieval round or internal model knowledge answers the question","Token cost or latency budget is tight"]
updated_at: "2026-11-23"
---

# Agent-Driven Research

> Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report

## Use when

- Open-ended research question needs multiple search rounds
- Answer needs synthesis across many sources
- Answers need source citations or information beyond the training cutoff

## Avoid when

- A single retrieval round or internal model knowledge answers the question
- Token cost or latency budget is tight

## Problem

Traditional research methods and static retrieval systems cannot adapt search strategy based on emerging results. Complex research tasks need multi-round investigation, cross-source synthesis, and dynamic strategy adjustment.

The same gap appears in question answering. A model with a training cutoff does not know recent facts, and simply connecting it to a search API is not enough. Something still has to:

- Decide when searching is necessary versus using internal knowledge
- Translate conversational context into effective search queries
- Find diverse, long-tail results rather than only popular pages
- Iterate and refine searches based on intermediate results
- Cite sources properly to build user trust and reduce hallucination

## Solution

Allow an AI agent to independently conduct the research process, ending only when its own criteria are met. Given a research question, the agent:

- Creates its own search queries through dynamic planning.
- Executes the searches across multiple sources.
- Examines the data and evaluates quality and relevance.
- Reflects on whether sufficient information has been gathered.
- Adjusts its search strategy based on findings and gaps.
- Repeats until satisfaction criteria or a step budget is reached.
- Synthesizes findings into a comprehensive, well-sourced report.

The key mechanism is a self-reflective iteration loop: after each search cycle, the agent evaluates results against its research goals and autonomously determines the next exploration direction. Production implementations typically combine four subsystems: planning (task decomposition), memory (context + vector store), action (tool orchestration), and reflection (quality evaluation).

**Coordinator and parallel search workers.** A common production shape splits the loop into two roles. A coordinating agent translates the question into search queries and fans out worker agents that run at the same time, then aggregates what they return:

1. **Query translation**: Extract keywords from conversational context (SERP APIs impose a 32 keyword limit) and rewrite natural language into standardized semantic expressions
2. **Operator selection**: Choose domain filters (one site, or one community), temporal filters (results from the last N months), and content-type filters
3. **Parallel fan-out**: Spawn worker agents that each search a different domain, angle, or time range, and use different query variations
4. **Deduplication and filtering**: The coordinator merges worker results, removes duplicates, and drops low-relevance snippets
5. **Reflection on gaps**: The coordinator identifies questions the findings raised but did not answer, and spawns more workers with narrower queries
6. **Cited synthesis**: Maintain a per-session index that ties each claim to its source, so the final report can cite properly

**Search depth follows need.** The source article describes three levels, analogous to autonomy levels: L1, where the model decides on its own when to search; L2, where the user explicitly triggers search; and L3, a multi-step iterative research mode for comprehensive coverage.

```mermaid
flowchart TD
    Q[Research Question] --> S{Search Needed?}
    S -->|No| K[Answer from Internal Knowledge]
    S -->|Yes| T[Query Translation & Operators]
    T --> C[Coordinating Agent]
    C --> W1[Worker: Domain A]
    C --> W2[Worker: Domain B]
    C --> W3[Worker: Time Range]
    W1 --> R[Results Aggregation & Dedup]
    W2 --> R
    W3 --> R
    R --> E{Sufficient Evidence?}
    E -->|No| F[Refine Queries for Gaps]
    F --> C
    E -->|Yes| G[Synthesize with Citations]
    G --> H[Sourced Report]
```

## How to use it

**When to implement:**

- Open-ended research requiring strategy adaptation and multi-source synthesis
- Assistants that need real-time information or factual, source-attributed answers
- Research tools that need diverse, long-tail web content

**Implementation considerations:**

- **Termination**: Define clear stopping conditions, either satisfaction-based or resource-limited, so the loop cannot run without end
- **Search API choice**: Classic SERP APIs (Google, Bing, DuckDuckGo) are optimized for humans. They curate a top-10 list rather than providing breadth, and some have deprecated advanced operators. Agent-native search APIs such as [Exa](https://exa.ai) and [Tavily](https://www.tavily.com) address this gap directly
- **Caching**: Consider a cached web index for quick retrieval, using search APIs primarily for URL discovery and then pulling content directly
- **Parallelization**: Web search is easily parallelizable; spawn multiple workers for speed
- **Search like a person**: Do not stop at the first result; check multiple sources and iterate with refined queries

**Combinations:** Pair with a reflection loop for self-correction, and with agentic RAG for document retrieval over private sources.

## Trade-offs

* **Pros:** Enables autonomous multi-round investigation; adapts strategy based on findings; produces comprehensive, well-sourced outputs; grounding in cited sources reduces hallucination; parallel workers keep latency manageable.
* **Cons:** Higher token cost; operators commonly estimate 5-10x versus single-round retrieval, though this is an estimate rather than a benchmarked figure. Increased latency from multiple LLM calls; external dependencies on search APIs; planning stability challenges; orchestration complexity adds states to debug; reliable tool calls require trained models.

## References

- Primary source: [36kr interview with Connie Fan and Danny Tarlow (Gemini team) on agentic coding and search](https://eu.36kr.com/en/p/3352908436796289) — Tarlow on how developers work in a large codebase: "You would use code search, look at the file structure, click around, read some code" and "The agentic model mimics this approach."
- [How AI web search works | Amplify Partners](https://www.amplifypartners.com/blog-posts/how-ai-web-search-works) - written by Justin Gage, published January 15, 2026; source for query translation, parallel workers, and the three search levels
- [Exa](https://exa.ai) and [Tavily](https://www.tavily.com) - agent-native search APIs that replace raw SERP integration
- [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) (Anthropic) — orchestrator and agent-loop patterns behind production research agents
- ReAct (Reasoning + Acting): Foundational pattern establishing the Thought → Action → Observation loop; Yao et al., Princeton University & Google Research, ICLR 2023, [arXiv:2210.03629](https://arxiv.org/abs/2210.03629)
- "The AI Scientist: Towards Fully Automated Open-Ended Scientific Discovery": Automated research lifecycle from idea generation to manuscript writing; Sakana AI + Oxford + UBC, arXiv:2408.06292, 2024
- "From AI for Science to Agentic Science: A Survey on Autonomous Scientific Discovery": Survey of autonomous research agents; Shanghai AI Lab, arXiv:2508.14111, 2025
- Tongyi DeepResearch: Open-source agent-driven research system; Alibaba Tongyi Lab, [arXiv:2510.24701](https://arxiv.org/abs/2510.24701), 2025; code at [Alibaba-NLP/DeepResearch](https://github.com/Alibaba-NLP/DeepResearch)
- [Retrieval-Augmented Generation (RAG) | Lewis et al., NeurIPS 2020](https://arxiv.org/abs/2005.11401)
- [Toolformer | Schick et al., NeurIPS 2023](https://arxiv.org/abs/2302.04761)

</details>

---

## Agentic Search Over Vector Embeddings

- URL: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings
- Markdown: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings.md
- Category: Tool Use & Environment | Status: emerging

> Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively

### Use when

- Codebase changes often or has local uncommitted changes
- Team has no dedicated vector infrastructure
- Security-sensitive deployment needs fewer dependencies

### Avoid when

- Codebase has millions of files
- Queries need semantic matching across different terms
- Model is not capable enough to search iteratively

<details>
<summary>Full pattern specification</summary>

---
title: "Agentic Search Over Vector Embeddings"
summary: "Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively"
status: "emerging"
category: "Tool Use & Environment"
url: "https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings"
source: "https://every.to/podcast/transcript-how-to-use-claude-code-like-the-people-who-built-it"
authors: ["Nikola Balic (@nibzard)"]
tags: ["search","vector-embeddings","bash","grep","RAG","agentic-RAG","maintenance"]
signals: ["Codebase changes often or has local uncommitted changes","Team has no dedicated vector infrastructure","Security-sensitive deployment needs fewer dependencies"]
anti_signals: ["Codebase has millions of files","Queries need semantic matching across different terms","Model is not capable enough to search iteratively"]
updated_at: "2026-01-05"
---

# Agentic Search Over Vector Embeddings

> Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively

## Use when

- Codebase changes often or has local uncommitted changes
- Team has no dedicated vector infrastructure
- Security-sensitive deployment needs fewer dependencies

## Avoid when

- Codebase has millions of files
- Queries need semantic matching across different terms
- Model is not capable enough to search iteratively

## Problem

Vector embeddings for code search require:

- Continuous re-indexing as code changes
- Handling local uncommitted changes
- Additional security surface area for enterprise deployments
- Infrastructure overhead (embedding models, vector databases)
- Stale indices when developers work on multiple branches

Traditional RAG approaches add complexity that may not be necessary with modern capable LLMs.

## Solution

Replace vector search with **agentic search** using bash, grep, file traversal, and other command-line tools. Modern LLMs are skilled enough at using search tools iteratively to achieve comparable accuracy without the maintenance burden of vector indices.

**Key approach:**

1. **Tool-based search**: Provide grep, ripgrep, find, ls, and other search utilities
2. **Iterative refinement**: Let the agent search multiple times, narrowing results
3. **No pre-indexing**: Search happens on-demand against current file state
4. **Optional MCP integration**: If teams want semantic search, expose it via MCP tool

```pseudo
# Instead of:
vector_db.index(codebase)  # requires continuous updates
results = vector_db.query(embedding(query))

# Use:
agent.call_tool("grep", pattern="function.*authenticate")
agent.call_tool("find", pattern="**/auth/*.ts")
agent.refine_search_based_on_results()
```

## How to use it

**When to use agentic search:**

- Code bases with frequent changes
- Teams without dedicated vector infrastructure
- Security-sensitive deployments (fewer external dependencies)
- Local development where files change constantly
- Multi-branch workflows

**Implementation:**

1. Provide comprehensive search tools (grep, ripgrep, find, fd, ast-grep)
2. Give agent permission to search iteratively
3. Optimize for fast tool execution rather than perfect first results
4. Let agent learn search strategies through system prompts

**Claude Code example:**

Claude Code initially used vector embeddings but switched to pure agentic search for:

- **Cleaner deployment**: No indexing step, works immediately
- **Local changes**: Always searches current file state
- **Security**: Reduced attack surface for enterprise
- **Accuracy**: Comparable results with Sonnet 4+ models

## Trade-offs

**Pros:**

- No indexing infrastructure to maintain
- Always searches current state (no stale results)
- Works with local uncommitted changes
- Simpler security model
- Faster setup for new repositories
- No embedding model costs

**Cons:**

- May require multiple search iterations (more tokens)
- Slower on very large codebases (millions of files)
- Less semantic understanding (e.g., "authentication" vs "login")
- Requires capable models (Sonnet 4+) for good results
- Higher latency for complex queries

## References

* Cat Wu (Anthropic): "We did use vector embeddings initially. They're really tricky to maintain because you have to continuously re-index... Claude is really good at agentic search. You can get to the same accuracy level with agentic search and it's just a much cleaner deployment story."
* Cat Wu: "If you do want to bring semantic search to Claude Code, you can do so via an MCP tool."
* [AI & I Podcast: How to Use Claude Code Like the People Who Built It](https://every.to/podcast/transcript-how-to-use-claude-code-like-the-people-who-built-it)

</details>

---

## Progressive Disclosure for Large Files

- URL: https://agentic-patterns.com/patterns/progressive-disclosure-large-files
- Markdown: https://agentic-patterns.com/patterns/progressive-disclosure-large-files.md
- Category: Context & Memory | Status: emerging

> Puts only file metadata in the prompt and gives the agent load, peek, and extract tools to pull file content into context on demand

### Use when

- Agent works with large PDFs, DOCX files, or images
- Files are much bigger than the relevant text they contain
- Workflows compare documents or read ticket attachments

### Avoid when

- Files are small enough to load in full
- Extra tool round-trips are not acceptable

<details>
<summary>Full pattern specification</summary>

---
title: "Progressive Disclosure for Large Files"
summary: "Puts only file metadata in the prompt and gives the agent load, peek, and extract tools to pull file content into context on demand"
status: "emerging"
category: "Context & Memory"
url: "https://agentic-patterns.com/patterns/progressive-disclosure-large-files"
source: "https://lethain.com/agents-large-files/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["progressive-disclosure","large-files","context-optimization","file-management","lazy-loading","file-handling","metadata"]
signals: ["Agent works with large PDFs, DOCX files, or images","Files are much bigger than the relevant text they contain","Workflows compare documents or read ticket attachments"]
anti_signals: ["Files are small enough to load in full","Extra tool round-trips are not acceptable"]
updated_at: "2026-10-13"
---

# Progressive Disclosure for Large Files

> Puts only file metadata in the prompt and gives the agent load, peek, and extract tools to pull file content into context on demand

## Use when

- Agent works with large PDFs, DOCX files, or images
- Files are much bigger than the relevant text they contain
- Workflows compare documents or read ticket attachments

## Avoid when

- Files are small enough to load in full
- Extra tool round-trips are not acceptable

## Problem

Large files (PDFs, DOCXs, images) overwhelm the context window when loaded naively. A 5-10MB PDF may contain only 10-20KB of relevant text/tables, but the entire file is often shoved into context, wasting tokens and degrading performance.

## Solution

Apply **progressive disclosure**: load file metadata first, then provide tools to load content on-demand.

**Core approach:**

1. **Always include file metadata** in the prompt (not full content):

   ```
   Files:
     - id: f_a1
       name: my_image.png
       size: 500,000
       preloaded: false
     - id: f_b3
       name: report.pdf
       size: 8500000
       preloaded: false
   ```

2. **Optionally preload first N KB** of appropriate mimetypes (configurable per-workflow, can be 0)

3. **Provide three file operations:**

   - `load_file(id)` - Load entire file into context
   - `peek_file(id, start, stop)` - Load a section of file
   - `extract_file(id)` - Transform PDF/DOCX/PPT into simplified text

4. **Include a `large_files` skill** explaining when/how to use these tools

```pseudo
# Agent workflow for document comparison
1. Prompt includes file metadata for report_2024.pdf and report_2025.pdf
2. Agent sees large PDFs, checks large_files skill
3. Agent calls: extract_file("report_2024.pdf")
4. Agent calls: extract_file("report_2025.pdf")
5. Agent compares extracted summaries using minimal context
```

```pseudo
# Agent workflow for image analysis
1. Prompt includes metadata for screenshot.png
2. Agent sees PNG type, calls: load_file("screenshot.png")
3. Image content is loaded, agent analyzes visual content
```

## How to use it

**Best for:**

- Document comparison workflows (multiple PDFs)
- Ticket systems with file attachments (images, PDFs)
- Data export analysis (large reports in various formats)
- Any workflow where agents need file content but files are large

**Implementation considerations:**

- File `id` should be a stable reference for tool calls
- `extract_file` should return simplified text (tables, text content)
- Consider making `extract_file` return a virtual `file_id` for very large extractions
- Preloading first N KB is optional - can give agent initial context without full load
- Cache extracted content to avoid re-processing; pick TTLs to match how often the underlying files change

**Tool design:**

```python
def load_file(file_id: str, format: str = "text") -> str:
    """Load entire file content into context window."""

def peek_file(file_id: str, offset: int, length: int, unit: str = "bytes") -> str:
    """Load a specific range from file. Unit options: bytes, lines, pages, tokens."""

def extract_file(file_id: str, extraction: str = "text") -> str:
    """Convert PDF/DOCX/PPT to simplified representation.
    Extraction options: text, structure, tables, summary."""
```

## Trade-offs

**Pros:**

- Enables working with files much larger than context window
- Agent has control over what/when to load
- Reusable across workflows via `large_files` skill
- Extracted text is typically far smaller than the original file (a multi-megabyte PDF may hold only kilobytes of relevant text)

**Cons:**

- Adds tool call overhead (multiple round-trips)
- Requires preloading heuristics (how much is enough?)
- Extraction from complex formats (DOCX) can be slow without native dependencies
- Agent may make poor loading decisions without proper guidance

**Trade-offs in preloading:**

- **Preloading**: Gives agent immediate context but reduces control
- **No preloading**: Maximum agent control but requires explicit load calls

## References

* [Building an internal agent: Progressive disclosure and handling large files](https://lethain.com/agents-large-files/) - Will Larson (2025), the practitioner source for the metadata-plus-load/peek/extract core described above
* Agent Skills use the same progressive-disclosure model for instructions: a `SKILL.md` with metadata loads up front and full instructions are read only on demand - https://code.claude.com/docs/en/skills
* Related: [Progressive Tool Discovery](progressive-tool-discovery.md) - the same lazy-loading idea applied to tool definitions rather than file contents
* Related: [Context-Minimization Pattern](context-minimization-pattern.md) - Complementary pattern for reducing context bloat
* LangChain - Document loaders with metadata-first approach ([github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain))

</details>

---

## Semantic Context Filtering Pattern

- URL: https://agentic-patterns.com/patterns/semantic-context-filtering
- Markdown: https://agentic-patterns.com/patterns/semantic-context-filtering.md
- Category: Context & Memory | Status: emerging

> Extracts only the semantic or interactive parts of raw data, such as accessibility trees or relevant fields, before sending it to the LLM

### Use when

- Raw HTML, API responses, or documents exceed context or cost budgets
- Boilerplate and noise confuse the model's reasoning
- Agent acts on elements that must map back to the original source

### Avoid when

- Source data is already compact and relevant
- Hidden or dynamic content that filters can remove is essential to the task

<details>
<summary>Full pattern specification</summary>

---
title: "Semantic Context Filtering Pattern"
summary: "Extracts only the semantic or interactive parts of raw data, such as accessibility trees or relevant fields, before sending it to the LLM"
status: "emerging"
category: "Context & Memory"
url: "https://agentic-patterns.com/patterns/semantic-context-filtering"
source: "https://github.com/hyperbrowserai/HyperAgent"
authors: ["Nikola Balic (@nibzard)"]
tags: ["context-filtering","token-optimization","semantic-extraction","noise-reduction"]
signals: ["Raw HTML, API responses, or documents exceed context or cost budgets","Boilerplate and noise confuse the model's reasoning","Agent acts on elements that must map back to the original source"]
anti_signals: ["Source data is already compact and relevant","Hidden or dynamic content that filters can remove is essential to the task"]
updated_at: "2026-10-13"
---

# Semantic Context Filtering Pattern

> Extracts only the semantic or interactive parts of raw data, such as accessibility trees or relevant fields, before sending it to the LLM

## Use when

- Raw HTML, API responses, or documents exceed context or cost budgets
- Boilerplate and noise confuse the model's reasoning
- Agent acts on elements that must map back to the original source

## Avoid when

- Source data is already compact and relevant
- Hidden or dynamic content that filters can remove is essential to the task

## Problem

Raw data sources are too verbose and noisy for effective LLM consumption. Full representations include invisible elements, implementation details, and irrelevant information that bloat context and confuse reasoning.

Research on boilerplate detection shows that a large fraction of web page content is navigation, templates, ads, and other boilerplate that carries no page-specific signal, which is why shallow text features suffice to strip it (Kohlschütter et al., WSDM 2010).

- **Token explosion**: raw data exceeds context limits or becomes prohibitively expensive
- **Poor signal-to-noise and confused reasoning**: the LLM wastes reasoning capacity on irrelevant details, which leads to hallucinations and wrong conclusions
- **Slower inference**: more tokens mean slower generation and higher costs

The issue appears in web scraping (full DOM with scripts, styles, and tracking iframes), API responses (nested metadata, internal fields, debug info), document processing (headers, footers, navigation), and code analysis (comments, whitespace, boilerplate code).

## Solution

Extract only the semantic, interactive, or relevant elements from raw data. Give the LLM a clean representation that holds what matters for reasoning.

**Core principle: do not send raw data to the LLM. Send semantic abstractions.**

Production systems use this approach: browser automation tools (Puppeteer and Playwright accessibility trees), RAG frameworks (LangChain and LlamaIndex semantic chunking), and code analysis tools (Aider's AST-based repo-map).

### Example 1: Browser accessibility tree instead of HTML

Raw HTML (10,000+ tokens), with scripts, styles, tracking pixels, and ad iframes:

```html
<html>
  <head><script src="analytics.js"></script></head>
  <body>
    <div class="tracking-pixel" style="display:none"></div>
    <iframe src="ad-server.com"></iframe>
    <nav aria-label="Navigation"><a href="/">Home</a></nav>
    <main><button id="login-button">Login</button><input type="email" name="email" placeholder="Email" /></main>
  </body>
</html>
```

The accessibility tree keeps the interactive elements and a locator for each (100-200 tokens):

```json
{
  "interactiveElements": [
    { "role": "link", "name": "Home", "xpath": "/html/body/nav/a[1]" },
    { "role": "button", "name": "Login", "id": "login-button", "xpath": "/html/body/main/button" },
    { "role": "textbox", "name": "Email", "id": "email", "xpath": "/html/body/main/input" }
  ]
}
```

```typescript
// snapshot() already filters aria-hidden, display:none, ad and tracking iframes, and non-semantic divs
const tree = await page.accessibility.snapshot({ interestingOnly: true });
```

### Example 2: API response filtering

Raw API responses include internal metadata (2,000 tokens). Filter to the semantic fields only:

```json
{
  "data": { "users": [{ "id": "123", "name": "Alice", "email": "alice@example.com",
                        "internalFlags": ["vip", "beta_tester"],
                        "metadata": { "created_at": "2024-01-01", "version": 42 } }] },
  "_internal": { "requestId": "req-abc123", "latency": 45, "cache": "HIT", "debug": [] },
  "_links": { "self": "/users", "next": "/users?page=2" }
}
```

```typescript
function filterAPIResponse(response: any, relevantFields: string[]) {
  const users = response.data.users.map((user: Record<string, unknown>) =>
    Object.fromEntries(relevantFields.filter((field) => field in user).map((field) => [field, user[field]])));
  return { users };   // About 200 tokens instead of 2,000
}
```

### Example 3: Document section extraction

Full documents add a header on every page, a legal disclaimer, a navigation menu, and repeated contact information. Keep the named content sections and strip the boilerplate. In this example the result is about 20% of the original size:

```python
BOILERPLATE = ["COMPANY CONFIDENTIAL", "Copyright", "Table of Contents", "Legal disclaimer"]

def extract_semantic_content(document: str) -> dict:
    """Keep the named content sections; drop headers, footers, navigation, and disclaimers."""
    return {name: remove_boilerplate(extract_section(document, name), BOILERPLATE)
            for name in ("EXECUTIVE SUMMARY", "ANALYSIS", "CONCLUSIONS")}
```

### Architecture

```mermaid
graph LR
    A[Raw Data Source] --> B[Semantic Filter]
    B --> D[Interactive Elements]
    B --> E[Relevant Fields]
    B --> F[Semantic Sections]
    B --> C[Clean Context]
    C --> G[LLM Processing]
    style A fill:#f99,stroke:#333
    style C fill:#9f9,stroke:#333
```

### Key benefits

Illustrative comparison for the raw-HTML example above; actual ratios depend entirely on how verbose the source representation is:

| Aspect | Raw Data | Semantic Filter |
|--------|----------|-----------------|
| Token count | 10,000+ (full DOM) | 100-1,000 (accessibility tree) |
| LLM reasoning | Confused by noise | Focused on signal |
| Cost and latency | Scales with raw size; slower with bigger context | Scales with filtered size; faster with smaller context |
| Accuracy | Prone to errors | More reliable |

## How to use it

**1. Identify the semantic elements for your domain:** interactive ARIA roles for web pages (`button`, `link`, `textbox`, `checkbox`, `radio`, `combobox`, `slider`), business fields only for API responses (`name`, `email`, `status`, `amount`), and content sections only for documents (`executive_summary`, `analysis`, `conclusions`).

**2. Build the filter layer:**

```typescript
class SemanticFilter {
  filter(data: any, domain: 'web' | 'api' | 'document'): any {
    if (domain === 'web') return this.filterAccessibilityTree(data);
    return domain === 'api' ? this.filterAPIResponse(data) : this.filterDocumentSections(data);
  }

  private filterAccessibilityTree(dom: any[]): any[] {   // Only interactive, visible, non-ad elements
    return dom.filter((el) => el.interactive && !el.isHidden && !this.isAdIframe(el))
      .map((el) => ({ role: el.role, name: el.name, xpath: el.xpath }));
  }
}
```

**3. Apply the filter before the LLM call:**

```typescript
// Wrong: send raw data
await llm.generate({ prompt: `Analyze this page: ${rawHTML}` });

// Right: filter first
const filtered = semanticFilter.filter(rawHTML, 'web');
await llm.generate({ prompt: `Analyze this page: ${JSON.stringify(filtered)}` });
```

**4. Keep a reference mapping for execution:** the filtered context uses semantic IDs (`btn-1`, "Login", "button"). The execution layer maps each one back to its original reference (`frameIndex-backendNodeId`, or an XPath such as `/html/body/main/button`) before it acts.

## Trade-offs

**Pros:**

- **Dramatic token reduction**: filtered representations are routinely an order of magnitude or more smaller than the raw source
- **Better LLM reasoning and higher reliability**: the model focuses on signal, with less confusion and hallucination
- **Lower costs and faster inference**: fewer tokens are cheaper and quicker to process

**Cons:**

- **Filter complexity**: you build and maintain filter logic that is tailored to each use case
- **Information loss**: the filter can remove elements or context that matter
- **Mapping overhead**: you track filtered-to-original references, and you version filters alongside the data schemas they read

**Failure modes / gotchas:**

- **Hidden but content-rich:** accordions, tab panels, and collapsed content can be excluded by the accessibility tree
- **Dynamic content:** AJAX-loaded content, infinite scroll, and lazy-loaded elements require wait and scroll strategies before the filter runs
- **Canvas and SVG:** charts and custom-rendered content may need OCR or a fallback to HTML
- **Over-aggressive filtering:** the filter removes an element that the task needs. Start conservative (filter obvious noise, include borderline cases), keep a filter bypass for debugging, and widen the filter if accuracy drops

**Security note:** semantic extraction can also provide security benefits. By removing untrusted content after the extraction of safe intermediate representations, agents gain resistance to prompt injection (see the Context-Minimization Pattern).

## References

- [HyperAgent GitHub Repository](https://github.com/hyperbrowserai/HyperAgent) - Accessibility-tree context with no screenshots and automatic ad-frame filtering
- [Playwright MCP](https://github.com/microsoft/playwright-mcp) - browser automation server that exposes the accessibility tree instead of raw DOM or screenshots
- Kohlschütter et al., ["Boilerplate Detection using Shallow Text Features"](https://doi.org/10.1145/1718487.1718542), WSDM 2010 - foundational research showing shallow text features detect boilerplate that carries no page-specific signal
- Beurer-Kellner et al., ["Design Patterns for Securing LLM Agents"](https://arxiv.org/abs/2506.08837), arXiv 2025 - Context-Minimization Pattern (security framework)
- [WAI-ARIA Accessibility Tree](https://www.w3.org/TR/core-aam-1.1/) - Browser accessibility API
- Related patterns: [Context Window Anxiety Management](context-window-anxiety-management.md), [Curated Code Context Window](curated-code-context-window.md)
- Distinct from [Context-Minimization Pattern](context-minimization-pattern.md): that pattern decides how much total context the agent keeps as a security and budget discipline, while this one transforms a specific raw input into its semantic elements before it reaches the context at all

</details>

---

## Output Verification Loop

- URL: https://agentic-patterns.com/patterns/output-verification-loop
- Markdown: https://agentic-patterns.com/patterns/output-verification-loop.md
- Category: Reliability & Eval | Status: emerging

> Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the result.

### Use when

- Agent output feeds into decisions or downstream agents
- Hallucination risk is non-trivial
- Compliance requires an audit trail

### Avoid when

- Output is purely creative with no factual claims
- Latency budget under 500ms

<details>
<summary>Full pattern specification</summary>

---
title: "Output Verification Loop"
summary: "Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the result."
status: "emerging"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/output-verification-loop"
source: "https://aclanthology.org/2023.emnlp-main.741/"
authors: ["John Weston (@JohnnyTarrr)"]
tags: ["verification","hallucination-detection","trust-scores","fact-checking","multi-agent"]
signals: ["Agent output feeds into decisions or downstream agents","Hallucination risk is non-trivial","Compliance requires an audit trail"]
anti_signals: ["Output is purely creative with no factual claims","Latency budget under 500ms"]
updated_at: "2026-10-13"
---

# Output Verification Loop

> Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the result.

## Use when

- Agent output feeds into decisions or downstream agents
- Hallucination risk is non-trivial
- Compliance requires an audit trail

## Avoid when

- Output is purely creative with no factual claims
- Latency budget under 500ms

## Problem

LLM agents confidently produce outputs that contain factual errors, hallucinated citations, or unsupported claims. In multi-agent pipelines the problem compounds: one agent's hallucination becomes another agent's input. Standard reflection loops catch stylistic issues but lack grounding against external evidence, so factual errors pass through unchallenged.

## Solution

Insert a verification step between generation and action. The step works in three phases:

1. **Claim extraction** -- decompose the LLM output into individual, atomic claims.
2. **Evidence retrieval** -- for each claim, retrieve supporting or contradicting evidence from authoritative sources (APIs, knowledge bases, RAG stores).
3. **Scoring** -- assign a per-claim trust score based on evidence alignment and return an aggregate confidence for the full output.

The agent (or orchestrator) uses the scores to decide whether to proceed, retry with a corrected prompt, or escalate to a human.

```pseudo
output = agent.generate(prompt)
result = verify(output, context)

if result.trust_score >= threshold:
    proceed(output)
else:
    retry_with_feedback(result.flagged_claims)
```

In multi-agent systems, run verification at each hand-off between agents so errors don't propagate through the pipeline. Verification receipts (signed, timestamped results) provide an audit trail for compliance.

## How to use it

- Place a verification call after any agent step that produces factual claims others will depend on.
- Set a trust-score threshold appropriate to the domain (higher for medical/financial, lower for exploratory research).
- In a swarm or multi-agent pipeline, verify at every agent boundary rather than only at the final output.
- Store verification receipts when you need a compliance audit trail.

### Known implementations

- [VeroQ Shield](https://github.com/veroq-ai/shield) -- claim-level verification with evidence chains, Python and TypeScript SDKs. Self-hosted Docker option for air-gapped deployments. An early-stage vendor project (a handful of commits, no releases, paid SaaS tiers from $24 to $399 per month); no affiliation between the pattern author and veroq-ai is disclosed.
- [OpenFactCheck](https://arxiv.org/abs/2405.05583) -- open-source library for the same claim-decomposition plus evidence-retrieval pipeline.

## Trade-offs

- **Pros:** Catches factual errors that reflection loops miss; provides quantified confidence rather than binary pass/fail; audit trail via receipts; composable across multi-agent pipelines.
- **Cons:** Adds latency per verification call; evidence quality bounds verification quality; requires an evidence source relevant to the domain.

## References

- [VeroQ Shield -- LLM output verification](https://github.com/veroq-ai/shield)
- [FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation](https://aclanthology.org/2023.emnlp-main.741/) (Min et al., EMNLP 2023) -- established the decomposition-into-atomic-claims plus evidence-check lineage this pattern follows
- [OpenFactCheck: Building, Benchmarking Customized Fact-Checking Systems and Evaluating the Factuality of Claims and LLMs](https://arxiv.org/abs/2405.05583) (2024) -- open-source, maintained implementation of the pipeline
- [Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651) (Madaan et al., 2023) -- related but lacks external evidence grounding
- [FacTool: Factuality Detection in Generative AI](https://arxiv.org/abs/2307.13528) -- academic approach to claim-level verification

</details>
