assistant message appears twice when using createUIMessageStream & addToolResult
Description
We are trying to implement user confirmations with createUIMessageStream and addToolResult but are observing that after the user sends the confirmation, the assistant message response is recreated with a new id.
This is the backend code:
import {
streamText,
convertToModelMessages,
createUIMessageStream,
pipeUIMessageStreamToResponse,
stepCountIs,
tool,
} from 'ai';
import express, { RequestHandler } from 'express';
import { z } from 'zod';
import {
isSupportedModel,
MODEL_NAME_TO_AI_SDK_MODEL,
SupportedModel,
} from 'contextBuilder/model';
const router = express.Router({});
router.post('/chat/:threadId', (async (req, res) => {
const { messages, modelName } = req.body;
if (!isSupportedModel(modelName)) {
const errorMessage = `unsupported model: ${modelName}`;
res.status(400).send(errorMessage);
return;
}
const model = modelName as SupportedModel;
const modelMessages = convertToModelMessages(messages);
const stream = createUIMessageStream({
execute: async ({ writer }) => {
const result = streamText({
model: MODEL_NAME_TO_AI_SDK_MODEL[model],
messages: modelMessages,
system: 'You are a helpful assistant.',
tools: {
callTool: tool({
inputSchema: z.object({
name: z.string().describe('The name of the person to call.'),
}),
}),
},
stopWhen: stepCountIs(5),
});
writer.merge(result.toUIMessageStream());
},
});
pipeUIMessageStreamToResponse({
response: res,
stream,
});
}) as RequestHandler);
export default router;
On the Frontend we are following this pattern from the v4 documentation:
<button
type="button"
className="rounded bg-blue-500 px-4 py-2 font-bold text-white hover:bg-blue-700"
onClick={(e) => {
e.preventDefault();
addToolResult({
toolCallId,
output: APPROVAL.YES,
});
}}
>
Yes
</button>
With this useChat:
const transport = useMemo(() => {
const apiUrl = `${BACKEND_URL}qnaChat/chat/${threadId}`;
return new DefaultChatTransport({
api: apiUrl,
body: {
modelName,
},
credentials: 'include',
});
}, [threadId, modelName]);
// Initialize useChat with empty messages
const {
messages,
status,
error,
regenerate,
stop,
sendMessage,
setMessages,
addToolResult,
} = useChat({
transport,
experimental_throttle: 100,
});
This is an example of a message that we see on the frontend after adding the tool result:
[ { "parts": [ { "type": "text", "text": "call sam" } ], "id": "XhxEmOVNLMsaYrmw", "role": "user" }, { "id": "c79cFGysd67mVRl0", "role": "assistant", "parts": [ { "type": "step-start" }, { "type": "text", "text": "I'll call Sam for you.", "state": "done" }, { "type": "tool-callTool", "toolCallId": "toolu_01JK1kWkHzHpJWVvdTD2zJGi", "state": "output-available", "input": { "name": "sam" }, "output": "No, denied." } ] }, { "id": "3WO6JsFvt80kQbBS", "role": "assistant", "parts": [ { "type": "step-start" }, { "type": "text", "text": "I'll call Sam for you.", "state": "done" }, { "type": "tool-callTool", "toolCallId": "toolu_01JK1kWkHzHpJWVvdTD2zJGi", "state": "output-available", "input": { "name": "sam" }, "output": "No, denied." }, { "type": "step-start" }, { "type": "text", "text": "It looks like the call to Sam was denied. The system returned "No, denied." This could mean Sam is unavailable, the number is blocked, or there's some other restriction preventing the call from going through.", "state": "done" } ] } ]
AI SDK Version
- ai: 5.0.0-beta.14
Please try passing originalMessages: messages into createUIMessageStream to ensure the id from the last assistant message is reused.
Thanks! That worked.
Identify issue type
Identified as None
Confidence: High
Rationale
This was a usage/configuration support issue rather than a demonstrated SDK defect or request to change the product or documentation.
Evidence
- The duplicate assistant message occurred because
createUIMessageStreamwas called withoutoriginalMessages. - A maintainer recommended passing
originalMessages: messagesso the prior assistant message ID is reused. - The reporter confirmed that this change resolved the issue.