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): expose Ollama num_ctx so indexing fits the model window (#3870) (#3958)

LearningCircuit49c1ec0753a5
diff --git a/changelog.d/3870.bugfix.md b/changelog.d/3870.bugfix.md
new file mode 100644
index 0000000000..d62f04b357
--- /dev/null
+++ b/changelog.d/3870.bugfix.md
@@ -0,0 +1 @@
+Fix Ollama embedding indexing aborting with `"input length exceeds the context length"` (HTTP 500) by exposing a configurable `embeddings.ollama.num_ctx` setting. The new field appears on the embedding settings page when the Ollama provider is selected and ships with a default of 8192 tokens, which covers chunk sizes up to ~5000 characters for `nomic-embed-text`, `mxbai-embed-large`, `bge-m3`, and `qwen3-embedding`.
diff --git a/src/local_deep_research/defaults/settings_ollama_embeddings.json b/src/local_deep_research/defaults/settings_ollama_embeddings.json
index ff17b865b3..a8281b79c1 100644
--- a/src/local_deep_research/defaults/settings_ollama_embeddings.json
+++ b/src/local_deep_research/defaults/settings_ollama_embeddings.json
@@ -12,5 +12,19 @@
"ui_element": "text",
"value": "http://localhost:11434",
"visible": true
+ },
+ "embeddings.ollama.num_ctx": {
+ "category": "embeddings",
+ "description": "Context window size (in tokens) used when generating Ollama embeddings. Must be at least as large as the longest chunk after tokenization; otherwise Ollama returns 'input length exceeds the context length' (HTTP 500) and indexing fails. The default of 8192 covers chunk sizes up to ~5000 characters for most models. Increase for very large chunks; decrease to save VRAM. qwen3-embedding supports up to 32768; nomic-embed-text supports 8192.",
+ "editable": true,
+ "max_value": 131072.0,
+ "min_value": 512.0,
+ "name": "Ollama Embeddings Context Window",
+ "options": null,
+ "step": 512.0,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 8192,
+ "visible": true
}
}
diff --git a/src/local_deep_research/embeddings/providers/implementations/ollama.py b/src/local_deep_research/embeddings/providers/implementations/ollama.py
index 83839df7d2..a2e42abefd 100644
--- a/src/local_deep_research/embeddings/providers/implementations/ollama.py
+++ b/src/local_deep_research/embeddings/providers/implementations/ollama.py
@@ -57,15 +57,30 @@ class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
if base_url is None:
base_url = get_ollama_base_url(settings_snapshot)
- logger.info(
- f"Creating OllamaEmbeddings with model={model}, base_url={base_url}"
+ # Without an explicit num_ctx, Ollama uses the model's modelfile
+ # default (often 2048). Inputs longer than that return HTTP 500
+ # ("input length exceeds the context length") rather than being
+ # truncated, which aborts indexing mid-batch.
+ num_ctx = get_setting_from_snapshot(
+ "embeddings.ollama.num_ctx",
+ default=8192,
+ settings_snapshot=settings_snapshot,
)
- return OllamaEmbeddings(
- model=model,
- base_url=base_url,
+ logger.info(
+ f"Creating OllamaEmbeddings with model={model}, "
+ f"base_url={base_url}, num_ctx={num_ctx}"
)
+ ollama_kwargs: Dict[str, Any] = {
+ "model": model,
+ "base_url": base_url,
+ }
+ if num_ctx:
+ ollama_kwargs["num_ctx"] = int(num_ctx)
+
+ return OllamaEmbeddings(**ollama_kwargs)
+
@classmethod
def is_available(
cls, settings_snapshot: Optional[Dict[str, Any]] = None
diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.js
index 57bbc2a38d..c8b68253a8 100644
--- a/src/local_deep_research/web/static/js/embedding_settings.js
+++ b/src/local_deep_research/web/static/js/embedding_settings.js
@@ -24,7 +24,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Setup provider change handler
document.getElementById('embedding-provider').addEventListener('change', function() {
updateModelOptions();
- toggleOllamaUrlField();
+ toggleOllamaFields();
});
// Setup model change handler
@@ -121,8 +121,11 @@ async function loadCurrentSettings() {
// Load Ollama URL from global settings
await loadOllamaUrl();
+ // Load Ollama embeddings num_ctx from global settings
+ await loadOllamaNumCtx();
+
// Show/hide Ollama URL field based on provider
- toggleOllamaUrlField();
+ toggleOllamaFields();
// Update the saved defaults display
renderSavedDefaults(settings);
@@ -141,7 +144,11 @@ async function loadCurrentSettings() {
try { return JSON.parse(document.getElementById('text-separators').value); }
catch { return ["\n\n", "\n", ". ", " ", ""]; }
})(),
- 'embeddings.ollama.url': document.getElementById('ollama-url').value
+ 'embeddings.ollama.url': document.getElementById('ollama-url').value,
+ 'embeddings.ollama.num_ctx': (function() {
+ const v = parseInt(document.getElementById('ollama-num-ctx').value, 10);
+ return Number.isNaN(v) ? 8192 : v;
+ })()
};
// Attach auto-save listeners after original values are captured
@@ -427,6 +434,19 @@ function attachAutoSaveListeners() {
ollamaUrlEl.addEventListener('keydown', function(e) {
if (e.key === 'Enter') { e.preventDefault(); saveOllamaUrlAuto(); }
});
+
+ // Ollama embeddings num_ctx - blur / Enter
+ const ollamaNumCtxEl = document.getElementById('ollama-num-ctx');
+ function saveOllamaNumCtx() {
+ const value = parseInt(ollamaNumCtxEl.value, 10);
+ if (isNaN(value) || value < 512 || value > 131072) return;
+ const oldValue = originalValues['embeddings.ollama.num_ctx'];
+ saveSetting('embeddings.ollama.num_ctx', value, 'Ollama embeddings num_ctx', oldValue);
+ }
+ ollamaNumCtxEl.addEventListener('blur', saveOllamaNumCtx);
+ ollamaNumCtxEl.addEventListener('keydown', function(e) {
+ if (e.key === 'Enter') { e.preventDefault(); saveOllamaNumCtx(); }
+ });
}
/**
@@ -844,17 +864,17 @@ const escapeHtml = window.escapeHtml || function(str) {
/**
- * Toggle Ollama URL field visibility based on selected provider
+ * Toggle Ollama-specific fields (URL, num_ctx) based on selected provider
*/
-function toggleOllamaUrlField() {
+function toggleOllamaFields() {
const provider = document.getElementById('embedding-provider').value;
+ const display = provider === 'ollama' ? 'block' : 'none';
+
const ollamaUrlGroup = document.getElementById('ollama-url-group');
+ if (ollamaUrlGroup) ollamaUrlGroup.style.display = display;
- if (provider === 'ollama') {
- ollamaUrlGroup.style.display = 'block';
- } else {
- ollamaUrlGroup.style.display = 'none';
- }
+ const ollamaNumCtxGroup = document.getElementById('ollama-num-ctx-group');
+ if (ollamaNumCtxGroup) ollamaNumCtxGroup.style.display = display;
}
/**
@@ -872,3 +892,19 @@ async function loadOllamaUrl() {
SafeLogger.error('Error loading Ollama URL:', error);
}
}
+
+/**
+ * Load Ollama embeddings num_ctx from settings
+ */
+async function loadOllamaNumCtx() {
+ try {
+ const response = await safeFetch('/settings/api/embeddings.ollama.num_ctx');
+ const data = await response.json();
+
+ if (data && data.value !== undefined && data.value !== null) {
+ document.getElementById('ollama-num-ctx').value = data.value;
+ }
+ } catch (error) {
+ SafeLogger.error('Error loading Ollama num_ctx:', error);
+ }
+}
diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.html
index 174765a103..2f07cb8c2d 100644
--- a/src/local_deep_research/web/templates/pages/embedding_settings.html
+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html
@@ -96,6 +96,14 @@
</small>
</div>
+ <div class="ldr-form-group" id="ollama-num-ctx-group" style="display: none;">
+ <label for="ollama-num-ctx">{{ tooltip("Ollama Context Window (num_ctx)", "Token budget passed to Ollama for each embedding call. If your chunks tokenize to more than this, Ollama returns HTTP 500 and indexing fails. Increase if you see 'input length exceeds the context length'. Default 8192 is safe for chunk sizes up to ~5000 characters.") }}</label>
+ <input type="number" id="ollama-num-ctx" class="ldr-form-control" value="8192" min="512" max="131072" step="512">
+ <small class="ldr-form-text ldr-text-muted">
+ Tokens. Must exceed the largest chunk after tokenization. Increase if Ollama returns "input length exceeds the context length".
+ </small>
+ </div>
+
<div class="ldr-form-group">
<label for="embedding-model">Model</label>
<select id="embedding-model" class="ldr-form-control">
diff --git a/tests/embeddings/test_ollama_embeddings.py b/tests/embeddings/test_ollama_embeddings.py
index 696c6eea18..f5061c93af 100644
--- a/tests/embeddings/test_ollama_embeddings.py
+++ b/tests/embeddings/test_ollama_embeddings.py
@@ -117,6 +117,20 @@ class TestOllamaEmbeddingsIsAvailable:
# ── create_embeddings ────────────────────────────────────────────────────
+def _make_settings_side_effect(values):
+ """Build a side_effect for get_setting_from_snapshot that dispatches by key.
+
+ ``values`` maps setting keys (e.g. "embeddings.ollama.model") to the value
+ that lookup should return. Keys absent from ``values`` fall back to the
+ caller-provided ``default`` argument.
+ """
+
+ def _side_effect(key, default=None, **_kwargs):
+ return values.get(key, default)
+
+ return _side_effect
+
+
class TestOllamaEmbeddingsCreate:
"""Tests for create_embeddings method."""
@@ -125,7 +139,12 @@ class TestOllamaEmbeddingsCreate:
with patch(
f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
) as mock_get_setting:
- mock_get_setting.return_value = "nomic-embed-text"
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ )
with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
mock_get_url.return_value = "http://localhost:11434"
@@ -143,33 +162,47 @@ class TestOllamaEmbeddingsCreate:
def test_create_with_custom_model(self):
"""Creates embeddings with custom model."""
- with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
- mock_get_url.return_value = "http://localhost:11434"
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.num_ctx": 8192}
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ mock_instance = Mock()
+ mock_ollama.return_value = mock_instance
+
+ OllamaEmbeddingsProvider.create_embeddings(
+ model="mxbai-embed-large"
+ )
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["model"] == "mxbai-embed-large"
+
+ def test_create_with_custom_base_url(self):
+ """Creates embeddings with custom base URL."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.num_ctx": 8192}
+ )
with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
mock_instance = Mock()
mock_ollama.return_value = mock_instance
OllamaEmbeddingsProvider.create_embeddings(
- model="mxbai-embed-large"
+ model="nomic-embed-text",
+ base_url="http://custom:8080",
)
call_kwargs = mock_ollama.call_args[1]
- assert call_kwargs["model"] == "mxbai-embed-large"
-
- def test_create_with_custom_base_url(self):
- """Creates embeddings with custom base URL."""
- with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
- mock_instance = Mock()
- mock_ollama.return_value = mock_instance
-
- OllamaEmbeddingsProvider.create_embeddings(
- model="nomic-embed-text",
- base_url="http://custom:8080",
- )
-
- call_kwargs = mock_ollama.call_args[1]
- assert call_kwargs["base_url"] == "http://custom:8080"
+ assert call_kwargs["base_url"] == "http://custom:8080"
def test_create_uses_settings_snapshot(self):
"""Uses settings snapshot when provided."""
@@ -178,7 +211,12 @@ class TestOllamaEmbeddingsCreate:
with patch(
f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
) as mock_get_setting:
- mock_get_setting.return_value = "custom-model"
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "custom-model",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ )
with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
mock_get_url.return_value = "http://localhost:11434"
@@ -191,6 +229,157 @@ class TestOllamaEmbeddingsCreate:
# Verify get_setting_from_snapshot was called with settings
mock_get_setting.assert_called()
+ def test_create_passes_num_ctx_when_set(self):
+ """Forwards num_ctx to OllamaEmbeddings when configured."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings()
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["num_ctx"] == 8192
+
+ def test_create_omits_num_ctx_when_unset(self):
+ """Does not pass num_ctx when the setting is None."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": None,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings()
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert "num_ctx" not in call_kwargs
+
+ def test_create_passes_custom_num_ctx(self):
+ """Forwards a non-default num_ctx (proves the value is pass-through, not hardcoded)."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 16384,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings()
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["num_ctx"] == 16384
+
+ def test_create_coerces_string_num_ctx_to_int(self):
+ """Coerces string num_ctx to int (settings storage may return strings)."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": "8192",
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings()
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["num_ctx"] == 8192
+ assert isinstance(call_kwargs["num_ctx"], int)
+
+ def test_create_coerces_float_num_ctx_to_int(self):
+ """Coerces float num_ctx to int (JSON deserialization may yield floats)."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192.0,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings()
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["num_ctx"] == 8192
+ assert isinstance(call_kwargs["num_ctx"], int)
+
+ def test_create_combines_custom_model_and_num_ctx(self):
+ """Custom model arg and num_ctx setting both flow through."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.num_ctx": 4096}
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings(
+ model="bge-m3",
+ )
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["model"] == "bge-m3"
+ assert call_kwargs["num_ctx"] == 4096
+
+ def test_create_uses_default_num_ctx_when_snapshot_missing_key(self):
+ """Falls back to default=8192 when snapshot doesn't contain num_ctx."""
+ # _make_settings_side_effect returns the caller's `default=` for
+ # absent keys, mirroring what the real settings system does when
+ # neither DB nor JSON defaults have the key (shouldn't happen in
+ # practice once the JSON ships, but verifies the explicit default
+ # in create_embeddings is wired correctly).
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.model": "nomic-embed-text"}
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ OllamaEmbeddingsProvider.create_embeddings()
+
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["num_ctx"] == 8192
+
# ── _get_model_capabilities ─────────────────────────────────────────────
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 5f84aaa357..029542159d 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -653,6 +653,20 @@
"value": 1800,
"visible": true
},
+ "embeddings.ollama.num_ctx": {
+ "category": "embeddings",
+ "description": "Context window size (in tokens) used when generating Ollama embeddings. Must be at least as large as the longest chunk after tokenization; otherwise Ollama returns 'input length exceeds the context length' (HTTP 500) and indexing fails. The default of 8192 covers chunk sizes up to ~5000 characters for most models. Increase for very large chunks; decrease to save VRAM. qwen3-embedding supports up to 32768; nomic-embed-text supports 8192.",
+ "editable": true,
+ "max_value": 131072.0,
+ "min_value": 512.0,
+ "name": "Ollama Embeddings Context Window",
+ "options": null,
+ "step": 512.0,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 8192,
+ "visible": true
+ },
"embeddings.ollama.url": {
"category": "embeddings",
"description": "URL of the Ollama endpoint for embedding models. This setting allows you to use a different Ollama server for embeddings than for LLM operations. If not set, the system will fall back to the LLM Ollama URL.",