Skip to main content

@betterdb/retrieval (Python)

PyPI version total downloads license: MIT python GitHub stars

betterdb-retrieval — developer-facing retrieval SDK over Valkey Search (FT.*): typed index schema, idempotent index lifecycle, upsert/delete, and vector + filtered + hybrid query. This is the Python equivalent of the TypeScript @betterdb/retrieval package, built on betterdb-valkey-search-kit.

See it live in BetterDB Monitor

BetterDB Monitor auto-discovers every betterdb-retrieval instance on your Valkey - zero configuration, the library already registers itself - and turns its stats into live dashboards:

  • AI Cache & Memory - hit rate, cost saved, evictions, and index size across all your caches and memory stores, with history.
  • AI Traces - OpenTelemetry waterfalls for each request, correlated with live Valkey state to explain every cache hit and miss.

AI Cache & Memory tab in BetterDB Monitor

AI Traces waterfall in BetterDB Monitor

Run it self-hosted (docker run -p 3001:3001 betterdb/monitor), or use BetterDB Cloud - which can also provision a managed, TLS-enabled Valkey instance with the Search module in one click - exactly what this library needs.

Installation

pip install betterdb-retrieval valkey

Requires a Valkey server with the Valkey Search module loaded.

Quick start

from valkey.asyncio import Valkey

from betterdb_retrieval import Retriever, UpsertEntry

client = Valkey.from_url("redis://localhost:6379")


async def embed(text: str) -> list[float]:
    ...  # return an embedding


retriever = Retriever(
    client=client,
    name="docs",
    schema={
        "fields": {
            "category": {"type": "tag"},
            "year": {"type": "numeric", "sortable": True},
        },
        "vector": {"algorithm": "hnsw", "metric": "cosine"},
    },
    embed_fn=embed,
)

# Create the index if it doesn't exist (idempotent; dims resolved from embed_fn).
await retriever.create_index()

await retriever.upsert([
    UpsertEntry(
        id="doc1",
        text="Valkey is a high-performance key-value store",
        fields={"category": "db", "year": 2024},
    ),
])

hits = await retriever.query(
    text="fast in-memory database",
    k=5,
    filter={"category": "db"},
)

Retriever API

  • create_index() — create the index if absent (idempotent). Vector dimension is taken from schema["vector"]["dims"] or resolved by probing embed_fn.
  • upsert(entries) — embed each entry's text and write it as a hash with its fields.
  • delete(ids) — delete documents by id.
  • query(*, k, text=None, vector=None, filter=None, hybrid=None) — KNN search. Provide text (embedded for you) or a precomputed vector, a positive k, an optional filter (tag/numeric fields), and hybrid="rerank" to post-process hits through a rerank_fn. Returns list[QueryHit].
  • describe_index() / health() — index stats: doc count, indexing state, dimension, percent indexed, and an optional estimated recall.
  • drop_index() — drop the index (no-op if it doesn't exist).
  • register() / unregister() — publish/remove a discovery marker in the shared __betterdb:caches registry, ownership-checked so it never clobbers a foreign cache type.

QueryHit.score is the raw KNN vector distance (lower is closer), not a similarity — rank ascending.

Observability

Pass metrics (a RetrievalMetrics) and/or tracer (a RetrievalTracer) to instrument every operation. create_prometheus_metrics() provides a ready-made prometheus-client implementation.

Development

uv run --extra dev pytest tests -q

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

betterdb_retrieval-0.4.1.tar.gz (42.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

betterdb_retrieval-0.4.1-py3-none-any.whl (19.3 kB view details)

Uploaded Python 3

File details

Details for the file betterdb_retrieval-0.4.1.tar.gz.

File metadata

  • Download URL: betterdb_retrieval-0.4.1.tar.gz
  • Upload date:
  • Size: 42.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for betterdb_retrieval-0.4.1.tar.gz
Algorithm Hash digest
SHA256 d9f633fbaf58d717ae6c9c01f7977cf8d78fe2a8dd455c921b239f90f9f7ef8a
MD5 9298cc057fa6e36927df480e51c9670f
BLAKE2b-256 615b7fb960e2d9c01cb2481d2454d62f7aac8a696b17a8afd8328936b01fd0c8

See more details on using hashes here.

Provenance

The following attestation bundles were made for betterdb_retrieval-0.4.1.tar.gz:

Publisher: retrieval-py-release.yml on BetterDB-inc/monitor

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file betterdb_retrieval-0.4.1-py3-none-any.whl.

File metadata

File hashes

Hashes for betterdb_retrieval-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 01b97fb443f66077b305879991acf0891dc00e286b365cce5470feaad7771628
MD5 669049aea909efb20618cad18273640f
BLAKE2b-256 3c80df4ac1fa2af9528e66dd631e47988a6a81cf6ba7a303fdcd243b96184429

See more details on using hashes here.

Provenance

The following attestation bundles were made for betterdb_retrieval-0.4.1-py3-none-any.whl:

Publisher: retrieval-py-release.yml on BetterDB-inc/monitor

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.5.0

2 files

This release

0.4.1 This release

2 files

0.4.0

2 files

0.3.0

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page