modelfusion 0.71.0 → 0.73.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 (151) hide show
  1. package/README.md +57 -45
  2. package/core/FunctionEvent.d.ts +5 -5
  3. package/core/api/ApiCallError.cjs +2 -1
  4. package/core/api/ApiCallError.d.ts +3 -3
  5. package/core/api/ApiCallError.js +2 -1
  6. package/core/api/postToApi.cjs +10 -3
  7. package/core/api/postToApi.js +10 -3
  8. package/guard/guard.cjs +5 -4
  9. package/guard/guard.d.ts +1 -1
  10. package/guard/guard.js +5 -4
  11. package/model-function/ModelCallEvent.d.ts +2 -2
  12. package/model-function/generate-structure/StructureGenerationEvent.d.ts +2 -2
  13. package/model-function/generate-structure/StructureParseError.cjs +10 -0
  14. package/model-function/generate-structure/StructureParseError.d.ts +8 -0
  15. package/model-function/generate-structure/StructureParseError.js +10 -0
  16. package/model-function/generate-structure/index.cjs +0 -3
  17. package/model-function/generate-structure/index.d.ts +0 -3
  18. package/model-function/generate-structure/index.js +0 -3
  19. package/model-function/index.cjs +0 -1
  20. package/model-function/index.d.ts +0 -1
  21. package/model-function/index.js +0 -1
  22. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.d.ts +3 -3
  23. package/model-provider/ollama/OllamaError.cjs +21 -7
  24. package/model-provider/ollama/OllamaError.d.ts +10 -3
  25. package/model-provider/ollama/OllamaError.js +21 -7
  26. package/model-provider/ollama/OllamaTextGenerationModel.cjs +2 -2
  27. package/model-provider/ollama/OllamaTextGenerationModel.d.ts +5 -5
  28. package/model-provider/ollama/OllamaTextGenerationModel.js +2 -2
  29. package/model-provider/openai/chat/OpenAIChatMessage.cjs +16 -25
  30. package/model-provider/openai/chat/OpenAIChatMessage.d.ts +10 -28
  31. package/model-provider/openai/chat/OpenAIChatMessage.js +16 -25
  32. package/model-provider/openai/chat/OpenAIChatModel.cjs +2 -48
  33. package/model-provider/openai/chat/OpenAIChatModel.d.ts +15 -107
  34. package/model-provider/openai/chat/OpenAIChatModel.js +2 -48
  35. package/package.json +1 -1
  36. package/tool/Tool.cjs +5 -16
  37. package/tool/Tool.d.ts +9 -14
  38. package/tool/Tool.js +5 -16
  39. package/tool/ToolCall.d.ts +15 -0
  40. package/tool/ToolCallArgumentsValidationError.cjs +49 -0
  41. package/tool/ToolCallArgumentsValidationError.d.ts +23 -0
  42. package/tool/ToolCallArgumentsValidationError.js +45 -0
  43. package/tool/ToolCallError.cjs +34 -0
  44. package/tool/ToolCallError.d.ts +17 -0
  45. package/tool/ToolCallError.js +30 -0
  46. package/{model-function/generate-tool-call → tool}/ToolCallGenerationError.cjs +4 -4
  47. package/{model-function/generate-tool-call → tool}/ToolCallGenerationError.d.ts +1 -1
  48. package/{model-function/generate-tool-call → tool}/ToolCallGenerationError.js +2 -2
  49. package/{model-function/generate-tool-call/ToolCallParametersValidationError.cjs → tool/ToolCallParseError.cjs} +13 -13
  50. package/{model-function/generate-tool-call/ToolCallParametersValidationError.d.ts → tool/ToolCallParseError.d.ts} +6 -6
  51. package/{model-function/generate-tool-call/ToolCallParametersValidationError.js → tool/ToolCallParseError.js} +11 -11
  52. package/tool/ToolCallResult.d.ts +13 -0
  53. package/{model-function/generate-tool-call → tool}/ToolDefinition.d.ts +2 -2
  54. package/tool/ToolExecutionError.cjs +5 -4
  55. package/tool/ToolExecutionError.d.ts +4 -4
  56. package/tool/ToolExecutionError.js +5 -4
  57. package/tool/WebSearchTool.cjs +4 -4
  58. package/tool/WebSearchTool.d.ts +2 -2
  59. package/tool/WebSearchTool.js +4 -4
  60. package/tool/{ExecuteToolEvent.d.ts → execute-tool/ExecuteToolEvent.d.ts} +1 -1
  61. package/tool/{executeTool.cjs → execute-tool/executeTool.cjs} +15 -15
  62. package/tool/{executeTool.d.ts → execute-tool/executeTool.d.ts} +6 -6
  63. package/tool/{executeTool.js → execute-tool/executeTool.js} +15 -15
  64. package/tool/execute-tool/index.cjs +18 -0
  65. package/tool/execute-tool/index.d.ts +2 -0
  66. package/tool/execute-tool/index.js +2 -0
  67. package/tool/execute-tool/safeExecuteToolCall.cjs +34 -0
  68. package/tool/execute-tool/safeExecuteToolCall.d.ts +5 -0
  69. package/tool/execute-tool/safeExecuteToolCall.js +30 -0
  70. package/tool/generate-tool-call/TextGenerationToolCallModel.cjs +59 -0
  71. package/tool/generate-tool-call/TextGenerationToolCallModel.d.ts +35 -0
  72. package/tool/generate-tool-call/TextGenerationToolCallModel.js +55 -0
  73. package/{model-function → tool}/generate-tool-call/ToolCallGenerationEvent.d.ts +1 -1
  74. package/{model-function → tool}/generate-tool-call/ToolCallGenerationModel.d.ts +3 -3
  75. package/{model-function → tool}/generate-tool-call/generateToolCall.cjs +11 -11
  76. package/{model-function → tool}/generate-tool-call/generateToolCall.d.ts +3 -3
  77. package/{model-function → tool}/generate-tool-call/generateToolCall.js +11 -11
  78. package/tool/generate-tool-call/index.cjs +20 -0
  79. package/tool/generate-tool-call/index.d.ts +4 -0
  80. package/tool/generate-tool-call/index.js +4 -0
  81. package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/ToolCallsOrTextGenerationEvent.d.ts +1 -1
  82. package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/ToolCallsOrTextGenerationModel.d.ts +3 -3
  83. package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/generateToolCallsOrText.cjs +8 -8
  84. package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/generateToolCallsOrText.d.ts +3 -3
  85. package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/generateToolCallsOrText.js +8 -8
  86. package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/index.cjs +0 -7
  87. package/tool/generate-tool-calls-or-text/index.d.ts +3 -0
  88. package/tool/generate-tool-calls-or-text/index.js +3 -0
  89. package/tool/index.cjs +12 -7
  90. package/tool/index.d.ts +12 -7
  91. package/tool/index.js +12 -7
  92. package/tool/{UseToolEvent.d.ts → use-tool/UseToolEvent.d.ts} +1 -1
  93. package/tool/use-tool/index.cjs +18 -0
  94. package/tool/use-tool/index.d.ts +2 -0
  95. package/tool/use-tool/index.js +2 -0
  96. package/tool/use-tool/useTool.cjs +30 -0
  97. package/tool/use-tool/useTool.d.ts +16 -0
  98. package/tool/use-tool/useTool.js +26 -0
  99. package/tool/use-tools-or-generate-text/UseToolsOrGenerateTextEvent.d.ts +7 -0
  100. package/tool/use-tools-or-generate-text/index.cjs +18 -0
  101. package/tool/use-tools-or-generate-text/index.d.ts +2 -0
  102. package/tool/use-tools-or-generate-text/index.js +2 -0
  103. package/tool/use-tools-or-generate-text/useToolsOrGenerateText.cjs +48 -0
  104. package/tool/use-tools-or-generate-text/useToolsOrGenerateText.d.ts +18 -0
  105. package/tool/use-tools-or-generate-text/useToolsOrGenerateText.js +44 -0
  106. package/util/getErrorMessage.cjs +3 -0
  107. package/util/getErrorMessage.d.ts +1 -1
  108. package/util/getErrorMessage.js +3 -0
  109. package/model-function/generate-structure/NoSuchStructureError.cjs +0 -17
  110. package/model-function/generate-structure/NoSuchStructureError.d.ts +0 -4
  111. package/model-function/generate-structure/NoSuchStructureError.js +0 -13
  112. package/model-function/generate-structure/StructureOrTextGenerationModel.d.ts +0 -26
  113. package/model-function/generate-structure/generateStructureOrText.cjs +0 -54
  114. package/model-function/generate-structure/generateStructureOrText.d.ts +0 -97
  115. package/model-function/generate-structure/generateStructureOrText.js +0 -50
  116. package/model-function/generate-tool-call/ToolCall.d.ts +0 -5
  117. package/model-function/generate-tool-call/index.d.ts +0 -10
  118. package/model-function/generate-tool-call/index.js +0 -10
  119. package/tool/NoSuchToolError.cjs +0 -25
  120. package/tool/NoSuchToolError.d.ts +0 -10
  121. package/tool/NoSuchToolError.js +0 -21
  122. package/tool/UseToolOrGenerateTextEvent.d.ts +0 -7
  123. package/tool/useTool.cjs +0 -40
  124. package/tool/useTool.d.ts +0 -15
  125. package/tool/useTool.js +0 -36
  126. package/tool/useToolOrGenerateText.cjs +0 -50
  127. package/tool/useToolOrGenerateText.d.ts +0 -23
  128. package/tool/useToolOrGenerateText.js +0 -46
  129. /package/{model-function/generate-tool-call → tool}/NoSuchToolDefinitionError.cjs +0 -0
  130. /package/{model-function/generate-tool-call → tool}/NoSuchToolDefinitionError.d.ts +0 -0
  131. /package/{model-function/generate-tool-call → tool}/NoSuchToolDefinitionError.js +0 -0
  132. /package/{model-function/generate-tool-call → tool}/ToolCall.cjs +0 -0
  133. /package/{model-function/generate-tool-call → tool}/ToolCall.js +0 -0
  134. /package/{model-function/generate-structure/StructureOrTextGenerationModel.cjs → tool/ToolCallResult.cjs} +0 -0
  135. /package/{model-function/generate-structure/StructureOrTextGenerationModel.js → tool/ToolCallResult.js} +0 -0
  136. /package/{model-function/generate-tool-call → tool}/ToolDefinition.cjs +0 -0
  137. /package/{model-function/generate-tool-call → tool}/ToolDefinition.js +0 -0
  138. /package/tool/{ExecuteToolEvent.cjs → execute-tool/ExecuteToolEvent.cjs} +0 -0
  139. /package/tool/{ExecuteToolEvent.js → execute-tool/ExecuteToolEvent.js} +0 -0
  140. /package/{model-function → tool}/generate-tool-call/ToolCallGenerationEvent.cjs +0 -0
  141. /package/{model-function → tool}/generate-tool-call/ToolCallGenerationEvent.js +0 -0
  142. /package/{model-function → tool}/generate-tool-call/ToolCallGenerationModel.cjs +0 -0
  143. /package/{model-function → tool}/generate-tool-call/ToolCallGenerationModel.js +0 -0
  144. /package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/ToolCallsOrTextGenerationEvent.cjs +0 -0
  145. /package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/ToolCallsOrTextGenerationEvent.js +0 -0
  146. /package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/ToolCallsOrTextGenerationModel.cjs +0 -0
  147. /package/{model-function/generate-tool-call → tool/generate-tool-calls-or-text}/ToolCallsOrTextGenerationModel.js +0 -0
  148. /package/tool/{UseToolEvent.cjs → use-tool/UseToolEvent.cjs} +0 -0
  149. /package/tool/{UseToolEvent.js → use-tool/UseToolEvent.js} +0 -0
  150. /package/tool/{UseToolOrGenerateTextEvent.cjs → use-tools-or-generate-text/UseToolsOrGenerateTextEvent.cjs} +0 -0
  151. /package/tool/{UseToolOrGenerateTextEvent.js → use-tools-or-generate-text/UseToolsOrGenerateTextEvent.js} +0 -0
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  **ModelFusion** is a TypeScript library for building AI applications, chatbots, and agents.
16
16
 
