A language model can produce a convincing answer and still get a specific fact wrong, such as the documents required for enrollment or the number of days a student can borrow a book. When those facts already exist in our documents, we can retrieve them and give them to the model before it answers.
That is the idea behind CampusRAG, an educational application I built with Python. A user asks a question, the system searches Markdown documents for relevant passages, and an open language model generates an English answer using that context. The interface displays the retrieved passages so the user can inspect the evidence.
This article walks through the implementation and explains how to enable automated deployment from GitHub to Hugging Face Spaces.
What is Retrieval-Augmented Generation?
Retrieval-Augmented Generation, or RAG, combines information retrieval with text generation. Instead of relying only on knowledge stored in a model's parameters, the application supplies external information at query time.
Lewis and colleagues' RAG paper describes combining a generative model with retrievable external memory. For this application, the process has three stages:
- Retrieve: find content related to the question.
- Augment: add that content to the model's context.
- Generate: produce an answer using the supplied information.
Updating the documents does not require retraining the model. It does require rebuilding the retrieval index so the application can find the updated information.
RAG can help ground answers, but it does not eliminate hallucinations. A model can still make mistakes if the retrieved information is incomplete, incorrect, or irrelevant.
The use case: a fictional campus assistant
I prepared four documents covering the library, enrollment, software projects, and technical support. All Campus Demo information is fictional and does not represent the policies of a real university.
For example, the library document states that the book loan period is seven calendar days. The application should retrieve that fact when someone asks:
How many days can I borrow library books?
The interface lets users ask a question, read the answer, and expand the retrieved sources. This makes the pipeline easier to inspect: we can see which information the model received.
Tools and architecture
| Component | Tool | Purpose |
|---|---|---|
| Backend | Python and FastAPI | Serve the interface and process questions |
| Knowledge base | Markdown | Store the source documents |
| Retrieval | scikit-learn | TF-IDF and cosine similarity |
| Generation | Qwen2.5-0.5B-Instruct | Write answers using retrieved context |
| Inference | Transformers and PyTorch | Run the model on CPU |
| Interface | HTML, CSS, and JavaScript | Ask questions and inspect sources |
| Automation | GitHub Actions | Run tests and synchronize application files |
| Deployment target | Hugging Face Docker Spaces | Build and host the public application |
The complete flow is:
Markdown documents
↓
Overlapping chunks
↓
TF-IDF index
↑
Question → retrieval → relevant passages
↓
context + question
↓
Qwen model
↓
answer + sources
I chose lexical retrieval to keep the project small and easy to reproduce. TF-IDF represents words and phrases as sparse vectors; it is not a semantic embedding model. It works best when a question shares vocabulary with the documents and is less flexible with synonyms or paraphrases.
1. Prepare and split the documents
Source files live in data/. Each document is split into windows of 120 words, with a 25-word overlap.
The overlap preserves information near chunk boundaries. These sizes are measured in words, not in the model's tokenizer tokens; those are different units.
The chunking function is:
def split_text(text: str, size: int = 120, overlap: int = 25) -> list[str]:
if size <= 0 or overlap < 0 or overlap >= size:
raise ValueError("Expected size > overlap >= 0.")
words = text.split()
chunks = []
for start in range(0, len(words), size - overlap):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
Each chunk keeps its source filename and chunk number. These metadata make it possible to trace the retrieved context back to its origin.
2. Build the retriever
I use TfidfVectorizer to index the passages. The configuration lowercases text, normalizes accents, considers individual words and pairs of words, and removes English stop words.
Here is the search method inside Retriever:
def search(self, question: str, top_k: int = 2,
min_score: float = 0.08) -> list[Hit]:
if not 1 <= top_k <= 5:
raise ValueError("top_k must be between 1 and 5.")
query = self.vectorizer.transform([question])
scores = cosine_similarity(query, self.matrix).ravel()
order = scores.argsort()[::-1]
return [
Hit(self.chunks[i], float(scores[i]))
for i in order[:top_k]
if scores[i] >= min_score
]
The API retrieves up to two passages. The 0.08 threshold is a heuristic for this demo, not a probability that the answer is correct. It should be calibrated when the corpus changes.
If no passages reach the threshold, the application returns this message directly:
I could not find enough information in the documents to answer that question.
The model is not called in that case. This prevents generation when retrieval is empty, although it does not detect every case of irrelevant context.
3. Construct the model's context
Retrieved passages receive identifiers such as [1] and [2]. The system message asks the model to answer in English, use only facts from the context, and cite the corresponding source number.
General rules stay in the system message. The documents and question are placed in the user message with this structure:
CONTEXT:
[1] library.md (chunk 1)
...retrieved content...
QUESTION:
How many days can I borrow library books?
ANSWER:
The instructions also say to treat commands inside retrieved documents as data. This is a basic mitigation and does not provide complete protection against prompt injection.
4. Generate with an open model on CPU
The generator uses Qwen2.5-0.5B-Instruct, loaded with Transformers. I selected a small model so the demonstration can run on CPU.
The code pins the model revision to keep the weights consistent. The first question downloads and loads the model; later questions reuse the same instance.
This excerpt shows generation and decoding of only the newly generated tokens:
text = self.tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
inputs = self.tokenizer(text, return_tensors="pt")
with self.torch.inference_mode():
output = self.model.generate(
**inputs,
max_new_tokens=180,
do_sample=False,
repetition_penalty=1.1,
pad_token_id=self.tokenizer.eos_token_id,
)
new_tokens = output[0, inputs["input_ids"].shape[1]:]
answer = self.tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
The application does not require a commercial generation API key. Inference runs on the application's server, which needs enough CPU and memory. The first download may take several minutes, and a model of this size has limitations in comprehension and instruction following.
5. Expose the pipeline through FastAPI
The POST /api/ask endpoint receives a JSON question:
{
"question": "How many days can I borrow library books?"
}
The API validates the input, retrieves context, calls the generator when appropriate, and returns:
-
answer: the generated answer or insufficient-evidence message. -
sources: source files, chunk numbers, retrieved text, and similarity scores. -
generated: whether the generator was called. -
seconds: the time spent processing the question.
Only one generation runs at a time to limit CPU use. A busy model produces a 429 response; a model loading or execution failure produces a 503 response.
The interface labels the evidence as retrieved sources. Displaying a source does not automatically prove that every generated claim is supported by it, and the model may omit or misuse requested citations.
6. Run the project on Windows
With Python 3.11 installed, use these PowerShell commands:
git clone https://github.com/Dayan-18/Retrieval-Augmented-Generation_Dayan.git
cd Retrieval-Augmented-Generation_Dayan
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install --upgrade pip
.\.venv\Scripts\python.exe -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe -m uvicorn app:app --host 127.0.0.1 --port 7860
Open http://localhost:7860. There is no need to activate the virtual environment because the commands call its Python executable directly.
7. Automate deployment to Hugging Face
The project includes a Dockerfile and a GitHub Actions workflow to prepare publication on a public hosting service.
Docker Spaces runs a custom container and lets us configure the application's exposed port. This project listens on 0.0.0.0:7860, uses a non-root container user, and sets sdk: docker and app_port: 7860 in the README metadata.
The initial setup is:
- Create a public GitHub repository and push the code.
- Create a public Hugging Face Space with the Docker SDK.
- Create a token with write access to that Space.
- Add
HF_TOKENas a GitHub repository secret. - Add
HF_SPACE_IDas a repository variable, usingusername/space-name. - Run Test and deploy CampusRAG from the Actions tab.
The token is used only for publishing files and is stored through GitHub Actions Secrets. It is not committed to the repository or sent to the visitor's browser.
The automated flow is:
Push to main
↓
Retrieval and API tests
↓
If tests pass and HF_SPACE_ID is configured
↓
Synchronize files with the Space
↓
Hugging Face builds the container
↓
Check a real question at the public URL
Synchronization uses HfApi.upload_folder with an explicit allowlist of runtime files. It does not upload cached model weights or Git history.
A successful workflow confirms that files were uploaded, but we still need to check that the Space reaches Running and generates an answer. Later pushes to main repeat the process automatically.
8. Verify the application
The lightweight test suite checks chunking, retrieval, context construction, input validation, and API error handling:
.\.venv\Scripts\python.exe -m pip install -r requirements-test.txt
.\.venv\Scripts\python.exe -m unittest discover -s tests -v
API tests use a generator test double, so GitHub Actions can run them without downloading model weights. All 15 tests passed during local verification of the English version.
The repository also includes a real-model integration check:
.\.venv\Scripts\python.exe scripts\smoke_model.py
It asks about the book loan period and checks for a generated answer, retrieval of library.md, and the key fact of seven days. Its scope is limited: it does not evaluate every possible answer.
During the local real-model check, the application returned “You can borrow up to three library books for seven calendar days.” The retrieved evidence came from library.md.
Questions outside the corpus are useful checks too. Inspect whether their retrieved passages are relevant. Retrieval and generation should be evaluated separately: finding the correct document does not guarantee a correct answer.
Limitations and next steps
This implementation prioritizes a complete RAG pipeline that is easy to read and run. Its main limits are lexical retrieval, a small language model, and the absence of a broad evaluation dataset.
Possible improvements include multilingual embeddings, hybrid search, a reranker, and verified question-answer pairs for evaluation. A service for real users would also need authentication, usage quotas, and privacy controls appropriate to its documents and audience.
Building CampusRAG helped me separate the responsibilities of the pipeline: documents supply facts, retrieval selects evidence, and the model writes the answer. That separation makes failures easier to investigate and lets us update the system's knowledge without changing the model's weights.
Project source code: Dayan-18/Retrieval-Augmented-Generation_Dayan on GitHub.
Top comments (0)