Build a Cited Wikipedia Research Helper in Python—with Explicit Session Memory
A Wikipedia research helper should not answer “from memory” and add a link afterward. It should fetch a specific page revision, keep the source URL and revision metadata beside the extract, and make the application—not the model—decide which session and tools are allowed.
The Python workflow below searches Wikipedia through the official MediaWiki Action API, retrieves a plain-text lead with its current revision ID and timestamp, and saves explicit session state to JSON. An optional language model can summarize that evidence later, but it does not get to invent or silently replace the source.
✅ The result: a small, testable evidence tool with citations and session continuity—not a claim that Wikipedia or an agent is automatically correct.
Replace “real-time answer” with revision-stamped evidence
Wikipedia can change quickly, but “current page” is not the same as verified real-time truth. A page may be incomplete, disputed, vandalized, or simply unsuitable for the question.
The useful guarantee is narrower: at a recorded time, the program retrieved an extract from a page with a particular URL, revision ID, and revision timestamp. Those fields let a reviewer identify what was used.
| Field | Why save it |
|---|---|
| Page title | shows which search result was selected |
| Full URL | gives the reader a source to open |
| Revision ID | identifies a specific page revision |
| Revision timestamp | shows when that revision was saved |
| Extract | preserves the text supplied as evidence |
A model-generated answer without these fields is hard to audit. A source bundle with them can be checked even if the page changes later.
Keep the search tool separate from conversation state
This tutorial uses two small components:
WikipediaClientperforms search and evidence retrieval.ResearchSessionstores the selected title, evidence records, and user questions.
Neither component decides whether a statement is true. The client transports source data; the session preserves application state. If a language model is added, it receives a bounded evidence block rather than unrestricted web access.
This separation also avoids tying the tutorial to one rapidly changing agent framework. The official MediaWiki request remains visible, and the memory file can be inspected with any text editor.
Send a descriptive User-Agent
Wikimedia’s API etiquette documentation asks clients to identify themselves with a descriptive User-Agent and contact information. Do not impersonate a popular browser.
The client enforces that boundary:
class WikipediaClient:
def __init__(
self,
user_agent,
api_url="https://en.wikipedia.org/w/api.php",
http=None,
timeout=15.0,
):
if not user_agent.strip() or "contact" not in user_agent.lower():
raise ValueError(
"Use a descriptive User-Agent with contact information"
)
self.api_url = api_url
self.timeout = timeout
self.http = http or requests.Session()
self.http.headers.update({"User-Agent": user_agent})
Use a project URL, monitored email address, or Wikimedia user page that a service operator can actually reach. The example checks for the word contact only as a tutorial guardrail; a production policy should validate your organization’s approved identifier format.
Search only the article namespace
MediaWiki’s list=search module accepts the query in srsearch. Restricting srnamespace to 0 keeps the result list in the main article namespace for this research use case.
def search(self, query, limit=5):
query = query.strip()
if not query:
raise ValueError("query must not be blank")
if not 1 <= limit <= 10:
raise ValueError("limit must be between 1 and 10")
payload = self._get(
{
"action": "query",
"list": "search",
"srsearch": query,
"srnamespace": 0,
"srlimit": limit,
"format": "json",
"formatversion": 2,
}
)
rows = payload.get("query", {}).get("search", [])
return [
row["title"]
for row in rows
if isinstance(row, dict) and row.get("title")
]
Search returns candidates, not a final fact. Do not automatically assume the first title represents the user’s intent when names, places, or abbreviations are ambiguous. Show the candidates or apply a documented selection rule.
Fetch text, URL, and revision in one request
The evidence request combines three MediaWiki properties:
extractssupplies a plain-text introductory extract;infowithinprop=urlsupplies the full page URL; andrevisionswithrvprop=ids|timestampsupplies revision identity.
payload = self._get(
{
"action": "query",
"prop": "extracts|info|revisions",
"titles": title,
"redirects": 1,
"exintro": 1,
"explaintext": 1,
"exsentences": sentences,
"inprop": "url",
"rvprop": "ids|timestamp",
"rvlimit": 1,
"format": "json",
"formatversion": 2,
}
)
The implementation rejects a missing page and an incomplete response. It does not return an empty extract as successful evidence.
The parsed record has a fixed shape:
@dataclass(frozen=True)
class Evidence:
title: str
url: str
revision_id: int
revision_timestamp: str
extract: str
📌 A revision timestamp describes the page revision, not when the underlying historical event occurred and not when an external claim was verified by an independent source.
Save session state explicitly
A follow-up question needs an explicit referent. The session records the currently selected title, the retrieved evidence, and the question trail:
@dataclass
class ResearchSession:
session_id: str
selected_title: str | None = None
evidence: list[Evidence] = field(default_factory=list)
questions: list[str] = field(default_factory=list)
def add_evidence(self, item):
self.selected_title = item.title
self.evidence = [
existing
for existing in self.evidence
if existing.url != item.url
]
self.evidence.append(item)
def add_question(self, question):
question = question.strip()
if not question:
raise ValueError("question must not be blank")
self.questions.append(question)
This is application memory, not model memory. The application can show “Current topic: Alan Turing” before accepting “When was he born?” and can require confirmation before switching to another title.
The session file is written through a temporary file and then replaced:
def save(self, path):
path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"session_id": self.session_id,
"selected_title": self.selected_title,
"evidence": [asdict(item) for item in self.evidence],
"questions": self.questions,
}
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8",
)
temporary.replace(path)
The loader also requires an expected session ID. This is only a minimal isolation check. A web application still needs authenticated ownership, access control, storage permissions, retention rules, and protection against path traversal.
Treat retrieved text as evidence, not instructions
Pages and search results are external content. A language model may encounter text that resembles commands, system messages, or requests to call another tool.
The evidence object produces a labeled block with the source fields:
def prompt_block(self):
return (
"<evidence>\n"
f"<title>{self.title}</title>\n"
f"<url>{self.url}</url>\n"
f"<revision_id>{self.revision_id}</revision_id>\n"
f"<revision_timestamp>{self.revision_timestamp}</revision_timestamp>\n"
f"<quoted_text>{self.extract}</quoted_text>\n"
"</evidence>"
)
⚠️ Tags improve structure; they do not make untrusted text safe. The system policy should say that evidence is quoted data, tool permissions must be enforced outside the model, and consequential actions require separate authorization.
An answer generator should also be required to return citations that match an evidence URL. If the evidence does not support an answer, the correct result is “not established by the retrieved page,” followed by another source search—not a confident guess.
Run the evidence helper
Install Requests:
py -m pip install "requests>=2.32,<3"
Save the full implementation as wikipedia_evidence.py, then run:
py wikipedia_evidence.py "Alan Turing" \
--user-agent "MyResearchTool/1.0 (contact: you@example.com)" \
--session research-001 \
--output sessions/research-001.json
PowerShell uses the backtick rather than the backslash for native multiline commands, so it may be simpler to enter the command on one line.
The program:
- searches the main namespace;
- selects the first candidate for this CLI demonstration;
- fetches the introductory extract and revision metadata;
- records the query and evidence in one session; and
- prints a JSON evidence record.
A user-facing application should display multiple candidates before selection when the query is ambiguous.
Test the HTTP boundary without depending on live pages
Tests should not fail merely because a live page was edited. The included suite injects a fake HTTP client and fixed API responses.
One test confirms that search stays in namespace 0 and respects the result limit:
def test_search_uses_main_namespace_and_limit(self):
http = FakeHttp([
{"query": {"search": [{"title": "Alan Turing"}]}}
])
client = WikipediaClient(
"EvidenceTool/1.0 (contact: test@example.com)",
http=http,
)
self.assertEqual(
client.search("Alan Turing", limit=3),
["Alan Turing"],
)
params = http.calls[0]["params"]
self.assertEqual(params["srnamespace"], 0)
self.assertEqual(params["srlimit"], 3)
Another test checks that a returned page becomes revision-stamped evidence. Additional tests cover missing pages, session save/load, and rejection of a mismatched session ID.
Run:
py -m unittest -v test_wikipedia_evidence.py
Five deterministic tests passed while preparing this guide. A separate live smoke request also completed the search and evidence request against English Wikipedia. The tests establish client behavior; they do not certify the truth of Wikipedia content or a language model’s summary.
Handle predictable failures
The program should stop or ask for help when:
- search returns no title;
- several candidates could match the query;
- the page is missing or redirected unexpectedly;
- the extract or revision fields are absent;
- the API returns an error or times out;
- the requested session does not belong to the authenticated user;
- the source does not answer the user’s question; or
- a claim needs a primary or more authoritative source.
Retries should be bounded. Cache evidence where appropriate and keep the revision metadata. Wikimedia’s API etiquette guidance recommends caching rather than repeating identical requests unnecessarily.
Requests raises HTTP errors through raise_for_status(), and the client additionally checks MediaWiki’s JSON-level error field. Network success alone is not application success.
Know what “memory” should not do
Do not save every page forever just because storage is cheap. Decide what the session needs, how long it should exist, and how a user deletes it.
Do not blend different users into one global chat buffer. Do not allow a model-generated session ID to select storage. Do not let an old answer become the source for a new answer when the original evidence is available.
Conversation history can help resolve “he,” “that paper,” or “the second result,” but the final factual claim should point back to evidence. A previous assistant message is not an independent source.
Add a model only after the evidence path works
A model can help synthesize several extracts or turn a long lead into a short answer. Add it after the deterministic path is tested:
- the application selects the session;
- the tool retrieves and records evidence;
- the application builds a bounded evidence packet;
- the model drafts an answer with source URLs;
- code validates that cited URLs came from the packet; and
- the interface shows the answer and sources together.
Do not expose chain-of-thought or rely on verbose agent logs as proof. Tool calls, selected sources, revision metadata, validation outcomes, and user-visible citations are the useful audit trail.
For questions involving medicine, law, finance, safety, or a living person, Wikipedia should usually be a starting point rather than the final authority. Follow its citations to suitable primary or authoritative sources.
Documentation used for the API contract
- MediaWiki Search API
- MediaWiki TextExtracts extension
- MediaWiki Info API
- MediaWiki Revisions API
- MediaWiki API etiquette
- Requests quickstart
- Python JSON documentation
A useful research assistant is not defined by how many tools it can call. It is defined by whether a reader can see which source was selected, which revision was used, what the session remembered, and where the system correctly refused to make a claim.
Comments
Post a Comment