Skip to content
Merged
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
5 changes: 4 additions & 1 deletion mem0/embeddings/huggingface.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def __init__(self, config: Optional[BaseEmbedderConfig] = None):

if config.huggingface_base_url:
self.client = OpenAI(base_url=config.huggingface_base_url)
self.config.model = self.config.model or "tei"
else:
self.config.model = self.config.model or "multi-qa-MiniLM-L6-cos-v1"

Expand All @@ -36,6 +37,8 @@ def embed(self, text, memory_action: Optional[Literal["add", "search", "update"]
list: The embedding vector.
"""
if self.config.huggingface_base_url:
return self.client.embeddings.create(input=text, model="tei").data[0].embedding
return self.client.embeddings.create(
input=text, model=self.config.model, **self.config.model_kwargs
).data[0].embedding
else:
return self.model.encode(text, convert_to_numpy=True).tolist()
31 changes: 31 additions & 0 deletions tests/embeddings/test_huggingface_embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,34 @@ def test_embed_with_custom_embedding_dims(mock_sentence_transformer):
assert embedder.config.embedding_dims == 768

assert result == [1.0, 1.1, 1.2]


def test_embed_with_huggingface_base_url():
config = BaseEmbedderConfig(
huggingface_base_url="http://localhost:8080",
model="my-custom-model",
model_kwargs={"truncate": True},
)
with patch("mem0.embeddings.huggingface.OpenAI") as mock_openai:
mock_client = Mock()
mock_openai.return_value = mock_client

# Create a mock for the response object and its attributes
mock_embedding_response = Mock()
mock_embedding_response.embedding = [0.1, 0.2, 0.3]

mock_create_response = Mock()
mock_create_response.data = [mock_embedding_response]

mock_client.embeddings.create.return_value = mock_create_response

embedder = HuggingFaceEmbedding(config)
result = embedder.embed("Hello from custom endpoint")

mock_openai.assert_called_once_with(base_url="http://localhost:8080")
mock_client.embeddings.create.assert_called_once_with(
input="Hello from custom endpoint",
model="my-custom-model",
truncate=True,
)
assert result == [0.1, 0.2, 0.3]