---
title: "Context Engineering for Search Agents: Fit Web Results in Context"
description: "Raw web pages are 50,000 to 83,000 tokens. We measured five real pages, compared four HTML-to-markdown approaches, and lay out the layering, budgets and notes that keep search agents fast and accurate."
category: "guides"
url: https://keirolabs.cloud/blog/context-engineering-web-search-agents
published: 2026-11-24
updated: 2026-11-24
---

# Context engineering for web search agents: keep results from eating the context window

## The 60-second version

**Context engineering is deciding what goes into a model's context window, in what form and in what order, on every call.** For an agent with web search, the biggest variable is the search results. Raw web pages are enormous, and an agent that pastes them in runs out of room, slows down and gets worse at answering.

We measured five real pages with a standard tokenizer (OpenAI's `o200k_base`):

| Page | Raw HTML | Whole page as markdown | Main content only |
|---|---|---|---|
| Wikipedia: Retrieval-augmented generation | 82,615 tokens | 22,845 | **7,817** |
| GitHub changelog (a listing page) | 74,860 | 6,660 | **432** |
| MDN: HTTP 429 reference | 56,687 | 13,718 | **561** |
| Python docs: asyncio tasks | 50,050 | 15,710 | **12,546** |
| Hacker News front page | 11,634 | 3,819 | **1,329** |

**One raw page can fill a small model's whole window.** Converting to markdown cuts it by two-thirds to 90%, and keeping only the main content cuts it by 75% to 99%. A search result with title, URL and snippet is about 65 tokens.

**The rules that follow from this:**

- Show the model snippets first.
- Fetch full pages only on purpose, as clean main content.
- Cap every tool result.
- Keep a running set of notes instead of the whole transcript.

## Why does context size matter if models have huge windows?

**Because a big window is not free and not perfectly used.**

- **Cost:** every token in the context is billed again on every call in the loop. An agent that carries 60,000 tokens of pages through 8 steps pays for 480,000 input tokens.
- **Speed:** time to first token grows with input length.
- **Quality:** buried facts are easier to miss. Ten pages of navigation menus, cookie banners and footers dilute the three sentences that answer the question.
- **Room to work:** small and local models often have 8k to 32k tokens. Two raw pages and they are full.

**So the question is not "will it fit?"** It is "is every token here helping the next decision?"

## How should search results enter the context?

**In layers, from cheapest to most expensive, each one only when the previous layer isn't enough.**

| Layer | Size | What the model does with it |
|---|---|---|
| 1. Search results: title, URL, snippet | ~65 tokens each, ~650 for 10 | Decides which pages are worth reading |
| 2. Main content of chosen pages | Hundreds to ~12k tokens each | Reads the details |
| 3. Notes: extracted facts with source URLs | ~50-200 tokens per fact | Carries forward between steps |
| 4. Final answer context: notes plus quotes | As small as possible | Writes the cited answer |

**The common mistake is jumping straight to layer 2 for all 10 results.** At the main-content sizes in the table above, ten pages come to roughly 20,000 to 50,000 tokens for a single search. Let the model pick 2 or 3 pages from the snippets instead. Our [agentic search guide](/blog/agentic-search) has a loop built that way.

## How do I turn a web page into LLM-friendly text?

**Strip it to the main content, then convert to markdown.** Markdown keeps headings, lists, tables and code blocks, which the model uses to understand structure, at a fraction of the size of HTML.

**What we found testing four common Python approaches on the pages above:**

| Approach | Strength | Weakness we saw |
|---|---|---|
| `BeautifulSoup.get_text()` | Small output | Loses all structure: headings, tables and code become flat lines |
| `markdownify` / `html2text` on the whole page | Keeps structure | Keeps the menus, sidebars and footers too: 3.8k to 22.8k tokens |
| `readability` + `markdownify` | Good on articles | **Failed on listing pages**: 0 tokens from Hacker News, 28 from the GitHub changelog. On MDN it kept the examples but dropped the definition at the top |
| `trafilatura` (markdown output) | Best balance in our test: kept the MDN definition, the docs' code and the list pages | Keeps relative links (`/en-US/docs/...`) and Wikipedia's citation markers, which you may want to strip |

```python
import trafilatura, requests

html = requests.get(url, timeout=30, headers={"User-Agent": "Mozilla/5.0"}).text
md = trafilatura.extract(html, output_format="markdown", include_links=True, include_tables=True)
```

**Two things a converter can't fix:**

- **JavaScript-rendered pages.** A plain HTTP request gets an empty shell, so you need a headless browser first.
- **Sites that block bots.** These return a challenge page instead of content.

**That is what extraction APIs handle.** Keirolabs `/extract` returns clean markdown for a URL at 2 credits a page. `/search/content` returns search results with page text already cleaned. Both are ours. Comparisons with other tools are in [search API vs scraping API for LLMs](/blog/search-api-vs-scraping-api-for-llms).

## How do I stop tool results from eating the context window?

**Enforce budgets in code, at the tool boundary.** The model can't be trusted to ask for less.

```python
MAX_RESULT_TOKENS = 4000          # per tool call
CHARS_PER_TOKEN = 4               # rough rule for English text

def fit(text: str, max_tokens: int = MAX_RESULT_TOKENS) -> str:
    limit = max_tokens * CHARS_PER_TOKEN
    if len(text) <= limit:
        return text
    head = text[: int(limit * 0.8)]
    return head + f"\n\n[truncated: {len(text) - len(head):,} more characters. Call read_page with a section name for more.]"
```

**Five techniques, in the order to add them:**

1. **Cap each tool result.** Say how much was cut, so the model knows to ask for more if it needs it.
2. **Return compact text, not raw JSON.** `[1] Title\nURL\nsnippet` came to 48 tokens in our test, against 99 for the same result as pretty-printed JSON with metadata fields.
3. **Drop the boilerplate.** Remove navigation, footers, cookie banners, citation markers and image tags before the text reaches the model.
4. **Replace pages with notes.** After the model reads a page, ask it for the 3 to 5 facts it needs, with the source URL. Keep the facts and drop the page from later calls.
5. **Clear old tool results.** Once a search's useful facts are in the notes, the raw results can go. Some APIs do this server-side. Anthropic's context editing, for example, can clear old tool results automatically.

## What should the notes look like?

**Short, sourced and structured,** so the final answer can cite them and you can check them:

```json
[
  {"fact": "Free plan: 1,000 credits a month, no card", "source": "https://example.com/pricing", "checked": "2026-11-24"},
  {"fact": "Rate limit on the free plan: 10 requests a minute", "source": "https://example.com/docs/limits", "checked": "2026-11-24"}
]
```

**Ten facts like these are about 450 tokens.** The pages they came from may have been 20,000. Every later step in the loop reads the 450.

**Keep exact values exact.** Copy prices, versions, dates and names verbatim into the notes. Paraphrasing at this stage is where numbers quietly change. The [grounding guide](/blog/grounding-ai-agents-web-search) shows how to check the final answer's citations against the notes.

## What order should the context be in?

**Stable content first, changing content last.** This matters for prompt caching: many model APIs cache an identical prefix and bill it at a fraction of the price on later calls.

1. **System prompt and tool definitions.** These never change, so put them first.
2. **Task instructions and today's date.** These change once a day.
3. **Notes so far.** These grow by appending.
4. **The newest tool results.** These change every step.
5. **The current question or next instruction.**

Put a timestamp or request ID at the top and every call misses the cache. Put the date in step 2, not in the system prompt's first line.

## Context engineering checklist for search agents

- **Show snippets first, about 65 tokens each, and let the model choose pages.**
- **Fetch main content, not raw HTML.** Expect a 75% to 99% reduction.
- **Cap every tool result in code, and say when it was cut.**
- **Return compact text instead of JSON.**
- **Turn pages into sourced notes, and drop the pages.**
- **Keep the prompt prefix stable so it caches.**
- **Measure tokens per step.** If one step is 10 times the others, that is where to cut.

Keirolabs gives agents both layers on one key: `/search/lite` for compact results ($0.03 to $0.10 per 1,000 on plans), and `/extract` or `/search/content` for clean page text. New accounts get up to 2,000 free credits ([get a key](https://platform.keirolabs.cloud/register)).
