@ai-sdk/google 2.0.107 → 2.0.109

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.
@@ -28,6 +28,7 @@ __export(index_exports, {
28
28
  module.exports = __toCommonJS(index_exports);
29
29
 
30
30
  // src/google-generative-ai-language-model.ts
31
+ var import_provider4 = require("@ai-sdk/provider");
31
32
  var import_provider_utils4 = require("@ai-sdk/provider-utils");
32
33
  var import_v43 = require("zod/v4");
33
34
 
@@ -503,7 +504,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
503
504
  functionCall: {
504
505
  ...part.toolCallId != null ? { id: part.toolCallId } : {},
505
506
  name: part.toolName,
506
- args: part.input
507
+ args: parseToolCallInput(part.input)
507
508
  },
508
509
  thoughtSignature: effectiveThoughtSignature
509
510
  };
@@ -531,7 +532,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
531
532
  name: part.toolName,
532
533
  response: {
533
534
  name: part.toolName,
534
- content: output.value
535
+ content: serializeFunctionResponseContent(output.value)
535
536
  }
536
537
  }
537
538
  });
@@ -622,11 +623,46 @@ function appendLegacyToolResultParts({
622
623
  );
623
624
  break;
624
625
  default:
625
- parts.push({ text: JSON.stringify(contentPart) });
626
+ parts.push({ text: (0, import_provider_utils.stringifyWithBigIntAndCycles)(contentPart) });
626
627
  break;
627
628
  }
628
629
  }
629
630
  }
631
+ function serializeFunctionResponseContent(value) {
632
+ return containsNonJsonValue(value) ? (0, import_provider_utils.secureJsonParse)((0, import_provider_utils.stringifyWithBigIntAndCycles)(value)) : value;
633
+ }
634
+ function containsNonJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
635
+ if (typeof value === "bigint") {
636
+ return true;
637
+ }
638
+ if (typeof value !== "object" || value === null) {
639
+ return false;
640
+ }
641
+ if (typeof value.toJSON === "function") {
642
+ return true;
643
+ }
644
+ if (ancestors.has(value)) {
645
+ return true;
646
+ }
647
+ ancestors.add(value);
648
+ try {
649
+ return Object.values(value).some(
650
+ (item) => containsNonJsonValue(item, ancestors)
651
+ );
652
+ } finally {
653
+ ancestors.delete(value);
654
+ }
655
+ }
656
+ function parseToolCallInput(input) {
657
+ if (typeof input !== "string") {
658
+ return input;
659
+ }
660
+ try {
661
+ return (0, import_provider_utils.secureJsonParse)(input);
662
+ } catch (e) {
663
+ return input;
664
+ }
665
+ }
630
666
 
631
667
  // src/get-model-path.ts
