# RAG with fresh pages

One search that brings back the text of each page, then one model call that answers only from it, with citations.

Available · Python 3.9+ · One file · Any OpenAI-compatible model · Tested 2026-11-19

> **For agents.** Read the API key from the `MILLIONSHORT_API_KEY` environment variable. Never print it; where a client needs it in a settings file, use a file that is not committed.
> The MCP address is https://mcp.millionshort.com/mcp (streamable HTTP; send `Authorization: Bearer <key>`, or no header for the no-key mode).
> On `INSUFFICIENT_CREDITS` stop and ask a person; on `RATE_LIMITED` or `CAPACITY` wait the `Retry-After` seconds, then retry once.
> Set-up steps written for agents: https://millionshort.com/docs/auth.md. Every integration: https://millionshort.com/docs/integrations.md.

`include_content` adds the text of each page, as we hold it, to its result: no second request to the site, no scraper to run. The script asks for five pages without the 1,000 most popular sites, puts their text in the prompt as numbered sources, and tells the model to answer only from them.

## 1. Get the code

```python rag.py
"""RAG with fresh pages: search with the text of each page, then answer only from that text.

    pip install openai
    export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
    export OPENAI_API_KEY=...            # or any OpenAI-compatible API: also set OPENAI_BASE_URL
    python rag.py "What should I check before buying a used e-bike battery?"

One search (1 credit, plus 1 for the page text of up to 10 results) and one model call.
MODEL picks the model (default gpt-5.4-mini).
"""
import json
import os
import sys
import urllib.error
import urllib.request

from openai import OpenAI

API = os.environ.get("MILLIONSHORT_BASE_URL", "https://api.millionshort.com").rstrip("/")
MODEL = os.environ.get("MODEL", "gpt-5.4-mini")


def retrieve(question, k=5):
    body = {"query": question, "num_results": k, "remove_top_sites": 1000,
            "include_content": True, "max_characters": 4000, "max_highlights": 3}
    request = urllib.request.Request(
        f"{API}/v1/search",
        data=json.dumps(body).encode(),
        headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"], "Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        answer = json.load(response)
    docs = []
    for r in answer["data"]["results"]:
        text = (r.get("content") or {}).get("text") or "\n".join(r.get("highlights") or [r.get("snippet") or ""])
        docs.append({"title": r["title"], "url": r["url"], "text": text})
    return docs, answer["usage"]["credits"]


def main(question):
    try:
        docs, credits = retrieve(question)
    except urllib.error.HTTPError as failure:
        sys.exit(f"The search failed: HTTP {failure.code} {failure.read().decode(errors='replace')[:300]}")
    if not docs:
        sys.exit("No results: try other words.")
    sources = "\n\n".join(f"[{n}] {d['title']} ({d['url']})\n{d['text']}" for n, d in enumerate(docs, 1))
    prompt = (f"Answer the question using only the sources below. Cite each claim as [n]. If the sources "
              f"do not answer it, say so.\n\nQuestion: {question}\n\nSources:\n{sources}")
    reply = OpenAI().chat.completions.create(model=MODEL, messages=[{"role": "user", "content": prompt}])
    print(reply.choices[0].message.content)
    print("\nSources:")
    for n, d in enumerate(docs, 1):
        print(f"[{n}] {d['url']}")
    print(f"\n(search: {credits} credits)", file=sys.stderr)


if __name__ == "__main__":
    main(" ".join(sys.argv[1:]) or "What should I check before buying a used e-bike battery?")
```

## 2. Run it

```bash
pip install openai
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
export OPENAI_API_KEY=your-model-key
python rag.py "What should I check before buying a used e-bike battery?"
```

For another OpenAI-compatible API, also set OPENAI_BASE_URL and MODEL.

## 3. What you get

```text Output (shortened)
Before buying a used e-bike battery, check its condition and how much it may have been used,
since used batteries can lose the ability to hold a charge after about 800 to 1,000 charge
cycles [3]. Ask the seller how long they have had the bike and how often it was used [3] ...

Sources:
[1] https://bigringcyclery.com/used-bike-buying-guide-what-to-check-before-you-pay/
[2] https://www.pedalchef.com/post/buying-used-bike/
[3] https://www.slashgear.com/1683551/electric-bike-used-new-things-know-before-buying/
```

A result that comes back without text falls back to its highlights, so every source has something to quote.

## 4. Change it

| To | Change |
|---|---|
| Send less text to the model | Lower `max_characters` (500 to 50,000), or drop `include_content` and use `max_highlights` alone |
| Use recent news | `"sources": ["news"]` and `"time_range": "week"` |
| Keep mainstream sites | `"remove_top_sites": 0` |

## Costs and limits

1 credit for the search, plus 1 for the page text of its results (up to 10): 2 credits a question with five results. The script prints the search's cost to stderr. The model's own cost is separate.

## When it fails

| What you see | Why | Fix |
|---|---|---|
| `401 AUTH_MISSING_KEY` or `AUTH_INVALID_KEY` | The key is missing or wrong | Set `MILLIONSHORT_API_KEY`; keys start with `ms-` |
| `400 INVALID_PARAM` | A field name or value the API does not take | The `message` names the field; the [search reference](https://millionshort.com/docs/search/parameters) lists them all |
| `429 RATE_LIMITED` or `CAPACITY` | Too many calls a minute, or no free capacity right now | Wait the `Retry-After` seconds, then retry |
| `429 INSUFFICIENT_CREDITS` | The plan's credits are used up | Stop and add credits; do not retry |
| The answer says the sources do not cover it | The five pages found do not answer the question | Reword it, or search another source |

## Related

- [RAG guide](https://millionshort.com/docs/search/guides/rag): retrieval patterns, chunking and citations at more length.
- [Page content](https://millionshort.com/docs/search/parameters): the `include_content` and `max_characters` fields.
- [Research agent](https://millionshort.com/docs/integrations/cookbook-research-agent): the model searches by itself, as often as it needs.
