GeminiEmbedder
On this page
embeddings.gemini_embedder.GeminiEmbedder(BaseEmbedder) — Google Gemini Embeddings API client, using the new google-genai SDK.
[!WARNING] SDK choice matters This class imports
from google import genai— the new SDK. It explicitly is not compatible with the older, deprecatedgoogle-generativeaipackage; if that's the one installed, theImportErrormessage raised here says so directly.
Purpose
Wraps client.models.embed_content() with task-type support (RETRIEVAL_QUERY, RETRIEVAL_DOCUMENT, SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING), Matryoshka-style output-dimension reduction (output_dimensionality), retry logic, and usage tracking.
Constructor
GeminiEmbedder(
model_name: str = "gemini-embedding-001",
api_key: Optional[str] = None,
task_type: Optional[str] = None,
output_dimensionality: Optional[int] = None,
device: Optional[str] = None,
normalize_embeddings: bool = True,
batch_size: int = 50,
max_length: Optional[int] = None,
cache_embeddings: bool = True,
show_progress: bool = False,
timeout: int = 60,
max_retries: int = 3,
retry_delay: float = 2.0,
track_usage: bool = True,
**kwargs,
)
Parameters
MODEL_SPECS (class attribute)
TASK_TYPES (class attribute)
RETRIEVAL_QUERY, RETRIEVAL_DOCUMENT, SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING — each with Arabic/English descriptions and a use-case string. Duplicated at module scope in embeddings/__init__.py as __task_types_gemini__.
Raises
ValueErrorif no API key is resolvable.ImportErrorifgoogle-genaiisn't installed (with an explicit warning about the deprecatedgoogle-generativeaipackage).ValueErrorfrom_validate_api_key()if the API responds with an invalid-key or model-not-found error (other errors during validation are only logged as warnings, not raised).
encode()
encode(
texts: Union[str, List[str]],
show_progress_bar: bool = False,
convert_to_numpy: bool = True,
task_type: Optional[str] = None,
batch_size: Optional[int] = None,
**kwargs,
) -> np.ndarray
Behavior
- If
task_typeis passed, it temporarily overridesself.task_typefor the duration of the call (restored in afinallyblock). - Wraps single string in a list; raises
ValueErrorif empty after filtering blank entries. - Iterates in
batch_size-sized chunks; per text, checks the cache using a key that includes the activetask_typeandoutput_dimensionality(so the same text cached under different task types produces separate cache entries — correctly avoiding cross-task-type cache collisions). - Non-cached texts go through
_process_batch(), which builds atypes.EmbedContentConfig(iftask_typeoroutput_dimensionalityis set) and callsclient.models.embed_content(). Retries on rate-limit (429/quota) and timeout errors with exponential backoff; otherAPIErrors are not retried. - Validates the returned embedding count matches input count (raises
ValueErroron mismatch) and warns (does not raise) on a dimension mismatch against the expected dimension. - Stacks batches, L2-normalizes if
normalize_embeddings=True, updates stats.
Returns
np.ndarray of shape (n, embedding_dim) — always 2D, no single-string unwrap.
Raises
ValueErrorfor empty input or an embedding-count mismatch from the API.RuntimeErrorif all retries in_process_batchare exhausted.- Re-raises non-retryable
APIErrors and any other unexpected exception.
Diagnostics
get_usage_stats() -> Dict[str, Any], clear_cache(), get_model_info()
Standard introspection; get_model_info() includes the full model_spec, current task_type, and (if tracking) GeminiUsageStats.get_summary().
GeminiUsageStats (dataclass)
Fields: total_requests, total_texts, total_characters, start_time, errors, cache_hits. .add_request(text_count, char_count) and .add_error() mutate counters; .get_summary() derives avg_texts_per_request, avg_chars_per_text, and success_rate.
Context manager
__enter__ returns self; __exit__ logs a session summary (requests, texts, characters, elapsed time, success rate) if track_usage=True.
Examples
from embeddings import GeminiEmbedder
embedder = zerda.GeminiEmbedder(api_key="your-key", task_type="RETRIEVAL_DOCUMENT")
vectors = embedder.encode(["first document", "second document"])
# Dimension reduction via MRL
embedder = GeminiEmbedder(api_key="your-key", output_dimensionality=768)
# Overriding task type per-call without changing the instance default
query_vec = embedder.encode("what is the capital of Egypt?", task_type="RETRIEVAL_QUERY")
Related APIs
- BaseEmbedder — parent class
- OpenAIEmbedder, MistralEmbedder — sibling hosted-API embedders