AI SDK 7: Mit stoppedBy abgebrochene Chat-Antworten sauber behandeln
Der Artikel zeigt anhand von MockLanguageModelV4 und ai@7.0.183, wie sich in einer React-Chat-Anwendung mit dem Feld stoppedBy nachvollziehen laesst, warum eine Antwort endete. Getestet wird die Verdrahtung der App, nicht das Verhalten eines echten Modells.

Vom Cuelark-Team. Die Details stammen aus den Release Notes und der Dokumentation des Vercel AI SDK, geprüft am 27. November 2026. Wir haben kein echtes Modell aufgerufen. Alles Weitere lief gegen MockLanguageModelV4 aus ai/test auf ai@7.0.183. Getestet wird also die Verkabelung, die Ihre App sieht, und nicht das Verhalten eines bestimmten Modells.
Ein Chat mit Tool-Aufrufen kann aus sehr unterschiedlichen Gründen enden. Das Modell hat seine Antwort gegeben. Ihr Step-Limit hat mitten in einer Aufgabe gegriffen. Ein Tool wartet auf die Freigabe durch den Nutzer. Oder das Modell hat ein Tool aufgerufen, das nur der Browser ausführen kann. Bis jetzt mussten Sie raten, welcher Fall eingetreten ist, und zwar anhand von finishReason. Dieses Feld beschreibt aber nur den letzten Modellaufruf. Eine Schleife, die ihr Step-Limit erreicht, meldet weiterhin tool-calls.
ai@7.0.181, veröffentlicht am 23. November (UTC), fügt stoppedBy zu den Ergebnissen von generateText und streamText, zum onEnd-Callback und zum finalen finish-Stream-Part hinzu. Laut der Dokumentation zur Loop-Steuerung des AI SDK gibt es vier Werte:
Derselbe Release fügt einen onWarning-Callback pro Aufruf hinzu. Laut Dokumentation melden WorkflowAgent und HarnessAgent stoppedBy noch nicht.
stoppedBy existiert nur im serverseitigen Stream. Der finish-Chunk des UI-Nachrichtenstreams, den useChat liest, enthält finishReason und messageMetadata, aber nicht stoppedBy. Übergeben Sie es deshalb über die Nachrichten-Metadaten:
// app/api/chat/route.ts import { openai } from '@ai-sdk/openai'; import { streamText, convertToModelMessages, tool, isStepCount, type UIMessage, type StoppedBy, type FinishReason, } from 'ai'; import { z } from 'zod'; export type ChatMessage = UIMessage < { stoppedBy?: StoppedBy; finishReason?: FinishReason } >; const tools = { searchDocs: tool ( { description: 'Search the docs', inputSchema: z. object ( { query: z. string ( ) } ), execute: async ( { query } ) => ( { hits: [ `result for ${query}` ] } ), } ), deleteDraft: tool ( { description: 'Delete a draft', inputSchema: z. object ( { id: z. string ( ) } ), needsApproval: true, execute: async ( { id } ) => ( { deleted: id } ), } ), askUser: tool ( { description: 'Ask the user a clarifying question', inputSchema: z. object ( { question: z. string ( ) } ), // no execute: the browser answers this one } ), }; export async function POST ( req: Request ) { const { messages }: { messages: ChatMessage [ ] } = await req. json ( ); const result = streamText ( { model: openai ( 'gpt-6.2-sol' ), messages: await convertToModelMessages ( messages ), tools, stopWhen: isStepCount ( 3 ), onWarning: ( { warnings } ) => console. warn ( 'model warnings', warnings ), } ); return result. toUIMessageStreamResponse < ChatMessage > ( { messageMetadata: ( { part } ) => part. type === 'finish'? { stoppedBy: part. stoppedBy, finishReason: part. finishReason }: undefined, } ); } Vollbildmodus öffnen Vollbildmodus beenden Auf dem Client liefert useChat<ChatMessage>() message.metadata.stoppedBy auf der letzten Assistenten-Nachricht. Nur zwei Fälle erfordern eine neue UI:
export function LoopStatus ( { message, onContinue }: { message: ChatMessage; onContinue: ( ) => void } ) { const { stoppedBy, finishReason } = message. metadata?? { }; if ( stoppedBy === 'stop-condition' ) { return < p > Paused after the step limit. < button onClick = { onContinue } > Keep going </ button ></ p >; } if ( stoppedBy === 'model' && finishReason === 'length' ) { return < p > The answer hit the length limit and may be cut off. </ p >; } return null; // approval and client-side tools already show up as tool parts } Vollbildmodus öffnen Vollbildmodus beenden Wir verbinden onContinue mit sendMessage({ text: 'Continue where you left off.' }). Die Fälle mit Freigabe und clientseitigen Tools erscheinen bereits als Tool-Parts in den Zuständen approval-requested und input-available, sodass diese Parts ihre eigenen Buttons rendern können.
Wir haben sechs skriptgesteuerte Szenarien durch den obigen Route-Handler laufen lassen (mit eingesetztem Mock-Modell) und jede Antwort so ausgelesen, wie useChat es tut, mit parseJsonEventStream und readUIMessageStream.
Die letzten drei Zeilen sind der entscheidende Punkt. finishReason ist in allen dreien gleich, während stoppedBy sie unterscheidet. Die Metadaten kamen jedes Mal auf dem Client an.
Im sechsten Szenario ließ der Mock eine Provider-Warnung zurückgeben. Mit gesetztem onWarning erhielt der Callback {"type":"unsupported","feature":"temperature"}, und es wurde nichts ausgegeben. Ohne ihn ging dieselbe Warnung an den globalen Warnungs-Logger. Das entspricht der streamText-Referenz, wonach Warnungen diesen Logger überspringen, wenn onWarning gesetzt ist.
@ai-sdk/provider-utils@5.0.84 (25. November, UTC) behob ein Absturzrisiko. Zuvor pufferte parseJsonEventStream ein Server-Sent-Event ohne Größenlimit, sodass ein Stream, der ein Event nie abschloss, Speicher auffressen konnte. Nun ist ein einzelnes Event auf 67.108.864 Zeichen begrenzt. Laut den Release Notes gilt diese Obergrenze auch für die Streams, die useChat und useCompletion lesen. 5.0.85 einen Tag später ließ die Responses-Modelle von OpenAI und xAI Events von bis zu 512 MiB zu, weil response.completed jedes Output-Element wiederholt, einschließlich Base64-Bildern.
Wir haben ein SSE-Event durch parseJsonEventStream mit dem Chunk-Schema der UI-Nachricht geschoben:
Für eine Chat-App lautet die praktische Regel, große Payloads aus einzelnen Events herauszuhalten. Wenn ein Tool eine generierte Datei zurückgibt, senden Sie statt Base64 eine URL in der Tool-Ausgabe. In ai@7.0.183 fanden wir keine Option maxEventSize auf DefaultChatTransport, Sie können die Obergrenze also nicht über useChat anheben.
Wenn Sie die Nachrichtenliste und die Zeilen zum Tool-Status lieber nicht selbst bauen möchten: Cuelark UI bietet shadcn-artige AI-Chat-Komponenten, die zu diesem Setup passen.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
By the Cuelark Team. Details come from the Vercel AI SDK release notes and docs, checked on 27 November 2026. We didn't call a real model. Everything below ran against MockLanguageModelV4 from ai/test on ai@7.0.183, so this tests the wiring your app sees, not how any model behaves.
A tool-calling chat can end for very different reasons. The model gave its answer. Your step limit kicked in halfway through a task. A tool is waiting for the user to approve it. Or the model called a tool that only the browser can run. Until now you had to guess which one happened from finishReason, and that field only describes the last model call. A loop that hits its step limit still says tool-calls.
ai@7.0.181, published November 23 (UTC), adds stoppedBy to the generateText and streamText results, the onEnd callback, and the final finish stream part. Per the AI SDK loop control docs it has four values:
The same release adds a per-call onWarning callback. The docs say WorkflowAgent and HarnessAgent don't report stoppedBy yet.
stoppedBy lives on the server-side stream. The UI message stream's finish chunk that useChat reads carries finishReason and messageMetadata, but not stoppedBy. So pass it through message metadata:
// app/api/chat/route.ts import { openai } from '@ai-sdk/openai'; import { streamText, convertToModelMessages, tool, isStepCount, type UIMessage, type StoppedBy, type FinishReason, } from 'ai'; import { z } from 'zod'; export type ChatMessage = UIMessage < { stoppedBy?: StoppedBy; finishReason?: FinishReason } >; const tools = { searchDocs: tool ( { description: 'Search the docs', inputSchema: z. object ( { query: z. string ( ) } ), execute: async ( { query } ) => ( { hits: [ `result for ${query}` ] } ), } ), deleteDraft: tool ( { description: 'Delete a draft', inputSchema: z. object ( { id: z. string ( ) } ), needsApproval: true, execute: async ( { id } ) => ( { deleted: id } ), } ), askUser: tool ( { description: 'Ask the user a clarifying question', inputSchema: z. object ( { question: z. string ( ) } ), // no execute: the browser answers this one } ), }; export async function POST ( req: Request ) { const { messages }: { messages: ChatMessage [ ] } = await req. json ( ); const result = streamText ( { model: openai ( 'gpt-6.2-sol' ), messages: await convertToModelMessages ( messages ), tools, stopWhen: isStepCount ( 3 ), onWarning: ( { warnings } ) => console. warn ( 'model warnings', warnings ), } ); return result. toUIMessageStreamResponse < ChatMessage > ( { messageMetadata: ( { part } ) => part. type === 'finish'? { stoppedBy: part. stoppedBy, finishReason: part. finishReason }: undefined, } ); } Enter fullscreen mode Exit fullscreen mode On the client, useChat<ChatMessage>() gives you message.metadata.stoppedBy on the last assistant message. Only two cases need new UI:
export function LoopStatus ( { message, onContinue }: { message: ChatMessage; onContinue: ( ) => void } ) { const { stoppedBy, finishReason } = message. metadata?? { }; if ( stoppedBy === 'stop-condition' ) { return < p > Paused after the step limit. < button onClick = { onContinue } > Keep going </ button ></ p >; } if ( stoppedBy === 'model' && finishReason === 'length' ) { return < p > The answer hit the length limit and may be cut off. </ p >; } return null; // approval and client-side tools already show up as tool parts } Enter fullscreen mode Exit fullscreen mode We wire onContinue to sendMessage({ text: 'Continue where you left off.' }). The approval and client-side tool cases already appear as tool parts in approval-requested and input-available states, so those parts can render their own buttons.
We ran six scripted scenarios through the route handler above (with the mock model swapped in) and read each response the way useChat does, using parseJsonEventStream and readUIMessageStream.
The last three rows are the point. finishReason is the same in all three, while stoppedBy tells them apart. The metadata arrived on the client every time.
The sixth scenario had the mock return a provider warning. With onWarning set, the callback got {"type":"unsupported","feature":"temperature"} and nothing was printed. Without it, the same warning went to the global warning logger. That matches the streamText reference, which says warnings skip that logger when onWarning is set.
@ai-sdk/provider-utils@5.0.84 (November 25, UTC) fixed a crash risk. Before, parseJsonEventStream buffered a server-sent event with no size limit, so a stream that never finished an event could use up memory. Now a single event is capped at 67,108,864 characters. Per the release notes, this cap also covers the streams useChat and useCompletion read. 5.0.85 a day later let the OpenAI and xAI Responses models accept events of up to 512 MiB, because response.completed repeats every output item, including base64 images.
We pushed one SSE event through parseJsonEventStream with the UI message chunk schema:
For a chat app, the practical rule is to keep big payloads out of single events. If a tool returns a generated file, send a URL in the tool output instead of base64. In ai@7.0.183, we found no maxEventSize option on DefaultChatTransport, so you can't raise the cap from useChat.
If you'd rather not build the message list and tool-status rows yourself, Cuelark UI has shadcn-style AI chat components that fit this setup.