Skip to content

Search an image library by image, by text, and for near-duplicates

Embed a library of images with dinov3 and siglip2, keep the vectors in a small local index that is updated incrementally, and answer three questions: which images look like this one, which images match this sentence, and which images are near-duplicates of each other. The smoke set runs on the free tier, with no key and no sign-up.

Built with DINOv3. dinov3 output is covered by the DINOv3 License; products built on it should show the tag “Built with DINOv3”.

Models: dinov3, siglip2 · Without a key: Smoke run · Languages: Python, Go · Try in Playground (opens in a new tab) · Source on GitHub (opens in a new tab)

A photo library has a few hundred to a few tens of thousands of images, grows by a few images a day, and is searched by people who remember what a photo looked like or what was in it, not what it is called. Three things are wanted:

  • find the images that look like a given image (retrieval by example);
  • find the images that show what a sentence describes (text search);
  • find copies of the same picture that were resized, cropped, re-compressed, flipped or watermarked (near-duplicates).

The constraints that shape the code are the ones around the call, not the model:

  • Cost. An image costs 0.05 credits per model, so a library costs 0.10 credits per image once. Re-embedding the library on every change would multiply that, so the index must be rebuilt incrementally: only new or changed files are embedded, found by the sha256 of their content.
  • Limits. The free tier caps each project per minute and per day, and every image is a call. A library of a few hundred images can run into the cap, and the Cookbook’s shared project is also used by other readers, so the run has to wait out a 429 and, when the daily cap is reached, stop cleanly and continue later, not fail half-way.
  • Failure. Batches can lose an item, expire, or lose the connection. A rerun must not embed or pay twice.
  • Scale. At this size the vectors fit in memory and exact search is one matrix product. No vector database is needed, and none is added.
folder of images
| sha256 of every file; compare with the catalogue in the index
v
new or changed images only
| with a key: POST /v1/images (free), then POST /v1/batch/embeddings
| on the free tier: one call per image, the image inline
| chunks of 50, one model at a time, dinov3 then siglip2
v
index directory: index.json + vectors-dinov3-N.f32 + vectors-siglip2-N.f32
| committed after every chunk (atomic), stops cleanly at the daily cap
v
queries, all local except the query text or the query image that is not in the library
image -> dinov3 vector -> exact cosine top-k
text -> POST /v1/embeddings (siglip2 texts) -> exact cosine top-k over the siglip2 image vectors
duplicates -> dinov3 vectors, pairs above a threshold, connected components (union-find)
  1. With a key, POST /v1/images: upload each new file once and get a handle. Free. The free tier has no upload: each image goes inline as base64 (up to 4 MiB decoded).
  2. With a key, POST /v1/batch/embeddings with dinov3 and with siglip2: up to 1,000 items per request, 50 here. A batch takes one token of the per-minute limit, but its items run one after another on the server. The free tier has no batch endpoints, so there each image is one POST /v1/embeddings call per model.
  3. index.json and the vector files are written after every chunk. Vectors are L2-normalised, so the dot product is the cosine similarity.
  4. A text query is one POST /v1/embeddings call with siglip2 (0.01 credits per text, up to 64 texts per call); it is ranked against the siglip2 vectors of the images, because image and text share one space. An image query uses the stored dinov3 vector when the image is in the library, and one call otherwise.
  5. Near-duplicates need no call: the pairs above a threshold are read off the stored dinov3 vectors.

Setup and run in each language

Commands for the smoke set, run from the repository root. The smoke set needs no API key: it runs on the free tier. The full set needs a key; the cap makes the client refuse calls that could exceed it.

Requires: Python 3.12, uv 0.5

cd use-cases/05-image-library-search/python
uv sync --frozen
uv run --frozen python main.py --manifest ../assets/smoke/manifest.json --out out
# Full set: the full dataset is a release asset of the repository and needs an API key; unpack it and pass its manifest.
export FOLDBUN_API_KEY="fbs_..."
export FOLDBUN_MAX_CREDITS=51
uv run --frozen python main.py --manifest ../assets/full.json --out out
# no key needed: without FOLDBUN_API_KEY the free tier serves the calls. With a key they are charged at list price.
cd use-cases/05-image-library-search/python
uv run imgsearch.py index ~/photos # embed new and changed files; run it again to resume
uv run imgsearch.py image ~/photos/2026/beach.jpg # images that look like this one
uv run imgsearch.py text "a photo of a dog on a beach" # images that match a sentence
uv run imgsearch.py duplicates --threshold 0.90 # groups of near-duplicates
uv run imgsearch.py status # what the index holds
uv run main.py # the smoke set; writes out/result.json (what the harness runs)

index accepts --batch-size. When the server answers 429 it waits for Retry-After and carries on. When the daily cap of the project is reached, it prints how many vectors are missing and when the calls come back, and exits with code 1; run the same command then, and the index continues where it stopped. The exit codes are listed in the header of imgsearch.py.

The first query after a fresh index shows its cost on the last line, for example cost: 0.01 credits at list price, 0 charged, in 1 calls.

The same code, driven by a manifest, is what the harness runs (main.py --manifest M --out DIR). It also writes DIR/index/ (the index), DIR/stats.json (timing, what was embedded, whether the run stopped at a limit, the result of a second indexing pass that must make no call) and DIR/result.json in the format of contract/result.schema.json: one item per library image and one per text query, each with the ledger rows of its own calls.

The full set (400 images, 100 near-duplicate variants, 40 text queries, 73 MB) is a release asset of the repository (see datasets/README.md). Its manifest is committed as assets/full.json; the images and the ground truth are in the archive. Extract it into assets/ and run the reference implementation on it from the repository root. The full run needs FOLDBUN_API_KEY (it exits with code 2 without one): it is large and uses uploads and batches. It is at most 51 credits at list price (500 images x 0.10 plus 40 texts x 0.01 is 50.4) in about 1,040 calls.

tar xzf 05-image-library-search-full.tar.gz -C use-cases/05-image-library-search/assets
export FOLDBUN_API_KEY="fbs_..."
uv run python -m harness live --size full --uc 05 --max-credits 51 --dry-run # the plan, nothing is sent
uv run python -m harness refresh --size full --uc 05 --max-credits 51 # runs, scores, writes expected/full.json and expected/full-summary.json, then `uv run python -m harness snippets`

harness live runs the same and only checks the result against the floors in usecase.toml [quality]; the metrics are those of evaluate.py --result out/result.json --truth assets/truth.json.

The Go implementation is the same pipeline as one command: cd use-cases/05-image-library-search/go && go run . --manifest ../assets/smoke/manifest.json --out out. It uses only the standard library and reads and writes the same index format, so an index built by one language can be continued by the other with --resume. It has no counterpart of imgsearch.py (the folder commands are in Python only), and in Go --limit 0 means all items.

Indexing a library is work nobody sits and waits for. With a key, add --async and each model gets one async job (POST /v1/jobs) instead of batches: the images are uploaded as before, the jobs run on idle capacity at a tenth of the price, and the code polls them (every 30 seconds, --poll-seconds), reads their results and commits the vectors.

cd use-cases/05-image-library-search/python
export FOLDBUN_API_KEY="fbs_..."
uv run imgsearch.py index ~/photos --async # the folder version
uv run main.py --manifest ../assets/full.json --out out --async # the full set (after extracting it, see below)
cd ../go && go run . --manifest ../assets/smoke/manifest.json --out out --async # the same in Go
  • The price. Async items cost a tenth: the 500 images of the full set are about 50 credits with batches and about 5 with async jobs (500 x 0.10 x 0.1). The text queries are still sent as they are, so a full run is about 5.4 credits instead of 50.4.
  • No promise of when it finishes. A job runs when there is idle capacity: it may take minutes or hours, so use --async for a library you index in the background, not for one a user is waiting for. An item that has not started after 24 hours expires and is not charged, and the results of a finished job are kept for 7 days. Items that expire or fail stay missing in the index; run the same command again and they are submitted as a new job. Interrupt the run and run it again within 24 hours: the job is found by its idempotency key instead of being submitted twice.
  • A key is needed. Async jobs are not part of the free tier: without FOLDBUN_API_KEY, --async prints FOLDBUN_API_KEY is not set, and this needs a key: async jobs are not part of the free tier. and exits with code 2.

