ai 4.0.11 → 4.0.13

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
@@ -1,7 +1,7 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __export = (target, all) => {
3
- for (var name11 in all)
4
- __defProp(target, name11, { get: all[name11], enumerable: true });
3
+ for (var name13 in all)
4
+ __defProp(target, name13, { get: all[name13], enumerable: true });
5
5
  };
6
6
 
7
7
  // streams/index.ts
@@ -347,7 +347,7 @@ function getBaseTelemetryAttributes({
347
347
  telemetry,
348
348
  headers
349
349
  }) {
350
- var _a11;
350
+ var _a13;
351
351
  return {
352
352
  "ai.model.provider": model.provider,
353
353
  "ai.model.id": model.modelId,
@@ -357,7 +357,7 @@ function getBaseTelemetryAttributes({
357
357
  return attributes;
358
358
  }, {}),
359
359
  // add metadata as attributes:
360
- ...Object.entries((_a11 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a11 : {}).reduce(
360
+ ...Object.entries((_a13 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a13 : {}).reduce(
361
361
  (attributes, [key, value]) => {
362
362
  attributes[`ai.telemetry.metadata.${key}`] = value;
363
363
  return attributes;
@@ -382,7 +382,7 @@ var noopTracer = {
382
382
  startSpan() {
383
383
  return noopSpan;
384
384
  },
385
- startActiveSpan(name11, arg1, arg2, arg3) {
385
+ startActiveSpan(name13, arg1, arg2, arg3) {
386
386
  if (typeof arg1 === "function") {
387
387
  return arg1(noopSpan);
388
388
  }
@@ -452,13 +452,13 @@ function getTracer({
452
452
  // core/telemetry/record-span.ts
453
453
  import { SpanStatusCode } from "@opentelemetry/api";
454
454
  function recordSpan({
455
- name: name11,
455
+ name: name13,
456
456
  tracer,
457
457
  attributes,
458
458
  fn,
459
459
  endWhenDone = true
460
460
  }) {
461
- return tracer.startActiveSpan(name11, { attributes }, async (span) => {
461
+ return tracer.startActiveSpan(name13, { attributes }, async (span) => {
462
462
  try {
463
463
  const result = await fn(span);
464
464
  if (endWhenDone) {
@@ -566,14 +566,14 @@ async function embed({
566
566
  }),
567
567
  tracer,
568
568
  fn: async (doEmbedSpan) => {
569
- var _a11;
569
+ var _a13;
570
570
  const modelResponse = await model.doEmbed({
571
571
  values: [value],
572
572
  abortSignal,
573
573
  headers
574
574
  });
575
575
  const embedding2 = modelResponse.embeddings[0];
576
- const usage2 = (_a11 = modelResponse.usage) != null ? _a11 : { tokens: NaN };
576
+ const usage2 = (_a13 = modelResponse.usage) != null ? _a13 : { tokens: NaN };
577
577
  doEmbedSpan.setAttributes(
578
578
  selectTelemetryAttributes({
579
579
  telemetry,
@@ -683,14 +683,14 @@ async function embedMany({
683
683
  }),
684
684
  tracer,
685
685
  fn: async (doEmbedSpan) => {
686
- var _a11;
686
+ var _a13;
687
687
  const modelResponse = await model.doEmbed({
688
688
  values,
689
689
  abortSignal,
690
690
  headers
691
691
  });
692
692
  const embeddings3 = modelResponse.embeddings;
693
- const usage2 = (_a11 = modelResponse.usage) != null ? _a11 : { tokens: NaN };
693
+ const usage2 = (_a13 = modelResponse.usage) != null ? _a13 : { tokens: NaN };
694
694
  doEmbedSpan.setAttributes(
695
695
  selectTelemetryAttributes({
696
696
  telemetry,
@@ -742,14 +742,14 @@ async function embedMany({
742
742
  }),
743
743
  tracer,
744
744
  fn: async (doEmbedSpan) => {
745
- var _a11;
745
+ var _a13;
746
746
  const modelResponse = await model.doEmbed({
747
747
  values: chunk,
748
748
  abortSignal,
749
749
  headers
750
750
  });
751
751
  const embeddings2 = modelResponse.embeddings;
752
- const usage2 = (_a11 = modelResponse.usage) != null ? _a11 : { tokens: NaN };
752
+ const usage2 = (_a13 = modelResponse.usage) != null ? _a13 : { tokens: NaN };
753
753
  doEmbedSpan.setAttributes(
754
754
  selectTelemetryAttributes({
755
755
  telemetry,
@@ -829,7 +829,7 @@ async function download({
829
829
  url,
830
830
  fetchImplementation = fetch
831
831
  }) {
832
- var _a11;
832
+ var _a13;
833
833
  const urlText = url.toString();
834
834
  try {
835
835
  const response = await fetchImplementation(urlText);
@@ -842,7 +842,7 @@ async function download({
842
842
  }
843
843
  return {
844
844
  data: new Uint8Array(await response.arrayBuffer()),
845
- mimeType: (_a11 = response.headers.get("content-type")) != null ? _a11 : void 0
845
+ mimeType: (_a13 = response.headers.get("content-type")) != null ? _a13 : void 0
846
846
  };
847
847
  } catch (error) {
848
848
  if (DownloadError.isInstance(error)) {
@@ -905,8 +905,8 @@ var dataContentSchema = z.union([
905
905
  z.custom(
906
906
  // Buffer might not be available in some environments such as CloudFlare:
907
907
  (value) => {
908
- var _a11, _b;
909
- return (_b = (_a11 = globalThis.Buffer) == null ? void 0 : _a11.isBuffer(value)) != null ? _b : false;
908
+ var _a13, _b;
909
+ return (_b = (_a13 = globalThis.Buffer) == null ? void 0 : _a13.isBuffer(value)) != null ? _b : false;
910
910
  },
911
911
  { message: "Must be a Buffer" }
912
912
  )
@@ -1414,7 +1414,7 @@ function detectSingleMessageCharacteristics(message) {
1414
1414
 
1415
1415
  // core/prompt/attachments-to-parts.ts
1416
1416
  function attachmentsToParts(attachments) {
1417
- var _a11, _b, _c;
1417
+ var _a13, _b, _c;
1418
1418
  const parts = [];
1419
1419
  for (const attachment of attachments) {
1420
1420
  let url;
@@ -1426,7 +1426,7 @@ function attachmentsToParts(attachments) {
1426
1426
  switch (url.protocol) {
1427
1427
  case "http:":
1428
1428
  case "https:": {
1429
- if ((_a11 = attachment.contentType) == null ? void 0 : _a11.startsWith("image/")) {
1429
+ if ((_a13 = attachment.contentType) == null ? void 0 : _a13.startsWith("image/")) {
1430
1430
  parts.push({ type: "image", image: url });
1431
1431
  } else {
1432
1432
  if (!attachment.contentType) {
@@ -1512,8 +1512,8 @@ _a6 = symbol6;
1512
1512
 
1513
1513
  // core/prompt/convert-to-core-messages.ts
1514
1514
  function convertToCoreMessages(messages, options) {
1515
- var _a11;
1516
- const tools = (_a11 = options == null ? void 0 : options.tools) != null ? _a11 : {};
1515
+ var _a13;
1516
+ const tools = (_a13 = options == null ? void 0 : options.tools) != null ? _a13 : {};
1517
1517
  const coreMessages = [];
1518
1518
  for (const message of messages) {
1519
1519
  const { role, content, toolInvocations, experimental_attachments } = message;
@@ -1800,7 +1800,7 @@ var arrayOutputStrategy = (schema) => {
1800
1800
  additionalProperties: false
1801
1801
  },
1802
1802
  validatePartialResult({ value, latestObject, isFirstDelta, isFinalDelta }) {
1803
- var _a11;
1803
+ var _a13;
1804
1804
  if (!isJSONObject(value) || !isJSONArray(value.elements)) {
1805
1805
  return {
1806
1806
  success: false,
@@ -1823,7 +1823,7 @@ var arrayOutputStrategy = (schema) => {
1823
1823
  }
1824
1824
  resultArray.push(result.value);
1825
1825
  }
1826
- const publishedElementCount = (_a11 = latestObject == null ? void 0 : latestObject.length) != null ? _a11 : 0;
1826
+ const publishedElementCount = (_a13 = latestObject == null ? void 0 : latestObject.length) != null ? _a13 : 0;
1827
1827
  let textDelta = "";
1828
1828
  if (isFirstDelta) {
1829
1829
  textDelta += "[";
@@ -2155,7 +2155,7 @@ async function generateObject({
2155
2155
  }),
2156
2156
  tracer,
2157
2157
  fn: async (span) => {
2158
- var _a11, _b;
2158
+ var _a13, _b;
2159
2159
  if (mode === "auto" || mode == null) {
2160
2160
  mode = model.defaultObjectGenerationMode;
2161
2161
  }
@@ -2217,7 +2217,7 @@ async function generateObject({
2217
2217
  }),
2218
2218
  tracer,
2219
2219
  fn: async (span2) => {
2220
- var _a12, _b2, _c, _d, _e, _f;
2220
+ var _a14, _b2, _c, _d, _e, _f;
2221
2221
  const result2 = await model.doGenerate({
2222
2222
  mode: {
2223
2223
  type: "object-json",
@@ -2236,7 +2236,7 @@ async function generateObject({
2236
2236
  throw new NoObjectGeneratedError();
2237
2237
  }
2238
2238
  const responseData = {
2239
- id: (_b2 = (_a12 = result2.response) == null ? void 0 : _a12.id) != null ? _b2 : generateId3(),
2239
+ id: (_b2 = (_a14 = result2.response) == null ? void 0 : _a14.id) != null ? _b2 : generateId3(),
2240
2240
  timestamp: (_d = (_c = result2.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),
2241
2241
  modelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId
2242
2242
  };
@@ -2271,7 +2271,7 @@ async function generateObject({
2271
2271
  rawResponse = generateResult.rawResponse;
2272
2272
  logprobs = generateResult.logprobs;
2273
2273
  resultProviderMetadata = generateResult.providerMetadata;
2274
- request = (_a11 = generateResult.request) != null ? _a11 : {};
2274
+ request = (_a13 = generateResult.request) != null ? _a13 : {};
2275
2275
  response = generateResult.responseData;
2276
2276
  break;
2277
2277
  }
@@ -2317,7 +2317,7 @@ async function generateObject({
2317
2317
  }),
2318
2318
  tracer,
2319
2319
  fn: async (span2) => {
2320
- var _a12, _b2, _c, _d, _e, _f, _g, _h;
2320
+ var _a14, _b2, _c, _d, _e, _f, _g, _h;
2321
2321
  const result2 = await model.doGenerate({
2322
2322
  mode: {
2323
2323
  type: "object-tool",
@@ -2335,7 +2335,7 @@ async function generateObject({
2335
2335
  abortSignal,
2336
2336
  headers
2337
2337
  });
2338
- const objectText = (_b2 = (_a12 = result2.toolCalls) == null ? void 0 : _a12[0]) == null ? void 0 : _b2.args;
2338
+ const objectText = (_b2 = (_a14 = result2.toolCalls) == null ? void 0 : _a14[0]) == null ? void 0 : _b2.args;
2339
2339
  if (objectText === void 0) {
2340
2340
  throw new NoObjectGeneratedError();
2341
2341
  }
@@ -2440,9 +2440,9 @@ var DefaultGenerateObjectResult = class {
2440
2440
  this.logprobs = options.logprobs;
2441
2441
  }
2442
2442
  toJsonResponse(init) {
2443
- var _a11;
2443
+ var _a13;
2444
2444
  return new Response(JSON.stringify(this.object), {
2445
- status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
2445
+ status: (_a13 = init == null ? void 0 : init.status) != null ? _a13 : 200,
2446
2446
  headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
2447
2447
  contentType: "application/json; charset=utf-8"
2448
2448
  })
@@ -2480,17 +2480,17 @@ var DelayedPromise = class {
2480
2480
  return this.promise;
2481
2481
  }
2482
2482
  resolve(value) {
2483
- var _a11;
2483
+ var _a13;
2484
2484
  this.status = { type: "resolved", value };
2485
2485
  if (this.promise) {
2486
- (_a11 = this._resolve) == null ? void 0 : _a11.call(this, value);
2486
+ (_a13 = this._resolve) == null ? void 0 : _a13.call(this, value);
2487
2487
  }
2488
2488
  }
2489
2489
  reject(error) {
2490
- var _a11;
2490
+ var _a13;
2491
2491
  this.status = { type: "rejected", error };
2492
2492
  if (this.promise) {
2493
- (_a11 = this._reject) == null ? void 0 : _a11.call(this, error);
2493
+ (_a13 = this._reject) == null ? void 0 : _a13.call(this, error);
2494
2494
  }
2495
2495
  }
2496
2496
  };
@@ -2579,8 +2579,8 @@ function createStitchableStream() {
2579
2579
 
2580
2580
  // core/util/now.ts
2581
2581
  function now() {
2582
- var _a11, _b;
2583
- return (_b = (_a11 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a11.now()) != null ? _b : Date.now();
2582
+ var _a13, _b;
2583
+ return (_b = (_a13 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a13.now()) != null ? _b : Date.now();
2584
2584
  }
2585
2585
 
2586
2586
  // core/generate-object/stream-object.ts
@@ -2869,7 +2869,7 @@ var DefaultStreamObjectResult = class {
2869
2869
  const transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(
2870
2870
  new TransformStream({
2871
2871
  async transform(chunk, controller) {
2872
- var _a11, _b, _c;
2872
+ var _a13, _b, _c;
2873
2873
  if (isFirstChunk) {
2874
2874
  const msToFirstChunk = now2() - startTimestampMs;
2875
2875
  isFirstChunk = false;
@@ -2915,7 +2915,7 @@ var DefaultStreamObjectResult = class {
2915
2915
  switch (chunk.type) {
2916
2916
  case "response-metadata": {
2917
2917
  response = {
2918
- id: (_a11 = chunk.id) != null ? _a11 : response.id,
2918
+ id: (_a13 = chunk.id) != null ? _a13 : response.id,
2919
2919
  timestamp: (_b = chunk.timestamp) != null ? _b : response.timestamp,
2920
2920
  modelId: (_c = chunk.modelId) != null ? _c : response.modelId
2921
2921
  };
@@ -3112,9 +3112,9 @@ var DefaultStreamObjectResult = class {
3112
3112
  });
3113
3113
  }
3114
3114
  toTextStreamResponse(init) {
3115
- var _a11;
3115
+ var _a13;
3116
3116
  return new Response(this.textStream.pipeThrough(new TextEncoderStream()), {
3117
- status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
3117
+ status: (_a13 = init == null ? void 0 : init.status) != null ? _a13 : 200,
3118
3118
  headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3119
3119
  contentType: "text/plain; charset=utf-8"
3120
3120
  })
@@ -3127,7 +3127,7 @@ import { createIdGenerator as createIdGenerator3 } from "@ai-sdk/provider-utils"
3127
3127
 
3128
3128
  // errors/index.ts
3129
3129
  import {
3130
- AISDKError as AISDKError10,
3130
+ AISDKError as AISDKError12,
3131
3131
  APICallError as APICallError2,
3132
3132
  EmptyResponseBodyError,
3133
3133
  InvalidPromptError as InvalidPromptError2,
@@ -3189,6 +3189,52 @@ var NoSuchToolError = class extends AISDKError9 {
3189
3189
  };
3190
3190
  _a9 = symbol9;
3191
3191
 
3192
+ // errors/tool-call-repair-error.ts
3193
+ import { AISDKError as AISDKError10, getErrorMessage as getErrorMessage3 } from "@ai-sdk/provider";
3194
+ var name10 = "AI_ToolCallRepairError";
3195
+ var marker10 = `vercel.ai.error.${name10}`;
3196
+ var symbol10 = Symbol.for(marker10);
3197
+ var _a10;
3198
+ var ToolCallRepairError = class extends AISDKError10 {
3199
+ constructor({
3200
+ cause,
3201
+ originalError,
3202
+ message = `Error repairing tool call: ${getErrorMessage3(cause)}`
3203
+ }) {
3204
+ super({ name: name10, message, cause });
3205
+ this[_a10] = true;
3206
+ this.originalError = originalError;
3207
+ }
3208
+ static isInstance(error) {
3209
+ return AISDKError10.hasMarker(error, marker10);
3210
+ }
3211
+ };
3212
+ _a10 = symbol10;
3213
+
3214
+ // errors/tool-execution-error.ts
3215
+ import { AISDKError as AISDKError11, getErrorMessage as getErrorMessage4 } from "@ai-sdk/provider";
3216
+ var name11 = "AI_ToolExecutionError";
3217
+ var marker11 = `vercel.ai.error.${name11}`;
3218
+ var symbol11 = Symbol.for(marker11);
3219
+ var _a11;
3220
+ var ToolExecutionError = class extends AISDKError11 {
3221
+ constructor({
3222
+ toolArgs,
3223
+ toolName,
3224
+ cause,
3225
+ message = `Error executing tool ${toolName}: ${getErrorMessage4(cause)}`
3226
+ }) {
3227
+ super({ name: name11, message, cause });
3228
+ this[_a11] = true;
3229
+ this.toolArgs = toolArgs;
3230
+ this.toolName = toolName;
3231
+ }
3232
+ static isInstance(error) {
3233
+ return AISDKError11.hasMarker(error, marker11);
3234
+ }
3235
+ };
3236
+ _a11 = symbol11;
3237
+
3192
3238
  // core/prompt/prepare-tools-and-tool-choice.ts
3193
3239
  import { asSchema as asSchema2 } from "@ai-sdk/ui-utils";
3194
3240
 
@@ -3210,24 +3256,24 @@ function prepareToolsAndToolChoice({
3210
3256
  };
3211
3257
  }
3212
3258
  const filteredTools = activeTools != null ? Object.entries(tools).filter(
3213
- ([name11]) => activeTools.includes(name11)
3259
+ ([name13]) => activeTools.includes(name13)
3214
3260
  ) : Object.entries(tools);
3215
3261
  return {
3216
- tools: filteredTools.map(([name11, tool2]) => {
3262
+ tools: filteredTools.map(([name13, tool2]) => {
3217
3263
  const toolType = tool2.type;
3218
3264
  switch (toolType) {
3219
3265
  case void 0:
3220
3266
  case "function":
3221
3267
  return {
3222
3268
  type: "function",
3223
- name: name11,
3269
+ name: name13,
3224
3270
  description: tool2.description,
3225
3271
  parameters: asSchema2(tool2.parameters).jsonSchema
3226
3272
  };
3227
3273
  case "provider-defined":
3228
3274
  return {
3229
3275
  type: "provider-defined",
3230
- name: name11,
3276
+ name: name13,
3231
3277
  id: tool2.id,
3232
3278
  args: tool2.args
3233
3279
  };
@@ -3257,14 +3303,49 @@ function removeTextAfterLastWhitespace(text2) {
3257
3303
  // core/generate-text/parse-tool-call.ts
3258
3304
  import { safeParseJSON as safeParseJSON2, safeValidateTypes as safeValidateTypes3 } from "@ai-sdk/provider-utils";
3259
3305
  import { asSchema as asSchema3 } from "@ai-sdk/ui-utils";
3260
- function parseToolCall({
3306
+ async function parseToolCall({
3261
3307
  toolCall,
3262
- tools
3308
+ tools,
3309
+ repairToolCall,
3310
+ system,
3311
+ messages
3263
3312
  }) {
3264
- const toolName = toolCall.toolName;
3265
3313
  if (tools == null) {
3266
3314
  throw new NoSuchToolError({ toolName: toolCall.toolName });
3267
3315
  }
3316
+ try {
3317
+ return await doParseToolCall({ toolCall, tools });
3318
+ } catch (error) {
3319
+ if (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolArgumentsError.isInstance(error))) {
3320
+ throw error;
3321
+ }
3322
+ let repairedToolCall = null;
3323
+ try {
3324
+ repairedToolCall = await repairToolCall({
3325
+ toolCall,
3326
+ tools,
3327
+ parameterSchema: ({ toolName }) => asSchema3(tools[toolName].parameters).jsonSchema,
3328
+ system,
3329
+ messages,
3330
+ error
3331
+ });
3332
+ } catch (repairError) {
3333
+ throw new ToolCallRepairError({
3334
+ cause: repairError,
3335
+ originalError: error
3336
+ });
3337
+ }
3338
+ if (repairedToolCall == null) {
3339
+ throw error;
3340
+ }
3341
+ return await doParseToolCall({ toolCall: repairedToolCall, tools });
3342
+ }
3343
+ }
3344
+ async function doParseToolCall({
3345
+ toolCall,
3346
+ tools
3347
+ }) {
3348
+ const toolName = toolCall.toolName;
3268
3349
  const tool2 = tools[toolName];
3269
3350
  if (tool2 == null) {
3270
3351
  throw new NoSuchToolError({
@@ -3344,6 +3425,7 @@ async function generateText({
3344
3425
  experimental_telemetry: telemetry,
3345
3426
  experimental_providerMetadata: providerMetadata,
3346
3427
  experimental_activeTools: activeTools,
3428
+ experimental_repairToolCall: repairToolCall,
3347
3429
  _internal: {
3348
3430
  generateId: generateId3 = originalGenerateId3,
3349
3431
  currentDate = () => /* @__PURE__ */ new Date()
@@ -3351,7 +3433,7 @@ async function generateText({
3351
3433
  onStepFinish,
3352
3434
  ...settings
3353
3435
  }) {
3354
- var _a11;
3436
+ var _a13;
3355
3437
  if (maxSteps < 1) {
3356
3438
  throw new InvalidArgumentError({
3357
3439
  parameter: "maxSteps",
@@ -3368,7 +3450,7 @@ async function generateText({
3368
3450
  });
3369
3451
  const initialPrompt = standardizePrompt({
3370
3452
  prompt: {
3371
- system: (_a11 = output == null ? void 0 : output.injectIntoSystemPrompt({ system, model })) != null ? _a11 : system,
3453
+ system: (_a13 = output == null ? void 0 : output.injectIntoSystemPrompt({ system, model })) != null ? _a13 : system,
3372
3454
  prompt,
3373
3455
  messages
3374
3456
  },
@@ -3394,7 +3476,7 @@ async function generateText({
3394
3476
  }),
3395
3477
  tracer,
3396
3478
  fn: async (span) => {
3397
- var _a12, _b, _c, _d, _e, _f;
3479
+ var _a14, _b, _c, _d, _e, _f;
3398
3480
  const mode = {
3399
3481
  type: "regular",
3400
3482
  ...prepareToolsAndToolChoice({ tools, toolChoice, activeTools })
@@ -3446,8 +3528,8 @@ async function generateText({
3446
3528
  "ai.prompt.tools": {
3447
3529
  // convert the language model level tools:
3448
3530
  input: () => {
3449
- var _a13;
3450
- return (_a13 = mode.tools) == null ? void 0 : _a13.map((tool2) => JSON.stringify(tool2));
3531
+ var _a15;
3532
+ return (_a15 = mode.tools) == null ? void 0 : _a15.map((tool2) => JSON.stringify(tool2));
3451
3533
  }
3452
3534
  },
3453
3535
  "ai.prompt.toolChoice": {
@@ -3467,7 +3549,7 @@ async function generateText({
3467
3549
  }),
3468
3550
  tracer,
3469
3551
  fn: async (span2) => {
3470
- var _a13, _b2, _c2, _d2, _e2, _f2;
3552
+ var _a15, _b2, _c2, _d2, _e2, _f2;
3471
3553
  const result = await model.doGenerate({
3472
3554
  mode,
3473
3555
  ...callSettings,
@@ -3479,7 +3561,7 @@ async function generateText({
3479
3561
  headers
3480
3562
  });
3481
3563
  const responseData = {
3482
- id: (_b2 = (_a13 = result.response) == null ? void 0 : _a13.id) != null ? _b2 : generateId3(),
3564
+ id: (_b2 = (_a15 = result.response) == null ? void 0 : _a15.id) != null ? _b2 : generateId3(),
3483
3565
  timestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : currentDate(),
3484
3566
  modelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : model.modelId
3485
3567
  };
@@ -3512,8 +3594,16 @@ async function generateText({
3512
3594
  }
3513
3595
  })
3514
3596
  );
3515
- currentToolCalls = ((_a12 = currentModelResponse.toolCalls) != null ? _a12 : []).map(
3516
- (modelToolCall) => parseToolCall({ toolCall: modelToolCall, tools })
3597
+ currentToolCalls = await Promise.all(
3598
+ ((_a14 = currentModelResponse.toolCalls) != null ? _a14 : []).map(
3599
+ (toolCall) => parseToolCall({
3600
+ toolCall,
3601
+ tools,
3602
+ repairToolCall,
3603
+ system,
3604
+ messages: stepInputMessages
3605
+ })
3606
+ )
3517
3607
  );
3518
3608
  currentToolResults = tools == null ? [] : await executeTools({
3519
3609
  toolCalls: currentToolCalls,
@@ -3659,25 +3749,33 @@ async function executeTools({
3659
3749
  }),
3660
3750
  tracer,
3661
3751
  fn: async (span) => {
3662
- const result2 = await tool2.execute(args, {
3663
- toolCallId,
3664
- messages,
3665
- abortSignal
3666
- });
3667
3752
  try {
3668
- span.setAttributes(
3669
- selectTelemetryAttributes({
3670
- telemetry,
3671
- attributes: {
3672
- "ai.toolCall.result": {
3673
- output: () => JSON.stringify(result2)
3753
+ const result2 = await tool2.execute(args, {
3754
+ toolCallId,
3755
+ messages,
3756
+ abortSignal
3757
+ });
3758
+ try {
3759
+ span.setAttributes(
3760
+ selectTelemetryAttributes({
3761
+ telemetry,
3762
+ attributes: {
3763
+ "ai.toolCall.result": {
3764
+ output: () => JSON.stringify(result2)
3765
+ }
3674
3766
  }
3675
- }
3676
- })
3677
- );
3678
- } catch (ignored) {
3767
+ })
3768
+ );
3769
+ } catch (ignored) {
3770
+ }
3771
+ return result2;
3772
+ } catch (error) {
3773
+ throw new ToolExecutionError({
3774
+ toolName,
3775
+ toolArgs: args,
3776
+ cause: error
3777
+ });
3679
3778
  }
3680
- return result2;
3681
3779
  }
3682
3780
  });
3683
3781
  return {
@@ -3709,6 +3807,46 @@ var DefaultGenerateTextResult = class {
3709
3807
  }
3710
3808
  };
3711
3809
 
3810
+ // core/generate-text/output.ts
3811
+ var output_exports = {};
3812
+ __export(output_exports, {
3813
+ object: () => object,
3814
+ text: () => text
3815
+ });
3816
+ import { parseJSON } from "@ai-sdk/provider-utils";
3817
+ import { asSchema as asSchema4 } from "@ai-sdk/ui-utils";
3818
+ var text = () => ({
3819
+ type: "text",
3820
+ responseFormat: () => ({ type: "text" }),
3821
+ injectIntoSystemPrompt({ system }) {
3822
+ return system;
3823
+ },
3824
+ parseOutput({ text: text2 }) {
3825
+ return text2;
3826
+ }
3827
+ });
3828
+ var object = ({
3829
+ schema: inputSchema
3830
+ }) => {
3831
+ const schema = asSchema4(inputSchema);
3832
+ return {
3833
+ type: "object",
3834
+ responseFormat: ({ model }) => ({
3835
+ type: "json",
3836
+ schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0
3837
+ }),
3838
+ injectIntoSystemPrompt({ system, model }) {
3839
+ return model.supportsStructuredOutputs ? system : injectJsonInstruction({
3840
+ prompt: system,
3841
+ schema: schema.jsonSchema
3842
+ });
3843
+ },
3844
+ parseOutput({ text: text2 }) {
3845
+ return parseJSON({ text: text2, schema });
3846
+ }
3847
+ };
3848
+ };
3849
+
3712
3850
  // core/generate-text/stream-text.ts
3713
3851
  import { createIdGenerator as createIdGenerator4 } from "@ai-sdk/provider-utils";
3714
3852
  import { formatDataStreamPart as formatDataStreamPart2 } from "@ai-sdk/ui-utils";
@@ -3809,8 +3947,10 @@ function runToolsTransformation({
3809
3947
  toolCallStreaming,
3810
3948
  tracer,
3811
3949
  telemetry,
3950
+ system,
3812
3951
  messages,
3813
- abortSignal
3952
+ abortSignal,
3953
+ repairToolCall
3814
3954
  }) {
3815
3955
  let toolResultsStreamController = null;
3816
3956
  const toolResultsStream = new ReadableStream({
@@ -3831,7 +3971,7 @@ function runToolsTransformation({
3831
3971
  }
3832
3972
  }
3833
3973
  const forwardStream = new TransformStream({
3834
- transform(chunk, controller) {
3974
+ async transform(chunk, controller) {
3835
3975
  const chunkType = chunk.type;
3836
3976
  switch (chunkType) {
3837
3977
  case "text-delta":
@@ -3880,9 +4020,12 @@ function runToolsTransformation({
3880
4020
  break;
3881
4021
  }
3882
4022
  try {
3883
- const toolCall = parseToolCall({
4023
+ const toolCall = await parseToolCall({
3884
4024
  toolCall: chunk,
3885
- tools
4025
+ tools,
4026
+ repairToolCall,
4027
+ system,
4028
+ messages
3886
4029
  });
3887
4030
  controller.enqueue(toolCall);
3888
4031
  if (tool2.execute != null) {
@@ -3935,7 +4078,11 @@ function runToolsTransformation({
3935
4078
  (error) => {
3936
4079
  toolResultsStreamController.enqueue({
3937
4080
  type: "error",
3938
- error
4081
+ error: new ToolExecutionError({
4082
+ toolName: toolCall.toolName,
4083
+ toolArgs: toolCall.args,
4084
+ cause: error
4085
+ })
3939
4086
  });
3940
4087
  outstandingToolResults.delete(toolExecutionId);
3941
4088
  attemptClose();
@@ -4017,6 +4164,7 @@ function streamText({
4017
4164
  experimental_providerMetadata: providerMetadata,
4018
4165
  experimental_toolCallStreaming: toolCallStreaming = false,
4019
4166
  experimental_activeTools: activeTools,
4167
+ experimental_repairToolCall: repairToolCall,
4020
4168
  onChunk,
4021
4169
  onFinish,
4022
4170
  onStepFinish,
@@ -4041,6 +4189,7 @@ function streamText({
4041
4189
  toolChoice,
4042
4190
  toolCallStreaming,
4043
4191
  activeTools,
4192
+ repairToolCall,
4044
4193
  maxSteps,
4045
4194
  continueSteps,
4046
4195
  providerMetadata,
@@ -4067,6 +4216,7 @@ var DefaultStreamTextResult = class {
4067
4216
  toolChoice,
4068
4217
  toolCallStreaming,
4069
4218
  activeTools,
4219
+ repairToolCall,
4070
4220
  maxSteps,
4071
4221
  continueSteps,
4072
4222
  providerMetadata,
@@ -4178,8 +4328,8 @@ var DefaultStreamTextResult = class {
4178
4328
  "ai.prompt.tools": {
4179
4329
  // convert the language model level tools:
4180
4330
  input: () => {
4181
- var _a11;
4182
- return (_a11 = mode.tools) == null ? void 0 : _a11.map((tool2) => JSON.stringify(tool2));
4331
+ var _a13;
4332
+ return (_a13 = mode.tools) == null ? void 0 : _a13.map((tool2) => JSON.stringify(tool2));
4183
4333
  }
4184
4334
  },
4185
4335
  "ai.prompt.toolChoice": {
@@ -4221,7 +4371,9 @@ var DefaultStreamTextResult = class {
4221
4371
  toolCallStreaming,
4222
4372
  tracer,
4223
4373
  telemetry,
4374
+ system,
4224
4375
  messages: stepInputMessages,
4376
+ repairToolCall,
4225
4377
  abortSignal
4226
4378
  });
4227
4379
  const stepRequest = request != null ? request : {};
@@ -4262,7 +4414,7 @@ var DefaultStreamTextResult = class {
4262
4414
  transformedStream.pipeThrough(
4263
4415
  new TransformStream({
4264
4416
  async transform(chunk, controller) {
4265
- var _a11, _b, _c;
4417
+ var _a13, _b, _c;
4266
4418
  if (stepFirstChunk) {
4267
4419
  const msToFirstChunk = now2() - startTimestampMs;
4268
4420
  stepFirstChunk = false;
@@ -4316,7 +4468,7 @@ var DefaultStreamTextResult = class {
4316
4468
  }
4317
4469
  case "response-metadata": {
4318
4470
  stepResponse = {
4319
- id: (_a11 = chunk.id) != null ? _a11 : stepResponse.id,
4471
+ id: (_a13 = chunk.id) != null ? _a13 : stepResponse.id,
4320
4472
  timestamp: (_b = chunk.timestamp) != null ? _b : stepResponse.timestamp,
4321
4473
  modelId: (_c = chunk.modelId) != null ? _c : stepResponse.modelId
4322
4474
  };
@@ -4563,7 +4715,8 @@ var DefaultStreamTextResult = class {
4563
4715
  self.stitchableStream.addStream(
4564
4716
  new ReadableStream({
4565
4717
  start(controller) {
4566
- controller.error(error);
4718
+ controller.enqueue({ type: "error", error });
4719
+ controller.close();
4567
4720
  }
4568
4721
  })
4569
4722
  );
@@ -4632,7 +4785,7 @@ var DefaultStreamTextResult = class {
4632
4785
  });
4633
4786
  }
4634
4787
  toDataStreamInternal({
4635
- getErrorMessage: getErrorMessage3 = () => "An error occurred.",
4788
+ getErrorMessage: getErrorMessage5 = () => "An error occurred.",
4636
4789
  // mask error messages for safety by default
4637
4790
  sendUsage = true
4638
4791
  } = {}) {
@@ -4692,7 +4845,7 @@ var DefaultStreamTextResult = class {
4692
4845
  }
4693
4846
  case "error": {
4694
4847
  controller.enqueue(
4695
- formatDataStreamPart2("error", getErrorMessage3(chunk.error))
4848
+ formatDataStreamPart2("error", getErrorMessage5(chunk.error))
4696
4849
  );
4697
4850
  break;
4698
4851
  }
@@ -4735,7 +4888,7 @@ var DefaultStreamTextResult = class {
4735
4888
  statusText,
4736
4889
  headers,
4737
4890
  data,
4738
- getErrorMessage: getErrorMessage3,
4891
+ getErrorMessage: getErrorMessage5,
4739
4892
  sendUsage
4740
4893
  } = {}) {
4741
4894
  writeToServerResponse({
@@ -4746,7 +4899,7 @@ var DefaultStreamTextResult = class {
4746
4899
  contentType: "text/plain; charset=utf-8",
4747
4900
  dataStreamVersion: "v1"
4748
4901
  }),
4749
- stream: this.toDataStream({ data, getErrorMessage: getErrorMessage3, sendUsage })
4902
+ stream: this.toDataStream({ data, getErrorMessage: getErrorMessage5, sendUsage })
4750
4903
  });
4751
4904
  }
4752
4905
  pipeTextStreamToResponse(response, init) {
@@ -4780,11 +4933,11 @@ var DefaultStreamTextResult = class {
4780
4933
  status,
4781
4934
  statusText,
4782
4935
  data,
4783
- getErrorMessage: getErrorMessage3,
4936
+ getErrorMessage: getErrorMessage5,
4784
4937
  sendUsage
4785
4938
  } = {}) {
4786
4939
  return new Response(
4787
- this.toDataStream({ data, getErrorMessage: getErrorMessage3, sendUsage }),
4940
+ this.toDataStream({ data, getErrorMessage: getErrorMessage5, sendUsage }),
4788
4941
  {
4789
4942
  status,
4790
4943
  statusText,
@@ -4796,9 +4949,9 @@ var DefaultStreamTextResult = class {
4796
4949
  );
4797
4950
  }
4798
4951
  toTextStreamResponse(init) {
4799
- var _a11;
4952
+ var _a13;
4800
4953
  return new Response(this.textStream.pipeThrough(new TextEncoderStream()), {
4801
- status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
4954
+ status: (_a13 = init == null ? void 0 : init.status) != null ? _a13 : 200,
4802
4955
  headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
4803
4956
  contentType: "text/plain; charset=utf-8"
4804
4957
  })
@@ -4806,46 +4959,6 @@ var DefaultStreamTextResult = class {
4806
4959
  }
4807
4960
  };
4808
4961
 
4809
- // core/generate-text/output.ts
4810
- var output_exports = {};
4811
- __export(output_exports, {
4812
- object: () => object,
4813
- text: () => text
4814
- });
4815
- import { parseJSON } from "@ai-sdk/provider-utils";
4816
- import { asSchema as asSchema4 } from "@ai-sdk/ui-utils";
4817
- var text = () => ({
4818
- type: "text",
4819
- responseFormat: () => ({ type: "text" }),
4820
- injectIntoSystemPrompt({ system }) {
4821
- return system;
4822
- },
4823
- parseOutput({ text: text2 }) {
4824
- return text2;
4825
- }
4826
- });
4827
- var object = ({
4828
- schema: inputSchema
4829
- }) => {
4830
- const schema = asSchema4(inputSchema);
4831
- return {
4832
- type: "object",
4833
- responseFormat: ({ model }) => ({
4834
- type: "json",
4835
- schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0
4836
- }),
4837
- injectIntoSystemPrompt({ system, model }) {
4838
- return model.supportsStructuredOutputs ? system : injectJsonInstruction({
4839
- prompt: system,
4840
- schema: schema.jsonSchema
4841
- });
4842
- },
4843
- parseOutput({ text: text2 }) {
4844
- return parseJSON({ text: text2, schema });
4845
- }
4846
- };
4847
- };
4848
-
4849
4962
  // core/middleware/wrap-language-model.ts
4850
4963
  var experimental_wrapLanguageModel = ({
4851
4964
  model,
@@ -4910,11 +5023,11 @@ function experimental_customProvider({
4910
5023
  }
4911
5024
 
4912
5025
  // core/registry/no-such-provider-error.ts
4913
- import { AISDKError as AISDKError11, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
4914
- var name10 = "AI_NoSuchProviderError";
4915
- var marker10 = `vercel.ai.error.${name10}`;
4916
- var symbol10 = Symbol.for(marker10);
4917
- var _a10;
5026
+ import { AISDKError as AISDKError13, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
5027
+ var name12 = "AI_NoSuchProviderError";
5028
+ var marker12 = `vercel.ai.error.${name12}`;
5029
+ var symbol12 = Symbol.for(marker12);
5030
+ var _a12;
4918
5031
  var NoSuchProviderError = class extends NoSuchModelError3 {
4919
5032
  constructor({
4920
5033
  modelId,
@@ -4923,16 +5036,16 @@ var NoSuchProviderError = class extends NoSuchModelError3 {
4923
5036
  availableProviders,
4924
5037
  message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`
4925
5038
  }) {
4926
- super({ errorName: name10, modelId, modelType, message });
4927
- this[_a10] = true;
5039
+ super({ errorName: name12, modelId, modelType, message });
5040
+ this[_a12] = true;
4928
5041
  this.providerId = providerId;
4929
5042
  this.availableProviders = availableProviders;
4930
5043
  }
4931
5044
  static isInstance(error) {
4932
- return AISDKError11.hasMarker(error, marker10);
5045
+ return AISDKError13.hasMarker(error, marker12);
4933
5046
  }
4934
5047
  };
4935
- _a10 = symbol10;
5048
+ _a12 = symbol12;
4936
5049
 
4937
5050
  // core/registry/provider-registry.ts
4938
5051
  import { NoSuchModelError as NoSuchModelError4 } from "@ai-sdk/provider";
@@ -4974,19 +5087,19 @@ var DefaultProviderRegistry = class {
4974
5087
  return [id.slice(0, index), id.slice(index + 1)];
4975
5088
  }
4976
5089
  languageModel(id) {
4977
- var _a11, _b;
5090
+ var _a13, _b;
4978
5091
  const [providerId, modelId] = this.splitId(id, "languageModel");
4979
- const model = (_b = (_a11 = this.getProvider(providerId)).languageModel) == null ? void 0 : _b.call(_a11, modelId);
5092
+ const model = (_b = (_a13 = this.getProvider(providerId)).languageModel) == null ? void 0 : _b.call(_a13, modelId);
4980
5093
  if (model == null) {
4981
5094
  throw new NoSuchModelError4({ modelId: id, modelType: "languageModel" });
4982
5095
  }
4983
5096
  return model;
4984
5097
  }
4985
5098
  textEmbeddingModel(id) {
4986
- var _a11;
5099
+ var _a13;
4987
5100
  const [providerId, modelId] = this.splitId(id, "textEmbeddingModel");
4988
5101
  const provider = this.getProvider(providerId);
4989
- const model = (_a11 = provider.textEmbeddingModel) == null ? void 0 : _a11.call(provider, modelId);
5102
+ const model = (_a13 = provider.textEmbeddingModel) == null ? void 0 : _a13.call(provider, modelId);
4990
5103
  if (model == null) {
4991
5104
  throw new NoSuchModelError4({
4992
5105
  modelId: id,
@@ -5034,7 +5147,7 @@ import {
5034
5147
  function AssistantResponse({ threadId, messageId }, process2) {
5035
5148
  const stream = new ReadableStream({
5036
5149
  async start(controller) {
5037
- var _a11;
5150
+ var _a13;
5038
5151
  const textEncoder = new TextEncoder();
5039
5152
  const sendMessage = (message) => {
5040
5153
  controller.enqueue(
@@ -5056,7 +5169,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5056
5169
  );
5057
5170
  };
5058
5171
  const forwardStream = async (stream2) => {
5059
- var _a12, _b;
5172
+ var _a14, _b;
5060
5173
  let result = void 0;
5061
5174
  for await (const value of stream2) {
5062
5175
  switch (value.event) {
@@ -5073,7 +5186,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5073
5186
  break;
5074
5187
  }
5075
5188
  case "thread.message.delta": {
5076
- const content = (_a12 = value.data.delta.content) == null ? void 0 : _a12[0];
5189
+ const content = (_a14 = value.data.delta.content) == null ? void 0 : _a14[0];
5077
5190
  if ((content == null ? void 0 : content.type) === "text" && ((_b = content.text) == null ? void 0 : _b.value) != null) {
5078
5191
  controller.enqueue(
5079
5192
  textEncoder.encode(
@@ -5107,7 +5220,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5107
5220
  forwardStream
5108
5221
  });
5109
5222
  } catch (error) {
5110
- sendError((_a11 = error.message) != null ? _a11 : `${error}`);
5223
+ sendError((_a13 = error.message) != null ? _a13 : `${error}`);
5111
5224
  } finally {
5112
5225
  controller.close();
5113
5226
  }
@@ -5168,7 +5281,7 @@ function toDataStreamInternal(stream, callbacks) {
5168
5281
  return stream.pipeThrough(
5169
5282
  new TransformStream({
5170
5283
  transform: async (value, controller) => {
5171
- var _a11;
5284
+ var _a13;
5172
5285
  if (typeof value === "string") {
5173
5286
  controller.enqueue(value);
5174
5287
  return;
@@ -5176,7 +5289,7 @@ function toDataStreamInternal(stream, callbacks) {
5176
5289
  if ("event" in value) {
5177
5290
  if (value.event === "on_chat_model_stream") {
5178
5291
  forwardAIMessageChunk(
5179
- (_a11 = value.data) == null ? void 0 : _a11.chunk,
5292
+ (_a13 = value.data) == null ? void 0 : _a13.chunk,
5180
5293
  controller
5181
5294
  );
5182
5295
  }
@@ -5199,7 +5312,7 @@ function toDataStream(stream, callbacks) {
5199
5312
  );
5200
5313
  }
5201
5314
  function toDataStreamResponse(stream, options) {
5202
- var _a11;
5315
+ var _a13;
5203
5316
  const dataStream = toDataStreamInternal(
5204
5317
  stream,
5205
5318
  options == null ? void 0 : options.callbacks
@@ -5208,7 +5321,7 @@ function toDataStreamResponse(stream, options) {
5208
5321
  const init = options == null ? void 0 : options.init;
5209
5322
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
5210
5323
  return new Response(responseStream, {
5211
- status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
5324
+ status: (_a13 = init == null ? void 0 : init.status) != null ? _a13 : 200,
5212
5325
  statusText: init == null ? void 0 : init.statusText,
5213
5326
  headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
5214
5327
  contentType: "text/plain; charset=utf-8",
@@ -5263,14 +5376,14 @@ function toDataStream2(stream, callbacks) {
5263
5376
  );
5264
5377
  }
5265
5378
  function toDataStreamResponse2(stream, options = {}) {
5266
- var _a11;
5379
+ var _a13;
5267
5380
  const { init, data, callbacks } = options;
5268
5381
  const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
5269
5382
  new TextEncoderStream()
5270
5383
  );
5271
5384
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
5272
5385
  return new Response(responseStream, {
5273
- status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
5386
+ status: (_a13 = init == null ? void 0 : init.status) != null ? _a13 : 200,
5274
5387
  statusText: init == null ? void 0 : init.statusText,
5275
5388
  headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
5276
5389
  contentType: "text/plain; charset=utf-8",
@@ -5362,7 +5475,7 @@ var StreamData = class {
5362
5475
  }
5363
5476
  };
5364
5477
  export {
5365
- AISDKError10 as AISDKError,
5478
+ AISDKError12 as AISDKError,
5366
5479
  APICallError2 as APICallError,
5367
5480
  AssistantResponse,
5368
5481
  DownloadError,
@@ -5386,6 +5499,8 @@ export {
5386
5499
  output_exports as Output,
5387
5500
  RetryError,
5388
5501
  StreamData,
5502
+ ToolCallRepairError,
5503
+ ToolExecutionError,
5389
5504
  TypeValidationError2 as TypeValidationError,
5390
5505
  UnsupportedFunctionalityError2 as UnsupportedFunctionalityError,
5391
5506
  convertToCoreMessages,