ai icon indicating copy to clipboard operation
ai copied to clipboard

streamText reports the original model after prepareStep switches models

Open brennanbutler01 opened this issue 2 months ago • 7 comments

Description

When prepareStep selects a different model, streamText calls that model correctly, but steps[i].model, onStepEnd and onEnd still identify the original model and provider.

In the reproduction below, only model B runs. generateText reports B correctly; streamText reports A. The streamed response.modelId correctly says B, so the returned fields disagree.

This can mislabel per-step usage and logs, or affect later decisions that inspect completed steps.

Expected: completed steps and their callbacks should identify the model selected by prepareStep, matching generateText.

Also reproduced with ToolLoopAgent.stream, with a switch on either the first or second step, and with or without provider response metadata.

The streamed step result is constructed using the outer model, while the model call uses the resolved stepModel from prepareStep. The same construction is present on main at 6dcd923799d2c663dff348927790c7967ce597dc.

Related reports #18229 and #18118 concern wrapper/Gateway response metadata. This reproduces without either, with correct response metadata supplied by the mock provider.

I can contribute regression tests and a focused fix if useful.

Investigation and reproduction prepared with AI assistance.

Reproduction

No API key or network model call is needed. In an empty directory:

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

Save this as repro.mjs, then run node repro.mjs:

import { generateText, streamText } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';

const usage = {
  inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
  outputTokens: { total: 1, text: 1, reasoning: 0 },
};
const finishReason = { unified: 'stop', raw: 'stop' };
const original = new MockLanguageModelV4({
  provider: 'provider-a', modelId: 'model-a',
});
const selected = new MockLanguageModelV4({
  provider: 'provider-b', modelId: 'model-b',
  doGenerate: {
    content: [{ type: 'text', text: 'Hello from model B.' }],
    finishReason, usage, warnings: [],
    response: { modelId: 'model-b' },
  },
  doStream: async () => ({
    stream: new ReadableStream({
      start(controller) {
        controller.enqueue({ type: 'response-metadata', modelId: 'model-b' });
        controller.enqueue({ type: 'text-start', id: 'text-1' });
        controller.enqueue({ type: 'text-delta', id: 'text-1', delta: 'Hello from model B.' });
        controller.enqueue({ type: 'text-end', id: 'text-1' });
        controller.enqueue({ type: 'finish', finishReason, usage });
        controller.close();
      },
    }),
  }),
});
const options = {
  model: original,
  prepareStep: () => ({ model: selected }),
  prompt: 'Say hello.',
};

const generated = await generateText(options);
const streamed = streamText(options);
await streamed.consumeStream();

console.log(JSON.stringify({
  generateText: generated.steps[0].model,
  streamText: (await streamed.steps)[0].model,
  streamResponseModelId: (await streamed.response).modelId,
  originalModelCalls: original.doGenerateCalls.length + original.doStreamCalls.length,
  selectedModelCalls: selected.doGenerateCalls.length + selected.doStreamCalls.length,
}, null, 2));

Output:

{
  "generateText": { "provider": "provider-b", "modelId": "model-b" },
  "streamText": { "provider": "provider-a", "modelId": "model-a" },
  "streamResponseModelId": "model-b",
  "originalModelCalls": 0,
  "selectedModelCalls": 2
}

AI SDK Version

  • ai: 7.0.101
  • zod: 4.4.3
  • Node.js: 24.13.0
  • macOS, arm64

Code of Conduct

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

brennanbutler01 avatar Sep 17 '26 07:09 brennanbutler01

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete behavioral defect: streamText records the original model instead of the model resolved by prepareStep, producing incorrect and internally inconsistent step and callback metadata.

Evidence

  • When prepareStep switches from model A to model B, streamText invokes model B but reports model A in steps[i].model, onStepEnd, and onEnd.
  • The reproduction shows generateText correctly reports provider-b/model-b while streamText incorrectly reports provider-a/model-a, despite response.modelId being model-b.
  • The report identifies an inconsistency in current behavior and provides a network-free reproduction on [email protected].

ai-sdk-factory[bot] avatar Sep 17 '26 07: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 called provider B/model B but reported provider A/model A through steps[i].model, onStepEnd, and onEnd; generateText and streamed response.modelId correctly reported model B.
  • The mismatch reproduced when switching on either the first or second step, both with and without provider response metadata, through both streamText and ToolLoopAgent.stream.
  • The issue reproduces with workspace [email protected], Node.js 22.23.2, and the repository's aligned dependencies, ruling out the reported [email protected] or Zod 4 setup as necessary causes.
  • packages/ai/src/generate-text/stream-text.ts calls the resolved step model but constructs DefaultStepResult from the outer model, causing completed-step metadata and callbacks to be mislabeled.
  • Runnable reproduction examples/ai-functions/src/reproduction/issue-20944-stream-text-prepare-step-model.ts expects every switched step and callback to identify provider B/model B and fails when they report provider A/model A.

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

Bugfix - AI SDK 7

Created bugfix and opened PR: #20946

Root Cause

The streaming event processor constructed DefaultStepResult and warning metadata from the outer model even though each call used the resolved stepModel; the reproduction confirmed model B was called while steps, onStepEnd, and onEnd reported model A.

Summary

Tracked the resolved model for each streaming step and used it when constructing completed-step metadata and logging warnings. Added a patch changeset and removed reproduction-only artifacts.

Testing

Expanded streamText regression coverage to verify prepareStep model changes across step-start events, step-end callbacks, returned steps, and onEnd data.

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

Bug Reproduction - AI SDK 5

Issue report appears invalid.

Target branch: release-v5.0

  • Issue #20944 assumes [email protected], but the target release-v5.0 checkout contains [email protected] in packages/ai/package.json.
  • The primary reported surface is unavailable: StepResult in packages/ai/src/generate-text/step-result.ts has no model or provider fields.
  • streamText on this branch exposes onStepFinish and onFinish, not the reported onStepEnd and onEnd, as defined in packages/ai/src/generate-text/stream-text.ts.
  • The reproduction also depends on AI SDK 7 APIs absent here: this branch provides MockLanguageModelV2 in packages/ai/src/test/mock-language-model-v2.ts and Experimental_Agent rather than MockLanguageModelV4 and ToolLoopAgent.
  • No reproduction artifact was created because adding the missing APIs would test a different release line rather than release-v5.0.

Relevant Documentation

  • https://ai-sdk.dev/v5/docs/reference/ai-sdk-core/stream-text

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

Bug Reproduction - AI SDK 6

Bug was reproduced.

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

Details

  • On the release-v6.0 workspace ([email protected]), the supported V3 equivalent reproduces the primary bug: prepareStep selects provider B/model B, but completed streaming steps report provider A/model A.
  • generateText, the streamed response metadata, and model call counts confirm model B actually handled the switched call, while steps, onStepFinish, and onFinish are mislabeled.
  • The mismatch occurs when switching either the first or second step, with and without provider response metadata, through both streamText and ToolLoopAgent.stream.
  • packages/ai/src/generate-text/stream-text.ts invokes the resolved stepModel but constructs DefaultStepResult and warning metadata using the outer modelInfo.
  • Runnable reproduction examples/ai-functions/src/reproduction/issue-20944-stream-text-prepare-step-model.ts expects provider B/model B and observed provider A/model A across every reported streaming case.

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

Backport to v6.0

created: #21026 (fixed merge).

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]