The client file (stack_client.py, stackclient/client.go) is a copy of the one in clients/ (retries and waits that follow the server’s 429 and rate-limit headers, idempotency keys for keyed calls, the credit cap and the ledger). The code below is what this use case adds.

The loop over the library. The images that lack a vector are cut into chunks and embedded with each model in turn. The models alternate chunk by chunk, so that when a run is cut short the first part of the library has both vectors.

Source: python/embedder.py (opens in a new tab)

def index_library(
client,
index: LibraryIndex,
root: Path,
models=("dinov3", "siglip2"),
*,
batch_size=50,
workers=4,
log=print,
async_mode=False,
poll_s=POLL_SECONDS,
sleep=time.sleep,
) -> Report:
"""Embed every library image that is missing from the index, with every model, a chunk at a time (or as async jobs)."""
check_free_size(client, len(index.items))
report = Report()
paths = {it["sha256"]: root / it["path"] for it in index.items}
if async_mode:
run_async(client, index, models, paths, report, workers=workers, poll_s=poll_s, log=log, sleep=sleep)
return report
for model in models:
pending = index.missing(model) # sha256 of the images that lack this model's vector, in catalogue order
log(f"{len(index.items)} images in the library, {len(pending)} to embed with {model}")
for start in range(0, len(pending), batch_size):
if report.stopped:
return report
chunk = {sha: paths[sha] for sha in pending[start : start + batch_size]}
embed_chunk(client, index, model, chunk, report, workers=workers)
log(f" {min(start + batch_size, len(pending))}/{len(pending)}")
return report

One batch. Each item of the stream is handled as it arrives. The ledger row of an item is the last row of the batch’s tag. An item that failed for a reason that may pass (image_not_found, model_busy, an expired item) goes into the next attempt; a stream that ends without a summary leaves some items with no outcome, and such an item may already be embedded and charged, so the same batch is sent again with the same body and the same idempotency key (the server replays what finished and runs the rest) instead of putting the item into a new batch; an item that still has no outcome after a few repeats is reported as outcome_unknown and is not sent under a new key; the daily cap being reached, or the credit cap, stops the run. The idempotency key of a batch is derived from its content, so rerunning an interrupted chunk replays the items that finished without charging them again.

Source: python/embedder.py (opens in a new tab)

