useChat not reacting to transport changes after initialization
Description
If I change the modelName through my UI I can see that the transport is changed correctly, however these changes aren't getting updated through useChat. In my backend the modelName that I receive is still the old value.
For example, if I start a chat, and then change to a different model for a subsequent message, I see that message was still sent through the original model at the time that useChat was mounted. If I refresh the page, then it uses the correct model.
const { modelName, updateModelName } = useModelName();
const transport = useMemo(() => {
const apiUrl = `${BACKEND_URL}qnaChat/chat/${threadId}`;
return new DefaultChatTransport({
api: apiUrl,
body: {
modelName: modelName === 'sonnet_4_reasoning' ? 'sonnet_4' : modelName,
reasoning: modelName === 'sonnet_4_reasoning',
},
credentials: 'include',
});
}, [threadId, modelName]);
// Initialize useChat with empty messages
const {
messages,
status,
error,
regenerate,
stop,
sendMessage,
setMessages,
addToolResult,
} = useChat({
messages: [] as UIMessage[],
transport,
experimental_throttle: 100,
});
AI SDK Version
- ai: 5.0.0-beta.25
+1
Hey! Check out these docs: https://v5.ai-sdk.dev/docs/troubleshooting/use-chat-custom-request-options
tldr; suggested approach is to pass any dynamic values on the request via sendMessage
Thanks @nicoalbanese that works for sendMessage! However we also need a way for addToolResult to pass any dynamic values.
Yes but how do you update the api url dynamically? The url should switch from /chat to /chat/{id}
Just ran into the same issue. My chat transport depends on a config which is fetched async (e.g. the API url) and I can't add that into my custom transport.
You can create a new instance of useChat is by setting and changing the id of useChat, so another way of solving this can look like this:
const config = useConfig();
const transport = useMemo(() => config && new CustomTextStreamChatTransport(config), [config]);
useChat({ id: config ? 'okay-lets-go' : undefined, transport })
Identify issue type
Identified as Bug
Confidence: Medium
Rationale
The report describes concrete stale behavior in the current useChat API: a newly supplied transport is ignored after initialization. Although dynamic request options can work around some cases, the comments identify flows where the stale transport still causes incorrect requests.
Evidence
- A memoized
DefaultChatTransportchanges whenmodelNamechanges, butuseChatcontinues sending the original model value until the page is refreshed. - A maintainer recommends passing dynamic values through
sendMessage, indicating a supported workaround rather than transport reactivity. - Follow-up comments note that the workaround does not cover
addToolResultor dynamically changing the API URL.