← Back to Official Package Registry
Tier 3: AI, Vector RAG & DataFrames • Embedded Vector & Hybrid RAGv1.0.0 • 58 KB • Ed25519 Verified

vec_rag@1.0.0

Navigable HNSW vector index, int8 scalar quantization, stemmed Okapi BM25 full-text search, Reciprocal Rank Fusion, and SQLite persistence.

use [vec_rag/bm25]use [vec_rag/chunker]use [vec_rag]
veko pkg add vec_rag@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

vec_rag

Pure-Veko embedded multi-layer HNSW vector store, symmetric int8 scalar quantization, Okapi BM25 full-text search, Reciprocal Rank Fusion (RRF) hybrid RAG, and Zero-FFI SQLite 3 persistence.

Overview

vec_rag provides an in-process Retrieval-Augmented Generation (RAG) and hybrid search engine written entirely in Veko with zero external dependencies or native FFI requirements:

  • vec_rag/chunker: Semantic prose (chunk-text), Markdown ATX heading-aware (chunk-markdown), and declaration-aware source code (chunk-code) splitters with configurable max_chars and sliding overlap_chars, preserving hierarchical heading breadcrumbs and exact byte offsets (start_off, end_off).
  • vec_rag/bm25: Alphanumeric tokenizer, deterministic English suffix stemmer-lite, stopword filter, and Okapi BM25 (k1 = 1.5, b = 0.75) inverted index (new-index, add-doc, remove-doc, search-bm25).
  • vec_rag: Dense block[f64] vector math (dot-product, cosine-similarity, l2-distance-sq, normalize-vec), symmetric int8 scalar quantization (quantize-i8, dequantize-i8, dot-i8) cutting embedding memory by 4x-8x, multi-layer HNSW navigable small-world graph (new-store, upsert, delete-doc, search-vector with metadata filtering), RRF k = 60 hybrid ranking (search-hybrid), and transactional JSON / Zero-FFI db/sqlite persistence (save-sqlite, load-sqlite).

Installation

powershell
veko pkg add vec_rag@1.0.0

Import the unified package and submodules:

rebol
use [
    rag     = vec_rag
    bm25    = vec_rag/bm25
    chunker = vec_rag/chunker
]

Architecture

  1. Deterministic Multi-Layer HNSW Graph: Document IDs map deterministically via 64-bit FNV-1a trailing-bit geometry to HNSW layers 0..4. Queries greedily descend upper layers (max_level .. 1) in $O(\log N)$ hops before running a bounded ef_search beam expansion at layer 0, with bidirectional degree pruning (M on upper layers, 2M on layer 0).
  2. 4x-8x RAM Savings via Symmetric int8 Quantization: quantize-i8 maps normalized f64 coordinates into compact 1-byte signed int8 codes ([-127..127]) stored inside bytes, enabling integer-only inner-loop dot products (dot-i8) scaled once on exit.
  3. Reciprocal Rank Fusion (RRF): search-hybrid executes semantic HNSW search and lexical Okapi BM25 search over the same document store, fusing rankings via $\text{RRF}(d) = \frac{1}{k + r_{\text{vec}}(d)} + \frac{1}{k + r_{\text{bm25}}(d)}$ (k = 60) so exact error codes, identifiers, and conceptual paraphrases rank together without score calibration drift.
  4. Zero-FFI SQLite 3 Storage: save-sqlite and load-sqlite persist embeddings, quantized int8 BLOBs, and JSON metadata inside standard SQLite format 3 B-tree files via db/sqlite, running identically across VM, Wasm 3.0, and Native targets.

Complete API Reference

vec_rag/chunker

Type / SignatureDescription
Chunk = struct { doc_id str, chunk_index i64, heading str = '', text str, start_off i64, end_off i64 }Semantic document chunk with section heading breadcrumb and byte span offsets.
chunk-text = fn [doc_id str, text str, max_chars i64, overlap_chars i64 /heading heading str = ''] block[Chunk]Splits UTF-8 prose on paragraph, line, sentence, or word boundaries with sliding overlap.
chunk-markdown = fn [doc_id str, md_text str, max_chars i64, overlap_chars i64] block[Chunk]Splits Markdown along #..###### ATX headings (ignoring # inside code fences) with hierarchical breadcrumbs.
chunk-code = fn [doc_id str, src_text str, max_chars i64, overlap_chars i64] block[Chunk]Splits source files along top-level function/type declarations.

vec_rag/bm25