def _pause(seconds):
time.sleep(seconds)
def run_batch(client, model, shas, handles, attempt, report):
"""One batch request (needs a key). Returns ([(sha256, vector)] that succeeded, [sha256] to send again).
A stream can end early (a dropped connection, a timeout) without a summary event. An image that got no outcome
may already have been embedded and charged on the server, so it is never sent under a new key: the same batch
is sent again with the same body and the same idempotency key, which replays what finished (no charge) and runs
the rest. Only images the server reported as failed or expired, which are not charged, go into the next attempt."""
tag = f"{model}:{shas[0][:12]}:{attempt}"
key = _key(model, handles, attempt)
body = {"model": model, "items": [{"image": sc.image_handle(h)} for h in handles]}
vectors, retry, failed = {}, set(), {} # by sha256; an image in none of them has no outcome yet
for send in range(1 + RECOVERY_SENDS):
try:
with closing(client.batch("embeddings", body, key, tag=tag)) as events:
for event, data in events:
if event != "item":
continue # progress heartbeats; the summary ends the stream
sha = shas[data["index"]]
if sha in vectors or sha in failed:
continue # a replay repeats the items we already hold
if data["status"] == "ok":
vectors[sha] = data["result"]["embeddings"][0]["vector"]
retry.discard(sha)
report.rows.setdefault(sha, []).append(client.calls(tag)[-1]) # the ledger row of the item that just arrived
elif data["status"] == "expired" or data["error"]["code"] in RETRY_CODES:
retry.add(sha) # not billed; goes into the next attempt (an evicted handle is uploaded again)
elif data["error"]["code"] in STOP_CODES:
report.stopped = {**data["error"], "model": model}
break # closing the stream stops the batch; the items that already finished are kept
else:
failed[sha] = data["error"] # for example an image the API cannot read: no retry helps
except sc.StackError as err:
if err.code in STOP_CODES: # refused before the stream started, or by the credit cap
report.stopped = {"code": err.code, "message": err.message, "model": model}
elif not err.retryable:
raise
if report.stopped or all(s in vectors or s in retry or s in failed for s in shas):
break
_pause(min(2**send, 10))
report.failed.update(failed)
if not report.stopped:
for sha in shas:
if sha not in vectors and sha not in retry and sha not in failed:
report.failed[sha] = {
"code": "outcome_unknown",
"message": "the stream ended before this image's outcome arrived, and every repeat under the same key failed too; "
"it was not sent under a new key because it may already be charged",
}
return [(s, vectors[s]) for s in shas if s in vectors], [s for s in shas if s in retry]
def run_singles(client, model, paths, shas, report, workers):
"""The free tier: one `/v1/embeddings` call per image, the bytes inline as base64 (at most 4 MiB). Same return value as run_batch."""
def one(sha):
if report.stopped:
return sha, "retry", None # another call already hit a limit: send nothing more
tag = f"{model}:{sha[:12]}"
body = {"model": model, "image": sc.image_base64(paths[sha].read_bytes())}
try:
result = client.post("/v1/embeddings", body, tag=tag) # the client waits and retries 429 by itself
except sc.MissingApiKey:
raise
except sc.StackError as err:
if err.code == "model_locked":
raise
kind = "stop" if err.code in STOP_CODES else "retry" if err.code in RETRY_CODES else "fail"
return sha, kind, {"code": err.code, "message": err.message}
return sha, "ok", (result["embeddings"][0]["vector"], client.calls(tag)[-1])
done, retry = [], []
with ThreadPoolExecutor(workers) as pool:
for sha, kind, value in pool.map(one, shas):
if kind == "ok":
done.append((sha, value[0]))
report.rows.setdefault(sha, []).append(value[1])
elif kind == "retry":
retry.append(sha)
elif kind == "stop":
report.stopped = report.stopped or {**value, "model": model}
else:
report.failed[sha] = value
return done, retry
def embed_chunk(client, index: LibraryIndex, model: str, paths: dict[str, Path], report: Report, *, workers=4) -> None:
"""Embed the images `paths` (sha256 -> file) with `model`, commit them, and record the outcome in `report`."""
todo = list(paths)
for attempt in range(ATTEMPTS):
if not todo or report.stopped:
break
if client.free:
done, retry = run_singles(client, model, paths, todo, report, workers)
else:
with ThreadPoolExecutor(workers) as pool:
handles = list(pool.map(lambda sha: _upload(client, paths[sha]), todo)) # free of charge; also re-uploads evicted images
done, retry = run_batch(client, model, todo, handles, attempt, report)
if done:
index.add(model, [s for s, _ in done], [v for _, v in done])
index.commit()
report.embedded += len(done)
todo = retry
for sha in [] if report.stopped else todo:
report.failed.setdefault(sha, {"code": "gave_up", "message": f"not embedded after {ATTEMPTS} attempts"})

The index on disk. Vector files are never modified in place. A commit writes new files, then replaces index.json atomically, then deletes the files nothing refers to. A crash leaves the old index or the new one.

Source: python/index.py (opens in a new tab)

def commit(self) -> None:
"""Write what changed. Call it after every batch, so that a stop or a crash loses at most one batch."""
self.dir.mkdir(parents=True, exist_ok=True)
keep = {it["sha256"] for it in self.items}
self.generation += 1
for model in sorted(self._dirty):
rows = self._rows[model]
order = [sha for sha, _ in sorted(rows.items(), key=lambda kv: kv[1]) if sha in keep]
matrix = self._vectors[model][[rows[sha] for sha in order]] if order else self._vectors[model][:0]
self._vectors[model], self._rows[model] = matrix, {sha: i for i, sha in enumerate(order)}
name = f"vectors-{model}-{self.generation}.f32"
atomic_write(self.dir / name, np.ascontiguousarray(matrix, dtype="<f4").tobytes())
self.models[model].update(file=name, sha256s=order)
self._dirty.clear()
meta = {"format": FORMAT, "generation": self.generation, "items": self.items, "models": self.models}
atomic_write(self.dir / "index.json", json.dumps(meta, indent=1).encode())
live = {info["file"] for info in self.models.values()}
for stale in self.dir.glob("vectors-*.f32"):
if stale.name not in live:
stale.unlink()

Exact search. The vectors are L2-normalised, so one matrix-vector product gives every cosine similarity.

