# RAG with MillionShort

Retrieve passages from the web for a language model, keep the noise out, and cite what you used.

Retrieval-augmented generation has three steps: find passages, put them in the prompt, and have the model answer from them with citations. This guide covers the first two with MillionShort, and stops where your model begins.

What you get from a search is a ranked list of results, each with a **snippet**: the passage of the page that matches the query, up to 2,000 characters. That is the text you retrieve by default. When a snippet is not enough, `include_content: true` adds the text of the page as we hold it to `web` and `news` results, for 1 credit a call (up to 10 results). It is our stored copy, not a live fetch; to fetch a page as it is now, use [Extract](https://millionshort.com/docs/extract/parameters).

## 1. Search with long snippets

Ask for the longest snippets when the results are going into a prompt. The default is 800 characters.

```bash
curl https://api.millionshort.com/v1/search \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "how does a heat pump work in cold climates",
    "num_results": 10,
    "max_chars_per_result": 2000
  }'
```

```python
import os

import requests

r = requests.post(
    "https://api.millionshort.com/v1/search",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    json={
        "query": "how does a heat pump work in cold climates",
        "num_results": 10,
        "max_chars_per_result": 2000
    },
    timeout=30,
)
r.raise_for_status()
for hit in r.json()["data"]["results"]:
    print(hit["position"], hit["title"], hit["url"])
```

```ts
const res = await fetch('https://api.millionshort.com/v1/search', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "query": "how does a heat pump work in cold climates",
    "num_results": 10,
    "max_chars_per_result": 2000
  }),
});
if (!res.ok) throw new Error(`POST /v1/search failed: ${res.status}`);
const { data } = (await res.json()) as {
  data: { results: { position: number; title: string; url: string }[] };
};
for (const hit of data.results) console.log(hit.position, hit.title, hit.url);
```

The same call as a tool of the MCP server:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search",
    "arguments": {
      "query": "how does a heat pump work in cold climates",
      "num_results": 10,
      "max_chars_per_result": 2000
    }
  }
}
```

## 2. Take the noise out before it reaches the model

A model cannot ignore what is in its context. Four controls keep weak pages out of it, and all four are free:

- **`remove_top_sites`** drops the most popular sites, which is where most search-optimised filler lives. Try 1,000 to 10,000. See [Remove the top sites](https://millionshort.com/docs/search/remove-top-sites).
- **`page_types`** keeps kinds of page: `articles`, `documentation`, `tutorials`, `research`, `reference` and others from [`GET /v1/sources`](https://millionshort.com/docs/api-reference/sources).
- **`exclude_domains`** removes sites you have learned not to trust. See [Lenses](https://millionshort.com/docs/search/lenses).
- **`exclude_risky`** drops every result whose site carries a risk label, so you do not have to check `risk` yourself.

Then, in your own code, keep at most two results per `site`, so one site cannot fill the context.

## 3. Build the context

Number the passages, and carry the URL with each one so the model can cite it.

```python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])


def retrieve(question, limit=6):
    r = client.search(
        question,
        num_results=20,
        remove_top_sites=1000,
        exclude_risky=True,
        max_chars_per_result=2000,
    )
    passages, per_site = [], {}
    for hit in r.results:
        if not hit["snippet"]:
            continue
        per_site[hit["site"]] = per_site.get(hit["site"], 0) + 1
        if per_site[hit["site"]] > 2:
            continue
        passages.append(hit)
        if len(passages) == limit:
            break
    return passages, r.usage.credits


def build_prompt(question, passages):
    blocks = [
        f"[{n}] {hit['title']}\n{hit['url']}\n{hit['snippet']}"
        for n, hit in enumerate(passages, start=1)
    ]
    return (
        "Answer the question using only the numbered passages. "
        "Cite passages as [n]. If they do not contain the answer, say so.\n\n"
        + "\n\n".join(blocks)
        + f"\n\nQuestion: {question}"
    )


