@ai-sdk/google 2.0.107 → 2.0.108

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.
@@ -1,4 +1,7 @@
1
1
  // src/google-generative-ai-language-model.ts
2
+ import {
3
+ APICallError
4
+ } from "@ai-sdk/provider";
2
5
  import {
3
6
  combineHeaders,
4
7
  createEventSourceResponseHandler,
@@ -387,7 +390,11 @@ function isEmptyObjectSchema(jsonSchema) {
387
390
  import {
388
391
  UnsupportedFunctionalityError as UnsupportedFunctionalityError2
389
392
  } from "@ai-sdk/provider";
390
- import { convertToBase64 } from "@ai-sdk/provider-utils";
393
+ import {
394
+ stringifyWithBigIntAndCycles,
395
+ secureJsonParse,
396
+ convertToBase64
397
+ } from "@ai-sdk/provider-utils";
391
398
  var SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
392
399
  function convertToGoogleGenerativeAIMessages(prompt, options) {
393
400
  var _a, _b, _c;
@@ -488,7 +495,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
488
495
  functionCall: {
489
496
  ...part.toolCallId != null ? { id: part.toolCallId } : {},
490
497
  name: part.toolName,
491
- args: part.input
498
+ args: parseToolCallInput(part.input)
492
499
  },
493
500
  thoughtSignature: effectiveThoughtSignature
494
501
  };
@@ -516,7 +523,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
516
523
  name: part.toolName,
517
524
  response: {
518
525
  name: part.toolName,
519
- content: output.value
526
+ content: serializeFunctionResponseContent(output.value)
520
527
  }
521
528
  }
522
529
  });
@@ -607,11 +614,46 @@ function appendLegacyToolResultParts({
607
614
  );
608
615
  break;
609
616
  default:
610
- parts.push({ text: JSON.stringify(contentPart) });
617
+ parts.push({ text: stringifyWithBigIntAndCycles(contentPart) });
611
618
  break;
612
619
  }
613
620
  }
614
621
  }
622
+ function serializeFunctionResponseContent(value) {
623
+ return containsNonJsonValue(value) ? secureJsonParse(stringifyWithBigIntAndCycles(value)) : value;
624
+ }
625
+ function containsNonJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
626
+ if (typeof value === "bigint") {
627
+ return true;
628
+ }
629
+ if (typeof value !== "object" || value === null) {
630
+ return false;
631
+ }
632
+ if (typeof value.toJSON === "function") {
633
+ return true;
634
+ }
635
+ if (ancestors.has(value)) {
636
+ return true;
637
+ }
638
+ ancestors.add(value);
639
+ try {
640
+ return Object.values(value).some(
641
+ (item) => containsNonJsonValue(item, ancestors)
642
+ );
643
+ } finally {
644
+ ancestors.delete(value);
645
+ }
646
+ }
647
+ function parseToolCallInput(input) {
648
+ if (typeof input !== "string") {
649
+ return input;
650
+ }
651
+ try {
652
+ return secureJsonParse(input);
653
+ } catch (e) {
654
+ return input;
655
+ }
656
+ }
615
657
 
616
658
  // src/get-model-path.ts
