ai icon indicating copy to clipboard operation
ai copied to clipboard

Duplicate toolCallId across steps causes readUIMessageStream to overwrite earlier tool parts

Open wangliang1996 opened this issue 4 months ago • 9 comments

Description

When multiple model steps are aggregated into a single UIMessage, a provider may return the same response-scoped tool call ID in more than one step. The AI SDK UI stream reducer currently looks up tool parts by toolCallId across the entire message, so a later tool call overwrites the earlier tool part instead of appending a new one.

This is reproducible with Amazon Bedrock's OpenAI-compatible Responses API (bedrock-mantle) using openai.gpt-5.6-sol and openai.gpt-5.5:

step 1: toolCallId=call_0, provider itemId=fc_227af95f253a54439ff537bed01fcf05
step 2: toolCallId=call_0, provider itemId=fc_c30b04930925594cbf2ca24deae09db9

Both tools execute successfully and both step results are present in the core streamText result. However, after toUIMessageStream() / readUIMessageStream(), the final UI message contains only one tool part: the part from step 2.

Expected behavior:

  • The final UIMessage contains two tool parts, one for each model step.
  • Provider protocol IDs remain unchanged when tool results are sent back to the provider.

Actual behavior:

  • The final UIMessage contains one tool part.
  • The second call_0 updates the first call_0 part and replaces its input, output, and provider item ID.

The provider item IDs are unique, but they are not available on every tool stream chunk (for example, tool-input-start and tool-output-available only carry toolCallId). A possible fix would be to scope tool-part lookup to the current step, or introduce a separate UI-part identity while preserving the provider's original toolCallId for protocol pairing.

This appears closely related to #7727. That issue was closed with the expectation that providers generate globally unique tool call IDs. In this case, the upstream OpenAI-compatible Responses endpoint returns response-scoped IDs such as call_0 for each response/step, while its fc_... item IDs remain globally unique.

Reproduction

The following minimal reproduction does not require AWS credentials. It feeds the UI reducer the same chunk shape observed from the real Bedrock response:

import { readUIMessageStream } from 'ai';

const chunks = [
  { type: 'start', messageId: 'message-1' },
  { type: 'start-step' },
  {
    type: 'tool-input-available',
    toolCallId: 'call_0',
    toolName: 'recordStep',
    input: { step: 1 },
    providerMetadata: { openai: { itemId: 'fc_step_1' } },
  },
  {
    type: 'tool-output-available',
    toolCallId: 'call_0',
    output: { recorded: 1 },
  },
  { type: 'finish-step' },
  { type: 'start-step' },
  {
    type: 'tool-input-available',
    toolCallId: 'call_0',
    toolName: 'recordStep',
    input: { step: 2 },
    providerMetadata: { openai: { itemId: 'fc_step_2' } },
  },
  {
    type: 'tool-output-available',
    toolCallId: 'call_0',
    output: { recorded: 2 },
  },
  { type: 'finish-step' },
  { type: 'finish' },
];

const stream = new ReadableStream({
  start(controller) {
    for (const chunk of chunks) controller.enqueue(chunk);
    controller.close();
  },
});

let finalMessage;
for await (const message of readUIMessageStream({ stream })) {
  finalMessage = message;
}

const toolParts = finalMessage.parts.filter(
  part => part.type.startsWith('tool-') || part.type === 'dynamic-tool',
);

console.log(toolParts);
console.log(`Expected tool parts: 2; actual: ${toolParts.length}`);

Output with [email protected]:

[
  {
    type: 'tool-recordStep',
    toolCallId: 'call_0',
    state: 'output-available',
    input: { step: 2 },
    output: { recorded: 2 },
    callProviderMetadata: { openai: { itemId: 'fc_step_2' } }
  }
]
Expected tool parts: 2; actual: 1

AI SDK Version

  • ai: 7.0.29
  • @ai-sdk/amazon-bedrock: 5.0.23
  • Node.js: 24.14.0
  • Provider/API: Amazon Bedrock Mantle, OpenAI-compatible Responses API
  • Models reproduced: openai.gpt-5.6-sol, openai.gpt-5.5

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

wangliang1996 avatar Jul 16 '26 08:07 wangliang1996

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete failure in existing UI stream aggregation behavior: tool parts from separate steps are incorrectly conflated and data from the earlier step is overwritten.

Evidence

  • Across multiple model steps, repeated response-scoped toolCallId values cause readUIMessageStream to update an earlier tool part rather than append a new one.
  • Both tool executions are present in the core streamText result, but the final aggregated UIMessage incorrectly contains only the second tool part.
  • The report includes a minimal reproduction on [email protected] showing two expected tool parts but only one actual part.

lgrammel avatar Jul 20 '26 07:07 lgrammel

Bug Reproduction

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • Issue #17347 reproduces on the current [email protected] checkout, so the behavior remains present after the reported [email protected] version.
  • The reproduction at examples/ai-functions/src/reproduction/issue-17347-duplicate-tool-call-id.ts expected two tool parts but received one containing only step 2's input, output, and fc_step_2 provider item ID.
  • packages/ai/src/ui/process-ui-message-stream.ts locates tool parts by toolCallId across the entire message, causing the second step's call_0 chunks to update the first step's part.
  • The credential-free reproduction directly evaluates the final UI aggregation failure; it does not independently rerun the reported live Bedrock tool executions.

Relevant Documentation

  • https://ai-sdk.dev/docs/reference/ai-sdk-ui/read-ui-message-stream
  • https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html
  • https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-openai-gpt-55.html
  • https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-openai-gpt-56-sol.html

lgrammel avatar Jul 20 '26 07:07 lgrammel

Bug Reproduction

Bug was reproduced.

Branch: release-v6.0 PR: successful reproduction pull request

Details

  • On release-v6.0 with [email protected], examples/ai-functions/src/reproduction/issue-17347-duplicate-tool-call-id.ts expected two tool parts but received one.
  • The surviving part contains step 2's input, output, and fc_step_2 item ID; step 1 and fc_step_1 were overwritten.
  • packages/ai/src/ui/process-ui-message-stream.ts searches the entire message for an existing part with the same toolCallId, conflating call_0 across steps.
  • The credential-free reproduction validates UI aggregation and unchanged expected toolCallId values, but does not independently rerun the live Bedrock executions or provider round trip.

Relevant Documentation

  • https://ai-sdk.dev/docs/reference/ai-sdk-ui/read-ui-message-stream
  • https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html
  • https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-openai-gpt-55.html
  • https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-openai-gpt-56-sol.html

lgrammel avatar Jul 21 '26 09:07 lgrammel

Bugfix

Created bugfix and opened PR: #17586

Root Cause

The UI stream reducer searched all message parts by toolCallId, so a later step reused and mutated the first matching part. The credential-free reproduction confirmed two step-local calls were aggregated into one part.

Summary

Scoped tool input aggregation to the current step while retaining explicit fallback handling for outputs that complete previously existing tool calls. Removed reproduction artifacts and added an ai package patch changeset.

Testing

Added a readUIMessageStream regression test asserting that repeated tool call IDs retain both steps' inputs, outputs, and provider metadata.

lgrammel avatar Jul 21 '26 10:07 lgrammel

Bug Reproduction

Bug was reproduced.

Branch: release-v5.0 PR: successful reproduction pull request

Details

  • The release-v5.0 target contains [email protected]; readUIMessageStream and the required multi-step tool chunks are available in packages/ai/src/ui-message-stream/.
  • The reproduction in examples/ai-functions/src/reproduction/issue-17347-duplicate-tool-call-id.ts, supported by examples/ai-functions/package.json, expected two step-local tool parts but received only one.
  • The surviving part contained step 2's input, output, and fc_step_2 provider item ID; step 1 and fc_step_1 were overwritten while the original call_0 remained unchanged.
  • packages/ai/src/ui/process-ui-message-stream.ts searches all message parts by toolCallId, causing the second step's call_0 chunks to mutate the first step's part.
  • The credential-free reproduction confirms the final UI aggregation failure but does not independently rerun the live Bedrock executions or provider round trip.

Relevant Documentation

  • https://ai-sdk.dev/docs/reference/ai-sdk-ui/read-ui-message-stream
  • https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html
  • https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-openai-gpt-55.html
  • https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-openai-gpt-56-sol.html

lgrammel avatar Jul 21 '26 11:07 lgrammel

Backport to v6.0

created: #17603 (clean).

lgrammel avatar Jul 21 '26 12:07 lgrammel

:rocket: Published in:

Package Version
ai 7.0.33 github npm
@ai-sdk/alibaba 2.0.16 github npm
@ai-sdk/amazon-bedrock 5.0.26 github npm
@ai-sdk/angular 3.0.33 github npm
@ai-sdk/anthropic 4.0.17 github npm
@ai-sdk/anthropic-aws 2.0.9 github npm
@ai-sdk/assemblyai 3.0.12 github npm
@ai-sdk/azure 4.0.18 github npm
@ai-sdk/baseten 2.0.14 github npm
@ai-sdk/black-forest-labs 2.0.12 github npm
@ai-sdk/bytedance 2.0.14 github npm
@ai-sdk/cartesia 3.0.6 github npm
@ai-sdk/cerebras 3.0.14 github npm
@ai-sdk/cohere 4.0.12 github npm
@ai-sdk/deepgram 3.0.12 github npm
@ai-sdk/deepinfra 3.0.14 github npm
@ai-sdk/deepseek 3.0.13 github npm
@ai-sdk/elevenlabs 3.0.13 github npm
@ai-sdk/fal 3.0.13 github npm
@ai-sdk/fireworks 3.0.15 github npm
@ai-sdk/gateway 4.0.25 github npm
@ai-sdk/gladia 3.0.12 github npm
@ai-sdk/google 4.0.20 github npm
@ai-sdk/google-vertex 5.0.24 github npm
@ai-sdk/groq 4.0.13 github npm
@ai-sdk/harness 1.0.38 github npm
@ai-sdk/harness-claude-code 1.0.39 github npm
@ai-sdk/harness-codex 1.0.40 github npm
@ai-sdk/harness-deepagents 1.0.37 github npm
@ai-sdk/harness-opencode 1.0.39 github npm
@ai-sdk/harness-pi 1.0.38 github npm
@ai-sdk/huggingface 2.0.14 github npm
@ai-sdk/hume 3.0.12 github npm
@ai-sdk/klingai 4.0.13 github npm
@ai-sdk/langchain 3.0.33 github npm
@ai-sdk/llamaindex 3.0.33 github npm
@ai-sdk/lmnt 3.0.12 github npm
@ai-sdk/luma 3.0.13 github npm
@ai-sdk/mcp 2.0.16 github npm
@ai-sdk/mistral 4.0.14 github npm
@ai-sdk/moonshotai 3.0.17 github npm
@ai-sdk/open-responses 2.0.12 github npm
@ai-sdk/openai 4.0.17 github npm
@ai-sdk/openai-compatible 3.0.14 github npm
@ai-sdk/otel 1.0.33 github npm
@ai-sdk/perplexity 4.0.13 github npm
@ai-sdk/policy-opa 1.0.33 github npm
@ai-sdk/prodia 2.0.13 github npm
@ai-sdk/provider-utils 5.0.12 github npm
@ai-sdk/quiverai 2.0.12 github npm
@ai-sdk/react 4.0.36 github npm
@ai-sdk/replicate 3.0.13 github npm
@ai-sdk/revai 3.0.12 github npm
@ai-sdk/rsc 3.0.33 github npm
@ai-sdk/sandbox-just-bash 1.0.38 github npm
@ai-sdk/sandbox-vercel 1.0.38 github npm
@ai-sdk/svelte 5.0.33 github npm
@ai-sdk/togetherai 3.0.15 github npm
@ai-sdk/tui 1.0.34 github npm
@ai-sdk/valibot 3.0.12 github npm
@ai-sdk/vercel 3.0.14 github npm
@ai-sdk/voyage 2.0.12 github npm
@ai-sdk/vue 4.0.33 github npm
@ai-sdk/workflow 1.0.33 github npm
@ai-sdk/workflow-harness 1.0.38 github npm
@ai-sdk/xai 4.0.18 github npm

github-actions[bot] avatar Jul 21 '26 12:07 github-actions[bot]

Backport to v5.0

created: #17605 (fixed merge).

lgrammel avatar Jul 21 '26 12:07 lgrammel

There is a remaining client-side case after #17586: addToolOutput still updates every part with the matching toolCallId in the last message, including completed calls from earlier steps.

The stream reducer now preserves both parts correctly. But if step 1 has a completed call_0 and step 2 has a pending call_0, completing step 2 through addToolOutput also replaces step 1's output. Reporting it here because it is the same cross-step ID problem.

Reproduced with published [email protected]. No provider or API key is needed. Install [email protected] and [email protected], save as repro.mts, and run with Node 24:

node repro.mts
import { AbstractChat, readUIMessageStream, type ChatState, type UIMessage, type UIMessageChunk } from 'ai';

const chunks: UIMessageChunk[] = [
  { type: 'start', messageId: 'synthetic-message' },
  { type: 'start-step' },
  { type: 'tool-input-available', toolCallId: 'call_0', toolName: 'recordStep', input: { step: 1 } },
  { type: 'tool-output-available', toolCallId: 'call_0', output: { recorded: 1 } },
  { type: 'finish-step' },
  { type: 'start-step' },
  { type: 'tool-input-available', toolCallId: 'call_0', toolName: 'recordStep', input: { step: 2 } },
  { type: 'finish-step' },
  { type: 'finish' },
];
let finalMessage: UIMessage | undefined;
for await (const message of readUIMessageStream({ stream: new ReadableStream({ start(controller) {
  for (const chunk of chunks) controller.enqueue(chunk);
  controller.close();
} }) })) finalMessage = message;
if (!finalMessage) throw new Error('Missing message');

// Minimal state container for the same AbstractChat used by framework bindings.
const state: ChatState<UIMessage> = {
  status: 'ready', error: undefined, messages: [finalMessage],
  pushMessage(message) { this.messages.push(message); },
  popMessage() { this.messages.pop(); },
  replaceMessage(index, message) { this.messages[index] = message; },
  snapshot(thing) { return structuredClone(thing); },
};
class SyntheticChat extends AbstractChat<UIMessage> {}
const chat = new SyntheticChat({ state });
await chat.addToolOutput({ tool: 'recordStep', toolCallId: 'call_0', output: { recorded: 2 } });
for (const part of chat.messages[0].parts) {
  if (part.type === 'tool-recordStep') console.log({ input: part.input, output: part.output });
}
// Expected outputs: { recorded: 1 }, { recorded: 2 }.
// Actual outputs:   { recorded: 2 }, { recorded: 2 }.

Actual:

{ input: { step: 1 }, output: { recorded: 2 } }
{ input: { step: 2 }, output: { recorded: 2 } }

Step 1 should retain { recorded: 1 }.

The same overwrite happens with dynamic tools and state: 'output-error'. My local ten-case matrix on Node 22.20.0 and 24.13.0 has four failures for reused IDs and six passing controls (distinct IDs and both outputs arriving through the stream). The reproduction passes strict TypeScript checking.

The lookup is in AbstractChat.addToolOutput in packages/ai/src/ui/chat.ts: both the displayed message and active response use parts.map(updatePart), where updatePart matches only toolCallId. That file is unchanged on main at 12845693d7a6a517dc633d6b6a2e4f5bfd24d2ec (source comparison; runtime tests used the published version).

I used AI assistance to investigate and prepare the reproduction and tests.

brennanbutler01 avatar Sep 17 '26 23:09 brennanbutler01