"""Local exact search using real NumPy and a temporary SQLite catalog."""
import json
import math
import sqlite3
from contextlib import closing
import numpy as np
from lab_tools import run_exercise
def vector(values):
data = np.asarray(values, dtype=np.float64)
if data.ndim != 1 or not data.size or not np.isfinite(data).all():
raise ValueError("expected a finite nonempty one-dimensional vector")
return data
def measures(a, b):
left, right = vector(a), vector(b)
if left.shape != right.shape:
raise ValueError("vector dimensions differ")
dot = float(np.dot(left, right))
distance = float(np.linalg.norm(left - right))
norms = float(np.linalg.norm(left) * np.linalg.norm(right))
cosine = dot / norms if norms else None
return {"dot": dot, "l2": distance, "cosine": cosine}
def exact_search(db, query, category, limit):
rows = db.execute("SELECT id, embedding FROM documents WHERE category = ?", (category,))
result = []
for name, raw in rows:
score = measures(query, json.loads(raw))["cosine"]
if score is not None:
result.append((name, score))
result.sort(key=lambda row: (-row[1], row[0]))
return result[:limit]
def exercise(checks, workspace):
expect = checks.expect
a, b = [3, 4], [0, 5]
actual = measures(a, b)
expect("vector_metrics", [a,b], "Compute three measures on the same vectors",
{"dot":20.0,"l2":round(math.sqrt(10), 8),"cosine":0.8},
dict(actual, l2=round(actual["l2"],8)))
documented = [0.12, -0.54, 0.87, 0.03]
peers = [[0.10, -0.50, 0.90, 0.05], [-0.80, 0.20, -0.30, 0.70]]
expect("vector_reference_values", [documented, peers], "Recompute both documented inputs independently",
[0.9985, -0.3835], [round(measures(documented, peer)["cosine"], 4) for peer in peers])
expect("vector_zero", [[0,0],b], "Keep Euclidean distance but leave cosine undefined",
{"dot":0.0,"l2":5.0,"cosine":None}, measures([0,0],b))
for name, values in (("dimensions", [1,2,3]), ("nonfinite", [0,np.inf]), ("rank", [[1,2]])):
try:
measures(a, values)
except ValueError as error:
seen = type(error).__name__
else:
seen = "no_error"
expect("vector_reject_"+name, [a, repr(values)], "Try the input under vector shape and finiteness guards", "ValueError", seen)
normalized = vector(a) / np.linalg.norm(a)
expect("vector_normalized", [a,b], "Compare normalized dot to cosine and norm to one", [1.0,0.8],
[round(float(np.linalg.norm(normalized)),8), round(float(normalized @ (vector(b)/np.linalg.norm(b))),8)])
db_path = workspace / "station-vectors.sqlite"
with closing(sqlite3.connect(db_path)) as db:
db.execute("CREATE TABLE documents(id TEXT PRIMARY KEY, category TEXT NOT NULL, embedding TEXT NOT NULL)")
fixtures = [
("a","maintenance",[1,1]), ("b","maintenance",[2,2]), ("c","maintenance",[1,0]),
("hidden","staff",[1,1]), ("zero","maintenance",[0,0]),
]
db.executemany("INSERT INTO documents VALUES (?,?,?)", [(name,group,json.dumps(data)) for name,group,data in fixtures])
db.commit()
found = exact_search(db,[1,1],"maintenance",2)
expect("vector_filter_tie", fixtures, "Filter by category before ranking, with an ID tie-break",
[["a",1.0],["b",1.0]], [[name,round(score,8)] for name,score in found])
expect("vector_empty_filter", "maintenance' OR 1=1 --", "Bind a literal category with no matches",
[], exact_search(db,[1,1],"maintenance' OR 1=1 --",2))
db.execute("UPDATE documents SET embedding=? WHERE id=?", (json.dumps([-1,-1]),"a"))
db.execute("DELETE FROM documents WHERE id=?", ("b",))
db.commit()
with closing(sqlite3.connect(db_path)) as db:
actual = exact_search(db,[1,1],"maintenance",5)
expect("vector_persistence", ["change a","delete b","reopen"], "Reopen SQLite and rerank retained valid vectors",
[["c",0.70710678],["a",-1.0]],[[name,round(score,8)] for name,score in actual])
expect("vector_source_counts", "maintenance records", "Read rows including zero but exclude it from cosine ranks",
[3,2],[db.execute("SELECT count(*) FROM documents WHERE category = ?", ("maintenance",)).fetchone()[0],len(actual)])
expect("vector_runtime", "installed NumPy", "Observe the version used to verify numeric expectations", "2.5.4", np.__version__)
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12,NumPy 2.5.4、标准库 SQLite、Chroma 1.5.9;本机数据,无模型调用 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12,NumPy 2.5.4、标准库 SQLite、Chroma 1.5.9;本机数据,无模型调用
入口文件:projects/ai-agent-vector/similarity.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
similarity.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12,NumPy 2.5.4、标准库 SQLite、Chroma 1.5.9;本机数据,无模型调用。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3109.zip
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip