Skip to Content
Recodocs

Vector indexes, embeddings and retrieval adapters

Shared VectorIndex contracts, optional backend adapters, embedding and rerank clients, parity tooling and hosted-service workflows with explicit caller-owned credentials.

7 min read

recohut_kit.vectors groups optional vector indexes and embedding clients under one namespace. Importing the package root does not load backends, SDKs or credentials. Submodules map a small set of contracts onto SQLite tables, PostgreSQL pgvector, Redis Search, Qdrant, Chroma, OpenSearch, S3 Vectors, Pinecone and Weaviate HTTP APIs, Amazon Bedrock Knowledge Bases, and file-backed LEANN indexes. Most of the code is deterministic adapters and arithmetic; embedding and rerank helpers call a model only when you pass a loaded client or when a submodule invokes your injected SDK.

The layer owns shape and wiring: records, hits, score direction, and filters as native objects. It keeps ingestion batch receipts, parity query receipts, and CollectionStatus (including states such as ready and loading). PineconeIndex.create_index refuses with ControlPlaneRefused; index creation is a control-plane act left to the caller, while temporary_document_index creates and deletes one ephemeral Pinecone index from a caller-supplied client, cloud, and region. The layer does not own automatic model downloads, environment-based credential discovery, or a full retrieval agent loop.

Purpose

A vector index compares numeric representations to retrieve plausible matches. Similarity is a way to find candidates; it is not proof that a match answers the person's question.

The vectors layer answers how kit code reads and writes embeddings in a backend-neutral way. recohut_kit.vectors.contracts defines VectorRecord, VectorHit, ScoreSemantics, and the VectorIndex and Embeddings protocols. Most VectorIndex adapters implement create, upsert, filtered query, delete, and unwrap(); NumpyUnitIndex and BedrockKnowledgeBase expose those methods and refuse writes. Scores stay in the backend’s native semantics; adapters may declare score_semantics so callers know whether higher or lower is better.

What lives here includes local exact indexes (sqlite, numpy_index), ANN-oriented database adapters (pgvector, redis_search), REST adapters with shared retry mechanics (pinecone, weaviate, _rest), in-memory recorded stand-ins for those REST paths (recorded), Qdrant collection create, upsert, query, and delete, plus optional sparse vectors (qdrant), semantic search across bound collections (collection_search), best-hit-per-item fetch (multi_view), brute-force parity reports (parity), metric and context-budget utilities (scaling, distance), Pinecone-specific ingestion and query builders, Bedrock KB read and publish paths, and thin embedding or cross-encoder wrappers.

What deliberately does not live here: choosing a hosted index SKU, billing, unstructured document parsing, lexical FTS (tests compose recohut_kit.storage.sqlite_fts beside SQLiteVectorIndex), and reasoning over retrieved passages. BedrockKnowledgeBase keeps VectorIndex query shape but rejects upsert, delete and numeric-vector-only callers because Bedrock owns the vectors.

Public API

The package root exports no names; import submodules explicitly (for example recohut_kit.vectors.contracts). The table lists the main public types and callables declared in module docstrings, __all__, or class definitions at module scope.

