Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: VoyageAI embeddings integration #2111

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/components/embedders/models/voyageai.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
title: VoyageAI
---

To use VoyageAI embedding models, set the `VOYAGE_API_KEY` environment variable. You can obtain the Voyage API key from the [VoyageAI Dashboard](https://dash.voyageai.com/api-keys).

### Usage

```python
import os
from mem0 import Memory

os.environ["VOYAGE_API_KEY"] = "your_api_key"
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM

config = {
"embedder": {
"provider": "voyageai",
"config": {
"model": "voyage-3"
}
}
}

m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
```

### Config

Here are the parameters available for configuring VoyageAI embedder:

| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `voyage-3` |
| `embedding_dims` | Dimensions of the embedding model | `None`(which uses the [pre-defined default values](https://docs.voyageai.com/docs/embeddings) according to the selected model) |
| `api_key` | The VoyageAI API key | `None` |
1 change: 1 addition & 0 deletions docs/components/embedders/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ See the list of supported embedders below.
<Card title="Gemini" href="/components/embedders/models/gemini"></Card>
<Card title="Vertex AI" href="/components/embedders/models/vertexai"></Card>
<Card title="Together" href="/components/embedders/models/together"></Card>
<Card title="VoyageAI" href="/components/embedders/models/voyageai"></Card>
</CardGroup>

## Usage
Expand Down
11 changes: 10 additions & 1 deletion mem0/embeddings/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@ class EmbedderConfig(BaseModel):
@field_validator("config")
def validate_config(cls, v, values):
provider = values.data.get("provider")
if provider in ["openai", "ollama", "huggingface", "azure_openai", "gemini", "vertexai", "together"]:
if provider in [
"openai",
"ollama",
"huggingface",
"azure_openai",
"gemini",
"vertexai",
"together",
"voyageai",
]:
return v
else:
raise ValueError(f"Unsupported embedding provider: {provider}")
34 changes: 34 additions & 0 deletions mem0/embeddings/voyageai.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os
from typing import Optional

from voyageai import Client

from mem0.configs.embeddings.base import BaseEmbedderConfig
from mem0.embeddings.base import EmbeddingBase


class VoyageAIEmbedding(EmbeddingBase):
def __init__(self, config: Optional[BaseEmbedderConfig] = None):
super().__init__(config)

self.config.model = self.config.model or "voyage-3"
self.config.embedding_dims = self.config.embedding_dims

api_key = self.config.api_key or os.getenv("VOYAGE_API_KEY")
self.client = Client(api_key=api_key)

def embed(self, text):
"""
Get the embedding for the given text using VoyageAI.

Args:
text (str): The text to embed.

Returns:
list: The embedding vector.
"""
return self.client.embed(
texts=[text],
model=self.config.model,
output_dimension=self.config.embedding_dims,
).embeddings[0]
7 changes: 3 additions & 4 deletions mem0/memory/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import json

from mem0.configs.prompts import FACT_RETRIEVAL_PROMPT


Expand All @@ -18,13 +16,14 @@ def parse_messages(messages):
response += f"assistant: {msg['content']}\n"
return response


def format_entities(entities):
if not entities:
return ""

formatted_lines = []
for entity in entities:
simplified = f"{entity['source']} -- {entity['relation'].upper()} -- {entity['destination']}"
formatted_lines.append(simplified)

return "\n".join(formatted_lines)
return "\n".join(formatted_lines)
1 change: 1 addition & 0 deletions mem0/utils/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class EmbedderFactory:
"gemini": "mem0.embeddings.gemini.GoogleGenAIEmbedding",
"vertexai": "mem0.embeddings.vertexai.VertexAIEmbedding",
"together": "mem0.embeddings.together.TogetherEmbedding",
"voyageai": "mem0.embeddings.voyageai.VoyageAIEmbedding",
}

@classmethod
Expand Down
44 changes: 44 additions & 0 deletions tests/embeddings/test_voyageai_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from unittest.mock import Mock, patch

import pytest

from mem0.configs.embeddings.base import BaseEmbedderConfig
from mem0.embeddings.voyageai import VoyageAIEmbedding


@pytest.fixture
def mock_voyageai_client():
with patch("mem0.embeddings.voyageai.Client") as mock_voyageai:
mock_client = Mock()
mock_voyageai.return_value = mock_client
yield mock_client


def test_embed_default_model(mock_voyageai_client):
config = BaseEmbedderConfig()
embedder = VoyageAIEmbedding(config)
mock_response = Mock()
mock_response.embeddings = [[0.1, 0.2, 0.3]]
mock_voyageai_client.embed.return_value = mock_response

result = embedder.embed("Default embedder")

mock_voyageai_client.embed.assert_called_once_with(
texts=["Default embedder"], model="voyage-3", output_dimension=None
)
assert result == [0.1, 0.2, 0.3]


def test_embed_custom_model(mock_voyageai_client):
config = BaseEmbedderConfig(model="voyage-3-large", embedding_dims=2048)
embedder = VoyageAIEmbedding(config)
mock_response = Mock()
mock_response.embeddings = [[0.4, 0.5, 0.6]]
mock_voyageai_client.embed.return_value = mock_response

result = embedder.embed("Custom embedder")

mock_voyageai_client.embed.assert_called_once_with(
texts=["Custom embedder"], model="voyage-3-large", output_dimension=2048
)
assert result == [0.4, 0.5, 0.6]