modelfusion 0.42.0 → 0.44.0

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.
Files changed (51) hide show
  1. package/README.md +42 -2
  2. package/core/getRun.cjs +60 -0
  3. package/core/getRun.d.ts +9 -0
  4. package/core/getRun.js +32 -0
  5. package/core/index.cjs +1 -0
  6. package/core/index.d.ts +1 -0
  7. package/core/index.js +1 -0
  8. package/guard/fixStructure.cjs +21 -0
  9. package/guard/fixStructure.d.ts +10 -0
  10. package/guard/fixStructure.js +17 -0
  11. package/guard/guard.cjs +72 -0
  12. package/guard/guard.d.ts +28 -0
  13. package/guard/guard.js +68 -0
  14. package/guard/index.cjs +18 -0
  15. package/guard/index.d.ts +2 -0
  16. package/guard/index.js +2 -0
  17. package/index.cjs +1 -0
  18. package/index.d.ts +1 -0
  19. package/index.js +1 -0
  20. package/model-function/executeCall.cjs +8 -2
  21. package/model-function/executeCall.js +8 -2
  22. package/model-function/generate-structure/StructureFromTextGenerationModel.cjs +15 -4
  23. package/model-function/generate-structure/StructureFromTextGenerationModel.d.ts +2 -1
  24. package/model-function/generate-structure/StructureFromTextGenerationModel.js +15 -4
  25. package/model-function/generate-structure/StructureGenerationModel.d.ts +2 -1
  26. package/model-function/generate-structure/StructureOrTextGenerationModel.d.ts +2 -0
  27. package/model-function/generate-structure/StructureParseError.cjs +34 -0
  28. package/model-function/generate-structure/StructureParseError.d.ts +10 -0
  29. package/model-function/generate-structure/StructureParseError.js +30 -0
  30. package/model-function/generate-structure/StructureValidationError.cjs +10 -3
  31. package/model-function/generate-structure/StructureValidationError.d.ts +3 -1
  32. package/model-function/generate-structure/StructureValidationError.js +10 -3
  33. package/model-function/generate-structure/generateStructure.cjs +2 -1
  34. package/model-function/generate-structure/generateStructure.js +2 -1
  35. package/model-function/generate-structure/generateStructureOrText.cjs +1 -0
  36. package/model-function/generate-structure/generateStructureOrText.js +1 -0
  37. package/model-function/generate-structure/streamStructure.cjs +8 -2
  38. package/model-function/generate-structure/streamStructure.js +8 -2
  39. package/model-function/generate-text/streamText.cjs +8 -2
  40. package/model-function/generate-text/streamText.js +8 -2
  41. package/model-function/index.cjs +1 -0
  42. package/model-function/index.d.ts +1 -0
  43. package/model-function/index.js +1 -0
  44. package/model-provider/openai/chat/OpenAIChatModel.cjs +47 -20
  45. package/model-provider/openai/chat/OpenAIChatModel.d.ts +36 -2
  46. package/model-provider/openai/chat/OpenAIChatModel.js +47 -20
  47. package/package.json +1 -1
  48. package/retriever/retrieve.cjs +8 -2
  49. package/retriever/retrieve.js +8 -2
  50. package/tool/executeTool.cjs +8 -2
  51. package/tool/executeTool.js +8 -2
package/README.md CHANGED
@@ -19,8 +19,9 @@ ModelFusion is a library for building AI apps, chatbots, and agents. It provides
19
19
 
20
20
  - **Multimodal Support**: Beyond just LLMs, ModelFusion encompasses a diverse array of models including text generation, text-to-speech, speech-to-text, and image generation, allowing you to build multifaceted AI applications with ease.
21
21
  - **Flexibility and control**: AI application development can be complex and unique to each project. With ModelFusion, you have complete control over the prompts and model settings, and you can access the raw responses from the models quickly to build what you need.
