Retrieval-augmented answers from a single static page

Retrieval-augmented generation, usually shortened to RAG, is the standard way to make a model answer from your own documents instead of from memory. Most tutorials reach for a vector database, an embedding service and a Python framework, and many teams go further and build fully local pipelines because they do not want sensitive internal documents leaving their network. That is the right call for production. For learning, demos and small public knowledge bases, though, the whole idea fits in one HTML file.
This guide builds that file step by step. Documents are split into chunks in the browser, ranked with a classic keyword algorithm called BM25, and the top passages are sent with the question to an OpenAI-compatible model. No server, no build tool and no key: the keyless free-ai endpoint on this site accepts calls from any origin. You will also see where this simple approach falls short and what to change when it does.
This site is independent and not affiliated with DeepSeek. The endpoint here serves an open-weight model of about 35B parameters and offers text chat and completions only, with no embeddings API, which is exactly why this demo uses keyword retrieval.
Frequently asked questions
What is retrieval-augmented generation?
It is a pattern where you first search your own documents for passages relevant to a question, then give those passages to the model along with the question, asking it to answer from them. The model supplies language; your documents supply facts.
How does keyword retrieval differ from vector search?
Keyword methods like BM25 score passages by shared words, weighting rare words more. Vector search compares embeddings, so it can match paraphrases with no words in common. Keyword search is simpler and fully local; vectors handle synonyms better.
Which is better for a small demo, BM25 or embeddings?
For a few hundred passages of technical or factual text, BM25 is often surprisingly good and needs no extra service. If users phrase questions very differently from the documents, embeddings will retrieve better.
Why not just paste all documents into the prompt?
It works while everything fits, but the context here is 32,000 tokens, and more irrelevant text tends to make answers worse. Retrieval keeps prompts short, fast and focused.
Are my documents sent to the API?
Only the chunks you include in a request are sent, together with the question. The full collection stays in the browser. Do not use this setup for confidential material; for that, run a local model and pipeline.
How do I stop the model inventing answers?
Tell it to answer only from the provided passages, to say when they do not contain the answer, and to cite passage numbers. Then show those passages to the user so they can check.
Can this approach scale to thousands of documents?
Ranking a few thousand chunks in JavaScript is fast. Beyond tens of thousands, or with many users, you will want a proper search index on a server.
Step by step
- Collect documents — Gather public text or Markdown files and save them as a JSON array of title and text pairs next to your HTML page.
- Chunk them — Split each document into passages of about 220 words, keeping the title with every passage.
- Build the BM25 index — Tokenise passages, count document frequencies and compute the average length once when the page loads.
- Retrieve and prompt — For each question take the top four passages, number them and send them with grounding rules to the chat endpoint.
- Show answer and sources — Render the answer as plain text and list the cited passages below it so users can verify.
The four moving parts
Every RAG system, however elaborate, has the same skeleton. You prepare documents by splitting them into chunks. You index those chunks so they can be searched. At question time you retrieve the best few. Finally you generate an answer by sending the question and the retrieved chunks to a model with instructions to stay grounded.
In a large production system each stage might be a separate service. In this demo each stage is a few lines of JavaScript, which makes it a good way to understand what the frameworks do for you.
Prepare
Split long documents into passages of a few hundred words, keeping the document title with each passage so the model knows where it came from.
Index and retrieve
Tokenise each passage, count term frequencies and compute how rare each word is across the collection, then score passages against the question.
Generate
Build a prompt containing numbered passages and the question, and ask the model to answer from them and cite the numbers it used.
Chunking documents sensibly
Chunk size is a trade-off. Large chunks keep context together but dilute keyword scores and eat the prompt budget. Small chunks score sharply but can cut a definition in half. For prose, passages of 150 to 300 words with a small overlap work well. For documentation, splitting at headings is often better than splitting by length, because each section is already about one thing.
The function below splits on blank lines, then merges paragraphs until a passage reaches a target length.
Keep titles attached
A passage that says 'it must be enabled first' is useless without knowing which feature 'it' is. Prefixing the document title fixes most of these ambiguities.
function chunk(docTitle, text, target = 220) {
const paras = text.split(/\n\s*\n/).map(p => p.trim()).filter(Boolean);
const out = [];
let cur = [];
let words = 0;
for (const p of paras) {
const n = p.split(/\s+/).length;
if (words + n > target && cur.length) {
out.push({ title: docTitle, text: cur.join("\n\n") });
cur = []; words = 0;
}
cur.push(p); words += n;
}
if (cur.length) out.push({ title: docTitle, text: cur.join("\n\n") });
return out;
}
Ranking passages with BM25
BM25 has been a search workhorse for decades. It rewards passages that contain the question's words, gives more weight to words that are rare across the collection, and dampens the effect of a word repeated many times or of very long passages. It needs no training and runs instantly on a few thousand chunks.
The implementation below is compact but complete. It lowercases text, keeps letters and digits from any script, drops very short tokens, and precomputes document frequencies once.
Tuning k1 and b
The defaults of 1.4 and 0.75 are fine for most text. Lower b if your passages vary a lot in length and long ones are being unfairly penalised.
Stop words
Filtering tokens shorter than three characters removes many common words cheaply. For better results, add a short stop-word list in your documents' language.
const tok = s => (s.toLowerCase().match(/[\p{L}\p{N}]+/gu) || []).filter(w => w.length > 2);
function buildIndex(chunks) {
const docs = chunks.map(c => tok(c.title + " " + c.text));
const df = new Map();
docs.forEach(d => new Set(d).forEach(w => df.set(w, (df.get(w) || 0) + 1)));
const avg = docs.reduce((a, d) => a + d.length, 0) / Math.max(1, docs.length);
return { chunks, docs, df, avg, N: docs.length };
}
function search(index, query, k = 4, k1 = 1.4, b = 0.75) {
const q = [...new Set(tok(query))];
const scored = index.docs.map((d, i) => {
const tf = new Map();
d.forEach(w => tf.set(w, (tf.get(w) || 0) + 1));
let s = 0;
for (const w of q) {
const f = tf.get(w) || 0;
if (!f) continue;
const n = index.df.get(w);
const idf = Math.log(1 + (index.N - n + 0.5) / (n + 0.5));
s += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * d.length / index.avg));
}
return { i, s };
});
return scored.filter(x => x.s > 0).sort((a, b) => b.s - a.s).slice(0, k).map(x => index.chunks[x.i]);
}Writing a grounded prompt
Retrieval only helps if the model actually uses the passages. The prompt should present them clearly, numbered, and state the rules: answer from these passages, cite them, and admit when they do not contain the answer. Put the question after the passages so it is the last thing the model reads.
A system message carries the rules; the user message carries passages and question. Keep the rules short and concrete.
Show the sources
Render the retrieved passages under the answer, highlighting the cited numbers. Users trust answers they can check, and you will spot retrieval failures immediately.
async function answer(index, question) {
const hits = search(index, question);
const context = hits.map((c, n) => `[${n + 1}] (${c.title})\n${c.text}`).join("\n\n");
const res = await fetch("https://api.apideepseekfreekey.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "free-ai",
max_tokens: 700,
messages: [
{ role: "system", content: "Answer only from the numbered passages. Cite them like [2]. If they do not contain the answer, say so plainly." },
{ role: "user", content: context + "\n\nQuestion: " + question }
]
})
});
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json();
return { text: data.choices[0].message.content, sources: hits };
}
Wiring the page together
The page needs only a way to load documents, an input for questions and an area for answers. Documents can be bundled as a JSON file next to the HTML, fetched from a public URL, or dropped in by the user with a file input. Build the index once when documents load and keep it in memory.
Because there is no key, the finished page can be hosted anywhere static files are served, and the source can be public. Each visitor's requests count against their own IP's limits: one request per second, two in parallel and a generous daily allowance.
Render safely
Insert model output with textContent or a sanitiser. Documents and answers can contain characters that would break or inject HTML.
- Load:
fetch('docs.json')or a file input reading.txtand.md - Index: call
chunkper document, thenbuildIndexonce - Ask: disable the button, call
answer, render text and sources - Errors: on 429 or 503 wait a few seconds and retry, as in the retry guide
Testing retrieval separately from generation
When a RAG answer is wrong, the cause is usually retrieval, not the model: the right passage was never sent. Test the two stages separately. Write a list of questions with the passage each should find, run only the search function, and count hits in the top four. Fix chunking and tokenisation until that number is high, then look at answer quality.
This split saves requests, too. Retrieval tests run entirely in the browser and cost nothing.
Typical retrieval fixes
Smaller chunks for sharper matches, adding titles and headings to each chunk, a stop-word list, and simple synonym expansion for key terms in your domain.
Typical generation fixes
Firmer grounding rules, fewer but better passages, and asking for a short answer followed by citations instead of a long essay.

Limits of the no-backend approach
This design is deliberately minimal and has honest limits. Keyword retrieval misses paraphrases. Everything loads into each visitor's browser, so the collection must be public and reasonably small. There is no access control, no update pipeline and no analytics. And the model is a mid-sized open-weight one; for nuanced synthesis across many sources, larger commercial models, DeepSeek's among them, will write better answers.
For sensitive company documents, the right architecture is the opposite of this demo: a local model, a local index and nothing crossing the network. The comparison in local versus hosted models covers what hardware that takes.
Upgrading retrieval
If you later add an embeddings service, keep BM25 and combine both scores. Hybrid retrieval usually beats either method alone.
Handling follow-up questions
Real users rarely ask one perfectly formed question. They ask a follow-up such as 'and what about the second option?', which on its own contains almost no useful keywords. Running BM25 on that sentence retrieves nothing helpful. The fix is to search with a combination of the new question and the previous one, or to ask the model first to rewrite the follow-up into a standalone question.
Rewriting costs one extra short request, but it makes retrieval far more reliable in a conversational interface. Since the endpoint is stateless, your page sends the recent turns each time anyway, so the information for the rewrite is already at hand.
Cheap version
Concatenate the last user question and the new one before searching. It is crude but often enough for short conversations.
Better version
Ask the model to turn the follow-up into a self-contained question in one sentence, then search with that. Show the rewritten query in a small grey line so users understand what was searched.

Good uses for a static RAG page
Within those limits there is plenty of room. A product's public documentation, a course reader, a set of meeting guidelines, a club's rulebook or a hackathon's FAQ are all small, public and frequently searched. A single page that answers questions about them with citations is useful and costs nothing to host.
It is also an excellent teaching tool. Students can see every stage, change a parameter and watch retrieval improve, without installing a framework or creating an account anywhere.
Keep the corpus current
Regenerate the JSON file whenever documents change, and show the build date on the page so users know how fresh the answers are.
Open the home page and send a request to the keyless endpoint straight from your browser, no account or key needed.
Read also
- DeepSeek chat vs reasoner: which mode suits your web app?
- Can a coding agent run on a cheaper OpenAI-compatible backend?
- What does a model with fewer refusals mean for your app's moderation?
- What can you do when your LLM API does not accept image input?
- Local DeepSeek distill vs hosted API: which is better for you?