Source: python/search.py (opens in a new tab)

def top_k(matrix: np.ndarray, query, k: int, exclude: int | None = None) -> list[tuple[int, float]]:
"""The `k` rows of `matrix` most similar to `query`, as (row, score), best first. `exclude` skips one row (the query itself)."""
if len(matrix) == 0:
return []
scores = matrix @ np.asarray(query, dtype=np.float32)
if exclude is not None:
scores[exclude] = -np.inf
k = min(k, len(scores) - (exclude is not None))
if k <= 0:
return []
best = np.argpartition(-scores, k - 1)[:k] if k < len(scores) else np.arange(len(scores))
best = best[np.lexsort((best, -scores[best]))] # by score, ties by row, so the order is stable
return [(int(i), float(scores[i])) for i in best]

Near-duplicates. Pairs above the threshold are found block by block (memory stays bounded) and merged with union-find.

Source: python/search.py (opens in a new tab)

class UnionFind:
def __init__(self, n: int):
self.parent = list(range(n))
def find(self, i: int) -> int:
while self.parent[i] != i:
self.parent[i] = self.parent[self.parent[i]] # path halving
i = self.parent[i]
return i
def union(self, i: int, j: int) -> None:
self.parent[self.find(j)] = self.find(i)
def similar_pairs(matrix: np.ndarray, threshold: float, block: int = 1024):
"""Yield (i, j, score) for every pair i < j with similarity >= threshold, one block of rows at a time (memory stays O(block x n))."""
n = len(matrix)
for start in range(0, n, block):
scores = matrix[start : start + block] @ matrix.T
rows, cols = np.nonzero(scores >= threshold)
for r, c in zip(rows, cols):
if start + r < c:
yield int(start + r), int(c), float(scores[r, c])
def duplicate_groups(matrix: np.ndarray, threshold: float) -> list[list[int]]:
"""Groups of rows that are near-duplicates of each other, found as connected components of the 'similar enough' graph.
Connected components are transitive: if A resembles B and B resembles C, all three end up in one group even when A and
C are below the threshold. A high threshold keeps chains short; the groups are what a person reviews, not a verdict.
"""
uf = UnionFind(len(matrix))
for i, j, _ in similar_pairs(matrix, threshold):
uf.union(i, j)
groups: dict[int, list[int]] = {}
for i in range(len(matrix)):
groups.setdefault(uf.find(i), []).append(i)
return sorted((g for g in groups.values() if len(g) > 1), key=lambda g: g[0])

Incremental re-indexing is checked on every run. After indexing, main.py indexes again. Nothing is missing, so the second pass must make no API call; the number is recorded in stats.json, and a call makes the run fail.

Source: python/main.py (opens in a new tab)

calls_before = len(client.ledger)
if args.use_async and (report.stopped or report.failed):
again = None # what is missing would only be submitted as new jobs; the next run does that
else:
again = embedder.index_library(client, index, base, MODELS, batch_size=args.batch_size, workers=args.concurrency, log=lambda *_: None, **mode)
stats["reindex"] = (
{"apiCalls": len(client.ledger) - calls_before, "embedded": again.embedded} if again else None
) # nothing is missing, so nothing is sent

Text queries. One call per query keeps the cost and the latency of each query in its own item. Texts can be sent together (up to 64 per call) to spend fewer calls against the project’s limits; the price is per text either way.

Source: python/main.py (opens in a new tab)

text_items, text_ms = [], []
siglip_items, siglip_matrix = index.matrix("siglip2")
for q in manifest.get("queries", []):
entry = {"id": q["id"], "calls": [], "output": None}
try:
vector, row = embedder.embed_text(client, q["text"], tag=q["id"])
t = time.monotonic()
ranked = search.top_k(siglip_matrix, vector, TEXT_RESULTS)
text_ms.append((time.monotonic() - t) * 1000)
entry["status"], entry["calls"] = "ok", [row]
entry["output"] = {"type": "query", "text": q["text"], "ranking": [siglip_items[i]["id"] for i, _ in ranked], "scores": [r4(s) for _, s in ranked]}
except sc.StackError as err:
print(f" {q['id']}: {err.status} {err.code}: {err.message}", file=sys.stderr)
if err.code == "model_locked":
return EXIT_TIER
entry["status"] = "expired" if err.code in embedder.STOP_CODES else "error"
entry["error"] = {"status": err.status, "code": err.code, "message": err.message}
if err.code == "budget_exceeded":
code = EXIT_BUDGET
text_items.append(entry)

