ai 3.3.16 → 3.3.18

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 name12 in all)
4
- __defProp(target, name12, { get: all[name12], enumerable: true });
3
+ for (var name10 in all)
4
+ __defProp(target, name10, { get: all[name10], enumerable: true });
5
5
  };
6
6
 
7
7
  // streams/index.ts
@@ -142,7 +142,7 @@ function getBaseTelemetryAttributes({
142
142
  telemetry,
143
143
  headers
144
144
  }) {
145
- var _a12;
145
+ var _a10;
146
146
  return {
147
147
  "ai.model.provider": model.provider,
148
148
  "ai.model.id": model.modelId,
@@ -152,7 +152,7 @@ function getBaseTelemetryAttributes({
152
152
  return attributes;
153
153
  }, {}),
154
154
  // add metadata as attributes:
155
- ...Object.entries((_a12 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a12 : {}).reduce(
155
+ ...Object.entries((_a10 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a10 : {}).reduce(
156
156
  (attributes, [key, value]) => {
157
157
  attributes[`ai.telemetry.metadata.${key}`] = value;
158
158
  return attributes;
@@ -177,7 +177,7 @@ var noopTracer = {
177
177
  startSpan() {
178
178
  return noopSpan;
179
179
  },
180
- startActiveSpan(name12, arg1, arg2, arg3) {
180
+ startActiveSpan(name10, arg1, arg2, arg3) {
181
181
  if (typeof arg1 === "function") {
182
182
  return arg1(noopSpan);
183
183
  }
@@ -245,13 +245,13 @@ function getTracer({ isEnabled }) {
245
245
  // core/telemetry/record-span.ts
246
246
  import { SpanStatusCode } from "@opentelemetry/api";
247
247
  function recordSpan({
248
- name: name12,
248
+ name: name10,
249
249
  tracer,
250
250
  attributes,
251
251
  fn,
252
252
  endWhenDone = true
253
253
  }) {
254
- return tracer.startActiveSpan(name12, { attributes }, async (span) => {
254
+ return tracer.startActiveSpan(name10, { attributes }, async (span) => {
255
255
  try {
256
256
  const result = await fn(span);
257
257
  if (endWhenDone) {
@@ -317,14 +317,14 @@ async function embed({
317
317
  headers,
318
318
  experimental_telemetry: telemetry
319
319
  }) {
320
- var _a12;
320
+ var _a10;
321
321
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
322
322
  model,
323
323
  telemetry,
324
324
  headers,
325
325
  settings: { maxRetries }
326
326
  });
327
- const tracer = getTracer({ isEnabled: (_a12 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a12 : false });
327
+ const tracer = getTracer({ isEnabled: (_a10 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a10 : false });
328
328
  return recordSpan({
329
329
  name: "ai.embed",
330
330
  attributes: selectTelemetryAttributes({
@@ -357,14 +357,14 @@ async function embed({
357
357
  }),
358
358
  tracer,
359
359
  fn: async (doEmbedSpan) => {
360
- var _a13;
360
+ var _a11;
361
361
  const modelResponse = await model.doEmbed({
362
362
  values: [value],
363
363
  abortSignal,
364
364
  headers
365
365
  });
366
366
  const embedding2 = modelResponse.embeddings[0];
367
- const usage2 = (_a13 = modelResponse.usage) != null ? _a13 : { tokens: NaN };
367
+ const usage2 = (_a11 = modelResponse.usage) != null ? _a11 : { tokens: NaN };
368
368
  doEmbedSpan.setAttributes(
369
369
  selectTelemetryAttributes({
370
370
  telemetry,
@@ -430,14 +430,14 @@ async function embedMany({
430
430
  headers,
431
431
  experimental_telemetry: telemetry
432
432
  }) {
433
- var _a12;
433
+ var _a10;
434
434
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
435
435
  model,
436
436
  telemetry,
437
437
  headers,
438
438
  settings: { maxRetries }
439
439
  });
440
- const tracer = getTracer({ isEnabled: (_a12 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a12 : false });
440
+ const tracer = getTracer({ isEnabled: (_a10 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a10 : false });
441
441
  return recordSpan({
442
442
  name: "ai.embedMany",
443
443
  attributes: selectTelemetryAttributes({
@@ -475,14 +475,14 @@ async function embedMany({
475
475
  }),
476
476
  tracer,
477
477
  fn: async (doEmbedSpan) => {
478
- var _a13;
478
+ var _a11;
479
479
  const modelResponse = await model.doEmbed({
480
480
  values,
481
481
  abortSignal,
482
482
  headers
483
483
  });
484
484
  const embeddings3 = modelResponse.embeddings;
485
- const usage2 = (_a13 = modelResponse.usage) != null ? _a13 : { tokens: NaN };
485
+ const usage2 = (_a11 = modelResponse.usage) != null ? _a11 : { tokens: NaN };
486
486
  doEmbedSpan.setAttributes(
487
487
  selectTelemetryAttributes({
488
488
  telemetry,
@@ -534,14 +534,14 @@ async function embedMany({
534
534
  }),
535
535
  tracer,
536
536
  fn: async (doEmbedSpan) => {
537
- var _a13;
537
+ var _a11;
538
538
  const modelResponse = await model.doEmbed({
539
539
  values: chunk,
540
540
  abortSignal,
541
541
  headers
542
542
  });
543
543
  const embeddings2 = modelResponse.embeddings;
544
- const usage2 = (_a13 = modelResponse.usage) != null ? _a13 : { tokens: NaN };
544
+ const usage2 = (_a11 = modelResponse.usage) != null ? _a11 : { tokens: NaN };
545
545
  doEmbedSpan.setAttributes(
546
546
  selectTelemetryAttributes({
547
547
  telemetry,
@@ -589,7 +589,6 @@ var DefaultEmbedManyResult = class {
589
589
 
590
590
  // core/generate-object/generate-object.ts
591
591
  import { safeParseJSON } from "@ai-sdk/provider-utils";
592
- import { asSchema } from "@ai-sdk/ui-utils";
593
592
 
594
593
  // core/prompt/convert-to-language-model-prompt.ts
595
594
  import { getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider-utils";
@@ -644,7 +643,7 @@ async function download({
644
643
  url,
645
644
  fetchImplementation = fetch
646
645
  }) {
647
- var _a12;
646
+ var _a10;
648
647
  const urlText = url.toString();
649
648
  try {
650
649
  const response = await fetchImplementation(urlText);
@@ -657,7 +656,7 @@ async function download({
657
656
  }
658
657
  return {
659
658
  data: new Uint8Array(await response.arrayBuffer()),
660
- mimeType: (_a12 = response.headers.get("content-type")) != null ? _a12 : void 0
659
+ mimeType: (_a10 = response.headers.get("content-type")) != null ? _a10 : void 0
661
660
  };
662
661
  } catch (error) {
663
662
  if (DownloadError.isInstance(error)) {
@@ -738,8 +737,8 @@ var dataContentSchema = z.union([
738
737
  z.custom(
739
738
  // Buffer might not be available in some environments such as CloudFlare:
740
739
  (value) => {
741
- var _a12, _b;
742
- return (_b = (_a12 = globalThis.Buffer) == null ? void 0 : _a12.isBuffer(value)) != null ? _b : false;
740
+ var _a10, _b;
741
+ return (_b = (_a10 = globalThis.Buffer) == null ? void 0 : _a10.isBuffer(value)) != null ? _b : false;
743
742
  },
744
743
  { message: "Must be a Buffer" }
745
744
  )
@@ -867,7 +866,7 @@ function convertToLanguageModelMessage(message, downloadedImages) {
867
866
  role: "user",
868
867
  content: message.content.map(
869
868
  (part) => {
870
- var _a12, _b, _c;
869
+ var _a10, _b, _c;
871
870
  switch (part.type) {
872
871
  case "text": {
873
872
  return {
@@ -890,7 +889,7 @@ function convertToLanguageModelMessage(message, downloadedImages) {
890
889
  return {
891
890
  type: "image",
892
891
  image: downloadedImage.data,
893
- mimeType: (_a12 = part.mimeType) != null ? _a12 : downloadedImage.mimeType,
892
+ mimeType: (_a10 = part.mimeType) != null ? _a10 : downloadedImage.mimeType,
894
893
  providerMetadata: part.experimental_providerMetadata
895
894
  };
896
895
  }
@@ -1322,8 +1321,8 @@ function prepareResponseHeaders(init, {
1322
1321
  contentType,
1323
1322
  dataStreamVersion
1324
1323
  }) {
1325
- var _a12;
1326
- const headers = new Headers((_a12 = init == null ? void 0 : init.headers) != null ? _a12 : {});
1324
+ var _a10;
1325
+ const headers = new Headers((_a10 = init == null ? void 0 : init.headers) != null ? _a10 : {});
1327
1326
  if (!headers.has("Content-Type")) {
1328
1327
  headers.set("Content-Type", contentType);
1329
1328
  }
@@ -1388,6 +1387,173 @@ var NoObjectGeneratedError = class extends AISDKError6 {
1388
1387
  };
1389
1388
  _a6 = symbol6;
1390
1389
 
1390
+ // core/generate-object/output-strategy.ts
1391
+ import {
1392
+ isJSONArray,
1393
+ isJSONObject,
1394
+ TypeValidationError,
1395
+ UnsupportedFunctionalityError
1396
+ } from "@ai-sdk/provider";
1397
+ import { safeValidateTypes as safeValidateTypes2 } from "@ai-sdk/provider-utils";
1398
+ import { asSchema } from "@ai-sdk/ui-utils";
1399
+
1400
+ // core/util/async-iterable-stream.ts
1401
+ function createAsyncIterableStream(source, transformer) {
1402
+ const transformedStream = source.pipeThrough(
1403
+ new TransformStream(transformer)
1404
+ );
1405
+ transformedStream[Symbol.asyncIterator] = () => {
1406
+ const reader = transformedStream.getReader();
1407
+ return {
1408
+ async next() {
1409
+ const { done, value } = await reader.read();
1410
+ return done ? { done: true, value: void 0 } : { done: false, value };
1411
+ }
1412
+ };
1413
+ };
1414
+ return transformedStream;
1415
+ }
1416
+
1417
+ // core/generate-object/output-strategy.ts
1418
+ var noSchemaOutputStrategy = {
1419
+ type: "no-schema",
1420
+ jsonSchema: void 0,
1421
+ validatePartialResult({ value }) {
1422
+ return { success: true, value };
1423
+ },
1424
+ validateFinalResult(value) {
1425
+ return value === void 0 ? { success: false, error: new NoObjectGeneratedError() } : { success: true, value };
1426
+ },
1427
+ createElementStream() {
1428
+ throw new UnsupportedFunctionalityError({
1429
+ functionality: "element streams in no-schema mode"
1430
+ });
1431
+ }
1432
+ };
1433
+ var objectOutputStrategy = (schema) => ({
1434
+ type: "object",
1435
+ jsonSchema: schema.jsonSchema,
1436
+ validatePartialResult({ value }) {
1437
+ return { success: true, value };
1438
+ },
1439
+ validateFinalResult(value) {
1440
+ return safeValidateTypes2({ value, schema });
1441
+ },
1442
+ createElementStream() {
1443
+ throw new UnsupportedFunctionalityError({
1444
+ functionality: "element streams in object mode"
1445
+ });
1446
+ }
1447
+ });
1448
+ var arrayOutputStrategy = (schema) => {
1449
+ const { $schema, ...itemSchema } = schema.jsonSchema;
1450
+ return {
1451
+ type: "object",
1452
+ // wrap in object that contains array of elements, since most LLMs will not
1453
+ // be able to generate an array directly:
1454
+ // possible future optimization: use arrays directly when model supports grammar-guided generation
1455
+ jsonSchema: {
1456
+ $schema: "http://json-schema.org/draft-07/schema#",
1457
+ type: "object",
1458
+ properties: {
1459
+ elements: { type: "array", items: itemSchema }
1460
+ },
1461
+ required: ["elements"],
1462
+ additionalProperties: false
1463
+ },
1464
+ validatePartialResult({
1465
+ value,
1466
+ parseState
1467
+ }) {
1468
+ if (!isJSONObject(value) || !isJSONArray(value.elements)) {
1469
+ return {
1470
+ success: false,
1471
+ error: new TypeValidationError({
1472
+ value,
1473
+ cause: "value must be an object that contains an array of elements"
1474
+ })
1475
+ };
1476
+ }
1477
+ const inputArray = value.elements;
1478
+ const resultArray = [];
1479
+ for (let i = 0; i < inputArray.length; i++) {
1480
+ const element = inputArray[i];
1481
+ const result = safeValidateTypes2({ value: element, schema });
1482
+ if (i === inputArray.length - 1 && (!result.success || parseState !== "successful-parse")) {
1483
+ continue;
1484
+ }
1485
+ if (!result.success) {
1486
+ return result;
1487
+ }
1488
+ resultArray.push(result.value);
1489
+ }
1490
+ return { success: true, value: resultArray };
1491
+ },
1492
+ validateFinalResult(value) {
1493
+ if (!isJSONObject(value) || !isJSONArray(value.elements)) {
1494
+ return {
1495
+ success: false,
1496
+ error: new TypeValidationError({
1497
+ value,
1498
+ cause: "value must be an object that contains an array of elements"
1499
+ })
1500
+ };
1501
+ }
1502
+ const inputArray = value.elements;
1503
+ for (const element of inputArray) {
1504
+ const result = safeValidateTypes2({ value: element, schema });
1505
+ if (!result.success) {
1506
+ return result;
1507
+ }
1508
+ }
1509
+ return { success: true, value: inputArray };
1510
+ },
1511
+ createElementStream(originalStream) {
1512
+ let publishedElements = 0;
1513
+ return createAsyncIterableStream(originalStream, {
1514
+ transform(chunk, controller) {
1515
+ switch (chunk.type) {
1516
+ case "object": {
1517
+ const array = chunk.object;
1518
+ for (; publishedElements < array.length; publishedElements++) {
1519
+ controller.enqueue(array[publishedElements]);
1520
+ }
1521
+ break;
1522
+ }
1523
+ case "text-delta":
1524
+ case "finish":
1525
+ break;
1526
+ case "error":
1527
+ controller.error(chunk.error);
1528
+ break;
1529
+ default: {
1530
+ const _exhaustiveCheck = chunk;
1531
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
1532
+ }
1533
+ }
1534
+ }
1535
+ });
1536
+ }
1537
+ };
1538
+ };
1539
+ function getOutputStrategy({
1540
+ output,
1541
+ schema
1542
+ }) {
1543
+ switch (output) {
1544
+ case "object":
1545
+ return objectOutputStrategy(asSchema(schema));
1546
+ case "array":
1547
+ return arrayOutputStrategy(asSchema(schema));
1548
+ case "no-schema":
1549
+ return noSchemaOutputStrategy;
1550
+ default: {
1551
+ const _exhaustiveCheck = output;
1552
+ throw new Error(`Unsupported output: ${_exhaustiveCheck}`);
1553
+ }
1554
+ }
1555
+ }
1556
+
1391
1557
  // core/generate-object/validate-object-generation-input.ts
1392
1558
  function validateObjectGenerationInput({
1393
1559
  output,
@@ -1396,7 +1562,7 @@ function validateObjectGenerationInput({
1396
1562
  schemaName,
1397
1563
  schemaDescription
1398
1564
  }) {
1399
- if (output != null && output !== "object" && output !== "no-schema") {
1565
+ if (output != null && output !== "object" && output !== "array" && output !== "no-schema") {
1400
1566
  throw new InvalidArgumentError({
1401
1567
  parameter: "output",
1402
1568
  value: output,
@@ -1442,6 +1608,15 @@ function validateObjectGenerationInput({
1442
1608
  });
1443
1609
  }
1444
1610
  }
1611
+ if (output === "array") {
1612
+ if (schema == null) {
1613
+ throw new InvalidArgumentError({
1614
+ parameter: "schema",
1615
+ value: schema,
1616
+ message: "Element schema is required for array output."
1617
+ });
1618
+ }
1619
+ }
1445
1620
  }
1446
1621
 
1447
1622
  // core/generate-object/generate-object.ts
@@ -1461,7 +1636,7 @@ async function generateObject({
1461
1636
  experimental_telemetry: telemetry,
1462
1637
  ...settings
1463
1638
  }) {
1464
- var _a12;
1639
+ var _a10;
1465
1640
  validateObjectGenerationInput({
1466
1641
  output,
1467
1642
  mode,
@@ -1469,7 +1644,8 @@ async function generateObject({
1469
1644
  schemaName,
1470
1645
  schemaDescription
1471
1646
  });
1472
- if (output === "no-schema" && mode === void 0) {
1647
+ const outputStrategy = getOutputStrategy({ output, schema: inputSchema });
1648
+ if (outputStrategy.type === "no-schema" && mode === void 0) {
1473
1649
  mode = "json";
1474
1650
  }
1475
1651
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
@@ -1478,8 +1654,7 @@ async function generateObject({
1478
1654
  headers,
1479
1655
  settings: { ...settings, maxRetries }
1480
1656
  });
1481
- const schema = inputSchema != null ? asSchema(inputSchema) : void 0;
1482
- const tracer = getTracer({ isEnabled: (_a12 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a12 : false });
1657
+ const tracer = getTracer({ isEnabled: (_a10 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a10 : false });
1483
1658
  return recordSpan({
1484
1659
  name: "ai.generateObject",
1485
1660
  attributes: selectTelemetryAttributes({
@@ -1494,10 +1669,10 @@ async function generateObject({
1494
1669
  "ai.prompt": {
1495
1670
  input: () => JSON.stringify({ system, prompt, messages })
1496
1671
  },
1497
- "ai.schema": schema != null ? { input: () => JSON.stringify(schema.jsonSchema) } : void 0,
1672
+ "ai.schema": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,
1498
1673
  "ai.schema.name": schemaName,
1499
1674
  "ai.schema.description": schemaDescription,
1500
- "ai.settings.output": output,
1675
+ "ai.settings.output": outputStrategy.type,
1501
1676
  "ai.settings.mode": mode
1502
1677
  }
1503
1678
  }),
@@ -1517,9 +1692,9 @@ async function generateObject({
1517
1692
  switch (mode) {
1518
1693
  case "json": {
1519
1694
  const validatedPrompt = validatePrompt({
1520
- system: schema == null ? injectJsonInstruction({ prompt: system }) : model.supportsStructuredOutputs && schema != null ? system : injectJsonInstruction({
1695
+ system: outputStrategy.jsonSchema == null ? injectJsonInstruction({ prompt: system }) : model.supportsStructuredOutputs ? system : injectJsonInstruction({
1521
1696
  prompt: system,
1522
- schema: schema.jsonSchema
1697
+ schema: outputStrategy.jsonSchema
1523
1698
  }),
1524
1699
  prompt,
1525
1700
  messages
@@ -1560,7 +1735,7 @@ async function generateObject({
1560
1735
  const result2 = await model.doGenerate({
1561
1736
  mode: {
1562
1737
  type: "object-json",
1563
- schema: schema == null ? void 0 : schema.jsonSchema,
1738
+ schema: outputStrategy.jsonSchema,
1564
1739
  name: schemaName,
1565
1740
  description: schemaDescription
1566
1741
  },
@@ -1640,7 +1815,7 @@ async function generateObject({
1640
1815
  }),
1641
1816
  tracer,
1642
1817
  fn: async (span2) => {
1643
- var _a13, _b;
1818
+ var _a11, _b;
1644
1819
  const result2 = await model.doGenerate({
1645
1820
  mode: {
1646
1821
  type: "object-tool",
@@ -1648,7 +1823,7 @@ async function generateObject({
1648
1823
  type: "function",
1649
1824
  name: schemaName != null ? schemaName : "json",
1650
1825
  description: schemaDescription != null ? schemaDescription : "Respond with a JSON object.",
1651
- parameters: schema.jsonSchema
1826
+ parameters: outputStrategy.jsonSchema
1652
1827
  }
1653
1828
  },
1654
1829
  ...prepareCallSettings(settings),
@@ -1657,7 +1832,7 @@ async function generateObject({
1657
1832
  abortSignal,
1658
1833
  headers
1659
1834
  });
1660
- const objectText = (_b = (_a13 = result2.toolCalls) == null ? void 0 : _a13[0]) == null ? void 0 : _b.args;
1835
+ const objectText = (_b = (_a11 = result2.toolCalls) == null ? void 0 : _a11[0]) == null ? void 0 : _b.args;
1661
1836
  if (objectText === void 0) {
1662
1837
  throw new NoObjectGeneratedError();
1663
1838
  }
@@ -1699,15 +1874,16 @@ async function generateObject({
1699
1874
  throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
1700
1875
  }
1701
1876
  }
1702
- const parseResult = safeParseJSON({
1703
- text: result,
1704
- // type casting required for `undefined` schema (no-schema mode),
1705
- // in which case <T> is <JSONValue> as desired.
1706
- schema
1707
- });
1877
+ const parseResult = safeParseJSON({ text: result });
1708
1878
  if (!parseResult.success) {
1709
1879
  throw parseResult.error;
1710
1880
  }
1881
+ const validationResult = outputStrategy.validateFinalResult(
1882
+ parseResult.value
1883
+ );
1884
+ if (!validationResult.success) {
1885
+ throw validationResult.error;
1886
+ }
1711
1887
  span.setAttributes(
1712
1888
  selectTelemetryAttributes({
1713
1889
  telemetry,
@@ -1716,13 +1892,13 @@ async function generateObject({
1716
1892
  "ai.usage.promptTokens": usage.promptTokens,
1717
1893
  "ai.usage.completionTokens": usage.completionTokens,
1718
1894
  "ai.result.object": {
1719
- output: () => JSON.stringify(parseResult.value)
1895
+ output: () => JSON.stringify(validationResult.value)
1720
1896
  }
1721
1897
  }
1722
1898
  })
1723
1899
  );
1724
1900
  return new DefaultGenerateObjectResult({
1725
- object: parseResult.value,
1901
+ object: validationResult.value,
1726
1902
  finishReason,
1727
1903
  usage: calculateCompletionTokenUsage(usage),
1728
1904
  warnings,
@@ -1744,9 +1920,9 @@ var DefaultGenerateObjectResult = class {
1744
1920
  this.experimental_providerMetadata = options.providerMetadata;
1745
1921
  }
1746
1922
  toJsonResponse(init) {
1747
- var _a12;
1923
+ var _a10;
1748
1924
  return new Response(JSON.stringify(this.object), {
1749
- status: (_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200,
1925
+ status: (_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200,
1750
1926
  headers: prepareResponseHeaders(init, {
1751
1927
  contentType: "application/json; charset=utf-8"
1752
1928
  })
@@ -1756,9 +1932,7 @@ var DefaultGenerateObjectResult = class {
1756
1932
  var experimental_generateObject = generateObject;
1757
1933
 
1758
1934
  // core/generate-object/stream-object.ts
1759
- import { safeValidateTypes as safeValidateTypes2 } from "@ai-sdk/provider-utils";
1760
1935
  import {
1761
- asSchema as asSchema2,
1762
1936
  isDeepEqualData,
1763
1937
  parsePartialJson
1764
1938
  } from "@ai-sdk/ui-utils";
@@ -1801,38 +1975,21 @@ var DelayedPromise = class {
1801
1975
  return this.promise;
1802
1976
  }
1803
1977
  resolve(value) {
1804
- var _a12;
1978
+ var _a10;
1805
1979
  this.status = { type: "resolved", value };
1806
1980
  if (this.promise) {
1807
- (_a12 = this._resolve) == null ? void 0 : _a12.call(this, value);
1981
+ (_a10 = this._resolve) == null ? void 0 : _a10.call(this, value);
1808
1982
  }
1809
1983
  }
1810
1984
  reject(error) {
1811
- var _a12;
1985
+ var _a10;
1812
1986
  this.status = { type: "rejected", error };
1813
1987
  if (this.promise) {
1814
- (_a12 = this._reject) == null ? void 0 : _a12.call(this, error);
1988
+ (_a10 = this._reject) == null ? void 0 : _a10.call(this, error);
1815
1989
  }
1816
1990
  }
1817
1991
  };
1818
1992
 
1819
- // core/util/async-iterable-stream.ts
1820
- function createAsyncIterableStream(source, transformer) {
1821
- const transformedStream = source.pipeThrough(
1822
- new TransformStream(transformer)
1823
- );
1824
- transformedStream[Symbol.asyncIterator] = () => {
1825
- const reader = transformedStream.getReader();
1826
- return {
1827
- async next() {
1828
- const { done, value } = await reader.read();
1829
- return done ? { done: true, value: void 0 } : { done: false, value };
1830
- }
1831
- };
1832
- };
1833
- return transformedStream;
1834
- }
1835
-
1836
1993
  // core/generate-object/stream-object.ts
1837
1994
  async function streamObject({
1838
1995
  model,
@@ -1851,7 +2008,7 @@ async function streamObject({
1851
2008
  onFinish,
1852
2009
  ...settings
1853
2010
  }) {
1854
- var _a12;
2011
+ var _a10;
1855
2012
  validateObjectGenerationInput({
1856
2013
  output,
1857
2014
  mode,
@@ -1859,7 +2016,8 @@ async function streamObject({
1859
2016
  schemaName,
1860
2017
  schemaDescription
1861
2018
  });
1862
- if (output === "no-schema" && mode === void 0) {
2019
+ const outputStrategy = getOutputStrategy({ output, schema: inputSchema });
2020
+ if (outputStrategy.type === "no-schema" && mode === void 0) {
1863
2021
  mode = "json";
1864
2022
  }
1865
2023
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
@@ -1868,9 +2026,8 @@ async function streamObject({
1868
2026
  headers,
1869
2027
  settings: { ...settings, maxRetries }
1870
2028
  });
1871
- const tracer = getTracer({ isEnabled: (_a12 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a12 : false });
2029
+ const tracer = getTracer({ isEnabled: (_a10 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a10 : false });
1872
2030
  const retry = retryWithExponentialBackoff({ maxRetries });
1873
- const schema = inputSchema != null ? asSchema2(inputSchema) : void 0;
1874
2031
  return recordSpan({
1875
2032
  name: "ai.streamObject",
1876
2033
  attributes: selectTelemetryAttributes({
@@ -1885,10 +2042,10 @@ async function streamObject({
1885
2042
  "ai.prompt": {
1886
2043
  input: () => JSON.stringify({ system, prompt, messages })
1887
2044
  },
1888
- "ai.schema": schema != null ? { input: () => JSON.stringify(schema.jsonSchema) } : void 0,
2045
+ "ai.schema": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,
1889
2046
  "ai.schema.name": schemaName,
1890
2047
  "ai.schema.description": schemaDescription,
1891
- "ai.settings.output": output,
2048
+ "ai.settings.output": outputStrategy.type,
1892
2049
  "ai.settings.mode": mode
1893
2050
  }
1894
2051
  }),
@@ -1903,9 +2060,9 @@ async function streamObject({
1903
2060
  switch (mode) {
1904
2061
  case "json": {
1905
2062
  const validatedPrompt = validatePrompt({
1906
- system: schema == null ? injectJsonInstruction({ prompt: system }) : model.supportsStructuredOutputs && schema != null ? system : injectJsonInstruction({
2063
+ system: outputStrategy.jsonSchema == null ? injectJsonInstruction({ prompt: system }) : model.supportsStructuredOutputs ? system : injectJsonInstruction({
1907
2064
  prompt: system,
1908
- schema: schema.jsonSchema
2065
+ schema: outputStrategy.jsonSchema
1909
2066
  }),
1910
2067
  prompt,
1911
2068
  messages
@@ -1913,7 +2070,7 @@ async function streamObject({
1913
2070
  callOptions = {
1914
2071
  mode: {
1915
2072
  type: "object-json",
1916
- schema: schema == null ? void 0 : schema.jsonSchema,
2073
+ schema: outputStrategy.jsonSchema,
1917
2074
  name: schemaName,
1918
2075
  description: schemaDescription
1919
2076
  },
@@ -1954,7 +2111,7 @@ async function streamObject({
1954
2111
  type: "function",
1955
2112
  name: schemaName != null ? schemaName : "json",
1956
2113
  description: schemaDescription != null ? schemaDescription : "Respond with a JSON object.",
1957
- parameters: schema.jsonSchema
2114
+ parameters: outputStrategy.jsonSchema
1958
2115
  }
1959
2116
  },
1960
2117
  ...prepareCallSettings(settings),
@@ -2032,12 +2189,10 @@ async function streamObject({
2032
2189
  })
2033
2190
  );
2034
2191
  return new DefaultStreamObjectResult({
2192
+ outputStrategy,
2035
2193
  stream: stream.pipeThrough(new TransformStream(transformer)),
2036
2194
  warnings,
2037
2195
  rawResponse,
2038
- // type casting required for `undefined` schema (no-schema mode),
2039
- // in which case <T> is <JSONValue> as desired.
2040
- schema,
2041
2196
  onFinish,
2042
2197
  rootSpan,
2043
2198
  doStreamSpan,
@@ -2052,7 +2207,7 @@ var DefaultStreamObjectResult = class {
2052
2207
  stream,
2053
2208
  warnings,
2054
2209
  rawResponse,
2055
- schema,
2210
+ outputStrategy,
2056
2211
  onFinish,
2057
2212
  rootSpan,
2058
2213
  doStreamSpan,
@@ -2061,6 +2216,7 @@ var DefaultStreamObjectResult = class {
2061
2216
  }) {
2062
2217
  this.warnings = warnings;
2063
2218
  this.rawResponse = rawResponse;
2219
+ this.outputStrategy = outputStrategy;
2064
2220
  this.objectPromise = new DelayedPromise();
2065
2221
  const { resolve: resolveUsage, promise: usagePromise } = createResolvablePromise();
2066
2222
  this.usage = usagePromise;
@@ -2076,6 +2232,7 @@ var DefaultStreamObjectResult = class {
2076
2232
  let error;
2077
2233
  let accumulatedText = "";
2078
2234
  let delta = "";
2235
+ let latestObjectJson = void 0;
2079
2236
  let latestObject = void 0;
2080
2237
  let firstChunk = true;
2081
2238
  const self = this;
@@ -2095,20 +2252,25 @@ var DefaultStreamObjectResult = class {
2095
2252
  if (typeof chunk === "string") {
2096
2253
  accumulatedText += chunk;
2097
2254
  delta += chunk;
2098
- const currentObject = parsePartialJson(
2099
- accumulatedText
2100
- );
2101
- if (!isDeepEqualData(latestObject, currentObject)) {
2102
- latestObject = currentObject;
2103
- controller.enqueue({
2104
- type: "object",
2105
- object: currentObject
2255
+ const { value: currentObjectJson, state: parseState } = parsePartialJson(accumulatedText);
2256
+ if (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {
2257
+ const validationResult = outputStrategy.validatePartialResult({
2258
+ value: currentObjectJson,
2259
+ parseState
2106
2260
  });
2107
- controller.enqueue({
2108
- type: "text-delta",
2109
- textDelta: delta
2110
- });
2111
- delta = "";
2261
+ if (validationResult.success && !isDeepEqualData(latestObject, validationResult.value)) {
2262
+ latestObjectJson = currentObjectJson;
2263
+ latestObject = validationResult.value;
2264
+ controller.enqueue({
2265
+ type: "object",
2266
+ object: latestObject
2267
+ });
2268
+ controller.enqueue({
2269
+ type: "text-delta",
2270
+ textDelta: delta
2271
+ });
2272
+ delta = "";
2273
+ }
2112
2274
  }
2113
2275
  return;
2114
2276
  }
@@ -2126,10 +2288,7 @@ var DefaultStreamObjectResult = class {
2126
2288
  controller.enqueue({ ...chunk, usage });
2127
2289
  resolveUsage(usage);
2128
2290
  resolveProviderMetadata(providerMetadata);
2129
- const validationResult = safeValidateTypes2({
2130
- value: latestObject,
2131
- schema
2132
- });
2291
+ const validationResult = outputStrategy.validateFinalResult(latestObjectJson);
2133
2292
  if (validationResult.success) {
2134
2293
  object = validationResult.value;
2135
2294
  self.objectPromise.resolve(object);
@@ -2224,6 +2383,9 @@ var DefaultStreamObjectResult = class {
2224
2383
  }
2225
2384
  });
2226
2385
  }
2386
+ get elementStream() {
2387
+ return this.outputStrategy.createElementStream(this.originalStream);
2388
+ }
2227
2389
  get textStream() {
2228
2390
  return createAsyncIterableStream(this.originalStream, {
2229
2391
  transform(chunk, controller) {
@@ -2253,8 +2415,8 @@ var DefaultStreamObjectResult = class {
2253
2415
  });
2254
2416
  }
2255
2417
  pipeTextStreamToResponse(response, init) {
2256
- var _a12;
2257
- response.writeHead((_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200, {
2418
+ var _a10;
2419
+ response.writeHead((_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200, {
2258
2420
  "Content-Type": "text/plain; charset=utf-8",
2259
2421
  ...init == null ? void 0 : init.headers
2260
2422
  });
@@ -2276,9 +2438,9 @@ var DefaultStreamObjectResult = class {
2276
2438
  read();
2277
2439
  }
2278
2440
  toTextStreamResponse(init) {
2279
- var _a12;
2441
+ var _a10;
2280
2442
  return new Response(this.textStream.pipeThrough(new TextEncoderStream()), {
2281
- status: (_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200,
2443
+ status: (_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200,
2282
2444
  headers: prepareResponseHeaders(init, {
2283
2445
  contentType: "text/plain; charset=utf-8"
2284
2446
  })
@@ -2288,7 +2450,7 @@ var DefaultStreamObjectResult = class {
2288
2450
  var experimental_streamObject = streamObject;
2289
2451
 
2290
2452
  // core/prompt/prepare-tools-and-tool-choice.ts
2291
- import { asSchema as asSchema3 } from "@ai-sdk/ui-utils";
2453
+ import { asSchema as asSchema2 } from "@ai-sdk/ui-utils";
2292
2454
 
2293
2455
  // core/util/is-non-empty-object.ts
2294
2456
  function isNonEmptyObject(object) {
@@ -2307,11 +2469,11 @@ function prepareToolsAndToolChoice({
2307
2469
  };
2308
2470
  }
2309
2471
  return {
2310
- tools: Object.entries(tools).map(([name12, tool2]) => ({
2472
+ tools: Object.entries(tools).map(([name10, tool2]) => ({
2311
2473
  type: "function",
2312
- name: name12,
2474
+ name: name10,
2313
2475
  description: tool2.description,
2314
- parameters: asSchema3(tool2.parameters).jsonSchema
2476
+ parameters: asSchema2(tool2.parameters).jsonSchema
2315
2477
  })),
2316
2478
  toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
2317
2479
  };
@@ -2319,7 +2481,7 @@ function prepareToolsAndToolChoice({
2319
2481
 
2320
2482
  // core/generate-text/tool-call.ts
2321
2483
  import { safeParseJSON as safeParseJSON2 } from "@ai-sdk/provider-utils";
2322
- import { asSchema as asSchema4 } from "@ai-sdk/ui-utils";
2484
+ import { asSchema as asSchema3 } from "@ai-sdk/ui-utils";
2323
2485
 
2324
2486
  // errors/invalid-tool-arguments-error.ts
2325
2487
  import { AISDKError as AISDKError7, getErrorMessage as getErrorMessage3 } from "@ai-sdk/provider";
@@ -2425,7 +2587,7 @@ function parseToolCall({
2425
2587
  }
2426
2588
  const parseResult = safeParseJSON2({
2427
2589
  text: toolCall.args,
2428
- schema: asSchema4(tool2.parameters)
2590
+ schema: asSchema3(tool2.parameters)
2429
2591
  });
2430
2592
  if (parseResult.success === false) {
2431
2593
  throw new InvalidToolArgumentsError({
@@ -2458,14 +2620,14 @@ async function generateText({
2458
2620
  experimental_telemetry: telemetry,
2459
2621
  ...settings
2460
2622
  }) {
2461
- var _a12;
2623
+ var _a10;
2462
2624
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
2463
2625
  model,
2464
2626
  telemetry,
2465
2627
  headers,
2466
2628
  settings: { ...settings, maxRetries }
2467
2629
  });
2468
- const tracer = getTracer({ isEnabled: (_a12 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a12 : false });
2630
+ const tracer = getTracer({ isEnabled: (_a10 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a10 : false });
2469
2631
  return recordSpan({
2470
2632
  name: "ai.generateText",
2471
2633
  attributes: selectTelemetryAttributes({
@@ -2485,7 +2647,7 @@ async function generateText({
2485
2647
  }),
2486
2648
  tracer,
2487
2649
  fn: async (span) => {
2488
- var _a13, _b, _c, _d;
2650
+ var _a11, _b, _c, _d;
2489
2651
  const retry = retryWithExponentialBackoff({ maxRetries });
2490
2652
  const validatedPrompt = validatePrompt({
2491
2653
  system,
@@ -2571,7 +2733,7 @@ async function generateText({
2571
2733
  }
2572
2734
  })
2573
2735
  );
2574
- currentToolCalls = ((_a13 = currentModelResponse.toolCalls) != null ? _a13 : []).map(
2736
+ currentToolCalls = ((_a11 = currentModelResponse.toolCalls) != null ? _a11 : []).map(
2575
2737
  (modelToolCall) => parseToolCall({ toolCall: modelToolCall, tools })
2576
2738
  );
2577
2739
  currentToolResults = tools == null ? [] : await executeTools({
@@ -3039,14 +3201,14 @@ async function streamText({
3039
3201
  onFinish,
3040
3202
  ...settings
3041
3203
  }) {
3042
- var _a12;
3204
+ var _a10;
3043
3205
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
3044
3206
  model,
3045
3207
  telemetry,
3046
3208
  headers,
3047
3209
  settings: { ...settings, maxRetries }
3048
3210
  });
3049
- const tracer = getTracer({ isEnabled: (_a12 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a12 : false });
3211
+ const tracer = getTracer({ isEnabled: (_a10 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a10 : false });
3050
3212
  return recordSpan({
3051
3213
  name: "ai.streamText",
3052
3214
  attributes: selectTelemetryAttributes({
@@ -3423,8 +3585,8 @@ var DefaultStreamTextResult = class {
3423
3585
  return this.pipeDataStreamToResponse(response, init);
3424
3586
  }
3425
3587
  pipeDataStreamToResponse(response, init) {
3426
- var _a12;
3427
- response.writeHead((_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200, {
3588
+ var _a10;
3589
+ response.writeHead((_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200, {
3428
3590
  "Content-Type": "text/plain; charset=utf-8",
3429
3591
  ...init == null ? void 0 : init.headers
3430
3592
  });
@@ -3446,8 +3608,8 @@ var DefaultStreamTextResult = class {
3446
3608
  read();
3447
3609
  }
3448
3610
  pipeTextStreamToResponse(response, init) {
3449
- var _a12;
3450
- response.writeHead((_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200, {
3611
+ var _a10;
3612
+ response.writeHead((_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200, {
3451
3613
  "Content-Type": "text/plain; charset=utf-8",
3452
3614
  ...init == null ? void 0 : init.headers
3453
3615
  });
@@ -3472,7 +3634,7 @@ var DefaultStreamTextResult = class {
3472
3634
  return this.toDataStreamResponse(options);
3473
3635
  }
3474
3636
  toDataStreamResponse(options) {
3475
- var _a12;
3637
+ var _a10;
3476
3638
  const init = options == null ? void 0 : "init" in options ? options.init : {
3477
3639
  headers: "headers" in options ? options.headers : void 0,
3478
3640
  status: "status" in options ? options.status : void 0,
@@ -3482,7 +3644,7 @@ var DefaultStreamTextResult = class {
3482
3644
  const getErrorMessage4 = options == null ? void 0 : "getErrorMessage" in options ? options.getErrorMessage : void 0;
3483
3645
  const stream = data ? mergeStreams(data.stream, this.toDataStream({ getErrorMessage: getErrorMessage4 })) : this.toDataStream({ getErrorMessage: getErrorMessage4 });
3484
3646
  return new Response(stream, {
3485
- status: (_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200,
3647
+ status: (_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200,
3486
3648
  statusText: init == null ? void 0 : init.statusText,
3487
3649
  headers: prepareResponseHeaders(init, {
3488
3650
  contentType: "text/plain; charset=utf-8",
@@ -3491,9 +3653,9 @@ var DefaultStreamTextResult = class {
3491
3653
  });
3492
3654
  }
3493
3655
  toTextStreamResponse(init) {
3494
- var _a12;
3656
+ var _a10;
3495
3657
  return new Response(this.textStream.pipeThrough(new TextEncoderStream()), {
3496
- status: (_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200,
3658
+ status: (_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200,
3497
3659
  headers: prepareResponseHeaders(init, {
3498
3660
  contentType: "text/plain; charset=utf-8"
3499
3661
  })
@@ -3504,7 +3666,7 @@ var experimental_streamText = streamText;
3504
3666
 
3505
3667
  // core/prompt/attachments-to-parts.ts
3506
3668
  function attachmentsToParts(attachments) {
3507
- var _a12, _b, _c;
3669
+ var _a10, _b, _c;
3508
3670
  const parts = [];
3509
3671
  for (const attachment of attachments) {
3510
3672
  let url;
@@ -3516,7 +3678,7 @@ function attachmentsToParts(attachments) {
3516
3678
  switch (url.protocol) {
3517
3679
  case "http:":
3518
3680
  case "https:": {
3519
- if ((_a12 = attachment.contentType) == null ? void 0 : _a12.startsWith("image/")) {
3681
+ if ((_a10 = attachment.contentType) == null ? void 0 : _a10.startsWith("image/")) {
3520
3682
  parts.push({ type: "image", image: url });
3521
3683
  }
3522
3684
  break;
@@ -3624,110 +3786,62 @@ function convertToCoreMessages(messages) {
3624
3786
  return coreMessages;
3625
3787
  }
3626
3788
 
3627
- // core/registry/invalid-model-id-error.ts
3628
- import { AISDKError as AISDKError9 } from "@ai-sdk/provider";
3629
- var name9 = "AI_InvalidModelIdError";
3789
+ // core/registry/custom-provider.ts
3790
+ import { NoSuchModelError } from "@ai-sdk/provider";
3791
+ function experimental_customProvider({
3792
+ languageModels,
3793
+ textEmbeddingModels,
3794
+ fallbackProvider
3795
+ }) {
3796
+ return {
3797
+ languageModel(modelId) {
3798
+ if (languageModels != null && modelId in languageModels) {
3799
+ return languageModels[modelId];
3800
+ }
3801
+ if (fallbackProvider) {
3802
+ return fallbackProvider.languageModel(modelId);
3803
+ }
3804
+ throw new NoSuchModelError({ modelId, modelType: "languageModel" });
3805
+ },
3806
+ textEmbeddingModel(modelId) {
3807
+ if (textEmbeddingModels != null && modelId in textEmbeddingModels) {
3808
+ return textEmbeddingModels[modelId];
3809
+ }
3810
+ if (fallbackProvider) {
3811
+ return fallbackProvider.textEmbeddingModel(modelId);
3812
+ }
3813
+ throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
3814
+ }
3815
+ };
3816
+ }
3817
+
3818
+ // core/registry/no-such-provider-error.ts
3819
+ import { AISDKError as AISDKError9, NoSuchModelError as NoSuchModelError2 } from "@ai-sdk/provider";
3820
+ var name9 = "AI_NoSuchProviderError";
3630
3821
  var marker9 = `vercel.ai.error.${name9}`;
3631
3822
  var symbol9 = Symbol.for(marker9);
3632
3823
  var _a9;
3633
- var InvalidModelIdError = class extends AISDKError9 {
3634
- constructor({
3635
- id,
3636
- message = `Invalid model id: ${id}`
3637
- }) {
3638
- super({ name: name9, message });
3639
- this[_a9] = true;
3640
- this.id = id;
3641
- }
3642
- static isInstance(error) {
3643
- return AISDKError9.hasMarker(error, marker9);
3644
- }
3645
- /**
3646
- * @deprecated use `isInstance` instead
3647
- */
3648
- static isInvalidModelIdError(error) {
3649
- return error instanceof Error && error.name === name9 && typeof error.id === "string";
3650
- }
3651
- /**
3652
- * @deprecated Do not use this method. It will be removed in the next major version.
3653
- */
3654
- toJSON() {
3655
- return {
3656
- name: this.name,
3657
- message: this.message,
3658
- stack: this.stack,
3659
- id: this.id
3660
- };
3661
- }
3662
- };
3663
- _a9 = symbol9;
3664
-
3665
- // core/registry/no-such-model-error.ts
3666
- import { AISDKError as AISDKError10 } from "@ai-sdk/provider";
3667
- var name10 = "AI_NoSuchModelError";
3668
- var marker10 = `vercel.ai.error.${name10}`;
3669
- var symbol10 = Symbol.for(marker10);
3670
- var _a10;
3671
- var NoSuchModelError = class extends AISDKError10 {
3824
+ var NoSuchProviderError = class extends NoSuchModelError2 {
3672
3825
  constructor({
3673
3826
  modelId,
3674
3827
  modelType,
3675
- message = `No such ${modelType}: ${modelId}`
3676
- }) {
3677
- super({ name: name10, message });
3678
- this[_a10] = true;
3679
- this.modelId = modelId;
3680
- this.modelType = modelType;
3681
- }
3682
- static isInstance(error) {
3683
- return AISDKError10.hasMarker(error, marker10);
3684
- }
3685
- /**
3686
- * @deprecated use `isInstance` instead
3687
- */
3688
- static isNoSuchModelError(error) {
3689
- return error instanceof Error && error.name === name10 && typeof error.modelId === "string" && typeof error.modelType === "string";
3690
- }
3691
- /**
3692
- * @deprecated Do not use this method. It will be removed in the next major version.
3693
- */
3694
- toJSON() {
3695
- return {
3696
- name: this.name,
3697
- message: this.message,
3698
- stack: this.stack,
3699
- modelId: this.modelId,
3700
- modelType: this.modelType
3701
- };
3702
- }
3703
- };
3704
- _a10 = symbol10;
3705
-
3706
- // core/registry/no-such-provider-error.ts
3707
- import { AISDKError as AISDKError11 } from "@ai-sdk/provider";
3708
- var name11 = "AI_NoSuchProviderError";
3709
- var marker11 = `vercel.ai.error.${name11}`;
3710
- var symbol11 = Symbol.for(marker11);
3711
- var _a11;
3712
- var NoSuchProviderError = class extends AISDKError11 {
3713
- constructor({
3714
3828
  providerId,
3715
3829
  availableProviders,
3716
3830
  message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`
3717
3831
  }) {
3718
- super({ name: name11, message });
3719
- this[_a11] = true;
3832
+ super({ errorName: name9, modelId, modelType, message });
3833
+ this[_a9] = true;
3720
3834
  this.providerId = providerId;
3721
3835
  this.availableProviders = availableProviders;
3722
3836
  }
3723
3837
  static isInstance(error) {
3724
- return AISDKError11.hasMarker(error, marker11);
3838
+ return AISDKError9.hasMarker(error, marker9);
3725
3839
  }
3726
3840
  /**
3727
3841
  * @deprecated use `isInstance` instead
3728
3842
  */
3729
3843
  static isNoSuchProviderError(error) {
3730
- return error instanceof Error && error.name === name11 && typeof error.providerId === "string" && Array.isArray(error.availableProviders);
3844
+ return error instanceof Error && error.name === name9 && typeof error.providerId === "string" && Array.isArray(error.availableProviders);
3731
3845
  }
3732
3846
  /**
3733
3847
  * @deprecated Do not use this method. It will be removed in the next major version.
@@ -3737,14 +3851,17 @@ var NoSuchProviderError = class extends AISDKError11 {
3737
3851
  name: this.name,
3738
3852
  message: this.message,
3739
3853
  stack: this.stack,
3854
+ modelId: this.modelId,
3855
+ modelType: this.modelType,
3740
3856
  providerId: this.providerId,
3741
3857
  availableProviders: this.availableProviders
3742
3858
  };
3743
3859
  }
3744
3860
  };
3745
- _a11 = symbol11;
3861
+ _a9 = symbol9;
3746
3862
 
3747
3863
  // core/registry/provider-registry.ts
3864
+ import { NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
3748
3865
  function experimental_createProviderRegistry(providers) {
3749
3866
  const registry = new DefaultProviderRegistry();
3750
3867
  for (const [id, provider] of Object.entries(providers)) {
@@ -3767,35 +3884,41 @@ var DefaultProviderRegistry = class {
3767
3884
  const provider = this.providers[id];
3768
3885
  if (provider == null) {
3769
3886
  throw new NoSuchProviderError({
3887
+ modelId: id,
3888
+ modelType: "languageModel",
3770
3889
  providerId: id,
3771
3890
  availableProviders: Object.keys(this.providers)
3772
3891
  });
3773
3892
  }
3774
3893
  return provider;
3775
3894
  }
3776
- splitId(id) {
3895
+ splitId(id, modelType) {
3777
3896
  const index = id.indexOf(":");
3778
3897
  if (index === -1) {
3779
- throw new InvalidModelIdError({ id });
3898
+ throw new NoSuchModelError3({
3899
+ modelId: id,
3900
+ modelType,
3901
+ message: `Invalid ${modelType} id for registry: ${id} (must be in the format "providerId:modelId")`
3902
+ });
3780
3903
  }
3781
3904
  return [id.slice(0, index), id.slice(index + 1)];
3782
3905
  }
3783
3906
  languageModel(id) {
3784
- var _a12, _b;
3785
- const [providerId, modelId] = this.splitId(id);
3786
- const model = (_b = (_a12 = this.getProvider(providerId)).languageModel) == null ? void 0 : _b.call(_a12, modelId);
3907
+ var _a10, _b;
3908
+ const [providerId, modelId] = this.splitId(id, "languageModel");
3909
+ const model = (_b = (_a10 = this.getProvider(providerId)).languageModel) == null ? void 0 : _b.call(_a10, modelId);
3787
3910
  if (model == null) {
3788
- throw new NoSuchModelError({ modelId: id, modelType: "languageModel" });
3911
+ throw new NoSuchModelError3({ modelId: id, modelType: "languageModel" });
3789
3912
  }
3790
3913
  return model;
3791
3914
  }
3792
3915
  textEmbeddingModel(id) {
3793
- var _a12, _b, _c;
3794
- const [providerId, modelId] = this.splitId(id);
3916
+ var _a10, _b, _c;
3917
+ const [providerId, modelId] = this.splitId(id, "textEmbeddingModel");
3795
3918
  const provider = this.getProvider(providerId);
3796
- const model = (_c = (_a12 = provider.textEmbeddingModel) == null ? void 0 : _a12.call(provider, modelId)) != null ? _c : (_b = provider.textEmbedding) == null ? void 0 : _b.call(provider, modelId);
3919
+ const model = (_c = (_a10 = provider.textEmbeddingModel) == null ? void 0 : _a10.call(provider, modelId)) != null ? _c : "textEmbedding" in provider ? (_b = provider.textEmbedding) == null ? void 0 : _b.call(provider, modelId) : void 0;
3797
3920
  if (model == null) {
3798
- throw new NoSuchModelError({
3921
+ throw new NoSuchModelError3({
3799
3922
  modelId: id,
3800
3923
  modelType: "textEmbeddingModel"
3801
3924
  });
@@ -3836,15 +3959,17 @@ function magnitude(vector) {
3836
3959
 
3837
3960
  // errors/index.ts
3838
3961
  import {
3839
- AISDKError as AISDKError12,
3962
+ AISDKError as AISDKError10,
3840
3963
  APICallError as APICallError2,
3841
3964
  EmptyResponseBodyError,
3842
3965
  InvalidPromptError as InvalidPromptError2,
3843
3966
  InvalidResponseDataError,
3844
3967
  JSONParseError,
3845
3968
  LoadAPIKeyError,
3846
- TypeValidationError,
3847
- UnsupportedFunctionalityError
3969
+ NoContentGeneratedError,
3970
+ NoSuchModelError as NoSuchModelError4,
3971
+ TypeValidationError as TypeValidationError2,
3972
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError2
3848
3973
  } from "@ai-sdk/provider";
3849
3974
 
3850
3975
  // streams/ai-stream.ts
@@ -3965,8 +4090,8 @@ function readableFromAsyncIterable(iterable) {
3965
4090
  controller.enqueue(value);
3966
4091
  },
3967
4092
  async cancel(reason) {
3968
- var _a12;
3969
- await ((_a12 = it.return) == null ? void 0 : _a12.call(it, reason));
4093
+ var _a10;
4094
+ await ((_a10 = it.return) == null ? void 0 : _a10.call(it, reason));
3970
4095
  }
3971
4096
  });
3972
4097
  }
@@ -4105,7 +4230,7 @@ import {
4105
4230
  function AssistantResponse({ threadId, messageId }, process2) {
4106
4231
  const stream = new ReadableStream({
4107
4232
  async start(controller) {
4108
- var _a12;
4233
+ var _a10;
4109
4234
  const textEncoder = new TextEncoder();
4110
4235
  const sendMessage = (message) => {
4111
4236
  controller.enqueue(
@@ -4123,7 +4248,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4123
4248
  );
4124
4249
  };
4125
4250
  const forwardStream = async (stream2) => {
4126
- var _a13, _b;
4251
+ var _a11, _b;
4127
4252
  let result = void 0;
4128
4253
  for await (const value of stream2) {
4129
4254
  switch (value.event) {
@@ -4140,7 +4265,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4140
4265
  break;
4141
4266
  }
4142
4267
  case "thread.message.delta": {
4143
- const content = (_a13 = value.data.delta.content) == null ? void 0 : _a13[0];
4268
+ const content = (_a11 = value.data.delta.content) == null ? void 0 : _a11[0];
4144
4269
  if ((content == null ? void 0 : content.type) === "text" && ((_b = content.text) == null ? void 0 : _b.value) != null) {
4145
4270
  controller.enqueue(
4146
4271
  textEncoder.encode(
@@ -4176,7 +4301,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4176
4301
  forwardStream
4177
4302
  });
4178
4303
  } catch (error) {
4179
- sendError((_a12 = error.message) != null ? _a12 : `${error}`);
4304
+ sendError((_a10 = error.message) != null ? _a10 : `${error}`);
4180
4305
  } finally {
4181
4306
  controller.close();
4182
4307
  }
@@ -4197,9 +4322,9 @@ var experimental_AssistantResponse = AssistantResponse;
4197
4322
 
4198
4323
  // streams/aws-bedrock-stream.ts
4199
4324
  async function* asDeltaIterable(response, extractTextDeltaFromChunk) {
4200
- var _a12, _b;
4325
+ var _a10, _b;
4201
4326
  const decoder = new TextDecoder();
4202
- for await (const chunk of (_a12 = response.body) != null ? _a12 : []) {
4327
+ for await (const chunk of (_a10 = response.body) != null ? _a10 : []) {
4203
4328
  const bytes = (_b = chunk.chunk) == null ? void 0 : _b.bytes;
4204
4329
  if (bytes != null) {
4205
4330
  const chunkText = decoder.decode(bytes);
@@ -4213,8 +4338,8 @@ async function* asDeltaIterable(response, extractTextDeltaFromChunk) {
4213
4338
  }
4214
4339
  function AWSBedrockAnthropicMessagesStream(response, callbacks) {
4215
4340
  return AWSBedrockStream(response, callbacks, (chunk) => {
4216
- var _a12;
4217
- return (_a12 = chunk.delta) == null ? void 0 : _a12.text;
4341
+ var _a10;
4342
+ return (_a10 = chunk.delta) == null ? void 0 : _a10.text;
4218
4343
  });
4219
4344
  }
4220
4345
  function AWSBedrockAnthropicStream(response, callbacks) {
@@ -4261,8 +4386,8 @@ async function readAndProcessLines(reader, controller) {
4261
4386
  controller.close();
4262
4387
  }
4263
4388
  function createParser2(res) {
4264
- var _a12;
4265
- const reader = (_a12 = res.body) == null ? void 0 : _a12.getReader();
4389
+ var _a10;
4390
+ const reader = (_a10 = res.body) == null ? void 0 : _a10.getReader();
4266
4391
  return new ReadableStream({
4267
4392
  async start(controller) {
4268
4393
  if (!reader) {
@@ -4292,9 +4417,9 @@ function CohereStream(reader, callbacks) {
4292
4417
 
4293
4418
  // streams/google-generative-ai-stream.ts
4294
4419
  async function* streamable3(response) {
4295
- var _a12, _b, _c;
4420
+ var _a10, _b, _c;
4296
4421
  for await (const chunk of response.stream) {
4297
- const parts = (_c = (_b = (_a12 = chunk.candidates) == null ? void 0 : _a12[0]) == null ? void 0 : _b.content) == null ? void 0 : _c.parts;
4422
+ const parts = (_c = (_b = (_a10 = chunk.candidates) == null ? void 0 : _a10[0]) == null ? void 0 : _b.content) == null ? void 0 : _c.parts;
4298
4423
  if (parts === void 0) {
4299
4424
  continue;
4300
4425
  }
@@ -4313,13 +4438,13 @@ function createParser3(res) {
4313
4438
  const trimStartOfStream = trimStartOfStreamHelper();
4314
4439
  return new ReadableStream({
4315
4440
  async pull(controller) {
4316
- var _a12, _b;
4441
+ var _a10, _b;
4317
4442
  const { value, done } = await res.next();
4318
4443
  if (done) {
4319
4444
  controller.close();
4320
4445
  return;
4321
4446
  }
4322
- const text = trimStartOfStream((_b = (_a12 = value.token) == null ? void 0 : _a12.text) != null ? _b : "");
4447
+ const text = trimStartOfStream((_b = (_a10 = value.token) == null ? void 0 : _a10.text) != null ? _b : "");
4323
4448
  if (!text)
4324
4449
  return;
4325
4450
  if (value.generated_text != null && value.generated_text.length > 0) {
@@ -4344,11 +4469,11 @@ function InkeepStream(res, callbacks) {
4344
4469
  let chat_session_id = "";
4345
4470
  let records_cited;
4346
4471
  const inkeepEventParser = (data, options) => {
4347
- var _a12, _b;
4472
+ var _a10, _b;
4348
4473
  const { event } = options;
4349
4474
  if (event === "records_cited") {
4350
4475
  records_cited = JSON.parse(data);
4351
- (_a12 = callbacks == null ? void 0 : callbacks.onRecordsCited) == null ? void 0 : _a12.call(callbacks, records_cited);
4476
+ (_a10 = callbacks == null ? void 0 : callbacks.onRecordsCited) == null ? void 0 : _a10.call(callbacks, records_cited);
4352
4477
  }
4353
4478
  if (event === "message_chunk") {
4354
4479
  const inkeepMessageChunk = JSON.parse(data);
@@ -4361,12 +4486,12 @@ function InkeepStream(res, callbacks) {
4361
4486
  passThroughCallbacks = {
4362
4487
  ...passThroughCallbacks,
4363
4488
  onFinal: (completion) => {
4364
- var _a12;
4489
+ var _a10;
4365
4490
  const inkeepOnFinalMetadata = {
4366
4491
  chat_session_id,
4367
4492
  records_cited
4368
4493
  };
4369
- (_a12 = callbacks == null ? void 0 : callbacks.onFinal) == null ? void 0 : _a12.call(callbacks, completion, inkeepOnFinalMetadata);
4494
+ (_a10 = callbacks == null ? void 0 : callbacks.onFinal) == null ? void 0 : _a10.call(callbacks, completion, inkeepOnFinalMetadata);
4370
4495
  }
4371
4496
  };
4372
4497
  return AIStream(res, inkeepEventParser, passThroughCallbacks).pipeThrough(
@@ -4388,7 +4513,7 @@ function toDataStream(stream, callbacks) {
4388
4513
  return stream.pipeThrough(
4389
4514
  new TransformStream({
4390
4515
  transform: async (value, controller) => {
4391
- var _a12;
4516
+ var _a10;
4392
4517
  if (typeof value === "string") {
4393
4518
  controller.enqueue(value);
4394
4519
  return;
@@ -4396,7 +4521,7 @@ function toDataStream(stream, callbacks) {
4396
4521
  if ("event" in value) {
4397
4522
  if (value.event === "on_chat_model_stream") {
4398
4523
  forwardAIMessageChunk(
4399
- (_a12 = value.data) == null ? void 0 : _a12.chunk,
4524
+ (_a10 = value.data) == null ? void 0 : _a10.chunk,
4400
4525
  controller
4401
4526
  );
4402
4527
  }
@@ -4408,13 +4533,13 @@ function toDataStream(stream, callbacks) {
4408
4533
  ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
4409
4534
  }
4410
4535
  function toDataStreamResponse(stream, options) {
4411
- var _a12;
4536
+ var _a10;
4412
4537
  const dataStream = toDataStream(stream, options == null ? void 0 : options.callbacks);
4413
4538
  const data = options == null ? void 0 : options.data;
4414
4539
  const init = options == null ? void 0 : options.init;
4415
4540
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
4416
4541
  return new Response(responseStream, {
4417
- status: (_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200,
4542
+ status: (_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200,
4418
4543
  statusText: init == null ? void 0 : init.statusText,
4419
4544
  headers: prepareResponseHeaders(init, {
4420
4545
  contentType: "text/plain; charset=utf-8",
@@ -4496,9 +4621,9 @@ function LangChainStream(callbacks) {
4496
4621
 
4497
4622
  // streams/mistral-stream.ts
4498
4623
  async function* streamable4(stream) {
4499
- var _a12, _b;
4624
+ var _a10, _b;
4500
4625
  for await (const chunk of stream) {
4501
- const content = (_b = (_a12 = chunk.choices[0]) == null ? void 0 : _a12.delta) == null ? void 0 : _b.content;
4626
+ const content = (_b = (_a10 = chunk.choices[0]) == null ? void 0 : _a10.delta) == null ? void 0 : _b.content;
4502
4627
  if (content === void 0 || content === "") {
4503
4628
  continue;
4504
4629
  }
@@ -4531,10 +4656,10 @@ async function* streamable5(stream) {
4531
4656
  model: chunk.model,
4532
4657
  // not exposed by Azure API
4533
4658
  choices: chunk.choices.map((choice) => {
4534
- var _a12, _b, _c, _d, _e, _f, _g;
4659
+ var _a10, _b, _c, _d, _e, _f, _g;
4535
4660
  return {
4536
4661
  delta: {
4537
- content: (_a12 = choice.delta) == null ? void 0 : _a12.content,
4662
+ content: (_a10 = choice.delta) == null ? void 0 : _a10.content,
4538
4663
  function_call: (_b = choice.delta) == null ? void 0 : _b.functionCall,
4539
4664
  role: (_c = choice.delta) == null ? void 0 : _c.role,
4540
4665
  tool_calls: ((_e = (_d = choice.delta) == null ? void 0 : _d.toolCalls) == null ? void 0 : _e.length) ? (_g = (_f = choice.delta) == null ? void 0 : _f.toolCalls) == null ? void 0 : _g.map((toolCall, index) => ({
@@ -4559,9 +4684,9 @@ function chunkToText() {
4559
4684
  const trimStartOfStream = trimStartOfStreamHelper();
4560
4685
  let isFunctionStreamingIn;
4561
4686
  return (json) => {
4562
- var _a12, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
4687
+ var _a10, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
4563
4688
  if (isChatCompletionChunk(json)) {
4564
- const delta = (_a12 = json.choices[0]) == null ? void 0 : _a12.delta;
4689
+ const delta = (_a10 = json.choices[0]) == null ? void 0 : _a10.delta;
4565
4690
  if ((_b = delta.function_call) == null ? void 0 : _b.name) {
4566
4691
  isFunctionStreamingIn = true;
4567
4692
  return {
@@ -4834,8 +4959,8 @@ function createFunctionCallTransformer(callbacks) {
4834
4959
 
4835
4960
  // streams/replicate-stream.ts
4836
4961
  async function ReplicateStream(res, cb, options) {
4837
- var _a12;
4838
- const url = (_a12 = res.urls) == null ? void 0 : _a12.stream;
4962
+ var _a10;
4963
+ const url = (_a10 = res.urls) == null ? void 0 : _a10.stream;
4839
4964
  if (!url) {
4840
4965
  if (res.error)
4841
4966
  throw new Error(res.error);
@@ -4856,8 +4981,8 @@ async function ReplicateStream(res, cb, options) {
4856
4981
 
4857
4982
  // streams/stream-to-response.ts
4858
4983
  function streamToResponse(res, response, init, data) {
4859
- var _a12;
4860
- response.writeHead((_a12 = init == null ? void 0 : init.status) != null ? _a12 : 200, {
4984
+ var _a10;
4985
+ response.writeHead((_a10 = init == null ? void 0 : init.status) != null ? _a10 : 200, {
4861
4986
  "Content-Type": "text/plain; charset=utf-8",
4862
4987
  ...init == null ? void 0 : init.headers
4863
4988
  });
@@ -4900,7 +5025,7 @@ var StreamingTextResponse = class extends Response {
4900
5025
  var generateId2 = generateIdImpl;
4901
5026
  var nanoid = generateIdImpl;
4902
5027
  export {
4903
- AISDKError12 as AISDKError,
5028
+ AISDKError10 as AISDKError,
4904
5029
  AIStream,
4905
5030
  APICallError2 as APICallError,
4906
5031
  AWSBedrockAnthropicMessagesStream,
@@ -4919,7 +5044,6 @@ export {
4919
5044
  InvalidArgumentError,
4920
5045
  InvalidDataContentError,
4921
5046
  InvalidMessageRoleError,
4922
- InvalidModelIdError,
4923
5047
  InvalidPromptError2 as InvalidPromptError,
4924
5048
  InvalidResponseDataError,
4925
5049
  InvalidToolArgumentsError,
@@ -4928,8 +5052,9 @@ export {
4928
5052
  LangChainStream,
4929
5053
  LoadAPIKeyError,
4930
5054
  MistralStream,
5055
+ NoContentGeneratedError,
4931
5056
  NoObjectGeneratedError,
4932
- NoSuchModelError,
5057
+ NoSuchModelError4 as NoSuchModelError,
4933
5058
  NoSuchProviderError,
4934
5059
  NoSuchToolError,
4935
5060
  OpenAIStream,
@@ -4937,8 +5062,8 @@ export {
4937
5062
  RetryError,
4938
5063
  StreamData2 as StreamData,
4939
5064
  StreamingTextResponse,
4940
- TypeValidationError,
4941
- UnsupportedFunctionalityError,
5065
+ TypeValidationError2 as TypeValidationError,
5066
+ UnsupportedFunctionalityError2 as UnsupportedFunctionalityError,
4942
5067
  convertToCoreMessages,
4943
5068
  cosineSimilarity,
4944
5069
  createCallbacksTransformer,
@@ -4950,6 +5075,7 @@ export {
4950
5075
  experimental_StreamData,
4951
5076
  experimental_createModelRegistry,
4952
5077
  experimental_createProviderRegistry,
5078
+ experimental_customProvider,
4953
5079
  experimental_generateObject,
4954
5080
  experimental_generateText,
4955
5081
  experimental_streamObject,