@ai-sdk/google 3.0.70 → 3.0.72

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.
package/dist/index.mjs CHANGED
@@ -3,11 +3,11 @@ import {
3
3
  generateId as generateId2,
4
4
  loadApiKey,
5
5
  withoutTrailingSlash,
6
- withUserAgentSuffix
6
+ withUserAgentSuffix as withUserAgentSuffix2
7
7
  } from "@ai-sdk/provider-utils";
8
8
 
9
9
  // src/version.ts
10
- var VERSION = true ? "3.0.70" : "0.0.0-test";
10
+ var VERSION = true ? "3.0.72" : "0.0.0-test";
11
11
 
12
12
  // src/google-generative-ai-embedding-model.ts
13
13
  import {
@@ -1499,7 +1499,7 @@ var GoogleGenerativeAILanguageModel = class {
1499
1499
  };
1500
1500
  }
1501
1501
  async doGenerate(options) {
1502
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1502
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1503
1503
  const { args, warnings, providerOptionsName } = await this.getArgs(options);
1504
1504
  const mergedHeaders = combineHeaders2(
1505
1505
  await resolve2(this.config.headers),
@@ -1567,12 +1567,12 @@ var GoogleGenerativeAILanguageModel = class {
1567
1567
  providerMetadata: thoughtSignatureMetadata
1568
1568
  });
1569
1569
  }
