Skip to content

fix(py/openai): split large embed batches into 2048-input requests - #7079

Closed
pcbeingused33 wants to merge 1 commit into
genkit-ai:mainfrom
pcbeingused33:fix/openai-embedder-batching
Closed

pcbeingused33 wants to merge 1 commit into
genkit-ai:mainfrom
pcbeingused33:fix/openai-embedder-batching

Conversation

@pcbeingused33

Copy link
Copy Markdown

The OpenAI embedder in genkit-openai passed every document to a single embeddings.create call. The OpenAI embeddings endpoint accepts at most 2048 inputs per request, so embedding a larger batch fails. The Google GenAI embedder already splits requests by a batch size.

Fix: send the inputs in chunks of 2048 and concatenate the returned embeddings in order. The dimensions and encodingFormat options go with every chunk. The four-way if/elif over those options is replaced by a kwargs dict so the loop does not repeat it.

Test: test_embedder_splits_large_batches_into_chunks embeds 5000 documents and expects calls of 2048, 2048 and 904 inputs, the option on each call, and the embeddings back in order. It fails before the change and passes after; the other 45 tests in openai_plugin_test.py still pass.

The JS compat-oai embedder has the same shape and is not touched here.


Disclosure: this change was prepared with AI assistance (Claude Code).

The OpenAI embedder sent every document in one embeddings.create call,
which the API rejects above 2048 inputs. Send the inputs in chunks of
2048 and concatenate the results in order.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces batching for OpenAI embedding requests, splitting inputs into chunks of at most 2048 to comply with the API limit, and adds a unit test to verify this behavior. The reviewer suggested optimizing performance by executing these chunked requests concurrently using asyncio.gather instead of sequentially.

Comment on lines 615 to +624
client = self._embed_client()
data: list[Any] = []
try:
if dimensions is not None and encoding_format is not None:
response = await client.embeddings.create(
model=name,
input=texts,
dimensions=dimensions,
encoding_format=encoding_format,
)
elif dimensions is not None:
response = await client.embeddings.create(
model=name,
input=texts,
dimensions=dimensions,
)
elif encoding_format is not None:
response = await client.embeddings.create(
model=name,
input=texts,
encoding_format=encoding_format,
)
else:
for start in range(0, len(texts), _MAX_EMBED_INPUTS):
response = await client.embeddings.create(
model=name,
input=texts,
input=texts[start : start + _MAX_EMBED_INPUTS],
**extra,
)
data.extend(response.data)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since the embedding requests for different chunks are completely independent, we can run them concurrently using asyncio.gather instead of sequentially in a loop. This can significantly reduce the total latency for large batches of documents.

            import asyncio

            client = self._embed_client()
            data: list[Any] = []
            try:
                chunks = [texts[i : i + _MAX_EMBED_INPUTS] for i in range(0, len(texts), _MAX_EMBED_INPUTS)]
                tasks = [
                    client.embeddings.create(
                        model=name,
                        input=chunk,
                        **extra,
                    )
                    for chunk in chunks
                ]
                responses = await asyncio.gather(*tasks)
                for response in responses:
                    data.extend(response.data)

@MichaelDoyle

Copy link
Copy Markdown
Contributor

Hi @pcbeingused333 — heads up that Genkit Python SDK development has moved to https://github.com/genkit-ai/genkit-python! Could you re-open this PR over there (file paths map 1:1 after stripping the leading py/ prefix), and link/close this PR once moved? cc @huangjeff5

@pcbeingused33

Copy link
Copy Markdown
Author

Moved to genkit-ai/genkit-python#141 as requested. Closing this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants