src.dackar.similarity.OllamaEmbedder¶
Ollama-backed dense-vector text embedder.
A stateless (except for its cache) embedder served by a locally running Ollama instance. The same instance can be shared across callers.
Embedding model notes:
nomic-embed-text:latest— fast, 274 MB. Good general-purpose default.mxbai-embed-large:latest— stronger retrieval ranking, ~2.4x larger (669 MB).
Caching¶
Two-level cache:
In-memory — a plain
dictmapping text to embedding, living for the lifetime of the embedder instance. Avoids redundant API calls within a single run.Persistent JSON file (optional) — loaded at construction and saved on demand via
save_cache(), so embeddings survive across restarts.
Graceful degradation¶
If the Ollama server is unreachable (URLError, TimeoutError) the
embedder logs a warning and returns a single-element vector [0.0] so the
caller can fall back (e.g. to a lexical similarity measure).
Only the standard library is required.
Attributes¶
Classes¶
Dense-vector text embedder backed by a local Ollama server. |
Functions¶
|
Return the cosine similarity between two vectors. |
Module Contents¶
- class src.dackar.similarity.OllamaEmbedder.OllamaEmbedder(model='nomic-embed-text:latest', base_url='http://localhost:11434', cache_path=None, timeout=30)[source]¶
Dense-vector text embedder backed by a local Ollama server.
- Parameters:
model (str) – Ollama model name, e.g.
"nomic-embed-text:latest"or"mxbai-embed-large:latest".base_url (str) – Base URL of the Ollama HTTP API. Default
"http://localhost:11434".cache_path (str | None) – Optional path to a JSON file used as a persistent cache. If the file already exists its contents are loaded on construction. Call
save_cache()to flush in-memory additions back to disk.timeout (int) – HTTP request timeout in seconds. Default 30.
- encode(text)[source]¶
Return the dense embedding vector for text.
Successful results are cached in memory. Returns the
[0.0]fallback singleton if Ollama is unavailable (logged at WARNING level); a fallback is never cached, so a later call retries the server.- Parameters:
text (str)
- Return type:
list[float]
- encode_batch(texts)[source]¶
Encode multiple texts, exploiting the in-memory cache.
- Parameters:
texts (list[str])
- Return type:
list[list[float]]
- cache_size()[source]¶
Return the number of successfully-embedded texts held in memory.
- Return type:
int
- src.dackar.similarity.OllamaEmbedder.cosine_similarity(a, b)[source]¶
Return the cosine similarity between two vectors.
Returns 0.0 if either vector is the fallback
[0.0]singleton, if the vectors differ in length, or if either norm is zero.- Parameters:
a (list[float])
b (list[float])
- Return type:
float