ai 3.3.29 → 3.3.31

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # ai
2
2
 
3
+ ## 3.3.31
4
+
5
+ ### Patch Changes
6
+
7
+ - 561fd7e: feat (ai/core): add output: enum to generateObject
8
+
9
+ ## 3.3.30
10
+
11
+ ### Patch Changes
12
+
13
+ - 6ee1f8e: feat (ai/core): add toDataStream to streamText result
14
+
3
15
  ## 3.3.29
4
16
 
5
17
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -770,6 +770,50 @@ Optional telemetry configuration (experimental).
770
770
  };
771
771
  }): Promise<GenerateObjectResult<Array<ELEMENT>>>;
772
772
  /**
773
+ Generate a value from an enum (limited list of string values) using a language model.
774
+
775
+ This function does not stream the output.
776
+
777
+ @return
778
+ A result object that contains the generated value, the finish reason, the token usage, and additional information.
779
+ */
780
+ declare function generateObject<ENUM extends string>(options: Omit<CallSettings, 'stopSequences'> & Prompt & {
781
+ output: 'enum';
782
+ /**
783
+ The language model to use.
784
+ */
785
+ model: LanguageModel;
786
+ /**
787
+ The enum values that the model should use.
788
+ */
789
+ enum: Array<ENUM>;
790
+ /**
791
+ The mode to use for object generation.
792
+
793
+ The schema is converted in a JSON schema and used in one of the following ways
794
+
795
+ - 'auto': The provider will choose the best mode for the model.
796
+ - 'tool': A tool with the JSON schema as parameters is is provided and the provider is instructed to use it.
797
+ - 'json': The JSON schema and an instruction is injected into the prompt. If the provider supports JSON mode, it is enabled. If the provider supports JSON grammars, the grammar is used.
798
+
799
+ Please note that most providers do not support all modes.
800
+
801
+ Default and recommended: 'auto' (best mode for the model).
802
+ */
803
+ mode?: 'auto' | 'json' | 'tool';
804
+ /**
805
+ Optional telemetry configuration (experimental).
806
+ */
807
+ experimental_telemetry?: TelemetrySettings;
808
+ /**
809
+ * Internal. For test use only. May change without notice.
810
+ */
811
+ _internal?: {
812
+ generateId?: () => string;
813
+ currentDate?: () => Date;
814
+ };
815
+ }): Promise<GenerateObjectResult<ENUM>>;
816
+ /**
773
817
  Generate JSON with any schema for a given prompt using a language model.
774
818
 
775
819
  This function does not stream the output. If you want to stream the output, use `streamObject` instead.
@@ -1519,10 +1563,22 @@ interface StreamTextResult<TOOLS extends Record<string, CoreTool>> {
1519
1563
 
1520
1564
  @returns A data stream.
1521
1565
 
1522
- @deprecated Use `toDataStreamResponse` instead.
1566
+ @deprecated Use `toDataStream` instead.
1523
1567
  */
1524
1568
  toAIStream(callbacks?: AIStreamCallbacksAndOptions): ReadableStream<Uint8Array>;
1525
1569
  /**
1570
+ Converts the result to a data stream.
1571
+
1572
+ @param data an optional StreamData object that will be merged into the stream.
1573
+ @param getErrorMessage an optional function that converts an error to an error message.
1574
+
1575
+ @return A data stream.
1576
+ */
1577
+ toDataStream(options?: {
1578
+ data?: StreamData;
1579
+ getErrorMessage?: (error: unknown) => string;
1580
+ }): ReadableStream<Uint8Array>;
1581
+ /**
1526
1582
  Writes stream data output to a Node.js response-like object.
1527
1583
  It sets a `Content-Type` header to `text/plain; charset=utf-8` and
1528
1584
  writes each stream data part as a separate chunk.
package/dist/index.d.ts CHANGED
@@ -770,6 +770,50 @@ Optional telemetry configuration (experimental).
770
770
  };
771
771
  }): Promise<GenerateObjectResult<Array<ELEMENT>>>;
772
772
  /**
773
+ Generate a value from an enum (limited list of string values) using a language model.
774
+
775
+ This function does not stream the output.
776
+
777
+ @return
778
+ A result object that contains the generated value, the finish reason, the token usage, and additional information.
779
+ */
780
+ declare function generateObject<ENUM extends string>(options: Omit<CallSettings, 'stopSequences'> & Prompt & {
781
+ output: 'enum';
782
+ /**
783
+ The language model to use.
784
+ */
785
+ model: LanguageModel;
786
+ /**
787
+ The enum values that the model should use.
788
+ */
789
+ enum: Array<ENUM>;
790
+ /**
791
+ The mode to use for object generation.
792
+
793
+ The schema is converted in a JSON schema and used in one of the following ways
794
+
795
+ - 'auto': The provider will choose the best mode for the model.
796
+ - 'tool': A tool with the JSON schema as parameters is is provided and the provider is instructed to use it.
797
+ - 'json': The JSON schema and an instruction is injected into the prompt. If the provider supports JSON mode, it is enabled. If the provider supports JSON grammars, the grammar is used.
798
+
799
+ Please note that most providers do not support all modes.
800
+
801
+ Default and recommended: 'auto' (best mode for the model).
802
+ */
803
+ mode?: 'auto' | 'json' | 'tool';
804
+ /**
805
+ Optional telemetry configuration (experimental).
806
+ */
807
+ experimental_telemetry?: TelemetrySettings;
808
+ /**
809
+ * Internal. For test use only. May change without notice.
810
+ */
811
+ _internal?: {
812
+ generateId?: () => string;
813
+ currentDate?: () => Date;
814
+ };
815
+ }): Promise<GenerateObjectResult<ENUM>>;
816
+ /**
773
817
  Generate JSON with any schema for a given prompt using a language model.
774
818
 
775
819
  This function does not stream the output. If you want to stream the output, use `streamObject` instead.
@@ -1519,10 +1563,22 @@ interface StreamTextResult<TOOLS extends Record<string, CoreTool>> {
1519
1563
 
1520
1564
  @returns A data stream.
1521
1565
 
1522
- @deprecated Use `toDataStreamResponse` instead.
1566
+ @deprecated Use `toDataStream` instead.
1523
1567
  */
1524
1568
  toAIStream(callbacks?: AIStreamCallbacksAndOptions): ReadableStream<Uint8Array>;
