Chunking, one client for an API and a local model, a spending cap that fires before the bill, blind judging, and a decision rule that caught me fitting the data
This is my own measurement on my own data. The numbers are from November 2026, and I describe the subject area only in general terms. Every program output below comes from running the code shown here. Where I quote the original run instead of repeating it, I say so.
In short: dropping the “all words” requirement raised recall@10 from 0.16 to 0.37, with no model and for $0. The model added another 14 to 20 points on top. And the decision rule I wrote before the first run caught me fitting the data: the best number, 0.57, comes from rules I invented on the same 23 queries. The code below shows how each of these numbers was measured.
This is the second of three articles. Part 1 was a no-code overview: what embedding models are, what they cost, why an open model beat a commercial one, and the first steps toward cross-language search. Part 2 is the practice: how to compare embedding models on your own data before you build the feature. Part 3 will cover how it runs day to day and what acceptance testing showed. It is still in progress.
All the code is Go 1.26 with the standard library only: no SDKs, no frameworks. Every model here returns vectors over a plain HTTP protocol, so an SDK adds nothing.
I ran the original measurement with quick scripts. For this article I rewrote the key parts in Go and checked them against the same data:
I did not repeat the parts that cost money or depended on that particular day: the paid embedding log, the provider’s bill, the story of the dropped connections, and latency under load. Those places are marked.
In the test output below I trimmed the file_test.go:NN: prefixes and wrapped the longest lines. The numbers are unchanged.
The corpus is 810 court decisions in Ukrainian, 30.86 million characters. It’s a debugging sample of decisions picked at random from public sources; the working corpus will start at 100,000 documents.
The measurement had to answer two questions:
I wrote the decision rule down before the first run. It had three outcomes:
The number 10 was a judgment call with no statistics behind it. The gain had to be visible on 23 queries from one judge and pay for the memory the model would take. The second outcome matters as much as the first: it keeps a vector from “winning” where fixing keyword search would have been enough. How the rule played out is in the results section, and it’s the most useful part of this article.
The OpenSearch node for the test is temporary: a separate container on 127.0.0.1:9201 with no data volume. It never touches the main node, and after the test I delete the container and nothing is left behind.
An embedding model encodes a limited span of text, and one vector can’t describe a document tens of thousands of characters long. So each document is cut into chunks, and in search a document is represented by its best chunk.
I first wanted to cut along the document’s logical sections. The data said no: almost all the text sat in one section. So I cut by paragraph. The target is 1,500 characters and the hard limit is 2,500. A paragraph is never split unless it’s longer than the limit, and then it’s split at the end of a sentence.
const ( Target = 1500 // a passage aims at this many characters HardMax = 2500 // and never exceeds this many)var ( paragraphBreak = regexp.MustCompile(`\n+`) sentenceEnd = regexp.MustCompile(`[.!?;:]\s+`))// runeLen counts characters, not bytes: a Cyrillic// letter is two bytes in UTF-8.func runeLen(s string) int { return utf8.RuneCountInString(s) }// Passages cuts a document into runs of whole paragraphs// of about Target characters, in reading order.func Passages(text string) []string { var out []string current := "" for _, raw := range paragraphBreak.Split(text, -1) { paragraph := strings.Join(strings.Fields(raw), " ") if paragraph == "" { continue } parts := []string{paragraph} if runeLen(paragraph) > HardMax { parts = splitLong(paragraph) } for _, part := range parts { if current != "" && runeLen(current)+1+runeLen(part) > Target { out = append(out, current) current = part } else if current != "" { current += "\n" + part } else { current = part } } } if current != "" { out = append(out, current) } return out}// sentences splits after . ! ? ; : and drops the// whitespace that follows. RE2 has no lookbehind, so the// cut point is taken from the match itself.func sentences(s string) []string { var out []string start := 0 for _, m := range sentenceEnd.FindAllStringIndex(s, -1) { // the punctuation mark is one byte out = append(out, s[start:m[0]+1]) start = m[1] } return append(out, s[start:])}
splitLong cuts a paragraph longer than HardMax into sentences, and a sentence longer than the limit at its last space. I left it out here for brevity.
Go has two traps for Cyrillic text:
A golden test checks the chunking: it cuts the whole corpus again and compares the SHA-256 of the chunk stream with the reference.
passages: measure 24716, Go 24716documents 810, 30.5 passages each; characters median 1312, p95 1489, max 2499--- PASS: TestPassagesGolden (2.42s)
The result:
chunks 24,716 (30.5 per doc)length, median 1,312 characters95th percentile 1,489 charactersmaximum 2,499 charactersvectors 24,716 × 1024 × f32 = 101 MB
Ollama and OpenRouter speak the same protocol, the OpenAI-compatible /embeddings. So one client covers both, and only the address changes: https://openrouter.ai/api/v1 with a key for the API, and http://localhost:11434/v1 with no key for the local model.
// Client speaks the OpenAI-compatible /embeddings protocol.// OpenRouter and a local Ollama both serve it, so one client// covers the API and the own copy.type Client struct { BaseURL string // OpenRouter or http://localhost:11434/v1 APIKey string // empty for Ollama HTTP *http.Client}type embedRequest struct { Model string `json:"model"` Input []string `json:"input"` Dimensions int `json:"dimensions,omitempty"` // OpenAI only}type embedResponse struct { Data []struct { Index int `json:"index"` Embedding []float32 `json:"embedding"` } `json:"data"` Usage struct { PromptTokens int `json:"prompt_tokens"` } `json:"usage"`}// Embed returns one vector per text, in input order, and// the tokens the provider billed for the batch.func (c *Client) Embed( ctx context.Context, model string, texts []string, dims int,) ([][]float32, int, error) { body, err := json.Marshal(embedRequest{ Model: model, Input: texts, Dimensions: dims, }) if err != nil { return nil, 0, err } var out embedResponse for attempt := 0; ; attempt++ { req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/embeddings", bytes.NewReader(body)) if err != nil { return nil, 0, err } req.Header.Set("Content-Type", "application/json") if c.APIKey != "" { req.Header.Set("Authorization", "Bearer "+c.APIKey) } resp, err := c.HTTP.Do(req) if err != nil { return nil, 0, err } retry := resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 if retry && attempt < 5 { resp.Body.Close() time.Sleep(time.Duration(1<<attempt) * time.Second) continue } if resp.StatusCode != http.StatusOK { resp.Body.Close() // 402 lands here: on OpenRouter it also means // "in-flight budget exhausted". return nil, 0, fmt.Errorf("embeddings: HTTP %d", resp.StatusCode) } err = json.NewDecoder(resp.Body).Decode(&out) resp.Body.Close() if err != nil { return nil, 0, err } break } if len(out.Data) != len(texts) { return nil, 0, fmt.Errorf("asked for %d vectors, got %d", len(texts), len(out.Data)) } sort.Slice(out.Data, func(i, j int) bool { return out.Data[i].Index < out.Data[j].Index }) vecs := make([][]float32, len(out.Data)) for i, d := range out.Data { vecs[i] = d.Embedding } return vecs, out.Usage.PromptTokens, nil}
Three details cost me time.
First, only OpenAI models understand dimensions, which asks for a shortened vector. I asked for 1,024 of 3,072 so that the comparison with bge-m3 ran at the same size. Other models answer in their own size, so check the vector length after each response.
Second, the order of results isn’t guaranteed. Sorting by index is mandatory: a vector attached to the wrong chunk breaks the measurement without any error.
Third, usage.prompt_tokens is the only honest record of spending. Both OpenRouter and Ollama return it. Here is Ollama's answer for the phrase «рішення суду першої інстанції» ("decision of the court of first instance"):
{"object":"list","model":"bge-m3", "usage":{"prompt_tokens":7, "total_tokens":7}, "data":[…1024 numbers…]}
Requests go in batches of 64 chunks. The client retries only 429 and 5xx answers: a dropped connection ends the run, and resuming covers it. Vectors are appended to a file, and Step 3 shows how that makes a run resumable.
A paid run has to stop before it overspends, not report the overspend on the bill. The check runs before each batch, so the batch that crosses the cap still goes out: the overshoot is at most one batch of 64 chunks, well under a cent.
The price comes first. Prices change, so the price comes from the provider’s catalog, not from a constant in the code. PricePerToken sends a GET to https://openrouter.ai/api/v1/embeddings/models, checks the HTTP status (an error page is not a price list), and hands the body to the parser:
// catalogPrice finds a model in the catalog; the price is// a string of dollars per token.func catalogPrice(r io.Reader, model string) (float64, error) { var cat struct { Data []struct { ID string `json:"id"` Pricing struct { Prompt string `json:"prompt"` } `json:"pricing"` } `json:"data"` } if err := json.NewDecoder(r).Decode(&cat); err != nil { return 0, err } for _, m := range cat.Data { if m.ID == model { return strconv.ParseFloat(m.Pricing.Prompt, 64) } } return 0, fmt.Errorf("%s is not in the embeddings catalog", model)}
price openai/text-embedding-3-large $0.130 per 1M tokensprice baai/bge-m3 $0.010 per 1M tokens
Then the meter. After every batch it projects the cost of the whole corpus from the actual tokens-per-character ratio and stops the run if the projection is over the cap.
// Meter sums what the provider billed and projects the// whole corpus from the tokens-per-character ratio so far.type Meter struct { Price float64 // dollars per token CapUSD float64 TotalChars int // the whole corpus, in runes, before the run Tokens int Chars int Unbilled int // batches returned without a token count}func (m *Meter) Add(texts []string, tokens int) { if tokens <= 0 { m.Unbilled++ // no usage: this batch's spend is unknown } m.Tokens += tokens for _, t := range texts { // runes, not bytes: Cyrillic is 2 bytes per letter m.Chars += utf8.RuneCountInString(t) }}func (m *Meter) Spent() float64 { return float64(m.Tokens) * m.Price}func (m *Meter) CharsPerToken() float64 { if m.Tokens == 0 { return 0 // nothing billed yet } return float64(m.Chars) / float64(m.Tokens)}func (m *Meter) Projected() float64 { if m.Chars == 0 { return 0 } return m.Spent() / float64(m.Chars) * float64(m.TotalChars)}// Check stops the run before the next batch is sent,// not after the bill.func (m *Meter) Check() error { if m.Unbilled > 0 { // Without a token count the spend stays at zero // and no cap can fire. return fmt.Errorf("stop: %d batches came back without "+ "usage; the spend is unknown", m.Unbilled) } if p := m.Projected(); p > m.CapUSD || m.Spent() > m.CapUSD { return fmt.Errorf("stop: projected $%.2f is over "+ "the cap $%.2f", p, m.CapUSD) } return nil}
A batch without usage stops the run. If the provider doesn't return a token count, the spend stays at zero and the cap can never fire. The first version of this code had exactly that hole. It never triggered during the test, because both providers returned usage, but now such a batch stops everything. How this works in daily operation is a topic for Part 3.
Here is the log of the real paid run. I didn’t repeat it for the article; the first, script version of the same meter wrote it. The projection settles after the first few hundred chunks:
model openai/text-embedding-3-large, $0.130/M tokens, cap $3.00; 24716 passages, 0 already embedded256/24716 spent $0.024, whole corpus ~$2.36512/24716 spent $0.048, whole corpus ~$2.35…24716/24716 spent $2.344, whole corpus ~$2.34done: 18030368 tokens, $2.344
model baai/bge-m3, $0.010/M tokens, cap $0.50; 24716 passages, 0 already embedded256/24716 spent $0.001, whole corpus ~$0.08…done: 7871701 tokens, $0.079
The spend is written to disk after every batch. A dropped connection taught me this: 128 chunks were left unrecorded, and I had to estimate their cost from the average price.
Vectors are written one after another as little-endian float32, so the file size alone says how many are done:
const ( Dim = 1024 // the vector size of every model in the test Batch = 64 // passages per request)// Done is the number of passages already embedded: the// whole vectors in the file. A size that is not a whole// number of vectors means a write was cut short; that is// for a human to look at, not for the run to guess.func Done(path string) (int, error) { st, err := os.Stat(path) if errors.Is(err, fs.ErrNotExist) { return 0, nil } if err != nil { return 0, err } if st.Size()%(Dim*4) != 0 { return 0, fmt.Errorf("%s: %d bytes is not a whole "+ "number of vectors", path, st.Size()) } return int(st.Size() / (Dim * 4)), nil}// AppendVectors writes a batch at the end of the file as// little-endian float32 and syncs it to disk.func AppendVectors(path string, vecs [][]float32) error { buf := make([]byte, 0, len(vecs)*Dim*4) for _, v := range vecs { if len(v) != Dim { return fmt.Errorf("vector of %d numbers, want %d", len(v), Dim) } for _, x := range v { buf = binary.LittleEndian.AppendUint32(buf, math.Float32bits(x)) } } f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } if _, err := f.Write(buf); err != nil { f.Close() return err } if err := f.Sync(); err != nil { f.Close() return err } return f.Close()}
The embedding loop starts where the file ends and checks the cap before every batch:
// EmbedAll embeds the passages the vector file does not// hold yet; dims is passed to the API as is. A rerun after// a crash starts where the file ends and asks the API for// nothing twice. The spend is saved before the vectors: a// crash between the two re-asks one batch and counts it// twice, so the record errs above the bill, never below.func EmbedAll( ctx context.Context, c *Client, model string, dims int, passages []string, vecPath, costPath string, m *Meter,) error { done, err := Done(vecPath) if err != nil { return err } if err := loadMeter(costPath, m); err != nil { return err } if done > 0 && m.Chars == 0 { return fmt.Errorf("%s holds %d vectors but %s has no "+ "spend for them", vecPath, done, costPath) } for start := done; start < len(passages); start += Batch { if err := m.Check(); err != nil { return err } batch := passages[start:min(start+Batch, len(passages))] // dims: 1024 for OpenAI, 0 for the rest vecs, tokens, err := c.Embed(ctx, model, batch, dims) if err != nil { return err } m.Add(batch, tokens) if err := saveMeter(costPath, m); err != nil { return err } if err := AppendVectors(vecPath, vecs); err != nil { return err } } return m.Check()}
The order “spend first, vectors second” is deliberate. A crash between the two repeats one batch and counts it twice, so the spending record can be too high but never too low. saveMeter writes to a temporary file and renames it, so a half-written record can't exist.
The test uses a fake API that fails on its third request. The first run stops after two batches, and the second run finishes the rest. The API is asked about each chunk exactly once, every vector lands in its place, and the spend survives. On the real file from the paid run there is nothing left to resume:
--- PASS: TestEmbedAllResumes (0.05s)--- PASS: TestEmbedAllStopsWithoutUsagevectors-baai_bge-m3.f32: 24716 passages done--- PASS: TestVectorFileGolden (0.00s)
The key number in Part 1 was characters per token: 3.92 for bge-m3 and 1.71 for OpenAI. For an open model you can get it for nothing, because the local copy returns the same usage.prompt_tokens. I take every hundredth chunk, 1% of the corpus, and run it through Ollama:
meter := &Meter{ Price: 0.01e-6, CapUSD: 1, TotalChars: 30862507, } for b := range slices.Chunk(sample, 16) { _, tokens, err := local.Embed(ctx, "bge-m3", b, 0) if err != nil { log.Fatal(err) } meter.Add(b, tokens) if err := meter.Check(); err != nil { log.Fatal(err) } } fmt.Printf("sample %d passages: %d chars, %d tokens, "+ "%.2f chars/token, corpus at $0.01/M ~ $%.3f\n", len(sample), meter.Chars, meter.Tokens, meter.CharsPerToken(), meter.Projected())
sample 248 passages: 312473 chars, 79068 tokens, 3.95 chars/token, corpus at $0.01/M ~ $0.078
Locally, on 1% of the corpus, I got 3.95 characters per token and a projected $0.078. OpenRouter’s bill for the whole corpus said 3.92 and $0.079. My own copy of the model predicted the provider’s bill to within a cent.
This doesn’t work for a closed model, because you can’t run its tokenizer yourself; a sample through the API is the only option. For OpenAI, 1% of my corpus would have cost about $0.02, and those are the best two cents you can spend before choosing a model.
The same sample answers a second question: how many tokens one chunk has by the model’s own count. That matters for models with a 512-token window, which simply don’t read anything past it. Here each chunk needs its own request, because usage counts the whole batch. Part 1 gave a rough “fewer than 5%” for chunks over 512 tokens; the exact count on this sample is lower still.
// TokensEach counts the tokens of every text with the// model's own tokenizer, one request per text: usage covers// a whole batch, and a window limit is a question about// each passage.func TokensEach( ctx context.Context, c *Client, model string, texts []string,) ([]int, error) { counts := make([]int, len(texts)) for i, t := range texts { _, tokens, err := c.Embed(ctx, model, []string{t}, 0) if err != nil { return nil, err } counts[i] = tokens } return counts, nil}
sample 248 passages: median 328 tokens, max 549, over 512: 1 (0.4%)--- PASS: TestTokenWindow (295.06s)
The OpenSearch mapping for the chunk index:
{ "settings": { "index": { "number_of_shards": 1, "number_of_replicas": 0, "knn": true } }, "mappings": { "dynamic": "strict", "_source": { "excludes": ["vector"] }, "properties": { "doc_id": { "type": "long" }, "chunk_no": { "type": "integer" }, "text": { "type": "text", "analyzer": "ukrainian" }, "vector": { "type": "knn_vector", "dimension": 1024, "method": { "name": "hnsw", "engine": "faiss", "space_type": "innerproduct", "parameters": { "m": 16, "ef_construction": 128 } } } } }}
Why each choice:
I checked the length of all 24,716 vectors of each model:
vectors-openai_text-embedding-3-large: 24716 vectors, length from 0.999315 to 1.000747vectors-baai_bge-m3: 24716 vectors, length from 1.000000 to 1.000000--- PASS: TestUnitVectors (0.20s)
bge-m3 vectors have length 1 to six decimal places. OpenAI vectors shortened to 1,024 range from 0.99932 to 1.00075, off by less than 0.08%. To see whether that changes the results, I ranked all chunks twice with the exact brute-force search from Step 9: once by inner product and once by cosine.
openai, 23 queries: same top ten inner vs cosine 21/23; recall@10 inner 0.381, cosine 0.381--- PASS: TestCosineOrInner (1.69s)
The top ten matched on 21 of 23 queries, and recall@10 was identical, so for OpenAI inner product and cosine are equivalent. The run showed something else along the way: exact search gave OpenAI 0.381, while the index gave 0.371. In Step 9 bge-m3 goes the other way, 0.510 for exact search against 0.520 for the index. Approximate HNSW search moves recall by about ±0.01 in either direction, and normalization has nothing to do with it.
Search asks for extra nearest chunks (k = top × 5) and folds them into documents. A document takes the place of its best chunk.
// PassageDocs searches the passage index and folds the// passages to documents: a document ranks by its best// passage.func PassageDocs( ctx context.Context, hc *http.Client, osURL, index string, query map[string]any, top int,) ([]int64, error) { var out struct { Hits struct { Hits []struct { Source struct { DocID int64 `json:"doc_id"` } `json:"_source"` } `json:"hits"` } `json:"hits"` } body := map[string]any{ "size": top * 5, "_source": []string{"doc_id"}, "query": query, } if err := search(ctx, hc, osURL, index, body, &out); err != nil { return nil, err } seen := map[int64]bool{} var docs []int64 for _, h := range out.Hits.Hits { if !seen[h.Source.DocID] { seen[h.Source.DocID] = true docs = append(docs, h.Source.DocID) } } if len(docs) > top { docs = docs[:top] } return docs, nil}// KNNDocs is branch V: the nearest passages to the query// vector.func KNNDocs( ctx context.Context, hc *http.Client, osURL, index string, vec []float32, top int,) ([]int64, error) { knn := map[string]any{"knn": map[string]any{ "vector": map[string]any{"vector": vec, "k": top * 5}, }} return PassageDocs(ctx, hc, osURL, index, knn, top)}
search sends a POST to _search and decodes the JSON; it's a plain HTTP call, so I left it out.
The × 5 margin is there because one document often has several close chunks. Without it, the ten nearest chunks collapse into just a few documents.
Judging all 810 documents for every query is not realistic. So for each query I merge the top ten from every search branch (the branches are in Step 7), and I judge only that merged pool. The order is random but reproducible. Documents already judged for the query stay out of the pool, so a new round shows only new documents and earlier judgments still count.
// Pool unites the top k of every branch for one query,// leaves out what is already marked for it and shuffles the// rest with a fixed seed: the marker sees neither the// branch nor its rank, a new round shows only new// documents, and the page can be rebuilt byte for byte.func Pool( queryID string, k int, branches map[string][]int64, marked map[int64]bool,) []int64 { seen := map[int64]bool{} var pool []int64 for _, ranking := range branches { for _, d := range ranking[:min(k, len(ranking))] { if !seen[d] && !marked[d] { seen[d] = true pool = append(pool, d) } } } // map order is random in Go; sort before the // seeded shuffle slices.Sort(pool) var seed [32]byte copy(seed[:], fmt.Sprintf("pool-%s", queryID)) r := rand.New(rand.NewChaCha8(seed)) r.Shuffle(len(pool), func(i, j int) { pool[i], pool[j] = pool[j], pool[i] }) return pool}
The Go trap here: iteration order over a map is random on every run. Without slices.Sort before the shuffle, the "fixed seed" fixes nothing.
A test on toy branches checks that after judging, the same pool is empty and a new branch brings only its own new document. A test on the real data builds the pool from every branch of all three rounds and subtracts the 821 judgments:
--- PASS: TestPoolSkipsMarked (0.00s)queries 23, marks 821: documents left to mark 0--- PASS: TestPoolGolden (0.00s)
Zero means the top tens of all branches contain no document I haven’t judged.
The page is one static HTML file with no server. Each document card hides which branch found it and at what rank. It has relevant/not-relevant checkboxes, and judgments are saved in the browser’s localStorage and exported to JSON with one button. A judgment's key is "<query>:<document>" and its value is 1 or 0.
I judged in three rounds. The main lesson was that every card needs the same evidence. In the first round, the excerpt from the best vector chunk appeared only on cards for documents the vector branch had found, and I marked those relevant 40% of the time against 16% for the rest. In the second round every card showed two excerpts: the best chunk by keywords and the best by meaning. I saw the 140 first-round cards that had lacked the vector excerpt again, and not one judgment changed.
round 1: with the vector passage 389 cards, relevant 40%; without 140, relevant 16%round 2: cards of round 1 shown again 140, marks changed 0--- PASS: TestMarkingRounds (0.00s)
There was no bias, but without the check I wouldn’t have known that.
// RecallAt is the share of the relevant documents a ranking// puts in its top k.func RecallAt( k int, ranking []int64, relevant map[int64]bool,) float64 { if len(relevant) == 0 { // nothing to find: a gap in the marks, // not a perfect score return 0 } hits := 0 for _, d := range ranking[:min(k, len(ranking))] { if relevant[d] { hits++ } } return float64(hits) / float64(len(relevant))}// NDCGAt is binary nDCG: a relevant document at rank i// gains 1/log2(i+1).func NDCGAt( k int, ranking []int64, relevant map[int64]bool,) float64 { var dcg, ideal float64 for i, d := range ranking[:min(k, len(ranking))] { if relevant[d] { dcg += 1 / math.Log2(float64(i+2)) } } for i := range min(k, len(relevant)) { ideal += 1 / math.Log2(float64(i+2)) } if ideal == 0 { return 0 // no relevant document: same as RecallAt } return dcg / ideal}// CeilingAt is the best recall@k any ranking can reach:// k slots for len(relevant) documents.func CeilingAt(k int, relevant map[int64]bool) float64 { return float64(min(k, len(relevant))) / float64(len(relevant))}
If a query has no relevant documents, both metrics return 0. Dividing by zero would give NaN, and one NaN would poison the average over all queries.
marks 821, queries 23: V bge-m3 recall@10 0.509 nDCG@10 0.657, ceiling 0.799most relevant documents for one query: 44, its ceiling 0.23--- PASS: TestMetricsGolden (0.00s)
Two things every report reader needs explained.
The first is the ceiling. A query with 44 relevant documents can’t get a recall@10 above 10/44 = 0.23. The average ceiling on my queries is 0.80. Without it, 0.51 reads as “half”, when it’s nearly two thirds of what’s achievable.
The second is that pooling lowers recall from round to round. Each new model finds new relevant documents, and the denominator grows. The same branch, the OpenAI hybrid, scored 0.703, then 0.661, then 0.499, though the branch itself never changed:
rounds 1..1 (529 marks): H openai recall@10 0.703rounds 1..2 (657 marks): H openai recall@10 0.661rounds 1..3 (821 marks): H openai recall@10 0.499
Numbers from different rounds can’t be compared. Every table from here on uses the final set of 821 judgments.
The main defense against fooling yourself is a strong opponent. The “all words” mode almost always returns nothing for a query written as a sentence, so beating it with a vector proves nothing. That’s why there are four keyword branches:
L1 old search: multi_match, best_fields, operator "and", over whole documentsL2 the same without "all words": minimum_should_match "40%"LC L2 over the chunk index's text field; doc = its best chunkL2LC best without a model: fusion of L2 and LCV vectors only (KNNDocs, Step 5)H hybrid: fusion of L2 and V
LC separates the model’s contribution from the chunking’s. V searches short chunks while L2 searches whole documents. Without LC you can’t tell what produced the gain: the model, or the shorter unit of search.
The keyword branches use plain OpenSearch BM25 with the same request bodies as ordinary keyword search. The fields depend on your schema; mine are the full text, several weighted fields, and the document number. Here is the L2 body, with section names generalized:
{ "size": 100, "_source": false, "query": { "multi_match": { "query": "<query>", "type": "best_fields", "fields": [ "full_text", "sections.<section_1>^3", "sections.<section_2>^2", "sections.<section_3>", "sections.<section_4>", "sections.<section_5>", "number.text^2"], "minimum_should_match": "40%" } }}
L1 differs by one line: "operator": "and" instead of minimum_should_match. The code for this request (LexicalDocs) is the same kind of plain HTTP call, so I left it out. Branch LC asks for the same 40% of words, over chunks:
// L2Match is how much of a sentence-long query a document// must contain in branches L2 and LC: 40% of the words,// not all of them.const L2Match = "40%"// LCDocs is branch LC: BM25 over the same passages the// vectors see. It tells the gain of the model apart from// the gain of a shorter unit of search.func LCDocs( ctx context.Context, hc *http.Client, osURL, index, query string, top int,) ([]int64, error) { match := map[string]any{"match": map[string]any{ "text": map[string]any{ "query": query, "minimum_should_match": L2Match, }, }} return PassageDocs(ctx, hc, osURL, index, match, top)}
All three branches in Go return the same top tens as the original run:
queries 23: same top ten L1 23, L2 23, LC 23--- PASS: TestLexicalGolden (0.80s)
Fusion uses Reciprocal Rank Fusion (RRF) [1]. BM25 scores and cosines live on incompatible scales, so RRF adds up ranks instead: each document gets the sum of 1/(k + rank) across branches.
// RRF merges rankings by reciprocal rank:// score = sum of 1/(k + rank).func RRF(k float64, rankings ...[]int64) []int64 { score := map[int64]float64{} for _, r := range rankings { for i, doc := range r { score[doc] += 1 / (k + float64(i+1)) } } docs := make([]int64, 0, len(score)) for d := range score { docs = append(docs, d) } sort.Slice(docs, func(i, j int) bool { if score[docs[i]] != score[docs[j]] { return score[docs[i]] > score[docs[j]] } // ties by id: the same input gives the same order return docs[i] < docs[j] }) return docs}
A toy example, RRF(60, [1 2 3], [3 1 4]):
rrf: [1 3 2 4]
k = 60 is the conventional value, and I didn't tune it. I do the fusion in Go. OpenSearch has built-in hybrid search, but in Go both branches stay visible, and the test can score each one separately.
Before computing any tables, I rebuilt both fusions on the test node from each branch’s top hundred and compared them with the saved top tens:
L2LC = RRF(L2, LC): same top ten 23/23semeval_chunks (OpenAI): same top ten V 23/23; H = RRF(L2, V) same documents 23/23, same order 22/23semeval_chunks_baai_bge-m3: same top ten V 23/23; H = RRF(L2, V) same documents 23/23, same order 23/23--- PASS: TestFusionGolden (2.88s)
In one OpenAI query, two neighbors in the hybrid top ten swapped places: below the top ten, today’s vector results differ slightly from the saved ones. The documents in the top ten are the same, so recall@10 doesn’t change.
Two routing rules sit on top of the fusion:
// Route puts two rules over the fusion: a query with a// document number goes to the word search L1, a query L1// finds nothing for goes to the vectors alone, and every// other query takes the fusion H.func Route(hasNumber bool, l1, v, h []int64) []int64 { switch { case hasNumber: return l1 case len(l1) == 0: return v } return h}
I detect a document number in a query by the number format used in my corpus. In the test, the flag comes from the query’s label, and on all 23 queries it agrees with the format.
Why the rules were needed: fusion without rules helped one model and hurt the other. The same test that prints the final table prints this one (recall@10, 821 judgments, V → H):
queries OpenAI bge-m3all 23 0.37 → 0.50 0.51 → 0.42paraphrase (17) 0.36 → 0.46 0.53 → 0.49Russian (3) 0.68 → 0.41 0.78 → 0.32numbers (2) 0 → 1.00 0 → 0
The keyword branch L2 that both fuse with doesn’t depend on the model: 0.31 for both.
For OpenAI, fusion helped on paraphrases and rescued the document numbers: the numbered document, first in the keyword results, stayed in the top ten. Two mid-strength result lists, by keywords and by meaning, complemented each other. bge-m3’s vector results are stronger, so fusion dilutes them: paraphrases lose 0.04, and numbered documents drop out of the top ten entirely.
Russian queries suffer most. The “all words” mode finds nothing for them. The “40% of words” mode finds a few documents through chance overlaps between Russian and Ukrainian words. That’s noise, and it pushes out the accurate semantic results: 0.78 drops to 0.32.
So “hybrid is always better” turned out to be false for one of the two models, and that gave me two rules. “Number → old search” fixes numbered queries. “Old search found nothing → vectors only” fixes Russian queries. The rule looks at L1 on purpose: in a foreign language L2 isn’t empty, it’s noisy. With the rules, bge-m3 reaches 0.57, the “bge-m3 + keywords + rules” row in the final table.
One caveat, which I come back to in the results: I invented both rules while looking at these same 23 queries. How they hold up day to day is for Part 3.
The plan is for the API to embed documents and for a local copy of the model to encode queries. That only works if the vectors match; otherwise query vectors and document vectors end up in different spaces. The check uses cosine similarity and the overlap of search results.
// Cosine of two vectors; bge-m3 vectors are unit length,// so this equals the inner product the k-NN index uses.func Cosine(a, b []float32) float64 { var dot, na, nb float64 for i := range a { dot += float64(a[i]) * float64(b[i]) na += float64(a[i]) * float64(a[i]) nb += float64(b[i]) * float64(b[i]) } return dot / (math.Sqrt(na) * math.Sqrt(nb))}
for _, q := range qs.Queries { t := time.Now() v, _, err := local.Embed(ctx, "bge-m3", []string{q.Text}, 0) if err != nil { log.Fatal(err) } lat = append(lat, time.Since(t)) minCos = min(minCos, Cosine(v[0], api[q.ID])) // the local query vector a, err := KNNDocs(ctx, hc, osURL, index, v[0], 10) if err != nil { log.Fatal(err) } // the API's b, err := KNNDocs(ctx, hc, osURL, index, api[q.ID], 10) if err != nil { log.Fatal(err) } if sameSet(a, b) { same++ } if slices.Equal(a, b) { sameOrder++ } rel := map[int64]bool{} for k, m := range marks { qid, doc, _ := strings.Cut(k, ":") if qid == q.ID && m == 1 { id, _ := strconv.ParseInt(doc, 10, 64) rel[id] = true } } recallLocal += RecallAt(10, a, rel) recallAPI += RecallAt(10, b, rel) }
queries 23: min cosine local vs API 0.99999, same top-10 23/23, same order 15/23, recall@10 0.509 vs 0.509median local encode 48mspassages 1024: cosine local vs API from 0.99990 to 0.99999
Query vectors agree to a cosine of at least 0.99999. The top tens matched on all 23 queries, and the order within the top ten matched on 15. On the rest, near-equal neighbors swapped places, and recall@10 didn’t change. The first 1,024 chunk vectors, computed locally and through the API, agree to between 0.99990 and 0.99999. It’s the same model: the local F16 build in Ollama and the provider on OpenRouter. Part 3 shows how this check runs in daily operation.
i5-9600K, CPU only, run for this article 48 mssame machine in the first test, under load (load avg ≈ 6) 0.4–0.5 s
Those are medians for encoding one query. On a CPU the model shares cores with everything else, which leads to two practical conclusions: measure query latency on the target machine under real load, and give the model its own cores or limit its neighbors. A cache of query vectors removes the problem for repeated queries.
In Part 1 I built a ladder of languages: a Ukrainian query against Ukrainian documents, then Russian, then Polish. This is the code that computed it. The local bge-m3 encodes the queries, so the whole check costs $0.
Comparing languages through the HNSW index is awkward: the index is approximate, and the graph itself can account for part of the difference between two result lists. So this step uses exact brute force over the vector file. LoadVectors reads the whole .f32 file, BruteTopK computes the inner product of the query with each of the 24,716 chunks, and a document again takes the place of its best chunk.
// BruteTopK ranks documents by their best passage against// q, scoring every passage in the file: no index and no// approximation, so a change in the top ten is the query's// doing, not the graph's. docOf[i] is the document of// passage i.func BruteTopK( vecs []float32, docOf []int64, q []float32, k int,) []int64 { best := map[int64]float64{} for i, doc := range docOf { var dot float64 for j, x := range vecs[i*Dim : (i+1)*Dim] { dot += float64(x) * float64(q[j]) } if s, ok := best[doc]; !ok || dot > s { best[doc] = dot } } docs := make([]int64, 0, len(best)) for d := range best { docs = append(docs, d) } slices.SortFunc(docs, func(a, b int64) int { // ties by id, as in RRF return cmp.Or(cmp.Compare(best[b], best[a]), cmp.Compare(a, b)) }) return docs[:min(k, len(docs))]}// Overlap is how many documents two top lists share.func Overlap(a, b []int64) int { n := 0 for _, d := range a { if slices.Contains(b, d) { n++ } } return n}
First, a sanity check. On the 18 Ukrainian queries without document numbers, exact search nearly reproduces the index:
ukrainian 18 queries: brute force vs index same documents 9.3/10, recall@10 0.510 vs 0.520
On average 9.3 of the 10 documents are the same, and recall@10 is 0.510 against 0.520. Same method, so the comparison holds.
The second problem is that the existing judgments may not cover a foreign-language result list. A Russian or Polish query pulls into its top ten documents nobody has judged for that meaning. Counting them as irrelevant would be unfair, so recall here is a lower bound, and the code reports how many documents are unjudged:
// RecallLowerBound scores a ranking against the marks of// one query (1 is relevant, 0 is not) and counts the// documents in its top k nobody has marked yet. Each of// those may still turn out relevant, so the recall is a// floor.func RecallLowerBound( k int, ranking []int64, marks map[int64]int,) (recall float64, unmarked int) { relevant := map[int64]bool{} for d, v := range marks { if v == 1 { relevant[d] = true } } for _, d := range ranking[:min(k, len(ranking))] { if _, ok := marks[d]; !ok { unmarked++ } } return RecallAt(k, ranking, relevant), unmarked}
The test has Russian queries for only three meanings, and each has a Ukrainian twin. The Russian results are scored against the twin’s judgments:
pair 1: same docs brute 9/10, index 9/10 recall@10 ukr 0.50, rus >= 0.44 (1 unmarked; index >= 0.44, 1 unmarked)pair 2: same docs brute 8/10, index 8/10 recall@10 ukr 1.00, rus >= 1.00 (1 unmarked; index >= 1.00, 2 unmarked)pair 3: same docs brute 7/10, index 7/10 recall@10 ukr 0.64, rus >= 0.50 (3 unmarked; index >= 0.50, 3 unmarked)pairs 3: recall@10 ukr 0.71, rus >= 0.65, 5 unmarked (index: rus >= 0.65, 6 unmarked)
The twins’ top tens share 9, 8, and 7 documents. On the same judgments the Ukrainian queries score 0.71 and the Russian ones at least 0.65. Exact search leaves 5 unjudged documents in the Russian top tens and the index leaves 6. The result lists differ slightly, but the lower bound is the same.
The Polish queries are translations of the same 18 Ukrainian ones. A language model did the translation, and no professional translator reviewed it. They are scored against the judgments of their Ukrainian originals:
polish 18 queries: recall@10 ukr 0.510, pol >= 0.378; same documents 6.3/10; better 0, equal 3, worse 15; 55 unmarked--- PASS: TestCrossLingual (3.95s)
In Polish the model searches noticeably worse: 0.51 against at least 0.38. The Polish top tens hold 55 unjudged documents, about a third of the results, and some of them are likely relevant. On average 6.3 of 10 documents match. Polish was never better, tied on 3 queries, and was worse on 15.
query → document n recall@10UA → UA 18 0.51PL → UA, same meanings 18 ≥ 0.38UA → UA, twin pairs 3 0.71RU → UA, same pairs 3 ≥ 0.65
Rungs of this ladder can be compared only on the same meanings. In the per-type table in Step 7, Russian queries score 0.78 and Ukrainian queries without numbers 0.52, but those are different queries, and there are only three Russian ones. On the same meanings, Russian trails Ukrainian, as it should.
The final table, on 821 judgments and 23 queries (the ceiling is 0.80):
recall nDCG @10 @10old "all words" search 0.16 0.21best without a model 0.37 0.48meaning only, OpenAI 0.37 0.49meaning only, bge-m3 0.51 0.66hybrid, no rules, OpenAI 0.50 0.58hybrid, no rules, bge-m3 0.42 0.56OpenAI + keywords + rules 0.53 0.66bge-m3 + keywords + rules 0.57 0.70
One test prints every row. Here L2LC is the best variant without a model, V is vectors only, H is the hybrid without rules, and R is the hybrid with routing rules:
L1 recall@10 0.161 nDCG@10 0.208L2 recall@10 0.314 nDCG@10 0.400L2LC recall@10 0.371 nDCG@10 0.480V openai recall@10 0.371 nDCG@10 0.488V bge-m3 recall@10 0.509 nDCG@10 0.657H openai recall@10 0.499 nDCG@10 0.575H bge-m3 recall@10 0.420 nDCG@10 0.561R openai recall@10 0.534 nDCG@10 0.661R bge-m3 recall@10 0.567 nDCG@10 0.702V openai vs L2LC -0.0 ppV bge-m3 vs L2LC +13.8 ppH openai vs L2LC +12.8 ppH bge-m3 vs L2LC +4.9 ppR openai vs L2LC +16.3 ppR bge-m3 vs L2LC +19.6 pp--- PASS: TestScoreTable (0.01s)
The answer to the second question: dropping “all words” raised recall@10 from 0.16 to 0.37 with no model and for $0. The model added another 14 to 20 points on top: 14 for bge-m3 vectors alone and 20 for bge-m3 with the rules. The biggest single gain in this whole measurement came from changing one search parameter.
Now the decision rule I wrote down before the run. It demanded two things: a hybrid at least 10 points above the best no-model variant (0.37), and no harm to queries with document numbers, which the old search finds completely, at 1.00.
So by the letter of the rule, the OpenAI hybrid wins. I’m still moving forward with bge-m3 and the rules, but provisionally. The rule measured quality only and left price out, and bge-m3 costs about 30 times less to embed and encodes queries on my own server for free. That’s a gap in the rule, and I’d rather name it than quietly rewrite the rule after seeing the results. The deciding test is on new queries, ones I hadn’t seen when I wrote the rules, in Part 3. And this is exactly why you write a decision rule in advance: it stopped me from passing off 0.57, fitted on the same queries, as a clean win.
The limits of this measurement: 23 queries from one judge show a direction, not precision; I measured 2 models out of roughly 15 suitable ones; and the routing rules were fitted on the same 23 queries.
Part 3, “Day to day: hybrid search, routing, and daily loads,” is still in progress. It will cover:
On we go…
[1] G. V. Cormack, C. L. A. Clarke, and S. Büttcher, “Reciprocal rank fusion outperforms Condorcet and individual rank learning methods,” in Proc. 32nd Int. ACM SIGIR Conf. Research and Development in Information Retrieval, 2009, pp. 758–759.
[2] J. Chen, S. Xiao, P. Zhang, K. Luo, D. Lian, and Z. Liu, “BGE M3-Embedding: Multi-lingual, multi-functionality, multi-granularity text embeddings through self-knowledge distillation,” arXiv:2402.03216, 2024.
[3] OpenSearch Project, “k-NN search,” OpenSearch documentation, version 2.19.
Semantic Search Over Court Decisions Without an LLM. Part 2: How I Measured It, in Go was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.