在 Token 傳輸途中中止:使用 Vercel AI SDK 與 React 19 串流聊天
Aborting Mid-Token: Streaming Chat with the Vercel AI SDK and React 19
使用 Vercel AI SDK 和 React 19 建立串流聊天時,傳入 AbortSignal 可在中止操作時停止底層請求及讀取器。自訂 fetch 應轉交呼叫端的 signal,並按訊息 ID 管理中止控制器,避免訊號失效或離開頁面後仍有讀取器運作。發生錯誤時應保留已顯示的部分內容,並區分用戶中止與傳輸失敗。
Aborting Mid-Token: Streaming Chat with the Vercel AI SDK and React 19
At 3:12 a.m. the page is not a model outage. A tab never released its SSE reader after a relay blip, so Chrome sits pegged while a half-rendered assistant message freezes the thread. Quota cuts look the same from the client: the socket dies mid-token, optimistic bubbles stay wrong, and the next send stacks another fetch. I have been integrating CopilotKit/OpenBot behind an OpenAI-compatible gateway, and this is the failure mode generic streaming snippets skip.
The UI stays client-side React 19. @ai-sdk/react parses tokens; a thin fetch wrapper owns transport so the component never blocks on I/O. On the wire, https://b-lost.com/v1 is an unbuffered SSE proxy in front of self-hosted OpenBot-style agents. No extra buffer means timeouts fail fast and AbortSignal still reaches the browser.
Cancellation that actually stops the reader
streamText streams tokens, but the underlying fetch only stops if you pass an AbortSignal. Without it, a dropped link or a Stop click leaves the reader draining into state updates.
import { useState, useRef, useCallback } from 'react';
import { streamText } from '@ai-sdk/react';
interface Message {
id: string;
role: 'user' | 'assistant';
content: string;
}
export function useStreamingChat() {
const [messages, setMessages] = useState<Message[]>([]);
const abortControllers = useRef<Map<string, AbortController>>(new Map());
const [isStreaming, setIsStreaming] = useState(false);
const [error, setError] = useState<Error | null>(null);
const sendMessage = useCallback(async (content: string) => {
const id = crypto.randomUUID();
const abortController = new AbortController();
abortControllers.current.set(id, abortController);
// Optimistic UI update
const optimisticId = `optimistic-${id}`;
setMessages(prev => [
...prev,
{ id: optimisticId, role: 'user', content },
{ id: `temp-${id}`, role: 'assistant', content: '' }
]);
setIsStreaming(true);
setError(null);
try {
const result = await streamText({
model: 'gpt-4o-mini', // or any compatible endpoint
prompt: content,
abortSignal: abortController.signal,
experimental_telemetry: {
isEnabled: true,
functionId: 'chat-message'
},
headers: {
'x-self-hosted': 'true' // route through OpenBot-compatible backend
}
});
let assistantContent = '';
for await (const chunk of result.textStream) {
assistantContent += chunk;
setMessages(prev =>
prev.map(msg =>
msg.id === `temp-${id}`
? { ...msg, content: assistantContent }
: msg
)
);
}
// Replace optimistic with final message
setMessages(prev =>
prev.filter(msg => !msg.id.startsWith('temp-')).concat({
id,
role: 'assistant',
content: assistantContent
})
);
} catch (err) {
if ((err as Error).name === 'AbortError') {
console.warn('Stream aborted by user');
} else {
setError(err as Error);
// Graceful degradation: show connection status toast
setMessages(prev => [
...prev.filter(msg => !msg.id.startsWith('temp-')),
{
id: `error-${id}`,
role: 'assistant',
content: 'Connection dropped. Retry or check network.'
}
]);
}
} finally {
abortControllers.current.delete(id);
setIsStreaming(false);
}
}, []);
const abortCurrentStream = useCallback(() => {
const controller = abortControllers.current.get('current');
if (controller) {
controller.abort();
abortControllers.current.delete('current');
}
}, []);
return {
messages,
sendMessage,
abortCurrentStream,
isStreaming,
error
};
}
Three boundaries matter. Optimistic inserts (user row plus an empty assistant row) keep the transcript from flashing blank while the first token is in flight. The signal aborts on Stop. The catch path treats AbortError as user intent and every other failure as transport: drop the temp row and surface a short recovery line instead of a blank hole. Non-abort failures belong on a retry queue with exponential backoff capped at three attempts. Partial text already painted should stay visible so the user is not staring at a wiped turn.
Pointing the SDK at an unbuffered relay
I do not maintain CopilotKit/OpenBot. I integrate it. Self-hosted OpenBot exposes an OpenAI-compatible surface; under concurrency, direct sockets are where mid-token cuts show up. The relay is the path that reproduces that behavior without adding a buffer of its own.
const config = {
baseURL: 'https://b-lost.com/v1',
headers: {
'Authorization': `Bearer ${process.env.MODEL_API_KEY}`,
'Content-Type': 'application/json'
},
fetch: (url, options) => {
const controller = new AbortController();
options.signal = controller.signal;
return fetch(url, { ...options, signal: controller.signal });
}
};
Override baseURL to an internal OpenBot endpoint on the same network, and keep https://b-lost.com/v1 when you need the production cut. The custom fetch above replaces options.signal with a controller nothing else can abort. That races the SDK signal and makes the hook's map theater. Forward the caller's signal. Key aborts by the same id you stored, not "current", and abort every map entry on unmount or you leak readers when the user navigates away.
The trade-off that stays ugly
Abort checks cost a few milliseconds. Against a high-latency relay they beat a 100ms poll: the main thread stops melting on 2000-token bursts, and Chrome traces show a large drop in perceived freeze versus letting the reader run out. That part is settled.
The hard part is optimistic state after tokens have already painted. Filtering temp- rows on error throws away text the user read. Keeping it means ids, the retry, and the final server message can disagree if a retry lands out of order. I would rather mark a partial assistant turn incomplete than wipe it and pretend the turn never happened. That fights both the SDK habit of replacing the row with a final message and the product desire for a clean transcript.
When you abort mid-token on a relay in front of OpenBot, do you keep the partial assistant text as the source of truth, or discard it and let the retry rewrite history?
來源:DEV Community · dev.to