mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
fix(python): skip OpenAI embedding requests when no valid text remains (#5195)
## Summary Follows up on #4005, which handled mixed batches in `OpenAIEmbeddings.generate_embeddings`. On `main`, when the input batch is empty (`[]`) or filtering leaves no valid texts (such as `[None, ""]`), `generate_embeddings` still imports the `openai` SDK and calls `embeddings.create(input=[], ...)`. - Return `[None] * len(texts)` early in `python/python/lancedb/embeddings/openai.py` when no valid texts remain (`[]` for empty input, one `None` per item when all inputs are filtered), before importing the `openai` SDK or sending a request. - Add regression tests in `python/python/tests/test_embeddings.py` covering empty batches, all-filtered batches, and native-backed `table.add(..., on_bad_vectors="null")` verifying rows are kept with null vectors and no OpenAI request is made. ## Attribution Successor to #3152. The early return and nullable ingestion test were originally contributed by @saudademjj in #3152. ## Verification - 3 new regression tests failed before the fix (observing `embeddings.create(input=[], ...)`) and passed after. - Related embedding test suite: `148 passed, 1 skipped, 9 deselected` (mocked client only; no live OpenAI API calls). - Ruff check and format checks are clean for the changed `python/` tree (scoped to `python/` only). Co-authored-by: saudademjj <128795969+saudademjj@users.noreply.github.com> Co-authored-by: saudademjj <128795969+saudademjj@users.noreply.github.com>
This commit is contained in:
@@ -99,8 +99,6 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
||||
texts: list[str] or np.ndarray (of str)
|
||||
The texts to embed
|
||||
"""
|
||||
openai = attempt_import_or_raise("openai")
|
||||
|
||||
valid_texts = []
|
||||
valid_indices = []
|
||||
for idx, text in enumerate(texts):
|
||||
@@ -108,6 +106,11 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
||||
valid_texts.append(text)
|
||||
valid_indices.append(idx)
|
||||
|
||||
if not valid_texts:
|
||||
return [None] * len(texts)
|
||||
|
||||
openai = attempt_import_or_raise("openai")
|
||||
|
||||
# TODO retry, rate limit, token limit
|
||||
def embed_batch(texts_batch, indices_batch):
|
||||
kwargs = {
|
||||
|
||||
@@ -1107,6 +1107,47 @@ def test_openai_bad_request_partial_batch_recovery():
|
||||
assert embeddings[1] is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_openai_client(monkeypatch):
|
||||
client = MagicMock()
|
||||
client.embeddings.create.return_value.data = []
|
||||
monkeypatch.setattr(
|
||||
"lancedb.embeddings.openai.attempt_import_or_raise", MagicMock()
|
||||
)
|
||||
monkeypatch.setattr(get_registry().get("openai"), "_openai_client", client)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("texts", "expected"),
|
||||
[([], []), ([None, ""], [None, None])],
|
||||
ids=["empty-batch", "all-inputs-filtered"],
|
||||
)
|
||||
def test_openai_skips_batches_without_valid_text(mock_openai_client, texts, expected):
|
||||
model = get_registry().get("openai").create()
|
||||
|
||||
assert model.compute_source_embeddings(texts) == expected
|
||||
mock_openai_client.embeddings.create.assert_not_called()
|
||||
|
||||
|
||||
def test_openai_add_all_invalid_texts_as_null_vectors(mock_openai_client, tmp_path):
|
||||
model = get_registry().get("openai").create(name="text-embedding-3-small", dim=2)
|
||||
|
||||
class TextModel(LanceModel):
|
||||
text: Optional[str] = model.SourceField()
|
||||
vector: Optional[Vector(model.ndims())] = model.VectorField()
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("words", schema=TextModel)
|
||||
table.add([{"text": None}, {"text": ""}], on_bad_vectors="null")
|
||||
|
||||
assert table.to_arrow().to_pylist() == [
|
||||
{"text": None, "vector": None},
|
||||
{"text": "", "vector": None},
|
||||
]
|
||||
mock_openai_client.embeddings.create.assert_not_called()
|
||||
|
||||
|
||||
def test_ollama_embeddings_pickle():
|
||||
"""OllamaEmbeddings must pickle even after the cached client is created."""
|
||||
registry = get_registry()
|
||||
|
||||
Reference in New Issue
Block a user