Large Language Models write well, but they know nothing about your documents, and they sometimes make things up with full confidence. Retrieval-Augmented Generation (RAG) addresses both problems. Before the model answers, we retrieve the most relevant passages from a knowledge base and give them to the model as context.
In this post I build a complete RAG application with Python and JavaScript. It is 100% open source, needs no paid API keys, and is deployed automatically to a public cloud (Hugging Face Spaces) by GitHub Actions on every push.
- 💻 Repository: https://github.com/IkerASierraR/rag-docs-assistant
- 🚀 Live demo: https://huggingface.co/spaces/Piker27/rag-docs-assistant
What we are building
The app is a docs assistant. You ask a question, it searches a small knowledge base (plus any .md / .txt files you add), and it answers using only the retrieved passages. It also shows the sources and their similarity scores so you can check the answer.
Architecture
GitHub Actions (on every push) ┌───────────────────────────────────────────────────────────┐ │ pytest ─► build_index.py (Python + sentence-transformers) │ │ data/*.md ─► chunks ─► embeddings ─► index.json │ │ ─► upload web/ + index.json to Hugging Face Space │ └───────────────────────────────────────────────────────────┘ │ ▼ Static Space (browser, transformers.js) question ─► MiniLM embedding ─► cosine top-k over index.json ─► prompt(context + question) ─► LaMini-Flan-T5 ─► answer + sources RAG has two phases, and I split them by where they run:
- Indexing (offline, Python, in CI): load documents, split them into chunks, embed every chunk, and save the vectors.
- Querying (online, in the browser): embed the question, find the most similar chunks, build a prompt with them, and let a small LLM write a grounded answer.
Why this split? Hugging Face Spaces that run a Python server (Gradio/Docker) now require a PRO subscription, while static Spaces are free. I build the index in Python during the pipeline and run inference in the browser with transformers.js. Both sides use the same embedding model, all-MiniLM-L6-v2, so the vectors are directly comparable.
| Piece | Choice |
|---|---|
| Indexing | Python 3.11 + sentence-transformers/all-MiniLM-L6-v2 |
| Vector store | JSON + cosine similarity |
| Generator | LaMini-Flan-T5-248M in the browser (transformers.js) |
| CI/CD | GitHub Actions |
| Cloud | Hugging Face Spaces (static, free) |
1. Chunking (Python, rag.py)
Embedding models work best on short, focused passages, and LLMs have a limited context window. So I split documents into chunks of about 500 characters, with 100 characters of overlap. The overlap means a sentence cut at a boundary still appears whole in some chunk:
def chunk_text(text: str, chunk_size: int = 500, overlap: int = 100) -> List[str]: pieces = re.split(r"(?<=[.!?])\s+|\n{2,}", text.strip()) chunks, current = [], "" for piece in pieces: piece = piece.strip() if not piece: continue if len(current) + len(piece) + 1 <= chunk_size: current = f"{current} {piece}".strip() continue if current: chunks.append(current) current = current[-overlap:] # carry overlap forward while len(piece) > chunk_size: # hard-split huge pieces chunks.append(piece[:chunk_size]) piece = piece[chunk_size - overlap:] current = f"{current} {piece}".strip() if current: chunks.append(current) return chunks 2. Embeddings and a tiny vector store
An embedding is a vector that represents the meaning of a text. all-MiniLM-L6-v2 produces 384-dimensional vectors and is fast on a CPU. A small knowledge base doesn't need a vector database. If every vector is normalized, cosine similarity is just a dot product, and one matrix-vector multiplication scores all chunks at once:
@dataclass class VectorStore: embed: Embedder chunks: List[Chunk] = field(default_factory=list) matrix: np.ndarray | None = None def add(self, chunks): vectors = _normalize(np.asarray(self.embed([c.text for c in chunks]), dtype=np.float32)) self.matrix = vectors if self.matrix is None else np.vstack([self.matrix, vectors]) self.chunks.extend(chunks) def search(self, query: str, k: int = 4): q = _normalize(np.asarray(self.embed([query]), dtype=np.float32))[0] scores = self.matrix @ q top = np.argsort(-scores)[:k] return [RetrievedChunk(self.chunks[i], float(scores[i])) for i in top] 3. Building the index in the pipeline (build_index.py)
The CI job runs this script and writes every chunk with its embedding to web/index.json:
rag = RAGPipeline() # loads sentence-transformers lazily n = rag.index(sorted(DATA_DIR.glob("*"))) payload = { "model": EMBED_MODEL, "dim": int(rag.store.matrix.shape[1]), "chunks": [ {"source": c.source, "index": c.index, "text": c.text, "embedding": [round(float(x), 5) for x in vec]} for c, vec in zip(rag.store.chunks, rag.store.matrix) ], } OUT.write_text(json.dumps(payload), encoding="utf-8") The knowledge base is always in sync with the repository: edit a Markdown file in data/, push, and the index is rebuilt.
4. Retrieval and generation in the browser (web/app.js)
transformers.js runs ONNX versions of Hugging Face models directly in the browser. With pooling: "mean" and normalize: true, Xenova/all-MiniLM-L6-v2 produces the same vectors as sentence-transformers:
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.0.2"; const embedder = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2"); const generator = await pipeline("text2text-generation", "Xenova/LaMini-Flan-T5-248M"); async function embed(text) { const out = await embedder(text, { pooling: "mean", normalize: true }); return Float32Array.from(out.data); } function search(qvec, k) { return store .map((c) => ({ c, score: dot(c.embedding, qvec) })) // cosine = dot (normalized) .sort((a, b) => b.score - a.score) .slice(0, k); } 5. A grounded prompt
To reduce hallucinations, the prompt tells the model to use only the context and to admit when it doesn't know:
function buildPrompt(question, hits) { const context = hits.map((h) => h.c.text).join("\n---\n"); return `Answer the question using only the context below. ` + `If the answer is not in the context, say "I don't know".\n\n` + `Context:\n${context}\n\nQuestion: ${question}\nAnswer:`; } const hits = search(await embed(question), k); const out = await generator(buildPrompt(question, hits), { max_new_tokens: 200 }); You can also upload your own .md / .txt files. They are chunked and embedded in the browser and added to the same in-memory store.
The repo also includes
app.py, a Gradio UI that runs the whole pipeline in Python (flan-t5-baseas the generator), for local use or for any host that runs Python servers.
6. Tests that run in a second
Downloading models in CI is slow, so the unit tests inject a fake bag-of-words embedder. They still cover chunking, ranking, prompt building, and the full pipeline:
VOCAB = ["rag", "retrieval", "cloud", "deploy", "chunk", "vector", "pizza"] def fake_embed(texts): return np.array([[t.lower().count(w) for w in VOCAB] for t in texts], dtype=np.float32) def test_vector_store_returns_most_similar_first(): store = VectorStore(embed=fake_embed) store.add([Chunk("We deploy to the cloud with GitHub Actions.", "a", 0), Chunk("Pizza is a tasty dish.", "b", 0)]) assert store.search("how do we deploy to the cloud?", k=1)[0].chunk.source == "a" 7. Automated deployment: GitHub Actions to Hugging Face Spaces
Every push to main runs test and then deploy. The deploy job only runs if the tests pass. It installs CPU-only PyTorch, builds the index, and uploads the static site with huggingface_hub:
name: CI / Deploy to Hugging Face Spaces on: push: branches: [main] workflow_dispatch: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: { python-version: "3.11" } - run: pip install "numpy<2.1" pypdf pytest - run: pytest -q deploy: needs: test runs-on: ubuntu-latest env: HF_TOKEN: ${{ secrets.HF_TOKEN }} HF_SPACE: ${{ vars.HF_SPACE }} steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: { python-version: "3.11" } - run: | pip install torch --index-url https://download.pytorch.org/whl/cpu pip install sentence-transformers "huggingface_hub<1.0" - run: python build_index.py - run: | python - <<'EOF' import os from huggingface_hub import HfApi api = HfApi(token=os.environ["HF_TOKEN"]) space = os.environ["HF_SPACE"] api.create_repo(space, repo_type="space", space_sdk="static", exist_ok=True) api.upload_folder(folder_path="web", repo_id=space, repo_type="space") EOF The Space reads its configuration from the YAML header of web/README.md (sdk: static, app_file: index.html).
One-time setup:
- Create a Hugging Face write token.
- In GitHub, go to Settings → Secrets and variables → Actions. Add the secret
HF_TOKENand the variableHF_SPACE(your-user/rag-docs-assistant). - Push. No credentials live in the code.
A lesson from the deployment: my first version deployed a Gradio (Python server) Space, and the API answered 402 Payment Required. Reading the CI log quickly showed that only static Spaces stay free, and that's what led to this architecture.
Result
Ask "Why do we split documents into chunks?". The app retrieves the chunking passage from the knowledge base, answers from it, and shows the source with its similarity score. The first visit downloads the models (about 150 MB), and the browser caches them after that.
Ideas to improve it
- Swap the JSON index for FAISS, pgvector, or Qdrant for large corpora.
- Use a stronger LLM through an API (OpenAI, Claude, Gemini, Ollama) for richer answers.
- Add a re-ranker (cross-encoder) after retrieval.
- Evaluate retrieval quality with a small labeled set of questions.
The full code is in the repo: https://github.com/IkerASierraR/rag-docs-assistant. Fork it and try it with your own documents. Thanks for reading! 🙌



