---
title: "Agentic Search & Agentic RAG: How AI Agents Search the Web"
description: "How agentic search works (plan, search, select, read, reflect), what 163 logged answers from OpenAI models reveal about how they search, and a complete Python loop with budgets and stopping rules."
category: "guides"
url: https://keirolabs.cloud/blog/agentic-search
published: 2026-11-24
updated: 2026-11-24
---

# Agentic search and agentic RAG: how AI agents search the web

## The 60-second version

**Agentic search is when an AI model runs the search itself, in a loop.** It decides what to search, reads the results, notices what is still missing, searches again, and stops when it has enough. **Agentic RAG** is the same loop applied to retrieval-augmented generation: the model chooses its own queries instead of getting one fixed retrieval step.

| | Classic RAG | Agentic search |
|---|---|---|
| Queries | One, usually the user's question as typed | Several, written by the model |
| Who decides what to read | The retriever's top-k | The model, after reading snippets |
| Follow-up searches | None | As many as the budget allows |
| Good at | Simple lookups over known documents | Comparisons, research, multi-part questions |
| Cost and latency | Low and predictable | Higher; needs a budget |

The loop has five steps: **plan, search, select, read, reflect.** Most of the engineering is deciding when the loop should stop.

## What does a search agent actually do?

**It repeats a small loop until it can answer.**

1. **Plan.** Break the question into the sub-questions it needs. "Is Postgres or MongoDB cheaper on AWS for 2 TB?" needs one search per database, plus storage prices, plus the current year.
2. **Search.** Send several queries at once.
3. **Select.** Read the titles and snippets, drop duplicates and junk, and pick the few pages worth opening.
4. **Read.** Fetch those pages' full text.
5. **Reflect.** Ask: can I answer every sub-question now, with a source for each? If not, write new queries for the gaps and go back to step 2.

**The difference from plain RAG is step 5.** A classic RAG pipeline retrieves once and answers with whatever it got. An agent notices that it found MongoDB's price but not Postgres's, and goes back for it.

## How do ChatGPT-style models search today?

**More simply than you might expect.** We logged 163 answers from three OpenAI models (gpt-4.1, gpt-4.1-mini and gpt-4o-mini) with web search turned on, between November 16 and 24, 2026, across 13 product questions run several times each.

| What we measured | Result |
|---|---|
| Search queries per answer | **Exactly 1, in all 163 answers** |
| Results retrieved per answer | 13.2 on average (gpt-4.1: 6.3; the mini models: 16 to 17) |
| Results cited per answer | 7.2 on average |
| Median rank of a cited result | 8th |
| Citations from the top 3 results | 28% |
| Citations from below rank 10 | 43% |
| Queries with a stale year added | 16 of 163 (10%), e.g. "…2024" asked in November 2026 |

**Three lessons for building your own agent:**

- **One rewritten query is the baseline, not the ceiling.** Here is how the models turned questions into queries:
  - "What is the cheapest web search API for AI agents?" became `cheapest web search API for AI agents 2024`.
  - "Best SerpAPI alternative that is cheaper?" became `cheaper alternatives to SerpAPI`.
  - "Cheapest SERP API in 2026?" became `cheapest SERP API 2026`.

  A comparison question deserves one query per thing being compared.
- **Retrieve wide, cite narrow.** The models cited about half of what they retrieved, and the cited half was spread across the whole list. Top-3 retrieval would have missed most of what they ended up using.
- **Anchor the date.** A model that doesn't know today's date will sometimes search for last year's answer.

## What does an agentic search loop look like in code?

**Below is a complete, small loop.** The model plans queries and decides when to stop. Your code does the searching, removes duplicate results, and enforces the budget. Search runs on Keirolabs (ours). The model is Claude through the Anthropic Python SDK, but any model that can return JSON works.

