ai icon indicating copy to clipboard operation
ai copied to clipboard

streamText does not enforce `toolChoice: 'required'`

Open canblmz1 opened this issue 2 months ago • 8 comments

Description

generateText() enforces required and specifically-selected tool choices: when a provider ignores toolChoice: 'required' and returns text without a structured tool call, generateText() rejects with ToolChoiceViolationError (AI_ToolChoiceViolationError), added in #19872.

streamText() exposes and forwards the same toolChoice setting but has no equivalent response-side check. Under the same semantic violation, streamText() completes successfully — finishReason: 'stop', the text is delivered, onFinish runs, onError is never called, and no ToolChoiceViolationError is surfaced.

The result is different SDK behavior for the same tool-choice contract between the two APIs.

Actual behavior

toolChoice: 'required', one tool defined, provider streams only text (stream-start → text-start → text-delta: "No tool call." → text-end → finish: stop):

streamText() resolves successfully
finishReason = 'stop'
text = 'No tool call.'
onFinish is called
onError is not called
no ToolChoiceViolationError is surfaced
provider called once

The equivalent generateText() call on the same revision rejects with AI_ToolChoiceViolationError.

Expected behavior

streamText() should not complete successfully when an enforced tool choice ('required' or a specific tool) is violated. The violation should be surfaced consistently with the ToolChoiceViolationError semantics already used by generateText(). The exact stream error-propagation shape is for maintainers to decide, consistent with existing streaming error conventions.

Valid control (unaffected)

When the stream contains a valid structured tool call under toolChoice: 'required', streamText() completes normally (finishReason: 'tool-calls', no error).

Existing precedent

  • #8992 — original report that toolChoice: 'required' was not enforced (generateText).
  • #19872 — merged fix that added ToolChoiceViolationError enforcement to generateText() only (packages/ai/src/generate-text/generate-text.ts); stream-text.ts was not part of that change.

Related factory PRs #20327 and #20328 touch streamText tool-choice state as part of the Groq/Google structured-output work on the v5/v6 release branches. I checked those changes before filing; they do not add the general streamText response-side enforcement described here.

Source pointers (main @ c3c189c068baefe62808b4eca5432fe092dc37cb)

packages/ai/src/generate-text/generate-text.ts        enforces toolChoice, throws ToolChoiceViolationError
packages/ai/src/generate-text/stream-text.ts          forwards toolChoice, no response-side enforcement
packages/ai/src/error/tool-choice-violation-error.ts  existing error class

Searched issues, PRs, and recent commits for streaming-specific tool-choice enforcement — nothing covers this gap.

Reproduction

Public API + the repo's MockLanguageModelV4, ai @ main (c3c189c068baefe62808b4eca5432fe092dc37cb, current main at time of reproduction):

import { tool } from '@ai-sdk/provider-utils';
import { convertArrayToReadableStream } from '@ai-sdk/provider-utils/test';
import { MockLanguageModelV4 } from 'ai/test';
import { streamText } from 'ai';
import { z } from 'zod/v4';

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

const result = streamText({
  model: new MockLanguageModelV4({
    doStream: async () => ({
      stream: convertArrayToReadableStream([
        { type: 'stream-start', warnings: [] },
        { type: 'text-start', id: '1' },
        { type: 'text-delta', id: '1', delta: 'No tool call.' },
        { type: 'text-end', id: '1' },
        { type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage },
      ]),
    }),
  }),
  tools: { tool1: tool({ inputSchema: z.object({ value: z.string() }) }) },
  toolChoice: 'required',
  prompt: 'test-input',
  onError: e => console.log('onError', e),
});

await result.consumeStream();
console.log(await result.finishReason); // 'stop' — onError never fires, no ToolChoiceViolationError

Control with generateText() and the same tools + toolChoice: 'required', a model returning content: [{ type: 'text', text: 'No tool call.' }] with finishReason: 'stop' — rejects with AI_ToolChoiceViolationError on the same revision.

As a failing test in packages/ai/src/generate-text/:

import { tool } from '@ai-sdk/provider-utils';
import { convertArrayToReadableStream } from '@ai-sdk/provider-utils/test';
import { expect, it } from 'vitest';
import { MockLanguageModelV4 } from '../test/mock-language-model-v4';
import { streamText } from './stream-text';
import { z } from 'zod/v4';

