modelfusion 0.22.0 → 0.24.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 (111) hide show
  1. package/README.md +3 -0
  2. package/core/FunctionOptions.d.ts +14 -0
  3. package/core/GlobalFunctionLogging.cjs +12 -0
  4. package/core/GlobalFunctionLogging.d.ts +3 -0
  5. package/core/GlobalFunctionLogging.js +7 -0
  6. package/core/getFunctionCallLogger.cjs +74 -0
  7. package/core/getFunctionCallLogger.d.ts +3 -0
  8. package/core/getFunctionCallLogger.js +70 -0
  9. package/core/index.cjs +1 -1
  10. package/core/index.d.ts +1 -1
  11. package/core/index.js +1 -1
  12. package/model-function/AbstractModel.d.ts +1 -0
  13. package/model-function/Model.d.ts +6 -1
  14. package/model-function/ModelCallEvent.d.ts +21 -2
  15. package/model-function/embed-text/embedText.d.ts +2 -2
  16. package/model-function/executeCall.cjs +24 -17
  17. package/model-function/executeCall.d.ts +15 -13
  18. package/model-function/executeCall.js +22 -15
  19. package/model-function/generate-image/generateImage.d.ts +1 -1
  20. package/model-function/generate-json/JsonGenerationEvent.d.ts +16 -0
  21. package/model-function/generate-json/JsonGenerationModel.d.ts +13 -0
  22. package/model-function/generate-json/JsonOrTextGenerationModel.d.ts +23 -0
  23. package/model-function/generate-json/JsonTextGenerationModel.cjs +3 -0
  24. package/model-function/generate-json/JsonTextGenerationModel.d.ts +6 -5
  25. package/model-function/generate-json/JsonTextGenerationModel.js +3 -0
  26. package/model-function/generate-json/generateJson.cjs +1 -0
  27. package/model-function/generate-json/generateJson.d.ts +2 -2
  28. package/model-function/generate-json/generateJson.js +1 -0
  29. package/model-function/generate-json/generateJsonOrText.cjs +1 -0
  30. package/model-function/generate-json/generateJsonOrText.d.ts +2 -2
  31. package/model-function/generate-json/generateJsonOrText.js +1 -0
  32. package/model-function/generate-text/TextGenerationEvent.d.ts +5 -2
  33. package/model-function/generate-text/TextGenerationModel.d.ts +5 -0
  34. package/model-function/generate-text/generateText.cjs +1 -0
  35. package/model-function/generate-text/generateText.d.ts +1 -1
  36. package/model-function/generate-text/generateText.js +1 -0
  37. package/model-function/generate-text/streamText.cjs +9 -6
  38. package/model-function/generate-text/streamText.d.ts +5 -5
  39. package/model-function/generate-text/streamText.js +9 -6
  40. package/model-function/index.cjs +3 -2
  41. package/model-function/index.d.ts +3 -2
  42. package/model-function/index.js +3 -2
  43. package/model-function/synthesize-speech/SpeechSynthesisEvent.d.ts +2 -2
  44. package/model-function/synthesize-speech/SpeechSynthesisModel.d.ts +1 -1
  45. package/model-function/synthesize-speech/synthesizeSpeech.d.ts +1 -1
  46. package/model-function/transcribe-speech/TranscriptionModel.d.ts +1 -1
  47. package/model-function/transcribe-speech/transcribe.d.ts +1 -1
  48. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.cjs +9 -0
  49. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.d.ts +1 -0
  50. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.js +9 -0
  51. package/model-provider/cohere/CohereTextEmbeddingModel.cjs +6 -0
  52. package/model-provider/cohere/CohereTextEmbeddingModel.d.ts +1 -0
  53. package/model-provider/cohere/CohereTextEmbeddingModel.js +6 -0
  54. package/model-provider/cohere/CohereTextGenerationModel.cjs +20 -0
  55. package/model-provider/cohere/CohereTextGenerationModel.d.ts +2 -1
  56. package/model-provider/cohere/CohereTextGenerationModel.js +20 -0
  57. package/model-provider/cohere/CohereTokenizer.d.ts +1 -1
  58. package/model-provider/elevenlabs/ElevenLabsSpeechSynthesisModel.cjs +8 -0
  59. package/model-provider/elevenlabs/ElevenLabsSpeechSynthesisModel.d.ts +1 -0
  60. package/model-provider/elevenlabs/ElevenLabsSpeechSynthesisModel.js +8 -0
  61. package/model-provider/huggingface/HuggingFaceTextEmbeddingModel.cjs +7 -0
  62. package/model-provider/huggingface/HuggingFaceTextEmbeddingModel.d.ts +1 -0
  63. package/model-provider/huggingface/HuggingFaceTextEmbeddingModel.js +7 -0
  64. package/model-provider/huggingface/HuggingFaceTextGenerationModel.cjs +16 -0
  65. package/model-provider/huggingface/HuggingFaceTextGenerationModel.d.ts +1 -0
  66. package/model-provider/huggingface/HuggingFaceTextGenerationModel.js +16 -0
  67. package/model-provider/llamacpp/LlamaCppTextEmbeddingModel.cjs +6 -0
  68. package/model-provider/llamacpp/LlamaCppTextEmbeddingModel.d.ts +1 -0
  69. package/model-provider/llamacpp/LlamaCppTextEmbeddingModel.js +6 -0
  70. package/model-provider/llamacpp/LlamaCppTextGenerationModel.cjs +31 -0
  71. package/model-provider/llamacpp/LlamaCppTextGenerationModel.d.ts +6 -0
  72. package/model-provider/llamacpp/LlamaCppTextGenerationModel.js +31 -0
  73. package/model-provider/openai/OpenAIImageGenerationModel.cjs +8 -0
  74. package/model-provider/openai/OpenAIImageGenerationModel.d.ts +1 -0
  75. package/model-provider/openai/OpenAIImageGenerationModel.js +8 -0
  76. package/model-provider/openai/OpenAITextEmbeddingModel.cjs +5 -0
  77. package/model-provider/openai/OpenAITextEmbeddingModel.d.ts +12 -11
  78. package/model-provider/openai/OpenAITextEmbeddingModel.js +5 -0
  79. package/model-provider/openai/OpenAITextGenerationModel.cjs +62 -6
  80. package/model-provider/openai/OpenAITextGenerationModel.d.ts +34 -17
  81. package/model-provider/openai/OpenAITextGenerationModel.js +60 -5
  82. package/model-provider/openai/OpenAITranscriptionModel.cjs +7 -0
  83. package/model-provider/openai/OpenAITranscriptionModel.d.ts +2 -0
  84. package/model-provider/openai/OpenAITranscriptionModel.js +7 -0
  85. package/model-provider/openai/TikTokenTokenizer.d.ts +4 -2
  86. package/model-provider/openai/chat/OpenAIChatModel.cjs +68 -9
  87. package/model-provider/openai/chat/OpenAIChatModel.d.ts +40 -20
  88. package/model-provider/openai/chat/OpenAIChatModel.js +66 -8
  89. package/model-provider/openai/chat/OpenAIChatPrompt.d.ts +2 -2
  90. package/model-provider/openai/chat/countOpenAIChatMessageTokens.cjs +5 -2
  91. package/model-provider/openai/chat/countOpenAIChatMessageTokens.js +5 -2
  92. package/model-provider/stability/StabilityImageGenerationModel.cjs +15 -0
  93. package/model-provider/stability/StabilityImageGenerationModel.d.ts +1 -0
  94. package/model-provider/stability/StabilityImageGenerationModel.js +15 -0
  95. package/package.json +1 -1
  96. package/prompt/PromptFormatTextGenerationModel.cjs +3 -0
  97. package/prompt/PromptFormatTextGenerationModel.d.ts +1 -0
  98. package/prompt/PromptFormatTextGenerationModel.js +3 -0
  99. package/tool/executeTool.cjs +3 -0
  100. package/tool/executeTool.js +3 -0
  101. package/tool/useTool.d.ts +2 -2
  102. package/tool/useToolOrGenerateText.d.ts +2 -2
  103. package/core/ConsoleLogger.cjs +0 -9
  104. package/core/ConsoleLogger.d.ts +0 -5
  105. package/core/ConsoleLogger.js +0 -5
  106. package/model-function/generate-json/GenerateJsonModel.d.ts +0 -8
  107. package/model-function/generate-json/GenerateJsonOrTextModel.d.ts +0 -18
  108. /package/model-function/generate-json/{GenerateJsonModel.cjs → JsonGenerationModel.cjs} +0 -0
  109. /package/model-function/generate-json/{GenerateJsonModel.js → JsonGenerationModel.js} +0 -0
  110. /package/model-function/generate-json/{GenerateJsonOrTextModel.cjs → JsonOrTextGenerationModel.cjs} +0 -0
  111. /package/model-function/generate-json/{GenerateJsonOrTextModel.js → JsonOrTextGenerationModel.js} +0 -0
