rony-chat-bot/internal/portfolio/hybrid.go
Victor Hugo Vargas 129809067b feat(rag): hybrid retrieval, reference documents, and vendor sampling
Answers were short, sometimes in the wrong language, and occasionally about
projects that do not exist. Measured on a 20-question battery against the real
corpus in both Spanish and English, this takes grounded content from 3/10 to
9/10 and language matching from 7/10 to 10/10.

Retrieval
- Fuse FTS5 keyword search with dense vectors via Reciprocal Rank Fusion.
  Both halves are load-bearing: the corpus is English and visitors ask in
  Spanish, so the meaningful words score zero. "paga" appears 0 times in a
  document that says "Payments: Stripe" — the question "¿Con qué se paga en la
  tienda de ropa?" retrieved nothing at all. Embeddings put all three of that
  project's chunks on top. RRF ranks by agreement rather than comparing a BM25
  score against a cosine, quantities with no shared scale.
- internal/embed: OpenAI-compatible embeddings client, unit-normalised so a
  dot product is the cosine. Reorders by the response `index` field.
- Store a content hash beside each vector and skip rows where it no longer
  matches the chunk. Chunk ids survive body edits, so without this an edited
  document keeps serving embeddings that describe text that is gone —
  reproduced live by changing a payment provider and watching the old one keep
  coming back.
- Degrade to keyword-only when the embedder is down instead of failing.

Reference documents that are not projects
- Index `.mdx` alongside `.md`, and split sources into projects (announced in
  the catalogue) and reference material (retrievable, never listed). A CV is
  what someone deciding whether to hire actually reads, and it was unreachable
  while it lived only in the Astro site — but filing it under projects made
  the bot list "cv" as one of Victor's works.
- Skip each directory's README. `data/projects/README.md` was being indexed,
  so the catalogue injected into every prompt announced "README" and
  "README.es" as projects of Victor's.
- Exclude frontmatter from retrieval. It is dense metadata in a very short
  chunk, which makes it a magnet for short queries: a CV's `location:` field
  answered "¿Dónde ha trabajado Victor?" with a city instead of a work history.
- Split oversized sections at `###` before falling back to byte offsets. A CV's
  Experience section is a list of jobs, and size-splitting cut one mid-word,
  stranding the employer's name in the previous chunk.

Prompt and sampling
- Inject the full project catalogue every turn. Top-K search returns the best
  matching sections, so "list every project" cannot be answered from retrieval
  alone, and a small model asked to enumerate from partial hits invents the
  rest. ~10 tokens per project; this is what stopped the invented names.
- Wire the sampling parameters the model authors publish (top_k, top_p, min_p,
  repeat_penalty, presence_penalty) through config to llama.cpp. Leaving them
  at llama.cpp's defaults produced 16-token stub answers.
- Localised system prompt selected by detected language. The English prompt
  plus "reply in the user's language" answered 1/5 Spanish questions in
  Spanish; few-shot examples fixed the language but got copied verbatim into
  real answers.
- Fold compaction's system notes into the leading system message. Gemma's chat
  template rejects a system message that is not first, and the whole request
  failed with HTTP 400 the moment compaction fired.

Configuration and docs
- context_size 4096, down from 8192. The largest prompt this bot ever built
  over 20 real requests was 1255 tokens, compaction starts at ~3070, and the
  cut saved 212 MB resident with zero truncations and identical throughput.
- Correct the RAM figures throughout. They were measured with a GPU absorbing
  llama.cpp's buffers; on a GPU-less VPS those come out of system RAM, which
  is 1.1 GB more for qwen2.5-3b and 2.8 GB more for granite. Both READMEs
  still started gemma-3-1b while the config defaulted to qwen, and neither
  started the embedder at all.

Measured on the 2-core, 8 GB CPU-only target: 3.64 GB LLM + 0.91 GB embedder
+ 0.02 GB bot, 21.0 tok/s steady state.