it('streamText surfaces a violation for an unsatisfied required tool choice', async () => {
  const errors: unknown[] = [];
  const result = streamText({
    model: new MockLanguageModelV4({
      doStream: async () => ({
        stream: convertArrayToReadableStream([
          { type: 'stream-start', warnings: [] },
          { type: 'text-start', id: '1' },
          { type: 'text-delta', id: '1', delta: 'No tool call.' },
          { type: 'text-end', id: '1' },
          {
            type: 'finish',
            finishReason: { unified: 'stop', raw: 'stop' },
            usage: {
              inputTokens: { total: 3 },
              outputTokens: { total: 10 },
            },
          },
        ]),
      }),
    }),
    tools: { tool1: tool({ inputSchema: z.object({ value: z.string() }) }) },
    toolChoice: 'required',
    prompt: 'test-input',
    onError: e => errors.push(e),
  });

  await result.consumeStream();

  expect(await result.finishReason).not.toBe('stop');
});

On current main this fails: finishReason is 'stop' and errors stays empty.

AI SDK Version

  • ai: main @ c3c189c068baefe62808b4eca5432fe092dc37cb
  • Node: v22.13+

Code of Conduct

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

canblmz1 avatar Sep 07 '26 10:09 canblmz1

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete failure in existing streamText behavior: an enforced tool choice is not validated, unlike the corresponding documented/current behavior of generateText.

Evidence

  • streamText() accepts and forwards toolChoice: 'required' but successfully returns text when no tool call is produced.
  • The equivalent generateText() invocation rejects with the existing ToolChoiceViolationError, creating inconsistent behavior for the same contract.
  • The report includes a reproducible mock stream and a failing test showing finishReason: 'stop' with no onError invocation.

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

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • On main at c3c189c068baefe62808b4eca5432fe092dc37cb, a required-tool stream delivered No tool call., resolved with finishReason: 'stop', invoked onFinish, never invoked onError, and made one provider call.
  • A specifically selected tool1 also completed successfully after the provider returned a structured call to tool2, with no ToolChoiceViolationError.
  • The generateText control rejected with ToolChoiceViolationError, while a valid required-tool stream completed normally with finishReason: 'tool-calls'.
  • Expected behavior is for streamText to surface ToolChoiceViolationError rather than successfully completing when a required or specifically selected tool choice is unsatisfied.
  • Runnable reproduction examples/ai-functions/src/reproduction/issue-20424-stream-text-tool-choice.ts exits non-zero when either enforced tool-choice violation completes without the expected error.

ai-sdk-factory[bot] avatar Sep 07 '26 11:09 ai-sdk-factory[bot]

Bugfix - AI SDK 7

Created bugfix and opened PR: #20426

Root Cause

The streaming response transform forwarded the provider finish event without validating the effective per-step tool choice against streamed tool calls. The reproduction confirmed both required and selected-tool violations completed without errors.

Summary

Tracked normalized streamed response content and tool calls, emitted ToolChoiceViolationError for unsatisfied enforced choices, and prevented semantic violations from triggering stream retries.

Testing

Added regression coverage for required-tool violations, incorrect selected tools, prepareStep overrides, error content, and retry suppression.

