Skip to content

Fix ollama embedder #245

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

Merged
merged 2 commits into from
Jan 15, 2025
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Next

### Fixed

- Fix a bug where the `OllamaEmbedder` would return a `list[list[float]]` instead of the expected `list[float]`.

## 1.4.1

### Fixed
Expand Down
6 changes: 4 additions & 2 deletions src/neo4j_graphrag/embeddings/ollama.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,12 @@ def embed_query(self, text: str, **kwargs: Any) -> list[float]:
**kwargs,
)

if embeddings_response is None or embeddings_response.embeddings is None:
if embeddings_response is None or not embeddings_response.embeddings:
raise EmbeddingsGenerationError("Failed to retrieve embeddings.")

embedding = embeddings_response.embeddings
embeddings = embeddings_response.embeddings
# client always returns a sequence of sequences
embedding = embeddings[0]
if not isinstance(embedding, list):
raise EmbeddingsGenerationError("Embedding is not a list of floats.")

Expand Down
13 changes: 12 additions & 1 deletion tests/unit/embeddings/test_ollama_embedder.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import pytest
from neo4j_graphrag.embeddings.ollama import OllamaEmbeddings
from neo4j_graphrag.exceptions import EmbeddingsGenerationError


@patch("builtins.__import__", side_effect=ImportError)
Expand All @@ -27,9 +28,19 @@ def test_ollama_embedder_missing_dependency(mock_import: Mock) -> None:
@patch("builtins.__import__")
def test_ollama_embedder_happy_path(mock_import: Mock) -> None:
mock_import.return_value.Client.return_value.embed.return_value = MagicMock(
embeddings=[1.0, 2.0],
embeddings=[[1.0, 2.0]],
)
embedder = OllamaEmbeddings(model="test")
res = embedder.embed_query("my text")
assert isinstance(res, list)
assert res == [1.0, 2.0]


@patch("builtins.__import__")
def test_ollama_embedder_empty_list(mock_import: Mock) -> None:
mock_import.return_value.Client.return_value.embed.return_value = MagicMock(
embeddings=[],
)
embedder = OllamaEmbeddings(model="test")
with pytest.raises(EmbeddingsGenerationError):
embedder.embed_query("my text")
Loading