@zvec/pi-tools-search0.1.0
Hybrid dense + BM25 tool retrieval for the Pi coding agent - a drop-in replacement for Pi's built-in tool_search, backed by zvec.
Untested on omp
This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.
Reports 0
No reports yet.
Readme
English | 中文
pi-tools-search
Hybrid tool retrieval for the Pi coding agent — a drop-in replacement for Pi's built-in tool_search that ranks deferred tools by meaning, not just keywords, backed by zvec.
💫 Why | 🧠 How it works | 🚀 Install | ⚙️ Configuration | 📊 Benchmarks | 🤝 Community
Pi includes a tool_search that ranks deferred and MCP tool metadata with Okapi BM25.
BM25 is fast and dependency-free, but it only finds tools that share surface words
with the query. Rephrase the request, or ask in a language the tool description is
not written in, and the term set matches nothing.
pi-tools-search registers the same tool, with the same contract — same
name, same model-only exposure, same reachesTools: "all", same parameters — but
ranks with a hybrid retriever: dense semantic embeddings fused with zvec's own
BM25 full-text index over the same document text, stored and queried through
zvec. Nothing about your agent loop changes; the
model still calls tool_search and gets the right tools loaded.
💫 Why
- Loads the right tool more often. On a 1,094-tool corpus, the correct tool
appears in the top-1 / top-4 / top-8 candidates the model sees +9.1pp / +9.2pp
/ +9.2pp more often than Pi's BM25 — significant under a paired bootstrap
(259/103, 199/41, 174/16 wins/losses). Those are the default
bekkonumbers (61.5 / 83.7 / 90.8); the 384-d MiniLM calibration scored 62.8 / 85.7 / 91.5. This is exactly whattool_searchdoes: it declares its top-k to the model at once. - Works for multilingual queries. A Chinese query matches English tool
descriptions through the dense channel. Pi 1.5.0 already segments CJK into words,
so its BM25 is no longer blind to the script; what it still cannot do is match a
Chinese question against an English description, because the two share no term.
The default
bekkotable carries a 200k WordPiece vocabulary over 40 languages, so Chinese queries work out of the box;EMBED_MODEL=potion, the static fallback that needs no native runtime, is the one model with no Chinese in its vocabulary (see “Choosing a model”). - Saves the tokens deferred loading already promises. Declaring 200 tools
costs ~34k prompt tokens per turn;
tool_searchkeeps that at ~855 regardless of corpus size (−97.5%). This extension makes the loaded subset more likely to be the right one. - Drop-in, contract-compatible. Same tool name and semantics, so it replaces
the built-in ranker without touching prompts, MCP servers, or agent code. Set
PI_TOOLS_SEARCH=offto A/B against the BM25 baseline at any time. - Local by default, remote by choice. The default backend is a table
lookup, not a Transformer: 256-d INT8 weights running in-process through
onnxruntime-node, with the weights and the index staying on your machine and nothing going over the network beyond the one-time model download. SettingPI_TOOLS_SEARCH_EMBEDDER=bailianswaps the dense side for a hosted Qwen embedder that measured 74.8% / 93.5% / 97.1% R@1/4/8 on the same corpus — the price being an API key, one round trip per query, and tool descriptions leaving the machine.
🧠 How it works
user prompt ─▶ tool_search(query)
│
▼
┌─────────────────────────┐ lazy, keyed by corpus signature
│ build / reuse zvec index│ (FNV-1a over model id + every tool)
└─────────────────────────┘
│
┌──────────┴───────────┐
▼ ▼
two dense views lexical channel
bekko (256-d) zvec FTS (BM25)
full text / names stemmed term index
└──────────┬───────────┘
▼
min-max each, fuse 0.2·full + 0.4·names + 0.4·lexical
▼
top-k tool names ─▶ pi.setActiveTools(...) ─▶ next model call
- Same tool metadata, name kept in the text. Each tool is rendered as
name name_words description schema— everything Pi's own document builder puts intotext, plus the tool name, plus a tool's namespace text when it has one. Pi 1.5.0 moved the name out of the text into a field it weights 3× and keeps the namespace in a third; a single-field FTS index has no such channel, so dropping the name here would hand this extension less signal than Pi keeps. The benchmark harness imports both Pi's ranker and Pi's document builder and compares all 1,094 documents one by one: none of them has a namespace, and the only difference is that prefix. - Lazy, content-keyed index. The index is built on first search and reused across turns. Its cache key is a signature over the index format version, the embedding-model id and every searchable tool's id and text (sorted, so registry order does not matter). It is rebuilt only when one of those actually changes — e.g. an MCP server connects late — never when a tool is merely loaded.
- Three lists, one score. Dense vectors capture semantics; zvec's BM25
full-text index (with stemming) captures exact surface forms like function names.
The dense side runs twice over the same tool: once on the full document, once on a
view that keeps the property names but drops the per-property
descriptionprose — a mean-pooled vector cannot tell that prose from the tool's own summary, and a field name is one token that means one thing. Each list is min-max normalized and combined as0.2·dense_full + 0.4·dense_names + 0.4·lexical(0.5/0.5when the second view is off), with the weights renormalized over the lists that actually returned hits. That last part is why the fusion runs here instead of inside zvec'smultiQuerySync: its nativeweightedreranker normalizes each list analytically and multiplies the weights as given, so it cannot drop a list that came back empty. The two are close, not identical — over 200 BFCL queries at the shipped pool the top hit agrees on 96% of them and the full top-8 order on 15% (benchmarks/run_native_rerank.ts). - Graceful degradation. If zvec is unavailable or a query fails, it falls back
to a bundled BM25 ranker; if the full-text query matches nothing, it degrades to
dense-only. A failed index build never breaks
tool_search— it logs and answers from BM25. - One ranker, six embedders.
PI_TOOLS_SEARCH_EMBEDDERpicks the dense side: one of five local models (EMBED_MODEL) or Bailian'sqwen3.7-text-embedding(1024-d, opt-in). The backend carries what was fitted against that model — the prefixes (Qwen3 wants an instruction on the query, EmbeddingGemma on the document as well, the default bekko neither) and the fusion weights (0.70/0.15/0.15for the two strongest dense channels,0.20/0.40/0.40otherwise). The model id and the document prefix are part of the index signature, so each backend keeps its own store and switching costs no rebuild; only the newestPI_TOOLS_SEARCH_KEEP(5) stay on disk, enough to hold both sides of an A/B. A remote index that cannot be built falls back to the local model once, and a query that fails degrades to BM25 like any other.
🚀 Install
pi-tools-search is a Pi package.
Install it from npm, git, or a local path:
# From npm (once published)
pi install npm:@zvec/pi-tools-search
# From git
pi install git:github.com/zvec-ai/pi-tools-search
# From a local checkout
git clone https://github.com/zvec-ai/pi-tools-search.git
cd pi-tools-search && npm install
pi install ./pi-tools-search
Try it for a single invocation without adding it to your settings:
pi -e npm:@zvec/pi-tools-search
Pi installs the runtime dependencies (@zvec/zvec and @huggingface/tokenizers,
28.9 MB measured) plus onnxruntime-node (288 MB of native runtime, an optional
dependency that npm installs by default — see “Choosing a model” for the
install without it) and loads src/index.ts as an extension. The one optional
peer is @huggingface/transformers, needed only by the transformer models
(minilm, gemma, qwen3); the two static models, the default bekko and
potion, run without it. The extension registers tool_search
and activates it as soon as there is any deferred or MCP tool to search.
[!NOTE] On the first search, the default model (
hotchpotch/bekko-static-embedding-v1, a 52 MB INT8 graph plus a 5 MB tokenizer) is downloaded into~/.cache/pi-tools-search, and the index is built once — about a second for 1,094 tools, because a static table embeds without a Transformer (a transformer model takes up to ~1.5 minutes on the same corpus). Both are cached for later runs. WithEMBED_MODEL=potionthe weights of azvec-grepinstall are reused instead of downloaded (PI_TOOLS_SEARCH_REUSE_ZVEC_GREP=0disables that). SetHF_MIRROR=1ifhuggingface.cois unreachable.
Platforms
Windows (x64, arm64), Linux (x64, arm64, glibc and musl) and macOS (arm64) each
have a prebuilt @zvec/zvec binding, so nothing compiles on install. CI runs
the unit and integration suites and the real-model smoke test on
ubuntu-latest, macos-latest and windows-latest; Node 22.19 or newer, the
same floor Pi sets.
One dependency has gaps: onnxruntime-node publishes no darwin-x64 or musl
binary. On Intel macOS and Alpine the default bekko cannot run, so the first
search switches to potion — 34 MB, no native runtime, English-only vocabulary
— and prints one warning saying why. EMBED_MODEL=potion states it up front;
EMBED_MODEL=bekko on such a machine fails loudly instead of swapping silently.
Try it with a demo tool set
No MCP server handy? Load the bundled fixture, which registers 20 deferred stub tools, alongside the extension:
pi -e ./src/index.ts -e ./examples/tool-fixture.ts \
-p "email my manager about the login bug"
Watch tool_search load send_email (and friends) for the next turn. Run
/pi-tools-status inside Pi to see the index state, backend, and tool counts.
⚙️ Configuration
An installed extension is configured through these environment variables, every one of them
optional; the BAILIAN_* ones can also live in a config file, described below. A host that loads
the package itself can pass the same settings as options instead — see
Embedding it from code.
| Variable | Default | Effect |
|---|---|---|
PI_TOOLS_SEARCH |
(unset) | Set to off to rank with the bundled BM25 fallback instead of zvec (A/B baseline). |
PI_TOOLS_SEARCH_LIMIT |
8 |
Default number of tools one tool_search call loads (Pi's default). |
PI_TOOLS_SEARCH_DIR |
<agent dir>/pi-tools-search |
Where index stores are kept. |
PI_TOOLS_SEARCH_KEEP |
5 |
How many index stores to leave on disk, newest first. A changed tool set, model or FTS layout gets a store of its own; older ones are deleted on the next corpus change. 0 keeps every one. Stores the running session has open are never deleted, and a store touched in the last minute is skipped so a build in another process is not cut in half. |
PI_TOOLS_SEARCH_NAME_VIEW |
(on) | Set to 0 to index one dense field instead of two (the full document only, 0.5/0.5 fusion). Costs one rebuild; the store schema follows the documents. |
EMBED_MODEL |
hotchpotch/bekko-static-embedding-v1 |
Dense model: a registered alias (potion, bekko, minilm, qwen3, gemma, or default) or any transformers.js repo id. The default is bekko, a static INT8 ONNX table that runs on onnxruntime-node; potion is the same kind of table without the native runtime, at the price of an English-only vocabulary. Transformer models need the optional peer @huggingface/transformers. Changing it invalidates every cached index. |
PI_TOOLS_SEARCH_MODEL_CACHE |
~/.cache/pi-tools-search |
Where model weights are cached. |
PI_TOOLS_SEARCH_REUSE_ZVEC_GREP |
(on) | Set to 0 to stop reading zvec-grep's model cache. By default its potion weights are reused when the repo and revision match exactly and the width agrees; that cache lives under $ZVEC_GREP_HOME (~/.zvec-grep). |
HF_MIRROR |
(unset) | Set to 1 to download weights from hf-mirror.com. |
PI_TOOLS_SEARCH_EMBEDDER |
local |
bailian swaps the dense side for Alibaba Cloud Model Studio's qwen3.7-text-embedding (1024-d, +13.3pp R@1 over the default on BFCL). Sends every tool description and query off-box; needs BAILIAN_API_KEY. |
BAILIAN_API_KEY |
(unset) | Required for that backend. If it is missing, one warning is logged and the local model is used. |
BAILIAN_EMBED_MODEL |
qwen3.7-text-embedding |
Remote embedding model. Changing it changes the index key. |
BAILIAN_EMBED_DIM |
1024 |
Vector width, baked into the store schema (768, 1024, 1536, 2048 …). A store built at another width is not reopened. |
BAILIAN_EMBED_URL |
https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings |
OpenAI-compatible endpoint override, for gateways or private deployments. |
BAILIAN_EMBED_TIMEOUT_MS |
3000 |
Per-request timeout; one retry, after which the query answers from BM25. |
Turning on the remote embedder
Two things are needed: an API key from the Alibaba Cloud Model Studio console
(sk-…) and an account allowed to use qwen3.7-text-embedding. Pi hands an
extension nothing but the ExtensionAPI, and settings.json has no slot for
extension settings or secrets, so there are only two places to put them.
A config file (recommended, survives restarts). By default
~/.pi/agent/pi-tools-search/config.json, or wherever PI_CODING_AGENT_DIR
points:
{
"embedder": "bailian",
"apiKey": "sk-xxxxxxxx",
"dim": 1024
}
chmod 600 it; if the mode is open to other users the extension says so at
startup. Besides apiKey the file accepts model, dim, url and timeoutMs,
which map to the BAILIAN_EMBED_* variables above. A broken file logs one
warning and is treated as absent.
Or just for this session. Environment variables win over the file, so a quick switch does not mean editing anything:
export BAILIAN_API_KEY=sk-xxxxxxxx
pi
PowerShell:
$env:BAILIAN_API_KEY = "sk-xxxxxxxx"
Either way the variable has to be set in the shell that starts Pi. Two things
that read the wrong way: an apiKey on its own does not turn the remote path
on — embedder (or PI_TOOLS_SEARCH_EMBEDDER) is the switch, and having a key is not the
same as agreeing to send tool descriptions off-box. And an empty environment
variable counts as unset, so it will not blank out a key from the file.
Check that it took effect: /pi-tools-status prints
Embedder: bailian:qwen3.7-text-embedding@1024 (remote, BAILIAN), a Key: …
line holding either the variable name or the file path (never the key itself),
and a Remote: N requests, M tokens, … counter. Do not skip this — a missing key
only logs one warning and falls back to the local model, so the session works
either way and nothing looks broken.
The first search builds the remote index and uploads every tool description, so
it takes longer than the local build. A new key does not invalidate the store;
changing BAILIAN_EMBED_MODEL or BAILIAN_EMBED_DIM does, because the vectors
change. BAILIAN_EMBED_URL covers gateways and private deployments.
Embedding it from code
Pi loads an extension's default export with just the ExtensionAPI, so an installed
copy is configured through the table above or the config file beside the index. A host that loads
the package itself can pass the same settings as a second argument instead; options wins over
both.
import piToolsSearch from "@zvec/pi-tools-search";
import { localBackend } from "@zvec/pi-tools-search/src/backend.ts";
piToolsSearch(pi, {
storeDir: "/var/cache/pi/zvec", // default: <agent dir>/pi-tools-search
limit: 5, // default: PI_TOOLS_SEARCH_LIMIT (8)
forceBm25: false, // default: PI_TOOLS_SEARCH === "off"
nameView: true, // default: PI_TOOLS_SEARCH_NAME_VIEW !== "0"
keepStores: 3, // default: PI_TOOLS_SEARCH_KEEP (5)
// Rank with your own vectors instead of the bundled model.
index: {
modelId: "my-embedder-v3", // names the store; change it with the vectors
embedFn: (texts) => embed(texts), // unit-length vectors, in input order
queryPrefix: "",
docPrefix: "",
weights: { dense: 0.5, name: 0.25, lexical: 0.25 },
},
// Or replace the backend outright, and say what to rebuild with if it fails.
embedder: myBackend,
fallbackEmbedder: localBackend(),
});
The ranker is exported on its own for a host that wants retrieval without the Pi tool:
ZvecToolIndex (openOrBuild, search, searchWith), corpusSignature and INDEX_VERSION,
selectBackend and localBackend, and the fusion helpers in src/fusion.ts. The package is
published as TypeScript sources, so the types come with it.
Two things bite if ignored. The model id, the document prefix and the FTS layout are part of the
store key, so changing one is a rebuild rather than a stale read. And embedFn has to return
unit-length vectors in input order — nothing downstream normalizes them or checks the order.
The remote backend needs no environment variable from a host:
selectBackend({ PI_TOOLS_SEARCH_EMBEDDER: "bailian", BAILIAN_API_KEY: key }) returns the same backend the
environment path would have built, and it goes straight into embedder. A host that prefers the
file can call loadConfig/mergeEnv from src/config.ts itself.
Choosing a model
Five local models are registered, all offline after the first download. The
default is bekko: a 200k-word WordPiece table over 40 languages in a
52 MB INT8 graph, run through onnxruntime-node. It is not a Transformer — one
token lookup, one mean, one L2 — so it builds 1,094 tools in about a second and
answers in 3.7 ms, and a Chinese query works without a code change.
potion is the fallback on a machine that cannot run the native runtime: the
same 256-d static lookup over a 34 MB safetensors table, no onnxruntime-node
at all. There the default switches to it on the first search, with one warning;
naming bekko explicitly keeps the error instead, and the index answers from
BM25 until it is changed. The price is a vocabulary
with no Chinese and 1.5pp less R@1 than MiniLM. The transformer models
(minilm, gemma, qwen3) need one optional peer,
npm i @huggingface/transformers; it has to land in the extension's own
node_modules, which is why the error message spells out the --prefix to use.
A missing runtime also costs no bandwidth: both static models resolve theirs
before fetching a byte, so a mismatch is detected before the 57 MB of weights
are fetched. What it does not do is swap silently — the warning names the
runtime, the platform and the model it fell back to, so /pi-tools-status and the
first search tell the same story.
EMBED_MODEL |
width | download | pooling | prefixes | BFCL R@1 / 4 / 8 | p50 query |
|---|---|---|---|---|---|---|
bekko (default) |
256 | 57 MB | mean | — | 61.5 / 83.7 / 90.8 | 3.7 ms |
potion |
256 | 34 MB | mean | — | 61.3 / 83.3 / 90.6 | 2.6 ms |
minilm |
384 | 487 MB | mean | — | 62.8 / 85.7 / 91.5 | 11 ms |
gemma |
768 | 336 MB | mean | query + document | 65.6 / 88.4 / 93.4 | 63 ms |
qwen3 |
1024 | 629 MB | last token | query | 67.4 / 89.5 / 95.0 | 52 ms |
The download is the expensive part (34 MB → 629 MB, into PI_TOOLS_SEARCH_MODEL_CACHE),
and each model rebuilds the store once. Two of these are static models — no
attention, no Transformer: a token-id lookup into an embedding table, then a mean
and an L2. potion keeps that table in model.safetensors and src/model2vec.ts
averages the rows its token ids point at; bekko stores it as an INT8 ONNX graph
whose output is already pooled, which src/static-onnx.ts runs through
onnxruntime-node (52 MB graph + 5 MB tokenizer, 200k WordPiece vocabulary, 40
languages, 256 of its 1024 Matryoshka dims). Both finish the 1,094-tool build in
about a second and answer in under 4 ms. The two larger models buy +2 to +3pp R@8
at ~5× the per-query latency — and gemma's q8 build is 336 MB, i.e. smaller
than the fp32 MiniLM; what it costs is latency, not disk. The prompts
qwen3 and gemma carry are applied on
the dense side only, and Gemma's document prompt enters the store signature, so the
full-text query never sees Instruct: … and no store is ever reopened under the
wrong prefix. Every number is benchmarks/REPORT.md §5.5.
The known trade-off of the fallback: potion has no Chinese in its
vocabulary. On the smoke fixture's three Chinese queries it misses top-1 every
time, while bekko, MiniLM, gemma and qwen3 get all three — which is why
bekko, not potion, is the default. gemma is the strongest of them
(gold scores 0.71 / 0.76 / 0.77 against MiniLM's 0.36 / 0.51 / 0.24 and bekko's
0.21 / 0.23 / 0.28); bekko is the cheapest that still works (57 MB). If the
288 MB native runtime is what you are protecting, EMBED_MODEL=potion is the
smallest install that still embeds; otherwise bekko is the better table.
Slash command: /pi-tools-status prints the current backend (zvec hybrid d0.2/n0.4/s0.4, or d0.5/s0.5 with PI_TOOLS_SEARCH_NAME_VIEW=0, or BM25 fallback),
the embedder actually in use (Embedder: … (local) or … (remote, BAILIAN)),
how many tools are indexed, the last build time and origin (built / cached),
request/token/retry/failure counters for the remote backend, and the on-disk
store path.
📊 Benchmarks
Measured against the installed Pi 1.5.0's built-in BM25 tool_search on a
BFCL v3 corpus of 1,094
tools and 1,710 queries. The zvec column is the default,
EMBED_MODEL=bekko: a 256-d INT8 static table, two dense views of the same tools
(full document + property names only) fused with zvec's BM25 over a 64-candidate
pool per list, weighted 0.20 / 0.40 / 0.40. The ranker ablations in §5 were run
on a 384-d MiniLM control column, which scores 62.8 / 85.7 / 91.5 in this same
configuration — 0.7–2pp more at every k for 8.5× the download and 3× the
per-query cost (§5.5).
| Pi 1.5.0 built-in BM25 | pi-tools-search (Bekko, default) | |
|---|---|---|
| Recall@1 | 52.4% | 61.5% (+9.1pp) |
| Recall@4 | 74.5% | 83.7% (+9.2pp) |
| Recall@8 | 81.5% | 90.8% (+9.2pp) |
| MRR@8 | 0.6256 | 0.7180 |
| Search latency p50 / p95 (1,094 tools)† | 20.8 / 44.3 ms | 3.7 / 7.8 ms |
| Prompt tokens / turn (200 tools) | 34,190 | 855 (−97.5%) |
| Whole-session tokens (40 tools × 12 q) | 14,198 | 5,047 (−64.5%) |
The win is significant at every k (paired bootstrap, every 95% CI clears zero) and
largest on live_multiple questions where one query maps to several functions
(+11.2pp Recall@4, +10.6pp Recall@8). On live_simple — single, paraphrased
questions, which is what a real user writes — the gain is the thinnest (+6.6pp
Recall@4, +10.1pp Recall@8). The ranker ablation itself was measured on the
MiniLM control column: there, neither channel alone beats the baseline at
Recall@1 (dense only 50.1%, the full-text index only 51.9%) and fusing them is
what wins. Reciprocal rank fusion was measured on those same candidates too: it
trades 1.1pp Recall@1 for 0.8pp Recall@8, so it is available as a mode
(searchWith(q, k, { fusion: "rrf" })) rather than as the default. Of the 154
queries the MiniLM run still misses at Recall@8, 126 are also missed by the
installed Pi — 82% of the residual is the corpus, not the ranker (report §5).
At 1,094 tools latency favours the default too: 3.7 ms p50 / 7.8 ms p95 against 20.8 / 44.3 ms, because a static table does no Transformer forward pass while Pi re-tokenizes all 1,094 documents on every call. On a handful of tools Pi is still the cheaper side (sub-millisecond against a fixed embedding cost); the crossover was 400–500 tools for the MiniLM calibration (§6) and is earlier for a static table. The second dense view adds nothing measurable to query latency (its extra ANN lookup is below what the harness resolves) and costs ~13% more index build. Retrieval quality — not speed — is the reason to install this.
End to end, in real Pi sessions with a frontier model driving the loop (report
§7), over the same 1,093 tools and 1,710 questions and with every arm ranking
the model's own tool_search query: BM25 answers 75.2% of questions with the
right tool, the default bekko 81.9%, the dependency-free potion-code
table (no native runtime installed at all) 81.3%, local Qwen3 0.6B 82.3%
and the remote qwen3.7-text-embedding 82.8% — +6.7pp of accuracy
[+5.0, +8.4] and +7.7pp of retrieval hit for the default, with no API key and no
tool description leaving the machine. The last 0.9pp between the default and the
endpoint is inside the noise; the remote arm's +4.1pp of retrieval is not, and
that is what its round trip and key buy. Dropping onnxruntime-node for potion
costs 0.6pp [−1.9, +0.7] — also inside the noise — and 1.8 s less per question,
but its table is English-only, which is why bekko is the default.
Full methodology, all tables, ablations, and reproduction steps live in
benchmarks/REPORT.md, including the tokenizer
ablation: an ngram(4–4) index lifts Recall@1 to 61.5% at a 16-candidate pool and
62.7% at the default pool of 64 (against 59.1% / 60.8%), but returns nothing for Chinese
queries shorter than four characters — and the fact that its gain shrinks as
the pool widens is the useful part: the two knobs buy the same thing.
† The Pi column is the installed tool measured in report §6; the zvec column is the Bekko run in §5.5. Both include query embedding and the default 64-candidate pool, and both are the installed Pi 1.5.0 on one machine, but they are different sessions — latencies move 10–20% between runs, so read the shape, not the cells.
Switching the dense side to the remote embedder (PI_TOOLS_SEARCH_EMBEDDER=bailian, report
§5.3–§5.4) lifts the same ranker to 74.8% / 93.5% / 97.1%, MRR 0.8348 —
+13.3pp R@1 over the default Bekko column and +22.4pp over Pi — for one HTTP round trip
per query (121 ms p50) and an API key. It is off by default: every row above is
reproduced with no key and no network.
The other four local models are a single variable away (EMBED_MODEL, report
§5.5): gemma scores 65.6 / 88.4 / 93.4 and qwen3 67.4 / 89.5 / 95.0 — 4.1 and
5.9pp above the default at R@1 — for 336 MB and 629 MB of download and
~5× the query latency. MiniLM, the 384-d control column every ablation runs on,
scores 62.8 / 85.7 / 91.5 — +1.29 / +1.93 / +0.70pp over the default, with the
R@4 gap clear of zero and both ends inside the noise — for 487 MB of weights, an
89 s build and 3× the per-query cost. The dependency-free potion table sits
0.41pp below Bekko at R@4 and inside the noise at R@1 and R@8, at 34 MB and
2.6 ms, but its vocabulary has no Chinese. That — not speed — is what dropping
the Transformer costs.
The default is therefore bekko: 256-d, 57 MB of weights, Chinese works, a
~1 s build and 3.7 ms per query — 0.41pp R@4 above potion and inside the noise
at R@1 and R@8, but able to embed a Chinese query at all. What it costs is a
native runtime: onnxruntime-node (288 MB) is an optional dependency that npm
installs by default, so pi install measures ~317 MB — the one number to weigh
before installing. EMBED_MODEL=potion (34 MB of weights, no native runtime) is
the fallback for a machine that cannot run it, and minilm / gemma / qwen3
remain one peer (npm i @huggingface/transformers) and one EMBED_MODEL away
when R@1 is the budget.
🚧 Limitations
- Top-1 is still wrong ~39% of the time. Recall@1 is 61.5% for the default
bekko(62.8% for MiniLM) against 52.4% for the installed Pi 1.5.0. If your flow hinges on the single best tool, that is an improvement but not a solution. - Cold-start build. The first index build costs a few seconds (tens of tools)
up to ~1.5 minutes (1,094 tools, measured with MiniLM: 80–91 s for one and two
dense views); it is cached afterwards. There is no incremental update yet — a
corpus change triggers a full rebuild. Old stores are not thrown away at once:
they stay reusable when you switch back to a model or a tool set, and only
stores beyond
PI_TOOLS_SEARCH_KEEP(5 by default, oldest directory mtime first) are swept; the live one and anything touched in the last minute are never deleted. - Token savings depend on corpus size. They are dramatic at hundreds of tools and modest below ~100 (where the built-in already suffices for English).
- English-only benchmark. The multilingual capability is structural (tokenizer + model), not quantified by the BFCL numbers.
- The FTS tokenizer is fixed at build time. The default index uses zvec's
standardanalyzer, which keepssnake_caseidentifiers as one token (a query formaildoes not matchsend_email). An ngram(4–4) index does match it and is +2.4pp Recall@1 on BFCL at a 16-candidate pool (+1.9pp at the default pool of 64) with Recall@8 flat, but it returns nothing for Chinese queries shorter than four characters and costs 2.3× the store, so it is an option (openOrBuild(..., { fts })) rather than the default. - It overrides Pi's built-in
tool_search. Pi lets an extension register a tool under a built-in's name; the extension wins without a warning, and the MCP extension keeps activatingtool_searchbecause this registration declaresreachesTools. The name is the key, so do not install a second searcher beside it. - The model-facing description is not Pi's.
queryasks the model to pass the request through as written, because the index matches the user's own nouns; Pi's asks for a "search query". And alimitthat is not a positive integer falls back to 8 here, where Pi throws. - The remote backend leaves the machine.
PI_TOOLS_SEARCH_EMBEDDER=bailiansends every searchable tool's name, description and JSON schema to Alibaba Cloud Model Studio on each index build, and every query text on each search, and adds a round trip (121 ms p50 measured) to each search. That is why it is opt-in and why the local model stays the default.
🛠️ Development
Requires Node.js ≥ 22.19.0. The extension is written in TypeScript and run
directly by Pi via tsx (no build step; tsconfig.json sets noEmit).
git clone https://github.com/zvec-ai/pi-tools-search.git
cd pi-tools-search
npm install
npm run check # lint + format:check + typecheck + unit + integration tests
npm run smoke # opt-in: real-model end-to-end (downloads ~57 MB on first run, ~470 MB with EMBED_MODEL=minilm)
npm run smoke:package # opt-in: pack + clean-install the tarball, run it, process.exit
Layout:
src/
index.ts the Pi extension: registers tool_search, /pi-tools-status
zvec-index.ts build/open the zvec collection; two dense fields + FTS, three-list query, fallback chain
backend.ts which embedder: a local model or Bailian, plus its query prefix and fusion weights
remote-embedder.ts the Bailian HTTP client (batching, retries, timeouts, cache, L2 normalization)
embedder.ts dense embeddings: static table by default, transformers.js optional (lazy)
model2vec.ts the static table: reads safetensors directly and reuses zvec-grep's model cache
static-onnx.ts static models with an ONNX graph (bekko), loads onnxruntime on demand
model.ts embedding model id + EmbedFn type
document.ts two views: name + name_words + description + schema (+ namespace), and the same text with property names only
signature.ts corpus signature (the index cache key)
sparse.ts TF-IDF + CJK-bigram sparse vectors (legacy ablation, no longer indexed)
fusion.ts min-max normalization + weighted score fusion over N lists
bm25.ts bundled BM25 fallback ranker
test/unit/ pure-logic tests (no native library, no model)
test/integration/ extension + index tests against the real zvec library
benchmarks/ BFCL v3 harness; see benchmarks/REPORT.md
examples/ a 20-tool demo fixture
See CONTRIBUTING.md for the development workflow and pull
request conventions.
🤝 Join Our Community
❤️ Contributing
Bug fixes, features, and documentation improvements are all welcome. Please read
CONTRIBUTING.md first; report security issues privately per
SECURITY.md.
📄 License
Apache License 2.0. See LICENSE.
The benchmark corpus and queries are derived from the
Berkeley Function Calling Leaderboard v3
dataset (Apache-2.0); see benchmarks/REPORT.md.

