Skip to content

feat(llm): add first_token_timeout to FallbackAdapter - #3080

Open
rosetta-livekit-bot[bot] wants to merge 1 commit into
mainfrom
decades-morning-cobra
Open

rosetta-livekit-bot[bot] wants to merge 1 commit into
mainfrom
decades-morning-cobra

Conversation

@rosetta-livekit-bot

@rosetta-livekit-bot rosetta-livekit-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add an optional firstTokenTimeout deadline to FallbackAdapter
  • fail over when metadata or keep-alive chunks arrive without text or tool calls
  • apply the same deadline to recovery probes and preserve cancellation while waiting
  • port the source behavior tests and add a minor @livekit/agents changeset

Ports livekit/agents#8691.

Testing

  • pnpm test agents (Node 22: 5,125 passed, 10 skipped)
  • pnpm --filter @livekit/agents build
  • pnpm --filter @livekit/agents lint
  • pnpm --filter @livekit/agents typecheck
  • pnpm --filter @livekit/agents api:check
  • pnpm exec prettier --check "agents/src/**/*.{ts,tsx,md,json}"
Source diff coverage
  • livekit-agents/livekit/agents/llm/fallback_adapter.py: adapted to agents/src/llm/fallback_adapter.ts, with the public API reflected in agents/etc/agents.api.md. The Python seconds option becomes milliseconds per agents-js conventions; the absolute first-output deadline and cancellation use native JavaScript timers and stream cancellation.
  • tests/test_llm_fallback.py: adapted to agents/src/llm/fallback_adapter.test.ts. Ports both source cases: keep-alive/usage-only chunks trigger failover, while text before later keep-alives disables the deadline.
  • livekit-agents/pyproject.toml: not applicable. The source only adds the Python <3.11 async-timeout compatibility dependency; Node provides native timer and cancellation primitives.
  • uv.lock: not applicable. This is the lockfile result of the Python-only compatibility dependency and has no target counterpart.

Ported from livekit/agents#8691

Original PR description

llm.FallbackAdapter fails over when an attempt errors, and attempt_timeout is the only time limit on an attempt. The OpenAI-compatible plugins pass that value to httpx as a read timeout, so any bytes reset it: SSE keep-alive comments such as OpenRouter's : OPENROUTER PROCESSING, a role-only first delta, or reasoning deltas that _parse_choice drops. A provider can hold an attempt open far past attempt_timeout with no ChatChunk, and the caller hears silence instead of the next provider.

attempt_timeout cannot carry this limit, because each plugin gives conn_options.timeout its own meaning: a read timeout in the OpenAI-compatible plugins, a total deadline in Google.

first_token_timeout sets a deadline from the start of each attempt to its first chunk with text or a tool call. When the deadline expires, the attempt raises asyncio.TimeoutError and the adapter fails over as it does for any other failed attempt.

Why it is a separate argument that defaults to off:

  • Reusing attempt_timeout stops healthy fallbacks. A cold fallback on a large prompt can take more than 5 s to its first token, and #6171 reports 10.8 s on a 19k-token turn. With the default None, existing adapters keep their current behavior.
  • Only output stops the clock. Usage and metadata chunks do not count, per ChatChunk.has_response(). After the first token, gaps in the stream have no limit.
  • The recovery probe uses the same deadline. Without it, a slow provider passes its probe, is marked available, and times out again on the next turn.
llm.FallbackAdapter([primary, fallback], first_token_timeout=4.0)

The value is in seconds, and it covers the internal retries of one attempt.

Fixes #6171. Alternative to #6173. Related to #6916.

Context for reviewing and coding agents

How to see it

test_first_token_timeout[stalled] in tests/test_llm_fallback.py fails on main when first_token_timeout is replaced with attempt_timeout: the primary sends a usage-only chunk each second, and the response never comes from the fallback. The [answered] case asserts that keep-alives after the first token do not cause a failover. The live repro is mock_stall.py in #6171.

Blast radius

The deadline lives in FallbackLLMStream._try_generate (llm/fallback_adapter.py:224). Its two callers are the serving loop in _run (llm/fallback_adapter.py:366) and the recovery probe in _try_recovery (llm/fallback_adapter.py:335). The STT, TTS and realtime fallback adapters are not changed.

Why not #6173

#6173 reuses attempt_timeout as the first-chunk deadline, so the 10.8 s fallback in #6171 would fail at 5 s and the whole request would error. It also stops the clock on any chunk, including usage-only chunks, and it conflicts with the current _try_generate.

Open design question

#6916 asks for a separate fallback_attempt_timeout for providers after the first. The two arguments should be decided together, so the constructor does not get overlapping timeout settings.

