Machine Learning Mastery

Graph-RAG for Enterprise Documents: Building a Knowledge Graph from PDFs, Wikis, and Databases

6.9内容质量

TL;DR · AI 摘要

Graph-RAG for Enterprise Documents: Building a Knowledge Graph from PDFs, Wikis, and Databases - MachineLearningMastery....

核心要点

  • 主题聚焦:Graph-RAG for Enterprise Documents: Building a K
  • 来源:Machine Learning Mastery,建议结合原文判断细节。
  • AI 分析暂不可用,本条为保底评分与摘要。
#AI#编程#后端#安全#产品
打开原文

用于企业文档的 Graph-RAG:从 PDF、维基和数据库构建知识图谱 - MachineLearningMastery.com

用于企业文档的 Graph-RAG:从 PDF、维基和数据库构建知识图谱

By

Shittu Olumide

on

2026年11月18日

in

语言模型

0

分享

发布

在本文中,你将学习如何构建一个 Graph-RAG 系统,将实时数据库、维基页面和 PDF 整合为一个优先级知识源,使你的助手在这些来源存在分歧时能够给出唯一正确的答案。

我们将涵盖的主题包括:

  • 如何将数据库行和维基操作手册转换为简单四元组存储中的优先级事实。
  • 如何使用 pdfplumber 和 Chroma 提取、分块并嵌入 PDF 文本作为向量后备方案。
  • 如何通过明确的优先级规则将这三个层级融合为一个提示,解决冲突。

晚上11点,一位工程师向你的内部AI助手发送消息,询问谁负责支付服务的值班。助手已阅读维基,索引了共享驱动器中的所有PDF,并与服务注册表保持实时连接。这应该是一个简单的问题。但维基最后一次编辑是在四个月前,自那以后值班轮换已更改了两次,而数据库中当前答案只存储在一行中。如果检索系统将这三个来源视为同等可信的文本,就有可能让工程师得到一个早已离开轮换的人员信息。

这就是文章《超越向量搜索:构建确定性三级 Graph-RAG 系统》中讨论的精确失败案例,其中仅依赖向量的 RAG 会混淆篮球运动员当前效力的球队,因为多个球队名称在嵌入空间中距离很近。解决方案是:三个检索层级(绝对事实图、背景统计图和向量数据库),通过在提示中编写明确的优先级规则进行融合,而不是使用路由算法。本文采用相同的架构,将其指向实时数据库、一组维基页面和一批PDF,所有内容共同生成一个融合答案。

该方法有实际数据支持:由 Neo4j 赞助的 IDC 研究发现,将生成式 AI 建立在基于图的上下文中,平均可将幻觉率降低 44%,一家生命科学公司将幻觉率从 20-40% 降至 2-5%。

场景

我们将为虚构公司 "Northwind" 的平台团队构建系统,该团队运行三个服务:支付服务、结账服务、通知服务。三个来源描述了这些服务。一个服务注册数据库(现实中是 Postgres,此处使用 SQLite)实时保存所有者、值班工程师、状态、版本和 SLA 级别,始终是最新的,因此设为优先级 1。

维基的操作手册虽然详尽,但一旦轮换变更后无人更新就会变得过时,因此设为优先级 2,直到与更新内容冲突前仍有参考价值。一个 PDF 文件夹(包含 SLA 文档和事件后分析报告)提供了结构化来源无法包含的叙事背景,因此设为优先级 3,作为向量后备方案。

我们将故意植入一个冲突:维基的支付服务手册中提到的值班工程师与数据库不再一致。这个冲突正是该架构存在的全部原因。

三个模块(数据库/维基/PDF 图标)分别输入到标注优先级的框中,最终汇聚到一个融合提示框,指向 LLM 图标和单个答案气泡(点击放大)图片由作者提供

先决条件

You’ll need Python 3.10+ and a local model server. Like the original article, we’ll use Ollama with llama3.2 ; swapping in a hosted API later only changes the one function that sends the final request.

