AI Document Question Answering Project

Artificial Intelligence project 04

AI Document Question Answering Project

Build a complete document question answering workflow with reproducible Python code, transparent inputs, reviewable output, and responsible-use limits.

Explore AI training in VizagView all project ideas

AI objective

Answer a question by returning the highest-scoring source sentence and its document identifier.

Data or knowledge source

Three short synthetic policy documents about attendance, projects, and technical support, indexed at sentence level.

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

Build sentence-level TF-IDF vectors, compare the question by cosine similarity, and refuse to answer when the best score is below the threshold.

Validation checklist

  • Answers carry a source identifier
  • Unknown questions produce a refusal
  • Sentence boundaries are preserved
  • The score is available for error analysis

Complete Python code

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

"""Answer a question by returning the most relevant source sentence."""

from __future__ import annotations

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


DOCUMENTS = {
    "attendance": "The attendance requirement is at least 80 percent of scheduled sessions. Approved exceptions are reviewed by the training team.",
    "projects": "Portfolio projects are reviewed during designated mentoring sessions. Feedback focuses on correctness, documentation, and presentation.",
    "support": "Technical questions can be submitted through the published support channel. Response time depends on course schedule and issue complexity.",
}


@dataclass(frozen=True)
class Answer:
    text: str
    source: str | None
    score: float


def build_sentence_index(documents: dict[str, str] = DOCUMENTS):
    rows = []
    for source, text in documents.items():
        for sentence in re.split(r"(?<=[.!?])\s+", text):
            if sentence.strip():
                rows.append((source, sentence.strip()))
    vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
    matrix = vectorizer.fit_transform([row[1] for row in rows])
    return rows, vectorizer, matrix


def answer_question(question: str, threshold: float = 0.12) -> Answer:
    rows, vectorizer, matrix = build_sentence_index()
    scores = cosine_similarity(vectorizer.transform([question]), matrix)[0]
    index = int(scores.argmax())
    score = float(scores[index])
    if score < threshold:
        return Answer("The supplied documents do not contain a confident answer.", None, score)
    return Answer(rows[index][1], rows[index][0], score)


def main() -> None:
    for question in ("What attendance is required?", "When are projects reviewed?", "What is the parking fee?"):
        print(question, "->", answer_question(question))


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_document_question_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

An extractive answer, source name, and retrieval score.

Accuracy, privacy, and responsible-use limits

Retrieval similarity does not prove that a sentence fully answers the question. Keep documents authoritative and current, show source context, and escalate ambiguous cases.

Ways to extend the project

Add document chunking, hybrid keyword retrieval, metadata filters, multiple citations, answer-span evaluation, and document freshness checks.

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.