NameKindModuleWhat it does
VectorRecorddataclasscontractsStored row: identifier, vector tuple, and JSON metadata
VectorHitdataclasscontractsQuery hit: identifier, score, and metadata
ScoreSemanticsdataclasscontractsDeclares score kind and whether higher is better
SCORE_KINDSconstantcontractsAllowed score kind strings
score_semantics_offunctioncontractsReads an index’s optional score_semantics
require_id_sequencefunctioncontractsRejects a bare string mistaken for an id list
VectorIndexprotocolcontractscreate/upsert/query/delete collection API
Embeddingsprotocolcontractsembed(texts) plus unwrap()
cosine, dot, normalize, normalized_dot, euclideanfunctionsscalingDependency-free vector math
metric_consistency_check, MetricConsistencyfunction, classscalingChecks metric agreement on samples
plan_context, ContextBudgetfunction, classscalingAdmits a ranked prefix under a token budget
StageRecorder, aggregate_stages, diagnoseclass, functionsscalingStage timing recorder, stage totals, and advice
squared_euclidean, manhattan, hamming, metric_guidancefunctions, tupledistanceSquared Euclidean, Manhattan, and Hamming distances, and metric guidance records
SQLiteVectorIndex, pack_vector, unpack_vectorclass, functionssqliteSQLite tables with float32 blobs and cosine rank
NumpyUnitIndexclassnumpy_indexRead-only unit vectors with NumPy dot ranking
PgVectorIndex, HnswIndexOptions, IvfflatIndexOptions, AnnIndexReceiptclasspgvectorpgvector tables and explicit ANN index DDL
PineconeIndex, auth_headers, equals_filterclass, functionspineconePinecone data-plane REST VectorIndex
WeaviateIndex, auth_headers, equals_filter, graphql_literalclass, functionsweaviateWeaviate REST plus GraphQL queries
RetryPolicy, send, VectorAuthError, …class, function, errors_restShared httpx send with bounded 429/503 retry
RecordedPinecone, RecordedWeaviate, recorded_clientclasses, functionrecordedIn-memory exact backends behind MockTransport
QdrantIndex, with_sparse, native_queryclass, functionsqdrantQdrant collections with optional sparse vectors
ChromaIndex, embedding_function_classclass, functionchromaChroma with caller-supplied embeddings
OpenSearchIndexclassopensearchOpenSearch k-NN index adapter
RedisSearchIndex, IndexInfo, similarityclasses, functionredis_searchRedis Search HASH vectors, default HNSW, with exact FLAT available; similarity converts a native distance to a score
S3VectorsIndexclasss3_vectorsAmazon S3 Vectors index operations
LeannPassage, LeannRetriever, equality_filterclasses, functionleannLeannRetriever is a text-in retriever (search(query, limit)), not a VectorIndex; equality_filter builds an equality filter
OpenAIEmbeddingsclassembeddings_openaiOpenAI embeddings via injected client
BedrockEmbeddingsclassembeddings_bedrockBedrock Titan embeddings with bounded decode
SentenceTransformerEmbeddings, EmbeddingBatchclassesembeddings_sentence_transformersPreloaded SentenceTransformer encoder
SentenceTransformerReranker, RerankReceiptclass, dataclassrerank_sentence_transformersPreloaded CrossEncoder scores
CollectionSearch, CollectionBinding, verify_embedding_modelclasses, functioncollection_searchverify_embedding_model returns the lowest re-embedding cosine
query_best_per_item, ItemHit, GroupedHitsfunction, classesmulti_viewBest hit per item with over-fetch
ExactReference, parity_report, ParityReport, backend_matrixtypes, functionsparityRecall@k and monotonicity vs brute force
reconcile, ReconcileReportfunction, dataclassreconcileSync authoritative projection into Qdrant
PineconeIngestion, require_publishedclass, functionpinecone_ingestionBatched Pinecone ingest with drift checks
PineconeVectorSearch, PineconeDocumentSearchclassespinecone_documentsDense and integrated document search helpers
temporary_document_indexfunctionpinecone_resourcesEphemeral Pinecone index lifetime
search_after_writefunctionpinecone_readinessPoll until search sees new writes
rerank_candidatesfunctionpinecone_rerankPinecone rerank API mapping
reconcile_sourcefunctionpinecone_lifecycleNamespace reconcile against a source projection
BedrockKnowledgeBaseclassbedrock_knowledge_baseText query against a managed knowledge base
BedrockKnowledgeBasePublisherclassbedrock_kb_publishS3 publish plus ingestion job for a KB

pinecone_application verifies an existing index and binds a tenant to one namespace; pinecone_queries builds lexical clauses with no client.

How it composes

Within the kit, imports are intentional and narrow:

This vectors moduleImports from
contracts, parity, most adaptersrecohut_kit.json (JsonValue, canonical_json, …)
collection_searchrecohut_kit.retrieval_calibration
scalingrecohut_kit.latency, recohut_kit.retrieval_benchmark
rerank_sentence_transformersrecohut_kit.inspection, recohut_kit.json, recohut_kit.knowledge
pinecone_ingestionrecohut_kit.production.retry, recohut_kit.storage.sqlite_tx
bedrock_knowledge_base, bedrock_kb_publishrecohut_kit.providers.receipts; publish also uses recohut_kit.knowledge, recohut_kit.objects.s3
pinecone, weaviate, recorded, parity, reconcile, distancesibling recohut_kit.vectors.* modules

The package root docstring states it uses nothing else in the kit. Adapters expect you to inject database connections, HTTP clients, cloud SDK clients, and API keys. recorded.py imports httpx on import; chromadb and qdrant_client import inside the calls that need them; these submodules do not import pinecone or sentence_transformers at runtime (pinecone appears only in type-checking imports).

Minimal usage example

The SQLite test uses an in-memory index, three records, a metadata filter with limit=3, a ValueError on a wrong-length upsert, and delete of "a".

import sqlite3

from recohut_kit.vectors.contracts import VectorRecord
from recohut_kit.vectors.sqlite import SQLiteVectorIndex

connection = sqlite3.connect(":memory:")
index = SQLiteVectorIndex(connection)
index.create_collection("items", dimensions=2)
index.upsert(
    "items",
    [
        VectorRecord("b", (1.0, 0.0), {"kind": "x", "n": 1}),
        VectorRecord("a", (2.0, 0.0), {"kind": "y", "n": 1}),
        VectorRecord("c", (0.0, 1.0), {"kind": "x", "n": 2}),
    ],
)
hits = index.query("items", (1.0, 1.0), limit=3)
assert [hit.identifier for hit in hits] == ["a", "b", "c"]
filtered = index.query("items", (1.0, 0.0), limit=3, metadata_filter={"kind": "x"})
assert [hit.identifier for hit in filtered] == ["b", "c"]
index.delete("items", ["a"])
connection.close()

The SQLite test breaks equal cosine scores by identifier, so query (1.0, 1.0) returns a, then b, then c. Equality filters in that test match JSON metadata scalars. The SQLite test rejects a 3-D upsert into the 2-D collection with ValueError.

Limits and gotchas

  • Native scores and filters. VectorIndex.query accepts metadata_filter objects defined by each backend. ScoreSemantics must agree with the kind string; mismatches raise at construction time.
  • Identifier batches. require_id_sequence and adapters that call it reject passing a single string where a sequence of ids is expected.
  • SQLite float32. pack_vector refuses vectors whose float32 Euclidean norm is outside 1e-15..1e15, the range where float32 cosine would underflow or overflow. SQLiteVectorIndex scores cosine similarity (higher is better), which differs from PgVectorIndex cosine distance semantics documented in sqlite.py.
  • Exact local scan. Default SQLite ranking scans every row matching the filter. NumPy is used when importable, pure Python otherwise; use_sqlite_vec=True opts into sqlite-vec and computes the same cosine.
  • REST adapters are not agents. Pinecone and Weaviate modules map fixed documented requests. Credential headers are caller-supplied. Pinecone create_index, and a dimension mismatch on create_collection, raise ControlPlaneRefused; WeaviateIndex.create_collection creates the class.
  • Recorded lane. recorded_client never hits the network; parity latency measures adapter plus stand-in, not a hosted service (parity module docstring).
  • Cross-backend comparison. parity_report checks recall@k and score monotonicity in each backend’s native direction; it does not compare raw scores across backends.
  • Embeddings modules. embeddings_sentence_transformers does not import sentence_transformers at module import; you preload the model. BedrockEmbeddings and OpenAIEmbeddings require explicit model and client; BedrockEmbeddings also requires a positive max_response_bytes. Titan schema only unless you use unwrap().
  • Bedrock KB partial index. BedrockKnowledgeBase supports text-oriented query; collection write paths are unsupported by design.
  • LEANN build policy. LeannRetriever.build refuses remote embedding modes unless allowed and rejects duplicate passage ids (asserted in tests).
  • Scaling estimates. scaling.plan_context and related helpers produce planning numbers, not invoices.

Verification

The example checks local ranking and metadata filters. See Verify the examples.

How is this page?

Last updated on