ollama pull llama3.2 mkdir graphrag-enterprise && cd graphrag-enterprise mkdir -p data/wiki data/pdfs pip install chromadb spacy pdfplumber requests python -m spacy download en_core_web_sm

1

2

3

4

5

6

ollama

pull

llama3

.

mkdir

graphrag

-

enterprise

&&

cd

p

data

/

wiki

pdfs

pip

install

chromadb

spacy

pdfplumber

requests

python

m

download

en_core_web_sm

chromadb 是我们的三级向量存储。spacy 处理命名实体识别,这样我们就可以从问题中提取服务名称。pdfplumber 比大多数轻量级替代方案更可靠地提取 PDF 文本。requests 与 Ollama 的本地 REST API 通信。

第一步:四元组存储和 CMDB(优先级 1)

优先级 1 和 2 都需要一个家:一个主谓宾上下文(SPOC)四元组存储。而不是引入原始教程的 QuadStore 库,这里有一个从零开始构建的最小版本:

quadstore.py class 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)

7

8

9

10

11

12

13

14

15

16

17

18

19

20

quadstore.py

class

QuadStore

:

def

__init__

(

self

)

_quads

=

[

]

add

,

subject

predicate

object

context

"general"

append

query

None

results

for

s

o

c

if

is

not

and

!=

continue

return

__len__

len

两种方法,四个字段,任何未指定的参数都作为通配符。原始库为这些字段建立了索引以实现常数时间查找,这在处理数百万条事实时很重要;对于一个团队的服务目录,普通的扫描已经足够。

现在数据库本身:我们的服务注册表,或配置管理数据库(CMDB)。SQLite 使教程保持无依赖;稍后替换为 psycopg2 和 Postgres 连接字符串是一个独立的更改。

setup_cmdb.py import 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()

21

22

setup_cmdb.py

import

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"

"2.9.0"

"2026-08-22"

"notifications-service"

"Platform Comms"

"Priya Nair"

"deprecated"

"1.4.3"

"2025-11-02"

"Tier-2 (99.9%)"

conn

connect

execute

executemany

"INSERT OR REPLACE INTO services VALUES (?, ?, ?, ?, ?, ?, ?)"

commit

close

notifications-service 被标记为已弃用是有意为之;我们之后会用到这个功能。运行它,你将得到一个真实的 .db 文件。接下来,将这些行转换为优先级 1 事实,每次查询实时数据,确保它们永远不会过时:

ingest_db.py import sqlite3 from 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

ingest_db.py

from

FIELD_TO_PREDICATE

{

"owner_team"

"on_call_engineer"

"status"

"current_version"

"last_deployed"

"sla_tier"

}

build_p1_store

qs

row_factory

Row

rows

"SELECT * FROM services"

fetchall

field

items

"service_name"

"cmdb"

每个事实都会被打上 "cmdb" 的上下文标签,这样下游代码始终能知道这些事实来自哪个层级。

第二步:导入维基(优先级 2)

维基页面不会直接给你整洁的列,这意味着需要解析文本。我们将保持简单:使用正则表达式匹配大多数运行手册中使用的 "key: value" 风格。以下是 data/wiki/runbook-payments.md 的内容,写法与真实页面逐渐过时的方式一致:

Payments Service Runbook Owner team: Payments Platform On-call engineer: Jordan Blake Escalation: page #payments-oncall in PagerDuty if no response in 10 minutes.

Payments Service Runbook

Owner

team

Payments

Platform

call

engineer

Jordan

Blake

Escalation

page

#payments-oncall in PagerDuty if no response in 10 minutes.

Jordan Blake 这里,Amara Chen 在数据库中:我们故意设置的冲突。添加一个匹配的 runbook-checkout.md(Diego Ruiz,与数据库一致)和一个提及 notifications-service 正在停用的入职页面。现在提取数据:

ingest_wiki.py import re, glob from pathlib import Path from 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

23

24

ingest_wiki.py

re

glob

pathlib

Path

FIELD_PATTERNS

