diff --git a/examples/README.md b/examples/README.md index d1237e9..051ed3a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -9,6 +9,7 @@ Each directory is its own Go module with annotated Go files. Run one with `gomcp | [`files`](files) | read-only directory browser: resource template, two tools, path traversal protection | HTTP or stdio | | [`todo`](todo) | todo list in a JSON file: Setup and Teardown, tools, a prompt, a resource | HTTP or stdio | | [`fetch`](fetch) | `fetch_url` with an allowlist, size limit and timeout, `ToolError` | HTTP or stdio | +| [`remember`](remember) | knowledge base in SQLite: `remember`, `recall`, `forget`; semantic search with an embedding endpoint (Ollama, OpenAI, ...), BM25 without | HTTP or stdio | | [`features`](features) | every feature once (auth, tasks, sampling, elicitation, ...), see its README | HTTP or stdio | | [`esm`](esm) | ticket desk: Entra authentication with scopes per role, confirmation before every change, a state machine in a service on top of a repository, tests at every level, see its README | HTTP (auth), stdio for local tries | diff --git a/examples/remember/README.md b/examples/remember/README.md new file mode 100644 index 0000000..1bf4fcd --- /dev/null +++ b/examples/remember/README.md @@ -0,0 +1,68 @@ +# remember + +A knowledge base the model fills and queries, stored in SQLite. No authentication, meant to run locally for one person. + +- `remember`: stores a fact (text plus optional tags). +- `recall`: finds the facts closest to a question, best first, with a score. `min_score` drops weak hits. +- `forget`: deletes a fact by id. + +## Two ways to search + +| | Configured | How `recall` ranks | Finds `vehicle` for "my car is red" | +| --- | --- | --- | --- | +| semantic | `REMEMBER_EMBED_URL` set | cosine similarity of embedding vectors | yes | +| lexical | nothing set | BM25 over stemmed words, prefixes and typos (trigrams) | no | + +The embedding endpoint is anything OpenAI compatible (`POST {url}/embeddings`): OpenAI, Ollama, LM Studio, vLLM, LiteLLM. +Each fact's vector is stored next to it in SQLite (a `float32` BLOB) together with the model that made it. +Vectors of different models are not comparable, so at start every fact with a missing or foreign vector is embedded +again. That makes two things automatic: turning embeddings on for an existing database, and changing the model. +An unreachable endpoint stops the start, and `remember` fails instead of storing a fact it cannot find later. + +## Configuration + +| Variable | Meaning | +| --- | --- | +| `REMEMBER_DB` | SQLite file, default `./remember.db` | +| `REMEMBER_EMBED_URL` | base URL, e.g. `http://localhost:11434/v1` for Ollama. Empty: lexical search | +| `REMEMBER_EMBED_MODEL` | embedding model, required with the URL, e.g. `nomic-embed-text` | +| `REMEMBER_EMBED_KEY` | API key, if the endpoint needs one | + +Note the text of a fact leaves the machine when the endpoint is a hosted one. Use a local Ollama for private notes. + +### Try it with Ollama + +Ollama serves the OpenAI API under `http://localhost:11434/v1`. Pull an embedding model first; chat models also answer +`/embeddings`, but slowly and with poor results. + +```sh +ollama pull nomic-embed-text # about 270 MB + +REMEMBER_DB=$HOME/remember.db \ +REMEMBER_EMBED_URL=http://localhost:11434/v1 REMEMBER_EMBED_MODEL=nomic-embed-text \ +gomcp serve ./examples/remember +``` + +Without the two `REMEMBER_EMBED_*` variables the server uses lexical search and needs no setup: `gomcp serve ./examples/remember`. +A model that is not pulled stops the start with the endpoint's error. + +Client config for stdio (build once, `gomcp stdio` compiles on every start; the first build of the SQLite driver takes a while): + +```sh +gomcp build ./examples/remember ./bin/remember +``` + +```json +{ + "mcpServers": { + "remember": { + "command": "/absolute/path/to/bin/remember", + "args": ["--stdio"], + "env": { "REMEMBER_DB": "/Users/steven/remember.db", "REMEMBER_EMBED_URL": "http://localhost:11434/v1", "REMEMBER_EMBED_MODEL": "nomic-embed-text" } + } + } +} +``` + +Every `recall` reads all rows and compares against every vector: fine for thousands of facts. Beyond tens of thousands, use +an index (sqlite-vec, an ANN library). diff --git a/examples/remember/embed.go b/examples/remember/embed.go new file mode 100644 index 0000000..165d96c --- /dev/null +++ b/examples/remember/embed.go @@ -0,0 +1,105 @@ +package api + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "strings" + "time" +) + +// An embedder talks to any OpenAI compatible POST {url}/embeddings: OpenAI, Ollama +// (http://localhost:11434/v1), LM Studio, vLLM, LiteLLM. The text becomes a vector; +// texts about the same thing end up close together, whatever their words. +type embedder struct { + url, model, key string + client *http.Client +} + +// embed returns the vector for text. +func (e *embedder) embed(ctx context.Context, text string) ([]float32, error) { + body, _ := json.Marshal(map[string]any{"model": e.model, "input": text}) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(e.url, "/")+"/embeddings", bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + if e.key != "" { + req.Header.Set("Authorization", "Bearer "+e.key) + } + resp, err := e.client.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + data, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return nil, err + } + if resp.StatusCode >= 400 { + return nil, fmt.Errorf("embedding endpoint answered %s", resp.Status) + } + var out struct { + Data []struct { + Embedding []float32 `json:"embedding"` + } `json:"data"` + } + if err := json.Unmarshal(data, &out); err != nil || len(out.Data) != 1 || len(out.Data[0].Embedding) == 0 { + return nil, errors.New("embedding endpoint sent no vector") + } + return out.Data[0].Embedding, nil +} + +// newEmbedder reads REMEMBER_EMBED_URL, REMEMBER_EMBED_MODEL and REMEMBER_EMBED_KEY +// (optional). Without a URL it returns nil and the memory falls back to lexical search. +func newEmbedder(getenv func(string) string) (*embedder, error) { + url := getenv("REMEMBER_EMBED_URL") + if url == "" { + return nil, nil + } + model := getenv("REMEMBER_EMBED_MODEL") + if model == "" { + return nil, errors.New("REMEMBER_EMBED_URL is set, so REMEMBER_EMBED_MODEL must be set too") + } + return &embedder{url: url, model: model, key: getenv("REMEMBER_EMBED_KEY"), client: &http.Client{Timeout: 30 * time.Second}}, nil +} + +// cosine similarity in [-1,1]; 0 for vectors of different size or length zero. +func cosine(a, b []float32) float64 { + if len(a) != len(b) { + return 0 + } + 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]) + } + if na == 0 || nb == 0 { + return 0 + } + return dot / (math.Sqrt(na) * math.Sqrt(nb)) +} + +// encode and decode store a vector as little endian float32 in a BLOB. +func encode(v []float32) []byte { + out := make([]byte, 4*len(v)) + for i, f := range v { + binary.LittleEndian.PutUint32(out[4*i:], math.Float32bits(f)) + } + return out +} + +func decode(b []byte) []float32 { + out := make([]float32, len(b)/4) + for i := range out { + out[i] = math.Float32frombits(binary.LittleEndian.Uint32(b[4*i:])) + } + return out +} diff --git a/examples/remember/go.mod b/examples/remember/go.mod new file mode 100644 index 0000000..7c70337 --- /dev/null +++ b/examples/remember/go.mod @@ -0,0 +1,20 @@ +module github.com/StevenCyb/example_remember + +go 1.26.2 + +require github.com/StevenCyb/GoMCP v0.0.0 + +require ( + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.49.0 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect + modernc.org/sqlite v1.64.0 // indirect +) + +replace github.com/StevenCyb/GoMCP => ../.. diff --git a/examples/remember/go.sum b/examples/remember/go.sum new file mode 100644 index 0000000..2a6f49a --- /dev/null +++ b/examples/remember/go.sum @@ -0,0 +1,20 @@ +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.64.0 h1:xCoLcRc2g33gLkmaRrcsJLitr4TRMQGGb3H4HYs3mbM= +modernc.org/sqlite v1.64.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= diff --git a/examples/remember/remember.go b/examples/remember/remember.go new file mode 100644 index 0000000..de3d808 --- /dev/null +++ b/examples/remember/remember.go @@ -0,0 +1,256 @@ +// Example: a knowledge base the model fills and queries, stored in SQLite. With an +// embedding endpoint configured, recall finds facts by meaning ("vehicle" finds a fact +// about a car); without one it ranks by words (BM25, stems, typos). No authentication: +// run it for yourself, locally. +// +// Configuration, all from the environment: +// +// REMEMBER_DB SQLite file, default ./remember.db +// REMEMBER_EMBED_URL OpenAI compatible base URL, e.g. http://localhost:11434/v1 (Ollama); empty = lexical search +// REMEMBER_EMBED_MODEL embedding model, required with the URL, e.g. nomic-embed-text +// REMEMBER_EMBED_KEY API key for the endpoint, if it needs one + +// @MCP.Server("remember", version="1.0.0") +// @MCP.Instructions("A memory. Use remember to store a fact, recall to find facts by topic or question, forget to delete one.") +package api + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "os" + "strings" + "time" + + "github.com/StevenCyb/GoMCP/pkg/mcp" + _ "modernc.org/sqlite" // pure Go driver, no cgo +) + +type Fact struct { + ID int `json:"id"` + Text string `json:"text"` + Tags []string `json:"tags,omitempty"` + Created time.Time `json:"created"` +} + +var ( + db *sql.DB + emb *embedder // nil: lexical search +) + +// row is a fact as stored: with the model that made its vector (empty: no vector yet). +type row struct { + Fact + model string + vec []float32 +} + +// open creates the database and its table. AUTOINCREMENT: an id is never reused. +func open(path string) (*sql.DB, error) { + d, err := sql.Open("sqlite", path) + if err != nil { + return nil, err + } + d.SetMaxOpenConns(1) // one writer, no "database is locked" + _, err = d.Exec(`CREATE TABLE IF NOT EXISTS facts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + text TEXT NOT NULL, + tags TEXT NOT NULL DEFAULT '[]', + created TEXT NOT NULL, + model TEXT NOT NULL DEFAULT '', + vec BLOB)`) + if err != nil { + _ = d.Close() + return nil, err + } + return d, nil +} + +func insert(ctx context.Context, f Fact, model string, vec []float32) (Fact, error) { + tags, _ := json.Marshal(f.Tags) + res, err := db.ExecContext(ctx, `INSERT INTO facts (text, tags, created, model, vec) VALUES (?, ?, ?, ?, ?)`, + f.Text, string(tags), f.Created.Format(time.RFC3339), model, encode(vec)) + if err != nil { + return Fact{}, err + } + id, err := res.LastInsertId() + f.ID = int(id) + return f, err +} + +func all(ctx context.Context) ([]row, error) { + rs, err := db.QueryContext(ctx, `SELECT id, text, tags, created, model, vec FROM facts ORDER BY id`) + if err != nil { + return nil, err + } + defer func() { _ = rs.Close() }() + var out []row + for rs.Next() { + var r row + var tags, created string + var vec []byte + if err := rs.Scan(&r.ID, &r.Text, &tags, &created, &r.model, &vec); err != nil { + return nil, err + } + _ = json.Unmarshal([]byte(tags), &r.Tags) + r.Created, _ = time.Parse(time.RFC3339, created) + r.vec = decode(vec) + out = append(out, r) + } + return out, rs.Err() +} + +// backfill embeds every fact whose vector is missing or comes from another model, so +// switching the model (or turning embeddings on later) needs no manual step. +func backfill(ctx context.Context) error { + rows, err := all(ctx) + if err != nil { + return err + } + for _, r := range rows { + if r.model == emb.model && len(r.vec) > 0 { + continue + } + vec, err := emb.embed(ctx, r.Text) + if err != nil { + return fmt.Errorf("embedding fact %d: %w", r.ID, err) + } + if _, err := db.ExecContext(ctx, `UPDATE facts SET model = ?, vec = ? WHERE id = ?`, emb.model, encode(vec), r.ID); err != nil { + return err + } + } + return nil +} + +// Example: a bad configuration or an unreachable embedding endpoint stops the start, +// rather than silently searching a different way than the operator asked for. +// +// @MCP.Setup +func Setup() (err error) { + if emb, err = newEmbedder(os.Getenv); err != nil { + return err + } + path := os.Getenv("REMEMBER_DB") + if path == "" { + path = "remember.db" + } + if db, err = open(path); err != nil { + return err + } + if emb != nil { + return backfill(context.Background()) + } + return nil +} + +// @MCP.Teardown +func Teardown() { + if db != nil { + _ = db.Close() + } +} + +type RememberIn struct { + Text string `json:"text" desc:"The fact, one self-contained statement" min:"1" max:"2000"` + Tags []string `json:"tags,omitempty" desc:"Optional topics, they are searchable too" max:"10"` +} + +type ForgetIn struct { + ID int `json:"id" desc:"Id of the fact, as returned by remember or recall"` +} + +type RecallIn struct { + Query string `json:"query" desc:"What you look for, in your own words" min:"1" max:"500"` + Limit int `json:"limit,omitempty" desc:"Most results, default 5" min:"0" max:"50"` + MinScore float64 `json:"min_score,omitempty" desc:"Drop weaker hits. Cosine similarity (0 to 1) with embeddings, BM25 without. Around 0.5 is a loose match for most embedding models" min:"0"` +} + +type Hits struct { + Hits []Hit `json:"hits"` +} + +// @MCP.Tool("remember", description="Stores a fact in the knowledge base") +func Remember(ctx mcp.Context, in RememberIn) (Fact, error) { + f := Fact{Text: strings.TrimSpace(in.Text), Tags: in.Tags, Created: time.Now().UTC().Truncate(time.Second)} + var model string + var vec []float32 + if emb != nil { + var err error + // tags are part of what the fact is about, so they go into the vector too + if vec, err = emb.embed(ctx, strings.TrimSpace(f.Text+" "+strings.Join(f.Tags, " "))); err != nil { + return Fact{}, mcp.ToolError("cannot embed: " + err.Error()) + } + model = emb.model + } + f, err := insert(ctx, f, model, vec) + if err != nil { + return Fact{}, mcp.ToolError("cannot save: " + err.Error()) + } + return f, nil +} + +// @MCP.Tool("forget", description="Deletes a fact by id") +func Forget(ctx mcp.Context, in ForgetIn) (Fact, error) { + rows, err := all(ctx) + if err != nil { + return Fact{}, mcp.ToolError("cannot read: " + err.Error()) + } + for _, r := range rows { + if r.ID == in.ID { + if _, err := db.ExecContext(ctx, `DELETE FROM facts WHERE id = ?`, in.ID); err != nil { + return Fact{}, mcp.ToolError("cannot delete: " + err.Error()) + } + return r.Fact, nil + } + } + return Fact{}, mcp.ToolError("no such fact") +} + +// @MCP.Tool("recall", description="Finds the facts closest to a question or topic, best first") +// @MCP.Hint(readOnly) +func Recall(ctx mcp.Context, in RecallIn) (Hits, error) { + rows, err := all(ctx) + if err != nil { + return Hits{}, mcp.ToolError("cannot read: " + err.Error()) + } + limit := in.Limit + if limit == 0 { + limit = 5 + } + hits, err := find(ctx, rows, in.Query, limit) + if err != nil { + return Hits{}, mcp.ToolError("cannot embed: " + err.Error()) + } + kept := []Hit{} + for _, h := range hits { + if h.Score >= in.MinScore { + kept = append(kept, h) + } + } + return Hits{Hits: kept}, nil +} + +// find ranks by cosine similarity when an embedder is configured, else by words. +// ponytail: compares against every stored vector, move to sqlite-vec or an ANN index +// when the memory grows past tens of thousands of facts. +func find(ctx context.Context, rows []row, query string, limit int) ([]Hit, error) { + if emb == nil { + facts := make([]Fact, len(rows)) + for i, r := range rows { + facts[i] = r.Fact + } + return lexical(facts, query, limit), nil + } + q, err := emb.embed(ctx, query) + if err != nil { + return nil, err + } + var hits []Hit + for _, r := range rows { + if r.model == emb.model && len(r.vec) == len(q) { + hits = append(hits, Hit{Fact: r.Fact, Score: round(cosine(q, r.vec))}) + } + } + return rank(hits, limit), nil +} diff --git a/examples/remember/remember_test.go b/examples/remember/remember_test.go new file mode 100644 index 0000000..b4d70bc --- /dev/null +++ b/examples/remember/remember_test.go @@ -0,0 +1,210 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/StevenCyb/GoMCP/pkg/mcp" +) + +// tctx is the smallest mcp.Context the tools need: a plain context. +type tctx struct { + mcp.Context + c context.Context +} + +func (t tctx) Deadline() (time.Time, bool) { return t.c.Deadline() } +func (t tctx) Done() <-chan struct{} { return t.c.Done() } +func (t tctx) Err() error { return t.c.Err() } +func (t tctx) Value(k any) any { return t.c.Value(k) } + +func ctx() mcp.Context { return tctx{c: context.Background()} } + +// concepts is a toy "model": words of one group share a dimension, like synonyms +// land close together in a real embedding. +var concepts = [][]string{ + {"car", "vehicle", "automobile", "drive"}, + {"dog", "puppy", "canine"}, + {"password", "credential", "secret"}, + {"deploy", "release", "ship"}, +} + +func fakeVector(text string) []float32 { + v := make([]float32, len(concepts)+1) + v[len(concepts)] = 0.01 // never the zero vector + for _, w := range strings.Fields(strings.ToLower(text)) { + for i, group := range concepts { + for _, g := range group { + if w == g { + v[i]++ + } + } + } + } + return v +} + +// useFake points the package at a temp database and, if model is not empty, a fake endpoint. +func useFake(t *testing.T, model string) (calls *int, url string) { + t.Helper() + calls = new(int) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *calls++ + var req struct{ Input string } + _ = json.NewDecoder(r.Body).Decode(&req) + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"embedding": fakeVector(req.Input)}}}) + })) + t.Cleanup(srv.Close) + var err error + if db, err = open(filepath.Join(t.TempDir(), "kb.db")); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + emb = nil + if model != "" { + emb = &embedder{url: srv.URL, model: model, client: srv.Client()} + } + return calls, srv.URL +} + +func TestLexical(t *testing.T) { + kb := []Fact{ + {ID: 1, Text: "Deployment to production runs through the GitLab pipeline", Tags: []string{"ci"}}, + {ID: 2, Text: "The database password rotates every 90 days"}, + {ID: 3, Text: "Kubernetes pods restart when the liveness probe fails"}, + {ID: 4, Text: "Lunch is at noon"}, + } + cases := map[string]struct { + query string + want int // id of the best hit, 0 = no hit + }{ + "exact": {"database password", 2}, + "word form": {"how do we deploy", 1}, + "plural": {"pod restarts", 3}, + "typo": {"kubernets liveness", 3}, + "tag": {"ci", 1}, + "unrelated": {"quantum physics", 0}, + "empty query": {" ", 0}, + } + for name, c := range cases { + hits := lexical(kb, c.query, 5) + switch { + case c.want == 0 && len(hits) != 0: + t.Errorf("%s: want no hit, got %v", name, hits) + case c.want != 0 && (len(hits) == 0 || hits[0].ID != c.want): + t.Errorf("%s: want %d first, got %v", name, c.want, hits) + } + } + if got := lexical(kb, "the", 1); len(got) > 1 { + t.Errorf("limit ignored: %v", got) + } +} + +func TestSemanticRecall(t *testing.T) { + useFake(t, "toy-1") + for _, text := range []string{"My car is red", "The puppy sleeps all day", "Release on Friday"} { + if _, err := Remember(ctx(), RememberIn{Text: text}); err != nil { + t.Fatal(err) + } + } + // none of the query words occur in the facts: only the "meaning" matches + for query, want := range map[string]string{"vehicle": "My car is red", "canine": "The puppy sleeps all day", "ship it": "Release on Friday"} { + h, err := Recall(ctx(), RecallIn{Query: query, MinScore: 0.5}) + if err != nil || len(h.Hits) != 1 || h.Hits[0].Text != want { + t.Errorf("%q: got %v, %v, want %q", query, h, err, want) + } + } + if h, _ := Recall(ctx(), RecallIn{Query: "quantum", MinScore: 0.5}); len(h.Hits) != 0 { + t.Errorf("unrelated query must not match: %v", h) + } +} + +func TestLexicalFallbackAndBackfill(t *testing.T) { + calls, url := useFake(t, "") + if _, err := Remember(ctx(), RememberIn{Text: "My car is red"}); err != nil { + t.Fatal(err) + } + if h, _ := Recall(ctx(), RecallIn{Query: "vehicle"}); len(h.Hits) != 0 || *calls != 0 { + t.Fatalf("without embedder only words match and nothing is called: %v, %d calls", h, *calls) + } + + // turn embeddings on: the existing fact gets its vector at start + emb = &embedder{url: url, model: "toy-1", client: http.DefaultClient} + if err := backfill(context.Background()); err != nil { + t.Fatal(err) + } + if h, _ := Recall(ctx(), RecallIn{Query: "vehicle", MinScore: 0.5}); len(h.Hits) != 1 { + t.Errorf("backfilled fact not found: %v", h) + } + + // a new model invalidates old vectors: they are embedded again, not compared + before := *calls + emb.model = "toy-2" + if err := backfill(context.Background()); err != nil || *calls != before+1 { + t.Fatalf("model change must re-embed once: %v, %d calls", err, *calls-before) + } + if err := backfill(context.Background()); err != nil || *calls != before+1 { + t.Fatalf("nothing left to embed: %v, %d calls", err, *calls-before) + } +} + +func TestForgetAndIDs(t *testing.T) { + useFake(t, "") + a, err := Remember(ctx(), RememberIn{Text: " the sky is blue ", Tags: []string{"nature"}}) + if err != nil || a.ID != 1 || a.Text != "the sky is blue" { + t.Fatalf("remember: %v, %v", a, err) + } + if _, err := Forget(ctx(), ForgetIn{ID: a.ID}); err != nil { + t.Fatal(err) + } + if _, err := Forget(ctx(), ForgetIn{ID: a.ID}); err == nil { + t.Error("forgetting twice must fail") + } + if b, _ := Remember(ctx(), RememberIn{Text: "grass is green"}); b.ID == a.ID { + t.Errorf("id reused: %d", b.ID) + } +} + +func TestRememberFailsWhenEndpointIsDown(t *testing.T) { + useFake(t, "toy-1") + emb.url = "http://127.0.0.1:1" + if _, err := Remember(ctx(), RememberIn{Text: "x"}); err == nil { + t.Error("a fact without vector must not be stored silently") + } + rows, _ := all(context.Background()) + if len(rows) != 0 { + t.Errorf("stored anyway: %v", rows) + } +} + +func TestNewEmbedder(t *testing.T) { + env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } + if e, err := newEmbedder(env(nil)); e != nil || err != nil { + t.Errorf("no URL means lexical: %v, %v", e, err) + } + if _, err := newEmbedder(env(map[string]string{"REMEMBER_EMBED_URL": "http://x"})); err == nil { + t.Error("URL without model must fail") + } + if e, err := newEmbedder(env(map[string]string{"REMEMBER_EMBED_URL": "http://x", "REMEMBER_EMBED_MODEL": "m"})); e == nil || err != nil { + t.Errorf("got %v, %v", e, err) + } +} + +func TestVectorHelpers(t *testing.T) { + v := []float32{1, -2.5, 0} + if got := decode(encode(v)); len(got) != 3 || got[0] != 1 || got[1] != -2.5 || got[2] != 0 { + t.Errorf("round trip: %v", got) + } + if c := cosine([]float32{1, 0}, []float32{2, 0}); c < 0.999 { + t.Errorf("same direction: %v", c) + } + if cosine([]float32{1, 0}, []float32{0, 1}) != 0 || cosine([]float32{1}, []float32{1, 2}) != 0 || cosine([]float32{0}, []float32{0}) != 0 { + t.Error("orthogonal, different size and zero vectors must be 0") + } +} diff --git a/examples/remember/search.go b/examples/remember/search.go new file mode 100644 index 0000000..0388e46 --- /dev/null +++ b/examples/remember/search.go @@ -0,0 +1,133 @@ +package api + +import ( + "math" + "slices" + "strings" + "unicode" +) + +// Lexical search, the fallback when no embedding endpoint is configured: BM25 over +// stemmed terms where a query term also matches prefixes and typos. + +// terms splits text into lowercase words with a crude stem (plural, -ing, -ed). +func terms(s string) []string { + var out []string + for _, w := range strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) { + for _, suf := range []string{"ing", "ed", "es", "s"} { + if len(w) > len(suf)+3 && strings.HasSuffix(w, suf) { + w = strings.TrimSuffix(w, suf) + break + } + } + out = append(out, w) + } + return out +} + +// trigrams of a word padded with spaces, as a set. +func trigrams(w string) map[string]bool { + r := []rune(" " + w + " ") + out := map[string]bool{} + for i := 0; i+3 <= len(r); i++ { + out[string(r[i:i+3])] = true + } + return out +} + +// similarity of two terms in [0,1]: 1 equal, 0.8 prefix (4+ letters), else trigram Dice +// when it is high enough to be a typo. +func similarity(q, d string) float64 { + switch { + case q == d: + return 1 + case len(q) >= 4 && len(d) >= 4 && (strings.HasPrefix(d, q) || strings.HasPrefix(q, d)): + return 0.8 + case len(q) < 4 || len(d) < 4: + return 0 + } + a, b := trigrams(q), trigrams(d) + common := 0 + for g := range a { + if b[g] { + common++ + } + } + if dice := 2 * float64(common) / float64(len(a)+len(b)); dice >= 0.6 { + return dice * 0.7 + } + return 0 +} + +type Hit struct { + Fact + Score float64 `json:"score"` +} + +// rank sorts best first (newer first on ties) and cuts to limit. +func rank(hits []Hit, limit int) []Hit { + slices.SortStableFunc(hits, func(a, b Hit) int { + switch { + case a.Score > b.Score: + return -1 + case a.Score < b.Score: + return 1 + } + return b.ID - a.ID + }) + if len(hits) > limit { + hits = hits[:limit] + } + return hits +} + +// lexical ranks facts for the query with BM25; tags count as text. Facts that match no +// query term are left out. +func lexical(facts []Fact, query string, limit int) []Hit { + q := terms(query) + docs := make([][]string, len(facts)) + total := 0 + for i, f := range facts { + docs[i] = terms(f.Text + " " + strings.Join(f.Tags, " ")) + total += len(docs[i]) + } + if len(q) == 0 || total == 0 { + return nil + } + avg := float64(total) / float64(len(facts)) + + // tf[i][j]: how strongly doc i contains query term j + tf := make([][]float64, len(facts)) + df := make([]int, len(q)) + for i, d := range docs { + tf[i] = make([]float64, len(q)) + for j, qt := range q { + for _, dt := range d { + tf[i][j] += similarity(qt, dt) + } + if tf[i][j] > 0 { + df[j]++ + } + } + } + + const k1, b = 1.2, 0.75 + var hits []Hit + for i, f := range facts { + var score float64 + for j := range q { + if tf[i][j] == 0 { + continue + } + idf := math.Log(1 + (float64(len(facts))-float64(df[j])+0.5)/(float64(df[j])+0.5)) + norm := tf[i][j] + k1*(1-b+b*float64(len(docs[i]))/avg) + score += idf * tf[i][j] * (k1 + 1) / norm + } + if score > 0 { + hits = append(hits, Hit{Fact: f, Score: round(score)}) + } + } + return rank(hits, limit) +} + +func round(f float64) float64 { return math.Round(f*1000) / 1000 }