The Go program has a second mode that serves searches over an index that an earlier run wrote, in Python or in Go (the format is shared): go run . serve --index out/index. It listens on 127.0.0.1:8080 by default (--addr changes it), is read-only (nothing is indexed over HTTP), answers JSON and reports every error as {"error": {"code": "...", "message": "..."}}.

curl "127.0.0.1:8080/search?q=a+photo+of+a+dog&k=10" # images that match a text (siglip2)
curl "127.0.0.1:8080/similar?id=5177b735e298df6c&k=10" # images that look like a library image (dinov3)
curl "127.0.0.1:8080/duplicates?threshold=0.90" # groups of near-duplicates (dinov3)
curl "127.0.0.1:8080/healthz"

/search embeds the text with siglip2 through the client, so every query is one call (0.01 credits at list price; free on the free tier, which the service uses when FOLDBUN_API_KEY is not set, and charged when it is). /similar and /duplicates read the stored vectors and make no API call. k defaults to 10 and is lowered to 100 when larger; a bad k, an empty or over-long q and a threshold outside (0, 1] answer 400, an unknown image id 404, any method but GET 405, and an API failure 502 (429 when the project’s limit, the balance or the credit cap is used up). SIGINT and SIGTERM stop the service after the running requests finish.

The handler table and the server settings (timeouts, header limit, graceful shutdown) are all of it:

Source: go/serve.go (opens in a new tab)

// handler routes the four read-only endpoints; any other method or path gets the standard error shape.
func (s *service) handler() http.Handler {
routes := map[string]http.HandlerFunc{"/search": s.search, "/similar": s.similar, "/duplicates": s.duplicates, "/healthz": s.healthz}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h, ok := routes[r.URL.Path]
switch {
case !ok:
apiError(w, http.StatusNotFound, "not_found", "unknown path")
case r.Method != http.MethodGet && r.Method != http.MethodHead:
w.Header().Set("Allow", "GET, HEAD")
apiError(w, http.StatusMethodNotAllowed, "method_not_allowed", "the service is read-only: use GET")
default:
h(w, r)
}
})
}
// listenAndServe serves until ctx ends (SIGINT or SIGTERM in main), then lets running requests finish for up to 10 s.
func listenAndServe(ctx context.Context, ln net.Listener, h http.Handler) error {
srv := &http.Server{
Handler: h,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 2 * time.Minute, // a text query waits for the API, which may retry
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 16 << 10,
}
failed := make(chan error, 1)
go func() { failed <- srv.Serve(ln) }()
select {
case err := <-failed:
return err
case <-ctx.Done():
}
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(shutdown)
}

The search is a brute-force pass over the vectors, which is fine to a few tens of thousands of images; see the limits below for what to use beyond that.

What is measured, with evaluate.py (standard library only; it reads result.json, stats.json and the ground truth):

  • Image to image. Each near-duplicate variant is a query; i2i_recall_at_k is the share of variants whose original is among the k nearest images.
  • Text to image. 40 queries of the form “a photo of a <class>”, scored against the human-verified Open Images image-level labels of the originals: text_precision_at_5, text_precision_at_10, text_recall_at_10, text_map. Variants are not relevant by definition and are removed from the rankings before scoring.
  • Near-duplicates. Precision, recall and F1 of “similarity at or above the threshold” on the candidate pairs. The threshold is chosen on split a of the data (the lowest threshold that keeps precision at 0.99 or better) and applied unchanged to split b, where the numbers are reported.
  • Speed and cost. The local search time (no network involved), the number of calls a second indexing pass makes (it must be none), and the list price and the charge per 1,000 images. Indexing throughput depends on the reader’s network path to the API, so it is not published.

The numbers below are generated from expected/full-summary.json, which a maintainer records from a live run on the full set (about 500 images). Until then the block says so. The offline runs of harness check use the fake API, whose vectors are deterministic but carry no meaning: they verify the plumbing (the index is built, a second pass sends nothing, queries return ranked results of the right shape) and not the quality, so no quality bound applies to them.

