Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(embeddings): bound OpenAI embeddings request batch via configurable chunk_size (#5144)

Ehsanfc7ea75b84cd
diff --git a/changelog.d/+openai-embeddings-chunk-size.bugfix.md b/changelog.d/+openai-embeddings-chunk-size.bugfix.md
new file mode 100644
index 0000000000..9da13780d4
--- /dev/null
+++ b/changelog.d/+openai-embeddings-chunk-size.bugfix.md
@@ -0,0 +1 @@
+OpenAI embeddings now honor a configurable `embeddings.openai.chunk_size`, the maximum number of chunks packed into one `/v1/embeddings` request. `create_embeddings` previously never set it, so LangChain's default of 1000 applied and `embed_documents` sent every chunk of a document in a single request with no bound on the batch's cumulative tokens. Against an OpenAI-compatible local server (LM Studio, vLLM, llama.cpp) with a small context window, that request returns a 400 `exceed_context_size` once the combined chunk tokens exceed `n_ctx`, which the `check_embedding_ctx_length=False` path used for non-OpenAI hosts does not prevent (it only splits an individual over-long input, not the number of inputs). Setting the new option lets a small-context endpoint bound each request below its `n_ctx`; leaving it blank keeps LangChain's default, which suits the OpenAI cloud. Fixes #4966.
diff --git a/src/local_deep_research/defaults/settings_openai_embeddings.json b/src/local_deep_research/defaults/settings_openai_embeddings.json
index 058cec38b2..de90298cb8 100644
--- a/src/local_deep_research/defaults/settings_openai_embeddings.json
+++ b/src/local_deep_research/defaults/settings_openai_embeddings.json
@@ -54,5 +54,19 @@
"ui_element": "number",
"value": null,
"visible": true
+ },
+ "embeddings.openai.chunk_size": {
+ "category": "embeddings",
+ "description": "Maximum number of text chunks sent in a single embeddings request. embed_documents batches up to this many inputs per /v1/embeddings request (LangChain's default is 1000) and does not bound the batch's total tokens, so a document that splits into many chunks can overrun a local server's context window (n_ctx) and return a 400 exceed_context_size error. Lower this if indexing a collection fails that way against an OpenAI-compatible local server (LM Studio, vLLM, llama.cpp). Leave blank to keep LangChain's default, which suits the OpenAI cloud.",
+ "editable": true,
+ "max_value": null,
+ "min_value": 1,
+ "name": "OpenAI Embeddings Batch Size",
+ "options": null,
+ "step": 1,
+ "type": "APP",
+ "ui_element": "number",
+ "value": null,
+ "visible": true
}
}
diff --git a/src/local_deep_research/embeddings/providers/implementations/openai.py b/src/local_deep_research/embeddings/providers/implementations/openai.py
index 165ca798e5..e5e2318e43 100644
--- a/src/local_deep_research/embeddings/providers/implementations/openai.py
+++ b/src/local_deep_research/embeddings/providers/implementations/openai.py
@@ -118,6 +118,14 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
settings_snapshot=settings_snapshot,
)
+ chunk_size = kwargs.get("chunk_size")
+ if chunk_size is None:
+ chunk_size = get_setting_from_snapshot(
+ "embeddings.openai.chunk_size",
+ default=None,
+ settings_snapshot=settings_snapshot,
+ )
+
logger.info(f"Creating OpenAIEmbeddings with model={model}")
# Build parameters. Annotated as Dict[str, Any] so the
@@ -149,6 +157,21 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
if dimensions and model.startswith("text-embedding-3"):
params["dimensions"] = int(dimensions)
+ # Cap how many chunks go into one /v1/embeddings request.
+ # embed_documents batches up to chunk_size inputs (LangChain's
+ # default is 1000) into a single request and never bounds the
+ # batch's cumulative token count, so a document that splits into
+ # many chunks is sent as one oversized request. An OpenAI-compatible
+ # local server (LM Studio, vLLM, llama.cpp) then rejects it with a
+ # 400 exceed_context_size once the combined tokens pass its context
+ # window, which the check_embedding_ctx_length guard above does not
+ # prevent (that only splits an individual over-long input, not the
+ # number of inputs). Leaving this unset keeps LangChain's default,
+ # which suits the OpenAI cloud; setting it lets a small-context
+ # endpoint bound each request below its n_ctx.
+ if chunk_size is not None and int(chunk_size) > 0:
+ params["chunk_size"] = int(chunk_size)
+
return OpenAIEmbeddings(**params)
@classmethod
diff --git a/tests/embeddings/test_openai_embeddings.py b/tests/embeddings/test_openai_embeddings.py
index 3198e620ba..d303988996 100644
--- a/tests/embeddings/test_openai_embeddings.py
+++ b/tests/embeddings/test_openai_embeddings.py
@@ -284,6 +284,134 @@ class TestOpenAIEmbeddingsProviderCreateEmbeddings:
call_kwargs = mock_class.call_args[1]
assert "dimensions" not in call_kwargs
+ def test_create_embeddings_with_chunk_size(self):
+ """A configured chunk_size is passed through to OpenAIEmbeddings.
+
+ This caps how many chunks embed_documents packs into a single
+ /v1/embeddings request (see #4966).
+ """
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ mock_embeddings = MagicMock()
+
+ with patch(
+ "local_deep_research.embeddings.providers.implementations.openai.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with patch(
+ "langchain_openai.OpenAIEmbeddings",
+ return_value=mock_embeddings,
+ ) as mock_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ chunk_size=64,
+ )
+
+ call_kwargs = mock_class.call_args[1]
+ assert call_kwargs["chunk_size"] == 64
+
+ def test_create_embeddings_chunk_size_omitted_when_unset(self):
+ """With chunk_size unset, no chunk_size is passed and LangChain's
+ default (1000) is preserved. This keeps behavior unchanged for the
+ OpenAI cloud, which accepts large batches.
+ """
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ mock_embeddings = MagicMock()
+
+ with patch(
+ "local_deep_research.embeddings.providers.implementations.openai.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with patch(
+ "langchain_openai.OpenAIEmbeddings",
+ return_value=mock_embeddings,
+ ) as mock_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ )
+
+ call_kwargs = mock_class.call_args[1]
+ assert "chunk_size" not in call_kwargs
+
+ def test_create_embeddings_non_positive_chunk_size_ignored(self):
+ """A non-positive chunk_size is ignored rather than passed through
+ (LangChain requires a positive batch size)."""
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ mock_embeddings = MagicMock()
+
+ with patch(
+ "local_deep_research.embeddings.providers.implementations.openai.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with patch(
+ "langchain_openai.OpenAIEmbeddings",
+ return_value=mock_embeddings,
+ ) as mock_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ chunk_size=0,
+ )
+
+ call_kwargs = mock_class.call_args[1]
+ assert "chunk_size" not in call_kwargs
+
+ def test_chunk_size_bounds_embedding_request_batch(self):
+ """Behavioral regression for #4966: the configured chunk_size bounds
+ the number of chunks in each embeddings request.
+
+ Drives the real LangChain ``embed_documents`` against a stub client
+ that records the batch size of every request. On a local
+ (non-openai) endpoint ``check_embedding_ctx_length`` is disabled, so
+ ``embed_documents`` batches raw texts in slices of ``chunk_size``.
+ Without the fix the setting is ignored, LangChain's default of 1000
+ applies, and all 50 chunks are sent as one oversized request.
+ """
+ import types
+
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ snapshot = {
+ "embeddings.openai.base_url": "http://localhost:1234/v1",
+ "embeddings.openai.api_key": "",
+ "embeddings.openai.model": "text-embedding-qwen3-embedding-0.6b",
+ "embeddings.openai.dimensions": None,
+ "embeddings.openai.chunk_size": 16,
+ }
+
+ embeddings = OpenAIEmbeddingsProvider.create_embeddings(
+ settings_snapshot=snapshot
+ )
+ # The fix must both set the attribute and, because it is a local
+ # endpoint, leave the ctx-length guard disabled (the batching path
+ # this test exercises).
+ assert embeddings.chunk_size == 16
+ assert embeddings.check_embedding_ctx_length is False
+
+ batch_sizes = []
+
+ def fake_create(input, **kwargs):
+ batch_sizes.append(len(input))
+ return {"data": [{"embedding": [0.0, 0.0]} for _ in input]}
+
+ embeddings.client = types.SimpleNamespace(create=fake_create)
+ embeddings.embed_documents(["chunk"] * 50)
+
+ assert max(batch_sizes) <= 16
+ assert len(batch_sizes) == 4 # ceil(50 / 16)
+
class TestOpenAIEmbeddingsProviderIsAvailable:
"""Tests for OpenAIEmbeddingsProvider.is_available method."""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index b71a124eba..f00d98017b 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -852,6 +852,20 @@
"value": "",
"visible": true
},
+ "embeddings.openai.chunk_size": {
+ "category": "embeddings",
+ "description": "Maximum number of text chunks sent in a single embeddings request. embed_documents batches up to this many inputs per /v1/embeddings request (LangChain's default is 1000) and does not bound the batch's total tokens, so a document that splits into many chunks can overrun a local server's context window (n_ctx) and return a 400 exceed_context_size error. Lower this if indexing a collection fails that way against an OpenAI-compatible local server (LM Studio, vLLM, llama.cpp). Leave blank to keep LangChain's default, which suits the OpenAI cloud.",
+ "editable": true,
+ "max_value": null,
+ "min_value": 1,
+ "name": "OpenAI Embeddings Batch Size",
+ "options": null,
+ "step": 1,
+ "type": "APP",
+ "ui_element": "number",
+ "value": null,
+ "visible": true
+ },
"embeddings.openai.dimensions": {
"category": "embeddings",
"description": "Optional output vector dimensionality. Only applies to OpenAI text-embedding-3 models (which support truncation); ignored for other models including most local servers. Leave blank to use the model's native dimensionality.",