{"slug": "graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis", "title": "Graph-RAG for Enterprise Documents: Building a Knowledge Graph from PDFs, Wikis, and Databases", "summary": "A tutorial published on MachineLearningMastery.com details how to build a three-tier Graph-RAG system that fuses a live SQLite service-registry database, wiki runbooks, and PDFs into one prioritized knowledge source, so an internal assistant returns a single answer when sources conflict. The approach assigns the database Priority 1, wiki pages Priority 2, and a Chroma vector store of PDF text extracted with pdfplumber Priority 3, resolving conflicts through explicit priority rules written into the prompt rather than a routing algorithm. The article cites an IDC study sponsored by Neo4j finding organizations grounding generative AI in graph-based context cut hallucination rates by 44 percent on average, with one life sciences company dropping from a 20 to 40 percent hallucination rate to 2 to 5 percent.", "body_md": "In this article, you will learn how to build a Graph-RAG system that combines a live database, wiki pages, and PDFs into one prioritized knowledge source, so your assistant gives a single, correct answer when those sources disagree.\n\nTopics we will cover include:\n\n- How to turn database rows and wiki runbooks into prioritized facts in a simple quad store.\n- How to extract, chunk, and embed PDF text with pdfplumber and Chroma as a vector fallback.\n- How to fuse all three tiers into one prompt with explicit priority rules that resolve conflicts.\n\nAn engineer pings your internal AI assistant at 11 p.m. and asks who’s on-call for the payments service. The assistant has read the wiki, indexed every PDF in the shared drive, and has a live connection to the service registry. It should be a trivial question. But the wiki was last edited four months ago, the on-call rotation has changed twice since then, and the database has the current answer sitting in a single row. If retrieval treats all three sources as equally trustworthy text, there’s a real chance it hands your engineer someone who left the rotation months ago.\n\nThat’s the exact failure covered in the article [Beyond Vector Search: Building a Deterministic 3-Tiered Graph-RAG System](https://machinelearningmastery.com/beyond-vector-search-building-a-deterministic-3-tiered-graph-rag-system/), where vector-only RAG confuses which team a basketball player currently plays for, because multiple team names sit close together in embedding space. The fix: three retrieval tiers (an absolute-facts graph, a background-stats graph, and a vector database), fused through explicit priority rules written into the prompt instead of a routing algorithm. This article takes that same architecture and points it at a live database, a set of wiki pages, and a batch of PDFs, all feeding one fused answer.\n\nThe approach has real-world backing: an [IDC study sponsored by Neo4j found organizations grounding generative AI in graph-based context cut hallucination rates by 44 percent on average](https://neo4j.com/blog/news/research-finds-enterprises-earn-230-percent-roi/), and one life sciences company went from a 20 to 40 percent hallucination rate down to 2 to 5 percent.\n\n### The Scenario\n\nWe’ll build for a fictional platform team at “Northwind,” running three services: **payments-service, checkout-service, notifications-service**. Three sources describe them. A **service registry database** (Postgres in reality, SQLite here) holds the owner, on-call engineer, status, version, and SLA tier, live and always current, so it becomes **Priority 1**.\n\nA **wiki space** of runbooks is thorough but drifts stale the moment nobody updates it after a rotation change, so it becomes **Priority 2**, useful until it conflicts with something more current. A **folder of PDFs** (an SLA doc, an incident postmortem) adds narrative context no structured source holds, so it becomes **Priority 3**, our vector fallback.\n\nWe’ll deliberately plant one conflict: the wiki’s payments runbook names an on-call engineer the database no longer agrees with. That conflict is the whole reason this architecture exists.\n\n### Prerequisites\n\nYou’ll need Python 3.10+ and a local model server. Like the original article, we’ll use [Ollama](https://ollama.com/) with **llama3.2**; swapping in a hosted API later only changes the one function that sends the final request.\n\n```\nollama pull llama3.2\n\nmkdir graphrag-enterprise && cd graphrag-enterprise\nmkdir -p data/wiki data/pdfs\npip install chromadb spacy pdfplumber requests\npython -m spacy download en_core_web_sm\n\n123456\n\nollama pull llama3.2 mkdir graphrag-enterprise && cd graphrag-enterprisemkdir -p data/wiki data/pdfspip install chromadb spacy pdfplumber requestspython -m spacy download en_core_web_sm\n```\n\n**[chromadb](https://docs.trychroma.com/)** is our Priority 3 vector store. **[spacy](https://pypi.org/project/spacy/)** handles named entity recognition so we can pull service names out of a question. **[pdfplumber](https://pypi.org/project/pdfplumber/)** extracts PDF text more reliably than most lightweight alternatives. **[requests](https://pypi.org/project/requests/)** talks to Ollama’s local REST API.\n\n## Step 1: The Quad Store and the CMDB (Priority 1)\n\nPriorities 1 and 2 both need a home: a Subject-Predicate-Object-Context (SPOC) quad store. Rather than pull in the original tutorial’s [QuadStore library](https://github.com/mmmayo13/quadstore), here’s a minimal version built from scratch:\n\n``` python\n# quadstore.py\nclass QuadStore:\n    def __init__(self):\n        self._quads = []\n\n    def add(self, subject, predicate, object, context=\"general\"):\n        self._quads.append((subject, predicate, object, context))\n\n    def query(self, subject=None, predicate=None, object=None, context=None):\n        results = []\n        for s, p, o, c in self._quads:\n            if subject is not None and s != subject: continue\n            if predicate is not None and p != predicate: continue\n            if object is not None and o != object: continue\n            if context is not None and c != context: continue\n            results.append((s, p, o, c))\n        return results\n\n    def __len__(self):\n        return len(self._quads)\n\n1234567891011121314151617181920\n\n# quadstore.pyclass QuadStore:    def __init__(self):        self._quads = []     def add(self, subject, predicate, object, context=\"general\"):        self._quads.append((subject, predicate, object, context))     def query(self, subject=None, predicate=None, object=None, context=None):        results = []        for s, p, o, c in self._quads:            if subject is not None and s != subject: continue            if predicate is not None and p != predicate: continue            if object is not None and o != object: continue            if context is not None and c != context: continue            results.append((s, p, o, c))        return results     def __len__(self):        return len(self._quads)\n```\n\nTwo methods, four fields, and any argument left **None** acts as a wildcard. The original library indexes these fields for constant-time lookups, which matters at millions of facts; a plain scan is fine for one team’s service catalog.\n\nNow the database itself: our service registry, or configuration management database (CMDB). SQLite keeps the tutorial dependency-free; swapping in **psycopg2** and a Postgres connection string later is an isolated change.\n\n``` python\n# setup_cmdb.py\nimport sqlite3\n\nDB_PATH = \"data/cmdb.db\"\nSCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS services (\n    service_name TEXT PRIMARY KEY, owner_team TEXT NOT NULL,\n    on_call_engineer TEXT NOT NULL, status TEXT NOT NULL,\n    current_version TEXT NOT NULL, last_deployed TEXT NOT NULL, sla_tier TEXT NOT NULL\n);\n\"\"\"\nSERVICES = [\n    (\"payments-service\", \"Payments Platform\", \"Amara Chen\", \"active\", \"4.2.1\", \"2026-09-10\", \"Tier-1 (99.95%)\"),\n    (\"checkout-service\", \"Checkout Experience\", \"Diego Ruiz\", \"active\", \"2.9.0\", \"2026-08-22\", \"Tier-1 (99.95%)\"),\n    (\"notifications-service\", \"Platform Comms\", \"Priya Nair\", \"deprecated\", \"1.4.3\", \"2025-11-02\", \"Tier-2 (99.9%)\"),\n]\n\nconn = sqlite3.connect(DB_PATH)\nconn.execute(SCHEMA)\nconn.executemany(\"INSERT OR REPLACE INTO services VALUES (?, ?, ?, ?, ?, ?, ?)\", SERVICES)\nconn.commit()\nconn.close()\n\n12345678910111213141516171819202122\n\n# setup_cmdb.pyimport sqlite3 DB_PATH = \"data/cmdb.db\"SCHEMA = \"\"\"CREATE TABLE IF NOT EXISTS services (    service_name TEXT PRIMARY KEY, owner_team TEXT NOT NULL,    on_call_engineer TEXT NOT NULL, status TEXT NOT NULL,    current_version TEXT NOT NULL, last_deployed TEXT NOT NULL, sla_tier TEXT NOT NULL);\"\"\"SERVICES = [    (\"payments-service\", \"Payments Platform\", \"Amara Chen\", \"active\", \"4.2.1\", \"2026-09-10\", \"Tier-1 (99.95%)\"),    (\"checkout-service\", \"Checkout Experience\", \"Diego Ruiz\", \"active\", \"2.9.0\", \"2026-08-22\", \"Tier-1 (99.95%)\"),    (\"notifications-service\", \"Platform Comms\", \"Priya Nair\", \"deprecated\", \"1.4.3\", \"2025-11-02\", \"Tier-2 (99.9%)\"),] conn = sqlite3.connect(DB_PATH)conn.execute(SCHEMA)conn.executemany(\"INSERT OR REPLACE INTO services VALUES (?, ?, ?, ?, ?, ?, ?)\", SERVICES)conn.commit()conn.close()\n```\n\n**notifications-service** is marked **deprecated** on purpose; we’ll use that later. Run it, and you have a real **.db** file. Next, convert those rows into Priority 1 facts, querying live every time so they’re never stale by construction:\n\n``` python\n# ingest_db.py\nimport sqlite3\nfrom quadstore import QuadStore\n\nFIELD_TO_PREDICATE = {\n    \"owner_team\": \"owner_team\", \"on_call_engineer\": \"on_call_engineer\",\n    \"status\": \"status\", \"current_version\": \"current_version\",\n    \"last_deployed\": \"last_deployed\", \"sla_tier\": \"sla_tier\",\n}\n\ndef build_p1_store(db_path=\"data/cmdb.db\"):\n    qs = QuadStore()\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    rows = conn.execute(\"SELECT * FROM services\").fetchall()\n    conn.close()\n    for row in rows:\n        for field, predicate in FIELD_TO_PREDICATE.items():\n            qs.add(row[\"service_name\"], predicate, row[field], \"cmdb\")\n    return qs\n\n1234567891011121314151617181920\n\n# ingest_db.pyimport sqlite3from quadstore import QuadStore FIELD_TO_PREDICATE = {    \"owner_team\": \"owner_team\", \"on_call_engineer\": \"on_call_engineer\",    \"status\": \"status\", \"current_version\": \"current_version\",    \"last_deployed\": \"last_deployed\", \"sla_tier\": \"sla_tier\",} def build_p1_store(db_path=\"data/cmdb.db\"):    qs = QuadStore()    conn = sqlite3.connect(db_path)    conn.row_factory = sqlite3.Row    rows = conn.execute(\"SELECT * FROM services\").fetchall()    conn.close()    for row in rows:        for field, predicate in FIELD_TO_PREDICATE.items():            qs.add(row[\"service_name\"], predicate, row[field], \"cmdb\")    return qs\n```\n\nEvery fact gets tagged with context **“cmdb”**, so downstream code always knows which tier it came from.\n\n## Step 2: Ingesting the Wiki (Priority 2)\n\nWiki pages don’t hand you clean columns, so this means parsing prose. We’ll keep it narrow: regex patterns for the *“key: value”* style most runbooks use. Here’s **data/wiki/runbook-payments.md**, written the way a real page drifts out of date:\n\n```\n# Payments Service Runbook\nOwner team: Payments Platform\nOn-call engineer: Jordan Blake\nEscalation: page #payments-oncall in PagerDuty if no response in 10 minutes.\n\n1234\n\n# Payments Service RunbookOwner team: Payments PlatformOn-call engineer: Jordan BlakeEscalation: page #payments-oncall in PagerDuty if no response in 10 minutes.\n```\n\nJordan Blake here, Amara Chen in the database: our planted conflict. Add a matching **runbook-checkout.md** (Diego Ruiz, consistent with the database) and an onboarding page mentioning that **notifications-service** is being sunset. Now extract:\n\n``` python\n# ingest_wiki.py\nimport re, glob\nfrom pathlib import Path\nfrom quadstore import QuadStore\n\nFIELD_PATTERNS = {\n    \"owner_team\": re.compile(r\"Owner team:\\s*(.+)\"),\n    \"on_call_engineer\": re.compile(r\"On-call engineer:\\s*(.+)\"),\n}\n\ndef service_name_from_filename(path):\n    stem = Path(path).stem\n    return stem.replace(\"runbook-\", \"\") + \"-service\" if stem.startswith(\"runbook-\") else stem\n\ndef build_p2_store(wiki_dir=\"data/wiki\"):\n    qs = QuadStore()\n    for path in glob.glob(f\"{wiki_dir}/*.md\"):\n        text = Path(path).read_text()\n        service = service_name_from_filename(path)\n        for predicate, pattern in FIELD_PATTERNS.items():\n            match = pattern.search(text)\n            if match:\n                qs.add(service, predicate, match.group(1).strip(), Path(path).name)\n    return qs\n\n123456789101112131415161718192021222324\n\n# ingest_wiki.pyimport re, globfrom pathlib import Pathfrom quadstore import QuadStore FIELD_PATTERNS = {    \"owner_team\": re.compile(r\"Owner team:\\s*(.+)\"),    \"on_call_engineer\": re.compile(r\"On-call engineer:\\s*(.+)\"),} def service_name_from_filename(path):    stem = Path(path).stem    return stem.replace(\"runbook-\", \"\") + \"-service\" if stem.startswith(\"runbook-\") else stem def build_p2_store(wiki_dir=\"data/wiki\"):    qs = QuadStore()    for path in glob.glob(f\"{wiki_dir}/*.md\"):        text = Path(path).read_text()        service = service_name_from_filename(path)        for predicate, pattern in FIELD_PATTERNS.items():            match = pattern.search(text)            if match:                qs.add(service, predicate, match.group(1).strip(), Path(path).name)    return qs\n```\n\nEach fact is tagged with the wiki page it came from, so a disagreement later traces back to a specific document. In production, a real Confluence export won’t follow this tidy convention; you’d widen the patterns per template or add a lightweight LLM extraction pass for pages that don’t fit one.\n\n## Step 3: Ingesting PDFs (Priority 3)\n\nPDFs aren’t going to resolve into clean facts, and we’re not trying to make them. For this tutorial, create two sample PDFs: an SLA document stating that payments-service commits to 99.95 percent monthly uptime with a service-credit process, and a postmortem describing a September 14, 2026, incident where on-call engineer Amara Chen diagnosed a database failover and rolled back the connection pool within nine minutes. (Any PDF writer works for generating these; [ReportLab](https://www.reportlab.com/) or exporting from a doc editor are both fine.) Then extract, chunk, and embed:\n\n``` python\n# ingest_pdfs.py\nimport glob\nfrom pathlib import Path\nimport chromadb\nfrom chromadb.config import Settings\nimport pdfplumber\n\ndef extract_text(pdf_path):\n    with pdfplumber.open(pdf_path) as pdf:\n        return \"\\n\".join(page.extract_text() or \"\" for page in pdf.pages)\n\ndef chunk_text(text, chunk_size=500):\n    words, chunks, current, current_len = text.split(), [], [], 0\n    for word in words:\n        current.append(word)\n        current_len += len(word) + 1\n        if current_len >= chunk_size:\n            chunks.append(\" \".join(current)); current, current_len = [], 0\n    if current: chunks.append(\" \".join(current))\n    return chunks\n\ndef build_p3_store(pdf_dir=\"data/pdfs\", chroma_path=\"data/chroma_db\"):\n    client = chromadb.PersistentClient(path=chroma_path, settings=Settings(anonymized_telemetry=False))\n    collection = client.get_or_create_collection(name=\"enterprise_docs\")\n    documents, ids, metadatas = [], [], []\n    for pdf_path in glob.glob(f\"{pdf_dir}/*.pdf\"):\n        name = Path(pdf_path).stem\n        for i, chunk in enumerate(chunk_text(extract_text(pdf_path))):\n            documents.append(chunk); ids.append(f\"{name}-{i}\"); metadatas.append({\"source\": name})\n    if documents:\n        collection.upsert(documents=documents, ids=ids, metadatas=metadatas)\n    return collection\n\n1234567891011121314151617181920212223242526272829303132\n\n# ingest_pdfs.pyimport globfrom pathlib import Pathimport chromadbfrom chromadb.config import Settingsimport pdfplumber def extract_text(pdf_path):    with pdfplumber.open(pdf_path) as pdf:        return \"\\n\".join(page.extract_text() or \"\" for page in pdf.pages) def chunk_text(text, chunk_size=500):    words, chunks, current, current_len = text.split(), [], [], 0    for word in words:        current.append(word)        current_len += len(word) + 1        if current_len >= chunk_size:            chunks.append(\" \".join(current)); current, current_len = [], 0    if current: chunks.append(\" \".join(current))    return chunks def build_p3_store(pdf_dir=\"data/pdfs\", chroma_path=\"data/chroma_db\"):    client = chromadb.PersistentClient(path=chroma_path, settings=Settings(anonymized_telemetry=False))    collection = client.get_or_create_collection(name=\"enterprise_docs\")    documents, ids, metadatas = [], [], []    for pdf_path in glob.glob(f\"{pdf_dir}/*.pdf\"):        name = Path(pdf_path).stem        for i, chunk in enumerate(chunk_text(extract_text(pdf_path))):            documents.append(chunk); ids.append(f\"{name}-{i}\"); metadatas.append({\"source\": name})    if documents:        collection.upsert(documents=documents, ids=ids, metadatas=metadatas)    return collection\n```\n\n[pdfplumber](https://github.com/jsvine/pdfplumber) handles the page-by-page text extraction. Chunks stay small (around 500 characters) so each one holds one idea, which matters for retrieval precision; longer PDFs would want a token-aware splitter instead. The first run downloads Chroma’s default embedding model automatically.\n\n## Step 4: Retrieval and the Fused Prompt\n\nWith three stores built, we need to pull entities from a question and query all three, then hand everything to the model with explicit rules for resolving conflicts.\n\n``` python\n# retrieval.py\nimport spacy\n\nnlp = spacy.load(\"en_core_web_sm\")\nKNOWN_SERVICES = [\"payments-service\", \"checkout-service\", \"notifications-service\"]\n\ndef extract_entities(text):\n    entities = {ent.text for ent in nlp(text).ents}\n    lowered = text.lower()\n    entities.update(s for s in KNOWN_SERVICES if s in lowered)\n    return list(entities)\n\ndef get_facts(quad_store, entities):\n    facts = []\n    for entity in entities:\n        facts.extend(quad_store.query(subject=entity))\n        facts.extend(quad_store.query(object=entity))\n    return list(set(facts))\n\ndef federated_retrieve(question, p1_store, p2_store, chroma_collection, n_results=2):\n    entities = extract_entities(question)\n    facts_p1 = get_facts(p1_store, entities)\n    facts_p2 = get_facts(p2_store, entities)\n    vector_results = chroma_collection.query(query_texts=[question], n_results=n_results)\n    return entities, facts_p1, facts_p2, vector_results\n\n12345678910111213141516171819202122232425\n\n# retrieval.pyimport spacy nlp = spacy.load(\"en_core_web_sm\")KNOWN_SERVICES = [\"payments-service\", \"checkout-service\", \"notifications-service\"] def extract_entities(text):    entities = {ent.text for ent in nlp(text).ents}    lowered = text.lower()    entities.update(s for s in KNOWN_SERVICES if s in lowered)    return list(entities) def get_facts(quad_store, entities):    facts = []    for entity in entities:        facts.extend(quad_store.query(subject=entity))        facts.extend(quad_store.query(object=entity))    return list(set(facts)) def federated_retrieve(question, p1_store, p2_store, chroma_collection, n_results=2):    entities = extract_entities(question)    facts_p1 = get_facts(p1_store, entities)    facts_p2 = get_facts(p2_store, entities)    vector_results = chroma_collection.query(query_texts=[question], n_results=n_results)    return entities, facts_p1, facts_p2, vector_results\n```\n\nspaCy’s general model won’t recognize our made-up service names on its own, so pairing it with a small known-terms list is a common, practical fix for internal tools. **get_facts()** checks each entity as both subject and object, since a fact can name it either way.\n\nNow for the part that actually resolves conflicts. It isn’t code logic, but a prompt:\n\n``` python\n# prompt.py\ndef format_quads(quads):\n    return \"\\n\".join(f\"({c}) {s} {p.replace('_', ' ')}: {o}.\" for s, p, o, c in quads)\n\ndef format_vector_results(vector_results):\n    if not vector_results or not vector_results.get(\"documents\"):\n        return \"\"\n    return \"\\n\\n\".join(vector_results[\"documents\"][0])\n\ndef build_system_prompt(facts_p1, facts_p2, vector_results):\n    p1 = format_quads(facts_p1) or \"(none retrieved for this question)\"\n    p2 = format_quads(facts_p2) or \"(none retrieved for this question)\"\n    p3 = format_vector_results(vector_results) or \"(none retrieved for this question)\"\n\n    return f\"\"\"You are a strict data-retrieval assistant for an internal engineering platform. Your ONLY knowledge comes from the text below. Ignore anything you think you already know about these services.\n\nPRIORITY RULES (strict):\n1. Priority 1 comes from the live CMDB and is always current. If it answers the question, use ONLY that answer.\n2. Priority 2 comes from wiki pages and can go stale. If it conflicts with Priority 1, Priority 1 wins and you must not mention Priority 2's version.\n3. Only fall back to Priority 2 if Priority 1 has no relevant answer.\n4. Priority 3 is unstructured document text. Use it for narrative detail, but never let it override a Priority 1 fact.\n5. If nothing answers the question, say \"I do not have enough information\" rather than guessing.\n\nGive one single, direct answer. Do not list conflicting possibilities or mention which tier the answer came from.\n\n---\n[PRIORITY 1: CMDB]\n{p1}\n\n[PRIORITY 2: WIKI]\n{p2}\n\n[PRIORITY 3: DOCUMENTS]\n{p3}\n---\n\"\"\"\n\n123456789101112131415161718192021222324252627282930313233343536\n\n# prompt.pydef format_quads(quads):    return \"\\n\".join(f\"({c}) {s} {p.replace('_', ' ')}: {o}.\" for s, p, o, c in quads) def format_vector_results(vector_results):    if not vector_results or not vector_results.get(\"documents\"):        return \"\"    return \"\\n\\n\".join(vector_results[\"documents\"][0]) def build_system_prompt(facts_p1, facts_p2, vector_results):    p1 = format_quads(facts_p1) or \"(none retrieved for this question)\"    p2 = format_quads(facts_p2) or \"(none retrieved for this question)\"    p3 = format_vector_results(vector_results) or \"(none retrieved for this question)\"     return f\"\"\"You are a strict data-retrieval assistant for an internal engineering platform. Your ONLY knowledge comes from the text below. Ignore anything you think you already know about these services. PRIORITY RULES (strict):1. Priority 1 comes from the live CMDB and is always current. If it answers the question, use ONLY that answer.2. Priority 2 comes from wiki pages and can go stale. If it conflicts with Priority 1, Priority 1 wins and you must not mention Priority 2's version.3. Only fall back to Priority 2 if Priority 1 has no relevant answer.4. Priority 3 is unstructured document text. Use it for narrative detail, but never let it override a Priority 1 fact.5. If nothing answers the question, say \"I do not have enough information\" rather than guessing. Give one single, direct answer. Do not list conflicting possibilities or mention which tier the answer came from. ---[PRIORITY 1: CMDB]{p1} [PRIORITY 2: WIKI]{p2} [PRIORITY 3: DOCUMENTS]{p3}---\"\"\"\n```\n\nRule 2 is the one doing the real work: it doesn’t just say “prefer Priority 1,” it forbids mentioning Priority 2’s conflicting version at all. A model that hedges with “the wiki says X but the database says Y” hasn’t resolved anything for the person asking.\n\n## Step 5: Running It\n\n``` python\n# main.py\nimport requests\nfrom ingest_db import build_p1_store\nfrom ingest_wiki import build_p2_store\nfrom ingest_pdfs import build_p3_store\nfrom retrieval import federated_retrieve\nfrom prompt import build_system_prompt\n\ndef ask(question, p1, p2, collection):\n    _, facts_p1, facts_p2, vector_results = federated_retrieve(question, p1, p2, collection)\n    system_prompt = build_system_prompt(facts_p1, facts_p2, vector_results)\n    response = requests.post(\n        \"http://localhost:11434/api/chat\",\n        json={\"model\": \"llama3.2\", \"messages\": [\n            {\"role\": \"system\", \"content\": system_prompt},\n            {\"role\": \"user\", \"content\": question},\n        ], \"stream\": False},\n    )\n    response.raise_for_status()\n    return response.json()[\"message\"][\"content\"]\n\nif __name__ == \"__main__\":\n    p1, p2, collection = build_p1_store(), build_p2_store(), build_p3_store()\n    for q in [\n        \"Who is on-call for payments-service right now?\",\n        \"What's our SLA for payments-service?\",\n        \"What happened in the last payments-service incident and who handled it?\",\n        \"Is notifications-service still active?\",\n    ]:\n        print(f\"\\nQ: {q}\\nA: {ask(q, p1, p2, collection)}\")\n\n123456789101112131415161718192021222324252627282930\n\n# main.pyimport requestsfrom ingest_db import build_p1_storefrom ingest_wiki import build_p2_storefrom ingest_pdfs import build_p3_storefrom retrieval import federated_retrievefrom prompt import build_system_prompt def ask(question, p1, p2, collection):    _, facts_p1, facts_p2, vector_results = federated_retrieve(question, p1, p2, collection)    system_prompt = build_system_prompt(facts_p1, facts_p2, vector_results)    response = requests.post(        \"http://localhost:11434/api/chat\",        json={\"model\": \"llama3.2\", \"messages\": [            {\"role\": \"system\", \"content\": system_prompt},            {\"role\": \"user\", \"content\": question},        ], \"stream\": False},    )    response.raise_for_status()    return response.json()[\"message\"][\"content\"] if __name__ == \"__main__\":    p1, p2, collection = build_p1_store(), build_p2_store(), build_p3_store()    for q in [        \"Who is on-call for payments-service right now?\",        \"What's our SLA for payments-service?\",        \"What happened in the last payments-service incident and who handled it?\",        \"Is notifications-service still active?\",    ]:        print(f\"\\nQ: {q}\\nA: {ask(q, p1, p2, collection)}\")\n```\n\nRun **python setup_cmdb.py**, generate your sample PDFs, then run **python main.py**. Everything builds once at startup and runs locally against Ollama from there.\n\n### Testing It\n\nEach question exercises the hierarchy differently. “**Who’s on-call for payments-service?**” pulls Amara Chen from Priority 1 and Jordan Blake from the stale wiki; rule 2 means the answer names only Amara Chen, with no hedging. “**What’s our SLA?**” needs Priority 1’s **sla_tier** fact plus the fuller SLA text from Priority 3; neither tier alone tells the whole story. “**What happened in the last incident?**” has no structured answer at all; it lives entirely in the postmortem PDF, which happens to name Amara Chen again, reinforcing Priority 1 without contradicting it. And “**Is notifications-service still active?**” is a test of restraint: Priority 1 says **deprecated** directly, and the model shouldn’t need to reach for anything else.\n\nAs the original article notes, this isn’t foolproof; it depends on the model actually following the rules rather than falling back on its own training data, which is why the rules need to be explicit and repeated rather than a vague instruction to “**be accurate**.”\n\n## Taking This to Production\n\nSwapping SQLite for Postgres is a small, isolated change. The bigger question is refresh cadence: Priority 1 should stay live or near-live, since that’s its whole value, while Priorities 2 and 3 can re-ingest on a nightly or hourly job. Just make sure that job actually runs, since a stale Priority 2 tier is worse than none at all. Real wiki exports won’t follow a tidy “key: value” format, so expect to widen your extraction patterns or add an LLM extraction pass. Access control also needs to happen before facts reach the prompt, not as an instruction inside it, since a soft instruction can be argued with, but data that was never fetched can’t be. And once you’re modeling a genuinely large, densely connected graph rather than one team’s service catalog, a real graph database like [Neo4j](https://neo4j.com/) or [ArangoDB](https://arango.ai/) starts earning its complexity.\n\n## Conclusion\n\nThe advantages carry over from the original architecture: predictability, since a live database fact is close to guaranteed to be correct; explainability, since the three tiers stay labeled and traceable; and simplicity, with no routing model to train, just three pipelines and one well-written prompt. The trade-off is token overhead and reliance on the model actually following instructions instead of its own training data. For an enterprise assistant, that trade is usually worth making. A tool that costs a few extra cents in tokens is fine. One that confidently pages the wrong engineer at 2 a.m. is not.\n\nIf you want the original example this article builds on, it’s worth reading: [Beyond Vector Search: Building a Deterministic 3-Tiered Graph-RAG System](https://machinelearningmastery.com/beyond-vector-search-building-a-deterministic-3-tiered-graph-rag-system/). Same core idea, just pointed at databases, wikis, and PDFs.", "url": "https://wpnews.pro/news/graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis", "canonical_source": "https://machinelearningmastery.com/graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis-and-databases/", "published_at": "2026-11-18 11:00:00+00:00", "updated_at": "2026-11-18 13:41:37.522691+00:00", "lang": "en", "topics": ["large-language-models", "generative-ai", "ai-agents", "ai-tools"], "entities": ["MachineLearningMastery.com", "Neo4j", "IDC", "Ollama", "llama3.2", "Chroma", "pdfplumber", "spaCy"], "also_reported_by": [], "takeaway": "Fuse a live database, wiki pages and PDF vectors into one prompt with explicit tier priorities — database first, wiki second, vector fallback third — so conflicting sources resolve to the current row instead of a stale wiki entry.", "recommendation": {"advice": "Rank retrieval sources by freshness and authority in the prompt — live database rows above wiki text above PDF vectors — so stale documents cannot override current facts when sources disagree.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis", "markdown": "https://wpnews.pro/news/graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis.md", "text": "https://wpnews.pro/news/graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis.txt", "jsonld": "https://wpnews.pro/news/graph-rag-for-enterprise-documents-building-a-knowledge-graph-from-pdfs-wikis.jsonld"}}