compile

r

"Owner team:\s*(.+)"

"On-call engineer:\s*(.+)"

service_name_from_filename

stem

replace

"runbook-"

+

"-service"

startswith

else

/

build_p2_store

wiki_dir

"data/wiki"

f

"{wiki_dir}/*.md"

text

read_text

service

pattern

match

search

group

strip

name

每个事实都会标记其来源的维基页面,因此后续的分歧可以追溯到特定文档。在生产环境中,真实的Confluence导出不会遵循这种整洁的约定;你会根据模板扩展模式,或为不匹配任何模板的页面添加轻量级LLM提取流程。

步骤3:PDF摄入(优先级3)

PDF不会解析为清晰的事实,我们也不试图这样做。对于本教程,创建两个示例PDF:一份SLA文档声明payments-service承诺每月99.95%的正常运行时间并附带服务补偿流程,以及一份事后分析报告描述2026年9月14日的事件,值班工程师Amara Chen诊断出数据库故障转移并在九分钟内回滚了连接池。(任何PDF生成工具都适用于创建这些文件;ReportLab或从文档编辑器导出均可。)然后进行提取、分块和嵌入:

ingest_pdfs.py import glob from pathlib import Path import chromadb from chromadb.config import Settings import 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

25

26

27

28

29

30

31

32

ingest_pdfs.py

config

Settings

extract_text

pdf_path

with

open

as

pdf

"\n"

join

or

pages

chunk_text

chunk_size

500

words

chunks

current

current_len

split

word

+=

=

" "

;

build_p3_store

pdf_dir

"data/pdfs"

chroma_path

"data/chroma_db"

client

PersistentClient

anonymized_telemetry

False

collection

get_or_create_collection

"enterprise_docs"

documents

ids

metadatas

"{pdf_dir}/*.pdf"

i

chunk

enumerate

"{name}-{i}"

"source"

upsert

pdfplumber处理逐页文本提取。分块保持较小(约500字符),以便每个分块只包含一个想法,这对检索精度很重要;更长的PDF可能需要使用基于令牌的分块器。首次运行时会自动下载Chroma的默认嵌入模型。

步骤4:检索与融合提示

构建三个存储后,需要从问题中提取实体并查询所有三个存储,然后将所有内容连同解决冲突的明确规则一起传递给模型。

retrieval.py

import 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

retrieval.py

nlp

load

"en_core_web_sm"

KNOWN_SERVICES

extract_entities

entities

ent

ents

lowered

lower

update

list

get_facts

quad_store

facts

entity

extend

set

federated_retrieve

question

p1_store

p2_store

chroma_collection

n_results

facts_p1

facts_p2

vector_results

query_texts

spaCy的通用模型无法自行识别我们虚构的服务名称,因此将其与一个小型已知术语列表结合使用,是内部工具中常见且实用的解决方案。get_facts()函数将每个实体同时作为主语和宾语进行查询,因为事实可能以任一方式提及该实体。

现在是实际解决冲突的部分。这不是代码逻辑,而是一个提示:

prompt.py