1570
- } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
1570
+ } else if ("functionCall" in part && part.functionCall.name != null) {
1571
1571
  content.push({
1572
1572
  type: "tool-call",
1573
1573
  toolCallId: this.config.generateId(),
1574
1574
  toolName: part.functionCall.name,
1575
- input: JSON.stringify(part.functionCall.args),
1575
+ input: JSON.stringify((_e = part.functionCall.args) != null ? _e : {}),
1576
1576
  providerMetadata: part.thoughtSignature ? {
1577
1577
  [providerOptionsName]: {
1578
1578
  thoughtSignature: part.thoughtSignature
@@ -1594,13 +1594,13 @@ var GoogleGenerativeAILanguageModel = class {
1594
1594
  } : void 0
1595
1595
  });
1596
1596
  } else if ("toolCall" in part && part.toolCall) {
1597
- const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
1597
+ const toolCallId = (_f = part.toolCall.id) != null ? _f : this.config.generateId();
1598
1598
  lastServerToolCallId = toolCallId;
1599
1599
  content.push({
1600
1600
  type: "tool-call",
1601
1601
  toolCallId,
1602
1602
  toolName: `server:${part.toolCall.toolType}`,
1603
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1603
+ input: JSON.stringify((_g = part.toolCall.args) != null ? _g : {}),
1604
1604
  providerExecuted: true,
1605
1605
  dynamic: true,
1606
1606
  providerMetadata: part.thoughtSignature ? {
@@ -1617,12 +1617,12 @@ var GoogleGenerativeAILanguageModel = class {
1617
1617
  }
1618
1618
  });
1619
1619
  } else if ("toolResponse" in part && part.toolResponse) {
1620
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
1620
+ const responseToolCallId = (_h = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _h : this.config.generateId();
1621
1621
  content.push({
1622
1622
  type: "tool-result",
1623
1623
  toolCallId: responseToolCallId,
1624
1624
  toolName: `server:${part.toolResponse.toolType}`,
1625
- result: (_h = part.toolResponse.response) != null ? _h : {},
1625
+ result: (_i = part.toolResponse.response) != null ? _i : {},
1626
1626
  providerMetadata: part.thoughtSignature ? {
1627
1627
  [providerOptionsName]: {
1628
1628
  thoughtSignature: part.thoughtSignature,
@@ -1639,10 +1639,10 @@ var GoogleGenerativeAILanguageModel = class {
1639
1639
  lastServerToolCallId = void 0;
1640
1640
  }
1641
1641
  }
1642
- const sources = (_i = extractSources({
1642
+ const sources = (_j = extractSources({
1643
1643
  groundingMetadata: candidate.groundingMetadata,
1644
1644
  generateId: this.config.generateId
1645
- })) != null ? _i : [];
1645
+ })) != null ? _j : [];
1646
1646
  for (const source of sources) {
1647
1647
  content.push(source);
1648
1648
  }
@@ -1656,19 +1656,19 @@ var GoogleGenerativeAILanguageModel = class {
1656
1656
  (part) => part.type === "tool-call" && !part.providerExecuted
1657
1657
  )
1658
1658
  }),
1659
- raw: (_j = candidate.finishReason) != null ? _j : void 0
1659
+ raw: (_k = candidate.finishReason) != null ? _k : void 0
1660
1660
  },
1661
1661
  usage: convertGoogleGenerativeAIUsage(usageMetadata),
1662
1662
  warnings,
1663
1663
  providerMetadata: {
1664
1664
  [providerOptionsName]: {
1665
- promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
1666
- groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
1667
- urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
1668
- safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
1665
+ promptFeedback: (_l = response.promptFeedback) != null ? _l : null,
1666
+ groundingMetadata: (_m = candidate.groundingMetadata) != null ? _m : null,
1667
+ urlContextMetadata: (_n = candidate.urlContextMetadata) != null ? _n : null,
1668
+ safetyRatings: (_o = candidate.safetyRatings) != null ? _o : null,
1669
1669
  usageMetadata: usageMetadata != null ? usageMetadata : null,
1670
- finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
1671
- serviceTier: (_p = response.serviceTier) != null ? _p : null
1670
+ finishMessage: (_p = candidate.finishMessage) != null ? _p : null,
1671
+ serviceTier: (_q = response.serviceTier) != null ? _q : null
1672
1672
  }
1673
1673
  },
1674
1674
  request: { body: args },
@@ -1927,6 +1927,7 @@ var GoogleGenerativeAILanguageModel = class {
1927
1927
  const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
1928
1928
  const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
1929
1929
  const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
1930
+ const isNoArgsCompleteCall = part.functionCall.name != null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue !== true;
1930
1931
  if (isStreamingChunk) {
1931
1932
  if (part.functionCall.name != null && part.functionCall.willContinue === true) {
1932
1933
  const toolCallId = generateId3();
@@ -2023,6 +2024,28 @@ var GoogleGenerativeAILanguageModel = class {
2023
2024
  providerMetadata: providerMeta
2024
2025
  });
2025
2026
  hasToolCalls = true;
2027
+ } else if (isNoArgsCompleteCall) {
2028
+ const toolCallId = generateId3();
2029
+ const toolName = part.functionCall.name;
2030
+ controller.enqueue({
2031
+ type: "tool-input-start",
2032
+ id: toolCallId,
2033
+ toolName,
2034
+ providerMetadata: providerMeta
2035
+ });
2036
+ controller.enqueue({
2037
+ type: "tool-input-end",
2038
+ id: toolCallId,
2039
+ providerMetadata: providerMeta
2040
+ });
2041
+ controller.enqueue({
2042
+ type: "tool-call",
2043
+ toolCallId,
2044
+ toolName,
2045
+ input: "{}",
2046
+ providerMetadata: providerMeta
2047
+ });
2048
+ hasToolCalls = true;
2026
2049
  }
2027
2050
  }
2028
2051
  }
@@ -3055,8 +3078,8 @@ var googleVideoModelOptionsSchema = lazySchema12(
3055
3078
 
3056
3079
  // src/interactions/google-interactions-language-model.ts
3057
3080
  import {
3058
- combineHeaders as combineHeaders5,
3059
- createEventSourceResponseHandler as createEventSourceResponseHandler2,
3081
+ combineHeaders as combineHeaders6,
3082
+ createEventSourceResponseHandler as createEventSourceResponseHandler3,
3060
3083
  createJsonResponseHandler as createJsonResponseHandler6,
3061
3084
  generateId as defaultGenerateId2,
3062
3085
  parseProviderOptions as parseProviderOptions5,
@@ -4680,8 +4703,45 @@ function parseGoogleInteractionsOutputs({
4680
4703
  import {
4681
4704
  createJsonResponseHandler as createJsonResponseHandler5,
4682
4705
  delay as delay2,
4683
- getFromApi as getFromApi2
4706
+ getFromApi as getFromApi2,
4707
+ isAbortError
4684
4708
  } from "@ai-sdk/provider-utils";
4709
+
4710
+ // src/interactions/cancel-google-interaction.ts
4711
+ import {
4712
+ combineHeaders as combineHeaders5,
4713
+ getRuntimeEnvironmentUserAgent,
4714
+ withUserAgentSuffix
4715
+ } from "@ai-sdk/provider-utils";
4716
+ var getOriginalFetch = () => globalThis.fetch;
4717
+ async function cancelGoogleInteraction({
4718
+ baseURL,
4719
+ interactionId,
4720
+ headers,
4721
+ fetch = getOriginalFetch()
4722
+ }) {
4723
+ if (interactionId == null || interactionId.length === 0) {
4724
+ return;
4725
+ }
4726
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}/cancel`;
4727
+ try {
4728
+ const response = await fetch(url, {
4729
+ method: "POST",
4730
+ headers: withUserAgentSuffix(
4731
+ combineHeaders5({ "Content-Type": "application/json" }, headers),
4732
+ getRuntimeEnvironmentUserAgent()
4733
+ ),
4734
+ body: "{}"
4735
+ });
4736
+ try {
4737
+ await response.text();
4738
+ } catch (e) {
4739
+ }
4740
+ } catch (e) {
4741
+ }
4742
+ }
4743
+
4744
+ // src/interactions/poll-google-interactions.ts
4685
4745
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]);
4686
4746
  function isTerminalStatus(status) {
4687
4747
  return status != null && TERMINAL_STATUSES.has(status);
@@ -4707,34 +4767,43 @@ async function pollGoogleInteractionUntilTerminal({
4707
4767
  const startedAt = Date.now();
4708
4768
  let nextDelayMs = initialDelayMs;
4709
4769
  const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4710
- while (true) {
4711
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
4712
- throw new DOMException("Polling was aborted", "AbortError");
4713
- }
4714
- if (Date.now() - startedAt > timeoutMs) {
4715
- throw new Error(
4716
- `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4717
- );
4770
+ const cancelOnServer = () => cancelGoogleInteraction({ baseURL, interactionId, headers, fetch });
4771
+ try {
4772
+ while (true) {
4773
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
4774
+ await cancelOnServer();
4775
+ throw new DOMException("Polling was aborted", "AbortError");
4776
+ }
4777
+ if (Date.now() - startedAt > timeoutMs) {
4778
+ throw new Error(
4779
+ `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4780
+ );
4781
+ }
4782
+ await delay2(nextDelayMs, { abortSignal });
4783
+ const {
4784
+ value: response,
4785
+ rawValue: rawResponse,
4786
+ responseHeaders
4787
+ } = await getFromApi2({
4788
+ url,
4789
+ headers,
4790
+ failedResponseHandler: googleFailedResponseHandler,
4791
+ successfulResponseHandler: createJsonResponseHandler5(
4792
+ googleInteractionsResponseSchema
4793
+ ),
4794
+ abortSignal,
4795
+ fetch
4796
+ });
4797
+ if (isTerminalStatus(response.status)) {
4798
+ return { response, rawResponse, responseHeaders };
4799
+ }
4800
+ nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4718
4801
  }
4719
- await delay2(nextDelayMs, { abortSignal });
4720
- const {
4721
- value: response,
4722
- rawValue: rawResponse,
4723
- responseHeaders
4724
- } = await getFromApi2({
4725
- url,
4726
- headers,
4727
- failedResponseHandler: googleFailedResponseHandler,
4728
- successfulResponseHandler: createJsonResponseHandler5(
4729
- googleInteractionsResponseSchema
4730
- ),
4731
- abortSignal,
4732
- fetch
4733
- });
4734
- if (isTerminalStatus(response.status)) {
4735
- return { response, rawResponse, responseHeaders };
4802
+ } catch (error) {
4803
+ if (isAbortError(error)) {
4804
+ await cancelOnServer();
4736
4805
  }
4737
- nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4806
+ throw error;
4738
4807
  }
4739
4808
  }
4740
4809
 
@@ -4886,6 +4955,174 @@ function prepareGoogleInteractionsTools({
4886
4955
  };
4887
4956
  }
4888
4957
 
4958
+ // src/interactions/stream-google-interactions.ts
4959
+ import {
4960
+ createEventSourceResponseHandler as createEventSourceResponseHandler2,
4961
+ delay as delay3,
4962
+ getFromApi as getFromApi3,
4963
+ isAbortError as isAbortError2
4964
+ } from "@ai-sdk/provider-utils";
4965
+ var DEFAULT_MAX_RETRIES = 3;
4966
+ var DEFAULT_RETRY_DELAY_MS = 500;
4967
+ function streamGoogleInteractionEvents({
4968
+ baseURL,
4969
+ interactionId,
4970
+ headers,
4971
+ fetch,
4972
+ abortSignal,
4973
+ maxRetries = DEFAULT_MAX_RETRIES,
4974
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS
4975
+ }) {
4976
+ if (interactionId.length === 0) {
4977
+ throw new Error(
4978
+ "google.interactions: cannot stream a background interaction without an id."
4979
+ );
4980
+ }
4981
+ const eventSourceHeaders = {
4982
+ ...headers,
4983
+ accept: "text/event-stream"
4984
+ };
4985
+ let lastEventId;
4986
+ let complete = false;
4987
+ let attempt = 0;
4988
+ let receivedAnyEventThisAttempt = false;
4989
+ let currentReader;
4990
+ const internalAbort = new AbortController();
4991
+ const upstreamAbortHandler = () => internalAbort.abort();
4992
+ if (abortSignal != null) {
4993
+ if (abortSignal.aborted) {
4994
+ internalAbort.abort();
4995
+ } else {
4996
+ abortSignal.addEventListener("abort", upstreamAbortHandler, {
4997
+ once: true
4998
+ });
4999
+ }
5000
+ }
5001
+ const effectiveSignal = internalAbort.signal;
5002
+ function buildUrl() {
5003
+ const base = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
5004
+ const params = new URLSearchParams({ stream: "true" });
5005
+ if (lastEventId != null) {
5006
+ params.set("last_event_id", lastEventId);
5007
+ }
5008
+ return `${base}?${params.toString()}`;
5009
+ }
5010
+ async function openReader() {
5011
+ const { value: stream } = await getFromApi3({
5012
+ url: buildUrl(),
5013
+ headers: eventSourceHeaders,
5014
+ failedResponseHandler: googleFailedResponseHandler,
5015
+ successfulResponseHandler: createEventSourceResponseHandler2(
5016
+ googleInteractionsEventSchema
5017
+ ),
5018
+ abortSignal: effectiveSignal,
5019
+ fetch
5020
+ });
5021
+ return stream.getReader();
5022
+ }
5023
+ return new ReadableStream({
5024
+ async start(controller) {
5025
+ try {
5026
+ while (!complete && !effectiveSignal.aborted) {
5027
+ if (currentReader == null) {
5028
+ try {
5029
+ currentReader = await openReader();
5030
+ receivedAnyEventThisAttempt = false;
5031
+ } catch (error) {
5032
+ if (isAbortError2(error) || effectiveSignal.aborted) {
5033
+ controller.error(error);
5034
+ return;
5035
+ }
5036
+ attempt++;
5037
+ if (attempt >= maxRetries) {
5038
+ controller.error(error);
5039
+ return;
5040
+ }
5041
+ await delay3(retryDelayMs * attempt, {
5042
+ abortSignal: effectiveSignal
5043
+ });
5044
+ continue;
5045
+ }
5046
+ }
5047
+ try {
5048
+ const { done, value } = await currentReader.read();
5049
+ if (done) {
5050
+ currentReader = void 0;
5051
+ if (complete) break;
5052
+ if (!receivedAnyEventThisAttempt) {
5053
+ attempt++;
5054
+ if (attempt >= maxRetries) {
5055
+ controller.error(
5056
+ new Error(
5057
+ "google.interactions: SSE stream closed without producing any events."
5058
+ )
5059
+ );
5060
+ return;
5061
+ }
5062
+ await delay3(retryDelayMs * attempt, {
5063
+ abortSignal: effectiveSignal
5064
+ });
5065
+ } else {
5066
+ attempt = 0;
5067
+ }
5068
+ continue;
5069
+ }
5070
+ receivedAnyEventThisAttempt = true;
5071
+ if (value.success) {
5072
+ const ev = value.value;
5073
+ if (typeof ev.event_id === "string" && ev.event_id.length > 0) {
5074
+ lastEventId = ev.event_id;
5075
+ }
5076
+ if (ev.event_type === "interaction.complete" || ev.event_type === "error") {
5077
+ complete = true;
5078
+ }
5079
+ }
5080
+ controller.enqueue(value);
5081
+ } catch (error) {
5082
+ if (isAbortError2(error) || effectiveSignal.aborted) {
5083
+ controller.error(error);
5084
+ return;
5085
+ }
5086
+ currentReader = void 0;
5087
+ attempt++;
5088
+ if (attempt >= maxRetries) {
5089
+ controller.error(error);
5090
+ return;
5091
+ }
5092
+ await delay3(retryDelayMs * attempt, {
5093
+ abortSignal: effectiveSignal
5094
+ });
5095
+ }
5096
+ }
5097
+ controller.close();
5098
+ } catch (error) {
5099
+ controller.error(error);
5100
+ } finally {
5101
+ if (abortSignal != null) {
5102
+ abortSignal.removeEventListener("abort", upstreamAbortHandler);
5103
+ }
5104
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
5105
+ });
5106
+ currentReader = void 0;
5107
+ if (effectiveSignal.aborted && !complete) {
5108
+ await cancelGoogleInteraction({
5109
+ baseURL,
5110
+ interactionId,
5111
+ headers,
5112
+ fetch
5113
+ });
5114
+ }
5115
+ }
5116
+ },
5117
+ cancel() {
5118
+ internalAbort.abort();
5119
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
5120
+ });
5121
+ currentReader = void 0;
5122
+ }
5123
+ });
5124
+ }
5125
+
4889
5126
  // src/interactions/synthesize-google-interactions-agent-stream.ts
4890
5127
  function synthesizeGoogleInteractionsAgentStream({
4891
5128
  response,
@@ -5199,7 +5436,7 @@ var GoogleInteractionsLanguageModel = class {
5199
5436
  var _a, _b, _c, _d, _e, _f;
5200
5437
  const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5201
5438
  const url = `${this.config.baseURL}/interactions`;
5202
- const mergedHeaders = combineHeaders5(
5439
+ const mergedHeaders = combineHeaders6(
5203
5440
  this.config.headers ? await resolve5(this.config.headers) : void 0,
5204
5441
  options.headers
5205
5442
  );
@@ -5279,12 +5516,12 @@ var GoogleInteractionsLanguageModel = class {
5279
5516
  var _a;
5280
5517
  const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5281
5518
  const url = `${this.config.baseURL}/interactions`;
5282
- const mergedHeaders = combineHeaders5(
5519
+ const mergedHeaders = combineHeaders6(
5283
5520
  this.config.headers ? await resolve5(this.config.headers) : void 0,
5284
5521
  options.headers
5285
5522
  );
5286
5523
  if (isAgent) {
5287
- return this.doStreamAgent({
5524
+ return this.doStreamBackground({
5288
5525
  args,
5289
5526
  warnings,
5290
5527
  url,
@@ -5299,7 +5536,7 @@ var GoogleInteractionsLanguageModel = class {
5299
5536
  headers: mergedHeaders,
5300
5537
  body,
5301
5538
  failedResponseHandler: googleFailedResponseHandler,
5302
- successfulResponseHandler: createEventSourceResponseHandler2(
5539
+ successfulResponseHandler: createEventSourceResponseHandler3(
5303
5540
  googleInteractionsEventSchema
5304
5541
  ),
5305
5542
  abortSignal: options.abortSignal,
@@ -5319,26 +5556,24 @@ var GoogleInteractionsLanguageModel = class {
5319
5556
  };
5320
5557
  }
5321
5558
  /*
5322
- * Drive the streaming surface for agent calls. Agent calls require
5559
+ * Drive the streaming surface for agent calls. Agents require
5323
5560
  * `background: true`, which is incompatible with `stream: true` on POST.
5324
5561
  *
5325
- * In principle the API also exposes `GET /interactions/{id}?stream=true`
5326
- * to replay events as the agent runs. In practice the connection is
5327
- * idle for long stretches while the agent thinks (deep-research can run
5328
- * for a minute or more between SSE events), and undici's default body
5329
- * timeout terminates the request mid-flight with `UND_ERR_BODY_TIMEOUT`.
5330
- * Tuning the timeout per-call would require the caller to thread an
5331
- * `undici.Agent` through `fetch`, which contradicts the AI SDK's
5332
- * pluggable-fetch contract.
5562
+ * Approach:
5563
+ * 1. POST `/interactions` with `background: true`. The response includes
5564
+ * the interaction id and an initial (usually non-terminal) status.
5565
+ * 2. If the POST status is already terminal (rare), synthesize a stream
5566
+ * from the polled outputs and we're done.
5567
+ * 3. Otherwise open `GET /interactions/{id}?stream=true` and pipe the
5568
+ * SSE events through `buildGoogleInteractionsStreamTransform` so the
5569
+ * consumer receives text deltas / thinking summaries / tool events as
5570
+ * they happen instead of all at once at the end.
5333
5571
  *
5334
- * We therefore drive `doStream` exactly like `doGenerate` for agents:
5335
- * POST with `background: true`, poll `GET /interactions/{id}` until
5336
- * terminal, then synthesize the stream from the final outputs. The
5337
- * user-facing surface stays identical -- text-start / text-delta /
5338
- * text-end / finish parts arrive in the same order as a true SSE
5339
- * response, just buffered until the agent completes.
5572
+ * The SSE connection can drop while the agent idles between events
5573
+ * (`UND_ERR_BODY_TIMEOUT`); `streamGoogleInteractionEvents` handles the
5574
+ * reconnect-with-`last_event_id` loop transparently.
5340
5575
  */
5341
- async doStreamAgent({
5576
+ async doStreamBackground({
5342
5577
  args,
5343
5578
  warnings,
5344
5579
  url,
@@ -5358,34 +5593,44 @@ var GoogleInteractionsLanguageModel = class {
5358
5593
  abortSignal: options.abortSignal,
5359
5594
  fetch: this.config.fetch
5360
5595
  });
5361
- let { responseHeaders: postHeaders, value: postResponse } = postResult;
5596
+ const { responseHeaders: postHeaders, value: postResponse } = postResult;
5362
5597
  const interactionId = postResponse.id;
5363
5598
  if (interactionId == null || interactionId.length === 0) {
5364
5599
  throw new Error(
5365
- "google.interactions: agent POST response did not include an interaction id; cannot poll for the agent result."
5600
+ "google.interactions: background POST response did not include an interaction id; cannot stream the result."
5366
5601
  );
5367
5602
  }
5368
- if (!isTerminalStatus(postResponse.status)) {
5369
- const polled = await pollGoogleInteractionUntilTerminal({
5370
- baseURL: this.config.baseURL,
5371
- interactionId,
5372
- headers: mergedHeaders,
5373
- fetch: this.config.fetch,
5374
- abortSignal: options.abortSignal,
5375
- timeoutMs: pollingTimeoutMs
5603
+ const headerServiceTier = postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"];
5604
+ if (isTerminalStatus(postResponse.status)) {
5605
+ const synthesized = synthesizeGoogleInteractionsAgentStream({
5606
+ response: postResponse,
5607
+ warnings,
5608
+ generateId: (_a = this.config.generateId) != null ? _a : defaultGenerateId2,
5609
+ includeRawChunks: options.includeRawChunks,
5610
+ headerServiceTier
5376
5611
  });
5377
- postResponse = polled.response;
5378
- postHeaders = (_a = polled.responseHeaders) != null ? _a : postHeaders;
5612
+ return {
5613
+ stream: synthesized,
5614
+ request: { body: args },
5615
+ response: { headers: postHeaders }
5616
+ };
5379
5617
  }
5380
- const stream = synthesizeGoogleInteractionsAgentStream({
5381
- response: postResponse,
5618
+ void pollingTimeoutMs;
5619
+ const events = streamGoogleInteractionEvents({
5620
+ baseURL: this.config.baseURL,
5621
+ interactionId,
5622
+ headers: mergedHeaders,
5623
+ fetch: this.config.fetch,
5624
+ abortSignal: options.abortSignal
5625
+ });
5626
+ const transform = buildGoogleInteractionsStreamTransform({
5382
5627
  warnings,
5383
5628
  generateId: (_b = this.config.generateId) != null ? _b : defaultGenerateId2,
5384
5629
  includeRawChunks: options.includeRawChunks,
5385
- headerServiceTier: postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"]
5630
+ serviceTier: headerServiceTier
5386
5631
  });
5387
5632
  return {
5388
- stream,
5633
+ stream: events.pipeThrough(transform),
5389
5634
  request: { body: args },
5390
5635
  response: { headers: postHeaders }
5391
5636
  };
@@ -5405,7 +5650,7 @@ function createGoogleGenerativeAI(options = {}) {
5405
5650
  var _a, _b;
5406
5651
  const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
5407
5652
  const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
5408
- const getHeaders = () => withUserAgentSuffix(
5653
+ const getHeaders = () => withUserAgentSuffix2(
5409
5654
  {
5410
5655
  "x-goog-api-key": loadApiKey({
5411
5656
  apiKey: options.apiKey,