22
- - **Type inference and validation**: ModelFusion uses TypeScript and [Zod](https://github.com/colinhacks/zod) to infer types wherever possible and to validate model responses.
23
- - **Integrated support features**: Essential features like logging, retries, throttling, tracing, and error handling are built-in, helping you focus more on building your application.
22
+ - **Type inference and validation**: ModelFusion uses TypeScript to infer types wherever possible and to validate model responses. By default, [Zod](https://github.com/colinhacks/zod) is used for type validation, but you can also use other libraries.
23
+ - **Guards**: ModelFusion provides a guard function that you can use to implement retry on error, redacting and changing reponses, etc.
24
+ - **Integrated support features**: Essential features like **observability**, logging, retries, throttling, tracing, and error handling are built-in, helping you focus more on building your application.
24
25
 
25
26
  ## Quick Install
26
27
 
@@ -454,6 +455,41 @@ const retrievedTexts = await retrieve(
454
455
 
455
456
  Available Vector Stores: [Memory](https://modelfusion.dev/integration/vector-index/memory), [Pinecone](https://modelfusion.dev/integration/vector-index/pinecone)
456
457
 
458
+ ### Guards
459
+
460
+ [Guards](https://github.com/lgrammel/modelfusion/tree/main/examples/basic/src/guard) can be used to implement retry on error, redacting and changing reponses, etc.
461
+
462
+ #### Retry structure parsing on error:
463
+
464
+ ```ts
465
+ const result = await guard(
466
+ (input) =>
467
+ generateStructure(
468
+ new OpenAIChatModel({
469
+ // ...
470
+ }),
471
+ new ZodStructureDefinition({
472
+ // ...
473
+ }),
474
+ input
475
+ ),
476
+ [
477
+ // ...
478
+ ],
479
+ fixStructure({
480
+ modifyInputForRetry: async ({ input, error }) => [
481
+ ...input,
482
+ OpenAIChatMessage.functionCall(null, {
483
+ name: error.structureName,
484
+ arguments: error.valueText,
485
+ }),
486
+ OpenAIChatMessage.user(error.message),
487
+ OpenAIChatMessage.user("Please fix the error and try again."),
488
+ ],
489
+ })
490
+ );
491
+ ```
492
+
457
493
  ### Observability
458
494
 
459
495
  Integrations: [Helicone](https://modelfusion.dev/integration/observability/helicone)
@@ -560,3 +596,7 @@ Extracts information about a topic from a PDF and writes a tweet in your own sty
560
596
  ### [Contributing Guide](https://github.com/lgrammel/modelfusion/blob/main/CONTRIBUTING.md)
561
597
 
562
598
  Read the [ModelFusion contributing guide](https://github.com/lgrammel/modelfusion/blob/main/CONTRIBUTING.md) to learn about the development process, how to propose bugfixes and improvements, and how to build and test your changes.
599
+
600
+ ```
601
+
602
+ ```
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.withRun = exports.getRun = void 0;
27
+ let runStorage;
28
+ const isNode = typeof process !== "undefined" &&
29
+ process.versions != null &&
30
+ process.versions.node != null;
31
+ async function ensureLoaded() {
32
+ if (!isNode)
33
+ return Promise.resolve();
34
+ if (!runStorage) {
35
+ const { AsyncLocalStorage } = await Promise.resolve().then(() => __importStar(require("node:async_hooks")));
36
+ runStorage = new AsyncLocalStorage();
37
+ }
38
+ return Promise.resolve();
39
+ }
40
+ /**
41
+ * Returns the run stored in an AsyncLocalStorage if running in Node.js. It can be set with `withRun()`.
42
+ */
43
+ async function getRun(run) {
44
+ await ensureLoaded();
45
+ return run ?? runStorage?.getStore();
46
+ }
47
+ exports.getRun = getRun;
48
+ /**
49
+ * Stores the run in an AsyncLocalStorage if running in Node.js. It can be retrieved with `getRun()`.
50
+ */
51
+ async function withRun(run, callback) {
52
+ await ensureLoaded();
53
+ if (runStorage != null) {
54
+ await runStorage.run(run, callback);
55
+ }
56
+ else {
57
+ await callback();
58
+ }
59
+ }
60
+ exports.withRun = withRun;
@@ -0,0 +1,9 @@
1
+ import { Run } from "./Run";
2
+ /**
3
+ * Returns the run stored in an AsyncLocalStorage if running in Node.js. It can be set with `withRun()`.
4
+ */
5
+ export declare function getRun(run?: Run): Promise<Run | undefined>;
6
+ /**
7
+ * Stores the run in an AsyncLocalStorage if running in Node.js. It can be retrieved with `getRun()`.
8
+ */
9
+ export declare function withRun(run: Run, callback: () => PromiseLike<void>): Promise<void>;
package/core/getRun.js ADDED
@@ -0,0 +1,32 @@
1
+ let runStorage;
2
+ const isNode = typeof process !== "undefined" &&
3
+ process.versions != null &&
4
+ process.versions.node != null;
5
+ async function ensureLoaded() {
6
+ if (!isNode)
7
+ return Promise.resolve();
8
+ if (!runStorage) {
9
+ const { AsyncLocalStorage } = await import("node:async_hooks");
10
+ runStorage = new AsyncLocalStorage();
11
+ }
12
+ return Promise.resolve();
13
+ }
14
+ /**
15
+ * Returns the run stored in an AsyncLocalStorage if running in Node.js. It can be set with `withRun()`.
16
+ */
17
+ export async function getRun(run) {
18
+ await ensureLoaded();
19
+ return run ?? runStorage?.getStore();
20
+ }
21
+ /**
22
+ * Stores the run in an AsyncLocalStorage if running in Node.js. It can be retrieved with `getRun()`.
23
+ */
24
+ export async function withRun(run, callback) {
25
+ await ensureLoaded();
26
+ if (runStorage != null) {
27
+ await runStorage.run(run, callback);
28
+ }
29
+ else {
30
+ await callback();
31
+ }
32
+ }
package/core/index.cjs CHANGED
@@ -24,4 +24,5 @@ __exportStar(require("./GlobalFunctionObservers.cjs"), exports);
24
24
  __exportStar(require("./Run.cjs"), exports);
25
25
  __exportStar(require("./Vector.cjs"), exports);
26
26
  __exportStar(require("./api/index.cjs"), exports);
27
+ __exportStar(require("./getRun.cjs"), exports);
27
28
  __exportStar(require("./structure/index.cjs"), exports);
package/core/index.d.ts CHANGED
@@ -8,4 +8,5 @@ export * from "./GlobalFunctionObservers.js";
8
8
  export * from "./Run.js";
9
9
  export * from "./Vector.js";
10
10
  export * from "./api/index.js";
11
+ export * from "./getRun.js";
11
12
  export * from "./structure/index.js";
package/core/index.js CHANGED
@@ -8,4 +8,5 @@ export * from "./GlobalFunctionObservers.js";
8
8
  export * from "./Run.js";
9
9
  export * from "./Vector.js";
10
10
  export * from "./api/index.js";
11
+ export * from "./getRun.js";
11
12
  export * from "./structure/index.js";
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fixStructure = void 0;
4
+ const StructureParseError_js_1 = require("../model-function/generate-structure/StructureParseError.cjs");
5
+ const StructureValidationError_js_1 = require("../model-function/generate-structure/StructureValidationError.cjs");
6
+ const fixStructure = ({ modifyInputForRetry }) => async (result) => {
7
+ if (result.type === "error" &&
8
+ (result.error instanceof StructureValidationError_js_1.StructureValidationError ||
9
+ result.error instanceof StructureParseError_js_1.StructureParseError)) {
10
+ return {
11
+ action: "retry",
12
+ input: await modifyInputForRetry({
13
+ type: "error",
14
+ input: result.input,
15
+ error: result.error,
16
+ }),
17
+ };
18
+ }
19
+ return undefined;
20
+ };
21
+ exports.fixStructure = fixStructure;
@@ -0,0 +1,10 @@
1
+ import { StructureParseError } from "../model-function/generate-structure/StructureParseError.js";
2
+ import { StructureValidationError } from "../model-function/generate-structure/StructureValidationError.js";
3
+ import { Guard } from "./guard.js";
4
+ export declare const fixStructure: <INPUT, OUTPUT>(options: {
5
+ modifyInputForRetry: (options: {
6
+ type: "error";
7
+ input: INPUT;
8
+ error: StructureValidationError | StructureParseError;
9
+ }) => PromiseLike<INPUT>;
10
+ }) => Guard<INPUT, OUTPUT>;
@@ -0,0 +1,17 @@
1
+ import { StructureParseError } from "../model-function/generate-structure/StructureParseError.js";
2
+ import { StructureValidationError } from "../model-function/generate-structure/StructureValidationError.js";
3
+ export const fixStructure = ({ modifyInputForRetry }) => async (result) => {
4
+ if (result.type === "error" &&
5
+ (result.error instanceof StructureValidationError ||
6
+ result.error instanceof StructureParseError)) {
7
+ return {
8
+ action: "retry",
9
+ input: await modifyInputForRetry({
10
+ type: "error",
11
+ input: result.input,
12
+ error: result.error,
13
+ }),
14
+ };
15
+ }
16
+ return undefined;
17
+ };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.guard = void 0;
4
+ async function guard(execute, input, guards, options) {
5
+ if (typeof guards === "function") {
6
+ guards = [guards];
7
+ }
8
+ const maxRetries = options?.maxRetries ?? 1;
9
+ let attempts = 0;
10
+ while (attempts <= maxRetries) {
11
+ let result;
12
+ try {
13
+ result = {
14
+ type: "value",
15
+ input,
16
+ output: await execute(input),
17
+ };
18
+ }
19
+ catch (error) {
20
+ result = {
21
+ type: "error",
22
+ input,
23
+ error,
24
+ };
25
+ }
26
+ let isValid = true;
27
+ for (const guard of guards) {
28
+ const guardResult = await guard(result);
29
+ if (guardResult === undefined) {
30
+ continue;
31
+ }
32
+ switch (guardResult.action) {
33
+ case "passThrough": {
34
+ break;
35
+ }
36
+ case "retry": {
37
+ input = guardResult.input;
38
+ isValid = false;
39
+ break;
40
+ }
41
+ case "return": {
42
+ result = {
43
+ type: "value",
44
+ input,
45
+ output: guardResult.output,
46
+ };
47
+ break;
48
+ }
49
+ case "throwError": {
50
+ result = {
51
+ type: "error",
52
+ input,
53
+ error: guardResult.error,
54
+ };
55
+ break;
56
+ }
57
+ }
58
+ }
59
+ if (isValid) {
60
+ if (result.type === "value") {
61
+ return result.output;
62
+ }
63
+ else {
64
+ throw result.error;
65
+ }
66
+ }
67
+ attempts++;
68
+ }
69
+ throw new Error(`Maximum retry attempts of ${maxRetries} reached ` +
70
+ `without producing a valid output or handling an error after ${attempts} attempts.`);
71
+ }
72
+ exports.guard = guard;
@@ -0,0 +1,28 @@
1
+ type OutputResult<INPUT, OUTPUT> = {
2
+ type: "value";
3
+ input: INPUT;
4
+ output: OUTPUT;
5
+ error?: undefined;
6
+ } | {
7
+ type: "error";
8
+ input: INPUT;
9
+ output?: undefined;
10
+ error: unknown;
11
+ };
12
+ export type OutputValidator<INPUT, OUTPUT> = ({ type, input, output, error, }: OutputResult<INPUT, OUTPUT>) => PromiseLike<boolean>;
13
+ export type Guard<INPUT, OUTPUT> = ({ type, input, output, error, }: OutputResult<INPUT, OUTPUT>) => PromiseLike<{
14
+ action: "retry";
15
+ input: INPUT;
16
+ } | {
17
+ action: "return";
18
+ output: OUTPUT;
19
+ } | {
20
+ action: "throwError";
21
+ error: unknown;
22
+ } | {
23
+ action: "passThrough";
24
+ } | undefined>;
25
+ export declare function guard<INPUT, OUTPUT>(execute: (input: INPUT) => PromiseLike<OUTPUT>, input: INPUT, guards: Array<Guard<INPUT, OUTPUT>> | Guard<INPUT, OUTPUT>, options?: {
26
+ maxRetries: number;
27
+ }): Promise<OUTPUT | undefined>;
28
+ export {};
package/guard/guard.js ADDED
@@ -0,0 +1,68 @@
1
+ export async function guard(execute, input, guards, options) {
2
+ if (typeof guards === "function") {
3
+ guards = [guards];
4
+ }
5
+ const maxRetries = options?.maxRetries ?? 1;
6
+ let attempts = 0;
7
+ while (attempts <= maxRetries) {
8
+ let result;
9
+ try {
10
+ result = {
11
+ type: "value",
12
+ input,
13
+ output: await execute(input),
14
+ };
15
+ }
16
+ catch (error) {
17
+ result = {
18
+ type: "error",
19
+ input,
20
+ error,
21
+ };
22
+ }
23
+ let isValid = true;
24
+ for (const guard of guards) {
25
+ const guardResult = await guard(result);
26
+ if (guardResult === undefined) {
27
+ continue;
28
+ }
29
+ switch (guardResult.action) {
30
+ case "passThrough": {
31
+ break;
32
+ }
33
+ case "retry": {
34
+ input = guardResult.input;
35
+ isValid = false;
36
+ break;
37
+ }
38
+ case "return": {
39
+ result = {
40
+ type: "value",
41
+ input,
42
+ output: guardResult.output,
43
+ };
44
+ break;
45
+ }
46
+ case "throwError": {
47
+ result = {
48
+ type: "error",
49
+ input,
50
+ error: guardResult.error,
51
+ };
52
+ break;
53
+ }
54
+ }
55
+ }
56
+ if (isValid) {
57
+ if (result.type === "value") {
58
+ return result.output;
59
+ }
60
+ else {
61
+ throw result.error;
62
+ }
63
+ }
64
+ attempts++;
65
+ }
66
+ throw new Error(`Maximum retry attempts of ${maxRetries} reached ` +
67
+ `without producing a valid output or handling an error after ${attempts} attempts.`);
68
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./fixStructure.cjs"), exports);
18
+ __exportStar(require("./guard.cjs"), exports);
@@ -0,0 +1,2 @@
1
+ export * from "./fixStructure.js";
2
+ export * from "./guard.js";
package/guard/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./fixStructure.js";
2
+ export * from "./guard.js";
package/index.cjs CHANGED
@@ -18,6 +18,7 @@ __exportStar(require("./composed-function/index.cjs"), exports);
18
18
  __exportStar(require("./core/index.cjs"), exports);
19
19
  __exportStar(require("./cost/index.cjs"), exports);
20
20
  __exportStar(require("./event-source/index.cjs"), exports);
21
+ __exportStar(require("./guard/index.cjs"), exports);
21
22
  __exportStar(require("./model-function/index.cjs"), exports);
22
23
  __exportStar(require("./model-provider/index.cjs"), exports);
23
24
  __exportStar(require("./observability/index.cjs"), exports);
package/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./composed-function/index.js";
2
2
  export * from "./core/index.js";
3
3
  export * from "./cost/index.js";
4
4
  export * from "./event-source/index.js";
5
+ export * from "./guard/index.js";
5
6
  export * from "./model-function/index.js";
6
7
  export * from "./model-provider/index.js";
7
8
  export * from "./observability/index.js";
package/index.js CHANGED
@@ -2,6 +2,7 @@ export * from "./composed-function/index.js";
2
2
  export * from "./core/index.js";
3
3
  export * from "./cost/index.js";
4
4
  export * from "./event-source/index.js";
5
+ export * from "./guard/index.js";
5
6
  export * from "./model-function/index.js";
6
7
  export * from "./model-provider/index.js";
7
8
  export * from "./observability/index.js";
@@ -7,6 +7,7 @@ const GlobalFunctionLogging_js_1 = require("../core/GlobalFunctionLogging.cjs");
7
7
  const GlobalFunctionObservers_js_1 = require("../core/GlobalFunctionObservers.cjs");
8
8
  const AbortError_js_1 = require("../core/api/AbortError.cjs");
9
9
  const getFunctionCallLogger_js_1 = require("../core/getFunctionCallLogger.cjs");
10
+ const getRun_js_1 = require("../core/getRun.cjs");
10
11
  const DurationMeasurement_js_1 = require("../util/DurationMeasurement.cjs");
11
12
  const runSafe_js_1 = require("../util/runSafe.cjs");
12
13
  class ModelFunctionPromise extends Promise {
@@ -54,7 +55,7 @@ function executeCall({ model, options, input, functionType, generateResponse, })
54
55
  }
55
56
  exports.executeCall = executeCall;
56
57
  async function doExecuteCall({ model, options, input, functionType, generateResponse, }) {
57
- const run = options?.run;
58
+ const run = await (0, getRun_js_1.getRun)(options?.run);
58
59
  const settings = model.settings;
59
60
  const eventSource = new FunctionEventSource_js_1.FunctionEventSource({
60
61
  observers: [
@@ -84,7 +85,12 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
84
85
  eventType: "started",
85
86
  ...startMetadata,
86
87
  });
87
- const result = await (0, runSafe_js_1.runSafe)(() => generateResponse(options));
88
+ const result = await (0, runSafe_js_1.runSafe)(() => generateResponse({
89
+ functionId: options?.functionId,
90
+ logging: options?.logging,
91
+ observers: options?.observers,
92
+ run,
93
+ }));
88
94
  const finishMetadata = {
89
95
  eventType: "finished",
90
96
  ...startMetadata,
@@ -4,6 +4,7 @@ import { getGlobalFunctionLogging } from "../core/GlobalFunctionLogging.js";
4
4
  import { getGlobalFunctionObservers } from "../core/GlobalFunctionObservers.js";
5
5
  import { AbortError } from "../core/api/AbortError.js";
6
6
  import { getFunctionCallLogger } from "../core/getFunctionCallLogger.js";
7
+ import { getRun } from "../core/getRun.js";
7
8
  import { startDurationMeasurement } from "../util/DurationMeasurement.js";
8
9
  import { runSafe } from "../util/runSafe.js";
9
10
  export class ModelFunctionPromise extends Promise {
@@ -49,7 +50,7 @@ export function executeCall({ model, options, input, functionType, generateRespo
49
50
  }));
50
51
  }
51
52
  async function doExecuteCall({ model, options, input, functionType, generateResponse, }) {
52
- const run = options?.run;
53
+ const run = await getRun(options?.run);
53
54
  const settings = model.settings;
54
55
  const eventSource = new FunctionEventSource({
55
56
  observers: [
@@ -79,7 +80,12 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
79
80
  eventType: "started",
80
81
  ...startMetadata,
81
82
  });
82
- const result = await runSafe(() => generateResponse(options));
83
+ const result = await runSafe(() => generateResponse({
84
+ functionId: options?.functionId,
85
+ logging: options?.logging,
86
+ observers: options?.observers,
87
+ run,
88
+ }));
83
89
  const finishMetadata = {
84
90
  eventType: "finished",
85
91
  ...startMetadata,
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StructureFromTextGenerationModel = void 0;
4
4
  const generateText_js_1 = require("../generate-text/generateText.cjs");
5
+ const StructureParseError_js_1 = require("./StructureParseError.cjs");
5
6
  class StructureFromTextGenerationModel {
6
7
  constructor({ model, format, }) {
7
8
  Object.defineProperty(this, "model", {
@@ -30,10 +31,20 @@ class StructureFromTextGenerationModel {
30
31
  }
31
32
  async doGenerateStructure(structure, prompt, options) {
32
33
  const { response, value } = await (0, generateText_js_1.generateText)(this.model, this.format.createPrompt(prompt, structure), options).asFullResponse();
33
- return {
34
- response,
35
- structure: this.format.extractStructure(value),
36
- };
34
+ try {
35
+ return {
36
+ response,
37
+ value: this.format.extractStructure(value),
38
+ valueText: value,
39
+ };
40
+ }
41
+ catch (error) {
42
+ throw new StructureParseError_js_1.StructureParseError({
43
+ structureName: structure.name,
44
+ valueText: value,
45
+ cause: error,
46
+ });
47
+ }
37
48
  }
38
49
  withSettings(additionalSettings) {
39
50
  return new StructureFromTextGenerationModel({
@@ -18,7 +18,8 @@ export declare class StructureFromTextGenerationModel<PROMPT, MODEL extends Text
18
18
  get settingsForEvent(): Partial<MODEL["settings"]>;
19
19
  doGenerateStructure(structure: StructureDefinition<string, unknown>, prompt: PROMPT, options?: FunctionOptions): Promise<{
20
20
  response: unknown;
21
- structure: unknown;
21
+ value: unknown;
22
+ valueText: string;
22
23
  }>;
23
24
  withSettings(additionalSettings: Partial<MODEL["settings"]>): this;
24
25
  }
@@ -1,4 +1,5 @@
1
1
  import { generateText } from "../generate-text/generateText.js";
2
+ import { StructureParseError } from "./StructureParseError.js";
2
3
  export class StructureFromTextGenerationModel {
3
4
  constructor({ model, format, }) {
4
5
  Object.defineProperty(this, "model", {
@@ -27,10 +28,20 @@ export class StructureFromTextGenerationModel {
27
28
  }
28
29
  async doGenerateStructure(structure, prompt, options) {
29
30
  const { response, value } = await generateText(this.model, this.format.createPrompt(prompt, structure), options).asFullResponse();
30
- return {
31
- response,
32
- structure: this.format.extractStructure(value),
33
- };
31
+ try {
32
+ return {
33
+ response,
34
+ value: this.format.extractStructure(value),
35
+ valueText: value,
36
+ };
37
+ }
38
+ catch (error) {
39
+ throw new StructureParseError({
40
+ structureName: structure.name,
41
+ valueText: value,
42
+ cause: error,
43
+ });
44
+ }
34
45
  }
35
46
  withSettings(additionalSettings) {
36
47
  return new StructureFromTextGenerationModel({
@@ -7,7 +7,8 @@ export interface StructureGenerationModelSettings extends ModelSettings {
7
7
  export interface StructureGenerationModel<PROMPT, SETTINGS extends StructureGenerationModelSettings = StructureGenerationModelSettings> extends Model<SETTINGS> {
8
8
  doGenerateStructure(structure: StructureDefinition<string, unknown>, prompt: PROMPT, options?: FunctionOptions): PromiseLike<{
9
9
  response: unknown;
10
- structure: unknown;
10
+ valueText: string;
11
+ value: unknown;
11
12
  usage?: {
12
13
  promptTokens: number;
13
14
  completionTokens: number;
@@ -9,10 +9,12 @@ export interface StructureOrTextGenerationModel<PROMPT, SETTINGS extends Structu
9
9
  structureAndText: {
10
10
  structure: null;
11
11
  value: null;
12
+ valueText: null;
12
13
  text: string;
13
14
  } | {
14
15
  structure: string;
15
16
  value: unknown;
17
+ valueText: string;
16
18
  text: string | null;
17
19
  };
18
20
  usage?: {