"""Observe exact chunks, native vector search, fusion and grounded graph paths."""
from collections import deque
from fractions import Fraction
from importlib.metadata import version
from math import dist, hypot
import sqlite3
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import chromadb
from chromadb.config import Settings
from lab_tools import Checks
def chunks(document_id, text, size, overlap):
if size < 1 or not 0 <= overlap < size:
raise ValueError("require 0 <= overlap < size")
for start in range(0,len(text),size-overlap):
end=min(start+size,len(text))
yield [f"{document_id}:{start}:{end}",start,end,text[start:end]]
if end==len(text):
break
def scores(a,b):
dot=sum(x*y for x,y in zip(a,b,strict=True))
length=hypot(*a)*hypot(*b)
if not length:
raise ValueError("zero vector has no cosine direction")
return [round(dot/length,6),round(dist(a,b),6),dot]
def rrf(rankings,k=60):
if k<0:
raise ValueError("k must be non-negative")
scores={}
for ranking in rankings:
for rank,key in enumerate(dict.fromkeys(ranking),1):
scores[key]=scores.get(key,Fraction())+Fraction(1,k+rank)
return [(key,str(scores[key])) for key in sorted(scores,key=lambda key:(-scores[key],key))]
def context(ids, evidence, budget):
rows=[]
for key in dict.fromkeys(ids):
text=evidence[key]
if len(text)<=budget:
rows.append({"id":key,"text":text})
budget-=len(text)
return rows
def relation_path(edges,start,target,predicate,max_hops):
queue=deque([(start,[])])
visited={start}
while queue:
node,path=queue.popleft()
if node==target:
return path
if len(path)>=max_hops:
continue
for source,kind,dest,evidence in edges:
if source==node and kind==predicate and dest not in visited:
visited.add(dest)
queue.append((dest,[*path,[source,kind,dest,evidence]]))
return None
def exercise(checks,root):
expect=checks.expect
example="ABCDEFGHIJ"
expect("python_rag_chunk_boundaries",["manual",example,6,2],"Split by original offsets and stop after reaching EOF",
[["manual:0:6",0,6,"ABCDEF"],["manual:4:10",4,10,"EFGHIJ"]],
list(chunks("manual",example,6,2)))
expect("python_rag_empty_input","empty document","Skip an empty document",[],list(chunks("empty","",5,2)))
for overlap in (-1,4,5):
try:
list(chunks("doc","XYZ",4,overlap))
except ValueError as error:
actual=str(error)
else:
actual=None
expect(f"python_rag_overlap_{overlap}",[4,overlap],"Reject a negative or nonadvancing overlap",
"require 0 <= overlap < size",actual)
expect("python_rag_three_metrics",[[2,0],[1,0],[0,1],[-1,0]],
"Compare direction, magnitude and signed dot product",
[[1.0,1.0,2],[0.0,2.236068,0],[-1.0,3.0,-2]],
[scores([2,0],item) for item in ([1,0],[0,1],[-1,0])])
try:
scores([0,0],[1,0])
except ValueError as error:
zero=str(error)
else:
zero=None
expect("python_rag_zero_cosine",[0,0],"Reject zero-length direction",
"zero vector has no cosine direction",zero)
client=chromadb.PersistentClient(path=str(root/"chroma"),settings=Settings(anonymized_telemetry=False))
store=client.get_or_create_collection("mbsky-python-rag",configuration={"hnsw":{"space":"cosine"}},
embedding_function=None)
texts={"bridge":"bridge manual", "ramp":"ramp guide ZX17", "staff":"private ramp ZX17"}
ids=list(texts)
store.add(ids=ids,documents=list(texts.values()),embeddings=[[1,0],[0.8,0.6],[1,0]],
metadatas=[{"scope":value} for value in ("public","public","staff")])
reopened=chromadb.PersistentClient(path=str(root/"chroma"),settings=Settings(anonymized_telemetry=False))
restored=reopened.get_collection("mbsky-python-rag",embedding_function=None)
hits=restored.query(query_embeddings=[[1,0]],n_results=2,where={"scope":"public"},
include=["documents","distances","metadatas"])
dense=hits["ids"][0]
expect("python_rag_chroma_vectors",[1,0],"Query native Chroma with aligned IDs, documents and filter",
[["bridge","ramp"],["bridge manual","ramp guide ZX17"],[0.0,0.2],["public","public"],"1.5.9"],
[dense,hits["documents"][0],[round(x,6) for x in hits["distances"][0]],
[row["scope"] for row in hits["metadatas"][0]],version("chromadb")])
with sqlite3.connect(":memory:") as db:
db.execute("CREATE VIRTUAL TABLE docs USING fts5(id UNINDEXED, body, scope UNINDEXED)")
db.executemany("INSERT INTO docs VALUES (?,?,?)",[(key,text,"staff" if key=="staff" else "public")
for key,text in texts.items()])
lexical=[row[0] for row in db.execute(
"SELECT id FROM docs WHERE docs MATCH ? AND scope=? ORDER BY bm25(docs),id",("ZX17","public"))]
expect("python_rag_lexical",["ZX17","public"],"Use SQLite FTS5 keyword search in the selected scope",["ramp"],lexical)
expected=[("ramp","123/3782"),("bridge","1/61")]
expect("python_rag_fuse_and_dedupe",[dense,[*lexical,*lexical]],"Fuse independent ranks and count an ID once per list",
expected,rrf((dense,[*lexical,*lexical])))
expect("python_rag_rank_tie",[["z"],["a"]],"Use the stable ID as a tie breaker when the two ranks are equal",
[("a","1/61"),("z","1/61")],rrf((["z"],["a"])))
candidates=[key for key,_ in rrf((dense,lexical))]
evidence={key:texts[key] for key in candidates}
expect("python_rag_budget_context",[candidates,15],"Preserve evidence identity within a character budget",
[{"id":"ramp","text":"ramp guide ZX17"}],context(candidates,evidence,15))
expect("python_rag_no_context",[candidates,5],"Keep an explicit empty context rather than inventing a citation",
[],context(candidates,evidence,5))
edges=[("Kai","advises","Lin","mentor-A"),("Lin","advises","Bo","mentor-B"),
("Bo","advises","Kai","mentor-C"),("Kai","works-with","Bo","other-A")]
route=[["Kai","advises","Lin","mentor-A"],["Lin","advises","Bo","mentor-B"]]
expect("python_rag_graph_two_hops",["Kai","Bo",2],"Follow two directed predicate-matching relations and retain both source IDs",
route,relation_path(edges,"Kai","Bo","advises",2))
expect("python_rag_graph_limit",["Kai","Bo",1],"Ignore unrelated edges and respect the maximum number of hops",
None,relation_path(edges,"Kai","Bo","advises",1))
expect("python_rag_graph_cycle",["Kai","unknown",5],"Stop on a cycle without inventing a path",
None,relation_path(edges,"Kai","unknown","advises",5))
joined={"relations":route,"passages":context(candidates,evidence,15)}
expect("python_rag_graph_vector_context",["Kai","Bo","ZX17"],"Keep typed relationships and text evidence separate",
[["mentor-A","mentor-B"],["ramp"]],[[item[3] for item in joined["relations"]],
[item["id"] for item in joined["passages"]]])
if __name__ == "__main__":
denied = AssertionError("network forbidden")
with patch("socket.socket.connect",side_effect=denied), patch("socket.socket.connect_ex",side_effect=denied):
if len(sys.argv) == 2:
checks = Checks()
exercise(checks,Path(sys.argv[1]))
checks.emit()
else:
with TemporaryDirectory(prefix="mbsky-python-rag-") as temp:
result = subprocess.run([sys.executable,"-B","-s","-X","utf8",str(Path(__file__).resolve()),temp],
capture_output=True,encoding="utf8",timeout=35,check=True)
assert not result.stderr,result.stderr
print(result.stdout.strip())
本例需在 CPython 3.12.14、Chroma 1.5.9、SQLite FTS5 和 langchain-text-splitters 1.1.3。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、Chroma 1.5.9、SQLite FTS5 和 langchain-text-splitters 1.1.3。
入口文件:projects/ai-agent-python-rag/python_rag.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python_rag.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Chroma 1.5.9、SQLite FTS5 和 langchain-text-splitters 1.1.3。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3101.zip