17
17
  - **Vendor-neutral**: ModelFusion is a non-commercial open source project that is community-driven. You can use it with any supported provider.
18
- - **Multimodal**: ModelFusion supports a wide range of models including text generation, image generation, vision, text-to-speech, speech-to-text, and embedding models.
18
+ - **Multi-modal**: ModelFusion supports a wide range of models including text generation, image generation, vision, text-to-speech, speech-to-text, and embedding models.
19
19
  - **Streaming**: ModelFusion supports streaming for many generation models, e.g. text streaming, structure streaming, and full duplex speech streaming.
20
20
  - **Utility functions**: ModelFusion provides functionality for tools and tool usage, vector indices, and guards functions.
21
21
  - **Type inference and validation**: ModelFusion infers TypeScript types wherever possible and to validates model responses.
@@ -250,39 +250,6 @@ for await (const part of structureStream) {
250
250
 
251
251
  Providers: [OpenAI](https://modelfusion.dev/integration/model-provider/openai)
252
252
 
253
- ### [Generate Structure or Text](https://modelfusion.dev/guide/function/generate-structure-or-text)
254
-
255
- Generate a structure (or text as a fallback) using a prompt and multiple schemas.
256
- It either matches one of the schemas or is text reponse.
257
-
258
- ```ts
259
- const { structure, value, text } = await generateStructureOrText(
260
- new OpenAIChatModel({ model: "gpt-3.5-turbo", maxCompletionTokens: 1000 }),
261
- [
262
- new ZodStructureDefinition({
263
- name: "getCurrentWeather" as const, // mark 'as const' for type inference
264
- description: "Get the current weather in a given location",
265
- schema: z.object({
266
- location: z
267
- .string()
268
- .describe("The city and state, e.g. San Francisco, CA"),
269
- unit: z.enum(["celsius", "fahrenheit"]).optional(),
270
- }),
271
- }),
272
- new ZodStructureDefinition({
273
- name: "getContactInformation" as const,
274
- description: "Get the contact information for a given person",
275
- schema: z.object({
276
- name: z.string().describe("The name of the person"),
277
- }),
278
- }),
279
- ],
280
- [OpenAIChatMessage.user(query)]
281
- );
282
- ```
283
-
284
- Providers: [OpenAI](https://modelfusion.dev/integration/model-provider/openai)
285
-
286
253
  ### [Embed Value](https://modelfusion.dev/guide/function/embed)
287
254
 
288
255
  Create embeddings for text and other values. Embeddings are vectors that represent the essence of the values in the context of the model.
@@ -366,16 +333,16 @@ Tools are functions that can be executed by an AI model. They are useful for bui
366
333
 
367
334
  Predefined tools: [SerpAPI](https://modelfusion.dev/integration/tool/serpapi), [Google Custom Search](https://modelfusion.dev/integration/tool/google-custom-search)
368
335
 
369
- #### Create Tool
336
+ #### [Creating Tools](https://modelfusion.dev/guide/tools/create-tools)
370
337
 
371
- A tool is a function with a name, a description, and a schema for the input parameters.
338
+ A tool is comprised of an async execute function, a name, a description, and a schema for the input parameters.
372
339
 
373
340
  ```ts
374
341
  const calculator = new Tool({
375
342
  name: "calculator",
376
343
  description: "Execute a calculation",
377
344
 
378
- inputSchema: new ZodSchema(
345
+ parameters: new ZodSchema(
379
346
  z.object({
380
347
  a: z.number().describe("The first number."),
381
348
  b: z.number().describe("The second number."),
@@ -402,31 +369,76 @@ const calculator = new Tool({
402
369
  });
403
370
  ```
404
371
 
405
- #### useTool
372
+ #### [generateToolCall](https://modelfusion.dev/guide/tools/generate-tool-call)
406
373
 
407
- The model determines the parameters for the tool from the prompt and then executes it.
374
+ With `generateToolCall`, you can generate a tool call for a specific tool with a language model that supports tools calls (e.g. OpenAI Chat). This function does not execute the tools.
408
375
 
409
376
  ```ts
410
- const { tool, parameters, result } = await useTool(
377
+ const { id, name, args } = await generateToolCall(
411
378
  new OpenAIChatModel({ model: "gpt-3.5-turbo" }),
412
379
  calculator,
413
380
  [OpenAIChatMessage.user("What's fourteen times twelve?")]
414
381
  );
415
382
  ```
416
383
 
417
- #### useToolOrGenerateText
384
+ #### [generateToolCallsOrText](https://modelfusion.dev/guide/tools/generate-tool-calls-or-text)
418
385
 
419
- The model determines which tool to use and its parameters from the prompt and then executes it.
420
- Text is generated as a fallback.
386
+ With `generateToolCallsOrText`, you can ask a language model to generate several tool calls as well as text. The model will choose which tools (if any) should be called with which arguments. Both the text and the tool calls are optional. This function does not execute the tools.
421
387
 
422
388
  ```ts
423
- const { tool, parameters, result, text } = await useToolOrGenerateText(
389
+ const { text, toolCalls } = await generateToolCallsOrText(
424
390
  new OpenAIChatModel({ model: "gpt-3.5-turbo" }),
425
- [calculator /* and other tools... */],
391
+ [toolA, toolB, toolC],
392
+ [OpenAIChatMessage.user(query)]
393
+ );
394
+ ```
395
+
396
+ #### [executeTool](https://modelfusion.dev/guide/tools/execute-tool)
397
+
398
+ You can directly invoke a tool with `executeTool`:
399
+
400
+ ```ts
401
+ const result = await executeTool(calculator, {
402
+ a: 14,
403
+ b: 12,
404
+ operator: "*",
405
+ });
406
+ ```
407
+
408
+ #### [useTool](https://modelfusion.dev/guide/tools/use-tool)
409
+
410
+ With `useTool`, you can use a tool with a language model that supports tools calls (e.g. OpenAI Chat). `useTool` first generates a tool call and then executes the tool with the arguments.
411
+
412
+ ```ts
413
+ const { tool, toolCall, args, ok, result } = await useTool(
414
+ new OpenAIChatModel({ model: "gpt-3.5-turbo" }),
415
+ calculator,
416
+ [OpenAIChatMessage.user("What's fourteen times twelve?")]
417
+ );
418
+
419
+ console.log(`Tool call:`, toolCall);
420
+ console.log(`Tool:`, tool);
421
+ console.log(`Arguments:`, args);
422
+ console.log(`Ok:`, ok);
423
+ console.log(`Result or Error:`, result);
424
+ ```
425
+
426
+ #### [useToolsOrGenerateText](https://modelfusion.dev/guide/tools/use-tools-or-generate-text)
427
+
428
+ With `useToolsOrGenerateText`, you can ask a language model to generate several tool calls as well as text. The model will choose which tools (if any) should be called with which arguments. Both the text and the tool calls are optional. This function executes the tools.
429
+
430
+ ```ts
431
+ const { text, toolResults } = await useToolsOrGenerateText(
432
+ new OpenAIChatModel({ model: "gpt-3.5-turbo" }),
433
+ [calculator /* ... */],
426
434
  [OpenAIChatMessage.user("What's fourteen times twelve?")]
427
435
  );
428
436
  ```
429
437
 
438
+ #### [Agent Loop](https://modelfusion.dev/guide/tools/agent-loop)
439
+
440
+ You can use `useToolsOrGenerateText` to implement an agent loop that responds to user messages and executes tools. [Learn more](https://modelfusion.dev/guide/tools/agent-loop).
441
+
430
442
  ### [Vector Indices](https://modelfusion.dev/guide/vector-index)
431
443
 
432
444
  ```ts
@@ -1,11 +1,11 @@
1
- import { ExecuteFunctionFinishedEvent, ExecuteFunctionStartedEvent } from "./ExecuteFunctionEvent.js";
2
1
  import { GuardFinishedEvent, GuardStartedEvent } from "../guard/GuardEvent.js";
3
2
  import { ModelCallFinishedEvent, ModelCallStartedEvent } from "../model-function/ModelCallEvent.js";
4
3
  import { RetrieveFinishedEvent, RetrieveStartedEvent } from "../retriever/RetrieveEvent.js";
5
- import { ExecuteToolFinishedEvent, ExecuteToolStartedEvent } from "../tool/ExecuteToolEvent.js";
6
- import { UseToolFinishedEvent, UseToolStartedEvent } from "../tool/UseToolEvent.js";
7
- import { UseToolOrGenerateTextFinishedEvent, UseToolOrGenerateTextStartedEvent } from "../tool/UseToolOrGenerateTextEvent.js";
4
+ import { ExecuteToolFinishedEvent, ExecuteToolStartedEvent } from "../tool/execute-tool/ExecuteToolEvent.js";
5
+ import { UseToolFinishedEvent, UseToolStartedEvent } from "../tool/use-tool/UseToolEvent.js";
6
+ import { UseToolsOrGenerateTextFinishedEvent, UseToolsOrGenerateTextStartedEvent } from "../tool/use-tools-or-generate-text/UseToolsOrGenerateTextEvent.js";
8
7
  import { UpsertIntoVectorIndexFinishedEvent, UpsertIntoVectorIndexStartedEvent } from "../vector-index/UpsertIntoVectorIndexEvent.js";
8
+ import { ExecuteFunctionFinishedEvent, ExecuteFunctionStartedEvent } from "./ExecuteFunctionEvent.js";
9
9
  export interface BaseFunctionEvent {
10
10
  /**
11
11
  * Unique identifier for the function call.
@@ -82,4 +82,4 @@ export interface BaseFunctionFinishedEvent extends BaseFunctionEvent {
82
82
  */
83
83
  result: BaseFunctionFinishedEventResult;
84
84
  }
85
- export type FunctionEvent = ExecuteFunctionStartedEvent | ExecuteFunctionFinishedEvent | ExecuteToolStartedEvent | ExecuteToolFinishedEvent | GuardStartedEvent | GuardFinishedEvent | ModelCallStartedEvent | ModelCallFinishedEvent | RetrieveStartedEvent | RetrieveFinishedEvent | UpsertIntoVectorIndexStartedEvent | UpsertIntoVectorIndexFinishedEvent | UseToolStartedEvent | UseToolFinishedEvent | UseToolOrGenerateTextStartedEvent | UseToolOrGenerateTextFinishedEvent;
85
+ export type FunctionEvent = ExecuteFunctionStartedEvent | ExecuteFunctionFinishedEvent | ExecuteToolStartedEvent | ExecuteToolFinishedEvent | GuardStartedEvent | GuardFinishedEvent | ModelCallStartedEvent | ModelCallFinishedEvent | RetrieveStartedEvent | RetrieveFinishedEvent | UpsertIntoVectorIndexStartedEvent | UpsertIntoVectorIndexFinishedEvent | UseToolStartedEvent | UseToolFinishedEvent | UseToolsOrGenerateTextStartedEvent | UseToolsOrGenerateTextFinishedEvent;
@@ -2,7 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ApiCallError = void 0;
4
4
  class ApiCallError extends Error {
5
- constructor({ message, url, requestBodyValues, statusCode, cause, isRetryable = statusCode === 429 || statusCode >= 500, }) {
5
+ constructor({ message, url, requestBodyValues, statusCode, cause, isRetryable = statusCode != null &&
6
+ (statusCode === 429 || statusCode >= 500), }) {
6
7
  super(message);
7
8
  Object.defineProperty(this, "url", {
8
9
  enumerable: true,
@@ -1,14 +1,14 @@
1
1
  export declare class ApiCallError extends Error {
2
2
  readonly url: string;
3
3
  readonly requestBodyValues: unknown;
4
- readonly statusCode: number;
4
+ readonly statusCode?: number;
5
5
  readonly cause?: unknown;
6
6
  readonly isRetryable: boolean;
7
7
  constructor({ message, url, requestBodyValues, statusCode, cause, isRetryable, }: {
8
8
  message: string;
9
9
  url: string;
10
10
  requestBodyValues: unknown;
11
- statusCode: number;
11
+ statusCode?: number;
12
12
  cause?: unknown;
13
13
  isRetryable?: boolean;
14
14
  });
@@ -17,7 +17,7 @@ export declare class ApiCallError extends Error {
17
17
  message: string;
18
18
  url: string;
19
19
  requestBodyValues: unknown;
20
- statusCode: number;
20
+ statusCode: number | undefined;
21
21
  cause: unknown;
22
22
  isRetryable: boolean;
23
23
  };
@@ -1,5 +1,6 @@
1
1
  export class ApiCallError extends Error {
2
- constructor({ message, url, requestBodyValues, statusCode, cause, isRetryable = statusCode === 429 || statusCode >= 500, }) {
2
+ constructor({ message, url, requestBodyValues, statusCode, cause, isRetryable = statusCode != null &&
3
+ (statusCode === 429 || statusCode >= 500), }) {
3
4
  super(message);
4
5
  Object.defineProperty(this, "url", {
5
6
  enumerable: true,
@@ -108,9 +108,16 @@ const postToApi = async ({ url, headers = {}, body, successfulResponseHandler, f
108
108
  // unwrap original error when fetch failed (for easier debugging):
109
109
  if (error instanceof TypeError && error.message === "fetch failed") {
110
110
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
111
- if (error.cause != null) {
112
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
113
- throw error.cause;
111
+ const cause = error.cause;
112
+ if (cause != null) {
113
+ // Failed to connect to server:
114
+ throw new ApiCallError_js_1.ApiCallError({
115
+ message: `Cannot connect to API: ${cause.message}`,
116
+ cause,
117
+ url,
118
+ requestBodyValues: body.values,
119
+ isRetryable: true,
120
+ });
114
121
  }
115
122
  }
116
123
  throw error;
@@ -101,9 +101,16 @@ export const postToApi = async ({ url, headers = {}, body, successfulResponseHan
101
101
  // unwrap original error when fetch failed (for easier debugging):
102
102
  if (error instanceof TypeError && error.message === "fetch failed") {
103
103
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
- if (error.cause != null) {
105
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
- throw error.cause;
104
+ const cause = error.cause;
105
+ if (cause != null) {
106
+ // Failed to connect to server:
107
+ throw new ApiCallError({
108
+ message: `Cannot connect to API: ${cause.message}`,
109
+ cause,
110
+ url,
111
+ requestBodyValues: body.values,
112
+ isRetryable: true,
113
+ });
107
114
  }
108
115
  }
109
116
  throw error;
package/guard/guard.cjs CHANGED
@@ -4,14 +4,14 @@ exports.guard = void 0;
4
4
  const executeFunctionCall_js_1 = require("../core/executeFunctionCall.cjs");
5
5
  async function guard(execute, input, guards, options) {
6
6
  const guardList = Array.isArray(guards) ? guards : [guards];
7
- const maxRetries = options?.maxRetries ?? 1;
7
+ const maxAttempts = options?.maxAttempts ?? 2;
8
8
  return (0, executeFunctionCall_js_1.executeFunctionCall)({
9
9
  options,
10
10
  input,
11
11
  functionType: "guard",
12
12
  execute: async (options) => {
13
13
  let attempts = 0;
14
- while (attempts <= maxRetries) {
14
+ while (attempts < maxAttempts) {
15
15
  let result;
16
16
  try {
17
17
  result = {
@@ -70,8 +70,9 @@ async function guard(execute, input, guards, options) {
70
70
  }
71
71
  attempts++;
72
72
  }
73
- throw new Error(`Maximum retry attempts of ${maxRetries} reached ` +
74
- `without producing a valid output or handling an error after ${attempts} attempts.`);
73
+ // TODO dedicated error type
74
+ throw new Error(`Maximum attempts of ${maxAttempts} reached ` +
75
+ `without producing a valid output or handling an error.`);
75
76
  },
76
77
  });
77
78
  }
package/guard/guard.d.ts CHANGED
@@ -24,6 +24,6 @@ export type Guard<INPUT, OUTPUT> = ({ type, input, output, error, }: OutputResul
24
24
  action: "passThrough";
25
25
  } | undefined>;
26
26
  export declare function guard<INPUT, OUTPUT>(execute: (input: INPUT, options?: FunctionOptions) => PromiseLike<OUTPUT>, input: INPUT, guards: Guard<INPUT, OUTPUT> | Array<Guard<INPUT, OUTPUT>>, options?: FunctionOptions & {
27
- maxRetries: number;
27
+ maxAttempts: number;
28
28
  }): Promise<OUTPUT | undefined>;
29
29
  export {};
package/guard/guard.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { executeFunctionCall } from "../core/executeFunctionCall.js";
2
2
  export async function guard(execute, input, guards, options) {
3
3
  const guardList = Array.isArray(guards) ? guards : [guards];
4
- const maxRetries = options?.maxRetries ?? 1;
4
+ const maxAttempts = options?.maxAttempts ?? 2;
5
5
  return executeFunctionCall({
6
6
  options,
7
7
  input,
8
8
  functionType: "guard",
9
9
  execute: async (options) => {
10
10
  let attempts = 0;
11
- while (attempts <= maxRetries) {
11
+ while (attempts < maxAttempts) {
12
12
  let result;
13
13
  try {
14
14
  result = {
@@ -67,8 +67,9 @@ export async function guard(execute, input, guards, options) {
67
67
  }
68
68
  attempts++;
69
69
  }
70
- throw new Error(`Maximum retry attempts of ${maxRetries} reached ` +
71
- `without producing a valid output or handling an error after ${attempts} attempts.`);
70
+ // TODO dedicated error type
71
+ throw new Error(`Maximum attempts of ${maxAttempts} reached ` +
72
+ `without producing a valid output or handling an error.`);
72
73
  },
73
74
  });
74
75
  }
@@ -1,4 +1,6 @@
1
1
  import { BaseFunctionFinishedEvent, BaseFunctionStartedEvent } from "../core/FunctionEvent.js";
2
+ import { ToolCallGenerationFinishedEvent, ToolCallGenerationStartedEvent } from "../tool/generate-tool-call/ToolCallGenerationEvent.js";
3
+ import { ToolCallsOrTextGenerationFinishedEvent, ToolCallsOrTextGenerationStartedEvent } from "../tool/generate-tool-calls-or-text/ToolCallsOrTextGenerationEvent.js";
2
4
  import { ModelInformation } from "./ModelInformation.js";
3
5
  import { EmbeddingFinishedEvent, EmbeddingStartedEvent } from "./embed/EmbeddingEvent.js";
4
6
  import { ImageGenerationFinishedEvent, ImageGenerationStartedEvent } from "./generate-image/ImageGenerationEvent.js";
@@ -6,8 +8,6 @@ import { SpeechGenerationFinishedEvent, SpeechGenerationStartedEvent, SpeechStre
6
8
  import { StructureGenerationFinishedEvent, StructureGenerationStartedEvent } from "./generate-structure/StructureGenerationEvent.js";
7
9
  import { StructureStreamingFinishedEvent, StructureStreamingStartedEvent } from "./generate-structure/StructureStreamingEvent.js";
8
10
  import { TextGenerationFinishedEvent, TextGenerationStartedEvent, TextStreamingFinishedEvent, TextStreamingStartedEvent } from "./generate-text/TextGenerationEvent.js";
9
- import { ToolCallGenerationFinishedEvent, ToolCallGenerationStartedEvent } from "./generate-tool-call/ToolCallGenerationEvent.js";
10
- import { ToolCallsOrTextGenerationFinishedEvent, ToolCallsOrTextGenerationStartedEvent } from "./generate-tool-call/ToolCallsOrTextGenerationEvent.js";
11
11
  import { TranscriptionFinishedEvent, TranscriptionStartedEvent } from "./generate-transcription/TranscriptionEvent.js";
12
12
  export interface BaseModelCallStartedEvent extends BaseFunctionStartedEvent {
13
13
  model: ModelInformation;
@@ -1,6 +1,6 @@
1
1
  import { BaseModelCallFinishedEvent, BaseModelCallStartedEvent } from "../ModelCallEvent.js";
2
2
  export interface StructureGenerationStartedEvent extends BaseModelCallStartedEvent {
3
- functionType: "generate-structure" | "generate-structure-or-text";
3
+ functionType: "generate-structure";
4
4
  }
5
5
  export type StructureGenerationFinishedEventResult = {
6
6
  status: "success";
@@ -18,6 +18,6 @@ export type StructureGenerationFinishedEventResult = {
18
18
  status: "abort";
19
19
  };
20
20
  export type StructureGenerationFinishedEvent = BaseModelCallFinishedEvent & {
21
- functionType: "generate-structure" | "generate-structure-or-text";
21
+ functionType: "generate-structure";
22
22
  result: StructureGenerationFinishedEventResult;
23
23
  };
@@ -30,5 +30,15 @@ class StructureParseError extends Error {
30
30
  this.cause = cause;
31
31
  this.valueText = valueText;
32
32
  }
33
+ toJSON() {
34
+ return {
35
+ name: this.name,
36
+ cause: this.cause,
37
+ message: this.message,
38
+ stack: this.stack,
39
+ structureName: this.structureName,
40
+ valueText: this.valueText,
41
+ };
42
+ }
33
43
  }
34
44
  exports.StructureParseError = StructureParseError;
@@ -7,4 +7,12 @@ export declare class StructureParseError extends Error {
7
7
  valueText: string;
8
8
  cause: unknown;
9
9
  });
10
+ toJSON(): {
11
+ name: string;
12
+ cause: unknown;
13
+ message: string;
14
+ stack: string | undefined;
15
+ structureName: string;
16
+ valueText: string;
17
+ };
10
18
  }
@@ -27,4 +27,14 @@ export class StructureParseError extends Error {
27
27
  this.cause = cause;
28
28
  this.valueText = valueText;
29
29
  }
30
+ toJSON() {
31
+ return {
32
+ name: this.name,
33
+ cause: this.cause,
34
+ message: this.message,
35
+ stack: this.stack,
36
+ structureName: this.structureName,
37
+ valueText: this.valueText,
38
+ };
39
+ }
30
40
  }
@@ -14,14 +14,11 @@ 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("./NoSuchStructureError.cjs"), exports);
18
17
  __exportStar(require("./StructureFromTextGenerationModel.cjs"), exports);
19
18
  __exportStar(require("./StructureGenerationEvent.cjs"), exports);
20
19
  __exportStar(require("./StructureGenerationModel.cjs"), exports);
21
- __exportStar(require("./StructureOrTextGenerationModel.cjs"), exports);
22
20
  __exportStar(require("./StructureParseError.cjs"), exports);
23
21
  __exportStar(require("./StructureStreamingEvent.cjs"), exports);
24
22
  __exportStar(require("./StructureValidationError.cjs"), exports);
25
23
  __exportStar(require("./generateStructure.cjs"), exports);
26
- __exportStar(require("./generateStructureOrText.cjs"), exports);
27
24
  __exportStar(require("./streamStructure.cjs"), exports);
@@ -1,11 +1,8 @@
1
- export * from "./NoSuchStructureError.js";
2
1
  export * from "./StructureFromTextGenerationModel.js";
3
2
  export * from "./StructureGenerationEvent.js";
4
3
  export * from "./StructureGenerationModel.js";
5
- export * from "./StructureOrTextGenerationModel.js";
6
4
  export * from "./StructureParseError.js";
7
5
  export * from "./StructureStreamingEvent.js";
8
6
  export * from "./StructureValidationError.js";
9
7
  export * from "./generateStructure.js";
10
- export * from "./generateStructureOrText.js";
11
8
  export * from "./streamStructure.js";
@@ -1,11 +1,8 @@
1
- export * from "./NoSuchStructureError.js";
2
1
  export * from "./StructureFromTextGenerationModel.js";
3
2
  export * from "./StructureGenerationEvent.js";
4
3
  export * from "./StructureGenerationModel.js";
5
- export * from "./StructureOrTextGenerationModel.js";
6
4
  export * from "./StructureParseError.js";
7
5
  export * from "./StructureStreamingEvent.js";
8
6
  export * from "./StructureValidationError.js";
9
7
  export * from "./generateStructure.js";
10
- export * from "./generateStructureOrText.js";
11
8
  export * from "./streamStructure.js";
@@ -31,7 +31,6 @@ __exportStar(require("./generate-image/generateImage.cjs"), exports);
31
31
  __exportStar(require("./generate-speech/index.cjs"), exports);
32
32
  __exportStar(require("./generate-structure/index.cjs"), exports);
33
33
  __exportStar(require("./generate-text/index.cjs"), exports);
34
- __exportStar(require("./generate-tool-call/index.cjs"), exports);
35
34
  __exportStar(require("./generate-transcription/TranscriptionEvent.cjs"), exports);
36
35
  __exportStar(require("./generate-transcription/TranscriptionModel.cjs"), exports);
37
36
  __exportStar(require("./generate-transcription/generateTranscription.cjs"), exports);
@@ -15,7 +15,6 @@ export * from "./generate-image/generateImage.js";
15
15
  export * from "./generate-speech/index.js";
16
16
  export * from "./generate-structure/index.js";
17
17
  export * from "./generate-text/index.js";
18
- export * from "./generate-tool-call/index.js";
19
18
  export * from "./generate-transcription/TranscriptionEvent.js";
20
19
  export * from "./generate-transcription/TranscriptionModel.js";
21
20
  export * from "./generate-transcription/generateTranscription.js";
@@ -15,7 +15,6 @@ export * from "./generate-image/generateImage.js";
15
15
  export * from "./generate-speech/index.js";
16
16
  export * from "./generate-structure/index.js";
17
17
  export * from "./generate-text/index.js";
18
- export * from "./generate-tool-call/index.js";
19
18
  export * from "./generate-transcription/TranscriptionEvent.js";
20
19
  export * from "./generate-transcription/TranscriptionModel.js";
21
20
  export * from "./generate-transcription/generateTranscription.js";
@@ -19,8 +19,8 @@ export declare class Automatic1111ImageGenerationModel extends AbstractModel<Aut
19
19
  get settingsForEvent(): Partial<Automatic1111ImageGenerationSettings>;
20
20
  doGenerateImage(prompt: Automatic1111ImageGenerationPrompt, options?: FunctionOptions): Promise<{
21
21
  response: {
22
- parameters: {};
23
22
  images: string[];
23
+ parameters: {};
24
24
  info: string;
25
25
  };
26
26
  base64Image: string;
@@ -42,12 +42,12 @@ declare const Automatic1111ImageGenerationResponseSchema: z.ZodObject<{
42
42
  parameters: z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>;
43
43
  info: z.ZodString;
44
44
  }, "strip", z.ZodTypeAny, {
45
- parameters: {};
46
45
  images: string[];
46
+ parameters: {};
47
47
  info: string;
48
48
  }, {
49
- parameters: {};
50
49
  images: string[];
50
+ parameters: {};
51
51
  info: string;
52
52
  }>;
53
53
  export type Automatic1111ImageGenerationResponse = z.infer<typeof Automatic1111ImageGenerationResponseSchema>;
@@ -1,9 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.failedOllamaCallResponseHandler = exports.OllamaError = void 0;
4
+ const zod_1 = require("zod");
4
5
  const ApiCallError_js_1 = require("../../core/api/ApiCallError.cjs");
6
+ const ZodSchema_js_1 = require("../../core/schema/ZodSchema.cjs");
7
+ const parseJSON_js_1 = require("../../core/schema/parseJSON.cjs");
8
+ const ollamaErrorDataSchema = new ZodSchema_js_1.ZodSchema(zod_1.z.object({
9
+ error: zod_1.z.string(),
10
+ }));
5
11
  class OllamaError extends ApiCallError_js_1.ApiCallError {
6
- constructor({ statusCode, url, requestBodyValues, message, }) {
12
+ constructor({ statusCode, url, requestBodyValues, data, message = data.error, }) {
7
13
  super({ message, statusCode, requestBodyValues, url });
8
14
  Object.defineProperty(this, "data", {
9
15
  enumerable: true,
@@ -11,13 +17,21 @@ class OllamaError extends ApiCallError_js_1.ApiCallError {
11
17
  writable: true,
12
18
  value: void 0
13
19
  });
20
+ this.data = data;
14
21
  }
15
22
  }
16
23
  exports.OllamaError = OllamaError;
17
- const failedOllamaCallResponseHandler = async ({ response, url, requestBodyValues }) => new OllamaError({
18
- url,
19
- requestBodyValues,
20
- statusCode: response.status,
21
- message: await response.text(),
22
- });
24
+ const failedOllamaCallResponseHandler = async ({ response, url, requestBodyValues }) => {
25
+ const responseBody = await response.text();
26
+ const parsedError = (0, parseJSON_js_1.parseJSON)({
27
+ text: responseBody,
28
+ schema: ollamaErrorDataSchema,
29
+ });
30
+ return new OllamaError({
31
+ url,
32
+ requestBodyValues,
33
+ statusCode: response.status,
34
+ data: parsedError,
35
+ });
36
+ };
23
37
  exports.failedOllamaCallResponseHandler = failedOllamaCallResponseHandler;
@@ -1,12 +1,19 @@
1
1
  import { ApiCallError } from "../../core/api/ApiCallError.js";
2
2
  import { ResponseHandler } from "../../core/api/postToApi.js";
3
+ import { ZodSchema } from "../../core/schema/ZodSchema.js";
4
+ declare const ollamaErrorDataSchema: ZodSchema<{
5
+ error: string;
6
+ }>;
7
+ type OllamaErrorData = (typeof ollamaErrorDataSchema)["_type"];
3
8
  export declare class OllamaError extends ApiCallError {
4
- readonly data: string;
5
- constructor({ statusCode, url, requestBodyValues, message, }: {
6
- message: string;
9
+ readonly data: OllamaErrorData;
10
+ constructor({ statusCode, url, requestBodyValues, data, message, }: {
11
+ message?: string;
7
12
  statusCode: number;
8
13
  url: string;
9
14
  requestBodyValues: unknown;
15
+ data: OllamaErrorData;
10
16
  });
11
17
  }
12
18
  export declare const failedOllamaCallResponseHandler: ResponseHandler<ApiCallError>;
19
+ export {};
@@ -1,6 +1,12 @@
1
+ import { z } from "zod";
1
2
  import { ApiCallError } from "../../core/api/ApiCallError.js";
3
+ import { ZodSchema } from "../../core/schema/ZodSchema.js";
4
+ import { parseJSON } from "../../core/schema/parseJSON.js";
5
+ const ollamaErrorDataSchema = new ZodSchema(z.object({
6
+ error: z.string(),
7
+ }));
2
8
  export class OllamaError extends ApiCallError {
3
- constructor({ statusCode, url, requestBodyValues, message, }) {
9
+ constructor({ statusCode, url, requestBodyValues, data, message = data.error, }) {
4
10
  super({ message, statusCode, requestBodyValues, url });
5
11
  Object.defineProperty(this, "data", {
6
12
  enumerable: true,
@@ -8,11 +14,19 @@ export class OllamaError extends ApiCallError {
8
14
  writable: true,
9
15
  value: void 0
10
16
  });
17
+ this.data = data;
11
18
  }
12
19
  }
13
- export const failedOllamaCallResponseHandler = async ({ response, url, requestBodyValues }) => new OllamaError({
14
- url,
15
- requestBodyValues,
16
- statusCode: response.status,
17
- message: await response.text(),
18
- });
20
+ export const failedOllamaCallResponseHandler = async ({ response, url, requestBodyValues }) => {
21
+ const responseBody = await response.text();
22
+ const parsedError = parseJSON({
23
+ text: responseBody,
24
+ schema: ollamaErrorDataSchema,
25
+ });
26
+ return new OllamaError({
27
+ url,
28
+ requestBodyValues,
29
+ statusCode: response.status,
30
+ data: parsedError,
31
+ });
32
+ };
@@ -119,7 +119,7 @@ const ollamaTextGenerationResponseSchema = zod_1.z.object({
119
119
  prompt_eval_count: zod_1.z.number(),
120
120
  eval_count: zod_1.z.number(),
121
121
  eval_duration: zod_1.z.number(),
122
- context: zod_1.z.array(zod_1.z.number()),
122
+ context: zod_1.z.array(zod_1.z.number()).optional(),
123
123
  });
124
124
  const ollamaTextStreamingResponseSchema = new ZodSchema_js_1.ZodSchema(zod_1.z.discriminatedUnion("done", [
125
125
  zod_1.z.object({
@@ -140,7 +140,7 @@ const ollamaTextStreamingResponseSchema = new ZodSchema_js_1.ZodSchema(zod_1.z.d
140
140
  prompt_eval_duration: zod_1.z.number().optional(),
141
141
  eval_count: zod_1.z.number(),
142
142
  eval_duration: zod_1.z.number(),
143
- context: zod_1.z.array(zod_1.z.number()),
143
+ context: zod_1.z.array(zod_1.z.number()).optional(),
144
144
  }),
145
145
  ]));
146
146
  async function callOllamaTextGenerationAPI({ api = new OllamaApiConfiguration_js_1.OllamaApiConfiguration(), abortSignal, responseFormat, prompt, model, format, contextWindowSize, maxCompletionTokens, mirostat, mirostat_eta, mirostat_tau, num_gpu, num_gqa, num_threads, repeat_last_n, repeat_penalty, seed, stopSequences, temperature, tfs_z, top_k, top_p, system, template, context, raw, }) {