ai icon indicating copy to clipboard operation
ai copied to clipboard

generateText and streamText treat generated file URLs as base64

Open brennanbutler01 opened this issue 2 months ago • 6 comments

Description

A V4 language model can return a file with data: { type: 'url', url: new URL(...) }. generateText and streamText turn that URL into a GeneratedFile as if it were base64 data.

This produces three incorrect results:

  • file.base64 contains the literal HTTPS URL.
  • Reading file.uint8Array throws InvalidCharacterError.
  • toUIMessageStream() emits an invalid URL such as data:image/png;base64,https://example.com/generated.png.

Inline base64 and byte-array file outputs work. ToolLoopAgent.generate and ToolLoopAgent.stream reproduce the URL failure too.

The URL output variant is declared in LanguageModelV4File. The Google Interactions adapter also emits it for image/video uri outputs. I reproduced the failure through that adapter using synthetic HTTP responses; no live Google requests were made.

Expected: preserve the distinction between a URL and encoded file data. The existing GeneratedFile byte getters should return actual file content, and UI file URLs should be usable.

The likely cause is in convert-language-model-content.ts and stream-language-model-call.ts: both call url.toString() and pass it to DefaultGeneratedFile, whose string constructor argument is treated as base64. URL outputs need explicit handling before reaching that constructor.

Related reports I checked: #11490 concerns the separate generateImage API; #11567 concerns URL strings in input messages. This reproduction uses a tagged URL in language-model output.

I can send the regression cases or help with a focused fix if useful.

Reproduction

No API key is needed. In an empty directory:

npm init -y
npm install [email protected]

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

import { generateText, simulateReadableStream, 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 model = new MockLanguageModelV4({
  doGenerate: {
    content: [{
      type: 'file', mediaType: 'image/png',
      data: { type: 'url', url: new URL('https://example.com/generated.png') },
    }],
    finishReason: { unified: 'stop', raw: 'stop' },
    usage, warnings: [],
  },
  doStream: async () => ({
    stream: simulateReadableStream({ chunks: [
      { type: 'stream-start', warnings: [] },
      { type: 'file', mediaType: 'image/png', data: { type: 'url', url: new URL('https://example.com/generated.png') } },
      { type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage },
    ] }),
  }),
});

const generated = await generateText({ model, prompt: 'Return an image.' });
console.log('base64:', generated.files[0].base64);
try {
  console.log('bytes:', generated.files[0].uint8Array);
} catch (error) {
  console.log('Reading bytes threw:', error instanceof Error ? error.name : error);
}

const streamed = streamText({ model, prompt: 'Return an image.' });
for await (const part of streamed.toUIMessageStream()) {
  if (part.type === 'file') console.log('UI file URL:', part.url);
}

Output:

base64: https://example.com/generated.png
Reading bytes threw: InvalidCharacterError
UI file URL: data:image/png;base64,https://example.com/generated.png

The reproduction passes strict application TypeScript checking. The local regression suite covers URL, base64, and byte-array output across all four entry points: eight inline-data controls pass and four URL cases fail.

Prepared with AI assistance for source inspection, synthetic reproductions, and local verification.

AI SDK Version

  • ai: 7.0.101, unmodified npm package
  • Node.js: 24.13.0, macOS arm64
  • Additional adapter check: local unmodified @ai-sdk/google 4.0.70 build, with synthetic fetch responses
  • Inspected main at 6dcd923799d2c663dff348927790c7967ce597dc: the affected conversion files are unchanged from the checkout base. 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 failure in existing file-output handling for a declared language-model output variant, with reproducible incorrect values and an exception.

Evidence

  • generateText and streamText incorrectly convert tagged URL file outputs into base64-backed GeneratedFile instances.
  • The reproduction shows the URL exposed as file.base64, file.uint8Array throwing InvalidCharacterError, and toUIMessageStream() producing an invalid data URL.
  • The URL output variant is part of LanguageModelV4File, and inline base64 and byte-array variants reportedly work correctly.

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

  • packages/provider/src/language-model/v4/language-model-v4-file.ts declares URL-backed files as a valid LanguageModelV4File variant on main with ai 7.0.105.
  • examples/ai-functions/src/reproduction/issue-20951-generated-file-url.ts reproduces the bug while confirming base64 and byte-array controls work.
  • generateText and ToolLoopAgent.generate expose the literal HTTPS URL through file.base64; reading file.uint8Array throws InvalidCharacterError instead of returning the mocked URL content.
  • streamText and ToolLoopAgent.stream exhibit the same generated-file failures and emit data:image/png;base64,https://example.com/generated.png instead of a usable source or data URL.
  • packages/ai/src/generate-text/convert-language-model-content.ts and packages/ai/src/generate-text/stream-language-model-call.ts stringify URL data before passing it to a base64-backed generated-file constructor, placing the defect in AI SDK core handling.

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

Bugfix - AI SDK 7

Created bugfix and opened PR: #20957

Root Cause

Core content converters stringified tagged file URLs before passing them to DefaultGeneratedFile, whose string input is defined as base64. The reproduction confirmed this path for generateText and streamText.

Summary

URL-backed outputs are now securely downloaded before GeneratedFile construction, with abort propagation and per-step caching to prevent duplicate downloads. Batch conversion was updated for asynchronous file resolution.

Testing

Added generate and stream regression tests verifying URL content is exposed through base64 and byte getters, including a single-download assertion.

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

Bug Reproduction - AI SDK 6

Issue report appears invalid.

Target branch: release-v6.0

  • Issue #20951 reports that URL-backed LanguageModelV4File outputs are misinterpreted as base64, but that output variant is unavailable on the release-v6.0 target branch.
  • packages/ai/package.json identifies the checked-out SDK as ai 6.0.288, whereas the report reproduces with ai 7.0.101.
  • packages/provider/src/language-model/v3/language-model-v3-file.ts permits generated-file data only as a base64 string or Uint8Array; it does not declare the tagged { type: 'url', url: URL } variant required by the issue.
  • packages/provider/src/language-model/index.ts exports only the V2 and V3 language-model specifications, and packages/ai/test/index.ts exports MockLanguageModelV3 rather than the reported MockLanguageModelV4.
  • No reproduction artifact was created because constructing the reported scenario would require adding or emulating an API from a different release line.

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

Bug Reproduction - AI SDK 5

Issue report appears invalid.

Target branch: release-v5.0

  • Issue #20951 assumes AI SDK 7's LanguageModelV4File tagged URL output and MockLanguageModelV4, but the target branch contains ai 5.0.263 and @ai-sdk/provider 2.0.4, as shown by packages/ai/package.json and packages/provider/package.json.
  • packages/provider/src/language-model/v2/language-model-v2-file.ts defines generated-file output data only as string | Uint8Array; the reported { type: 'url', url: URL } variant is unavailable.
  • packages/ai/test/index.ts exports MockLanguageModelV2 and does not export the reported MockLanguageModelV4; repository-wide inspection found no V4 language-model implementation.
  • The reported URL-output scenario is therefore not valid on release-v5; no reproduction artifact was created.

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

:rocket: Published in:

Package Version
ai 7.0.111 github npm
@ai-sdk/angular 3.0.111 github npm
@ai-sdk/code-mode 1.0.68 github npm
@ai-sdk/harness 1.0.121 github npm
@ai-sdk/harness-acp 1.0.59 github npm
@ai-sdk/harness-claude-code 1.0.125 github npm
@ai-sdk/harness-cline 1.0.48 github npm
@ai-sdk/harness-codex 1.0.123 github npm
@ai-sdk/harness-cursor 1.0.34 github npm
@ai-sdk/harness-deepagents 1.0.121 github npm
@ai-sdk/harness-fx 1.0.34 github npm
@ai-sdk/harness-github-copilot 1.0.16 github npm
@ai-sdk/harness-grok-build 1.0.58 github npm
@ai-sdk/harness-opencode 1.0.123 github npm
@ai-sdk/harness-pi 1.0.123 github npm
@ai-sdk/langchain 3.0.111 github npm
@ai-sdk/llamaindex 3.0.111 github npm
@ai-sdk/otel 1.0.111 github npm
@ai-sdk/policy-opa 1.0.111 github npm
@ai-sdk/react 4.0.114 github npm
@ai-sdk/rsc 3.0.111 github npm
@ai-sdk/sandbox-just-bash 1.0.121 github npm
@ai-sdk/sandbox-vercel 1.0.121 github npm
@ai-sdk/svelte 5.0.111 github npm
@ai-sdk/tui 1.0.112 github npm
@ai-sdk/vue 4.0.111 github npm
@ai-sdk/workflow 2.0.42 github npm
@ai-sdk/workflow-harness 1.0.121 github npm

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