Guides
RAG with MillionShort
Retrieve passages from the web for a language model, keep the noise out, and cite what you used.
Copy as MarkdownOpen in ChatGPT (opens in a new tab)Open in Claude (opens in a new tab)
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.
1. Search with long snippets
Ask for the longest snippets when the results are going into a prompt. The default is 800 characters.
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
}'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"])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:
{
"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_sitesdrops the most popular sites, which is where most search-optimised filler lives. Try 1,000 to 10,000. See Remove the top sites.page_typeskeeps kinds of page:articles,documentation,tutorials,research,referenceand others fromGET /v1/sources.exclude_domainsremoves sites you have learned not to trust. See Lenses.exclude_riskydrops every result whose site carries a risk label, so you do not have to checkriskyourself.
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.
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")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, 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.
5. Cite honestly
- Cite the
urlof each passage the answer used, and showsitebeside 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.bucketis worth showing to a person: along-tailsource and atop-100source 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
webcost 1.5 credits. - Every filter and
explainare 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.creditson 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_contentreturns the page text we hold forwebandnewsresults, as it was when we captured it. To fetch a page as it is now, use Extract. - No generated answer from a search. Search retrieves; your model writes. For an answer written by us, 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_dateandtime_rangework on the dated sources, such asnewsandacademic. Web pages carry no date, so the filter is not applied toweb, and the response says so in a warning.
Next
- Long-tail research: going past the first page on purpose.
- Agent tool use: let the model decide when to search.
- Use cases: RAG and low-noise RAG.