Repository navigation
fix(llm): size a context overflow against the machine's own device profile - #4095
Conversation
On NPU, every real context overflow was labelled "the model was loaded at the wrong context size", so the chat layer announced "Model reloaded — retrying...", replayed the identical oversized turn, and only then surfaced an error. Nothing was wrong with the load: both classifiers compared the reported n_ctx against a hardcoded 65536, the GPU/CPU window, while a correctly loaded NPU model sits at NPU_CTX_SIZE (32768) — so the comparison was unconditionally true there. The threshold now derives from the active device profile via a new active_profile_ctx_size(), rather than swapping one hardcoded constant for another. A corrupt config raises instead of guessing a device. Part of #2884.
`gaia chat "<message>"` printed the backend's own string verbatim, so a context overflow on NPU arrived as a bare "❌ Error: Max length reached!" — no cause, no next step. The classifier that turns that into an actionable message lived in gaia.ui, which needs fastapi, so the CLI could not reach it. Moved it next to the error classes it returns (classify_lemonade_exception in llm/providers/lemonade.py); gaia.ui keeps its existing name as a re-export. Part of #2884.
The agent loop reached the error classifier through gaia.ui and swallowed the ImportError, so on any install without the ui extras every Lemonade failure fell back to "try again in a moment" instead of the real remediation — which is how a context overflow reached the CLI as a bare backend string. Points both call sites at the classifier's new in-core home and drops the blanket except that hid the miss. Part of #2884.
Request changesSizing the overflow threshold against the machine's own device profile is the right fix, and the NPU/GPU behaviour is well covered by the new tests. Two things should be sorted before merge. A broken config file now crashes error handling instead of reporting the error. The new context-size lookup reads GAIA's config and raises loudly when that file is corrupt or unreadable — correct on its own, but the lookup runs inside the handlers that are already dealing with a failure (the CLI, the agent loop, the chat routes). The result is a raw traceback that replaces the error the user was actually hitting. The evidence run reproduced exactly this. Decide the unresolvable-profile case inside the classifier: log it and treat the overflow as not-retryable, so the user still gets the real message. The plain-CLI half of the fix landed on a method nothing calls. One smaller thing: for a connection failure the new typed message is less useful than the string it replaced — the old text named the model, the server URL, the log file and Real-world evidenceThe evidence bundle exercised the real stack against a stand-in Lemonade backend returning a genuine AFTER (this PR, HEAD):
❌ Error: This conversation got too long for the model's context window. Start a fresh task to keep going.
BEFORE (base 158e2a71):
❌ Error: OpenAI BadRequestError: Error code: 400 - {'error': {'type': 'exceed_context_size', ... 'n_ctx': 32768}}
🔍 Technical details🟡 A
|
The corrupt-config test passed alone and failed in the full suite: test_cli_config.py reloads gaia.config, rebinding GaiaConfigError to a new class object, so the module-level import pytest.raises was matching against had gone stale.
|
Full-suite note: One failure was mine and is fixed in 4364b30: the corrupt-config test passed alone and failed in the full suite because |
|
The two 🟡 issues from the first review are still open in this push. 🟡 🟡 A corrupt 🔍 Technical details
except Exception as e:
from gaia.llm.providers.lemonade import classify_lemonade_exception
classified = classify_lemonade_exception(e)
error_message = f"❌ Error: {classified.user_message if classified else str(e)}"
self.log.error(error_message)
print(error_message)
yield error_message
from gaia.config import GaiaConfigError
try:
threshold = active_profile_ctx_size()
except GaiaConfigError as exc:
logger.error("Cannot size the expected context window: %s", exc)
threshold = None
if threshold is not None and 0 < n_ctx_reported < threshold:
err_instance.retryable = TrueThe existing test |
Two review findings, both real. The plain-CLI half of the fix landed on `GaiaCliClient.chat`, which has no in-tree caller — `action == "chat"` routes to ChatAgent, and the GaiaCliClient path users reach is `prompt` -> `send_message`, whose handler still printed the raw backend string. Moved the typed-message treatment there. Both overflow classifiers called `active_profile_ctx_size()` bare. They run inside `except` handlers, so a corrupt `~/.gaia/config.json` raised a GaiaConfigError that replaced the error the user actually hit. The new `_loaded_below_profile` guard logs it and leaves the overflow non-retryable — it cannot promise a reload it cannot size. Also keeps the backend detail as a `Details:` line under the typed sentence, so a connection failure still names the server and the log file it used to.
|
Both 🟡 findings are fixed in c5f9547, and the 🟢 one too.
Branch is also merged up to current 🔍 Evidence — executed at HEAD c5f9547Driving the real How it was tested: real Tests: The NPU hardware still owed — the profile is exercised by pinning |
|
Green and current — merging. Evidence above was measured on CI on 🔍 On the eight jobs still queuedThe remaining checks (API Tests, Agent SDK Windows, CLI Windows, Lemonade smoke, SD, Lemonade Embeddings, NPU FLM Embedder, Example Agents stx) all target This matches the repo's practice rather than departing from it: #4109 merged at 04:49Z with three of these same jobs queued. |
One conflict, in `lemonade_client.py`: both sides added a new context-size helper at the same spot, and each has live callers, so both stay. `resolve_ctx_size(model, device)` (this branch) decides what window to REQUEST at load time and is what honours `GAIA_CTX_SIZE`; it is called from the agent base, the CLI, the installer and the manager. `active_profile_ctx_size()` (main, amd#4095) reports the device profile's own window with no override applied, and exists so the context-overflow classifiers can judge a reported `n_ctx`. Collapsing them would break one caller or the other. `cli.py` and `agent.py` automerged, and both sides' intent survives: main's `classify_lemonade_exception` error reporting is intact, and the inline `GAIA_CTX_SIZE` block this branch replaced with the central resolver stays deleted (main never touched it after the merge base).
Picks up amd#4095, which landed while the conflict resolution above was in progress. No conflicts.
On a Ryzen AI (NPU) machine, running out of context was reported as if the model had been loaded wrong. The chat UI announced "Model reloaded — retrying...", replayed the same oversized turn, and only then gave up; on the plain
gaia chat "<message>"command line the user got a bare❌ Error: Max length reached!with no cause and no next step. Nothing was wrong with the load — GAIA was measuring the overflow against the GPU context window (64K) on a machine whose real ceiling is 32K. Now the comparison uses whatever window the machine's own device profile expects, so an NPU overflow says what happened and what to do about it, on both surfaces.Closes #2884.
🔍 Technical details
Three defects, all the same root cause — a threshold that assumed one device:
_classify_lemonade_response,_classify_chat_exception) compared the reportedn_ctxagainst a hardcoded65536. On NPU a correct load isNPU_CTX_SIZE(32768), so0 < n_ctx < 65536was unconditionally true and every real overflow was markedretryable. The fix derives the threshold from the active device profile via a newactive_profile_ctx_size()inllm/lemonade_client.py— not by hardcoding 32768 in place, which would break GPU.Agent._extract_lemonade_user_messageimported the classifier fromgaia.ui._chat_helpersinside atry/except Exception: return None.gaia.uineeds fastapi, so on any install without the[ui]extras the import failed silently and every Lemonade error fell back to generic "try again in a moment" copy. That is how the raw backend string reached the CLI.GaiaCliClient.send_message— the handlergaia promptroutes to — printedstr(exc)verbatim. The typed sentence is now the headline and the backendstring is kept underneath as a
Details:line, so a connection failure stillnames the model, the URL and the server log.
Both classifiers call
active_profile_ctx_size()through a_loaded_below_profileguard: they run insideexcepthandlers, so an unreadable config is logged and the overflow left non-retryable rather than raising aGaiaConfigErrorthat replaces the error the user actually hit.The classifier moved to
llm/providers/lemonade.pyasclassify_lemonade_exception, next to the error classes it returns;gaia.ui._chat_helpers._classify_chat_exceptionis now a re-export so existing callers and tests are unchanged.Searched for other instances:
git grep -n 65536across the tree. Every other hit insrc/is an I/O chunk size, a UI picker option, a docstring example, the constant's own definition, orfactory/harvestreporting ratios — none is a ctx expectation.agent.py's literal ladder (context size (4096|8192|16384) is a fast path only; all three values are below both profiles, so it is correct on both, and_is_loaded_ctx_too_small()— already device-aware from the first half of this issue — covers everything else.Test plan
pytest tests/unit/test_ctx_overflow_device_profile_2884.py— 25 new tests, all green. They setdefault_devicetonpu/gpu/cputhrough the real config file (no mocked accessor) and assert the retryable decision flips with the profile, not with a constant.pytest tests/unit/test_lemonade_error_classification.py tests/unit/agents/ tests/unit/chat/ui/ tests/unit/test_cli_config.py tests/unit/test_cli_device_resolution.py tests/unit/test_lemonade_client_ctx_override.py tests/unit/test_base_agent_lemonade_api_key.py tests/unit/test_lemonade_ctx_ceiling.py— 1105 passed, 50 skipped / 1043 passed / 136 passed across the runs.python util/lint.py --all— exit 0;black --check src/gaia tests1065 unchanged,flake80,isortclean.default_device=npuin the config, which is the same input the production code reads. A reviewer on NPU can confirm with a >32K turn: the error should name the context window and suggest a fresh task, with no "Model reloaded — retrying..." line.Before / after on the plain CLI (from the new regression test)
Before —
tests/unit/test_ctx_overflow_device_profile_2884.pycaptured stdout while the fix was absent:After: