@ai-sdk/google 2.0.102 → 2.0.103

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.
@@ -111,6 +111,7 @@ declare const responseSchema: _ai_sdk_provider_utils.LazySchema<{
111
111
  })[] | null | undefined;
112
112
  } | null | undefined;
113
113
  finishReason?: string | null | undefined;
114
+ continuationToken?: string | null | undefined;
114
115
  safetyRatings?: {
115
116
  category?: string | null | undefined;
116
117
  probability?: string | null | undefined;
@@ -111,6 +111,7 @@ declare const responseSchema: _ai_sdk_provider_utils.LazySchema<{
111
111
  })[] | null | undefined;
112
112
  } | null | undefined;
113
113
  finishReason?: string | null | undefined;
114
+ continuationToken?: string | null | undefined;
114
115
  safetyRatings?: {
115
116
  category?: string | null | undefined;
116
117
  probability?: string | null | undefined;
@@ -31,6 +31,100 @@ module.exports = __toCommonJS(index_exports);
31
31
  var import_provider_utils4 = require("@ai-sdk/provider-utils");
32
32
  var import_v43 = require("zod/v4");
33
33
 
34
+ // src/add-google-generative-ai-usage-metadata.ts
35
+ function addGoogleGenerativeAIUsageMetadata(a, b) {
36
+ if (a == null || b == null) {
37
+ return b != null ? b : a;
38
+ }
39
+ return {
40
+ ...a,
41
+ ...b,
42
+ promptTokenCount: addCounts(a.promptTokenCount, b.promptTokenCount),
43
+ candidatesTokenCount: addCounts(
44
+ a.candidatesTokenCount,
45
+ b.candidatesTokenCount
46
+ ),
47
+ totalTokenCount: addCounts(a.totalTokenCount, b.totalTokenCount),
48
+ cachedContentTokenCount: addCounts(
49
+ a.cachedContentTokenCount,
50
+ b.cachedContentTokenCount
51
+ ),
52
+ thoughtsTokenCount: addCounts(a.thoughtsTokenCount, b.thoughtsTokenCount),
53
+ promptTokensDetails: addTokenDetails(
54
+ a.promptTokensDetails,
55
+ b.promptTokensDetails
56
+ ),
57
+ candidatesTokensDetails: addTokenDetails(
58
+ a.candidatesTokensDetails,
59
+ b.candidatesTokensDetails
60
+ )
61
+ };
62
+ }
63
+ function addCounts(a, b) {
64
+ return a == null && b == null ? b != null ? b : a : (a != null ? a : 0) + (b != null ? b : 0);
65
+ }
66
+ function addTokenDetails(a, b) {
67
+ var _a;
68
+ if (a == null || b == null) {
69
+ return b != null ? b : a;
70
+ }
71
+ const tokenCounts = /* @__PURE__ */ new Map();
72
+ for (const { modality, tokenCount } of [...a, ...b]) {
73
+ tokenCounts.set(modality, ((_a = tokenCounts.get(modality)) != null ? _a : 0) + tokenCount);
74
+ }
75
+ return Array.from(tokenCounts, ([modality, tokenCount]) => ({
76
+ modality,
77
+ tokenCount
78
+ }));
79
+ }
80
+
81
+ // src/continue-google-stream.ts
82
+ function continueGoogleStream({
83
+ stream,
84
+ getContinuationToken,
85
+ continueStream
86
+ }) {
87
+ let reader = stream.getReader();
88
+ let pendingContinuationToken;
89
+ return new ReadableStream({
90
+ async pull(controller) {
91
+ while (true) {
92
+ const { done, value } = await reader.read();
93
+ if (!done) {
94
+ if (value.success) {
95
+ const token = getContinuationToken(value.value);
96
+ if (token != null) {
97
+ pendingContinuationToken = token;
98
+ }
99
+ }
100
+ controller.enqueue(value);
101
+ return;
102
+ }
103
+ if (pendingContinuationToken == null) {
104
+ controller.close();
105
+ return;
106
+ }
107
+ const continuationToken = pendingContinuationToken;
108
+ pendingContinuationToken = void 0;
109
+ try {
110
+ reader = (await continueStream(continuationToken)).getReader();
111
+ } catch (error) {
112
+ controller.enqueue({
113
+ success: false,
114
+ error,
115
+ rawValue: void 0
116
+ });
117
+ controller.close();
118
+ return;
119
+ }
120
+ }
121
+ },
122
+ async cancel(reason) {
123
+ await reader.cancel(reason);
124
+ }
125
+ });
126
+ }
127
+
34
128
  // src/convert-json-schema-to-openapi-schema.ts
35
129
  var import_provider = require("@ai-sdk/provider");
36
130
  var recursiveReferenceFunctionalityPrefix = "recursive JSON Schema reference:";
@@ -706,7 +800,17 @@ var googleGenerativeAIProviderOptions = (0, import_provider_utils3.lazySchema)(
706
800
  /**
707
801
  * Optional. The service tier to use for the request.
708
802
  */
709
- serviceTier: import_v42.z.enum(["standard", "flex", "priority"]).optional()
803
+ serviceTier: import_v42.z.enum(["standard", "flex", "priority"]).optional(),
804
+ /**
805
+ * Optional. Resumes a response that stopped with `MAX_TOKENS` because it
806
+ * used up its `maxOutputTokens` budget (Gemini 4 long decode). Pass the
807
+ * `continuationToken` from the previous response's provider metadata
808
+ * together with the original prompt and a higher `maxOutputTokens` (the
809
+ * budget is cumulative across requests). Requests that reach the
810
+ * per-request cap while budget remains (`CONTINUATION`) are continued
811
+ * automatically. Sent as the `continuationToken` body field.
812
+ */
813
+ continuationToken: import_v42.z.string().optional()
710
814
  })