```python
import json, os, requests, datetime
from concurrent.futures import ThreadPoolExecutor
import anthropic

client = anthropic.Anthropic()
KEIRO = {"Authorization": f"Bearer {os.environ['KEIRO_API_KEY']}"}
TODAY = datetime.date.today().isoformat()

def search(q: str) -> list[dict]:
    r = requests.post("https://api.keirolabs.cloud/api/v2/search/lite",
                      headers=KEIRO, json={"query": q, "count": 10}, timeout=30)
    r.raise_for_status()
    return r.json()["results"]            # title, url, snippet

def extract(url: str) -> str:
    r = requests.post("https://api.keirolabs.cloud/api/v2/extract",
                      headers=KEIRO, json={"url": url}, timeout=60)
    r.raise_for_status()
    return r.json()["results"][0]["content"][:8000]   # markdown, capped before it enters context

def ask(prompt: str) -> dict:
    msg = client.messages.create(model="claude-opus-5-5", max_tokens=4000,
                                 messages=[{"role": "user", "content": prompt}])
    text = next(b.text for b in msg.content if b.type == "text")
    return json.loads(text[text.find("{"): text.rfind("}") + 1])

def agentic_search(question: str, max_rounds: int = 3, max_pages: int = 6) -> dict:
    seen, notes = set(), []
    plan = ask(f"Today is {TODAY}. Break this question into 2-5 web search queries. "
               f'Reply as JSON: {{"queries": [...]}}\nQuestion: {question}')
    queries = plan["queries"]
    for round_ in range(max_rounds):
        with ThreadPoolExecutor(5) as pool:                      # fan out
            results = [r for rs in pool.map(search, queries) for r in rs]
        fresh = [r for r in results if r["url"] not in seen]     # dedupe
        seen.update(r["url"] for r in fresh)
        listing = "\n".join(f"- {r['title']} | {r['url']} | {r.get('snippet', '')}" for r in fresh)
        pick = ask(f"Question: {question}\nNotes so far: {notes}\nNew results:\n{listing}\n"
                   f'Pick up to 3 URLs worth reading. Reply as JSON: {{"urls": [...]}}')
        for url in pick["urls"][: max_pages - len(notes)]:       # read
            notes.append({"url": url, "text": extract(url)})
        verdict = ask(f"Today is {TODAY}. Question: {question}\nNotes: {json.dumps(notes)[:60000]}\n"
                      'Can every part be answered with a source from the notes? Reply as JSON: '
                      '{"done": true/false, "missing_queries": [...]}')
        if verdict["done"] or len(notes) >= max_pages:           # stop
            break
        queries = verdict["missing_queries"]                     # reflect, loop
    return {"notes": notes, "rounds": round_ + 1}
```

Hand the returned notes to a final grounded-answer prompt, like the one in our [grounding guide](/blog/grounding-ai-agents-web-search).

**Why the work is split this way:**

- **Snippets are cheap and pages are expensive.** The loop lists snippets to the model first and fetches full text only for the URLs it picks.
- **Code owns the budget, not the model.** `max_rounds` and `max_pages` are hard limits. Asking the model to "be efficient" is not.
- **Deduplication happens in code.** Without it, the second round re-reads the same pages.

## When should the loop stop?

**Give it three ways to stop, and enforce all of them in code.**

| Stop when | Why |
|---|---|
| The model says every sub-question has a source | The normal exit |
| A round finds no new URLs | Searching again will not help; rewrite the queries or give up |
| The budget is spent: rounds, pages, tokens or seconds | Stops runaway loops on unanswerable questions |

**A reasonable starting budget:**

- **Interactive answers:** 3 rounds and 6 pages.
- **Research tasks:** 5 to 8 rounds.

Log rounds per question. If most questions need the full budget, the planning prompt is too vague or the search results are poor.

## What does agentic search cost?

**Count searches and page reads separately, because they are priced very differently.** One question with 3 rounds of 4 queries, plus 6 page reads, on Keirolabs paid plans:

| Step | Calls | Credits | Cost on plans |
|---|---|---|---|
| Lite searches | 12 | 12 × 0.0375 | under $0.002 |
| Page extracts | 6 | 6 × 2 | about $0.01–0.03 |
| **Search total per question** | | | **about $0.01–0.03** |

**The model tokens usually cost more than the search,** because every round re-sends the notes. That is the main reason to keep page text capped and summaries short; see [context engineering for search agents](/blog/context-engineering-web-search-agents).

**When you don't want to run the loop yourself,** a hosted deep-search endpoint runs it for you. Keirolabs `/deep` is 2 credits a call and found the answer to 96.5% of SimpleQA questions in our own harness ([results](/blog/deep-search-update)). Our comparison of [deep research APIs](/blog/deep-research-apis-2026-turnkey-vs-build-your-own) covers when building beats buying.

## Agentic search checklist

- **Put today's date in every planning prompt.**
- **Plan several queries, one per entity or sub-question.**
- **Retrieve 10 or more results per query.** Citations come from deep in the list.
- **Select from snippets, then read only the pages you picked.**
- **Deduplicate URLs across rounds.**
- **Set hard limits on rounds, pages and tokens in code.**
- **Finish with a grounded answer that cites the notes, and check the citations.**

New Keirolabs accounts get up to 2,000 free credits with no card (1,000 at signup, 1,000 more after setup) ([get a key](https://platform.keirolabs.cloud/register)). Page extraction is on paid plans, so on the free tier swap `extract()` for `/search/content`, which returns page text with the results.