Type / SignatureDescription
Bm25Hit = struct { doc_id str, score f64 }Ranked lexical hit from Okapi BM25 search.
Bm25IndexMutable Okapi BM25 inverted index (k1 = 1.5, b = 0.75).
stem-word = fn [word str] strDeterministic English suffix stemmer-lite.
tokenize = fn [text str] block[str]Lowercases, filters English stopwords, and stems alphanumeric tokens.
new-index = fn [/k1 k1 f64 = 1.5 /b b f64 = 0.75] Bm25IndexCreates an empty Okapi BM25 inverted index.
add-doc = fn [mut idx Bm25Index, doc_id str, text str] enumIndexes or updates doc_id in idx.
remove-doc = fn [mut idx Bm25Index, doc_id str] boolRemoves doc_id and its term postings from idx.
search-bm25 = fn [idx Bm25Index, query str, top_k i64] block[Bm25Hit]Returns top top_k documents ranked by Okapi BM25 score.

vec_rag

Type / SignatureDescription
QuantizedVec = struct { scale f64, dims i64, codes bytes }Compact 1-byte-per-dimension symmetric int8 vector representation.
SearchHit = struct { id str, text str, score f64, vec_score f64, bm25_score f64, metadata map }Unified result returned by search-vector and search-hybrid.
VecStoreMulti-layer HNSW vector graph paired with an Okapi BM25 index.
dot-product = fn [a block[f64], b block[f64]] f64Exact inner product of two equal-length vectors.
l2-distance-sq = fn [a block[f64], b block[f64]] f64Squared Euclidean distance between a and b.
normalize-vec = fn [v block[f64]] block[f64]Returns a unit L2-normalized vector.
cosine-similarity = fn [a block[f64], b block[f64]] f64Cosine similarity in [-1.0, 1.0].
quantize-i8 = fn [v block[f64]] QuantizedVecQuantizes block[f64] into int8 codes + scale.
dequantize-i8 = fn [q QuantizedVec] block[f64]Reconstructs block[f64] from QuantizedVec.
dot-i8 = fn [a QuantizedVec, b QuantizedVec] f64Integer-accumulated inner product over quantized int8 vectors.
new-store = fn [dims i64 /m m_links i64 = 8 /ef ef_search i64 = 32] VecStoreCreates a new HNSW + BM25 hybrid store.
upsert = fn [mut store VecStore, doc_id str, text str, vec block[f64] /meta metadata map = {}] enumInserts or updates a document in both HNSW and BM25 indexes.
delete-doc = fn [mut store VecStore, doc_id str] boolDeletes doc_id from HNSW layers and BM25 postings.
search-vector = fn [store VecStore, query_vec block[f64], top_k i64 /filter filter_meta map = {} /quantized use_i8 bool = false] block[SearchHit]Executes multi-layer HNSW nearest-neighbor search with optional metadata predicates.
search-hybrid = fn [store VecStore, query_text str, query_vec block[f64], top_k i64 /filter filter_meta map = {} /rrf_k rrf_k i64 = 60] block[SearchHit]Fuses HNSW vector search and Okapi BM25 via Reciprocal Rank Fusion.
to-json = fn [store VecStore] str / from-json = fn [raw str] VecStorePortable JSON serialization and index reconstruction.
save-sqlite = fn [store VecStore, db_path str] enum / load-sqlite = fn [db_path str] VecStorePersists and reloads VecStore using Zero-FFI db/sqlite.

Example Usage

rebol
use [rag = vec_rag, chunker = vec_rag/chunker]

chunks = chunker/chunk-markdown 'guide.md' '# Networking\nTLS 1.3 uses X25519MLKEM768.\n' 256 32

mut store = rag/new-store 4
_ = rag/upsert/meta mut store 'c-0' chunks[0].text [0.9 0.1 0.0 0.2] { section = chunks[0].heading }
_ = rag/upsert/meta mut store 'c-1' 'SQLite B-tree pages store relational rows.' [0.0 0.9 0.3 0.0] { section = 'Storage' }

hits = rag/search-hybrid store 'post-quantum X25519MLKEM768' [0.85 0.15 0.0 0.1] 2
println `Top hit: {hits[0].id} (RRF={hits[0].score})`

Verification

