Menu

Integrations / Cookbook and starters

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.

Copy as MarkdownOpen in ChatGPT (opens in a new tab)Open in Claude (opens in a new tab)

AvailablePython 3.9+One fileAny OpenAI-compatible modelTested 2026-11-19

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.

1Get the code

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?")

2Run it

Shell
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.

3What you get

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.

4Change it

ToChange
Send less text to the modelLower 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 seeWhyFix
401 AUTH_MISSING_KEY or AUTH_INVALID_KEYThe key is missing or wrongSet MILLIONSHORT_API_KEY; keys start with ms-
400 INVALID_PARAMA field name or value the API does not takeThe message names the field; the search reference lists them all
429 RATE_LIMITED or CAPACITYToo many calls a minute, or no free capacity right nowWait the Retry-After seconds, then retry
429 INSUFFICIENT_CREDITSThe plan's credits are used upStop and add credits; do not retry
The answer says the sources do not cover itThe five pages found do not answer the questionReword it, or search another source

This page as Markdown ยท llms.txt