Skip to content

feat(ui): prime a new chat's exact prompt before the first message - #5041

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/preload-first-turn
Oct 12, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/preload-first-turn

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

A new Agent UI chat took about 43 s to answer "hello" on Qwen3.6-35B-A3B, with only "Reading your request" on screen, because its first turn read ~19.3K tokens of system prompt and tool schemas from scratch. Now the backend reads that exact prompt into Lemonade's cache at start-up and whenever a new chat is opened. While that happens the new-chat view shows "Getting GAIA ready… 12s", and you can still type and send. The sidecar's existing warm-up primed a prompt that never matched a real turn, so its first question reused 0 tokens. It now primes the same prompt as the other paths.

Measured on the local Lemonade with the model reloaded before each run, so the prompt cache starts empty:

Path First "hello" before After Prompt tokens read on the first turn (before → after)
Agent UI, fresh chat (end to end over HTTP) 42.8 s 21.3 s 19,296 → 50
Agent UI new-chat build, in-process 44.2 s 5.3 s 19,295 → 50
HTTP sidecar 34.0 s (old warm-up) 5.4 s 19,295 → 50
TUI stdio (already primed, unchanged) 28.2 s (no warm-up) 5.8 s 19,295 → 50

The served UI still has a gap: its first token arrives about 15 s later than the in-process run, even though both read only 50 tokens. A second new chat on a warm cache answers in 6 s. The likely cause is llama.cpp restoring its checkpoint for Qwen3.6's hybrid layers. This PR doesn't fix it.

🔍 Technical details
  • The shared primitive is Agent.warm_up(). It sends system_prompt and _openai_tools exactly as process_query does, and now reports prompt_tokens and cached_tokens. The sidecar and the Agent UI (gaia/ui/warmup.py) both call it. The UI builds the agent with the same registry.create_agent kwargs that the streaming chat path uses on a cache miss.
  • Every new chat renders the same prefix whatever its session id (no attached docs). A unit test checks this byte for byte.
  • PrefixWarmer runs one warm-up at a time. It skips while any SSE chat turn is active and ignores a repeat within 30 s after success. Chat turns call wait_for_warm_up() before building their agent. That stops them reading the prompt twice and keeps them from racing the warm-up's tool registration.
  • It skips cloud models and models that aren't downloaded. The start-up warm-up runs only after the "Loading AI model" boot job succeeds, and it isn't a visible job, so it never blocks the composer.
  • New endpoints are GET and POST /api/system/warm-up, plus a warm_up field on /api/system/status. API types were regenerated.
  • The TUI's warm-up already matched the first turn while dynamic tools are off (the default since fix(gaia): offer the flagship every tool on every turn, as the Agent UI does #4554). The new test pins that. With GAIA_DYNAMIC_TOOLS=1 the first turn picks tools for its query, so a warm-up can't match it exactly. That opt-in path is unchanged.
  • No prompt content, tool sets, or tool order changed, so no eval categories need to re-run.
  • How it was measured: before each run the model was unloaded and reloaded, which clears llama.cpp's RAM prompt cache. Cached tokens are llama.cpp's own timings.cache_n / prompt_n from the response, and the Agent UI's stored input_tokens. The Lemonade is shared, and wall times varied by up to 2× when other clients were active. The numbers above come from quiet runs.

Test plan

  • python -m pytest tests/unit/test_ui_warmup.py hub/agents/gaia/python/tests/test_prompt_prefix_stability.py hub/agents/gaia/python/tests/test_warmup_no_download.py tests/unit/test_warm_up.py
  • cd src/gaia/apps/webui && npx vitest run && npx tsc --noEmit -p .
  • Start gaia chat --ui with a local model and open a new chat. "Getting GAIA ready… Ns" shows under the message box and clears when done, and the message box stays usable throughout.
  • Send "hello" right after it clears. The backend log's Warm-up (...) done line, and the message's input_tokens of about 50, show the prompt was reused.

A new Agent UI chat answered "hello" in ~43 s on Qwen3.6-35B-A3B because the
first turn read ~19.3K tokens of system prompt and tool schemas cold. The
backend now builds the flagship the way a new chat does and runs its
warm_up() at start-up and whenever a new chat is opened, so the first turn
reads only its own ~50 tokens. The new-chat view shows "Getting GAIA ready…
Ns" meanwhile without blocking the message box; a message sent mid-warm-up
waits for it instead of reading the prompt a second time. One warm-up runs at
a time, never alongside a chat turn, and a repeat within 30 s is a no-op.

The HTTP sidecar's warm-up sent only the agent's own prompt section and no
tools, so its prefix never matched a turn (0 of 19.3K tokens reused). It now
calls the same warm_up(), and logs a failure as a warning with its cause
instead of swallowing it at info level.

warm_up() reports prompt and cached token counts. Tests pin the warm-up
request's system message and tool schemas byte-for-byte to the first turn's,
for the TUI/sidecar agent and for the Agent UI's new-chat build.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes electron Electron app changes agents labels Oct 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

This PR loads GAIA's instructions into the local model's cache before a new chat's first message, so "hello" answers in seconds rather than ~40 s. The sidecar's warm-up now primes the same prompt a real turn sends. The design is sound and the prefix-equality tests are strong. One bug needs fixing first:

  • A non-streaming chat request can freeze the whole Agent UI server while a warm-up runs. The new "wait for the warm-up" step blocks on the main async thread in the non-streaming chat path, for up to 5 minutes. Until it returns, every other request stalls, including the warm-up progress poll and other chats' streams. The streaming path does this right because it waits in a worker thread. Move the non-streaming wait off the event loop too.