1525
1569
  /**
1570
+ Converts the result to a data stream.
1571
+
1572
+ @param data an optional StreamData object that will be merged into the stream.
1573
+ @param getErrorMessage an optional function that converts an error to an error message.
1574
+
1575
+ @return A data stream.
1576
+ */
1577
+ toDataStream(options?: {
1578
+ data?: StreamData;
1579
+ getErrorMessage?: (error: unknown) => string;
1580
+ }): ReadableStream<Uint8Array>;
1581
+ /**
1526
1582
  Writes stream data output to a Node.js response-like object.
1527
1583
  It sets a `Content-Type` header to `text/plain; charset=utf-8` and
1528
1584
  writes each stream data part as a separate chunk.
package/dist/index.js CHANGED
@@ -1537,7 +1537,7 @@ var objectOutputStrategy = (schema) => ({
1537
1537
  var arrayOutputStrategy = (schema) => {
1538
1538
  const { $schema, ...itemSchema } = schema.jsonSchema;
1539
1539
  return {
1540
- type: "array",
1540
+ type: "enum",
1541
1541
  // wrap in object that contains array of elements, since most LLMs will not
1542
1542
  // be able to generate an array directly:
1543
1543
  // possible future optimization: use arrays directly when model supports grammar-guided generation
@@ -1641,15 +1641,64 @@ var arrayOutputStrategy = (schema) => {
1641
1641
  }
1642
1642
  };
1643
1643
  };
1644
+ var enumOutputStrategy = (enumValues) => {
1645
+ return {
1646
+ type: "enum",
1647
+ // wrap in object that contains result, since most LLMs will not
1648
+ // be able to generate an enum value directly:
1649
+ // possible future optimization: use enums directly when model supports top-level enums
1650
+ jsonSchema: {
1651
+ $schema: "http://json-schema.org/draft-07/schema#",
1652
+ type: "object",
1653
+ properties: {
1654
+ result: { type: "string", enum: enumValues }
1655
+ },
1656
+ required: ["result"],
1657
+ additionalProperties: false
1658
+ },
1659
+ validateFinalResult(value) {
1660
+ if (!(0, import_provider9.isJSONObject)(value) || typeof value.result !== "string") {
1661
+ return {
1662
+ success: false,
1663
+ error: new import_provider9.TypeValidationError({
1664
+ value,
1665
+ cause: 'value must be an object that contains a string in the "result" property.'
1666
+ })
1667
+ };
1668
+ }
1669
+ const result = value.result;
1670
+ return enumValues.includes(result) ? { success: true, value: result } : {
1671
+ success: false,
1672
+ error: new import_provider9.TypeValidationError({
1673
+ value,
1674
+ cause: "value must be a string in the enum"
1675
+ })
1676
+ };
1677
+ },
1678
+ validatePartialResult() {
1679
+ throw new import_provider9.UnsupportedFunctionalityError({
1680
+ functionality: "partial results in enum mode"
1681
+ });
1682
+ },
1683
+ createElementStream() {
1684
+ throw new import_provider9.UnsupportedFunctionalityError({
1685
+ functionality: "element streams in enum mode"
1686
+ });
1687
+ }
1688
+ };
1689
+ };
1644
1690
  function getOutputStrategy({
1645
1691
  output,
1646
- schema
1692
+ schema,
1693
+ enumValues
1647
1694
  }) {
1648
1695
  switch (output) {
1649
1696
  case "object":
1650
1697
  return objectOutputStrategy((0, import_ui_utils.asSchema)(schema));
1651
1698
  case "array":
1652
1699
  return arrayOutputStrategy((0, import_ui_utils.asSchema)(schema));
1700
+ case "enum":
1701
+ return enumOutputStrategy(enumValues);
1653
1702
  case "no-schema":
1654
1703
  return noSchemaOutputStrategy;
1655
1704
  default: {
@@ -1665,9 +1714,10 @@ function validateObjectGenerationInput({
1665
1714
  mode,
1666
1715
  schema,
1667
1716
  schemaName,
1668
- schemaDescription
1717
+ schemaDescription,
1718
+ enumValues
1669
1719
  }) {
1670
- if (output != null && output !== "object" && output !== "array" && output !== "no-schema") {
1720
+ if (output != null && output !== "object" && output !== "array" && output !== "enum" && output !== "no-schema") {
1671
1721
  throw new InvalidArgumentError({
1672
1722
  parameter: "output",
1673
1723
  value: output,
@@ -1703,6 +1753,13 @@ function validateObjectGenerationInput({
1703
1753
  message: "Schema name is not supported for no-schema output."
1704
1754
  });
1705
1755
  }
1756
+ if (enumValues != null) {
1757
+ throw new InvalidArgumentError({
1758
+ parameter: "enumValues",
1759
+ value: enumValues,
1760
+ message: "Enum values are not supported for no-schema output."
1761
+ });
1762
+ }
1706
1763
  }
1707
1764
  if (output === "object") {
1708
1765
  if (schema == null) {
@@ -1712,6 +1769,13 @@ function validateObjectGenerationInput({
1712
1769
  message: "Schema is required for object output."
1713
1770
  });
1714
1771
  }
1772
+ if (enumValues != null) {
1773
+ throw new InvalidArgumentError({
1774
+ parameter: "enumValues",
1775
+ value: enumValues,
1776
+ message: "Enum values are not supported for object output."
1777
+ });
1778
+ }
1715
1779
  }
1716
1780
  if (output === "array") {
1717
1781
  if (schema == null) {
@@ -1721,6 +1785,52 @@ function validateObjectGenerationInput({
1721
1785
  message: "Element schema is required for array output."
1722
1786
  });
1723
1787
  }
1788
+ if (enumValues != null) {
1789
+ throw new InvalidArgumentError({
1790
+ parameter: "enumValues",
1791
+ value: enumValues,
1792
+ message: "Enum values are not supported for array output."
1793
+ });
1794
+ }
1795
+ }
1796
+ if (output === "enum") {
1797
+ if (schema != null) {
1798
+ throw new InvalidArgumentError({
1799
+ parameter: "schema",
1800
+ value: schema,
1801
+ message: "Schema is not supported for enum output."
1802
+ });
1803
+ }
1804
+ if (schemaDescription != null) {
1805
+ throw new InvalidArgumentError({
1806
+ parameter: "schemaDescription",
1807
+ value: schemaDescription,
1808
+ message: "Schema description is not supported for enum output."
1809
+ });
1810
+ }
1811
+ if (schemaName != null) {
1812
+ throw new InvalidArgumentError({
1813
+ parameter: "schemaName",
1814
+ value: schemaName,
1815
+ message: "Schema name is not supported for enum output."
1816
+ });
1817
+ }
1818
+ if (enumValues == null) {
1819
+ throw new InvalidArgumentError({
1820
+ parameter: "enumValues",
1821
+ value: enumValues,
1822
+ message: "Enum values are required for enum output."
1823
+ });
1824
+ }
1825
+ for (const value of enumValues) {
1826
+ if (typeof value !== "string") {
1827
+ throw new InvalidArgumentError({
1828
+ parameter: "enumValues",
1829
+ value,
1830
+ message: "Enum values must be strings."
1831
+ });
1832
+ }
1833
+ }
1724
1834
  }
1725
1835
  }
1726
1836
 
@@ -1728,6 +1838,8 @@ function validateObjectGenerationInput({
1728
1838
  var originalGenerateId = (0, import_provider_utils6.createIdGenerator)({ prefix: "aiobj-", length: 24 });
1729
1839
  async function generateObject({
1730
1840
  model,
1841
+ enum: enumValues,
1842
+ // rename bc enum is reserved by typescript
1731
1843
  schema: inputSchema,
1732
1844
  schemaName,
1733
1845
  schemaDescription,
@@ -1752,9 +1864,14 @@ async function generateObject({
1752
1864
  mode,
1753
1865
  schema: inputSchema,
1754
1866
  schemaName,
1755
- schemaDescription
1867
+ schemaDescription,
1868
+ enumValues
1869
+ });
1870
+ const outputStrategy = getOutputStrategy({
1871
+ output,
1872
+ schema: inputSchema,
1873
+ enumValues
1756
1874
  });
1757
- const outputStrategy = getOutputStrategy({ output, schema: inputSchema });
1758
1875
  if (outputStrategy.type === "no-schema" && mode === void 0) {
1759
1876
  mode = "json";
1760
1877
  }
@@ -4056,9 +4173,9 @@ var DefaultStreamTextResult = class {
4056
4173
  });
4057
4174
  }
4058
4175
  toAIStream(callbacks = {}) {
4059
- return this.toDataStream({ callbacks });
4176
+ return this.toDataStreamInternal({ callbacks });
4060
4177
  }
4061
- toDataStream({
4178
+ toDataStreamInternal({
4062
4179
  callbacks = {},
4063
4180
  getErrorMessage: getErrorMessage4 = () => ""
4064
4181
  // mask error messages for safety by default
@@ -4182,7 +4299,7 @@ var DefaultStreamTextResult = class {
4182
4299
  contentType: "text/plain; charset=utf-8",
4183
4300
  dataStreamVersion: "v1"
4184
4301
  }),
4185
- stream: data ? mergeStreams(data.stream, this.toDataStream({ getErrorMessage: getErrorMessage4 })) : this.toDataStream({ getErrorMessage: getErrorMessage4 })
4302
+ stream: this.toDataStream({ data, getErrorMessage: getErrorMessage4 })
4186
4303
  });
4187
4304
  }
4188
4305
  pipeTextStreamToResponse(response, init) {
@@ -4199,6 +4316,12 @@ var DefaultStreamTextResult = class {
4199
4316
  toAIStreamResponse(options) {
4200
4317
  return this.toDataStreamResponse(options);
4201
4318
  }
4319
+ toDataStream(options) {
4320
+ const stream = this.toDataStreamInternal({
4321
+ getErrorMessage: options == null ? void 0 : options.getErrorMessage
4322
+ });
4323
+ return (options == null ? void 0 : options.data) ? mergeStreams(options == null ? void 0 : options.data.stream, stream) : stream;
4324
+ }
4202
4325
  toDataStreamResponse(options) {
4203
4326
  var _a11;
4204
4327
  const init = options == null ? void 0 : "init" in options ? options.init : {
@@ -4208,8 +4331,7 @@ var DefaultStreamTextResult = class {
4208
4331
  };
4209
4332
  const data = options == null ? void 0 : "data" in options ? options.data : void 0;
4210
4333
  const getErrorMessage4 = options == null ? void 0 : "getErrorMessage" in options ? options.getErrorMessage : void 0;
4211
- const stream = data ? mergeStreams(data.stream, this.toDataStream({ getErrorMessage: getErrorMessage4 })) : this.toDataStream({ getErrorMessage: getErrorMessage4 });
4212
- return new Response(stream, {
4334
+ return new Response(this.toDataStream({ data, getErrorMessage: getErrorMessage4 }), {
4213
4335
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
4214
4336
  statusText: init == null ? void 0 : init.statusText,
4215
4337
  headers: prepareResponseHeaders(init, {