632
668
  function getModelPath(modelId) {
@@ -636,15 +672,16 @@ function getModelPath(modelId) {
636
672
  // src/google-error.ts
637
673
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
638
674
  var import_v4 = require("zod/v4");
675
+ var getGoogleErrorSchema = () => import_v4.z.object({
676
+ code: import_v4.z.number().nullable(),
677
+ message: import_v4.z.string(),
678
+ status: import_v4.z.string(),
679
+ details: import_v4.z.array(import_v4.z.unknown()).nullish()
680
+ });
639
681
  var googleErrorDataSchema = (0, import_provider_utils2.lazySchema)(
640
682
  () => (0, import_provider_utils2.zodSchema)(
641
683
  import_v4.z.object({
642
- error: import_v4.z.object({
643
- code: import_v4.z.number().nullable(),
644
- message: import_v4.z.string(),
645
- status: import_v4.z.string(),
646
- details: import_v4.z.array(import_v4.z.unknown()).nullish()
647
- })
684
+ error: getGoogleErrorSchema()
648
685
  })
649
686
  )
650
687
  );
@@ -652,6 +689,39 @@ var googleFailedResponseHandler = (0, import_provider_utils2.createJsonErrorResp
652
689
  errorSchema: googleErrorDataSchema,
653
690
  errorToMessage: (data) => data.error.message
654
691
  });
692
+ function mapGoogleErrorStatusToHttpStatusCode(status) {
693
+ switch (status) {
694
+ case "CANCELLED":
695
+ return 499;
696
+ case "INVALID_ARGUMENT":
697
+ case "FAILED_PRECONDITION":
698
+ case "OUT_OF_RANGE":
699
+ return 400;
700
+ case "DEADLINE_EXCEEDED":
701
+ return 504;
702
+ case "NOT_FOUND":
703
+ return 404;
704
+ case "ALREADY_EXISTS":
705
+ case "ABORTED":
706
+ return 409;
707
+ case "PERMISSION_DENIED":
708
+ return 403;
709
+ case "UNAUTHENTICATED":
710
+ return 401;
711
+ case "RESOURCE_EXHAUSTED":
712
+ return 429;
713
+ case "UNIMPLEMENTED":
714
+ return 501;
715
+ case "UNKNOWN":
716
+ case "INTERNAL":
717
+ case "DATA_LOSS":
718
+ return 500;
719
+ case "UNAVAILABLE":
720
+ return 503;
721
+ default:
722
+ return void 0;
723
+ }
724
+ }
655
725
 
656
726
  // src/google-generative-ai-options.ts
657
727
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
@@ -854,6 +924,9 @@ function prepareTools({
854
924
  modelId,
855
925
  isVertexProvider = false
856
926
  }) {
927
+ if ((toolChoice == null ? void 0 : toolChoice.type) === "none") {
928
+ tools = tools == null ? void 0 : tools.filter((tool) => tool.type === "function");
929
+ }
857
930
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
858
931
  const toolWarnings = [];
859
932
  const { supportsGemini2Tools, supportsFileSearch, usesGemini3Features } = getGoogleModelCapabilities(modelId);
@@ -869,7 +942,9 @@ function prepareTools({
869
942
  toolWarnings.push({
870
943
  type: "unsupported-tool",
871
944
  tool: tools.find((tool) => tool.type === "function"),
872
- details: `Cannot mix function tools with provider-defined tools in the same request. Falling back to provider-defined tools only. The following function tools will be ignored: ${functionTools.map((t) => t.name).join(", ")}. Please use either function tools or provider-defined tools, but not both.`
945
+ details: `Cannot mix function tools with provider-defined tools in the same request. Falling back to provider-defined tools only. The following function tools will be ignored: ${functionTools.map((t) => t.name).join(
946
+ ", "
947
+ )}. Please use either function tools or provider-defined tools, but not both.`
873
948
  });
874
949
  }
875
950
  if (hasProviderDefinedTools) {
@@ -1458,10 +1533,11 @@ var GoogleGenerativeAILanguageModel = class {
1458
1533
  await (0, import_provider_utils4.resolve)(this.config.headers),
1459
1534
  options.headers
1460
1535
  );
1536
+ const url = `${this.config.baseURL}/${getModelPath(
1537
+ this.modelId
1538
+ )}:streamGenerateContent?alt=sse`;
1461
1539
  const streamGenerateContent = (body2) => (0, import_provider_utils4.postJsonToApi)({
1462
- url: `${this.config.baseURL}/${getModelPath(
1463
- this.modelId
1464
- )}:streamGenerateContent?alt=sse`,
1540
+ url,
1465
1541
  headers,
1466
1542
  body: body2,
1467
1543
  failedResponseHandler: googleFailedResponseHandler,
@@ -1520,7 +1596,7 @@ var GoogleGenerativeAILanguageModel = class {
1520
1596
  controller.enqueue({ type: "stream-start", warnings });
1521
1597
  },
1522
1598
  transform(chunk, controller) {
1523
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
1599
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1524
1600
  if (options.includeRawChunks) {
1525
1601
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1526
1602
  }
@@ -1529,6 +1605,23 @@ var GoogleGenerativeAILanguageModel = class {
1529
1605
  return;
1530
1606
  }
1531
1607
  const value = chunk.value;
1608
+ if (value.error != null) {
1609
+ finishReason = "error";
1610
+ const error = value.error;
1611
+ controller.enqueue({
1612
+ type: "error",
1613
+ error: new import_provider4.APICallError({
1614
+ message: error.message,
1615
+ url,
1616
+ requestBodyValues: args,
1617
+ statusCode: (_a = error.code) != null ? _a : mapGoogleErrorStatusToHttpStatusCode(error.status),
1618
+ responseHeaders,
1619
+ responseBody: JSON.stringify({ error }),
1620
+ data: error
1621
+ })
1622
+ });
1623
+ return;
1624
+ }
1532
1625
  if (value.usageMetadata != null) {
1533
1626
  requestUsageMetadata = value.usageMetadata;
1534
1627
  }
@@ -1537,16 +1630,16 @@ var GoogleGenerativeAILanguageModel = class {
1537
1630
  requestUsageMetadata
1538
1631
  );
1539
1632
  if (usageMetadata != null) {
1540
- usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0;
1541
- usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0;
1542
- usage.totalTokens = (_c = usageMetadata.totalTokenCount) != null ? _c : void 0;
1543
- usage.reasoningTokens = (_d = usageMetadata.thoughtsTokenCount) != null ? _d : void 0;
1544
- usage.cachedInputTokens = (_e = usageMetadata.cachedContentTokenCount) != null ? _e : void 0;
1633
+ usage.inputTokens = (_b = usageMetadata.promptTokenCount) != null ? _b : void 0;
1634
+ usage.outputTokens = (_c = usageMetadata.candidatesTokenCount) != null ? _c : void 0;
1635
+ usage.totalTokens = (_d = usageMetadata.totalTokenCount) != null ? _d : void 0;
1636
+ usage.reasoningTokens = (_e = usageMetadata.thoughtsTokenCount) != null ? _e : void 0;
1637
+ usage.cachedInputTokens = (_f = usageMetadata.cachedContentTokenCount) != null ? _f : void 0;
1545
1638
  }
1546
1639
  if (value.serviceTier != null) {
1547
1640
  serviceTier = value.serviceTier;
1548
1641
  }
1549
- const candidate = (_f = value.candidates) == null ? void 0 : _f[0];
1642
+ const candidate = (_g = value.candidates) == null ? void 0 : _g[0];
1550
1643
  if ((candidate == null ? void 0 : candidate.continuationToken) != null) {
1551
1644
  lastContinuationToken = candidate.continuationToken;
1552
1645
  }
@@ -1561,12 +1654,12 @@ var GoogleGenerativeAILanguageModel = class {
1561
1654
  requestUsageMetadata = void 0;
1562
1655
  }
1563
1656
  if (candidate == null) {
1564
- const promptBlockReason2 = (_g = value.promptFeedback) == null ? void 0 : _g.blockReason;
1657
+ const promptBlockReason2 = (_h = value.promptFeedback) == null ? void 0 : _h.blockReason;
1565
1658
  if (promptBlockReason2 != null) {
1566
1659
  finishReason = "content-filter";
1567
1660
  providerMetadata = {
1568
1661
  google: {
1569
- promptFeedback: (_h = value.promptFeedback) != null ? _h : null,
1662
+ promptFeedback: (_i = value.promptFeedback) != null ? _i : null,
1570
1663
  groundingMetadata: lastGroundingMetadata,
1571
1664
  urlContextMetadata: lastUrlContextMetadata,
1572
1665
  safetyRatings: null,
@@ -1599,9 +1692,9 @@ var GoogleGenerativeAILanguageModel = class {
1599
1692
  }
1600
1693
  }
1601
1694
  if (content != null) {
1602
- const parts = (_i = content.parts) != null ? _i : [];
1695
+ const parts = (_j = content.parts) != null ? _j : [];
1603
1696
  for (const part of parts) {
1604
- if ("executableCode" in part && ((_j = part.executableCode) == null ? void 0 : _j.code)) {
1697
+ if ("executableCode" in part && ((_k = part.executableCode) == null ? void 0 : _k.code)) {
1605
1698
  const toolCallId = generateId2();
1606
1699
  lastCodeExecutionToolCallId = toolCallId;
1607
1700
  controller.enqueue({
@@ -1728,9 +1821,9 @@ var GoogleGenerativeAILanguageModel = class {
1728
1821
  }
1729
1822
  }
1730
1823
  }
1731
- const promptBlockReason = (_k = value.promptFeedback) == null ? void 0 : _k.blockReason;
1824
+ const promptBlockReason = (_l = value.promptFeedback) == null ? void 0 : _l.blockReason;
1732
1825
  const isPromptBlocked = candidate.finishReason == null && promptBlockReason != null;
1733
- const rawFinishReason = (_m = (_l = candidate.finishReason) != null ? _l : promptBlockReason) != null ? _m : void 0;
1826
+ const rawFinishReason = (_n = (_m = candidate.finishReason) != null ? _m : promptBlockReason) != null ? _n : void 0;
1734
1827
  if (rawFinishReason != null) {
1735
1828
  finishReason = isPromptBlocked ? "content-filter" : mapGoogleGenerativeAIFinishReason({
1736
1829
  finishReason: rawFinishReason,
@@ -1738,10 +1831,10 @@ var GoogleGenerativeAILanguageModel = class {
1738
1831
  });
1739
1832
  providerMetadata = {
1740
1833
  google: {
1741
- promptFeedback: (_n = value.promptFeedback) != null ? _n : null,
1834
+ promptFeedback: (_o = value.promptFeedback) != null ? _o : null,
1742
1835
  groundingMetadata: lastGroundingMetadata,
1743
1836
  urlContextMetadata: lastUrlContextMetadata,
1744
- safetyRatings: (_o = candidate.safetyRatings) != null ? _o : null,
1837
+ safetyRatings: (_p = candidate.safetyRatings) != null ? _p : null,
1745
1838
  serviceTier,
1746
1839
  // Only surface the token when the response stopped early
1747
1840
  // (budget used up, or continuing failed), not for the
@@ -2048,6 +2141,7 @@ var responseSchema = (0, import_provider_utils4.lazySchema)(
2048
2141
  var chunkSchema = (0, import_provider_utils4.lazySchema)(
2049
2142
  () => (0, import_provider_utils4.zodSchema)(
2050
2143
  import_v43.z.object({
2144
+ error: getGoogleErrorSchema().nullish(),
2051
2145
  candidates: import_v43.z.array(
2052
2146
  import_v43.z.object({
2053
2147
  content: getContentSchema().nullish(),