diff --git a/openevolve/embedding.py b/openevolve/embedding.py index 497d19fe0..b7e494de2 100644 --- a/openevolve/embedding.py +++ b/openevolve/embedding.py @@ -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): @@ -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: diff --git a/tests/test_embedding.py b/tests/test_embedding.py index 952553be1..57f5cee6c 100644 --- a/tests/test_embedding.py +++ b/tests/test_embedding.py @@ -3,6 +3,8 @@ from types import SimpleNamespace from unittest.mock import MagicMock, patch +from openai.types import CreateEmbeddingResponse + from openevolve.embedding import EmbeddingClient @@ -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]), ] ) @@ -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"