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: 3 additions & 2 deletions openevolve/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ def get_embedding(self, code: Union[str, List[str]]) -> Union[List[float], List[
of strings.

Returns:
list: Embedding vector for a string, or one vector per batch input.
list: Embedding vector for a string, or one vector per batch input
in input order.
On failure, return an empty vector for each input.
"""
if isinstance(code, str):
Expand All @@ -106,7 +107,7 @@ def get_embedding(self, code: Union[str, List[str]]) -> Union[List[float], List[
if single_code:
return response.data[0].embedding
else:
return [d.embedding for d in response.data]
return [d.embedding for d in sorted(response.data, key=lambda d: d.index)]
except Exception as e:
logger.info(f"Error getting embedding: {e}")
if single_code:
Expand Down
26 changes: 24 additions & 2 deletions tests/test_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

from openai.types import CreateEmbeddingResponse

from openevolve.embedding import EmbeddingClient


Expand Down Expand Up @@ -56,8 +58,8 @@ def test_get_embedding_returns_batch_embeddings(self):
client.client = MagicMock()
client.client.embeddings.create.return_value = SimpleNamespace(
data=[
SimpleNamespace(embedding=[0.1, 0.2]),
SimpleNamespace(embedding=[0.3, 0.4]),
SimpleNamespace(index=0, embedding=[0.1, 0.2]),
SimpleNamespace(index=1, embedding=[0.3, 0.4]),
]
)

Expand All @@ -70,6 +72,26 @@ def test_get_embedding_returns_batch_embeddings(self):
encoding_format="float",
)

def test_batch_embeddings_follow_input_indices(self):
client = EmbeddingClient.__new__(EmbeddingClient)
client.model = "text-embedding-3-small"
client.client = MagicMock()
client.client.embeddings.create.return_value = CreateEmbeddingResponse(
object="list",
data=[
{"object": "embedding", "index": 2, "embedding": [0.0, 0.0, 1.0]},
{"object": "embedding", "index": 0, "embedding": [1.0, 0.0, 0.0]},
{"object": "embedding", "index": 1, "embedding": [0.0, 1.0, 0.0]},
],
model=client.model,
usage={"prompt_tokens": 3, "total_tokens": 3},
)

self.assertEqual(
client.get_embedding(["first", "second", "third"]),
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
)

def test_single_request_failure_returns_empty_vector_and_can_recover(self):
client = EmbeddingClient.__new__(EmbeddingClient)
client.model = "text-embedding-3-small"
Expand Down
Loading