Known and unfixed, so they are not re-filed as new bugs: the model reads dates
out of the CV correctly but does the arithmetic on them wrong, and "¿Dónde ha
trabajado Victor?" still answers with projects rather than employers, though
"¿En qué empresas ha trabajado?" works.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 15:45:36 -07:00

238 lines
7.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package portfolio
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
"sort"
"github.com/VictorVargas/rony-chat-bot/internal/embed"
)
// Embedder is the subset of embed.Client the store needs. Keeping it an
// interface lets Reindex and HybridSearch be tested without an endpoint.
type Embedder interface {
Embed(ctx context.Context, texts []string) ([][]float32, error)
}
// rrfK is the usual Reciprocal Rank Fusion constant. RRF combines rankings
// rather than scores, which matters here because BM25 (unbounded, negative)
// and cosine similarity (01) are not comparable on any common scale. k=60
// is the value from the original paper and is not sensitive enough to be
// worth tuning for a corpus this size.
const rrfK = 60.0
// embedText is the exact string that gets embedded for a chunk, and the only
// definition of it. EmbedChunks and VectorSearch both go through this so the
// hash they compare can never be computed over different text.
//
// The project and heading are prepended because a bare body is ambiguous out
// of context: "Tech stack: Next.js, Stripe" says nothing about which project,
// and the question naming the shop needs to land on it.
func embedText(projectID, section, content string) string {
return projectID + " — " + section + "\n" + content
}
func hashOf(text string) string {
sum := sha256.Sum256([]byte(text))
return hex.EncodeToString(sum[:])
}
// VectorSearch returns the topK chunks whose embedding is closest to the
// query, scanning every stored vector. Chunks indexed before embeddings were
// enabled simply have no row and are skipped.
func (s *Store) VectorSearch(ctx context.Context, queryVec []float32, topK int) ([]SearchResult, error) {
if len(queryVec) == 0 {
return nil, nil
}
if topK <= 0 {
topK = 5
}
rows, err := s.db.QueryContext(ctx, `
SELECT c.id, c.project_id, c.kind, c.source_file, c.section, c.chunk_index, c.content,
v.vec, v.content_hash
FROM portfolio_vectors v
JOIN portfolio_chunks c ON c.id = v.chunk_id
WHERE v.dim = ? AND c.section <> 'frontmatter'`, len(queryVec))
if err != nil {
return nil, fmt.Errorf("vector search: %w", err)
}
defer rows.Close()
var hits []SearchResult
var stale int
for rows.Next() {
var r SearchResult
var blob []byte
var storedHash string
if err := rows.Scan(&r.ID, &r.ProjectID, &r.Kind, &r.SourceFile, &r.Section, &r.Index,
&r.Content, &blob, &storedHash); err != nil {
return nil, err
}
// Skip vectors describing a previous version of this chunk. Chunk
// ids survive body edits, so without this the row would be scored
// against text that is no longer there — quietly, with no error.
// The chunk stays reachable through keyword search meanwhile.
if storedHash != hashOf(embedText(r.ProjectID, r.Section, r.Content)) {
stale++
continue
}
r.Score = embed.Similarity(queryVec, embed.Decode(blob))
hits = append(hits, r)
}
if stale > 0 {
slog.Warn("ignoring stale embeddings; re-run reindex to refresh them", "chunks", stale)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Higher similarity is better, unlike the bm25() score used by Search.
sort.Slice(hits, func(i, j int) bool { return hits[i].Score > hits[j].Score })
return hits[:min(topK, len(hits))], nil
}
// HybridSearch fuses keyword and vector retrieval with Reciprocal Rank
// Fusion and returns the topK chunks.
//
// Neither retriever is sufficient alone on this corpus. Keyword search finds
// exact proper nouns ("Kubernetes", "Stripe") that embeddings can blur, but
// returns nothing when a Spanish question meets an English document. Vectors
// bridge the languages but rank a request for a specific rare token less
// sharply. RRF asks only for each side's ordering, so a chunk that both
// retrievers like rises above one that only a single retriever loved.
//
// When embedding fails — the endpoint is down, or none is configured — this
// degrades to plain keyword search rather than failing the request: a
// keyword-only answer beats no answer.
func (s *Store) HybridSearch(ctx context.Context, embedder Embedder, query string, topK int) ([]SearchResult, error) {
if topK <= 0 {
topK = 5
}
// Over-fetch from each side: a chunk ranked 8th by one retriever and 2nd
// by the other should still be able to win the fusion.
pool := topK * 3
keyword, kwErr := s.Search(ctx, query, pool)
if embedder == nil {
return keyword, kwErr
}
vecs, err := embedder.Embed(ctx, []string{query})
if err != nil || len(vecs) == 0 {
if kwErr != nil {
return nil, fmt.Errorf("both retrievers failed: keyword: %v; embedding: %w", kwErr, err)
}
return keyword, nil
}
semantic, vecErr := s.VectorSearch(ctx, vecs[0], pool)
if vecErr != nil && kwErr != nil {
return nil, fmt.Errorf("both retrievers failed: keyword: %v; vector: %w", kwErr, vecErr)
}
type fused struct {
res SearchResult
score float64
}
byID := map[string]*fused{}
add := func(list []SearchResult) {
for rank, r := range list {
f, ok := byID[r.ID]
if !ok {
f = &fused{res: r}
byID[r.ID] = f
}
f.score += 1 / (rrfK + float64(rank+1))
}
}
add(keyword)
add(semantic)
out := make([]fused, 0, len(byID))
for _, f := range byID {
out = append(out, *f)
}
sort.Slice(out, func(i, j int) bool {
if out[i].score != out[j].score {
return out[i].score > out[j].score
}
return out[i].res.ID < out[j].res.ID // stable across runs
})
results := make([]SearchResult, 0, min(topK, len(out)))
for _, f := range out[:min(topK, len(out))] {
f.res.Score = f.score
results = append(results, f.res)
}
return results, nil
}
// EmbedChunks computes and stores a vector for every indexed chunk. Called
// after Reindex, since it needs the chunks to exist.
//
// The heading is prepended to each chunk's text: a bare "Tech stack" body is
// a list of technologies with no hint of which project it belongs to, and the
// embedding of "tienda-ropa — Tech stack: Next.js, Stripe…" is much closer to
// a question naming the shop.
func (s *Store) EmbedChunks(ctx context.Context, embedder Embedder) (int, error) {
if embedder == nil {
return 0, nil
}
rows, err := s.db.QueryContext(ctx,
`SELECT id, project_id, section, content FROM portfolio_chunks ORDER BY id`)
if err != nil {
return 0, fmt.Errorf("read chunks for embedding: %w", err)
}
var ids, texts []string
for rows.Next() {
var id, project, section, content string
if err := rows.Scan(&id, &project, &section, &content); err != nil {
rows.Close()
return 0, err
}
ids = append(ids, id)
texts = append(texts, embedText(project, section, content))
}
rows.Close()
if err := rows.Err(); err != nil {
return 0, err
}
if len(ids) == 0 {
return 0, nil
}
vecs, err := embedder.Embed(ctx, texts)
if err != nil {
return 0, fmt.Errorf("embed chunks: %w", err)
}
if len(vecs) != len(ids) {
return 0, fmt.Errorf("embedder returned %d vectors for %d chunks", len(vecs), len(ids))
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `DELETE FROM portfolio_vectors`); err != nil {
return 0, err
}
stmt, err := tx.PrepareContext(ctx,
`INSERT INTO portfolio_vectors (chunk_id, content_hash, dim, vec) VALUES (?,?,?,?)`)
if err != nil {
return 0, err
}
defer stmt.Close()
for i, id := range ids {
if _, err := stmt.ExecContext(ctx, id, hashOf(texts[i]), len(vecs[i]), embed.Encode(vecs[i])); err != nil {
return 0, fmt.Errorf("store vector %s: %w", id, err)
}
}
if err := tx.Commit(); err != nil {
return 0, err
}
return len(ids), nil
}