package/README.md CHANGED
@@ -35,6 +35,8 @@ You need to install `zod` and a matching version of `zod-to-json-schema` (peer d
35
35
  npm install zod zod-to-json-schema
36
36
  ```
37
37
 
38
+ Or use a template: [ModelFusion terminal app starter](https://github.com/lgrammel/modelfusion-terminal-app-starter)
39
+
38
40
  ## Usage Examples
39
41
 
40
42
  You can provide API keys for the different [integrations](https://modelfusion.dev/integration/model-provider/) using environment variables (e.g., `OPENAI_API_KEY`) or pass them into the model constructors as options.
@@ -376,6 +378,7 @@ const { chunks } = await retrieveTextChunks(
376
378
  - [Text Chunks](https://modelfusion.dev/guide/text-chunk/)
377
379
  - [Split Text](https://modelfusion.dev/guide/text-chunk/split)
378
380
  - [Utilities](https://modelfusion.dev/guide/util/)
381
+ - [Function Logging](https://modelfusion.dev/guide/util/logging)
379
382
  - [Function observers](https://modelfusion.dev/guide/util/observer)
380
383
  - [Retry strategies](https://modelfusion.dev/guide/util/retry)
381
384
  - [Throttling strategies](https://modelfusion.dev/guide/util/throttle)
@@ -8,6 +8,11 @@ export type FunctionOptions = {
8
8
  * Optional function identifier that is used in events to identify the function.
9
9
  */
10
10
  functionId?: string;
11
+ /**
12
+ * Optional logging to use for the function. Logs are sent to the console.
13
+ * Overrides the global function logging setting.
14
+ */
15
+ logging?: FunctionLogging;
11
16
  /**
12
17
  * Optional observers that are called when the function is invoked.
13
18
  */
@@ -17,3 +22,12 @@ export type FunctionOptions = {
17
22
  */
18
23
  run?: Run;
19
24
  };
25
+ /**
26
+ * The logging to use for the function. Logs are sent to the console.
27
+ *
28
+ * - `off` or undefined: No logging.
29
+ * - `basic-text`: Log the timestamp and the type of event as a single line of text.
30
+ * - `detailed-object`: Log everything except the original response as an object to the console.
31
+ * - `detailed-json`: Log everything except the original response as a JSON string to the console.
32
+ */
33
+ export type FunctionLogging = undefined | "off" | "basic-text" | "detailed-object" | "detailed-json";
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGlobalFunctionLogging = exports.setGlobalFunctionLogging = void 0;
4
+ let globalFunctionLogging = undefined;
5
+ function setGlobalFunctionLogging(logLevel) {
6
+ globalFunctionLogging = logLevel;
7
+ }
8
+ exports.setGlobalFunctionLogging = setGlobalFunctionLogging;
9
+ function getGlobalFunctionLogging() {
10
+ return globalFunctionLogging;
11
+ }
12
+ exports.getGlobalFunctionLogging = getGlobalFunctionLogging;
@@ -0,0 +1,3 @@
1
+ import { FunctionLogging } from "./FunctionOptions.js";
2
+ export declare function setGlobalFunctionLogging(logLevel: FunctionLogging): void;
3
+ export declare function getGlobalFunctionLogging(): FunctionLogging;
@@ -0,0 +1,7 @@
1
+ let globalFunctionLogging = undefined;
2
+ export function setGlobalFunctionLogging(logLevel) {
3
+ globalFunctionLogging = logLevel;
4
+ }
5
+ export function getGlobalFunctionLogging() {
6
+ return globalFunctionLogging;
7
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFunctionCallLogger = void 0;
4
+ function getFunctionCallLogger(logging) {
5
+ switch (logging) {
6
+ case "basic-text":
7
+ return [basicTextObserver];
8
+ case "detailed-object":
9
+ return [detailedObjectObserver];
10
+ case "detailed-json":
11
+ return [detailedJsonObserver];
12
+ case "off":
13
+ default:
14
+ return [];
15
+ }
16
+ }
17
+ exports.getFunctionCallLogger = getFunctionCallLogger;
18
+ const basicTextObserver = {
19
+ onFunctionEvent(event) {
20
+ // log based on event type:
21
+ switch (event.eventType) {
22
+ case "started": {
23
+ console.log(`[${event.timestamp.toISOString()}] ${event.callId} - ${event.functionType} ${event.eventType}`);
24
+ break;
25
+ }
26
+ case "finished": {
27
+ console.log(`[${event.timestamp.toISOString()}] ${event.callId} - ${event.functionType} ${event.eventType} in ${event.durationInMs}ms`);
28
+ break;
29
+ }
30
+ }
31
+ },
32
+ };
33
+ const detailedObjectObserver = {
34
+ onFunctionEvent(event) {
35
+ // Remove the "response" property from the result (if any):
36
+ if (event.eventType === "finished" &&
37
+ event.result != null &&
38
+ "response" in event.result &&
39
+ event.result?.response != null) {
40
+ event = {
41
+ ...event,
42
+ result: Object.fromEntries(Object.entries(event.result).filter(([k]) => k !== "response")
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ ),
45
+ };
46
+ }
47
+ // filter all undefined properties from event for cleaner console output:
48
+ event = Object.fromEntries(
49
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
50
+ Object.entries(event).filter(([_, v]) => v !== undefined));
51
+ console.log(event);
52
+ },
53
+ };
54
+ const detailedJsonObserver = {
55
+ onFunctionEvent(event) {
56
+ // Remove the "response" property from the result (if any):
57
+ if (event.eventType === "finished" &&
58
+ event.result != null &&
59
+ "response" in event.result &&
60
+ event.result?.response != null) {
61
+ event = {
62
+ ...event,
63
+ result: Object.fromEntries(Object.entries(event.result).filter(([k]) => k !== "response")
64
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
65
+ ),
66
+ };
67
+ }
68
+ // filter all undefined properties from event for cleaner console output:
69
+ event = Object.fromEntries(
70
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
71
+ Object.entries(event).filter(([_, v]) => v !== undefined));
72
+ console.log(JSON.stringify(event));
73
+ },
74
+ };
@@ -0,0 +1,3 @@
1
+ import { FunctionOptions } from "./FunctionOptions.js";
2
+ import { FunctionObserver } from "./FunctionObserver.js";
3
+ export declare function getFunctionCallLogger(logging: FunctionOptions["logging"]): Array<FunctionObserver>;
@@ -0,0 +1,70 @@
1
+ export function getFunctionCallLogger(logging) {
2
+ switch (logging) {
3
+ case "basic-text":
4
+ return [basicTextObserver];
5
+ case "detailed-object":
6
+ return [detailedObjectObserver];
7
+ case "detailed-json":
8
+ return [detailedJsonObserver];
9
+ case "off":
10
+ default:
11
+ return [];
12
+ }
13
+ }
14
+ const basicTextObserver = {
15
+ onFunctionEvent(event) {
16
+ // log based on event type:
17
+ switch (event.eventType) {
18
+ case "started": {
19
+ console.log(`[${event.timestamp.toISOString()}] ${event.callId} - ${event.functionType} ${event.eventType}`);
20
+ break;
21
+ }
22
+ case "finished": {
23
+ console.log(`[${event.timestamp.toISOString()}] ${event.callId} - ${event.functionType} ${event.eventType} in ${event.durationInMs}ms`);
24
+ break;
25
+ }
26
+ }
27
+ },
28
+ };
29
+ const detailedObjectObserver = {
30
+ onFunctionEvent(event) {
31
+ // Remove the "response" property from the result (if any):
32
+ if (event.eventType === "finished" &&
33
+ event.result != null &&
34
+ "response" in event.result &&
35
+ event.result?.response != null) {
36
+ event = {
37
+ ...event,
38
+ result: Object.fromEntries(Object.entries(event.result).filter(([k]) => k !== "response")
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
+ ),
41
+ };
42
+ }
43
+ // filter all undefined properties from event for cleaner console output:
44
+ event = Object.fromEntries(
45
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
46
+ Object.entries(event).filter(([_, v]) => v !== undefined));
47
+ console.log(event);
48
+ },
49
+ };
50
+ const detailedJsonObserver = {
51
+ onFunctionEvent(event) {
52
+ // Remove the "response" property from the result (if any):
53
+ if (event.eventType === "finished" &&
54
+ event.result != null &&
55
+ "response" in event.result &&
56
+ event.result?.response != null) {
57
+ event = {
58
+ ...event,
59
+ result: Object.fromEntries(Object.entries(event.result).filter(([k]) => k !== "response")
60
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
+ ),
62
+ };
63
+ }
64
+ // filter all undefined properties from event for cleaner console output:
65
+ event = Object.fromEntries(
66
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
67
+ Object.entries(event).filter(([_, v]) => v !== undefined));
68
+ console.log(JSON.stringify(event));
69
+ },
70
+ };
package/core/index.cjs CHANGED
@@ -14,12 +14,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./ConsoleLogger.cjs"), exports);
18
17
  __exportStar(require("./DefaultRun.cjs"), exports);
19
18
  __exportStar(require("./FunctionEvent.cjs"), exports);
20
19
  __exportStar(require("./FunctionEventSource.cjs"), exports);
21
20
  __exportStar(require("./FunctionObserver.cjs"), exports);
22
21
  __exportStar(require("./FunctionOptions.cjs"), exports);
22
+ __exportStar(require("./GlobalFunctionLogging.cjs"), exports);
23
23
  __exportStar(require("./GlobalFunctionObservers.cjs"), exports);
24
24
  __exportStar(require("./Run.cjs"), exports);
25
25
  __exportStar(require("./Vector.cjs"), exports);
package/core/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- export * from "./ConsoleLogger.js";
2
1
  export * from "./DefaultRun.js";
3
2
  export * from "./FunctionEvent.js";
4
3
  export * from "./FunctionEventSource.js";
5
4
  export * from "./FunctionObserver.js";
6
5
  export * from "./FunctionOptions.js";
6
+ export * from "./GlobalFunctionLogging.js";
7
7
  export * from "./GlobalFunctionObservers.js";
8
8
  export * from "./Run.js";
9
9
  export * from "./Vector.js";
package/core/index.js CHANGED
@@ -1,9 +1,9 @@
1
- export * from "./ConsoleLogger.js";
2
1
  export * from "./DefaultRun.js";
3
2
  export * from "./FunctionEvent.js";
4
3
  export * from "./FunctionEventSource.js";
5
4
  export * from "./FunctionObserver.js";
6
5
  export * from "./FunctionOptions.js";
6
+ export * from "./GlobalFunctionLogging.js";
7
7
  export * from "./GlobalFunctionObservers.js";
8
8
  export * from "./Run.js";
9
9
  export * from "./Vector.js";
@@ -7,6 +7,7 @@ export declare abstract class AbstractModel<SETTINGS extends ModelSettings> impl
7
7
  abstract readonly provider: string;
8
8
  abstract readonly modelName: string | null;
9
9
  get modelInformation(): ModelInformation;
10
+ abstract get settingsForEvent(): Partial<SETTINGS>;
10
11
  readonly settings: SETTINGS;
11
12
  abstract withSettings(additionalSettings: Partial<SETTINGS>): this;
12
13
  }
@@ -6,9 +6,14 @@ export interface ModelSettings {
6
6
  */
7
7
  observers?: Array<FunctionObserver>;
8
8
  }
9
- export interface Model<SETTINGS> {
9
+ export interface Model<SETTINGS extends ModelSettings> {
10
10
  modelInformation: ModelInformation;
11
11
  readonly settings: SETTINGS;
12
+ /**
13
+ * Returns settings that should be recorded in observability events.
14
+ * Security-related settings (e.g. API keys) should not be included here.
15
+ */
16
+ get settingsForEvent(): Partial<SETTINGS>;
12
17
  /**
13
18
  * The `withSettings` method creates a new model with the same configuration as the original model, but with the specified settings changed.
14
19
  *
@@ -9,13 +9,23 @@ import { SpeechSynthesisFinishedEvent, SpeechSynthesisStartedEvent } from "./syn
9
9
  import { TranscriptionFinishedEvent, TranscriptionStartedEvent } from "./transcribe-speech/TranscriptionEvent.js";
10
10
  export interface BaseModelCallStartedEvent extends BaseFunctionStartedEvent {
11
11
  model: ModelInformation;
12
- settings: unknown;
12
+ /**
13
+ * The main input to the model call. The type depends on the call type or model.
14
+ */
13
15
  input: unknown;
16
+ /**
17
+ * The model settings used for the call. The type depends on the model.
18
+ */
19
+ settings: unknown;
14
20
  }
15
21
  export type BaseModelCallFinishedEventResult = {
16
22
  status: "success";
17
23
  response: unknown;
18
24
  output: unknown;
25
+ /**
26
+ * Optional usage information for the model call. The type depends on the call type.
27
+ */
28
+ usage?: unknown;
19
29
  } | {
20
30
  status: "error";
21
31
  error: unknown;
@@ -24,8 +34,17 @@ export type BaseModelCallFinishedEventResult = {
24
34
  };
25
35
  export interface BaseModelCallFinishedEvent extends BaseFunctionFinishedEvent {
26
36
  model: ModelInformation;
27
- settings: unknown;
37
+ /**
38
+ * The main input to the model call. The type depends on the call type or model.
39
+ */
28
40
  input: unknown;
41
+ /**
42
+ * The model settings used for the call. The type depends on the model.
43
+ */
44
+ settings: unknown;
45
+ /**
46
+ * The result of the model call. Can be "success", "error", or "abort". Additional information is provided depending on the status.
47
+ */
29
48
  result: BaseModelCallFinishedEventResult;
30
49
  }
31
50
  export type ModelCallStartedEvent = ImageGenerationStartedEvent | JsonGenerationStartedEvent | SpeechSynthesisStartedEvent | TextEmbeddingStartedEvent | TextGenerationStartedEvent | TextStreamingStartedEvent | TranscriptionStartedEvent;
@@ -14,7 +14,7 @@ import { TextEmbeddingModel, TextEmbeddingModelSettings } from "./TextEmbeddingM
14
14
  * ]
15
15
  * );
16
16
  */
17
- export declare function embedTexts<RESPONSE, SETTINGS extends TextEmbeddingModelSettings>(model: TextEmbeddingModel<RESPONSE, SETTINGS>, texts: string[], options?: ModelFunctionOptions<SETTINGS>): ModelFunctionPromise<TextEmbeddingModel<RESPONSE, SETTINGS>, Vector[], RESPONSE[]>;
17
+ export declare function embedTexts<RESPONSE, SETTINGS extends TextEmbeddingModelSettings>(model: TextEmbeddingModel<RESPONSE, SETTINGS>, texts: string[], options?: ModelFunctionOptions<SETTINGS>): ModelFunctionPromise<Vector[], RESPONSE[]>;
18
18
  /**
19
19
  * Generate an embedding for a single text.
20
20
  *
@@ -24,4 +24,4 @@ export declare function embedTexts<RESPONSE, SETTINGS extends TextEmbeddingModel
24
24
  * "At first, Nox didn't know what to do with the pup."
25
25
  * );
26
26
  */
27
- export declare function embedText<RESPONSE, SETTINGS extends TextEmbeddingModelSettings>(model: TextEmbeddingModel<RESPONSE, SETTINGS>, text: string, options?: ModelFunctionOptions<SETTINGS>): ModelFunctionPromise<TextEmbeddingModel<RESPONSE, SETTINGS>, Vector, RESPONSE>;
27
+ export declare function embedText<RESPONSE, SETTINGS extends TextEmbeddingModelSettings>(model: TextEmbeddingModel<RESPONSE, SETTINGS>, text: string, options?: ModelFunctionOptions<SETTINGS>): ModelFunctionPromise<Vector, RESPONSE>;
@@ -1,23 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ModelFunctionPromise = exports.executeCall = void 0;
3
+ exports.executeCall = exports.ModelFunctionPromise = void 0;
4
4
  const nanoid_1 = require("nanoid");
5
5
  const FunctionEventSource_js_1 = require("../core/FunctionEventSource.cjs");
6
+ const GlobalFunctionLogging_js_1 = require("../core/GlobalFunctionLogging.cjs");
6
7
  const GlobalFunctionObservers_js_1 = require("../core/GlobalFunctionObservers.cjs");
8
+ const getFunctionCallLogger_js_1 = require("../core/getFunctionCallLogger.cjs");
7
9
  const DurationMeasurement_js_1 = require("../util/DurationMeasurement.cjs");
8
10
  const AbortError_js_1 = require("../util/api/AbortError.cjs");
9
11
  const runSafe_js_1 = require("../util/runSafe.cjs");
10
- function executeCall({ model, options, input, functionType, generateResponse, extractOutputValue, }) {
11
- return new ModelFunctionPromise(doExecuteCall({
12
- model,
13
- options,
14
- input,
15
- functionType,
16
- generateResponse,
17
- extractOutputValue,
18
- }));
19
- }
20
- exports.executeCall = executeCall;
21
12
  class ModelFunctionPromise extends Promise {
22
13
  constructor(fullPromise) {
23
14
  super((resolve) => {
@@ -52,11 +43,24 @@ class ModelFunctionPromise extends Promise {
52
43
  }
53
44
  }
54
45
  exports.ModelFunctionPromise = ModelFunctionPromise;
55
- async function doExecuteCall({ model, options, input, functionType, generateResponse, extractOutputValue, }) {
46
+ function executeCall({ model, options, input, functionType, generateResponse, extractOutputValue, extractUsage, }) {
47
+ return new ModelFunctionPromise(doExecuteCall({
48
+ model,
49
+ options,
50
+ input,
51
+ functionType,
52
+ generateResponse,
53
+ extractOutputValue,
54
+ extractUsage,
55
+ }));
56
+ }
57
+ exports.executeCall = executeCall;
58
+ async function doExecuteCall({ model, options, input, functionType, generateResponse, extractOutputValue, extractUsage, }) {
56
59
  if (options?.settings != null) {
57
60
  model = model.withSettings(options.settings);
58
61
  options = {
59
62
  functionId: options.functionId,
63
+ logging: options.logging,
60
64
  observers: options.observers,
61
65
  run: options.run,
62
66
  };
@@ -65,6 +69,7 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
65
69
  const settings = model.settings;
66
70
  const eventSource = new FunctionEventSource_js_1.FunctionEventSource({
67
71
  observers: [
72
+ ...(0, getFunctionCallLogger_js_1.getFunctionCallLogger)(options?.logging ?? (0, GlobalFunctionLogging_js_1.getGlobalFunctionLogging)()),
68
73
  ...(0, GlobalFunctionObservers_js_1.getGlobalFunctionObservers)(),
69
74
  ...(settings.observers ?? []),
70
75
  ...(run?.observers ?? []),
@@ -74,21 +79,21 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
74
79
  });
75
80
  const durationMeasurement = (0, DurationMeasurement_js_1.startDurationMeasurement)();
76
81
  const startMetadata = {
82
+ functionType,
77
83
  callId: `call-${(0, nanoid_1.nanoid)()}`,
78
84
  runId: run?.runId,
79
85
  sessionId: run?.sessionId,
80
86
  userId: run?.userId,
81
87
  functionId: options?.functionId,
82
88
  model: model.modelInformation,
83
- functionType,
89
+ settings: model.settingsForEvent,
84
90
  input,
85
- settings,
86
91
  timestamp: durationMeasurement.startDate,
87
92
  startTimestamp: durationMeasurement.startDate,
88
93
  };
89
94
  eventSource.notify({
90
- ...startMetadata,
91
95
  eventType: "started",
96
+ ...startMetadata,
92
97
  });
93
98
  const result = await (0, runSafe_js_1.runSafe)(() => generateResponse({
94
99
  functionId: options?.functionId,
@@ -96,8 +101,8 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
96
101
  run,
97
102
  }));
98
103
  const finishMetadata = {
99
- ...startMetadata,
100
104
  eventType: "finished",
105
+ ...startMetadata,
101
106
  finishTimestamp: new Date(),
102
107
  durationInMs: durationMeasurement.durationInMs,
103
108
  };
@@ -124,11 +129,13 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
124
129
  }
125
130
  const response = result.output;
126
131
  const output = extractOutputValue(response);
132
+ const usage = extractUsage?.(response);
127
133
  eventSource.notify({
128
134
  ...finishMetadata,
129
135
  eventType: "finished",
130
136
  result: {
131
137
  status: "success",
138
+ usage,
132
139
  response,
133
140
  output,
134
141
  },
@@ -1,39 +1,41 @@
1
1
  import { Model, ModelSettings } from "./Model.js";
2
2
  import { ModelCallStartedEvent } from "./ModelCallEvent.js";
3
3
  import { ModelFunctionOptions } from "./ModelFunctionOptions.js";
4
- export type CallMetadata<MODEL extends Model<unknown>> = {
4
+ import { ModelInformation } from "./ModelInformation.js";
5
+ export type ModelCallMetadata = {
5
6
  callId: string;
6
7
  runId?: string;
7
8
  sessionId?: string;
8
9
  userId?: string;
9
10
  functionId?: string;
10
- model: MODEL["modelInformation"];
11
11
  startTimestamp: Date;
12
12
  finishTimestamp: Date;
13
13
  durationInMs: number;
14
+ model: ModelInformation;
14
15
  };
15
- export declare function executeCall<SETTINGS extends ModelSettings, MODEL extends Model<SETTINGS>, OUTPUT, RESPONSE>({ model, options, input, functionType, generateResponse, extractOutputValue, }: {
16
- model: MODEL;
17
- options?: ModelFunctionOptions<SETTINGS>;
18
- input: unknown;
19
- functionType: ModelCallStartedEvent["functionType"];
20
- generateResponse: (options: ModelFunctionOptions<SETTINGS>) => PromiseLike<RESPONSE>;
21
- extractOutputValue: (response: RESPONSE) => OUTPUT;
22
- }): ModelFunctionPromise<MODEL, OUTPUT, RESPONSE>;
23
- export declare class ModelFunctionPromise<MODEL extends Model<any>, OUTPUT, RESPONSE> extends Promise<OUTPUT> {
16
+ export declare class ModelFunctionPromise<OUTPUT, RESPONSE> extends Promise<OUTPUT> {
24
17
  private fullPromise;
25
18
  private outputPromise;
26
19
  constructor(fullPromise: Promise<{
27
20
  output: OUTPUT;
28
21
  response: RESPONSE;
29
- metadata: CallMetadata<MODEL>;
22
+ metadata: ModelCallMetadata;
30
23
  }>);
31
24
  asFullResponse(): Promise<{
32
25
  output: OUTPUT;
33
26
  response: RESPONSE;
34
- metadata: CallMetadata<MODEL>;
27
+ metadata: ModelCallMetadata;
35
28
  }>;
36
29
  then<TResult1 = OUTPUT, TResult2 = never>(onfulfilled?: ((value: OUTPUT) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
37
30
  catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | undefined | null): Promise<OUTPUT | TResult>;
38
31
  finally(onfinally?: (() => void) | undefined | null): Promise<OUTPUT>;
39
32
  }
33
+ export declare function executeCall<SETTINGS extends ModelSettings, MODEL extends Model<SETTINGS>, OUTPUT, RESPONSE>({ model, options, input, functionType, generateResponse, extractOutputValue, extractUsage, }: {
34
+ model: MODEL;
35
+ options?: ModelFunctionOptions<SETTINGS>;
36
+ input: unknown;
37
+ functionType: ModelCallStartedEvent["functionType"];
38
+ generateResponse: (options: ModelFunctionOptions<SETTINGS>) => PromiseLike<RESPONSE>;
39
+ extractOutputValue: (response: RESPONSE) => OUTPUT;
40
+ extractUsage?: (response: RESPONSE) => unknown;
41
+ }): ModelFunctionPromise<OUTPUT, RESPONSE>;
@@ -1,19 +1,11 @@
1
1
  import { nanoid as createId } from "nanoid";
2
2
  import { FunctionEventSource } from "../core/FunctionEventSource.js";
3
+ import { getGlobalFunctionLogging } from "../core/GlobalFunctionLogging.js";
3
4
  import { getGlobalFunctionObservers } from "../core/GlobalFunctionObservers.js";
5
+ import { getFunctionCallLogger } from "../core/getFunctionCallLogger.js";
4
6
  import { startDurationMeasurement } from "../util/DurationMeasurement.js";
5
7
  import { AbortError } from "../util/api/AbortError.js";
6
8
  import { runSafe } from "../util/runSafe.js";
7
- export function executeCall({ model, options, input, functionType, generateResponse, extractOutputValue, }) {
8
- return new ModelFunctionPromise(doExecuteCall({
9
- model,
10
- options,
11
- input,
12
- functionType,
13
- generateResponse,
14
- extractOutputValue,
15
- }));
16
- }
17
9
  export class ModelFunctionPromise extends Promise {
18
10
  constructor(fullPromise) {
19
11
  super((resolve) => {
@@ -47,11 +39,23 @@ export class ModelFunctionPromise extends Promise {
47
39
  return this.outputPromise.finally(onfinally);
48
40
  }
49
41
  }
50
- async function doExecuteCall({ model, options, input, functionType, generateResponse, extractOutputValue, }) {
42
+ export function executeCall({ model, options, input, functionType, generateResponse, extractOutputValue, extractUsage, }) {
43
+ return new ModelFunctionPromise(doExecuteCall({
44
+ model,
45
+ options,
46
+ input,
47
+ functionType,
48
+ generateResponse,
49
+ extractOutputValue,
50
+ extractUsage,
51
+ }));
52
+ }
53
+ async function doExecuteCall({ model, options, input, functionType, generateResponse, extractOutputValue, extractUsage, }) {
51
54
  if (options?.settings != null) {
52
55
  model = model.withSettings(options.settings);
53
56
  options = {
54
57
  functionId: options.functionId,
58
+ logging: options.logging,
55
59
  observers: options.observers,
56
60
  run: options.run,
57
61
  };
@@ -60,6 +64,7 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
60
64
  const settings = model.settings;
61
65
  const eventSource = new FunctionEventSource({
62
66
  observers: [
67
+ ...getFunctionCallLogger(options?.logging ?? getGlobalFunctionLogging()),
63
68
  ...getGlobalFunctionObservers(),
64
69
  ...(settings.observers ?? []),
65
70
  ...(run?.observers ?? []),
@@ -69,21 +74,21 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
69
74
  });
70
75
  const durationMeasurement = startDurationMeasurement();
71
76
  const startMetadata = {
77
+ functionType,
72
78
  callId: `call-${createId()}`,
73
79
  runId: run?.runId,
74
80
  sessionId: run?.sessionId,
75
81
  userId: run?.userId,
76
82
  functionId: options?.functionId,
77
83
  model: model.modelInformation,
78
- functionType,
84
+ settings: model.settingsForEvent,
79
85
  input,
80
- settings,
81
86
  timestamp: durationMeasurement.startDate,
82
87
  startTimestamp: durationMeasurement.startDate,
83
88
  };
84
89
  eventSource.notify({
85
- ...startMetadata,
86
90
  eventType: "started",
91
+ ...startMetadata,
87
92
  });
88
93
  const result = await runSafe(() => generateResponse({
89
94
  functionId: options?.functionId,
@@ -91,8 +96,8 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
91
96
  run,
92
97
  }));
93
98
  const finishMetadata = {
94
- ...startMetadata,
95
99
  eventType: "finished",
100
+ ...startMetadata,
96
101
  finishTimestamp: new Date(),
97
102
  durationInMs: durationMeasurement.durationInMs,
98
103
  };
@@ -119,11 +124,13 @@ async function doExecuteCall({ model, options, input, functionType, generateResp
119
124
  }
120
125
  const response = result.output;
121
126
  const output = extractOutputValue(response);
127
+ const usage = extractUsage?.(response);
122
128
  eventSource.notify({
123
129
  ...finishMetadata,
124
130
  eventType: "finished",
125
131
  result: {
126
132
  status: "success",
133
+ usage,
127
134
  response,
128
135
  output,
129
136
  },
@@ -16,4 +16,4 @@ import { ImageGenerationModel, ImageGenerationModelSettings } from "./ImageGener
16
16
  * ]
17
17
  * );
18
18
  */
19
- export declare function generateImage<PROMPT, RESPONSE, SETTINGS extends ImageGenerationModelSettings>(model: ImageGenerationModel<PROMPT, RESPONSE, SETTINGS>, prompt: PROMPT, options?: ModelFunctionOptions<SETTINGS>): ModelFunctionPromise<ImageGenerationModel<PROMPT, RESPONSE, SETTINGS>, string, RESPONSE>;
19
+ export declare function generateImage<PROMPT, RESPONSE, SETTINGS extends ImageGenerationModelSettings>(model: ImageGenerationModel<PROMPT, RESPONSE, SETTINGS>, prompt: PROMPT, options?: ModelFunctionOptions<SETTINGS>): ModelFunctionPromise<string, RESPONSE>;
@@ -2,6 +2,22 @@ import { BaseModelCallFinishedEvent, BaseModelCallStartedEvent } from "../ModelC
2
2
  export interface JsonGenerationStartedEvent extends BaseModelCallStartedEvent {
3
3
  functionType: "json-generation" | "json-or-text-generation";
4
4
  }
5
+ export type JsonGenerationFinishedEventResult = {
6
+ status: "success";
7
+ response: unknown;
8
+ output: unknown;
9
+ usage?: {
10
+ promptTokens: number;
11
+ completionTokens: number;
12
+ totalTokens: number;
13
+ };
14
+ } | {
15
+ status: "error";
16
+ error: unknown;
17
+ } | {
18
+ status: "abort";
19
+ };
5
20
  export type JsonGenerationFinishedEvent = BaseModelCallFinishedEvent & {
6
21
  functionType: "json-generation" | "json-or-text-generation";
22
+ result: JsonGenerationFinishedEventResult;
7
23
  };
@@ -0,0 +1,13 @@
1
+ import { ModelFunctionOptions } from "../ModelFunctionOptions.js";
2
+ import { Model, ModelSettings } from "../Model.js";
3
+ export interface JsonGenerationModelSettings extends ModelSettings {
4
+ }
5
+ export interface JsonGenerationModel<PROMPT, RESPONSE, SETTINGS extends JsonGenerationModelSettings> extends Model<SETTINGS> {
6
+ generateJsonResponse(prompt: PROMPT, options?: ModelFunctionOptions<SETTINGS>): PromiseLike<RESPONSE>;
7
+ extractJson(response: RESPONSE): unknown;
8
+ extractUsage?(response: RESPONSE): {
9
+ promptTokens: number;
10
+ completionTokens: number;
11
+ totalTokens: number;
12
+ };
13
+ }