ai icon indicating copy to clipboard operation
ai copied to clipboard

toUIMessageStream onError is called twice for one invalid tool call, with different argument types

Open uditkumar01 opened this issue 1 month ago • 4 comments

Description

When the model emits a tool call with invalid input, the onError callback passed to toUIMessageStream is called twice for that one failure, with two different argument types:

  1. With the error object (InvalidToolInputError or NoSuchToolError), when the invalid tool-call part is converted to a tool-input-error chunk.
  2. With a string (the message of the same error), when the tool-error part that follows the invalid call is converted to a tool-output-error chunk.

A callback that logs or reports errors records the failure twice. A callback that checks the error type, for example with InvalidToolInputError.isInstance(error), matches the first call and misses the second, so the two chunks for the same tool call can end up with different error text.

Expected: onError is called once per invalid tool call, with the original error object, and both chunks carry the text it returned.

This is a different cause from #14726, which is about stream error parts.

I have a fix with a test and can open a pull request. toUIMessageStream remembers the error text returned for the invalid tool call and reuses it for the tool error with the same toolCallId.

Reproduction

Save as repro.mjs in a new directory. It uses a mocked model, so no credentials are needed.

npm init -y
npm install [email protected]
node repro.mjs
import { streamText, tool, jsonSchema } from 'ai';
import { MockLanguageModelV4, simulateReadableStream } from 'ai/test';

const usage = {
  inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },
  outputTokens: { total: 1, text: 1, reasoning: undefined },
};

const result = streamText({
  model: new MockLanguageModelV4({
    doStream: async () => ({
      stream: simulateReadableStream({
        chunks: [
          { type: 'stream-start', warnings: [] },
          {
            type: 'tool-call',
            toolCallId: 'call-1',
            toolName: 'saveNote',
            input: '{"text":"hel',
          },
          {
            type: 'finish',
            finishReason: { unified: 'tool-calls', raw: 'tool_use' },
            usage,
          },
        ],
      }),
    }),
  }),
  prompt: 'save a note',
  tools: {
    saveNote: tool({
      inputSchema: jsonSchema({
        type: 'object',
        properties: { text: { type: 'string' } },
        required: ['text'],
      }),
      execute: async () => 'saved',
    }),
  },
});

let calls = 0;

const stream = result.toUIMessageStream({
  onError: error => {
    calls++;
    console.log(
      `onError call ${calls}:`,
      typeof error === 'string' ? 'string' : error?.constructor?.name,
    );
    return 'invalid tool call';
  },
});

for await (const chunk of stream) {
  if (chunk.type.startsWith('tool-')) {
    console.log('chunk:', chunk.type);
  }
}

console.log('total onError calls:', calls);

Actual output:

onError call 1: InvalidToolInputError
chunk: tool-input-error
onError call 2: string
chunk: tool-output-error
total onError calls: 2

Expected output:

onError call 1: InvalidToolInputError
chunk: tool-input-error
chunk: tool-output-error
total onError calls: 1

AI SDK Version

  • ai: 7.0.137

uditkumar01 avatar Oct 11 '26 10:10 uditkumar01

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete failure in existing behavior: one tool-call error is reported twice and inconsistently, causing duplicate logging and potentially inconsistent chunk error text.

Evidence

  • A single invalid tool call causes toUIMessageStream's onError callback to run twice.
  • The duplicate invocations use inconsistent argument types: first an InvalidToolInputError, then the same error represented as a string.
  • The issue includes a reproducible mocked-model script, actual output, expected output, and the affected version ([email protected]).

ai-sdk-factory[bot] avatar Oct 11 '26 10:10 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • packages/ai/package.json reports ai version 7.0.137, matching the reported version; all mocked APIs required by the report exist on the target checkout.
  • examples/ai-functions/src/reproduction/issue-22913-to-ui-message-stream-invalid-tool-call.ts reproduces both variants: malformed input passes an InvalidToolInputError then a string to onError, while an unknown tool passes a NoSuchToolError then a string.
  • Each single invalid tool call invoked onError twice and produced different tool-input-error and tool-output-error text; the expected behavior is one callback with the original error object and reuse of its returned text for both chunks, preventing duplicate reporting and inconsistent formatting.

ai-sdk-factory[bot] avatar Oct 11 '26 10:10 ai-sdk-factory[bot]

Bugfix - AI SDK 7

Created bugfix and opened PR: #22925

Root Cause

streamText emits both an invalid tool-call part containing the original error object and a following tool-error part containing its serialized message; toUIMessageStream independently passed both through onError, as confirmed by the original reproduction.

Summary

Cached the formatted error text by tool call ID and reused it for the corresponding tool-output-error chunk, while preserving existing handling for unrelated and provider-executed errors. Added a patch changeset.

Testing

Added regression coverage verifying one callback with the original error object and identical error text in both generated tool error chunks.

ai-sdk-factory[bot] avatar Oct 11 '26 11:10 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
ai 7.0.168 github npm
@ai-sdk/alibaba 2.0.87 github npm
@ai-sdk/amazon-bedrock 5.0.137 github npm
@ai-sdk/angular 3.0.168 github npm
@ai-sdk/anthropic 4.0.101 github npm
@ai-sdk/anthropic-aws 2.0.94 github npm
@ai-sdk/assemblyai 3.0.79 github npm
@ai-sdk/azure 4.0.121 github npm
@ai-sdk/baseten 2.1.67 github npm
@ai-sdk/black-forest-labs 2.0.81 github npm
@ai-sdk/bytedance 2.0.82 github npm
@ai-sdk/cartesia 3.0.73 github npm
@ai-sdk/cerebras 3.0.89 github npm
@ai-sdk/code-mode 1.0.125 github npm
@ai-sdk/cohere 4.0.80 github npm
@ai-sdk/deepgram 3.1.50 github npm
@ai-sdk/deepinfra 3.0.89 github npm
@ai-sdk/deepseek 3.0.83 github npm
@ai-sdk/devtools 1.0.71 github npm
@ai-sdk/elevenlabs 3.0.83 github npm
@ai-sdk/fal 3.0.80 github npm
@ai-sdk/fireworks 3.0.92 github npm
@ai-sdk/fish-audio 3.0.56 github npm
@ai-sdk/gateway 4.0.141 github npm
@ai-sdk/gladia 3.0.79 github npm
@ai-sdk/gmicloud 3.0.60 github npm
@ai-sdk/google 4.0.116 github npm
@ai-sdk/google-vertex 5.0.136 github npm
@ai-sdk/groq 4.0.80 github npm
@ai-sdk/harness 1.0.179 github npm
@ai-sdk/harness-acp 1.0.119 github npm
@ai-sdk/harness-claude-code 1.0.183 github npm
@ai-sdk/harness-cline 1.0.107 github npm
@ai-sdk/harness-codex 1.0.181 github npm
@ai-sdk/harness-cursor 1.0.94 github npm
@ai-sdk/harness-deepagents 1.0.179 github npm
@ai-sdk/harness-fx 1.0.95 github npm
@ai-sdk/harness-github-copilot 1.0.76 github npm
@ai-sdk/harness-grok-build 1.0.118 github npm
@ai-sdk/harness-opencode 1.0.182 github npm
@ai-sdk/harness-pi 1.0.182 github npm
@ai-sdk/heygen 3.0.21 github npm
@ai-sdk/huggingface 2.0.89 github npm
@ai-sdk/hume 3.0.78 github npm
@ai-sdk/klingai 4.0.81 github npm
@ai-sdk/langchain 3.0.168 github npm
@ai-sdk/llamaindex 3.0.168 github npm
@ai-sdk/luma 3.0.80 github npm
@ai-sdk/mcp 2.0.95 github npm
@ai-sdk/minimax 3.0.78 github npm
@ai-sdk/mistral 4.0.83 github npm
@ai-sdk/moonshotai 3.0.89 github npm
@ai-sdk/open-responses 2.0.84 github npm
@ai-sdk/openai 4.0.113 github npm
@ai-sdk/openai-compatible 3.0.89 github npm
@ai-sdk/otel 1.0.168 github npm
@ai-sdk/parallel 3.0.6 github npm
@ai-sdk/perplexity 5.0.30 github npm
@ai-sdk/policy-opa 1.0.168 github npm
@ai-sdk/prodia 2.0.80 github npm
@ai-sdk/provider-utils 5.0.78 github npm
@ai-sdk/quiverai 2.0.80 github npm
@ai-sdk/react 4.0.172 github npm
@ai-sdk/replicate 3.0.80 github npm
@ai-sdk/revai 3.0.78 github npm
@ai-sdk/rsc 3.0.168 github npm
@ai-sdk/sandbox-just-bash 1.0.179 github npm
@ai-sdk/sandbox-vercel 1.0.179 github npm
@ai-sdk/svelte 5.0.168 github npm
@ai-sdk/tencent 3.0.0 github npm
@ai-sdk/togetherai 3.0.90 github npm
@ai-sdk/tool-bash 1.0.22 github npm
@ai-sdk/tool-web-fetch 1.0.18 github npm
@ai-sdk/topaz 3.0.25 github npm
@ai-sdk/tui 1.0.169 github npm
@ai-sdk/typesafe-ai 3.0.37 github npm
@ai-sdk/valibot 3.0.78 github npm
@ai-sdk/voyage 2.0.79 github npm
@ai-sdk/vue 4.0.168 github npm
@ai-sdk/workflow 2.0.100 github npm
@ai-sdk/workflow-harness 1.0.179 github npm
@ai-sdk/xai 5.0.42 github npm
@ai-sdk/zai 3.0.51 github npm

github-actions[bot] avatar Nov 10 '26 17:11 github-actions[bot]