Implementation:Vibrantlabsai Ragas BaseRagasEmbeddings
| Knowledge Sources | |
|---|---|
| Domains | Embeddings, NLP, LLM Evaluation |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
This module defines the abstract base classes and factory functions for all embedding implementations in the Ragas evaluation toolkit, providing a unified interface for embedding text via multiple providers.
Description
The base.py module is the foundation of the Ragas embeddings subsystem. It contains two abstract base classes:
- BaseRagasEmbedding -- The modern abstract base class (ABC) that defines the standard interface for embedding providers. It declares abstract methods embed_text and aembed_text for single-text embedding (sync and async), and provides default implementations of embed_texts and aembed_texts for batch operations. It supports optional caching via a CacheInterface backend and includes a _from_factory classmethod for provider auto-discovery.
- BaseRagasEmbeddings -- The legacy abstract base class that extends LangChain's Embeddings class. It adds RunConfig-based retry logic, optional caching, and defines the embed_text and embed_texts convenience methods that delegate to the LangChain-style embed_documents and aembed_documents abstract methods.
The module also provides concrete wrapper classes:
- LangchainEmbeddingsWrapper -- Wraps any LangChain Embeddings instance into the Ragas interface (deprecated in favor of modern providers).
- LlamaIndexEmbeddingsWrapper -- Wraps any LlamaIndex BaseEmbedding instance into the Ragas interface (deprecated in favor of modern providers).
- HuggingfaceEmbeddings -- A pydantic dataclass that loads HuggingFace SentenceTransformer or CrossEncoder models for local embedding generation.
Finally, the embedding_factory function serves as a unified entry point that creates embedding instances for any supported provider (OpenAI, Google, HuggingFace, LiteLLM). It supports both a legacy interface (backward-compatible, returns LangchainEmbeddingsWrapper) and a modern interface (returns BaseRagasEmbedding subclasses). The _infer_embedding_provider_from_llm helper automatically selects a matching embedding provider based on an LLM class name.
Usage
Import this module when you need to:
- Create an embedding instance via the embedding_factory function
- Subclass BaseRagasEmbedding to implement a custom embedding provider
- Wrap existing LangChain or LlamaIndex embeddings for use with Ragas metrics
- Use HuggingFace sentence-transformers for local embedding generation
Code Reference
Source Location
- Repository: Vibrantlabsai_Ragas
- File: src/ragas/embeddings/base.py
Signature
class BaseRagasEmbedding(ABC):
def __init__(self, cache: t.Optional[CacheInterface] = None): ...
@abstractmethod
def embed_text(self, text: str, **kwargs: t.Any) -> t.List[float]: ...
@abstractmethod
async def aembed_text(self, text: str, **kwargs: t.Any) -> t.List[float]: ...
def embed_texts(self, texts: t.List[str], **kwargs: t.Any) -> t.List[t.List[float]]: ...
async def aembed_texts(self, texts: t.List[str], **kwargs: t.Any) -> t.List[t.List[float]]: ...
@classmethod
def _from_factory(cls, model=None, client=None, **kwargs) -> "BaseRagasEmbedding": ...
class BaseRagasEmbeddings(Embeddings, ABC):
run_config: RunConfig
cache: t.Optional[CacheInterface] = None
def __init__(self, cache: t.Optional[CacheInterface] = None): ...
async def embed_text(self, text: str, is_async=True) -> t.List[float]: ...
async def embed_texts(self, texts: t.List[str], is_async: bool = True) -> t.List[t.List[float]]: ...
@abstractmethod
async def aembed_query(self, text: str) -> t.List[float]: ...
@abstractmethod
async def aembed_documents(self, texts: t.List[str]) -> t.List[t.List[float]]: ...
def set_run_config(self, run_config: RunConfig): ...
class LangchainEmbeddingsWrapper(BaseRagasEmbeddings):
def __init__(self, embeddings: Embeddings, run_config=None, cache=None): ...
class LlamaIndexEmbeddingsWrapper(BaseRagasEmbeddings):
def __init__(self, embeddings: BaseEmbedding, run_config=None, cache=None): ...
@dataclass
class HuggingfaceEmbeddings(BaseRagasEmbeddings):
model_name: str = DEFAULT_MODEL_NAME
cache_folder: t.Optional[str] = None
model_kwargs: t.Dict[str, t.Any] = field(default_factory=dict)
encode_kwargs: t.Dict[str, t.Any] = field(default_factory=dict)
cache: t.Optional[CacheInterface] = None
def embedding_factory(
provider: str = "openai",
model: t.Optional[str] = None,
run_config: t.Optional[RunConfig] = None,
client: t.Optional[t.Any] = None,
interface: str = "auto",
base_url: t.Optional[str] = None,
cache: t.Optional[CacheInterface] = None,
**kwargs: t.Any,
) -> t.Union[BaseRagasEmbeddings, BaseRagasEmbedding]: ...
Import
from ragas.embeddings.base import BaseRagasEmbedding, BaseRagasEmbeddings
from ragas.embeddings.base import LangchainEmbeddingsWrapper, LlamaIndexEmbeddingsWrapper
from ragas.embeddings.base import HuggingfaceEmbeddings
from ragas.embeddings.base import embedding_factory
I/O Contract
embedding_factory Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| provider | str | No (default "openai") | Provider name or provider/model string (e.g., "openai", "openai/text-embedding-3-small", "google", "huggingface", "litellm") |
| model | str or None | No | The embedding model name; uses provider defaults if not provided |
| run_config | RunConfig or None | No | Configuration for retry logic and timeouts (legacy interface only) |
| client | Any or None | No | Pre-initialized client for modern providers; when provided, forces modern interface |
| interface | str | No (default "auto") | Interface type: "legacy", "modern", or "auto" (auto-detects based on parameters) |
| base_url | str or None | No | Base URL for the API endpoint |
| cache | CacheInterface or None | No | Optional cache backend (e.g., DiskCacheBackend) for caching embeddings across runs |
| **kwargs | Any | No | Additional provider-specific arguments |
embedding_factory Outputs
| Name | Type | Description |
|---|---|---|
| return | BaseRagasEmbeddings or BaseRagasEmbedding | An embedding instance; legacy calls return BaseRagasEmbeddings, modern calls return BaseRagasEmbedding |
BaseRagasEmbedding.embed_text Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| text | str | Yes | The text string to embed |
| **kwargs | Any | No | Additional arguments for the embedding call |
BaseRagasEmbedding.embed_text Outputs
| Name | Type | Description |
|---|---|---|
| return | List[float] | A list of floats representing the embedding vector |
Usage Examples
Modern Interface (Recommended)
from ragas.embeddings.base import embedding_factory
# OpenAI with client
import openai
client = openai.OpenAI()
embedder = embedding_factory("openai", model="text-embedding-3-small", client=client)
# HuggingFace (local)
embedder = embedding_factory("huggingface", model="sentence-transformers/all-MiniLM-L6-v2")
# Google with Vertex AI client
embedder = embedding_factory("google", client=vertex_client, project_id="my-project")
With Caching
from ragas.embeddings.base import embedding_factory
from ragas.cache import DiskCacheBackend
cache = DiskCacheBackend()
embedder = embedding_factory("openai", client=openai_client, cache=cache)
result = embedder.embed_text("Hello world")
HuggingFace Local Embeddings
from ragas.embeddings.base import HuggingfaceEmbeddings
embeddings = HuggingfaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")
query_embedding = embeddings.embed_query("What is the capital of France?")
doc_embeddings = embeddings.embed_documents(["Paris is in France.", "London is in the UK."])
Legacy Interface (Deprecated)
from ragas.embeddings.base import embedding_factory
# Backward-compatible call (auto-detects legacy mode)
embedder = embedding_factory()
embedder = embedding_factory("text-embedding-ada-002")
Related Pages
- Vibrantlabsai_Ragas_GoogleEmbeddings -- Google embedding provider built on BaseRagasEmbedding
- ragas.cache.CacheInterface -- Caching interface used for embedding result caching
- ragas.run_config.RunConfig -- Run configuration for retry and timeout management
- langchain_core.embeddings.Embeddings -- LangChain base class extended by BaseRagasEmbeddings