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.
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.
| Name | Kind | Module | What it does |
|---|---|---|---|
VectorRecord | dataclass | contracts | Stored row: identifier, vector tuple, and JSON metadata |
VectorHit | dataclass | contracts | Query hit: identifier, score, and metadata |
ScoreSemantics | dataclass | contracts | Declares score kind and whether higher is better |
SCORE_KINDS | constant | contracts | Allowed score kind strings |
score_semantics_of | function | contracts | Reads an index’s optional score_semantics |
require_id_sequence | function | contracts | Rejects a bare string mistaken for an id list |
VectorIndex | protocol | contracts | create/upsert/query/delete collection API |
Embeddings | protocol | contracts | embed(texts) plus unwrap() |
cosine, dot, normalize, normalized_dot, euclidean | functions | scaling | Dependency-free vector math |
metric_consistency_check, MetricConsistency | function, class | scaling | Checks metric agreement on samples |
plan_context, ContextBudget | function, class | scaling | Admits a ranked prefix under a token budget |
StageRecorder, aggregate_stages, diagnose | class, functions | scaling | Stage timing recorder, stage totals, and advice |
squared_euclidean, manhattan, hamming, metric_guidance | functions, tuple | distance | Squared Euclidean, Manhattan, and Hamming distances, and metric guidance records |
SQLiteVectorIndex, pack_vector, unpack_vector | class, functions | sqlite | SQLite tables with float32 blobs and cosine rank |
NumpyUnitIndex | class | numpy_index | Read-only unit vectors with NumPy dot ranking |
PgVectorIndex, HnswIndexOptions, IvfflatIndexOptions, AnnIndexReceipt | class | pgvector | pgvector tables and explicit ANN index DDL |
PineconeIndex, auth_headers, equals_filter | class, functions | pinecone | Pinecone data-plane REST VectorIndex |
WeaviateIndex, auth_headers, equals_filter, graphql_literal | class, functions | weaviate | Weaviate REST plus GraphQL queries |
RetryPolicy, send, VectorAuthError, … | class, function, errors | _rest | Shared httpx send with bounded 429/503 retry |
RecordedPinecone, RecordedWeaviate, recorded_client | classes, function | recorded | In-memory exact backends behind MockTransport |
QdrantIndex, with_sparse, native_query | class, functions | qdrant | Qdrant collections with optional sparse vectors |
ChromaIndex, embedding_function_class | class, function | chroma | Chroma with caller-supplied embeddings |
OpenSearchIndex | class | opensearch | OpenSearch k-NN index adapter |
RedisSearchIndex, IndexInfo, similarity | classes, function | redis_search | Redis Search HASH vectors, default HNSW, with exact FLAT available; similarity converts a native distance to a score |
S3VectorsIndex | class | s3_vectors | Amazon S3 Vectors index operations |
LeannPassage, LeannRetriever, equality_filter | classes, function | leann | LeannRetriever is a text-in retriever (search(query, limit)), not a VectorIndex; equality_filter builds an equality filter |
OpenAIEmbeddings | class | embeddings_openai | OpenAI embeddings via injected client |
BedrockEmbeddings | class | embeddings_bedrock | Bedrock Titan embeddings with bounded decode |
SentenceTransformerEmbeddings, EmbeddingBatch | classes | embeddings_sentence_transformers | Preloaded SentenceTransformer encoder |
SentenceTransformerReranker, RerankReceipt | class, dataclass | rerank_sentence_transformers | Preloaded CrossEncoder scores |
CollectionSearch, CollectionBinding, verify_embedding_model | classes, function | collection_search | verify_embedding_model returns the lowest re-embedding cosine |
query_best_per_item, ItemHit, GroupedHits | function, classes | multi_view | Best hit per item with over-fetch |
ExactReference, parity_report, ParityReport, backend_matrix | types, functions | parity | Recall@k and monotonicity vs brute force |
reconcile, ReconcileReport | function, dataclass | reconcile | Sync authoritative projection into Qdrant |
PineconeIngestion, require_published | class, function | pinecone_ingestion | Batched Pinecone ingest with drift checks |
PineconeVectorSearch, PineconeDocumentSearch | classes | pinecone_documents | Dense and integrated document search helpers |
temporary_document_index | function | pinecone_resources | Ephemeral Pinecone index lifetime |
search_after_write | function | pinecone_readiness | Poll until search sees new writes |
rerank_candidates | function | pinecone_rerank | Pinecone rerank API mapping |
reconcile_source | function | pinecone_lifecycle | Namespace reconcile against a source projection |
BedrockKnowledgeBase | class | bedrock_knowledge_base | Text query against a managed knowledge base |
BedrockKnowledgeBasePublisher | class | bedrock_kb_publish | S3 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 module | Imports from |
|---|---|
contracts, parity, most adapters | recohut_kit.json (JsonValue, canonical_json, …) |
collection_search | recohut_kit.retrieval_calibration |
scaling | recohut_kit.latency, recohut_kit.retrieval_benchmark |
rerank_sentence_transformers | recohut_kit.inspection, recohut_kit.json, recohut_kit.knowledge |
pinecone_ingestion | recohut_kit.production.retry, recohut_kit.storage.sqlite_tx |
bedrock_knowledge_base, bedrock_kb_publish | recohut_kit.providers.receipts; publish also uses recohut_kit.knowledge, recohut_kit.objects.s3 |
pinecone, weaviate, recorded, parity, reconcile, distance | sibling 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.queryacceptsmetadata_filterobjects defined by each backend.ScoreSemanticsmust agree with the kind string; mismatches raise at construction time. - Identifier batches.
require_id_sequenceand adapters that call it reject passing a single string where a sequence of ids is expected. - SQLite float32.
pack_vectorrefuses vectors whose float32 Euclidean norm is outside 1e-15..1e15, the range where float32 cosine would underflow or overflow.SQLiteVectorIndexscores cosine similarity (higher is better), which differs fromPgVectorIndexcosine distance semantics documented insqlite.py. - Exact local scan. Default SQLite ranking scans every row matching the filter. NumPy is used when importable, pure Python otherwise;
use_sqlite_vec=Trueopts 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 oncreate_collection, raiseControlPlaneRefused;WeaviateIndex.create_collectioncreates the class. - Recorded lane.
recorded_clientnever hits the network; parity latency measures adapter plus stand-in, not a hosted service (paritymodule docstring). - Cross-backend comparison.
parity_reportchecks recall@k and score monotonicity in each backend’s native direction; it does not compare raw scores across backends. - Embeddings modules.
embeddings_sentence_transformersdoes not importsentence_transformersat module import; you preload the model.BedrockEmbeddingsandOpenAIEmbeddingsrequire explicit model and client;BedrockEmbeddingsalso requires a positivemax_response_bytes. Titan schema only unless you useunwrap(). - Bedrock KB partial index.
BedrockKnowledgeBasesupports text-orientedquery; collection write paths are unsupported by design. - LEANN build policy.
LeannRetriever.buildrefuses remote embedding modes unless allowed and rejects duplicate passage ids (asserted in tests). - Scaling estimates.
scaling.plan_contextand 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