617
659
  function getModelPath(modelId) {
@@ -625,15 +667,16 @@ import {
625
667
  zodSchema
626
668
  } from "@ai-sdk/provider-utils";
627
669
  import { z } from "zod/v4";
670
+ var getGoogleErrorSchema = () => z.object({
671
+ code: z.number().nullable(),
672
+ message: z.string(),
673
+ status: z.string(),
674
+ details: z.array(z.unknown()).nullish()
675
+ });
628
676
  var googleErrorDataSchema = lazySchema(
629
677
  () => zodSchema(
630
678
  z.object({
631
- error: z.object({
632
- code: z.number().nullable(),
633
- message: z.string(),
634
- status: z.string(),
635
- details: z.array(z.unknown()).nullish()
636
- })
679
+ error: getGoogleErrorSchema()
637
680
  })
638
681
  )
639
682
  );
@@ -641,6 +684,39 @@ var googleFailedResponseHandler = createJsonErrorResponseHandler({
641
684
  errorSchema: googleErrorDataSchema,
642
685
  errorToMessage: (data) => data.error.message
643
686
  });
687
+ function mapGoogleErrorStatusToHttpStatusCode(status) {
688
+ switch (status) {
689
+ case "CANCELLED":
690
+ return 499;
691
+ case "INVALID_ARGUMENT":
692
+ case "FAILED_PRECONDITION":
693
+ case "OUT_OF_RANGE":
694
+ return 400;
695
+ case "DEADLINE_EXCEEDED":
696
+ return 504;
697
+ case "NOT_FOUND":
698
+ return 404;
699
+ case "ALREADY_EXISTS":
700
+ case "ABORTED":
701
+ return 409;
702
+ case "PERMISSION_DENIED":
703
+ return 403;
704
+ case "UNAUTHENTICATED":
705
+ return 401;
706
+ case "RESOURCE_EXHAUSTED":
707
+ return 429;
708
+ case "UNIMPLEMENTED":
709
+ return 501;
710
+ case "UNKNOWN":
711
+ case "INTERNAL":
712
+ case "DATA_LOSS":
713
+ return 500;
714
+ case "UNAVAILABLE":
715
+ return 503;
716
+ default:
717
+ return void 0;
718
+ }
719
+ }
644
720
 
645
721
  // src/google-generative-ai-options.ts
646
722
  import {
@@ -1452,10 +1528,11 @@ var GoogleGenerativeAILanguageModel = class {
1452
1528
  await resolve(this.config.headers),
1453
1529
  options.headers
1454
1530
  );
1531
+ const url = `${this.config.baseURL}/${getModelPath(
1532
+ this.modelId
1533
+ )}:streamGenerateContent?alt=sse`;
1455
1534
  const streamGenerateContent = (body2) => postJsonToApi({
1456
- url: `${this.config.baseURL}/${getModelPath(
1457
- this.modelId
1458
- )}:streamGenerateContent?alt=sse`,
1535
+ url,
1459
1536
  headers,
1460
1537
  body: body2,
1461
1538
  failedResponseHandler: googleFailedResponseHandler,
@@ -1514,7 +1591,7 @@ var GoogleGenerativeAILanguageModel = class {
1514
1591
  controller.enqueue({ type: "stream-start", warnings });
1515
1592
  },
1516
1593
  transform(chunk, controller) {
1517
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
1594
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1518
1595
  if (options.includeRawChunks) {
1519
1596
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1520
1597
  }
@@ -1523,6 +1600,23 @@ var GoogleGenerativeAILanguageModel = class {
1523
1600
  return;
1524
1601
  }
1525
1602
  const value = chunk.value;
1603
+ if (value.error != null) {
1604
+ finishReason = "error";
1605
+ const error = value.error;
1606
+ controller.enqueue({
1607
+ type: "error",
1608
+ error: new APICallError({
1609
+ message: error.message,
1610
+ url,
1611
+ requestBodyValues: args,
1612
+ statusCode: (_a = error.code) != null ? _a : mapGoogleErrorStatusToHttpStatusCode(error.status),
1613
+ responseHeaders,
1614
+ responseBody: JSON.stringify({ error }),
1615
+ data: error
1616
+ })
1617
+ });
1618
+ return;
1619
+ }
1526
1620
  if (value.usageMetadata != null) {
1527
1621
  requestUsageMetadata = value.usageMetadata;
1528
1622
  }
@@ -1531,16 +1625,16 @@ var GoogleGenerativeAILanguageModel = class {
1531
1625
  requestUsageMetadata
1532
1626
  );
1533
1627
  if (usageMetadata != null) {
1534
- usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0;
1535
- usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0;
1536
- usage.totalTokens = (_c = usageMetadata.totalTokenCount) != null ? _c : void 0;
1537
- usage.reasoningTokens = (_d = usageMetadata.thoughtsTokenCount) != null ? _d : void 0;
1538
- usage.cachedInputTokens = (_e = usageMetadata.cachedContentTokenCount) != null ? _e : void 0;
1628
+ usage.inputTokens = (_b = usageMetadata.promptTokenCount) != null ? _b : void 0;
1629
+ usage.outputTokens = (_c = usageMetadata.candidatesTokenCount) != null ? _c : void 0;
1630
+ usage.totalTokens = (_d = usageMetadata.totalTokenCount) != null ? _d : void 0;
1631
+ usage.reasoningTokens = (_e = usageMetadata.thoughtsTokenCount) != null ? _e : void 0;
1632
+ usage.cachedInputTokens = (_f = usageMetadata.cachedContentTokenCount) != null ? _f : void 0;
1539
1633
  }
1540
1634
  if (value.serviceTier != null) {
1541
1635
  serviceTier = value.serviceTier;
1542
1636
  }
1543
- const candidate = (_f = value.candidates) == null ? void 0 : _f[0];
1637
+ const candidate = (_g = value.candidates) == null ? void 0 : _g[0];
1544
1638
  if ((candidate == null ? void 0 : candidate.continuationToken) != null) {
1545
1639
  lastContinuationToken = candidate.continuationToken;
1546
1640
  }
@@ -1555,12 +1649,12 @@ var GoogleGenerativeAILanguageModel = class {
1555
1649
  requestUsageMetadata = void 0;
1556
1650
  }
1557
1651
  if (candidate == null) {
1558
- const promptBlockReason2 = (_g = value.promptFeedback) == null ? void 0 : _g.blockReason;
1652
+ const promptBlockReason2 = (_h = value.promptFeedback) == null ? void 0 : _h.blockReason;
1559
1653
  if (promptBlockReason2 != null) {
1560
1654
  finishReason = "content-filter";
1561
1655
  providerMetadata = {
1562
1656
  google: {
1563
- promptFeedback: (_h = value.promptFeedback) != null ? _h : null,
1657
+ promptFeedback: (_i = value.promptFeedback) != null ? _i : null,
1564
1658
  groundingMetadata: lastGroundingMetadata,
1565
1659
  urlContextMetadata: lastUrlContextMetadata,
1566
1660
  safetyRatings: null,
@@ -1593,9 +1687,9 @@ var GoogleGenerativeAILanguageModel = class {
1593
1687
  }
1594
1688
  }
1595
1689
  if (content != null) {
1596
- const parts = (_i = content.parts) != null ? _i : [];
1690
+ const parts = (_j = content.parts) != null ? _j : [];
1597
1691
  for (const part of parts) {
1598
- if ("executableCode" in part && ((_j = part.executableCode) == null ? void 0 : _j.code)) {
1692
+ if ("executableCode" in part && ((_k = part.executableCode) == null ? void 0 : _k.code)) {
1599
1693
  const toolCallId = generateId2();
1600
1694
  lastCodeExecutionToolCallId = toolCallId;
1601
1695
  controller.enqueue({
@@ -1722,9 +1816,9 @@ var GoogleGenerativeAILanguageModel = class {
1722
1816
  }
1723
1817
  }
1724
1818
  }
1725
- const promptBlockReason = (_k = value.promptFeedback) == null ? void 0 : _k.blockReason;
1819
+ const promptBlockReason = (_l = value.promptFeedback) == null ? void 0 : _l.blockReason;
1726
1820
  const isPromptBlocked = candidate.finishReason == null && promptBlockReason != null;
1727
- const rawFinishReason = (_m = (_l = candidate.finishReason) != null ? _l : promptBlockReason) != null ? _m : void 0;
1821
+ const rawFinishReason = (_n = (_m = candidate.finishReason) != null ? _m : promptBlockReason) != null ? _n : void 0;
1728
1822
  if (rawFinishReason != null) {
1729
1823
  finishReason = isPromptBlocked ? "content-filter" : mapGoogleGenerativeAIFinishReason({
1730
1824
  finishReason: rawFinishReason,
@@ -1732,10 +1826,10 @@ var GoogleGenerativeAILanguageModel = class {
1732
1826
  });
1733
1827
  providerMetadata = {
1734
1828
  google: {
1735
- promptFeedback: (_n = value.promptFeedback) != null ? _n : null,
1829
+ promptFeedback: (_o = value.promptFeedback) != null ? _o : null,
1736
1830
  groundingMetadata: lastGroundingMetadata,
1737
1831
  urlContextMetadata: lastUrlContextMetadata,
1738
- safetyRatings: (_o = candidate.safetyRatings) != null ? _o : null,
1832
+ safetyRatings: (_p = candidate.safetyRatings) != null ? _p : null,
1739
1833
  serviceTier,
1740
1834
  // Only surface the token when the response stopped early
1741
1835
  // (budget used up, or continuing failed), not for the
@@ -2042,6 +2136,7 @@ var responseSchema = lazySchema3(
2042
2136
  var chunkSchema = lazySchema3(
2043
2137
  () => zodSchema3(
2044
2138
  z3.object({
2139
+ error: getGoogleErrorSchema().nullish(),
2045
2140
  candidates: z3.array(
2046
2141
  z3.object({
2047
2142
  content: getContentSchema().nullish(),