@rosetta-livekit-bot
rosetta-livekit-bot Bot requested a review from a team as a code owner November 26, 2026 03:51
@changeset-bot

changeset-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 35eefa5

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 42 packages
Name Type
@livekit/agents Minor
@livekit/agents-plugin-anam Minor
@livekit/agents-plugin-anthropic Minor
@livekit/agents-plugin-assemblyai Minor
@livekit/agents-plugin-azure Minor
@livekit/agents-plugin-baseten Minor
@livekit/agents-plugin-bey Minor
@livekit/agents-plugin-cartesia Minor
@livekit/agents-plugin-cerebras Minor
@livekit/agents-plugin-deepgram Minor
@livekit/agents-plugin-did Minor
@livekit/agents-plugin-elevenlabs Minor
@livekit/agents-plugin-fishaudio Minor
@livekit/agents-plugin-google Minor
@livekit/agents-plugin-hume Minor
@livekit/agents-plugin-inworld Minor
@livekit/agents-plugin-krisp Minor
@livekit/agents-plugin-lemonslice Minor
@livekit/agents-plugin-liveavatar Minor
@livekit/agents-plugin-livekit Minor
@livekit/agents-plugin-meta Minor
@livekit/agents-plugin-minimax Minor
@livekit/agents-plugin-mistral Minor
@livekit/agents-plugin-mistralai Minor
@livekit/agents-plugin-neuphonic Minor
@livekit/agents-plugin-nvidia Minor
@livekit/agents-plugin-openai Minor
@livekit/agents-plugin-perplexity Minor
@livekit/agents-plugin-phonic Minor
@livekit/agents-plugin-protoface Minor
@livekit/agents-plugin-resemble Minor
@livekit/agents-plugin-rime Minor
@livekit/agents-plugin-runway Minor
@livekit/agents-plugin-sarvam Minor
@livekit/agents-plugin-silero Minor
@livekit/agents-plugin-soniox Minor
@livekit/agents-plugin-speechify Minor
@livekit/agents-plugin-synthesia Minor
@livekit/agents-plugin-tavus Minor
@livekit/agents-plugins-test Minor
@livekit/agents-plugin-trugen Minor
@livekit/agents-plugin-xai Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@rosetta-livekit-bot
rosetta-livekit-bot Bot requested a review from longcw November 26, 2026 03:52

@devin-ai-integration devin-ai-integration 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.

Devin Review found 2 potential issues.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +342 to +344
} catch (error) {
if (this.abortController.signal.aborted) return;
throw error;

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.

🔴 False recovery after fallback replies

When a fallback reply finishes, tryGenerate treats cancellation of a pending recovery probe as normal completion. The default LLM node closes the stream, so tryRecovery marks the timed-out provider available without seeing any output. The next turn tries that provider again.

Learn more

When a provider times out, the adapter starts a background request to check whether it recovered before moving on to the backup. tryRecovery treats normal exhaustion of that request's generator as success. The default LLM node closes the adapter stream after draining the backup's reply. If the probe is still waiting for its first output, that close rejects its wait, but the generator returns normally and the probe restores availability without a response.

Example: With a 300 ms deadline, the primary times out and its recovery probe starts. The backup finishes in 100 ms while the probe still has no output. Closing the reply cancels the probe and restores the primary, so another turn can repeat the 300 ms wait.

Recommended fix: Give the background probe a cancellation lifetime separate from the reply. A cancelled probe must not reach the success branch in tryRecovery. Add a test where the fallback reply is drained and closed while the probe still has no output, then verify that closing the reply does not restore the primary.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}
throw error;
} finally {
stream.close();

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.

🟡 Provider generation continues after failover

On a first-token timeout, tryGenerate closes the local stream but leaves some provider requests running. Anthropic generation and OpenAI Responses HTTP generation never pass the abort signal to their SDKs. The original request can keep generating while the backup answers.

Learn more

The adapter's first-token timer can expire while the provider is still processing an otherwise live request. LLMStream.close only aborts the stream's controller. The Anthropic request and OpenAI Responses HTTP request neither pass that signal to the SDK nor stop consuming events when it fires. The adapter moves on without stopping the network request or its event-processing loop.

Example: An Anthropic request needs 900 ms before it starts emitting text. A 300 ms deadline moves the agent to a backup, but the Anthropic plugin still reads and processes the original response.

Recommended fix: Wire the stream abort signal into provider request options and treat local abort as cancellation rather than a provider error. Follow the signal and cancellation handling in inference generation and its error path. Test that a first-token timeout aborts the transport of the original request while the backup still responds.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants