Retrieval-Augmented Answering RAG Project

Artificial Intelligence project 12

Retrieval-Augmented Answering RAG Project

Build a complete retrieval-augmented answering (rag) workflow with reproducible Python code, transparent inputs, reviewable output, and responsible-use limits.

Explore AI training in VizagView all project ideas

AI objective

Retrieve relevant passages and return an extractive, source-cited answer rather than generating unsupported text.

Data or knowledge source

Four synthetic handbook passages with stable source identifiers.

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install scikit-learn
  • About 45-60 minutes to build and review

How the system works

Fit TF-IDF over passages and the query, rank cosine similarity, filter by threshold, combine retrieved source sentences, and return source IDs and scores.

Validation checklist

  • Every answer carries its source identifiers
  • No result below threshold is included
  • No model generates new facts
  • Source and score arrays remain aligned

Complete Python code

Save the program as ai_retrieval_augmented_answering.py. The code runs locally and requires no paid API key or model download.

"""A small extractive RAG-style pipeline with source citations."""

from __future__ import annotations

from dataclasses import dataclass
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


PASSAGES = [
    ("handbook-attendance", "Learners qualify for the attendance requirement when they attend at least 80 percent of scheduled sessions."),
    ("handbook-projects", "Final projects should include source code, setup instructions, tests, and a short explanation of limitations."),
    ("handbook-certificates", "Certificate eligibility is reviewed after attendance and required project work are completed."),
    ("handbook-support", "Technical questions should include the error message, environment details, and steps to reproduce the issue."),
]


@dataclass(frozen=True)
class RagAnswer:
    answer: str
    sources: tuple[str, ...]
    scores: tuple[float, ...]


def answer(question: str, top_k: int = 2, threshold: float = 0.1) -> RagAnswer:
    texts = [text for _, text in PASSAGES]
    vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
    matrix = vectorizer.fit_transform(texts + [question])
    scores = cosine_similarity(matrix[-1], matrix[:-1])[0]
    selected = [int(i) for i in scores.argsort()[::-1][:top_k] if scores[i] >= threshold]
    if not selected:
        return RagAnswer("The supplied knowledge base does not contain a confident answer.", (), ())
    sentences = []
    for index in selected:
        sentences.extend(part.strip() for part in re.split(r"(?<=[.!?])\s+", texts[index]) if part.strip())
    return RagAnswer(" ".join(sentences), tuple(PASSAGES[i][0] for i in selected), tuple(float(scores[i]) for i in selected))


def main() -> None:
    result = answer("What should the final project contain?")
    print(result.answer)
    print("Sources:", ", ".join(result.sources))
    print("This extractive demo returns source text and does not invent an answer.")


if __name__ == "__main__":
    main()

Run the project

  1. Create and activate a virtual environment.
  2. Install dependencies with python -m pip install scikit-learn when packages are required.
  3. Run python ai_retrieval_augmented_answering.py.
  4. Review confidence, fallbacks, sources, or error metrics rather than accepting output automatically.
  5. Test additional normal, edge, unsupported, and adversarial inputs.

Expected output

A grounded extractive answer, cited source IDs, and retrieval scores.

Accuracy, privacy, and responsible-use limits

This demonstrates retrieval, not a production generative RAG system. Real systems need authoritative ingestion, permissions, versioning, chunk evaluation, citation verification, and injection defences.

Ways to extend the project

Add hybrid retrieval, embeddings, reranking, access controls, document versioning, a local language model, citation checking, and retrieval benchmarks.

Continue learning Artificial Intelligence

Try the next project, return to the Softenant project library, or explore the AI training in Vizag for guided NLP, retrieval, evaluation, automation, and responsible AI practice.