ai-sdk-factory[bot] avatar Sep 07 '26 12:09 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
ai 7.0.94 github npm
@ai-sdk/alibaba 2.0.42 github npm
@ai-sdk/amazon-bedrock 5.0.77 github npm
@ai-sdk/angular 3.0.94 github npm
@ai-sdk/anthropic 4.0.50 github npm
@ai-sdk/anthropic-aws 2.0.42 github npm
@ai-sdk/assemblyai 3.0.37 github npm
@ai-sdk/azure 4.0.64 github npm
@ai-sdk/baseten 2.1.23 github npm
@ai-sdk/black-forest-labs 2.0.38 github npm
@ai-sdk/bytedance 2.0.40 github npm
@ai-sdk/cartesia 3.0.32 github npm
@ai-sdk/cerebras 3.0.45 github npm
@ai-sdk/code-mode 1.0.51 github npm
@ai-sdk/cohere 4.0.38 github npm
@ai-sdk/deepgram 3.1.8 github npm
@ai-sdk/deepinfra 3.0.45 github npm
@ai-sdk/deepseek 3.0.40 github npm
@ai-sdk/devtools 1.0.16 github npm
@ai-sdk/elevenlabs 3.0.38 github npm
@ai-sdk/fal 3.0.38 github npm
@ai-sdk/fireworks 3.0.48 github npm
@ai-sdk/fish-audio 3.0.15 github npm
@ai-sdk/gateway 4.0.76 github npm
@ai-sdk/gladia 3.0.37 github npm
@ai-sdk/gmicloud 3.0.16 github npm
@ai-sdk/google 4.0.65 github npm
@ai-sdk/google-vertex 5.0.77 github npm
@ai-sdk/groq 4.0.38 github npm
@ai-sdk/harness 1.0.103 github npm
@ai-sdk/harness-acp 1.0.41 github npm
@ai-sdk/harness-claude-code 1.0.107 github npm
@ai-sdk/harness-cline 1.0.30 github npm
@ai-sdk/harness-codex 1.0.105 github npm
@ai-sdk/harness-cursor 1.0.16 github npm
@ai-sdk/harness-deepagents 1.0.103 github npm
@ai-sdk/harness-fx 1.0.16 github npm
@ai-sdk/harness-grok-build 1.0.40 github npm
@ai-sdk/harness-opencode 1.0.105 github npm
@ai-sdk/harness-pi 1.0.105 github npm
@ai-sdk/huggingface 2.0.45 github npm
@ai-sdk/hume 3.0.37 github npm
@ai-sdk/klingai 4.0.39 github npm
@ai-sdk/langchain 3.0.94 github npm
@ai-sdk/llamaindex 3.0.94 github npm
@ai-sdk/luma 3.0.38 github npm
@ai-sdk/mcp 2.0.46 github npm
@ai-sdk/minimax 3.0.26 github npm
@ai-sdk/mistral 4.0.40 github npm
@ai-sdk/moonshotai 3.0.46 github npm
@ai-sdk/open-responses 2.0.40 github npm
@ai-sdk/openai 4.0.61 github npm
@ai-sdk/openai-compatible 3.0.45 github npm
@ai-sdk/otel 1.0.94 github npm
@ai-sdk/perplexity 4.0.40 github npm
@ai-sdk/policy-opa 1.0.94 github npm
@ai-sdk/prodia 2.0.38 github npm
@ai-sdk/provider 4.0.11 github npm
@ai-sdk/provider-utils 5.0.37 github npm
@ai-sdk/quiverai 2.0.37 github npm
@ai-sdk/react 4.0.97 github npm
@ai-sdk/replicate 3.0.38 github npm
@ai-sdk/revai 3.0.37 github npm
@ai-sdk/rsc 3.0.94 github npm
@ai-sdk/sandbox-just-bash 1.0.103 github npm
@ai-sdk/sandbox-vercel 1.0.103 github npm
@ai-sdk/svelte 5.0.94 github npm
@ai-sdk/togetherai 3.0.46 github npm
@ai-sdk/tui 1.0.95 github npm
@ai-sdk/valibot 3.0.37 github npm
@ai-sdk/voyage 2.0.37 github npm
@ai-sdk/vue 4.0.94 github npm
@ai-sdk/workflow 2.0.25 github npm
@ai-sdk/workflow-harness 1.0.103 github npm
@ai-sdk/xai 4.0.55 github npm
@ai-sdk/zai 3.0.7 github npm

github-actions[bot] avatar Sep 08 '26 19:09 github-actions[bot]

There is still an execution gap after #20426. On [email protected], streamText reports ToolChoiceViolationError but also executes the wrong tool. The equivalent generateText call rejects without executing it.

This is reproducible with a tool that only increments a counter. No API key or network calls are needed.

In an empty directory:

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

Save 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';

let executions = 0;
const tools = {
  selected: tool({ inputSchema: z.object({}), execute: async () => 'selected' }),
  other: tool({
    inputSchema: z.object({}),
    execute: async () => { executions++; return 'other'; },
  }),
};
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: 'other', input: '{}' }],
    finishReason: { unified: 'tool-calls', raw: 'tool-calls' },
    usage, warnings: [],
  },
  doStream: async () => ({ stream: simulateReadableStream({ chunks: [
    { type: 'stream-start', warnings: [] },
    { type: 'tool-call', toolCallId: 'call-1', toolName: 'other', input: '{}' },
    { type: 'finish', finishReason: { unified: 'tool-calls', raw: 'tool-calls' }, usage },
  ] }) }),
});
const options = {
  model, tools, prompt: 'Call the selected tool.',
  toolChoice: { type: 'tool', toolName: 'selected' } as const,
};

try {
  await generateText(options);
} catch (error) {
  console.log('generateText error:', error instanceof Error ? error.name : error);
}
console.log('generateText wrong-tool executions:', executions);

executions = 0;
const result = streamText({
  ...options,
  onError: ({ error }) => {
    console.log('streamText error:', error instanceof Error ? error.name : error);
  },
});
await result.consumeStream();
console.log('streamText wrong-tool executions:', executions);

Actual output:

generateText error: AI_ToolChoiceViolationError
generateText wrong-tool executions: 0
streamText error: AI_ToolChoiceViolationError
streamText wrong-tool executions: 1

Expected: zero wrong-tool executions in both cases.

I also reproduced this through ToolLoopAgent.stream, with the tool choice configured directly or returned from prepareStep. A 16-case local regression suite has four failing streaming cases and 12 passing controls. All cases make one model call, including with streamRetries: 1. The example passes strict TypeScript checking.

The remaining path appears to be:

  • stream-language-model-call.ts emits model-call-end with finishReason: 'tool-calls' before emitting the violation.
  • execute-tools-from-stream.ts drains queued tool calls on that completion event.
  • The error is surfaced, but it does not prevent execution. The existing wrong-tool test added in #20426 has no execute callback, so it only verifies the error.

A fix should prevent queued tools from executing when response validation fails, while preserving usage reporting and the existing no-retry behavior. I can contribute the failing execution tests or help with that fix.

This overlaps the earlier wrong-tool report #12786, so I am adding the concrete post-fix reproduction here rather than opening another issue.

Tested with the unmodified npm [email protected], [email protected], Node 24.13.0 on macOS arm64. I also inspected main at 6dcd923799d2c663dff348927790c7967ce597dc: the response-validation and execution files are unchanged; stream-text.ts has additional tool-search changes. I have not built and run current main for this follow-up.

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

brennanbutler01 avatar Sep 17 '26 12:09 brennanbutler01

:rocket: Published in:

Package Version
ai 7.0.108 github npm
@ai-sdk/amazon-bedrock 5.0.89 github npm
@ai-sdk/angular 3.0.108 github npm
@ai-sdk/azure 4.0.76 github npm
@ai-sdk/code-mode 1.0.65 github npm
@ai-sdk/deepseek 3.0.50 github npm
@ai-sdk/gateway 4.0.88 github npm
@ai-sdk/harness 1.0.118 github npm
@ai-sdk/harness-acp 1.0.56 github npm
@ai-sdk/harness-claude-code 1.0.122 github npm
@ai-sdk/harness-cline 1.0.45 github npm
@ai-sdk/harness-codex 1.0.120 github npm
@ai-sdk/harness-cursor 1.0.31 github npm
@ai-sdk/harness-deepagents 1.0.118 github npm
@ai-sdk/harness-fx 1.0.31 github npm
@ai-sdk/harness-github-copilot 1.0.13 github npm
@ai-sdk/harness-grok-build 1.0.55 github npm
@ai-sdk/harness-opencode 1.0.120 github npm
@ai-sdk/harness-pi 1.0.120 github npm
@ai-sdk/langchain 3.0.108 github npm
@ai-sdk/llamaindex 3.0.108 github npm
@ai-sdk/mcp 2.0.55 github npm
@ai-sdk/openai 4.0.72 github npm
@ai-sdk/otel 1.0.108 github npm
@ai-sdk/policy-opa 1.0.108 github npm
@ai-sdk/react 4.0.111 github npm
@ai-sdk/rsc 3.0.108 github npm
@ai-sdk/sandbox-just-bash 1.0.118 github npm
@ai-sdk/sandbox-vercel 1.0.118 github npm
@ai-sdk/svelte 5.0.108 github npm
@ai-sdk/tui 1.0.109 github npm
@ai-sdk/vue 4.0.108 github npm
@ai-sdk/workflow 2.0.39 github npm
@ai-sdk/workflow-harness 1.0.118 github npm
@ai-sdk/xai 5.0.5 github npm

github-actions[bot] avatar Sep 21 '26 19:09 github-actions[bot]

Bug Reproduction - AI SDK 6

Bug was reproduced.

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

Details

  • On release-v6.0 with [email protected], a required-tool text-only stream returned No tool call., resolved with finishReason: 'stop', invoked onFinish, surfaced no ToolChoiceViolationError, and made one provider call.
  • A specifically selected-tool violation completed with finishReason: 'tool-calls' and executed the disallowed tool once through direct streamText, a prepareStep override, direct ToolLoopAgent.stream, and an agent prepareStep override.
  • Equivalent generateText controls rejected with ToolChoiceViolationError without executing the wrong tool, while a valid required-tool stream completed normally with finishReason: 'tool-calls'.
  • packages/ai/src/generate-text/generate-text.ts contains response-side tool-choice enforcement, while packages/ai/src/generate-text/stream-text.ts lacks equivalent enforcement.
  • Runnable reproduction added at examples/ai-functions/src/reproduction/issue-20424-stream-text-tool-choice.ts; it expects violations to surface and disallowed tools not to execute, but all five streaming violation cases fail those invariants.
  • The AI SDK 7 follow-up's exact streamRetries case could not be evaluated because that setting is absent on release-v6.0; the target branch exposes maxRetries instead.

Relevant Documentation

  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
  • https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-tool-choice-violation-error

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

Bugfix - AI SDK 6

Created bugfix and opened PR: #23255

Root Cause

The streaming tool transformation executed queued calls when the provider finish event arrived without validating the effective per-step tool choice against parsed tool calls; the reproduction confirmed violations completed successfully or executed the wrong tool.

Summary

Passed the effective tool choice into the streaming tool transformation, validated completed model output before tool execution, emitted ToolChoiceViolationError with an error finish reason, and discarded disallowed queued executions.

Testing

Added streamText regression coverage for missing required calls, selected-tool violations without execution, prepareStep overrides, preserved usage, error details, and error finish reasons.

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