---
title: "Grounding AI Agents with Web Search: Stop Hallucinations (2026)"
description: "What grounding is, why agents hallucinate, and how to ground answers in web search results with numbered sources, citation checks in code, and the failure modes we measured in 163 model answers."
category: "guides"
url: https://keirolabs.cloud/blog/grounding-ai-agents-web-search
published: 2026-11-24
updated: 2026-11-24
---

# Grounding AI agents with web search: stop hallucinations, cite sources

## The 60-second version

**Grounding means making a model answer from sources you give it at request time, not from what it memorized in training.** For an AI agent, those sources are usually web search results and the pages behind them. A grounded agent answers from evidence it can point to, and says so when the evidence is missing.

Grounding takes four steps, and most hallucinations come from skipping one of them:

1. **Retrieve.** Search the web for the question, using a query that matches what was actually asked.
2. **Read.** Get the text of the best results, not just the snippets.
3. **Answer from the sources only.** Tell the model to use the retrieved text and to cite it by ID.
4. **Check.** Confirm in code that every citation points to a source you actually retrieved, and that the quoted words appear in it.

| Without grounding | With grounding |
|---|---|
| Answers from training data, frozen at the knowledge cutoff | Answers from pages fetched today |
| Fills gaps with plausible guesses | Says "the sources don't say" |
| No way to check a claim | Every claim links to a source |
| Prices, versions and dates go stale | Current facts, if the search is current |

## Why do AI agents hallucinate?

**A language model predicts likely text. It does not look anything up unless you give it a tool or the text itself.** Ask about anything after its training cutoff, or anything too niche to have been in its training data, and it produces the most plausible-sounding answer. That might be a wrong price, a version number that doesn't exist, or a function with the wrong arguments.

**Three kinds of questions cause most of the trouble:**

- **Recent facts:** prices, releases, rate limits, who acquired whom.
- **Long-tail facts:** a specific API parameter, a small company's pricing, a court ruling.
- **Exact values:** numbers, dates, names and URLs, where "close" is wrong.

Grounding fixes these by putting the facts into the context window, so the model copies instead of guessing.

## What does grounding look like in code?

**The smallest working version is one search call and one prompt.** This example uses Keirolabs (ours) for search, but any search API that returns titles, URLs and text works the same way.

```python
import os, requests

def search_with_content(query: str, n: int = 5) -> list[dict]:
    """Search the web and return the top results with their page text."""
    r = requests.post(
        "https://api.keirolabs.cloud/api/v2/search/content",
        headers={"Authorization": f"Bearer {os.environ['KEIRO_API_KEY']}"},
        json={"query": query, "maxResults": n},
        timeout=60,
    )
    r.raise_for_status()
    return [{"id": i + 1, "title": x["title"], "url": x["url"], "text": x.get("full_text", "")}
            for i, x in enumerate(r.json()["results"])]

def grounded_prompt(question: str, sources: list[dict]) -> str:
    blocks = "\n\n".join(
        f"[{s['id']}] {s['title']}\nURL: {s['url']}\n{s['text'][:6000]}" for s in sources
    )
    return f"""Answer the question using ONLY the sources below.
Cite every factual claim with its source number, like [2].
Quote exact numbers and names as they appear in the source.
If the sources do not contain the answer, say "The sources don't say" and stop.

SOURCES:
{blocks}

QUESTION: {question}"""
```

**Four details in that prompt do most of the work:**

- **Numbered sources.** `[1]`, `[2]` give the model a short handle to cite, and give you something to check.
- **"ONLY the sources."** This turns the task from recall into reading.
- **"Quote exact numbers."** Paraphrased numbers are where small errors creep in.
- **An explicit way out.** Without "say the sources don't say", the model fills the gap from memory, which is the very thing you were trying to prevent.

**Cap the text per source.** `[:6000]` characters is a rough budget. A whole page can be tens of thousands of tokens, and our [context engineering guide](/blog/context-engineering-web-search-agents) shows how fast that adds up.

## How do I check the model's citations?

**Never trust a citation you haven't checked.** Models sometimes cite the wrong source number, or cite a source for a claim it doesn't make. Two cheap checks in plain Python catch most of these:

