ai icon indicating copy to clipboard operation
ai copied to clipboard

onFinish and onError aren't getting called in the useChat hook

Open nikitatome opened this issue 1 year ago • 2 comments

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

nikitatome avatar Sep 17 '25 21:09 nikitatome

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"
}

lgrammel avatar Jul 02 '26 09:07 lgrammel

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.

n1ckoates avatar Aug 25 '26 19:08 n1ckoates