711
815
  )
712
816
  );
@@ -1004,6 +1108,9 @@ function mapGoogleGenerativeAIFinishReason({
1004
1108
  case "STOP":
1005
1109
  return hasToolCalls ? "tool-calls" : "stop";
1006
1110
  case "MAX_TOKENS":
1111
+ // Gemini 4 long decode: the per-request cap was reached while budget
1112
+ // remains. Continued automatically; only surfaced if continuing fails.
1113
+ case "CONTINUATION":
1007
1114
  return "length";
1008
1115
  case "IMAGE_SAFETY":
1009
1116
  case "RECITATION":
@@ -1178,43 +1285,70 @@ var GoogleGenerativeAILanguageModel = class {
1178
1285
  } : googleToolConfig,
1179
1286
  cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
1180
1287
  labels: googleOptions == null ? void 0 : googleOptions.labels,
1181
- serviceTier: sanitizedServiceTier
1288
+ serviceTier: sanitizedServiceTier,
1289
+ ...(googleOptions == null ? void 0 : googleOptions.continuationToken) != null && {
1290
+ continuationToken: googleOptions.continuationToken
1291
+ }
1182
1292
  },
1183
1293
  warnings: [...warnings, ...toolWarnings]
1184
1294
  };
1185
1295
  }
1186
1296
  async doGenerate(options) {
1187
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1297
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1188
1298
  const { args, warnings } = await this.getArgs(options);
1189
1299
  const body = JSON.stringify(args);
1190
1300
  const mergedHeaders = (0, import_provider_utils4.combineHeaders)(
1191
1301
  await (0, import_provider_utils4.resolve)(this.config.headers),
1192
1302
  options.headers
1193
1303
  );
1194
- const {
1195
- responseHeaders,
1196
- value: response,
1197
- rawValue: rawResponse
1198
- } = await (0, import_provider_utils4.postJsonToApi)({
1304
+ const generateContent = (body2) => (0, import_provider_utils4.postJsonToApi)({
1199
1305
  url: `${this.config.baseURL}/${getModelPath(
1200
1306
  this.modelId
1201
1307
  )}:generateContent`,
1202
1308
  headers: mergedHeaders,
1203
- body: args,
1309
+ body: body2,
1204
1310
  failedResponseHandler: googleFailedResponseHandler,
1205
1311
  successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(responseSchema),
1206
1312
  abortSignal: options.abortSignal,
1207
1313
  fetch: this.config.fetch
1208
1314
  });
1209
- const candidate = (_a = response.candidates) == null ? void 0 : _a[0];
1210
- const promptBlockReason = (_b = response.promptFeedback) == null ? void 0 : _b.blockReason;
1315
+ let {
1316
+ responseHeaders,
1317
+ value: response,
1318
+ rawValue: rawResponse
1319
+ } = await generateContent(args);
1320
+ const continuedParts = [];
1321
+ let continuedUsageMetadata;
1322
+ const firstPromptTokenCount = (_a = response.usageMetadata) == null ? void 0 : _a.promptTokenCount;
1323
+ while (true) {
1324
+ const candidate2 = (_b = response.candidates) == null ? void 0 : _b[0];
1325
+ const continuationToken = (candidate2 == null ? void 0 : candidate2.finishReason) === "CONTINUATION" ? candidate2.continuationToken : void 0;
1326
+ if (continuationToken == null) {
1327
+ break;
1328
+ }
1329
+ continuedParts.push(...(_d = (_c = candidate2 == null ? void 0 : candidate2.content) == null ? void 0 : _c.parts) != null ? _d : []);
1330
+ continuedUsageMetadata = addGoogleGenerativeAIUsageMetadata(
1331
+ continuedUsageMetadata,
1332
+ (_e = response.usageMetadata) != null ? _e : void 0
1333
+ );
1334
+ ({
1335
+ responseHeaders,
1336
+ value: response,
1337
+ rawValue: rawResponse
1338
+ } = await generateContent({ ...args, continuationToken }));
1339
+ }
1340
+ const candidate = (_f = response.candidates) == null ? void 0 : _f[0];
1341
+ const promptBlockReason = (_g = response.promptFeedback) == null ? void 0 : _g.blockReason;
1211
1342
  const isPromptBlocked = (candidate == null ? void 0 : candidate.finishReason) == null && promptBlockReason != null;
1212
1343
  const content = [];
1213
- const parts = (_d = (_c = candidate == null ? void 0 : candidate.content) == null ? void 0 : _c.parts) != null ? _d : [];
1214
- const usageMetadata = response.usageMetadata;
1344
+ const parts = [...continuedParts, ...(_i = (_h = candidate == null ? void 0 : candidate.content) == null ? void 0 : _h.parts) != null ? _i : []];
1345
+ const usageMetadata = addGoogleGenerativeAIUsageMetadata(
1346
+ continuedUsageMetadata,
1347
+ (_j = response.usageMetadata) != null ? _j : void 0
1348
+ );
1215
1349
  let lastCodeExecutionToolCallId;
1216
1350
  for (const part of parts) {
1217
- if ("executableCode" in part && ((_e = part.executableCode) == null ? void 0 : _e.code)) {
1351
+ if ("executableCode" in part && ((_k = part.executableCode) == null ? void 0 : _k.code)) {
1218
1352
  const toolCallId = this.config.generateId();
1219
1353
  lastCodeExecutionToolCallId = toolCallId;
1220
1354
  content.push({
@@ -1255,7 +1389,7 @@ var GoogleGenerativeAILanguageModel = class {
1255
1389
  } else if ("functionCall" in part) {
1256
1390
  content.push({
1257
1391
  type: "tool-call",
1258
- toolCallId: (_f = part.functionCall.id) != null ? _f : this.config.generateId(),
1392
+ toolCallId: (_l = part.functionCall.id) != null ? _l : this.config.generateId(),
1259
1393
  toolName: part.functionCall.name,
1260
1394
  input: JSON.stringify(part.functionCall.args),
1261
1395
  providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
@@ -1268,10 +1402,10 @@ var GoogleGenerativeAILanguageModel = class {
1268
1402
  });
1269
1403
  }
1270
1404
  }
1271
- const sources = (_g = extractSources({
1405
+ const sources = (_m = extractSources({
1272
1406
  groundingMetadata: candidate == null ? void 0 : candidate.groundingMetadata,
1273
1407
  generateId: this.config.generateId
1274
- })) != null ? _g : [];
1408
+ })) != null ? _m : [];
1275
1409
  for (const source of sources) {
1276
1410
  content.push(source);
1277
1411
  }
@@ -1282,20 +1416,22 @@ var GoogleGenerativeAILanguageModel = class {
1282
1416
  hasToolCalls: content.some((part) => part.type === "tool-call")
1283
1417
  }),
1284
1418
  usage: {
1285
- inputTokens: (_h = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _h : void 0,
1286
- outputTokens: (_i = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _i : void 0,
1287
- totalTokens: (_j = usageMetadata == null ? void 0 : usageMetadata.totalTokenCount) != null ? _j : void 0,
1288
- reasoningTokens: (_k = usageMetadata == null ? void 0 : usageMetadata.thoughtsTokenCount) != null ? _k : void 0,
1289
- cachedInputTokens: (_l = usageMetadata == null ? void 0 : usageMetadata.cachedContentTokenCount) != null ? _l : void 0
1419
+ inputTokens: (_n = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _n : void 0,
1420
+ outputTokens: (_o = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _o : void 0,
1421
+ totalTokens: (_p = usageMetadata == null ? void 0 : usageMetadata.totalTokenCount) != null ? _p : void 0,
1422
+ reasoningTokens: (_q = usageMetadata == null ? void 0 : usageMetadata.thoughtsTokenCount) != null ? _q : void 0,
1423
+ cachedInputTokens: (_r = usageMetadata == null ? void 0 : usageMetadata.cachedContentTokenCount) != null ? _r : void 0
1290
1424
  },
1291
1425
  warnings,
1292
1426
  providerMetadata: {
1293
1427
  google: {
1294
- promptFeedback: (_m = response.promptFeedback) != null ? _m : null,
1295
- groundingMetadata: (_n = candidate == null ? void 0 : candidate.groundingMetadata) != null ? _n : null,
1296
- urlContextMetadata: (_o = candidate == null ? void 0 : candidate.urlContextMetadata) != null ? _o : null,
1297
- safetyRatings: (_p = candidate == null ? void 0 : candidate.safetyRatings) != null ? _p : null,
1298
- serviceTier: (_q = response.serviceTier) != null ? _q : null,
1428
+ promptFeedback: (_s = response.promptFeedback) != null ? _s : null,
1429
+ groundingMetadata: (_t = candidate == null ? void 0 : candidate.groundingMetadata) != null ? _t : null,
1430
+ urlContextMetadata: (_u = candidate == null ? void 0 : candidate.urlContextMetadata) != null ? _u : null,
1431
+ safetyRatings: (_v = candidate == null ? void 0 : candidate.safetyRatings) != null ? _v : null,
1432
+ serviceTier: (_w = response.serviceTier) != null ? _w : null,
1433
+ ...(candidate == null ? void 0 : candidate.continuationToken) != null ? { continuationToken: candidate.continuationToken } : {},
1434
+ ...continuedUsageMetadata != null && firstPromptTokenCount != null ? { initialPromptTokenCount: firstPromptTokenCount } : {},
1299
1435
  usageMetadata: usageMetadata != null ? usageMetadata : null
1300
1436
  }
1301
1437
  },
@@ -1314,17 +1450,27 @@ var GoogleGenerativeAILanguageModel = class {
1314
1450
  await (0, import_provider_utils4.resolve)(this.config.headers),
1315
1451
  options.headers
1316
1452
  );
1317
- const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
1453
+ const streamGenerateContent = (body2) => (0, import_provider_utils4.postJsonToApi)({
1318
1454
  url: `${this.config.baseURL}/${getModelPath(
1319
1455
  this.modelId
1320
1456
  )}:streamGenerateContent?alt=sse`,
1321
1457
  headers,
1322
- body: args,
1458
+ body: body2,
1323
1459
  failedResponseHandler: googleFailedResponseHandler,
1324
1460
  successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(chunkSchema),
1325
1461
  abortSignal: options.abortSignal,
1326
1462
  fetch: this.config.fetch
1327
1463
  });
1464
+ const { responseHeaders, value: firstResponse } = await streamGenerateContent(args);
1465
+ const response = continueGoogleStream({
1466
+ stream: firstResponse,
1467
+ getContinuationToken: (chunk) => {
1468
+ var _a, _b;
1469
+ const candidate = (_a = chunk.candidates) == null ? void 0 : _a[0];
1470
+ return (candidate == null ? void 0 : candidate.finishReason) === "CONTINUATION" ? (_b = candidate.continuationToken) != null ? _b : void 0 : void 0;
1471
+ },
1472
+ continueStream: async (continuationToken) => (await streamGenerateContent({ ...args, continuationToken })).value
1473
+ });
1328
1474
  let finishReason = "unknown";
1329
1475
  const usage = {
1330
1476
  inputTokens: void 0,
@@ -1335,6 +1481,10 @@ var GoogleGenerativeAILanguageModel = class {
1335
1481
  let lastGroundingMetadata = null;
1336
1482
  let lastUrlContextMetadata = null;
1337
1483
  let serviceTier = null;
1484
+ let requestUsageMetadata;
1485
+ let continuedUsageMetadata;
1486
+ let lastContinuationToken = null;
1487
+ let initialPromptTokenCount = void 0;
1338
1488
  const generateId2 = this.config.generateId;
1339
1489
  let hasToolCalls = false;
1340
1490
  let currentTextBlockId = null;
@@ -1358,7 +1508,13 @@ var GoogleGenerativeAILanguageModel = class {
1358
1508
  return;
1359
1509
  }
1360
1510
  const value = chunk.value;
1361
- const usageMetadata = value.usageMetadata;
1511
+ if (value.usageMetadata != null) {
1512
+ requestUsageMetadata = value.usageMetadata;
1513
+ }
1514
+ const usageMetadata = value.usageMetadata == null ? void 0 : addGoogleGenerativeAIUsageMetadata(
1515
+ continuedUsageMetadata,
1516
+ requestUsageMetadata
1517
+ );
1362
1518
  if (usageMetadata != null) {
1363
1519
  usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0;
1364
1520
  usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0;
@@ -1370,6 +1526,19 @@ var GoogleGenerativeAILanguageModel = class {
1370
1526
  serviceTier = value.serviceTier;
1371
1527
  }
1372
1528
  const candidate = (_f = value.candidates) == null ? void 0 : _f[0];
1529
+ if ((candidate == null ? void 0 : candidate.continuationToken) != null) {
1530
+ lastContinuationToken = candidate.continuationToken;
1531
+ }
1532
+ if ((candidate == null ? void 0 : candidate.finishReason) === "CONTINUATION") {
1533
+ if (continuedUsageMetadata == null) {
1534
+ initialPromptTokenCount = requestUsageMetadata == null ? void 0 : requestUsageMetadata.promptTokenCount;
1535
+ }
1536
+ continuedUsageMetadata = addGoogleGenerativeAIUsageMetadata(
1537
+ continuedUsageMetadata,
1538
+ requestUsageMetadata
1539
+ );
1540
+ requestUsageMetadata = void 0;
1541
+ }
1373
1542
  if (candidate == null) {
1374
1543
  const promptBlockReason2 = (_g = value.promptFeedback) == null ? void 0 : _g.blockReason;
1375
1544
  if (promptBlockReason2 != null) {
@@ -1552,7 +1721,12 @@ var GoogleGenerativeAILanguageModel = class {
1552
1721
  groundingMetadata: lastGroundingMetadata,
1553
1722
  urlContextMetadata: lastUrlContextMetadata,
1554
1723
  safetyRatings: (_o = candidate.safetyRatings) != null ? _o : null,
1555
- serviceTier
1724
+ serviceTier,
1725
+ // Only surface the token when the response stopped early
1726
+ // (budget used up, or continuing failed), not for the
1727
+ // checkpoint tokens of a stream that finished normally.
1728
+ ...lastContinuationToken != null && (rawFinishReason === "MAX_TOKENS" || rawFinishReason === "CONTINUATION") ? { continuationToken: lastContinuationToken } : {},
1729
+ ...initialPromptTokenCount != null ? { initialPromptTokenCount } : {}
1556
1730
  }
1557
1731
  };
1558
1732
  if (usageMetadata != null) {
@@ -1823,6 +1997,7 @@ var responseSchema = (0, import_provider_utils4.lazySchema)(
1823
1997
  import_v43.z.object({
1824
1998
  content: getContentSchema().nullish().or(import_v43.z.object({}).strict()),
1825
1999
  finishReason: import_v43.z.string().nullish(),
2000
+ continuationToken: import_v43.z.string().nullish(),
1826
2001
  safetyRatings: import_v43.z.array(getSafetyRatingSchema()).nullish(),
1827
2002
  groundingMetadata: getGroundingMetadataSchema().nullish(),
1828
2003
  urlContextMetadata: getUrlContextMetadataSchema().nullish()
@@ -1844,6 +2019,7 @@ var chunkSchema = (0, import_provider_utils4.lazySchema)(
1844
2019
  import_v43.z.object({
1845
2020
  content: getContentSchema().nullish(),
1846
2021
  finishReason: import_v43.z.string().nullish(),
2022
+ continuationToken: import_v43.z.string().nullish(),
1847
2023
  safetyRatings: import_v43.z.array(getSafetyRatingSchema()).nullish(),
1848
2024
  groundingMetadata: getGroundingMetadataSchema().nullish(),
1849
2025
  urlContextMetadata: getUrlContextMetadataSchema().nullish()