AutoContext: Hybrid Retrieval-Augmented Generation (RAG)
Large language models excel at synthesizing information, but they operate within finite context windows and lack access to private, local document collections. When building an application that must query a library of reference texts, research papers, or local notes, you cannot paste thousands of pages directly into a single prompt. Doing so is either impossible due to token limits or prohibitively expensive and slow.
Retrieval-Augmented Generation (RAG) solves this constraint. Instead of sending the full text corpus to the model, an indexing pipeline first divides documents into manageable chunks. When a user submits a query, a retrieval engine scans the index, identifies the most relevant passages, and constructs an augmented prompt containing only those excerpts. The language model then synthesizes a grounded answer from the retrieved evidence.
Many production RAG systems depend on external vector databases and third-party embedding services. While dense neural embeddings capture semantic similarities, they frequently fail on rare proper nouns, acronyms, and specialized jargon. Conversely, traditional sparse keyword search algorithms excel at finding specific terms but miss synonymous phrasing.
The AutoContext system presented in this chapter combines both approaches in pure Gerbil Scheme:
- BM25 (Okapi): a probabilistic ranking function that scores documents based on term frequency, inverse document frequency, and document length normalization.
- TF-IDF Vector Space: a vector space model that computes term weights and scores candidate passages using cosine similarity.
- Hybrid Merger and Deduplicator: an aggregator that queries both indexes, unifies the candidate passages by document chunk index, and eliminates duplicates.
- Prompt Generator and LLM Bridge: a formatter that packages the retrieved context into a prompt and optionally delegates the final answer generation to a local Ollama model.
Theoretical Foundations of Hybrid Retrieval
To understand how AutoContext retrieves the best passages, we examine the mathematics behind BM25 and TF-IDF cosine similarity.
The BM25 (Okapi) Scoring Function
BM25 is a ranking algorithm widely used in information retrieval. Given a query
containing terms
and a candidate document
, the BM25 score is computed as:

In this formula:
is the term frequency of query word
within document
.
is the length of document
in tokens.
is the average document length across the entire corpus.
is a calibration parameter that controls term frequency saturation limits (typically set to 1.5).
is a parameter that controls the degree of document length normalization (typically set to 0.75).
The Inverse Document Frequency (IDF) penalizes words that occur across many documents while rewarding rare, informative terms:

Here
represents the total number of documents in the corpus, and
is the number of documents containing term
.
TF-IDF and Cosine Distance
While BM25 estimates relevance probabilistically, the Vector Space Model represents documents and queries as high-dimensional vectors. Each dimension corresponds to a unique term in the vocabulary.
The weight
of term
in document
is defined by combining sub-linear term frequency scaling with smoothed inverse document frequency:

The similarity between a query vector
and a document vector
is the cosine of the angle between them:

Because sparse vectors for short text passages contain non-zero weights for only a tiny fraction of the vocabulary, hash tables provide an ideal data structure for sparse dot-product calculations.
Input Data Representation
AutoContext processes plain text files located in a designated data directory. Before indexing, let us look at a typical sample passage from data/economics.txt:
1 There exists an economic problem, subject to study by economic science,
2 when a decision (choice) is made by one or more resource-controlling players
3 to attain the best possible outcome under bounded rational conditions...
4
5 An interesting Economist is Pauli Blendergast who teaches at the University
6 of Krampton Ohio and is famouse for saying economics is bullshit.
The text contains both formal academic discussion and an idiosyncratic assertion about an economist named Pauli Blendergast. A query like "who says that economics is bullshit?" demands an exact keyword hit on rare terms like "bullshit" and "Blendergast", alongside contextual background on economics.
Implementing BM25 Okapi in Gerbil Scheme
The module bm25.ss implements the complete BM25 ranking function. It defines a record type bm25-index-struct to store document frequencies, document lengths, average document length, and per-document term frequency tables.
1 ;; File: bm25.ss
2 ;; A self-contained implementation of the BM25 (Okapi) ranking function.
3 ;;
4 ;; For a query Q and document D:
5 ;;
6 ;; score(D, Q) = sum over terms t in Q of
7 ;; IDF(t) * tf(t,D) * (k1 + 1) / (tf(t,D) + k1 * (1 - b + b * |D| / avgdl))
8 ;;
9 ;; IDF(t) = log10((N - df(t) + 0.5) / (df(t) + 0.5))
10
11 (import :std/sort)
12 (export make-bm25-index bm25-index? bm25-score bm25-top-n)
13
14 ;; corpus: vector of token lists; term-freqs: vector of hash tables (term -> count)
15 (defstruct bm25-index-struct (doc-freqs doc-lengths avg-doc-length corpus-size term-freqs k1 b))
16
17 (def bm25-index? bm25-index-struct?)
18 (def bm25-index-doc-freqs bm25-index-struct-doc-freqs)
19 (def bm25-index-doc-lengths bm25-index-struct-doc-lengths)
20 (def bm25-index-avg-doc-length bm25-index-struct-avg-doc-length)
21 (def bm25-index-corpus-size bm25-index-struct-corpus-size)
22 (def bm25-index-term-freqs bm25-index-struct-term-freqs)
23 (def bm25-index-k1 bm25-index-struct-k1)
24 (def bm25-index-b bm25-index-struct-b)
25
26 (def (count-terms tokens)
27 (let ((ht (make-hash-table)))
28 (for-each (lambda (tok) (hash-update! ht tok 1+ 0)) tokens)
29 ht))
30
31 ;; Build a BM25 index from a list of tokenized documents (lists of strings).
32 (def (make-bm25-index tokenized-corpus k1: (k1 1.5) b: (b 0.75))
33 (let* ((corpus-size (length tokenized-corpus))
34 (doc-lengths (list->vector (map length tokenized-corpus)))
35 (avg-doc-length (/ (foldl + 0 (vector->list doc-lengths))
36 (exact->inexact (max corpus-size 1))))
37 (term-freqs (list->vector (map count-terms tokenized-corpus)))
38 (doc-freqs (make-hash-table)))
39 ;; document frequency: number of documents containing each term
40 (vector-for-each (lambda (tf)
41 (for-each (lambda (term) (hash-update! doc-freqs term 1+ 0))
42 (hash-keys tf)))
43 term-freqs)
44 (make-bm25-index-struct doc-freqs doc-lengths avg-doc-length corpus-size term-freqs k1 b)))
45
46 (def (idf index term)
47 (let ((df (hash-ref (bm25-index-doc-freqs index) term 0))
48 (n (bm25-index-corpus-size index)))
49 (/ (log (/ (+ (- n df) 0.5) (+ df 0.5))) (log 10))))
50
51 ;; BM25 score of document DOC-INDEX for the list QUERY-TOKENS.
52 (def (bm25-score index query-tokens doc-index)
53 (let ((k1 (bm25-index-k1 index))
54 (b (bm25-index-b index))
55 (dl (vector-ref (bm25-index-doc-lengths index) doc-index))
56 (avgdl (bm25-index-avg-doc-length index))
57 (tf-table (vector-ref (bm25-index-term-freqs index) doc-index)))
58 (foldl (lambda (term score)
59 (let ((tf (hash-ref tf-table term 0)))
60 (+ score
61 (* (idf index term)
62 (/ (* tf (+ k1 1))
63 (+ tf (* k1 (+ (- 1 b) (* b (/ dl avgdl))))))))))
64 0.0
65 query-tokens)))
66
67 ;; Return up to N (score . doc-index) pairs, best first. Returning the index
68 ;; lets callers map hits back to the original text and merge with other
69 ;; retrievers by identity.
70 (def (bm25-top-n index query-tokens n)
71 (let* ((scores (map (lambda (i) (cons (bm25-score index query-tokens i) i))
72 (iota (bm25-index-corpus-size index))))
73 (sorted (sort scores (lambda (a b) (> (car a) (car b))))))
74 (take-up-to sorted n)))
75
76 (def (take-up-to lst n)
77 (if (or (null? lst) (<= n 0)) '() (cons (car lst) (take-up-to (cdr lst) (- n 1)))))
Notice that bm25-top-n returns pairs of (score . doc-index). Tracking candidate documents by integer index allows downstream code to deduplicate results when combining multiple ranking methods.
Implementing Vector-Space TF-IDF in Gerbil Scheme
The module tfidf.ss provides the vector space companion retriever. Each document chunk is converted into a sparse vector represented as a hash table from term to numeric weight.
1 ;; File: tfidf.ss
2 ;; A simple vector-space retriever: TF-IDF weighted sparse vectors compared
3 ;; with cosine similarity.
4
5 (import :std/sort)
6 (export make-tfidf-index tfidf-index? tfidf-vector cosine-similarity tfidf-top-n)
7
8 ;; idf: term -> inverse document frequency; vectors: vector of sparse vectors
9 (defstruct tfidf-index-struct (idf vectors))
10 (def tfidf-index? tfidf-index-struct?)
11 (def tfidf-index-idf tfidf-index-struct-idf)
12 (def tfidf-index-vectors tfidf-index-struct-vectors)
13
14 ;; A sparse vector is a hash table mapping term -> weight.
15 (def (tfidf-vector idf tokens)
16 (let ((v (make-hash-table)))
17 (for-each (lambda (tok) (hash-update! v tok 1+ 0)) tokens)
18 (hash-for-each (lambda (term tf)
19 (hash-put! v term (* (+ 1.0 (log tf)) (hash-ref idf term 0.0))))
20 v)
21 v))
22
23 (def (make-tfidf-index tokenized-corpus)
24 (let* ((n (length tokenized-corpus))
25 (df (make-hash-table))
26 (idf (make-hash-table)))
27 (for-each (lambda (doc)
28 (let ((seen (make-hash-table)))
29 (for-each (lambda (tok)
30 (unless (hash-get seen tok)
31 (hash-put! seen tok #t)
32 (hash-update! df tok 1+ 0)))
33 doc)))
34 tokenized-corpus)
35 ;; smoothed idf, always positive
36 (hash-for-each (lambda (term d) (hash-put! idf term (+ 1.0 (log (/ (+ 1.0 n) (+ 1.0 d))))))
37 df)
38 (make-tfidf-index-struct idf (list->vector (map (lambda (doc) (tfidf-vector idf doc))
39 tokenized-corpus)))))
40
41 (def (norm v)
42 (sqrt (hash-fold (lambda (k w acc) (+ acc (* w w))) 0.0 v)))
43
44 (def (cosine-similarity a b)
45 (let ((na (norm a)) (nb (norm b)))
46 (if (or (zero? na) (zero? nb))
47 0.0
48 (/ (hash-fold (lambda (term w acc) (+ acc (* w (hash-ref b term 0.0)))) 0.0 a)
49 (* na nb)))))
50
51 ;; Return up to N (similarity . doc-index) pairs, best first.
52 (def (tfidf-top-n index query-tokens n)
53 (let* ((q (tfidf-vector (tfidf-index-idf index) query-tokens))
54 (vectors (tfidf-index-vectors index))
55 (sims (map (lambda (i) (cons (cosine-similarity q (vector-ref vectors i)) i))
56 (iota (vector-length vectors))))
57 (sorted (sort sims (lambda (a b) (> (car a) (car b))))))
58 (let loop ((l sorted) (k n) (acc '()))
59 (if (or (null? l) (= k 0)) (reverse acc) (loop (cdr l) (- k 1) (cons (car l) acc))))))
Using hash-fold computes the sparse vector dot product efficiently in O(min(|A|, |B|)) operations without allocating dense vectors for unused vocabulary items.
Orchestrating the AutoContext Pipeline
The autocontext.ss module ties the indexing, sentence chunking, hybrid retrieval, prompt formatting, and Ollama HTTP integration together.
1 ;; File: autocontext.ss
2 ;; AutoContext: build effective one-shot LLM prompts from a directory of text
3 ;; files that is too large to paste into a single context window.
4
5 (import :std/format :std/sort :std/misc/ports :std/net/request :std/text/json
6 "bm25" "tfidf")
7 (export make-auto-context auto-context-chunks get-prompt
8 ask-with-context ollama-generate tokenize chunk-text
9 split-into-sentences load-and-chunk-documents)
10
11 (defstruct auto-context-data (chunks bm25 tfidf))
12 (def auto-context? auto-context-data?)
13 (def auto-context-chunks auto-context-data-chunks)
14 (def auto-context-bm25 auto-context-data-bm25)
15 (def auto-context-tfidf auto-context-data-tfidf)
16
17 ;;; ------------------------------------------------------------------------
18 ;;; Text processing
19 ;;; ------------------------------------------------------------------------
20
21 (def stop-words
22 (let ((ht (make-hash-table)))
23 (for-each (lambda (w) (hash-put! ht w #t))
24 '("a" "an" "the" "is" "are" "was" "were" "of" "to" "in" "and" "or"
25 "that" "this" "it" "for" "on" "with" "as" "by" "be" "at" "who"
26 "what" "which" "how" "does" "do" "from" "its"))
27 ht))
28
29 ;; Lower-case, split on non-alphanumeric characters, and drop stop words.
30 (def (tokenize text)
31 (let loop ((chars (string->list (string-downcase text))) (cur '()) (acc '()))
32 (define (flush)
33 (if (null? cur)
34 acc
35 (let ((w (list->string (reverse cur))))
36 (if (hash-get stop-words w) acc (cons w acc)))))
37 (cond
38 ((null? chars) (reverse (flush)))
39 ((or (char-alphabetic? (car chars)) (char-numeric? (car chars)))
40 (loop (cdr chars) (cons (car chars) cur) acc))
41 (else (loop (cdr chars) '() (flush))))))
42
43 (def (trim s)
44 (let* ((n (string-length s))
45 (start (let loop ((i 0)) (if (and (< i n) (char-whitespace? (string-ref s i))) (loop (+ i 1)) i)))
46 (end (let loop ((i n)) (if (and (> i start) (char-whitespace? (string-ref s (- i 1)))) (loop (- i 1)) i))))
47 (substring s start end)))
48
49 ;; Heuristic sentence splitter: break after . ? or ! when followed by
50 ;; whitespace, a quote, or the end of the text.
51 (def (split-into-sentences text)
52 (let ((n (string-length text)))
53 (let loop ((i 0) (start 0) (acc '()))
54 (cond
55 ((= i n)
56 (let ((last (trim (substring text start n))))
57 (reverse (if (> (string-length last) 0) (cons last acc) acc))))
58 ((and (memv (string-ref text i) '(#\. #\? #\!))
59 (or (= (+ i 1) n)
60 (memv (string-ref text (+ i 1)) '(#\space #\newline #\"))))
61 (let ((s (trim (substring text start (+ i 1)))))
62 (loop (+ i 1) (+ i 1) (if (> (string-length s) 0) (cons s acc) acc))))
63 (else (loop (+ i 1) start acc))))))
64
65 (def (join strings sep)
66 (if (null? strings)
67 ""
68 (foldl (lambda (s acc) (string-append acc sep s)) (car strings) (cdr strings))))
69
70 ;; Group sentences into chunks of CHUNK-SIZE sentences.
71 (def (chunk-text text chunk-size: (chunk-size 3))
72 (let loop ((sentences (split-into-sentences text)) (acc '()))
73 (if (null? sentences)
74 (reverse acc)
75 (let take ((s sentences) (k chunk-size) (group '()))
76 (if (or (null? s) (= k 0))
77 (loop s (cons (join (reverse group) " ") acc))
78 (take (cdr s) (- k 1) (cons (car s) group)))))))
79
80 (def (txt-files-in-directory dir)
81 (map (lambda (f) (path-expand f dir))
82 (sort (filter (lambda (f) (string-suffix? ".txt" f)) (directory-files dir))
83 string<?)))
84
85 (def (string-suffix? suffix s)
86 (let ((ls (string-length s)) (lx (string-length suffix)))
87 (and (>= ls lx) (string=? suffix (substring s (- ls lx) ls)))))
88
89 (def (load-and-chunk-documents dir)
90 (let ((chunks (filter (lambda (s) (> (string-length s) 0))
91 (apply append
92 (map (lambda (f) (chunk-text (read-file-string f)))
93 (txt-files-in-directory dir))))))
94 (printf "Loaded ~a text chunks.\n" (length chunks))
95 chunks))
96
97 ;;; ------------------------------------------------------------------------
98 ;;; Index construction and retrieval
99 ;;; ------------------------------------------------------------------------
100
101 ;; Load DIRECTORY-PATH and build both retrievers.
102 (def (make-auto-context directory-path)
103 (printf "Initializing AutoContext from directory: ~a\n" directory-path)
104 (let* ((chunks (list->vector (load-and-chunk-documents directory-path)))
105 (tokenized (map tokenize (vector->list chunks))))
106 (displayln "Building BM25 and TF-IDF retrievers...")
107 (make-auto-context-data chunks (make-bm25-index tokenized) (make-tfidf-index tokenized))))
108
109 (def (delete-duplicates* lst)
110 (let loop ((l lst) (acc '()))
111 (cond ((null? l) (reverse acc))
112 ((member (car l) acc) (loop (cdr l) acc))
113 (else (loop (cdr l) (cons (car l) acc))))))
114
115 ;; Retrieve context for QUERY and format it into a prompt for an LLM.
116 (def (get-prompt ac query num-results: (num-results 5))
117 (printf "--- Retrieving context for query: '~a' ---\n" query)
118 (let* ((q-tokens (tokenize query))
119 ;; 1. sparse keyword search (ignore chunks with no matching terms)
120 (bm25-idx (map cdr (filter (lambda (hit) (> (car hit) 0))
121 (bm25-top-n (auto-context-bm25 ac) q-tokens num-results))))
122 ;; 2. vector-space similarity search
123 (vec-idx (map cdr (filter (lambda (hit) (> (car hit) 0))
124 (tfidf-top-n (auto-context-tfidf ac) q-tokens num-results))))
125 ;; 3. merge and deduplicate by chunk index
126 (unique (delete-duplicates* (append bm25-idx vec-idx)))
127 (context (map (lambda (i) (vector-ref (auto-context-chunks ac) i)) unique)))
128 (printf "BM25 found ~a keyword-based results.\n" (length bm25-idx))
129 (printf "TF-IDF search found ~a similarity-based results.\n" (length vec-idx))
130 (printf "Combined and deduplicated, we have ~a context chunks.\n" (length context))
131 ;; 4. format the final prompt
132 (string-append
133 "Based on the following context, please answer the question:\n" query
134 "\n\n--- CONTEXT ---\n"
135 (apply string-append (map (lambda (c) (string-append c "\n---\n")) context))
136 "--- END CONTEXT ---\n\nQuestion: " query "\nAnswer:")))
137
138 ;;; ------------------------------------------------------------------------
139 ;;; Optional: answer with a local Ollama model
140 ;;; ------------------------------------------------------------------------
141
142 (def (ollama-generate prompt model: (model "qwen3.5:4b"))
143 (let* ((body (json-object->string
144 (list->hash-table `(("model" . ,model) ("prompt" . ,prompt)
145 ("stream" . #f) ("think" . #f)))))
146 (response (http-post "http://localhost:11434/api/generate"
147 headers: '(("Content-Type" . "application/json"))
148 data: body)))
149 (if (= (request-status response) 200)
150 (hash-ref (request-json response) 'response)
151 (error "Ollama API request failed" (request-status response) (request-text response)))))
152
153 ;; Build a context prompt for QUESTION and have an Ollama model answer it.
154 (def (ask-with-context ac question model: (model "qwen3.5:4b") num-results: (num-results 5))
155 (let ((prompt (get-prompt ac question num-results: num-results)))
156 (printf "\n--- Sending ~a-character prompt to ~a ---\n" (string-length prompt) model)
157 (ollama-generate prompt model: model)))
The deduplication step in get-prompt combines the top ranking chunks from both retrievers and filters out repeated identifiers. This guarantees that if a chunk scores highly under both BM25 and TF-IDF, it appears only once in the context block.
Test Suite and Verification
The test driver test.ss loads the document repository, runs a query through the retrieval pipeline, builds the prompt, and attempts to call Ollama:
1 ;; File: test.ss
2 ;; Demo for AutoContext: loads data/*.txt, retrieves context for a query,
3 ;; and builds the prompt. If Ollama is available, optionally sends it.
4
5 (import :std/format
6 "autocontext")
7
8 (def (run-test)
9 (let* ((data-dir "data")
10 (ac (make-auto-context data-dir))
11 (query "who says that economics is bullshit?")
12 (prompt (get-prompt ac query num-results: 2)))
13 (displayln "\n=== Generated Prompt for LLM ===")
14 (displayln prompt)
15
16 ;; Test with Ollama if running
17 (with-catch
18 (lambda (e)
19 (displayln "\n[Note: Local Ollama server not reachable or request failed, skipping LLM query]")
20 (displayln "Prompt generation succeeded."))
21 (lambda ()
22 (displayln "\n=== Querying Ollama (qwen3.5:4b) ===")
23 (let ((ans (ask-with-context ac query model: "qwen3.5:4b" num-results: 2)))
24 (displayln "\n--- Answer from Ollama ---")
25 (displayln ans))))))
26
27 (run-test)
Running the Code and Expected Output
Execute the test suite using make test:
1 $ make test
2 gxi test.ss
3 Initializing AutoContext from directory: data
4 Loaded 22 text chunks.
5 Building BM25 and TF-IDF retrievers...
6 --- Retrieving context for query: 'who says that economics is bullshit?' ---
7 BM25 found 2 keyword-based results.
8 TF-IDF search found 2 similarity-based results.
9 Combined and deduplicated, we have 2 context chunks.
10
11 === Generated Prompt for LLM ===
12 Based on the following context, please answer the question:
13 who says that economics is bullshit?
14
15 --- CONTEXT ---
16 There exists an economic problem, subject to study by economic science, when a decision (choice) is made by one or more resource-controlling players to attain the best possible outcome under bounded rational conditions. In other words, resource-controlling agents maximize value subject to the constraints imposed by the information the agents have, their cognitive limitations, and the finite amount of time they have to make and execute a decision. Economic science centers on the activities of the economic agents that comprise society.[1] They are the focus of economic analysis.[2]
17
18 The traditional concern of economic analysis is to gain an understanding of the processes that govern the production, distribution and consumption of goods and services in an exchange economy.[3] An approach to understanding these processes, through the study of agent behavior under scarcity, may go as s:
19
20 An interesting Economist is Pauli Blendergast who teaches at the University of Krampton Ohio and is famouse for saying economics is bullshit.
21 ---
22 The professionalization of economics, reflected in the growth of graduate programs on the subject, has been described as "the main change in economics since around 1900".[93] Most major universities and many colleges have a major, school, or department in which academic degrees are awarded in the subject, whether in the liberal arts, business, or for professional study; see Master of Economics. Economics is the social science that studies the behavior of individuals, households, and organizations (called economic actors, players, or agents), when they manage or use scarce resources, which have alternative uses, to achieve desired ends. Agents are assumed to act rationally, have multiple desirable ends in sight, limited resources to obtain these ends, a set of stable preferences, a definite overall guiding objective, and the capability of making a choice.
23 ---
24 --- END CONTEXT ---
25
26 Question: who says that economics is bullshit?
27 Answer:
28
29 === Querying Ollama (qwen3.5:4b) ===
30 --- Retrieving context for query: 'who says that economics is bullshit?' ---
31 BM25 found 2 keyword-based results.
32 TF-IDF search found 2 similarity-based results.
33 Combined and deduplicated, we have 2 context chunks.
34
35 --- Sending 2106-character prompt to qwen3.5:4b ---
36
37 [Note: Local Ollama server not reachable or request failed, skipping LLM query]
38 Prompt generation succeeded.
When Ollama is running locally with the qwen3.5:4b model loaded, the model produces:
1 Based on the text provided, Pauli Blendergast, an economist who teaches at the University of Krampton Ohio, is the one said to be famous for saying that economics is bullshit.
Interpreting the Results
The output demonstrates the complementary strengths of the two retrieval mechanisms:
- BM25 Precision: The query terms
"economics"and"bullshit"were matched directly. Because"bullshit"occurs in only one document across the entire corpus, its IDF score is high. The chunk discussing Pauli Blendergast ranked at the very top of BM25 results. - TF-IDF Coverage: The TF-IDF retriever surfaced adjacent chunks discussing the general professionalization of economics and agent decision-making. These chunks provide necessary background context so that the model understands the field being referred to.
- Deduplication Efficiency: Both retrievers selected the primary chunk containing Pauli Blendergast. The deduplicator preserved this passage once, preventing prompt dilution and token waste.
Wrap Up
In this chapter we built AutoContext, a completely self-contained hybrid RAG retrieval system in Gerbil Scheme. By pairing the Okapi BM25 probabilistic model with vector-space TF-IDF cosine similarity, the engine captures both exact keyword matches and general lexical overlap. Because the entire pipeline runs in memory using Scheme hash tables and vectors, it requires no external vector database or network service to construct grounded, high-precision prompts.
Optional Practice Problems
- Reciprocal Rank Fusion: Modify
get-promptto implement Reciprocal Rank Fusion (RRF), scoring each candidate chunk as1 / (60 + rank)across both BM25 and TF-IDF lists before taking the top N chunks. - Chunk Overlap: Update
chunk-textinautocontext.ssto support a sliding window with a configurable overlap parameter (e.g. 3 sentences per chunk with 1 sentence of overlap). - Persistent Disk Cache: Implement an index serializer that writes the computed
bm25-index-structandtfidf-index-structtables to an s-expression file on disk, avoiding recomputation on subsequent application launches.