🧠 AI with Python — 📚 Multi-document Question Answering
Posted on: November 30, 2026
Description:
The workshop closes its tool desk at a specific time. Borrowed kits have a separate return deadline. A visitor needs both facts to plan a Saturday visit. If a search returns only the opening-hours guide, the answer can be accurate and still be incomplete.
Search for each piece of evidence
The notebook supplies two subquestions explicitly. Each gets its own TF-IDF search over three fictional workshop documents. Cosine similarity ranks the passages by their overlap with the question after weighting terms by their rarity in the collection. A single broad search can work, but its best passages might all cover the same half of a question.
| Subquestion | Selected passage | Supported answer |
|---|---|---|
| When does the tool desk close on Saturday? | hours.md#desk |
4 pm on Saturday |
| When is a borrowed kit due back? | loans.md#return |
By noon on the next open day |
The third passage, lockers.md#access, describes digital keys. All three passages have stable IDs, so we can trace a claim back to its source after retrieval.
Let the reader choose a line
A local language model, llama3.2:1b through Ollama, sees one subquestion and the numbered lines in its retrieved passage. It returns a line ID or NONE. Python copies the selected line and attaches its passage ID. This is an extractive answer: when the policy says “next open day,” the system preserves that wording. The documents give no basis for promising Monday.
for row in answer(QUESTIONS, DOCUMENTS):
print(row["answer"], row["source"])
Remove the loan policy
With the same questions and only the hours and locker guides available, “borrowed” still retrieves the locker passage for the kit question. In the recorded run, the reader chose “Workshop lockers open with a digital key.” The citation pointed to a real sentence. That sentence said nothing about a deadline.
The notebook includes a deliberately narrow guard: accept a selected quote only if at least two distinct content words also appear in the question. The locker sentence shared zero. The final answer kept the Saturday closing time and returned “Insufficient evidence.” for the kit deadline.
without_loans = {key: lines for key, lines in DOCUMENTS.items()
if key != "loans.md#return"}
partial = answer(QUESTIONS, without_loans)
What this test tells us
A file can be relevant while a particular sentence is wrong. An overlap check can also accept a wrong day or reject a correct paraphrase. Test retrieval, the selected sentence, and the missing-source response separately. Try changing Saturday to Friday and inspect which line the model chooses.
The executed notebook includes the full three-document fixture, the local model call, and both runs.
Code Snippet:
"""Multi-document QA over a fictional workshop library, with one citation per claim."""
import json
import os
from urllib.request import Request, urlopen
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Each file contains one short passage. Stable IDs survive filtering and reranking.
DOCUMENTS = {
"hours.md#desk": ["On Saturday, the tool desk closes at 4 pm.",
"On Friday, the tool desk closes at 6 pm."],
"loans.md#return": ["A borrowed kit is due by noon on the next open day.",
"Return the kit to a staff member."],
"lockers.md#access": ["Workshop lockers open with a digital key.",
"Borrowed keys stay on site."],
}
QUESTIONS = ["When does the tool desk close on Saturday?", "When is a borrowed kit due back?"]
def retrieve(question, documents):
"""Return one passage by lexical similarity, or None when no terms match."""
if not documents:
return None
ids = list(documents)
vectorizer = TfidfVectorizer(stop_words="english")
matrix = vectorizer.fit_transform(" ".join(documents[key]) for key in ids)
scores = cosine_similarity(vectorizer.transform([question]), matrix)[0]
winner = int(scores.argmax())
return ids[winner] if scores[winner] > 0 else None
def select_line(question, lines):
"""Ask a local reader for a line ID. Text and source are resolved by Python."""
choices = {str(i): line for i, line in enumerate(lines, 1)}
schema = {"type": "object", "properties": {
"line": {"type": "string", "enum": ["NONE", *choices]}}, "required": ["line"]}
prompt = ("Choose ONE line that explicitly answers the question with the requested "
"fact. A related topic alone is insufficient. If no line answers it, use NONE. "
"Respond with a JSON object containing line.\n"
f"Question: {question}\nLines: {json.dumps(choices)}")
payload = {"model": "llama3.2:1b", "prompt": prompt, "format": schema,
"stream": False, "options": {"temperature": 0, "seed": 42}}
base = os.getenv("OLLAMA_HOST", "http://127.0.0.1:11434")
req = Request(base.rstrip("/") + "/api/generate", data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"})
with urlopen(req, timeout=120) as response:
selected = json.loads(json.load(response)["response"])["line"]
if selected != "NONE" and selected not in choices:
raise ValueError("Reader returned an invalid line ID")
return choices.get(selected)
def shared_terms(question, line):
"""A small lexical guard for this demo, not a semantic verifier."""
tokenize = TfidfVectorizer(stop_words="english").build_analyzer()
return set(tokenize(question)) & set(tokenize(line))
def answer(parts, documents):
rows = []
for part in parts:
source = retrieve(part, documents)
quote = select_line(part, documents[source]) if source else None
if quote and len(shared_terms(part, quote)) < 2:
quote = None
rows.append({"question": part, "answer": quote or "Insufficient evidence.",
"source": source if quote else None})
return rows
No comments yet. Be the first to comment!