```python
import re

def check_citations(answer: str, sources: list[dict]) -> dict:
    """Flag citations to sources that don't exist, and quoted text that isn't in the cited source."""
    by_id = {s["id"]: s for s in sources}
    cited = {int(n) for n in re.findall(r"\[(\d+)\]", answer)}
    unknown = sorted(cited - by_id.keys())

    # Every "quoted phrase" followed by [n] must appear in source n
    bad_quotes = []
    for quote, n in re.findall(r'"([^"]{8,200})"\s*\[(\d+)\]', answer):
        src = by_id.get(int(n))
        if src is None or quote.lower() not in src["text"].lower():
            bad_quotes.append((quote, int(n)))

    sentences = [s for s in re.split(r"(?<=[.!?])\s+", answer) if len(s) > 40]
    uncited = [s for s in sentences if not re.search(r"\[\d+\]", s)]
    return {"unknown_sources": unknown, "unsupported_quotes": bad_quotes, "uncited_sentences": uncited}

sources = [{"id": 1, "text": "The free plan includes 1,000 credits a month."}]
print(check_citations('It includes "1,000 credits a month" [1]. It also has SSO [2].', sources))
# {'unknown_sources': [2], 'unsupported_quotes': [], 'uncited_sentences': []}
```

**What to do with the flags:**

- **Unknown sources:** retry once with a note listing the valid IDs.
- **Unsupported quotes:** drop the claim or re-ask with the source attached.
- **Many uncited sentences:** the model is drifting back to memory. Tighten the prompt or retrieve more.

For high-stakes answers, add a second pass: give a cheap model one claim and its cited source at a time, and ask "Does the source support this claim? Yes or no." It is slower, but it catches claims that cite a real source that doesn't actually say what's claimed.

## Where does grounding still go wrong?

**Grounding moves the failure from "the model made it up" to "the search found the wrong thing."** Watch these four places.

**1. The search query drifts from the question.** When OpenAI models search the web, they first rewrite the question into a search query. We logged 163 answers from three OpenAI models with web search on, between November 16 and 24, 2026. **In 16 of them (10%), the model added a year the user never asked for, and it was an old one: "cheapest web search API for AI agents 2024", asked in November 2026.** The results were stale before the model read them. If you write the query yourself, put today's date in the system prompt and add the current year to time-sensitive queries.

**2. One search is not enough.** In the same logs, every answer used exactly one search query. That is fine for a simple lookup, but a comparison ("X vs Y pricing") needs one search per entity. [Agentic search](/blog/agentic-search) covers how to plan several queries and when to stop.

**3. Snippets are not sources.** A snippet is a search engine's two-line summary, cut off mid-sentence. Grounding an answer in snippets alone invites the model to fill in the rest. Read the page for any claim you will cite.

**4. The best source is not always the top result.** The models in our logs read about 13 results per answer and cited about 7. **The median cited result was ranked 8th, and 43% of citations came from results ranked below 10th.** Retrieve more than you plan to use, then let the model choose.

## Should I use a built-in search tool or my own?

**Model providers now offer built-in grounding:**

- Anthropic's server-side web search tool: $10 per 1,000 searches, plus tokens.
- Google's Grounding with Google Search for Gemini: 5,000 free searches a month on Gemini 3 models, then $14 per 1,000.

These are the fastest way to start.

**Bring your own search tool when you need control:**

- choosing which results the model sees;
- filtering domains;
- caching results;
- checking citations against the exact text you passed in;
- paying less per search at volume.

Wiring one in takes about 30 lines; see [how to give an LLM a web search tool](/blog/llm-web-search-tool-calling).

## How do I know grounding is working?

**Measure it on questions with known answers.** Keep 50 to 100 questions your users actually ask, each with the correct answer and the date you checked it. Run your agent on them weekly and track three numbers:

| Metric | What it tells you |
|---|---|
| Accuracy | Did the answer match? |
| Citation precision | What share of citations passed `check_citations`? |
| Abstention rate | How often did it say "the sources don't say"? Too low means guessing; too high means retrieval is failing |

For a public reference point, SimpleQA is a set of short factual questions often used to compare search APIs. In our own harness, Keirolabs deep search scored 95.3% on it ([results and method](/blog/most-accurate-web-search-api)). Run it on your own questions too, because a benchmark is not your traffic.

**To try the pattern above:** Keirolabs `/search/content` returns search results with full page text in one call, and new 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)). Our [guide to search APIs for RAG](/blog/best-search-apis-for-rag) compares the other options.
