Repository navigation
feat(llm): add first_token_timeout to FallbackAdapter - #8691
Conversation
attempt_timeout reaches the OpenAI-compatible plugins as an httpx read timeout, so SSE keep-alives and deltas that produce no ChatChunk keep an attempt open with no output and no failover. first_token_timeout bounds the time from the start of an attempt to its first chunk with text or a tool call, and fails over when it expires. It defaults to None.
|
@longcw |
no, STT has no "first token" to wait for. in streaming TTS, how long the first audio takes depends on when the LLM sends text. A timer that starts with the attempt would fire whenever the LLM is slow. The timer would have to start at the first text sent or the first flush, so it's a different mechanism, not a copy of this one. |
| else: | ||
| # keep-alives reset the provider's read timeout, so bound the | ||
| # wait for the first output here | ||
| chunk = await asyncio.wait_for( |
There was a problem hiding this comment.
nit from Codex:
python/cpython#86296 On Python 3.10 and 3.11, wait_for() can swallow cancellation if the chunk read has already completed when wait_for() handles the cancellation.
There was a problem hiding this comment.
Real on 3.10/3.11, and it matters here: an interrupt before the first token is common (barge-in, preemptive generation), and a dropped cancel holds the speech until the 5 s interruption timeout.
Switched to a timeout scope (βasyncio.timeout_atβ, βasync_timeoutβ on 3.10)
asyncio.wait_for drops a cancel on Python 3.10 and 3.11 when the awaited read finishes in the same loop iteration (cpython#86296). An interrupt before the first token then leaves the fallback stream reading the provider, which holds the speech until the interruption timeout. A timeout scope runs in the reading task and keeps the cancel.
There was a problem hiding this comment.
Devin Review found 2 new potential issues.
1 flag not posted on this PR by your GitHub settings β view it in Devin Review. (Configure)
| async with timeout_at(deadline): | ||
| chunk = await stream.__anext__() |
There was a problem hiding this comment.
π‘ Lost stream cancellation on Python 3.10
When stream closure cancels the task after the timer fires but before it resumes, timeout_at swallows the cancellation. Closing the stream then waits while the adapter starts another model request.
Learn more
Closing an LLM stream calls LLMStream.aclose, which cancels its generation task and waits. On Python 3.10, the imported async-timeout scope cancels that same task when its deadline expires. If closure also cancels the task before it resumes, the scope sees its own expired state and converts the cancellation into TimeoutError. The serving loop handles that as a provider failure and keeps going while closure waits.
Example: A voice turn stops while the primary is still waiting for its first token. In one event-loop iteration the deadline cancels the task, then stream closure cancels it before it resumes. The adapter starts a fallback request instead of stopping.
Recommended fix: On Python 3.10, isolate the read in a child task and use asyncio.wait with the remaining deadline. Cancel and drain the child on timeout or external cancellation, and let an external CancelledError propagate. Test with both cancellation callbacks queued before the waiting task resumes.
Was this helpful? React with π or π to provide feedback.
There was a problem hiding this comment.
Confirmed, but only on 3.10 (async-timeout can't tell its own cancel from an outside one; 3.11+ βasyncio.timeout_atβ uses βuncancel()β and keeps it). It needs the cancel and the deadline in the same loop iteration.
3.10 is EOL, so I'd not adding a separate child-task path for it.
| async with timeout_at(deadline): | ||
| chunk = await stream.__anext__() |
There was a problem hiding this comment.
π‘ Buffered output bypasses expired deadline
After the deadline expires, timeout_at can still accept a buffered first token. The read returns without yielding, so the adapter serves the late attempt instead of failing over.
Learn more
Both timeout implementations schedule a cancellation for a later event-loop turn when entered with an expired deadline. A read from LLMStream.anext can return immediately because tee_peer and the stream channel consume queued chunks without waiting. The scope exits before its cancellation runs. When that chunk contains text or a tool call, the adapter clears the deadline and commits to the provider.
Example: The adapter receives a metadata-only chunk just as the deadline comes due. On the next read the deadline has already passed, but a text chunk is queued and the read completes synchronously. The adapter accepts the text rather than treating the attempt as timed out.
Recommended fix: Check the monotonic clock before starting each pre-output read. Raise the same timeout the fallback loop already handles when no time remains, and keep the timeout scope for reads that need to wait.
| async with timeout_at(deadline): | |
| chunk = await stream.__anext__() | |
| if asyncio.get_running_loop().time() >= deadline: | |
| raise asyncio.TimeoutError | |
| async with timeout_at(deadline): | |
| chunk = await stream.__anext__() |
Was this helpful? React with π or π to provide feedback.
llm.FallbackAdapterfails over when an attempt errors, andattempt_timeoutis 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_choicedrops. A provider can hold an attempt open far pastattempt_timeoutwith noChatChunk, and the caller hears silence instead of the next provider.attempt_timeoutcannot carry this limit, because each plugin givesconn_options.timeoutits own meaning: a read timeout in the OpenAI-compatible plugins, a total deadline in Google.first_token_timeoutsets a deadline from the start of each attempt to its first chunk with text or a tool call. When the deadline expires, the attempt raisesasyncio.TimeoutErrorand the adapter fails over as it does for any other failed attempt.Why it is a separate argument that defaults to off:
attempt_timeoutstops healthy fallbacks. A cold fallback on a large prompt can take more than 5 s to its first token, and FallbackAdapter attempt_timeout is a read (inter-byte) timeout, not time-to-first-token β a provider that stalls before its first token causes long dead air with no failoverΒ #6171 reports 10.8 s on a 19k-token turn. With the defaultNone, existing adapters keep their current behavior.ChatChunk.has_response(). After the first token, gaps in the stream have no limit.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