ai icon indicating copy to clipboard operation
ai copied to clipboard

streamText calls onInputAvailable with invalid tool input

Open brennanbutler01 opened this issue 2 months ago • 6 comments

Description

streamText calls a tool's onInputAvailable callback even when the input failed its inputSchema validation. The callback receives the rejected input using the schema's inferred TypeScript type.

For example, with value: z.string(), the callback receives { value: 42 }. Calling input.value.toUpperCase() then throws and terminates the stream. generateText correctly skips the callback and produces a tool error for the same input. ToolLoopAgent.stream is also affected.

Expected: only successfully validated or repaired input reaches onInputAvailable. Invalid calls should retain their tool error so the normal recovery flow can continue.

The streaming callback helper invokes onInputAvailable without checking chunk.invalid. A possible fix is to skip that callback for invalid calls while retaining the input-start/input-delta events and the tool error.

I checked the related callback-order fix #17393 and the custom-validation request #12633; they address different behavior. I can send a regression test or a small PR if useful.

Reproduction

No API key or provider request is needed. In an empty directory:

npm init -y
npm install [email protected] [email protected]

Save this as repro.mts and run node repro.mts with Node 24:

import { generateText, simulateReadableStream, streamText, tool } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';

const usage = {
  inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
  outputTokens: { total: 1, text: 1, reasoning: 0 },
};
const model = new MockLanguageModelV4({
  doGenerate: {
    content: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'echo', input: '{"value":42}' }],
    finishReason: { unified: 'tool-calls', raw: 'tool-calls' },
    usage, warnings: [],
  },
  doStream: async () => ({
    stream: simulateReadableStream({
      chunks: [
        { type: 'stream-start', warnings: [] },
        { type: 'tool-input-start', id: 'call-1', toolName: 'echo' },
        { type: 'tool-input-delta', id: 'call-1', delta: '{"value":42}' },
        { type: 'tool-input-end', id: 'call-1' },
        { type: 'tool-call', toolCallId: 'call-1', toolName: 'echo', input: '{"value":42}' },
        { type: 'finish', finishReason: { unified: 'tool-calls', raw: 'tool-calls' }, usage },
      ],
    }),
  }),
});
const tools = {
  echo: tool({
    inputSchema: z.object({ value: z.string() }),
    onInputAvailable: ({ input }) => {
      console.log('onInputAvailable received:', input);
      console.log(input.value.toUpperCase()); // TypeScript accepts this: value is a string.
    },
    execute: async ({ value }) => value,
  }),
};

const generated = await generateText({ model, tools, prompt: 'Echo a value.' });
console.log('generateText: invalid =', generated.toolCalls[0].invalid);

const streamed = streamText({ model, tools, prompt: 'Echo a value.', onError: () => {} });
try {
  for await (const part of streamed.fullStream) {
    if (part.type === 'error') console.log('streamText error:', part.error);
  }
} catch (error) {
  console.log('streamText threw:', error instanceof Error ? error.message : error);
}

Output:

generateText: invalid = true
onInputAvailable received: { value: 42 }
streamText threw: input.value.toUpperCase is not a function

The reproduction passes strict TypeScript checking. Additional local regression cases reproduce this with malformed JSON and with repair returning null; valid and successfully repaired inputs work.

Prepared with AI assistance for investigation, reproduction code, and local verification.

AI SDK Version

  • ai: 7.0.101 (unmodified npm package)
  • zod: 4.4.3
  • Node.js: 24.13.0, macOS arm64
  • Also inspected main at 6dcd923799d2c663dff348927790c7967ce597dc: the relevant callback helper is unchanged. Main was not built or runtime-tested.

Code of Conduct

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

brennanbutler01 avatar Sep 17 '26 08:09 brennanbutler01

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete inconsistency and runtime failure in existing streaming tool behavior: schema-invalid input reaches a typed callback and can terminate the stream instead of preserving the normal tool-error recovery flow.

Evidence

  • streamText invokes onInputAvailable after inputSchema validation has failed, passing data that violates the callback's inferred TypeScript type.
  • The same invalid input is handled correctly by generateText, while streaming throws when the callback treats the value as the promised string type.
  • The issue includes a deterministic reproduction using MockLanguageModelV4 and identifies that the callback helper does not check chunk.invalid.

ai-sdk-factory[bot] avatar Sep 17 '26 08:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • On main at 6dcd923799, streamText passed schema-invalid input, malformed JSON, and input rejected after repairToolCall returned null to the typed onInputAvailable callback; calling input.value.toUpperCase() terminated each stream before its normal tool-error recovery event.
  • ToolLoopAgent.stream exhibited the same invalid callback invocation and stream termination.
  • generateText correctly skipped the callback and retained the invalid call as a tool-error; valid and successfully repaired streaming inputs also completed correctly.
  • packages/ai/src/generate-text/invoke-tool-callbacks-from-stream.ts invokes onInputAvailable without checking the parsed tool-call chunk's invalid flag, contrary to the documented validated-input contract.
  • The reproduction uses the supported current setup from packages/ai/package.json (ai 7.0.105, Node.js 22.23.2, and the Zod v4 compatibility export) and rules out an unsupported version or peer-dependency configuration.
  • Runnable artifact examples/ai-functions/src/reproduction/issue-20947.ts expects invalid inputs to skip onInputAvailable, preserve input lifecycle events, and reach tool-error recovery.

Relevant Documentation

  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling

ai-sdk-factory[bot] avatar Sep 17 '26 08:09 ai-sdk-factory[bot]

Bugfix - AI SDK 7

Created bugfix and opened PR: #20955

Root Cause

invokeToolCallbacksFromStream invoked onInputAvailable for every tool-call chunk without checking its invalid flag; the reproduction and new regression test confirmed invalid chunks still triggered the callback.

Summary

Skipped onInputAvailable for invalid streamed tool calls while preserving input lifecycle events and tool-error recovery, and added an ai package patch changeset.

Testing

Added regression coverage proving invalid tool calls pass through the stream and retain onInputStart/onInputDelta without invoking onInputAvailable.

ai-sdk-factory[bot] avatar Sep 17 '26 10:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 5

Issue report appears invalid.

Target branch: release-v5.0

  • Issue #20947 targets AI SDK 7.0.101 and requires MockLanguageModelV4 and ToolLoopAgent, while packages/ai/package.json identifies the target branch as AI SDK 5.0.259.
  • packages/ai/test/index.ts exports MockLanguageModelV2 but no V4 model, and packages/ai/src/agent/index.ts exports Experimental_Agent rather than ToolLoopAgent.
  • packages/ai/src/generate-text/run-tools-transformation.ts already emits a tool-error and exits the invalid-call branch before invoking onInputAvailable, so the reported AI SDK 7 callback path does not exist on this target branch.

Relevant Documentation

  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
  • https://ai-sdk.dev/docs/migration-guides/migration-guide-6-0

ai-sdk-factory[bot] avatar Sep 17 '26 20:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 6

Bug could not be reproduced.

Target branch: release-v6.0

  • The runnable artifact examples/ai-functions/src/reproduction/issue-20947.ts covers schema-invalid input, malformed JSON, repair returning null, valid input, successful repair, generateText, streamText, and ToolLoopAgent.stream.
  • On target package ai 6.0.285 with Node.js 22.23.2 and Zod 3.25.76's v4 compatibility export, invalid streamed inputs skipped onInputAvailable, retained input lifecycle events, produced tool-error, and did not terminate the stream.
  • The reported behavior—typed invalid input reaching onInputAvailable and terminating streaming—was not observed in either streamText or ToolLoopAgent.stream.
  • Valid and successfully repaired inputs reached onInputAvailable; generateText skipped the callback and retained the invalid tool error as expected.
  • packages/ai/src/generate-text/run-tools-transformation.ts handles toolCall.invalid and exits before invoking onInputAvailable; the AI SDK 7 callback helper named in the issue is absent from release-v6.0.

Relevant Documentation

  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
  • https://ai-sdk.dev/docs/reference/ai-sdk-core/tool
  • https://ai-sdk.dev/docs/migration-guides/migration-guide-6-0

Closed PR: cannot-reproduce investigation pull request

ai-sdk-factory[bot] avatar Sep 17 '26 20:09 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
ai 7.0.106 github npm
@ai-sdk/alibaba 2.0.50 github npm
@ai-sdk/amazon-bedrock 5.0.87 github npm
@ai-sdk/angular 3.0.106 github npm
@ai-sdk/anthropic 4.0.57 github npm
@ai-sdk/anthropic-aws 2.0.49 github npm
@ai-sdk/assemblyai 3.0.44 github npm
@ai-sdk/azure 4.0.74 github npm
@ai-sdk/baseten 2.1.30 github npm
@ai-sdk/black-forest-labs 2.0.45 github npm
@ai-sdk/bytedance 2.0.47 github npm
@ai-sdk/cartesia 3.0.39 github npm
@ai-sdk/cerebras 3.0.52 github npm
@ai-sdk/code-mode 1.0.63 github npm
@ai-sdk/cohere 4.0.45 github npm
@ai-sdk/deepgram 3.1.15 github npm
@ai-sdk/deepinfra 3.0.52 github npm
@ai-sdk/deepseek 3.0.48 github npm
@ai-sdk/elevenlabs 3.0.45 github npm
@ai-sdk/fal 3.0.45 github npm
@ai-sdk/fireworks 3.0.55 github npm
@ai-sdk/fish-audio 3.0.22 github npm
@ai-sdk/gateway 4.0.86 github npm
@ai-sdk/gladia 3.0.44 github npm
@ai-sdk/gmicloud 3.0.23 github npm
@ai-sdk/google 4.0.75 github npm
@ai-sdk/google-vertex 5.0.87 github npm
@ai-sdk/groq 4.0.45 github npm
@ai-sdk/harness 1.0.116 github npm
@ai-sdk/harness-acp 1.0.54 github npm
@ai-sdk/harness-claude-code 1.0.120 github npm
@ai-sdk/harness-cline 1.0.43 github npm
@ai-sdk/harness-codex 1.0.118 github npm
@ai-sdk/harness-cursor 1.0.29 github npm
@ai-sdk/harness-deepagents 1.0.116 github npm
@ai-sdk/harness-fx 1.0.29 github npm
@ai-sdk/harness-github-copilot 1.0.11 github npm
@ai-sdk/harness-grok-build 1.0.53 github npm
@ai-sdk/harness-opencode 1.0.118 github npm
@ai-sdk/harness-pi 1.0.118 github npm
@ai-sdk/huggingface 2.0.52 github npm
@ai-sdk/hume 3.0.44 github npm
@ai-sdk/klingai 4.0.46 github npm
@ai-sdk/langchain 3.0.106 github npm
@ai-sdk/llamaindex 3.0.106 github npm
@ai-sdk/luma 3.0.45 github npm
@ai-sdk/mcp 2.0.53 github npm
@ai-sdk/minimax 3.0.34 github npm
@ai-sdk/mistral 4.0.47 github npm
@ai-sdk/moonshotai 3.0.53 github npm
@ai-sdk/open-responses 2.0.48 github npm
@ai-sdk/openai 4.0.70 github npm
@ai-sdk/openai-compatible 3.0.52 github npm
@ai-sdk/otel 1.0.106 github npm
@ai-sdk/perplexity 4.0.47 github npm
@ai-sdk/policy-opa 1.0.106 github npm
@ai-sdk/prodia 2.0.45 github npm
@ai-sdk/provider-utils 5.0.44 github npm
@ai-sdk/quiverai 2.0.44 github npm
@ai-sdk/react 4.0.109 github npm
@ai-sdk/replicate 3.0.45 github npm
@ai-sdk/revai 3.0.44 github npm
@ai-sdk/rsc 3.0.106 github npm
@ai-sdk/sandbox-just-bash 1.0.116 github npm
@ai-sdk/sandbox-vercel 1.0.116 github npm
@ai-sdk/svelte 5.0.106 github npm
@ai-sdk/togetherai 3.0.53 github npm
@ai-sdk/tui 1.0.107 github npm
@ai-sdk/typesafe-ai 3.0.3 github npm
@ai-sdk/valibot 3.0.44 github npm
@ai-sdk/voyage 2.0.44 github npm
@ai-sdk/vue 4.0.106 github npm
@ai-sdk/workflow 2.0.37 github npm
@ai-sdk/workflow-harness 1.0.116 github npm
@ai-sdk/xai 5.0.3 github npm
@ai-sdk/zai 3.0.14 github npm

github-actions[bot] avatar Sep 18 '26 05:09 github-actions[bot]