Metric Value
i2i_recall_at_1 1
i2i_recall_at_5 1
i2i_recall_at_10 1
text_precision_at_5 0.905
text_precision_at_10 0.8075
text_recall_at_10 0.7963
text_map 0.8438
text_queries 40
dup_threshold 0.9352
dup_precision 1
dup_recall 0.9149
dup_f1 0.9556
dup_pairs_a 53
dup_pairs_b 47
images 500
images_embedded 500
cost_per_1000_images_list 100
cost_per_1000_images_charged 90
cost_per_text_query_list 0.01
search_ms_text 0.389
search_ms_image 0.003
second_pass_api_calls 0

An image costs 0.05 credits with dinov3 and 0.05 with siglip2; a text costs 0.01 with siglip2. The smoke set (25 images, 5 queries) is 25 x 0.10 + 5 x 0.01 = 2.55 credits at list price, in 55 calls: 25 for dinov3, 25 for siglip2 and 5 text queries. On the free tier the smoke run is not charged: it prints that list price labelled “free tier, not charged”. The full set (about 500 images, 40 queries) is 50.4 credits at list price, in about 1,040 calls, charged to a key; indexing resumes after each stop. With --async the 500 images cost a tenth, 5 instead of 50 credits (about 5.4 credits with the queries); the measured table below is of the batch run.

Each run records its own list price and charge:

Run Calls List price (credits) Charged (credits)
smoke 55 2.55 0
full 1040 45.4 45.4

Per 1,000 images the library costs 100 credits at list price, once; after that only new and changed images are charged. Queries cost 0.01 credits for a text and nothing for an image that is already in the library.

  • Exact search is for this size. One query is one pass over all vectors: about 3 MB per 1,000 images (768 values of 4 bytes), a few milliseconds for 10,000 images. Past roughly 50,000 to 100,000 images, or when queries must answer in a few milliseconds under load, move to an approximate index (FAISS, hnswlib, or pgvector in a database). Keep the interface: top_k(matrix, query, k) becomes a call to the index, the vector files stay the source of truth, and nothing else in the pipeline changes. All-pairs duplicate search grows with the square of the library; at that size use the index’s range search or group by a coarse hash first.
  • Duplicates are a threshold on a similarity. The default (0.90) is a starting point. Choose it on a labelled sample of the library, as evaluate.py does, and expect crops and heavy re-compression to score lower than resizes. Connected components chain: A resembles B and B resembles C puts all three in one group.
  • Image-level meaning only. Both models describe a whole image; there is no object location. siglip2 takes a 224 px input, so small objects are lost. Text queries work best in English, and the scores are small numbers: only the ranking carries meaning, so no fixed cut-off is used.
  • The model is part of the index. Vectors of different models are not comparable, and a new version of a model would make old vectors inconsistent with new ones. The index stores the vector length of each model and refuses a different one; rebuild it when a model changes.
  • Free-tier limits. The free tier limits each project per minute and per day by the weight of the model, and the Cookbook’s shared project is used by every reader, so a cap can be reached by others. The code reacts to the 429 and the headers the server sends instead of assuming a number. Items of a batch run one after another, so a batch of N takes about N times the processing time of one image; keep chunks well inside the 600 s limit of a batch.
  • Uploads are kept by the client. The client file keeps the bytes of uploaded images in memory to upload again when a handle is evicted. For a very large library, index it in several runs.
  • Reference: Embeddings and search (opens in a new tab), DINOv3 (opens in a new tab), SigLIP 2 (opens in a new tab) and Rate limits (opens in a new tab) in the documentation. dinov3 output is covered by the DINOv3 License; products built on it should show the tag “Built with DINOv3”.

The smoke set is 20 original photos, 5 near-duplicate variants and 5 text queries from datasets/smoke/05-image-library-search/ (assets/smoke/ links to it). The photos come from the Open Images V7 validation split (images CC BY 2.0 by their authors, labels CC BY 4.0); the variants are derived from them with recorded transforms. Authors and licences are in assets/smoke/ATTRIBUTION.csv. The full set (400 images, 100 variants, 40 queries) is a release asset described in datasets/README.md. Rights holders can request removal of an image or dataset through the contact page (opens in a new tab).