ai 6.0.328 → 6.0.330

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -164,7 +164,7 @@ function detectMediaType({
164
164
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
165
165
 
166
166
  // src/version.ts
167
- var VERSION = true ? "6.0.328" : "0.0.0-test";
167
+ var VERSION = true ? "6.0.330" : "0.0.0-test";
168
168
 
169
169
  // src/util/download/download.ts
170
170
  var download = async ({
@@ -144,7 +144,7 @@ import {
144
144
  } from "@ai-sdk/provider-utils";
145
145
 
146
146
  // src/version.ts
147
- var VERSION = true ? "6.0.328" : "0.0.0-test";
147
+ var VERSION = true ? "6.0.330" : "0.0.0-test";
148
148
 
149
149
  // src/util/download/download.ts
150
150
  var download = async ({
@@ -154,6 +154,7 @@ Here are the capabilities of popular models:
154
154
  | [Anthropic](/providers/ai-sdk-providers/anthropic) | `claude-opus-4-1` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
155
155
  | [Anthropic](/providers/ai-sdk-providers/anthropic) | `claude-opus-4-0` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
156
156
  | [Anthropic](/providers/ai-sdk-providers/anthropic) | `claude-sonnet-4-0` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
157
+ | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-4-carbon` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
157
158
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-3.8-flash` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
158
159
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-3.1-pro-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
159
160
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-3-pro-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
@@ -7,6 +7,15 @@ description: API Reference for pruneMessages.
7
7
 
8
8
  The `pruneMessages` function is used to prune or filter an array of `ModelMessage` objects. This is useful for reducing message context (to save tokens), removing intermediate reasoning, or trimming tool calls and empty messages before sending to an LLM.
9
9
 
10
+ <Note>
11
+ OpenAI Responses models may drop reasoning items after edits to their
12
+ preceding context. Pruning earlier history can therefore increase reasoning
13
+ work. Also preserve empty system messages carrying positioned configuration
14
+ updates; `emptyMessages: 'remove'` removes them. See [preserving reasoning
15
+ across
16
+ turns](/providers/ai-sdk-providers/openai#preserving-reasoning-across-turns).
17
+ </Note>
18
+
10
19
  ```ts filename="app/api/chat/route.ts"
11
20
  import { pruneMessages, streamText } from 'ai';
12
21
  __PROVIDER_IMPORT__;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "6.0.328",
3
+ "version": "6.0.330",
4
4
  "description": "AI SDK by Vercel - build apps like ChatGPT, Claude, Gemini, and more with a single interface for any model using the Vercel AI Gateway or go direct to OpenAI, Anthropic, Google, or any other model provider.",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@opentelemetry/api": "^1.9.0",
48
- "@ai-sdk/gateway": "3.0.234",
48
+ "@ai-sdk/gateway": "3.0.235",
49
49
  "@ai-sdk/provider": "3.0.19",
50
50
  "@ai-sdk/provider-utils": "4.0.66"
51
51
  },
@@ -58,7 +58,8 @@
58
58
  "tsx": "^4.19.2",
59
59
  "typescript": "5.8.3",
60
60
  "zod": "3.25.76",
61
- "@ai-sdk/google": "3.0.144",
61
+ "@ai-sdk/google": "3.0.145",
62
+ "@ai-sdk/openai": "3.0.141",
62
63
  "@ai-sdk/perplexity": "3.1.12",
63
64
  "@ai-sdk/test-server": "1.0.6",
64
65
  "@vercel/ai-tsconfig": "0.0.0"
@@ -24,6 +24,10 @@ import {
24
24
  createAsyncIterableStream,
25
25
  type AsyncIterableStream,
26
26
  } from '../util/async-iterable-stream';
27
+ import {
28
+ createArrayOutputStreamParser,
29
+ type ArrayOutputStreamParser,
30
+ } from '../util/array-output-stream';
27
31
  import type { DeepPartial } from '../util/deep-partial';
28
32
  import type { ObjectStreamPart } from './stream-object-result';
29
33
 
@@ -32,6 +36,8 @@ export interface OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM> {
32
36
 
33
37
  jsonSchema(): Promise<JSONSchema7 | undefined>;
34
38
 
39
+ createArrayStreamParser?(): ArrayOutputStreamParser<any>;
40
+
35
41
  validatePartialResult({
36
42
  value,
37
43
  textDelta,
@@ -136,6 +142,8 @@ const arrayOutputStrategy = <ELEMENT>(
136
142
  return {
137
143
  type: 'array',
138
144
 
145
+ createArrayStreamParser: () => createArrayOutputStreamParser(schema, false),
146
+
139
147
  // wrap in object that contains array of elements, since most LLMs will not
140
148
  // be able to generate an array directly:
141
149
  // possible future optimization: use arrays directly when model supports grammar-guided generation
@@ -600,6 +600,7 @@ class DefaultStreamObjectResult<
600
600
  let terminalError: { error: unknown } | undefined;
601
601
 
602
602
  // pipe chunks through a transformation stream that extracts metadata:
603
+ let arrayStreamParser = outputStrategy.createArrayStreamParser?.();
603
604
  let accumulatedText = '';
604
605
  let textDelta = '';
605
606
  let fullResponse: {
@@ -655,6 +656,27 @@ class DefaultStreamObjectResult<
655
656
  accumulatedText += chunk;
656
657
  textDelta += chunk;
657
658
 
659
+ if (arrayStreamParser != null) {
660
+ const result = await arrayStreamParser(chunk);
661
+ if (result !== 'fallback') {
662
+ if (result != null) {
663
+ latestObject = result.partial as PARTIAL;
664
+ controller.enqueue({
665
+ type: 'object',
666
+ object: latestObject,
667
+ });
668
+ controller.enqueue({
669
+ type: 'text-delta',
670
+ textDelta: result.textDelta,
671
+ });
672
+ textDelta = '';
673
+ isFirstDelta = false;
674
+ }
675
+ return;
676
+ }
677
+ arrayStreamParser = undefined;
678
+ }
679
+
658
680
  const { value: currentObjectJson, state: parseState } =
659
681
  await parsePartialJson(accumulatedText);
660
682
 
@@ -14,6 +14,10 @@ import { NoObjectGeneratedError } from '../error/no-object-generated-error';
14
14
  import type { FinishReason } from '../types/language-model';
15
15
  import type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';
16
16
  import type { LanguageModelUsage } from '../types/usage';
17
+ import {
18
+ createArrayOutputStreamParser,
19
+ arrayStreamParserFactories,
20
+ } from '../util/array-output-stream';
17
21
  import type { DeepPartial } from '../util/deep-partial';
18
22
  import { parsePartialJson } from '../util/parse-partial-json';
19
23
  import type { EnrichedStreamPart } from './stream-text';
@@ -130,12 +134,10 @@ export const object = <OBJECT>({
130
134
 
131
135
  if (!parseResult.success) {
132
136
  throw new NoObjectGeneratedError({
137
+ ...context,
133
138
  message: 'No object generated: could not parse the response.',
134
139
  cause: parseResult.error,
135
140
  text,
136
- response: context.response,
137
- usage: context.usage,
138
- finishReason: context.finishReason,
139
141
  });
140
142
  }
141
143
 
@@ -146,12 +148,10 @@ export const object = <OBJECT>({
146
148
 
147
149
  if (!validationResult.success) {
148
150
  throw new NoObjectGeneratedError({
151
+ ...context,
149
152
  message: 'No object generated: response did not match schema.',
150
153
  cause: validationResult.error,
151
154
  text,
152
- response: context.response,
153
- usage: context.usage,
154
- finishReason: context.finishReason,
155
155
  });
156
156
  }
157
157
 
@@ -212,7 +212,7 @@ export const array = <ELEMENT>({
212
212
  }): Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT> => {
213
213
  const elementSchema = asSchema(inputElementSchema);
214
214
 
215
- return {
215
+ const output: Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT> = {
216
216
  name: 'array',
217
217
 
218
218
  // JSON schema that describes an array of elements:
@@ -248,12 +248,10 @@ export const array = <ELEMENT>({
248
248
 
249
249
  if (!parseResult.success) {
250
250
  throw new NoObjectGeneratedError({
251
+ ...context,
251
252
  message: 'No object generated: could not parse the response.',
252
253
  cause: parseResult.error,
253
254
  text,
254
- response: context.response,
255
- usage: context.usage,
256
- finishReason: context.finishReason,
257
255
  });
258
256
  }
259
257
 
@@ -266,15 +264,13 @@ export const array = <ELEMENT>({
266
264
  !Array.isArray(outerValue.elements)
267
265
  ) {
268
266
  throw new NoObjectGeneratedError({
267
+ ...context,
269
268
  message: 'No object generated: response did not match schema.',
270
269
  cause: new TypeValidationError({
271
270
  value: outerValue,
272
271
  cause: 'response must be an object with an elements array',
273
272
  }),
274
273
  text,
275
- response: context.response,
276
- usage: context.usage,
277
- finishReason: context.finishReason,
278
274
  });
279
275
  }
280
276
 
@@ -287,12 +283,10 @@ export const array = <ELEMENT>({
287
283
 
288
284
  if (!validationResult.success) {
289
285
  throw new NoObjectGeneratedError({
286
+ ...context,
290
287
  message: 'No object generated: response did not match schema.',
291
288
  cause: validationResult.error,
292
289
  text,
293
- response: context.response,
294
- usage: context.usage,
295
- finishReason: context.finishReason,
296
290
  });
297
291
  }
298
292
 
@@ -369,6 +363,14 @@ export const array = <ELEMENT>({
369
363
  });
370
364
  },
371
365
  };
366
+
367
+ const parsePartialOutput = output.parsePartialOutput;
368
+ arrayStreamParserFactories.set(output, () =>
369
+ output.parsePartialOutput === parsePartialOutput
370
+ ? createArrayOutputStreamParser(elementSchema, true)
371
+ : undefined,
372
+ );
373
+ return output;
372
374
  };
373
375
 
374
376
  /**
@@ -429,12 +431,10 @@ export const choice = <CHOICE extends string>({
429
431
 
430
432
  if (!parseResult.success) {
431
433
  throw new NoObjectGeneratedError({
434
+ ...context,
432
435
  message: 'No object generated: could not parse the response.',
433
436
  cause: parseResult.error,
434
437
  text,
435
- response: context.response,
436
- usage: context.usage,
437
- finishReason: context.finishReason,
438
438
  });
439
439
  }
440
440
 
@@ -448,15 +448,13 @@ export const choice = <CHOICE extends string>({
448
448
  !choiceOptions.includes(outerValue.result as any)
449
449
  ) {
450
450
  throw new NoObjectGeneratedError({
451
+ ...context,
451
452
  message: 'No object generated: response did not match schema.',
452
453
  cause: new TypeValidationError({
453
454
  value: outerValue,
454
455
  cause: 'response must be an object that contains a choice value.',
455
456
  }),
456
457
  text,
457
- response: context.response,
458
- usage: context.usage,
459
- finishReason: context.finishReason,
460
458
  });
461
459
  }
462
460
 
@@ -556,12 +554,10 @@ export const json = ({
556
554
 
557
555
  if (!parseResult.success) {
558
556
  throw new NoObjectGeneratedError({
557
+ ...context,
559
558
  message: 'No object generated: could not parse the response.',
560
559
  cause: parseResult.error,
561
560
  text,
562
- response: context.response,
563
- usage: context.usage,
564
- finishReason: context.finishReason,
565
561
  });
566
562
  }
567
563
 
@@ -100,6 +100,7 @@ import type { ContentPart } from './content-part';
100
100
  import { executeToolCall } from './execute-tool-call';
101
101
  import { filterActiveTools } from './filter-active-tools';
102
102
  import { text, type Output } from './output';
103
+ import { createArrayStreamParser } from '../util/array-output-stream';
103
104
  import type {
104
105
  InferCompleteOutput,
105
106
  InferElementOutput,
@@ -667,10 +668,14 @@ function createOutputTransformStream<
667
668
  let text = '';
668
669
  let textChunk = '';
669
670
  let textProviderMetadata: ProviderMetadata | undefined = undefined;
671
+ let arrayStreamParser = createArrayStreamParser(output);
672
+ let lastArrayPartial: InferPartialOutput<OUTPUT> | undefined;
670
673
  let lastPublishedValue: string | undefined = undefined;
671
674
  let hasPublishedValue = false;
672
675
 
673
676
  function resetOutputState() {
677
+ arrayStreamParser = createArrayStreamParser(output);
678
+ lastArrayPartial = undefined;
674
679
  firstTextChunkId = undefined;
675
680
  text = '';
676
681
  textChunk = '';
@@ -753,6 +758,24 @@ function createOutputTransformStream<
753
758
  return;
754
759
  }
755
760
 
761
+ // Built-in arrays publish only changed snapshots, so growing arrays do
762
+ // not need to be reparsed, revalidated, or stringified on every chunk.
763
+ if (arrayStreamParser != null) {
764
+ const result = await arrayStreamParser(chunk.text);
765
+ if (result !== 'fallback') {
766
+ if (result != null) {
767
+ lastArrayPartial = result.partial as InferPartialOutput<OUTPUT>;
768
+ publishTextChunk({ controller, partialOutput: lastArrayPartial });
769
+ }
770
+ return;
771
+ }
772
+ arrayStreamParser = undefined;
773
+ if (lastArrayPartial != null) {
774
+ lastPublishedValue = JSON.stringify(lastArrayPartial);
775
+ hasPublishedValue = true;
776
+ }
777
+ }
778
+
756
779
  // only publish if partial json can be parsed:
757
780
  const result = await output.parsePartialOutput({ text });
758
781
 
@@ -0,0 +1,161 @@
1
+ import {
2
+ safeParseJSON,
3
+ safeValidateTypes,
4
+ type Schema,
5
+ } from '@ai-sdk/provider-utils';
6
+ import type { Output } from '../generate-text/output';
7
+
8
+ export type ArrayOutputStreamParser<ELEMENT> = (
9
+ textDelta: string,
10
+ ) => Promise<
11
+ { partial: ELEMENT[]; textDelta: string } | undefined | 'fallback'
12
+ >;
13
+
14
+ // Parser state belongs to a stream, not to the reusable output specification.
15
+ export const arrayStreamParserFactories = new WeakMap<
16
+ Output,
17
+ () => ArrayOutputStreamParser<any> | undefined
18
+ >();
19
+
20
+ export function createArrayStreamParser(output: Output) {
21
+ return arrayStreamParserFactories.get(output)?.();
22
+ }
23
+
24
+ enum Phase {
25
+ Prefix,
26
+ Elements,
27
+ Suffix,
28
+ Done,
29
+ }
30
+
31
+ /**
32
+ * Scan only new text and parse/validate each delimited element once. Keep the
33
+ * last element pending until another starts or the enclosing object closes,
34
+ * matching the partial JSON parser's treatment of an incomplete response.
35
+ * Nonstandard envelopes and malformed JSON use the existing partial parser.
36
+ */
37
+ export function createArrayOutputStreamParser<ELEMENT>(
38
+ schema: Schema<ELEMENT>,
39
+ skipInvalidElements: boolean,
40
+ ): ArrayOutputStreamParser<ELEMENT> {
41
+ let phase = Phase.Prefix;
42
+ let prefix = '';
43
+ let elementText = '';
44
+ let depth = 0;
45
+ let inString = false;
46
+ let escaped = false;
47
+ let afterComma = false;
48
+ let pending: [] | [ELEMENT] = [];
49
+ const elements: ELEMENT[] = [];
50
+ let publishedCount: number | undefined;
51
+
52
+ async function finishElement() {
53
+ const parsed = await safeParseJSON({ text: elementText });
54
+ if (!parsed.success) {
55
+ return false;
56
+ }
57
+
58
+ const validated = await safeValidateTypes({ value: parsed.value, schema });
59
+ if (validated.success) {
60
+ pending = [validated.value];
61
+ } else if (!skipInvalidElements) {
62
+ return false;
63
+ }
64
+ elementText = '';
65
+ return true;
66
+ }
67
+
68
+ function publishPending() {
69
+ elements.push(...pending);
70
+ pending = [];
71
+ }
72
+
73
+ return async textDelta => {
74
+ for (const char of textDelta) {
75
+ if (phase === Phase.Prefix) {
76
+ prefix += char;
77
+ if (char === '[') {
78
+ // Bound prefix scanning; other valid object shapes retain their
79
+ // existing behavior through the stateless parser.
80
+ if (!/^\s*\{\s*"elements"\s*:\s*\[$/.test(prefix)) {
81
+ return 'fallback';
82
+ }
83
+ phase = Phase.Elements;
84
+ } else if (prefix.length > 256) {
85
+ return 'fallback';
86
+ }
87
+ continue;
88
+ }
89
+
90
+ if (phase === Phase.Suffix || phase === Phase.Done) {
91
+ if (/\s/.test(char)) {
92
+ continue;
93
+ }
94
+ if (phase === Phase.Suffix && char === '}') {
95
+ publishPending();
96
+ phase = Phase.Done;
97
+ continue;
98
+ }
99
+ return 'fallback';
100
+ }
101
+
102
+ if (!inString && depth === 0 && (char === ',' || char === ']')) {
103
+ if (elementText.length > 0) {
104
+ if (!(await finishElement())) {
105
+ return 'fallback';
106
+ }
107
+ } else if (char === ',' || afterComma) {
108
+ return 'fallback';
109
+ }
110
+ afterComma = char === ',';
111
+ if (char === ']') {
112
+ phase = Phase.Suffix;
113
+ }
114
+ continue;
115
+ }
116
+
117
+ if (elementText.length === 0) {
118
+ if (/\s/.test(char)) {
119
+ continue;
120
+ }
121
+ publishPending();
122
+ afterComma = false;
123
+ }
124
+ elementText += char;
125
+
126
+ if (inString) {
127
+ if (escaped) {
128
+ escaped = false;
129
+ } else if (char === '\\') {
130
+ escaped = true;
131
+ } else if (char === '"') {
132
+ inString = false;
133
+ }
134
+ } else if (char === '"') {
135
+ inString = true;
136
+ } else if (char === '{' || char === '[') {
137
+ depth++;
138
+ } else if (char === '}' || char === ']') {
139
+ depth--;
140
+ }
141
+ }
142
+
143
+ if (phase === Phase.Prefix || publishedCount === elements.length) {
144
+ return undefined;
145
+ }
146
+
147
+ const previousCount = publishedCount ?? 0;
148
+ const delta =
149
+ (publishedCount == null ? '[' : '') +
150
+ (previousCount > 0 && elements.length > previousCount ? ',' : '') +
151
+ elements
152
+ .slice(previousCount)
153
+ .map(value => JSON.stringify(value))
154
+ .join(',') +
155
+ (phase === Phase.Done ? ']' : '');
156
+ publishedCount = elements.length;
157
+
158
+ // A snapshot prevents subsequent chunks from mutating already emitted arrays.
159
+ return { partial: elements.slice(), textDelta: delta };
160
+ };
161
+ }