Skip to content

base

langroid/embedding_models/base.py

EmbeddingModel

Bases: ABC

Abstract base class for an embedding model.

clone()

Return a copy of this embedding model suitable for use in cloned agents. Default behaviour attempts to deep-copy the model configuration and instantiate a fresh model of the same type; if that is not possible, the original instance is reused.

Source code in langroid/embedding_models/base.py
def clone(self) -> "EmbeddingModel":
    """
    Return a copy of this embedding model suitable for use in cloned agents.
    Default behaviour attempts to deep-copy the model configuration and
    instantiate a fresh model of the same type; if that is not possible,
    the original instance is reused.
    """
    config = getattr(self, "config", None)
    if config is not None and hasattr(config, "model_copy"):
        try:
            return type(self)(config.model_copy(deep=True))  # type: ignore[call-arg]
        except Exception:
            pass
    return self

similarity(text1, text2)

Compute cosine similarity between two texts.

Source code in langroid/embedding_models/base.py
def similarity(self, text1: str, text2: str) -> float:
    """Compute cosine similarity between two texts."""
    [emb1, emb2] = self.embedding_fn()([text1, text2])
    return float(
        np.array(emb1)
        @ np.array(emb2)
        / (np.linalg.norm(emb1) * np.linalg.norm(emb2))
    )