question = "how does a heat pump work in cold climates"
passages, credits = retrieve(question)
print(build_prompt(question, passages)[:400])
print(len(passages), "passages for", credits, "credits")
```

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

async function retrieve(question: string, limit = 6) {
  const r = await client.search(question, {
    numResults: 20,
    removeTopSites: 1000,
    excludeRisky: true,
    maxCharsPerResult: 2000,
  });
  const passages: typeof r.results = [];
  const perSite = new Map<string | null, number>();
  for (const hit of r.results) {
    if (!hit.snippet) continue;
    const seen = (perSite.get(hit.site) ?? 0) + 1;
    perSite.set(hit.site, seen);
    if (seen > 2) continue;
    passages.push(hit);
    if (passages.length === limit) break;
  }
  return { passages, credits: r.usage?.credits };
}

function buildPrompt(question: string, passages: Array<{ title: string; url: string; snippet: string }>) {
  const blocks = passages.map((hit, n) => `[${n + 1}] ${hit.title}\n${hit.url}\n${hit.snippet}`);
  return [
    'Answer the question using only the numbered passages. Cite passages as [n]. If they do not contain the answer, say so.',
    blocks.join('\n\n'),
    `Question: ${question}`,
  ].join('\n\n');
}

const question = 'how does a heat pump work in cold climates';
const { passages, credits } = await retrieve(question);
console.log(buildPrompt(question, passages).slice(0, 400));
console.log(passages.length, 'passages for', credits, 'credits');
```

Send the prompt to the model of your choice. Nothing here depends on which one.

## 4. Ask the right experts

A question about this week needs a current source; a question about a paper needs `academic`. One call can ask up to five [sources](https://millionshort.com/docs/search/sources), and each result says which it came from, so you can label passages for the model: "[3] (news, 2026-11-06) ...".

| Question | `sources` |
|---|---|
| General knowledge, how-to | `["web"]` |
| Current events | `["news", "web"]` |
| A scientific claim | `["academic", "web"]`, or `["medical"]` for clinical questions |
| Opinions and experience | `["discussions", "smallweb"]` |
| A company's own statements | `["finance", "news"]` |

Dated sources let you tell the model how old a passage is, and `time_range` or `start_date` and `end_date` keep only the passages from the days you want. `web` results have no date, so a date filter is not applied to them; see [Freshness](https://millionshort.com/docs/search/freshness).

## 5. Cite honestly

- Cite the `url` of each passage the answer used, and show `site` beside it.
- A snippet is part of a page. If the answer leans on one passage for something important, say that it is an excerpt.
- `popularity.bucket` is worth showing to a person: a `long-tail` source and a `top-100` source read differently.

## 6. Control the cost

- One search of one source is 1 credit for up to 10 results, and 0.5 more for each further 10. Twenty results from `web` cost 1.5 credits.
- Every filter and `explain` are free. Long snippets and highlights cost nothing extra. Page text (`include_content`) adds 1 credit to the call for up to 10 results that come back with it.
- A second source is a second credit. Add one when the question calls for it, not by default.
- Cache answers in your own store by query and options. The API does not charge less for a repeated search.
- Read `usage.credits` on every response and log it with your own request id.

## What this does not do

- **No live fetch in a search.** Snippets are up to 2,000 characters, and `include_content` returns the page text we hold for `web` and `news` results, as it was when we captured it. To fetch a page as it is now, use [Extract](https://millionshort.com/docs/extract/parameters).
- **No generated answer from a search.** Search retrieves; your model writes. For an answer written by us, [Agent](https://millionshort.com/docs/agent) is a separate, metered call: a written answer with a checked quote for every statement.
- **No meaning-based matching.** Retrieval is by the words of the query, so phrase the search the way a page would say it, and try a second wording when the first is thin.
- **No date filter on web pages.** `start_date`, `end_date` and `time_range` work on the dated sources, such as `news` and `academic`. Web pages carry no date, so the filter is not applied to `web`, and the response says so in a warning.

## Next

- [Long-tail research](https://millionshort.com/docs/search/guides/long-tail-research): going past the first page on purpose.
- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use): let the model decide when to search.
- Use cases: [RAG](https://millionshort.com/docs/use-cases/rag) and [low-noise RAG](https://millionshort.com/docs/use-cases/low-noise-rag).
