ai
ai copied to clipboard
onFinish and onError aren't getting called in the useChat hook
Description
Using createUIMessageStream on the server. The response finishes, but the onError and onFinish callbacks are never called.
const {
messages,
status,
error,
regenerate,
sendMessage,
setMessages,
addToolResult,
} = useChat({
chat,
experimental_throttle: 100,
onError: (err) => {
console.log('error', err);
},
onFinish: ({ isDisconnect, isAbort, isError, message, messages }) => {
console.log('isDisconnect', isDisconnect);
console.log('isAbort', isAbort);
console.log('isError', isError);
},
});
AI SDK Version
- ai: 5.0.39
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Identify issue type
{
"evidence": [
"Reporter says `useChat` `onError` and `onFinish` callbacks are never called.",
"They provide a code snippet using `useChat` callbacks and state the server stream response finishes.",
"Affected version is `ai` 5.0.39."
],
"rationale": "This describes a concrete current behavior where documented/expected callbacks in `useChat` fail to execute when the stream completes, so it is a bug report.",
"type": "bug",
"confidence": "high"
}
This is working as intended. When you pass an existing chat instance to useChat, the other hook options are ignored. The Chat instance owns lifecycle callbacks such as onFinish and onError.
The API reference documents this under the chat parameter: “If provided, other parameters are ignored.”
Configure the callbacks when creating the shared Chat:
const chat = new Chat({
onFinish: event => {
// Runs when the response finishes.
},
onError: error => {
// Runs when the request fails.
},
});
const helpers = useChat({ chat });
Alternatively, remove the chat option and pass the callbacks directly to useChat.