ai 5.0.0-beta.33 → 5.0.0-beta.34

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
@@ -98,45 +98,51 @@ var RetryError = class extends AISDKError3 {
98
98
  _a3 = symbol3;
99
99
 
100
100
  // src/util/retry-with-exponential-backoff.ts
101
- function getRetryDelay(error, exponentialBackoffDelay) {
101
+ function getRetryDelayInMs({
102
+ error,
103
+ exponentialBackoffDelay
104
+ }) {
102
105
  const headers = error.responseHeaders;
103
106
  if (!headers)
104
107
  return exponentialBackoffDelay;
105
- let timeoutMillis;
108
+ let ms;
106
109
  const retryAfterMs = headers["retry-after-ms"];
107
110
  if (retryAfterMs) {
108
111
  const timeoutMs = parseFloat(retryAfterMs);
109
112
  if (!Number.isNaN(timeoutMs)) {
110
- timeoutMillis = timeoutMs;
113
+ ms = timeoutMs;
111
114
  }
112
115
  }
113
116
  const retryAfter = headers["retry-after"];
114
- if (retryAfter && timeoutMillis === void 0) {
117
+ if (retryAfter && ms === void 0) {
115
118
  const timeoutSeconds = parseFloat(retryAfter);
116
119
  if (!Number.isNaN(timeoutSeconds)) {
117
- timeoutMillis = timeoutSeconds * 1e3;
120
+ ms = timeoutSeconds * 1e3;
118
121
  } else {
119
- timeoutMillis = Date.parse(retryAfter) - Date.now();
122
+ ms = Date.parse(retryAfter) - Date.now();
120
123
  }
121
124
  }
122
- if (timeoutMillis !== void 0 && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3) {
123
- return timeoutMillis;
125
+ if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) {
126
+ return ms;
124
127
  }
125
128
  return exponentialBackoffDelay;
126
129
  }
127
130
  var retryWithExponentialBackoffRespectingRetryHeaders = ({
128
131
  maxRetries = 2,
129
132
  initialDelayInMs = 2e3,
130
- backoffFactor = 2
133
+ backoffFactor = 2,
134
+ abortSignal
131
135
  } = {}) => async (f) => _retryWithExponentialBackoff(f, {
132
136
  maxRetries,
133
137
  delayInMs: initialDelayInMs,
134
- backoffFactor
138
+ backoffFactor,
139
+ abortSignal
135
140
  });
136
141
  async function _retryWithExponentialBackoff(f, {
137
142
  maxRetries,
138
143
  delayInMs,
139
- backoffFactor
144
+ backoffFactor,
145
+ abortSignal
140
146
  }, errors = []) {
141
147
  try {
142
148
  return await f();
@@ -158,11 +164,21 @@ async function _retryWithExponentialBackoff(f, {
158
164
  });
159
165
  }
160
166
  if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
161
- const actualDelay = getRetryDelay(error, delayInMs);
162
- await delay(actualDelay);
167
+ await delay(
168
+ getRetryDelayInMs({
169
+ error,
170
+ exponentialBackoffDelay: delayInMs
171
+ }),
172
+ { abortSignal }
173
+ );
163
174
  return _retryWithExponentialBackoff(
164
175
  f,
165
- { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
176
+ {
177
+ maxRetries,
178
+ delayInMs: backoffFactor * delayInMs,
179
+ backoffFactor,
180
+ abortSignal
181
+ },
166
182
  newErrors
167
183
  );
168
184
  }
@@ -179,7 +195,8 @@ async function _retryWithExponentialBackoff(f, {
179
195
 
180
196
  // src/util/prepare-retries.ts
181
197
  function prepareRetries({
182
- maxRetries
198
+ maxRetries,
199
+ abortSignal
183
200
  }) {
184
201
  if (maxRetries != null) {
185
202
  if (!Number.isInteger(maxRetries)) {
@@ -201,7 +218,8 @@ function prepareRetries({
201
218
  return {
202
219
  maxRetries: maxRetriesResult,
203
220
  retry: retryWithExponentialBackoffRespectingRetryHeaders({
204
- maxRetries: maxRetriesResult
221
+ maxRetries: maxRetriesResult,
222
+ abortSignal
205
223
  })
206
224
  };
207
225
  }
@@ -1957,7 +1975,10 @@ async function generateText({
1957
1975
  }) {
1958
1976
  const model = resolveLanguageModel(modelArg);
1959
1977
  const stopConditions = asArray(stopWhen);
1960
- const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
1978
+ const { maxRetries, retry } = prepareRetries({
1979
+ maxRetries: maxRetriesArg,
1980
+ abortSignal
1981
+ });
1961
1982
  const callSettings = prepareCallSettings(settings);
1962
1983
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
1963
1984
  model,
@@ -4448,7 +4469,8 @@ var DefaultStreamTextResult = class {
4448
4469
  }
4449
4470
  this.baseStream = stream.pipeThrough(createOutputTransformStream(output)).pipeThrough(eventProcessor);
4450
4471
  const { maxRetries, retry } = prepareRetries({
4451
- maxRetries: maxRetriesArg
4472
+ maxRetries: maxRetriesArg,
4473
+ abortSignal
4452
4474
  });
4453
4475
  const tracer = getTracer(telemetry);
4454
4476
  const callSettings = prepareCallSettings(settings);
@@ -5324,7 +5346,10 @@ async function embed({
5324
5346
  modelId: model.modelId
5325
5347
  });
5326
5348
  }
5327
- const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
5349
+ const { maxRetries, retry } = prepareRetries({
5350
+ maxRetries: maxRetriesArg,
5351
+ abortSignal
5352
+ });
5328
5353
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
5329
5354
  model,
5330
5355
  telemetry,
@@ -5454,7 +5479,10 @@ async function embedMany({
5454
5479
  modelId: model.modelId
5455
5480
  });
5456
5481
  }
5457
- const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
5482
+ const { maxRetries, retry } = prepareRetries({
5483
+ maxRetries: maxRetriesArg,
5484
+ abortSignal
5485
+ });
5458
5486
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
5459
5487
  model,
5460
5488
  telemetry,
@@ -5691,7 +5719,10 @@ async function generateImage({
5691
5719
  modelId: model.modelId
5692
5720
  });
5693
5721
  }
5694
- const { retry } = prepareRetries({ maxRetries: maxRetriesArg });
5722
+ const { retry } = prepareRetries({
5723
+ maxRetries: maxRetriesArg,
5724
+ abortSignal
5725
+ });
5695
5726
  const maxImagesPerCallWithDefault = (_a16 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a16 : 1;
5696
5727
  const callCount = Math.ceil(n / maxImagesPerCallWithDefault);
5697
5728
  const callImageCounts = Array.from({ length: callCount }, (_, i) => {
@@ -5780,12 +5811,7 @@ async function invokeModelMaxImagesPerCall(model) {
5780
5811
 
5781
5812
  // src/generate-object/generate-object.ts
5782
5813
  import {
5783
- JSONParseError as JSONParseError2,
5784
- TypeValidationError as TypeValidationError3
5785
- } from "@ai-sdk/provider";
5786
- import {
5787
- createIdGenerator as createIdGenerator3,
5788
- safeParseJSON as safeParseJSON3
5814
+ createIdGenerator as createIdGenerator3
5789
5815
  } from "@ai-sdk/provider-utils";
5790
5816
 
5791
5817
  // src/generate-object/output-strategy.ts
@@ -6172,6 +6198,63 @@ function validateObjectGenerationInput({
6172
6198
  }
6173
6199
  }
6174
6200
 
6201
+ // src/generate-object/parse-and-validate-object-result.ts
6202
+ import { JSONParseError as JSONParseError2, TypeValidationError as TypeValidationError3 } from "@ai-sdk/provider";
6203
+ import { safeParseJSON as safeParseJSON3 } from "@ai-sdk/provider-utils";
6204
+ async function parseAndValidateObjectResult(result, outputStrategy, context) {
6205
+ const parseResult = await safeParseJSON3({ text: result });
6206
+ if (!parseResult.success) {
6207
+ throw new NoObjectGeneratedError({
6208
+ message: "No object generated: could not parse the response.",
6209
+ cause: parseResult.error,
6210
+ text: result,
6211
+ response: context.response,
6212
+ usage: context.usage,
6213
+ finishReason: context.finishReason
6214
+ });
6215
+ }
6216
+ const validationResult = await outputStrategy.validateFinalResult(
6217
+ parseResult.value,
6218
+ {
6219
+ text: result,
6220
+ response: context.response,
6221
+ usage: context.usage
6222
+ }
6223
+ );
6224
+ if (!validationResult.success) {
6225
+ throw new NoObjectGeneratedError({
6226
+ message: "No object generated: response did not match schema.",
6227
+ cause: validationResult.error,
6228
+ text: result,
6229
+ response: context.response,
6230
+ usage: context.usage,
6231
+ finishReason: context.finishReason
6232
+ });
6233
+ }
6234
+ return validationResult.value;
6235
+ }
6236
+ async function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context) {
6237
+ try {
6238
+ return await parseAndValidateObjectResult(result, outputStrategy, context);
6239
+ } catch (error) {
6240
+ if (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError2.isInstance(error.cause) || TypeValidationError3.isInstance(error.cause))) {
6241
+ const repairedText = await repairText({
6242
+ text: result,
6243
+ error: error.cause
6244
+ });
6245
+ if (repairedText === null) {
6246
+ throw error;
6247
+ }
6248
+ return await parseAndValidateObjectResult(
6249
+ repairedText,
6250
+ outputStrategy,
6251
+ context
6252
+ );
6253
+ }
6254
+ throw error;
6255
+ }
6256
+ }
6257
+
6175
6258
  // src/generate-object/generate-object.ts
6176
6259
  var originalGenerateId3 = createIdGenerator3({ prefix: "aiobj", size: 24 });
6177
6260
  async function generateObject(options) {
@@ -6207,7 +6290,10 @@ async function generateObject(options) {
6207
6290
  schemaDescription,
6208
6291
  enumValues
6209
6292
  });
6210
- const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
6293
+ const { maxRetries, retry } = prepareRetries({
6294
+ maxRetries: maxRetriesArg,
6295
+ abortSignal
6296
+ });
6211
6297
  const outputStrategy = getOutputStrategy({
6212
6298
  output,
6213
6299
  schema: inputSchema,
@@ -6353,55 +6439,16 @@ async function generateObject(options) {
6353
6439
  resultProviderMetadata = generateResult.providerMetadata;
6354
6440
  request = (_a16 = generateResult.request) != null ? _a16 : {};
6355
6441
  response = generateResult.responseData;
6356
- async function processResult(result2) {
6357
- const parseResult = await safeParseJSON3({ text: result2 });
6358
- if (!parseResult.success) {
6359
- throw new NoObjectGeneratedError({
6360
- message: "No object generated: could not parse the response.",
6361
- cause: parseResult.error,
6362
- text: result2,
6363
- response,
6364
- usage,
6365
- finishReason
6366
- });
6367
- }
6368
- const validationResult = await outputStrategy.validateFinalResult(
6369
- parseResult.value,
6370
- {
6371
- text: result2,
6372
- response,
6373
- usage
6374
- }
6375
- );
6376
- if (!validationResult.success) {
6377
- throw new NoObjectGeneratedError({
6378
- message: "No object generated: response did not match schema.",
6379
- cause: validationResult.error,
6380
- text: result2,
6381
- response,
6382
- usage,
6383
- finishReason
6384
- });
6385
- }
6386
- return validationResult.value;
6387
- }
6388
- let object2;
6389
- try {
6390
- object2 = await processResult(result);
6391
- } catch (error) {
6392
- if (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError2.isInstance(error.cause) || TypeValidationError3.isInstance(error.cause))) {
6393
- const repairedText = await repairText({
6394
- text: result,
6395
- error: error.cause
6396
- });
6397
- if (repairedText === null) {
6398
- throw error;
6399
- }
6400
- object2 = await processResult(repairedText);
6401
- } else {
6402
- throw error;
6442
+ const object2 = await parseAndValidateObjectResultWithRepair(
6443
+ result,
6444
+ outputStrategy,
6445
+ repairText,
6446
+ {
6447
+ response,
6448
+ usage,
6449
+ finishReason
6403
6450
  }
6404
- }
6451
+ );
6405
6452
  span.setAttributes(
6406
6453
  selectTelemetryAttributes({
6407
6454
  telemetry,
@@ -6602,6 +6649,7 @@ function streamObject(options) {
6602
6649
  maxRetries,
6603
6650
  abortSignal,
6604
6651
  headers,
6652
+ experimental_repairText: repairText,
6605
6653
  experimental_telemetry: telemetry,
6606
6654
  providerOptions,
6607
6655
  onError = ({ error }) => {
@@ -6647,6 +6695,7 @@ function streamObject(options) {
6647
6695
  schemaName,
6648
6696
  schemaDescription,
6649
6697
  providerOptions,
6698
+ repairText,
6650
6699
  onError,
6651
6700
  onFinish,
6652
6701
  generateId: generateId3,
@@ -6669,6 +6718,7 @@ var DefaultStreamObjectResult = class {
6669
6718
  schemaName,
6670
6719
  schemaDescription,
6671
6720
  providerOptions,
6721
+ repairText,
6672
6722
  onError,
6673
6723
  onFinish,
6674
6724
  generateId: generateId3,
@@ -6684,7 +6734,8 @@ var DefaultStreamObjectResult = class {
6684
6734
  this._finishReason = new DelayedPromise();
6685
6735
  const model = resolveLanguageModel(modelArg);
6686
6736
  const { maxRetries, retry } = prepareRetries({
6687
- maxRetries: maxRetriesArg
6737
+ maxRetries: maxRetriesArg,
6738
+ abortSignal
6688
6739
  });
6689
6740
  const callSettings = prepareCallSettings(settings);
6690
6741
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
@@ -6902,27 +6953,21 @@ var DefaultStreamObjectResult = class {
6902
6953
  headers: response == null ? void 0 : response.headers
6903
6954
  });
6904
6955
  self._finishReason.resolve(finishReason != null ? finishReason : "unknown");
6905
- const validationResult = await outputStrategy.validateFinalResult(
6906
- latestObjectJson,
6907
- {
6908
- text: accumulatedText,
6909
- response: fullResponse,
6910
- usage
6911
- }
6912
- );
6913
- if (validationResult.success) {
6914
- object2 = validationResult.value;
6956
+ try {
6957
+ object2 = await parseAndValidateObjectResultWithRepair(
6958
+ accumulatedText,
6959
+ outputStrategy,
6960
+ repairText,
6961
+ {
6962
+ response: fullResponse,
6963
+ usage,
6964
+ finishReason
6965
+ }
6966
+ );
6915
6967
  self._object.resolve(object2);
6916
- } else {
6917
- error = new NoObjectGeneratedError({
6918
- message: "No object generated: response did not match schema.",
6919
- cause: validationResult.error,
6920
- text: accumulatedText,
6921
- response: fullResponse,
6922
- usage,
6923
- finishReason
6924
- });
6925
- self._object.reject(error);
6968
+ } catch (e) {
6969
+ error = e;
6970
+ self._object.reject(e);
6926
6971
  }
6927
6972
  break;
6928
6973
  }
@@ -7165,7 +7210,10 @@ async function generateSpeech({
7165
7210
  modelId: model.modelId
7166
7211
  });
7167
7212
  }
7168
- const { retry } = prepareRetries({ maxRetries: maxRetriesArg });
7213
+ const { retry } = prepareRetries({
7214
+ maxRetries: maxRetriesArg,
7215
+ abortSignal
7216
+ });
7169
7217
  const result = await retry(
7170
7218
  () => model.doGenerate({
7171
7219
  text: text2,
@@ -7213,7 +7261,7 @@ __export(output_exports, {
7213
7261
  });
7214
7262
  import {
7215
7263
  asSchema as asSchema4,
7216
- safeParseJSON as safeParseJSON4,
7264
+ safeParseJSON as safeParseJSON5,
7217
7265
  safeValidateTypes as safeValidateTypes4
7218
7266
  } from "@ai-sdk/provider-utils";
7219
7267
  var text = () => ({
@@ -7255,7 +7303,7 @@ var object = ({
7255
7303
  }
7256
7304
  },
7257
7305
  async parseOutput({ text: text2 }, context) {
7258
- const parseResult = await safeParseJSON4({ text: text2 });
7306
+ const parseResult = await safeParseJSON5({ text: text2 });
7259
7307
  if (!parseResult.success) {
7260
7308
  throw new NoObjectGeneratedError({
7261
7309
  message: "No object generated: could not parse the response.",
@@ -8477,7 +8525,10 @@ async function transcribe({
8477
8525
  modelId: model.modelId
8478
8526
  });
8479
8527
  }
8480
- const { retry } = prepareRetries({ maxRetries: maxRetriesArg });
8528
+ const { retry } = prepareRetries({
8529
+ maxRetries: maxRetriesArg,
8530
+ abortSignal
8531
+ });
8481
8532
  const audioData = audio instanceof URL ? (await download({ url: audio })).data : convertDataContentToUint8Array(audio);
8482
8533
  const result = await retry(
8483
8534
  () => {
@@ -8925,6 +8976,15 @@ var AbstractChat = class {
8925
8976
  this.resumeStream = async (options = {}) => {
8926
8977
  await this.makeRequest({ trigger: "resume-stream", ...options });
8927
8978
  };
8979
+ /**
8980
+ * Clear the error state and set the status to ready if the chat is in an error state.
8981
+ */
8982
+ this.clearError = () => {
8983
+ if (this.status === "error") {
8984
+ this.state.error = void 0;
8985
+ this.setStatus({ status: "ready" });
8986
+ }
8987
+ };
8928
8988
  this.addToolResult = async ({
8929
8989
  tool: tool3,
8930
8990
  toolCallId,