---
title: "RAG Chatbot with Web Search: Build One in Python (2026)"
description: "Build a RAG chatbot that answers from today's web instead of a vector database: turn each message into a search query, retrieve sources, answer with citations. 40 lines of tested Python, real outputs, and how to make it production-ready."
category: "guides"
url: https://keirolabs.cloud/blog/rag-chatbot-web-search
published: 2026-11-24
updated: 2026-11-24
---

# How to build a RAG chatbot with live web search (tested Python code)

## The 60-second version

**A RAG chatbot answers from retrieved sources instead of from the model's memory.** Every turn it does three things: turns the latest message into a search query, retrieves a handful of sources, and answers from those sources with citations. Most tutorials retrieve from a vector database of your own documents. This guide retrieves from the live web, which needs no database, no embeddings and no indexing job, and is current by default.

| Piece | Job | In this guide |
|---|---|---|
| **Query step** | Turns "when does *it* reach end of life?" into a standalone query | One small LLM call using the chat history |
| **Retriever** | Finds sources for the query | A web search API (title, URL, snippet) |
| **Answer step** | Writes the reply from the sources, with [n] citations | One LLM call with the sources in the system prompt |
| **Memory** | Keeps the conversation | A plain list of messages |

**The full chatbot is about 40 lines of Python,** and we ran it. The real outputs are below.

## Why a web search RAG chatbot instead of a vector database?

**Because the hard part of classic RAG is the index, and for many chatbots you don't need one.**

- **No ingestion pipeline.** No chunking, embedding or re-indexing when content changes.
- **Current answers.** The web already has today's prices, releases and news. A vector index only knows what you loaded into it.
- **Wider coverage.** Users ask about things you never thought to index.

**Use a vector database when the knowledge is private:** your internal docs, tickets or contracts. Many production chatbots do both: they search the web for public facts and a vector store for private ones ([vector database for RAG: when you need one](/blog/vector-database-for-rag)).

## Step 1: turn each message into a search query

**Chat messages make bad search queries.** "When does it reach end of life?" means nothing without the previous turn. So before retrieving, ask a model to rewrite the latest message into a standalone query:

```python
TODAY = "2026-11-24"

def to_query(history: list[dict], question: str) -> str:
    """Turn the latest message into a standalone search query, using the chat so far."""
    recent = "\n".join(f"{m['role']}: {m['content'][:300]}" for m in history[-6:])
    return llm([{"role": "user", "content":
        f"Today is {TODAY}. Conversation:\n{recent}\n\nLatest message: {question}\n\n"
        "Write one web search query (2-8 words) that would find the answer. "
        "Resolve pronouns from the conversation. Return only the query."}]).strip().strip('"')
```

`llm()` is any function that takes a list of chat messages and returns the model's text. A small, fast model is enough for this step. **Pass today's date.** Models otherwise add the year from their training data to queries: in our logs of 163 answers from OpenAI models with web search, 10% of queries included an old year nobody asked for ([grounding AI agents](/blog/grounding-ai-agents-web-search)). There are more rewriting techniques in [query rewriting and HyDE](/blog/query-rewriting-hyde).

## Step 2: retrieve sources

```python
import os, requests

def search(query: str, n: int = 6) -> list[dict]:
    r = requests.post("https://api.keirolabs.cloud/api/v2/search/lite",
                      headers={"Authorization": f"Bearer {os.environ['KEIRO_API_KEY']}"},
                      json={"query": query, "count": n}, timeout=30)
    r.raise_for_status()
    return r.json()["results"]          # [{"title", "url", "snippet"}, ...]
```

**Six results is a good default for chat.** Each snippet is around 65 tokens, so six cost about 400 tokens of context, against thousands for a full page ([context engineering for search agents](/blog/context-engineering-web-search-agents)).

## Step 3: answer from the sources, with citations

```python
def chat_turn(history: list[dict], question: str) -> str:
    query = to_query(history, question)
    results = search(query)
    sources = "\n\n".join(f"[{i+1}] {r['title']} ({r['url']})\n{r.get('snippet', '')}"
                          for i, r in enumerate(results))
    system = (f"Today is {TODAY}. Answer using the sources below and cite them as [n]. "
              "If the sources don't answer the question, say so instead of guessing.\n\n" + sources)
    answer = llm([{"role": "system", "content": system}, *history[-10:],
                  {"role": "user", "content": question}])
    history += [{"role": "user", "content": question}, {"role": "assistant", "content": answer}]
    return answer

history = []
print(chat_turn(history, "What's the latest stable version of Python?"))
print(chat_turn(history, "When does it reach end of life?"))
```

**Two details matter:** the sources go in the system prompt, fresh each turn, so old sources don't pile up in the history; and the instruction to say "the sources don't answer this" is what stops the bot from filling gaps with guesses.

## What it actually did

We ran the two-turn conversation above with a mid-size open model. **Turn 1:**

```text
SEARCH QUERY: latest stable Python version 2026
A: Python 3.15 is the latest stable release as of October 2026 [5]. It currently receives
   full bug-fix and security updates [5] ... Python 3.16 is still in pre-release [1].
```

**Turn 2,** "When does it reach end of life?":

```text
SEARCH QUERY: Python 3.15 end of life date
A: The sources don't state a definitive end-of-life date for Python 3.15. What they do say:
   endoflife.date shows that 3.15 "ends in 1 year and 10..." [2], but the text is cut off ...
```

**Two lessons from a real run:**

1. **The query step works.** "It" became "Python 3.15" without the user repeating themselves.
2. **Snippets aren't always enough.** The answer was in the source, but the snippet cut off mid-sentence. The bot said so instead of inventing a date, which is the behavior you want, and it points to the next upgrade.

## Upgrade: read full pages when snippets fall short

**When the answer needs detail, fetch the full text of the top results.** Keirolabs `/search/content` returns search results with each page's main content in one call. Keep it to the top two or three pages, and trim each page to the part that matters, so the context stays small.

A simple rule that works: **answer from snippets first; if the model says the sources don't answer the question, retry that turn with full page content.** Most turns stay cheap, and the hard ones get the detail.

## Make it production-ready

- **Stream the answer** so users see text immediately; retrieval adds a second or two before the first token.
- **Check the citations.** Verify each [n] points to a source you passed, and drop links that weren't in the sources ([LLM citations](/blog/llm-citations)).
- **Show the sources** under each answer as clickable links. Users trust answers they can check.
- **Skip search when it isn't needed.** "Thanks!" and "rewrite that shorter" don't need retrieval ([when should an AI agent search the web?](/blog/when-should-ai-agent-search-the-web)).
- **Treat retrieved text as untrusted.** Pages can contain instructions aimed at your bot ([prompt injection from web search results](/blog/prompt-injection-web-search-results)).
- **Keep users' questions private.** Chat queries often contain personal details. On Keirolabs paid plans, add `"zdr": true` to the request body and nothing about the query is retained ([web search APIs with zero data retention](/blog/web-search-api-zero-data-retention)).

## RAG chatbot checklist

- **Rewrite every message into a standalone query, with today's date.**
- **Retrieve 5 to 8 results; put them in the system prompt each turn.**
- **Require [n] citations and an explicit "the sources don't say".**
- **Fetch full pages only when snippets fall short.**
- **Verify citations, show sources, and stream the answer.**

Keirolabs `/search/lite` returns title, URL and snippet for $0.03 to $0.10 per 1,000 searches on plans, and `/search/content` adds full page text. New accounts get up to 2,000 free credits with no card ([get a key](https://platform.keirolabs.cloud/register)).