Real-world evidence

N/A: no evidence bundle was produced for this run. The PR description has before/after timings measured against a real Lemonade, but nothing in this run reproduced them. There's no screenshot of the "Getting GAIA ready… Ns" line, and no captured /api/system/warm-up request and response. For the UI and HTTP surfaces, this verdict rests on static review only.

🔍 Technical details

🟡 Important

Blocking Event.wait on the event loop in the non-streaming path (src/gaia/ui/_chat_helpers.py:1979)
_get_chat_response is an async def that routers/chat.py:198 awaits directly. wait_for_warm_up() calls threading.Event.wait(300) synchronously there, so a cold warm-up (20–40 s) stalls the uvicorn loop. In the streaming path (:2371) the same call sits inside _run_agent, which runs on a thread, so that one is fine.

        await asyncio.to_thread(wait_for_warm_up)

(Check that asyncio is imported in this module; _stream_chat_impl already awaits asyncio.to_thread.)

The busy probe misses non-streaming turns (src/gaia/ui/warmup.py, configure)
set_busy_check only looks at _active_sse_handlers. A warm-up can start in the middle of a non-streaming turn and compete with it for Lemonade's single slot, which the module docstring says must never happen. Either track non-streaming turns too, or say in the docstring that only SSE turns are guarded.

🟢 Minor

  • Missing UI evidence. A rendered screenshot of the new-chat status line is still owed, and it can come from the strix-halo lane. A captured POST /api/system/warm-up → {"state":"warming",…} would cover the route evidence before then.
  • _warm_new_chat_prefix hardcodes "device": "gpu". That matches the DB column default today (database.py:97). If create_session ever takes its device from the profile, the warm-up would quietly prime a different prefix. A shared constant would keep the two in step.

Strengths

  • test_ui_warmup.py and test_warm_up_primes_the_first_turns_exact_prefix check the warm-up and first-turn prefixes byte for byte, which is the invariant that matters. A drift would fail CI instead of quietly costing 30 s.
  • Failures now log a warning that names the cause, and show up in the status endpoint as failed with an error. The sidecar previously logged them at info as "skipped".
  • The warm-up runs one at a time, skips repeats within 30 s, and skips cloud or not-downloaded models, so it can't trigger a surprise download or double-load the model.

…route

The new-chat warm-up only recognised fireworks/amd cloud ids, so a cloud model known only from Lemonade's catalog would have been sent a paid request on every new chat. It now reads the catalog before classifying the model, also checks the model the agent actually picked when the session defers to the agent default, and skips the eval Claude provider.

Also documents /api/system/warm-up in the Agent UI SDK reference, which test_route_doc_coverage requires, and narrows the module docstring to say only streamed turns block a warm-up.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Holding this until after 0.25.0, unless you want it in the release. It doesn't change what the model sees, so no eval is needed. But it's an 850-line performance feature that runs a model request in the background on every new chat, and the RC is frozen. I pushed one fix: the warm-up could have sent a paid request to a cloud model on every new chat. That only happened when GAIA knew the model was cloud-hosted from Lemonade's model list, not from its name.

The bot's main finding is a false alarm. The non-streaming wait already runs in a worker thread, so it doesn't freeze the server.

🔍 Technical details

Pushed 10471e185 to kalin/preload-first-turn:

  • _warm_new_chat_prefix used cloud_model_provider(model_id) without metadata. That only catches the fireworks./amd. prefixes, so a cloud model known only from Lemonade's model list counted as local and as downloaded. It now calls get_model_info first, which fills _CLOUD_MODELS, and then classifies the model with _ui_cloud_provider.
  • When the session stays on the DB default, _build_create_kwargs leaves out model_id and the agent picks its own model. That model is now checked again after the agent is built. A model of None skips the warm-up.
  • The warm-up is skipped when GAIA_EVAL_AGENT_PROVIDER=claude is set, because otherwise it would make a Claude call.
  • Added /api/system/warm-up to docs/sdk/sdks/agent-ui.mdx. Without it, test_route_doc_coverage fails on this branch, and the Unit Tests jobs were still pending.
  • The module docstring now says only streamed turns stop a warm-up from starting. That covers the bot's second point.
  • Two new tests: a catalog-only cloud model never builds the agent, and the eval Claude provider is skipped.

The bot's 🟡 is a false alarm. In _get_chat_response, wait_for_warm_up() is inside _do_chat, which runs through run_in_executor, not on the event loop.

Checked and fine: the warm-up sends the same prefix as the real turn. Byte-for-byte tests cover both the UI and the sidecar. A model that isn't downloaded is never loaded. A turn sent mid-warm-up waits for it instead of reading the prompt twice.

Local results: tests/unit/chat/ui passed 1390, the four warm-up test files passed 22, and lint.py --black --isort was clean.

… absent

The CI unit job doesn't install hub packages, so the unguarded gaia_agent_chat import failed the hub-import guard on every platform.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 12, 2026
Merged via the queue into amd:main with commit a49e169 Oct 12, 2026
@kovtcharov-amd
kovtcharov-amd deleted the kalin/preload-first-turn branch October 12, 2026 22:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes electron Electron app changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants