ai icon indicating copy to clipboard operation
ai copied to clipboard

Tool calls skipped for the finish reason stay pending in the UI stream and response messages

Open uditkumar01 opened this issue 1 month ago • 3 comments

Description

Since #19066, tools only run when a model call finishes with stop or tool-calls. When a step finishes with length, error, content-filter or other, the tool calls that were ready to run are skipped, but nothing resolves them. They stay pending for the rest of the turn:

  • The UI message stream sends tool-input-available and then finish. The tool part stays in input-available, so a chat UI shows the tool as running after the stream has ended. onEnd / onFinish receive a responseMessage with that pending part, and it is usually persisted as is.
  • response.messages contains an assistant message with a tool call and no tool message. Sending that history back on the next turn fails on providers that require a result for every tool call.
  • Nothing on the tool part says why it did not run. The finish reason is only reported per step.

The common trigger is parallel tool calling with an output token limit: the model writes a batch of tool calls, hits the limit, and the step finishes with length.

Expected: every tool call that was skipped because of the finish reason is resolved, for example with a tool-error that carries a typed error including the finish reason. The UI part then ends in output-error, and the response messages pair each tool call with a result. Tools without an execute function should stay in input-available, since the client supplies their output.

I have a fix with tests for streamText and generateText and can open a pull request. It adds a ToolCallNotExecutedError (with toolName, toolCallId, finishReason), emits a tool-error for each skipped call, and keeps the current behavior of ending the loop after such a step.

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, readUIMessageStream } 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 },
};

let executed = 0;

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":"hello"}',
          },
          {
            type: 'finish',
            finishReason: { unified: 'length', raw: 'max_tokens' },
            usage,
          },
        ],
      }),
    }),
  }),
  prompt: 'save a note',
  tools: {
    saveNote: tool({
      inputSchema: jsonSchema({
        type: 'object',
        properties: { text: { type: 'string' } },
        required: ['text'],
      }),
      execute: async () => {
        executed++;
        return 'saved';
      },
    }),
  },
});

let message;
for await (const current of readUIMessageStream({
  stream: result.toUIMessageStream(),
})) {
  message = current;
}

const toolPart = message.parts.find(part => part.type === 'tool-saveNote');
const responseMessages = (await result.response).messages;

console.log('finishReason:', await result.finishReason);
console.log('tool executed:', executed);
console.log('UI tool part state:', toolPart.state);
console.log(
  'response message roles:',
  responseMessages.map(m => m.role),
);

Actual output:

finishReason: length
tool executed: 0
UI tool part state: input-available
response message roles: [ 'assistant' ]

Expected output:

finishReason: length
tool executed: 0
UI tool part state: output-error
response message roles: [ 'assistant', 'tool' ]

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 describes a concrete failure in existing streamText/generateText behavior: skipped tool calls remain unresolved and produce invalid or misleading UI and message state. The proposed typed error is a suggested fix for that failure, so the issue is a bug rather than a feature request.

Evidence

  • With [email protected], executable tool calls skipped after a length finish remain in the UI state input-available after the stream ends.
  • The generated response history contains an assistant tool call without a corresponding tool result, which can make subsequent provider requests fail.
  • The issue includes a self-contained mocked-model reproduction and contrasts actual output with expected resolved error state and paired tool response.

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 is version 7.0.137, matching the reported setup; the mocked reproduction requires no provider credentials or user configuration.
  • Added examples/ai-functions/src/reproduction/issue-22912-skipped-tool-calls.ts, covering parallel executable calls with length, error, content-filter, and other finish reasons in both streamText and generateText.
  • For every tested finish reason, executable tools were correctly not invoked, but no finish-reason-bearing tool-error was produced and response.messages contained only the assistant message instead of a paired tool message.
  • In streamText, the final UI message and the onEnd response message left both tool parts in input-available instead of the expected terminal output-error state.
  • Tools without an execute function retained the expected client-managed behavior: input-available in the UI with no synthetic tool error or tool response message.

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

Bugfix - AI SDK 7

Created bugfix and opened PR: #22932

Root Cause

The finish-reason execution gate returned without emitting terminal outputs for queued executable tool calls; downstream UI and response-message conversion therefore had no tool errors to resolve those calls.

Summary

Added a public ToolCallNotExecutedError carrying the tool name, call ID, and finish reason; generateText and streamText now emit tool errors for skipped executable calls while leaving client-managed tools pending and ending the generation loop.

Testing

Added regression coverage for generateText, streamText, and streamed tool execution across length, error, content-filter, and other finish reasons, including client-managed tool behavior.

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