def 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} --- """

33

34

35

36

prompt.py

format_quads

quads

"({c}) {s} {p.replace('_', ' ')}: {o}."

format_vector_results

get

"documents"

"\n\n"

build_system_prompt

p1

"(none retrieved for this question)"

p2

p3

"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. 优先级1来自实时CMDB,始终是最新状态。如果该优先级能回答问题,必须且只能使用该答案。
  1. 优先级2来自维基页面,内容可能过时。当与优先级1冲突时,必须以优先级1为准,且不得提及优先级2的版本。
  1. 仅当优先级1无相关答案时,才回退到优先级2。
  1. 优先级3是未结构化文档文本。可用于叙述性细节,但绝不能覆盖优先级1的事实。
  1. 如果没有任何信息能回答问题,应回复"do have enough information"而非猜测。

给出一个简洁直接的答案。不要列举冲突可能性,也不需要说明答案来源层级。


[优先级1:CMDB]

{p1}

[优先级2:维基]

{p2}

[优先级3:文档]

{p3}

规则2是真正起作用的规则:它不仅要求"优先使用优先级1",更明确禁止提及任何与优先级1冲突的优先级2版本。采用"维基显示X但数据库显示Y"这种模棱两可的表述,实际上并未真正解决提问者的问题。

第5步:运行程序

main.py import requests from ingest_db import build_p1_store from ingest_wiki import build_p2_store from ingest_pdfs import build_p3_store from retrieval import federated_retrieve from 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)}")

main.py

ingest_db

ingest_wiki

ingest_pdfs

retrieval

prompt

ask

_

system_prompt

response

"http://localhost:11434/api/chat"

json

"model"

"llama3.2"

"messages"

"role"

"system"

"content"

"user"

"stream"

raise_for_status

"message"

__name__

==

"__main__"

q

"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

"\nQ: {q}\nA: {ask(q, p1, p2, collection)}"

运行 python setup_cmdb.py 生成示例PDF后,再运行 python main.py 。所有内容在启动时一次性构建,并通过Ollama本地运行。

测试

/think

每个问题都以不同的方式测试层级结构。“谁负责支付服务的值班?”会从优先级1中提取Amara Chen,而从过时的维基中提取Jordan Blake;根据规则2,答案仅提及Amara Chen,没有任何模棱两可的表述。“我们的SLA是什么?”需要优先级1的sla_tier事实加上优先级3中更完整的SLA文本;单独的层级都无法完整说明情况。“上次事故发生了什么?”根本没有结构化答案;所有信息都存在于事后分析PDF中,PDF中恰好再次提到了Amara Chen,这强化了优先级1的结论且没有矛盾。“通知服务是否仍然活跃?”是对克制能力的测试:优先级1直接说明已弃用,模型无需再参考其他信息。

正如原文指出的,这种方法并非万无一失;它依赖模型真正遵循规则而非依赖自身的训练数据,这也是为什么规则需要明确且重复,而不是模糊的“请准确”指令。

四组问答对的终端截图,过时的Jordan Blake事实被灰显,而胜出的Amara Chen答案被突出显示(点击放大)图片由作者提供

生产环境中的应用

将SQLite替换为Postgres是一个小而独立的改动。更大的问题是刷新频率:优先级1应始终保持实时或接近实时,因为这是它的核心价值;而优先级2和3可以在夜间或每小时任务中重新导入。请确保任务确实执行,因为过时的优先级2层级比完全没有要糟糕得多。真实的维基导出不会遵循整洁的“键:值”格式,因此需要扩展提取模式或增加LLM提取步骤。访问控制也应在事实到达提示前完成,而不是作为提示内的指令,因为软性指令可能被争论,但从未获取的数据则无法被争论。一旦你建模的是一个真正庞大且高度互联的图,而非单个团队的服务目录,Neo4j或ArangoDB等真正的图数据库才开始体现出其复杂性价值。

结论

优势延续自原始架构:可预测性,因为实时数据库事实几乎可以保证正确;可解释性,因为三个层级始终保持标签和可追溯性;以及简洁性,无需训练路由模型,只需三个管道和一个精心撰写的提示。权衡在于令牌开销和对模型实际遵循指令而非自身训练数据的依赖。对于企业助手而言,这种权衡通常是值得的。一个花费额外几美分令牌的工具是可以接受的,而一个在凌晨2点错误通知工程师的工具则不可接受。

如果你想阅读本文所基于的原始示例,值得一读:Beyond Vector Search: Building a Deterministic 3-Tiered Graph-RAG System。核心思想相同,只是目标转向了数据库、维基和PDF。

更多相关内容

  • 自动化知识图谱构建:提取…
  • 向量数据库与图RAG在代理记忆中的对比:…
  • 如何构建多模态RAG图像处理流水线…
  • 领域知识在机器学习中的作用:…
  • pgvector与专用向量数据库对比:…
  • 三个难度层级解释向量数据库