powershell
veko check --strict-types packages/vec_rag/src/chunker.vk
veko check --strict-types packages/vec_rag/src/bm25.vk
veko check packages/vec_rag/src/mod.vk
veko check packages/vec_rag/examples/demo.vk
veko run -C all packages/vec_rag/examples/demo.vk
packages/vec_rag/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/vec_rag/examples/demo.vk
// Self-contained runnable verification suite for `vec_rag` (`1.0.0`):
// Markdown/text/code chunking, dense & quantized `int8` vector math, Okapi BM25,
// multi-layer HNSW vector search, metadata filtering, RRF hybrid ranking, and `db/sqlite` roundtrip.

use [
	fs
	m       = math
	rag     = vec_rag
	bm25    = vec_rag/bm25
	chunker = vec_rag/chunker
]

assert-eq = fn [label str, got any, want any] any [
	if got != want [
		println `[FAIL] {label}: got {mold got}, expected {mold want}`
		return (err `assert-eq failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

assert-true = fn [label str, cond bool] any [
	if not cond [
		println `[FAIL] {label}`
		return (err `assert-true failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

// Deterministic 8-dimensional topic embedding helper for the knowledge base
make-topic-vec = fn [v_conc f64, v_tls f64, v_sql f64, v_wasm f64, v_vec f64, v_sec f64, v_http f64, v_pkg f64] block[f64] [
	rag/normalize-vec [v_conc v_tls v_sql v_wasm v_vec v_sec v_http v_pkg]
]

main = fn [] any [
	println '=== vec_rag 1.0.0 Verification Suite ==='

	// 1. Markdown-heading-aware & prose semantic chunking
	kb_md = str/join [
		'# Veko Runtime Architecture\n'
		'Veko executes deterministically with single-owner ORO memory management and zero stop-the-world pauses.\n\n'
		'## Shared-Nothing Concurrency\n'
		'Isolated workers communicate over bounded channels using spawn and chan/recv without shared mutable locks.\n'
		'```vk\n'
		'# comment inside code fence is NOT a Markdown heading\n'
		'ch = chan/new 8\n'
		'```\n\n'
		'## Post-Quantum TLS 1.3\n'
		'Hybrid X25519MLKEM768 key exchange protects transport sockets against harvest-now-decrypt-later adversaries.\n'
	] ''

	md_chunks = chunker/chunk-markdown 'arch.md' kb_md 260 24
	_ = assert-eq/or 'Markdown chunker splits into 3 heading sections (ignoring fenced #)' (len md_chunks) 3 [e -> return e]
	_ = assert-eq/or 'Chunk 0 top heading preserved' md_chunks[0].heading 'Veko Runtime Architecture' [e -> return e]
	_ = assert-eq/or 'Chunk 1 nested heading breadcrumb preserved' md_chunks[1].heading 'Veko Runtime Architecture > Shared-Nothing Concurrency' [e -> return e]
	_ = assert-true/or 'Chunk 1 retains fenced # comment verbatim without splitting' (str/contains? md_chunks[1].text '# comment inside code fence') [e -> return e]
	_ = assert-eq/or 'Chunk 2 nested heading breadcrumb preserved' md_chunks[2].heading 'Veko Runtime Architecture > Post-Quantum TLS 1.3' [e -> return e]
	_ = assert-true/or 'Chunk byte offsets strictly monotonic & bounded' (md_chunks[0].start_off == 0 and md_chunks[1].start_off > md_chunks[0].end_off and md_chunks[2].end_off <= (len (bytes/from-str kb_md))) [e -> return e]

	prose = 'Alpha sentence one. Beta sentence two. Gamma sentence three. Delta sentence four. Epsilon sentence five.'
	txt_chunks = rag/chunk-text 'prose-1' prose 48 12
	_ = assert-true/or 'Sliding-window prose chunker produces overlapping chunks' ((len txt_chunks) >= 3 and txt_chunks[1].start_off < txt_chunks[0].end_off) [e -> return e]

	// 2. Dense vector math & symmetric `int8` scalar quantization accuracy
	v1 = rag/normalize-vec [0.85 -0.25 0.40 0.15 -0.10 0.05 0.12 -0.08]
	v2 = rag/normalize-vec [0.80 -0.20 0.45 0.10 -0.05 0.08 0.10 -0.05]
	exact_cos = rag/cosine-similarity v1 v2
	q1 = rag/quantize-i8 v1
	q2 = rag/quantize-i8 v2
	quant_cos = rag/dot-i8 q1 q2
	deq1 = rag/dequantize-i8 q1
	quant_err = m/abs-f64 (exact_cos - quant_cos)
	_ = assert-eq/or 'Quantized int8 code buffer uses 1 byte per dimension (8B vs 64B f64)' (len q1.codes) 8 [e -> return e]
	_ = assert-true/or 'Int8 dot-product matches f64 cosine within 0.01' (exact_cos > 0.98 and quant_err < 0.01 and (len deq1) == 8) [e -> return e]

	// 3. Standalone Okapi BM25 stemmer + keyword ranking
	mut b_idx = bm25/new-index
	_ = bm25/add-doc mut b_idx 'd-quant' 'Symmetric int8 quantization compresses dense vector embeddings by 4x.'
	_ = bm25/add-doc mut b_idx 'd-sqlite' 'Zero-FFI SQLite B-tree pages persist relational tables and indexes.'
	_ = bm25/add-doc mut b_idx 'd-tls' 'TLS 1.3 handshake with ML-KEM-768 post-quantum key encapsulation.'
	bm_hits = bm25/search-bm25 b_idx 'quantized vectors compression' 2
	_ = assert-true/or 'BM25 stemmer matches quantized/vectors -> quantization/vector' ((len bm_hits) >= 1 and bm_hits[0].doc_id == 'd-quant') [e -> return e]

	// 4. Multi-layer HNSW Vector Store, Metadata Filtering, Deletions & RRF Hybrid Search
	mut store = rag/new-store/m/ef 8 4 16
	_ = rag/upsert/meta mut store 'doc-conc' 'Shared-nothing concurrency with isolated spawn workers and bounded channels.' (make-topic-vec 0.95 0.05 0.0 0.15 0.0 0.10 0.05 0.0) { subsystem = 'runtime', tier = 'core' }
	_ = rag/upsert/meta mut store 'doc-tls' 'TLS 1.3 X25519MLKEM768 post-quantum cryptography and AEAD record sealing.' (make-topic-vec 0.05 0.95 0.0 0.0 0.0 0.35 0.25 0.0) { subsystem = 'net', tier = 'security' }
	_ = rag/upsert/meta mut store 'doc-sqlite' 'Pure-Veko SQLite format 3 slotted B-tree storage engine with ACID rollback journal.' (make-topic-vec 0.0 0.0 0.96 0.15 0.10 0.05 0.0 0.05) { subsystem = 'db', tier = 'storage' }
	_ = rag/upsert/meta mut store 'doc-wasm' 'Deterministic WebAssembly 3.0 sandbox execution with fuel metering and capability gates.' (make-topic-vec 0.20 0.0 0.10 0.94 0.0 0.30 0.0 0.05) { subsystem = 'runtime', tier = 'sandbox' }
	_ = rag/upsert/meta mut store 'doc-hnsw' 'Multi-layer HNSW navigable small-world vector index with Okapi BM25 RRF fusion and error code E-RAG-409.' (make-topic-vec 0.05 0.0 0.15 0.0 0.96 0.0 0.0 0.20) { subsystem = 'ai', tier = 'search' }
	_ = rag/upsert/meta mut store 'doc-secret' 'Static and runtime .secret taint firewall blocking credential leaks over JSON or HTTP.' (make-topic-vec 0.05 0.25 0.0 0.15 0.0 0.95 0.10 0.0) { subsystem = 'security', tier = 'security' }
	_ = rag/upsert/meta mut store 'doc-pkg' 'Decentralized VKP1 Ed25519-signed package archives fetched from veko-lang.org.' (make-topic-vec 0.0 0.15 0.0 0.05 0.05 0.20 0.20 0.92) { subsystem = 'tooling', tier = 'ecosystem' }

	// Semantic vector query for SQLite B-tree
	q_sql_vec = make-topic-vec 0.0 0.0 0.92 0.10 0.08 0.0 0.0 0.0
	vhits = rag/search-vector store q_sql_vec 3
	_ = assert-eq/or 'HNSW vector search ranks doc-sqlite #1' vhits[0].id 'doc-sqlite' [e -> return e]

	// Quantized int8 HNSW vector query
	vhits_i8 = rag/search-vector/quantized store q_sql_vec 3 true
	_ = assert-eq/or 'Quantized int8 HNSW search ranks doc-sqlite #1' vhits_i8[0].id 'doc-sqlite' [e -> return e]

	// Metadata filter (`subsystem = 'runtime'`) excludes top-scoring security/net docs
	q_mixed = make-topic-vec 0.35 0.90 0.0 0.40 0.0 0.50 0.0 0.0
	filtered_hits = rag/search-vector/filter store q_mixed 5 { subsystem = 'runtime' }
	_ = assert-eq/or 'Metadata filter restricts results to 2 runtime docs' (len filtered_hits) 2 [e -> return e]
	_ = assert-true/or 'Filtered hits all carry subsystem == runtime' ((map/get filtered_hits[0].metadata 'subsystem') == 'runtime' and (map/get filtered_hits[1].metadata 'subsystem') == 'runtime') [e -> return e]

	// Hybrid RRF search: ambiguous vector leaning toward runtime, exact rare BM25 token `E-RAG-409`
	q_ambig_vec = make-topic-vec 0.55 0.0 0.20 0.35 0.48 0.0 0.0 0.10
	hyb_hits = rag/search-hybrid store 'troubleshoot E-RAG-409 RRF fusion' q_ambig_vec 3
	_ = assert-eq/or 'RRF hybrid search promotes exact keyword + semantic match doc-hnsw to #1' hyb_hits[0].id 'doc-hnsw' [e -> return e]
	_ = assert-true/or 'Hybrid hit populates both vec_score and bm25_score > 0' (hyb_hits[0].vec_score > 0.0 and hyb_hits[0].bm25_score > 0.0) [e -> return e]

	// Delete document & confirm immediate removal from both vector & BM25 indexes
	del_ok = rag/delete-doc mut store 'doc-pkg'
	_ = assert-true/or 'delete-doc removes doc-pkg' (del_ok and (rag/doc-count store) == 6) [e -> return e]

	// 5. Persistence roundtrip through Zero-FFI `db/sqlite` (cleaning up temp files via `defer`)
	tmp_db = str/join [(os/temp-dir) '/veko_vec_rag_demo_' (mold (time/unix)) '.sqlite'] ''
	tmp_jnl = str/append tmp_db '-journal'
	defer [
		_ = os/remove/or tmp_db [ .ok ]
		_ = os/remove/or tmp_jnl [ .ok ]
	]

	sv = rag/save-sqlite store tmp_db
	if err? sv [ return sv ]
	_ = assert-true/or 'SQLite vector store persisted on disk' (fs/file? tmp_db) [e -> return e]

	reloaded = rag/load-sqlite/or tmp_db [e -> return e]
	_ = assert-eq/or 'Reloaded SQLite store preserves exact doc count (6)' (rag/doc-count reloaded) 6 [e -> return e]
	re_hyb = rag/search-hybrid reloaded 'X25519MLKEM768 post-quantum TLS' (make-topic-vec 0.0 0.95 0.0 0.0 0.0 0.30 0.20 0.0) 2
	_ = assert-eq/or 'Reloaded SQLite store hybrid search ranks doc-tls #1' re_hyb[0].id 'doc-tls' [e -> return e]

	println 'ALL vec_rag 1.0.0 TESTS PASSED'
	.ok
]

res = main
if err? res [
	println (mold res)
	os/exit 1
]
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/vec_rag/1.0.0.vkp
Archive SHA-256: 5f7f86231902c4dfc7ddd21cafc9717106415fb054b9c42d9f32ab32057c7dda
Merkle Root: 7b6865efb31c5bb1c20c4cfa98b628087e04d7bf927fd2c28babded210ba395d
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"vec_rag","version":"1.0.0","tier":3.0,"tier_label":"Tier 3: AI, Vector RAG & DataFrames","category":"Embedded Vector & Hybrid RAG","description":"Navigable HNSW vector index, int8 scalar quantization, stemmed Okapi BM25 full-text search, Reciprocal Rank Fusion, and SQLite persistence.","modules":["vec_rag/bm25","vec_rag/chunker","vec_rag"],"homepage":"https://veko-lang.org/packages/vec_rag"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md7 KB3395a444bee15ad72b628e968b30f86559c2a41412f5d226283358b34e08a108
bm25.vk8 KBb681c96e37d8ca493d900d8a86cbcf305aaf93f541c59cf4da0dc2b2ce34674e
chunker.vk9 KB5974ea6f1055965e12ac533f69db8d6a00f79803c7f117e39d1711fc183812d9
examples/demo.vk8 KB1b2f5e1cc7b1c6df33e23e4ebaed2320eb2eabf1a0bae8686a2d0d287cbc57e8
mod.vk23 KBbb125238b50d51b3c7a99cc3e037168a660224432d5e5cfbabd7840c91648e6f