modelfusion 0.7.0 → 0.9.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 (78) hide show
  1. package/README.md +14 -4
  2. package/composed-function/index.cjs +0 -3
  3. package/composed-function/index.d.ts +0 -3
  4. package/composed-function/index.js +0 -3
  5. package/index.cjs +1 -0
  6. package/index.d.ts +1 -0
  7. package/index.js +1 -0
  8. package/model-function/Model.d.ts +2 -2
  9. package/model-function/ModelCallEvent.d.ts +4 -6
  10. package/model-function/SuccessfulModelCall.cjs +6 -3
  11. package/model-function/SuccessfulModelCall.d.ts +3 -3
  12. package/model-function/SuccessfulModelCall.js +6 -3
  13. package/model-function/executeCall.cjs +6 -6
  14. package/model-function/executeCall.js +6 -6
  15. package/model-function/generate-json/JsonGenerationEvent.d.ts +2 -2
  16. package/model-function/generate-json/generateJsonOrText.cjs +4 -4
  17. package/model-function/generate-json/generateJsonOrText.js +4 -4
  18. package/model-function/generate-text/streamText.cjs +7 -7
  19. package/model-function/generate-text/streamText.js +7 -7
  20. package/model-function/index.cjs +1 -1
  21. package/model-function/index.d.ts +1 -1
  22. package/model-function/index.js +1 -1
  23. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.d.ts +3 -3
  24. package/model-provider/openai/chat/OpenAIChatPrompt.d.ts +1 -1
  25. package/package.json +1 -1
  26. package/run/ConsoleLogger.cjs +2 -2
  27. package/run/ConsoleLogger.d.ts +5 -5
  28. package/run/ConsoleLogger.js +2 -2
  29. package/run/DefaultRun.cjs +7 -7
  30. package/run/DefaultRun.d.ts +6 -6
  31. package/run/DefaultRun.js +7 -7
  32. package/run/Run.d.ts +2 -2
  33. package/run/RunFunction.d.ts +0 -4
  34. package/run/RunFunctionEvent.d.ts +12 -0
  35. package/{model-function/ModelCallEventSource.cjs → run/RunFunctionEventSource.cjs} +7 -7
  36. package/run/RunFunctionEventSource.d.ts +13 -0
  37. package/{model-function/ModelCallEventSource.js → run/RunFunctionEventSource.js} +5 -5
  38. package/run/RunFunctionObserver.cjs +2 -0
  39. package/run/RunFunctionObserver.d.ts +5 -0
  40. package/run/RunFunctionObserver.js +1 -0
  41. package/run/index.cjs +3 -0
  42. package/run/index.d.ts +3 -0
  43. package/run/index.js +3 -0
  44. package/tool/ExecuteToolEvent.cjs +2 -0
  45. package/tool/ExecuteToolEvent.d.ts +22 -0
  46. package/tool/ExecuteToolEvent.js +1 -0
  47. package/{composed-function/use-tool → tool}/Tool.cjs +31 -0
  48. package/tool/Tool.d.ts +42 -0
  49. package/tool/Tool.js +70 -0
  50. package/tool/ToolExecutionError.cjs +31 -0
  51. package/tool/ToolExecutionError.d.ts +11 -0
  52. package/tool/ToolExecutionError.js +27 -0
  53. package/tool/WebSearchTool.cjs +43 -0
  54. package/tool/WebSearchTool.d.ts +81 -0
  55. package/tool/WebSearchTool.js +39 -0
  56. package/tool/executeTool.cjs +79 -0
  57. package/tool/executeTool.d.ts +23 -0
  58. package/tool/executeTool.js +75 -0
  59. package/tool/index.cjs +23 -0
  60. package/tool/index.d.ts +7 -0
  61. package/tool/index.js +7 -0
  62. package/tool/useTool.cjs +33 -0
  63. package/tool/useTool.d.ts +15 -0
  64. package/tool/useTool.js +29 -0
  65. package/tool/useToolOrGenerateText.cjs +38 -0
  66. package/{composed-function/use-tool/useTool.d.ts → tool/useToolOrGenerateText.d.ts} +2 -15
  67. package/tool/useToolOrGenerateText.js +34 -0
  68. package/composed-function/use-tool/Tool.d.ts +0 -15
  69. package/composed-function/use-tool/Tool.js +0 -39
  70. package/composed-function/use-tool/useTool.cjs +0 -62
  71. package/composed-function/use-tool/useTool.js +0 -57
  72. package/model-function/ModelCallEventSource.d.ts +0 -13
  73. package/model-function/ModelCallObserver.d.ts +0 -5
  74. /package/{model-function/ModelCallObserver.cjs → run/RunFunctionEvent.cjs} +0 -0
  75. /package/{model-function/ModelCallObserver.js → run/RunFunctionEvent.js} +0 -0
  76. /package/{composed-function/use-tool → tool}/NoSuchToolError.cjs +0 -0
  77. /package/{composed-function/use-tool → tool}/NoSuchToolError.d.ts +0 -0
  78. /package/{composed-function/use-tool → tool}/NoSuchToolError.js +0 -0
@@ -0,0 +1,81 @@
1
+ import { z } from "zod";
2
+ import { Tool } from "./Tool.js";
3
+ declare const INPUT_SCHEMA: z.ZodObject<{
4
+ query: z.ZodString;
5
+ }, "strip", z.ZodTypeAny, {
6
+ query: string;
7
+ }, {
8
+ query: string;
9
+ }>;
10
+ declare const OUTPUT_SCHEMA: z.ZodObject<{
11
+ results: z.ZodArray<z.ZodObject<{
12
+ title: z.ZodString;
13
+ link: z.ZodString;
14
+ snippet: z.ZodString;
15
+ }, "strip", z.ZodTypeAny, {
16
+ link: string;
17
+ title: string;
18
+ snippet: string;
19
+ }, {
20
+ link: string;
21
+ title: string;
22
+ snippet: string;
23
+ }>, "many">;
24
+ }, "strip", z.ZodTypeAny, {
25
+ results: {
26
+ link: string;
27
+ title: string;
28
+ snippet: string;
29
+ }[];
30
+ }, {
31
+ results: {
32
+ link: string;
33
+ title: string;
34
+ snippet: string;
35
+ }[];
36
+ }>;
37
+ /**
38
+ * @see https://serpapi.com/search-api
39
+ */
40
+ export declare class WebSearchTool<NAME extends string> extends Tool<NAME, z.infer<typeof INPUT_SCHEMA>, z.infer<typeof OUTPUT_SCHEMA>> {
41
+ static readonly INPUT_SCHEMA: z.ZodObject<{
42
+ query: z.ZodString;
43
+ }, "strip", z.ZodTypeAny, {
44
+ query: string;
45
+ }, {
46
+ query: string;
47
+ }>;
48
+ static readonly OUTPUT_SCHEMA: z.ZodObject<{
49
+ results: z.ZodArray<z.ZodObject<{
50
+ title: z.ZodString;
51
+ link: z.ZodString;
52
+ snippet: z.ZodString;
53
+ }, "strip", z.ZodTypeAny, {
54
+ link: string;
55
+ title: string;
56
+ snippet: string;
57
+ }, {
58
+ link: string;
59
+ title: string;
60
+ snippet: string;
61
+ }>, "many">;
62
+ }, "strip", z.ZodTypeAny, {
63
+ results: {
64
+ link: string;
65
+ title: string;
66
+ snippet: string;
67
+ }[];
68
+ }, {
69
+ results: {
70
+ link: string;
71
+ title: string;
72
+ snippet: string;
73
+ }[];
74
+ }>;
75
+ constructor(options: {
76
+ name: NAME;
77
+ description: string;
78
+ execute(input: z.infer<typeof INPUT_SCHEMA>): Promise<z.infer<typeof OUTPUT_SCHEMA>>;
79
+ });
80
+ }
81
+ export {};
@@ -0,0 +1,39 @@
1
+ import { z } from "zod";
2
+ import { Tool } from "./Tool.js";
3
+ const INPUT_SCHEMA = z.object({
4
+ query: z.string(),
5
+ });
6
+ const OUTPUT_SCHEMA = z.object({
7
+ results: z.array(z.object({
8
+ title: z.string(),
9
+ link: z.string().url(),
10
+ snippet: z.string(),
11
+ })),
12
+ });
13
+ /**
14
+ * @see https://serpapi.com/search-api
15
+ */
16
+ export class WebSearchTool extends Tool {
17
+ constructor(options) {
18
+ super({
19
+ name: options.name,
20
+ description: options.description,
21
+ inputSchema: INPUT_SCHEMA,
22
+ outputSchema: OUTPUT_SCHEMA,
23
+ execute: options.execute,
24
+ });
25
+ }
26
+ }
27
+ // expose the schemas to library consumers:
28
+ Object.defineProperty(WebSearchTool, "INPUT_SCHEMA", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: INPUT_SCHEMA
33
+ });
34
+ Object.defineProperty(WebSearchTool, "OUTPUT_SCHEMA", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: OUTPUT_SCHEMA
39
+ });
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeTool = void 0;
4
+ const nanoid_1 = require("nanoid");
5
+ const RunFunctionEventSource_js_1 = require("../run/RunFunctionEventSource.cjs");
6
+ const DurationMeasurement_js_1 = require("../util/DurationMeasurement.cjs");
7
+ const AbortError_js_1 = require("../util/api/AbortError.cjs");
8
+ const runSafe_js_1 = require("../util/runSafe.cjs");
9
+ const ToolExecutionError_js_1 = require("./ToolExecutionError.cjs");
10
+ async function executeTool(tool, input, options) {
11
+ const run = options?.run;
12
+ const eventSource = new RunFunctionEventSource_js_1.RunFunctionEventSource({
13
+ observers: run?.observers ?? [],
14
+ errorHandler: run?.errorHandler,
15
+ });
16
+ const durationMeasurement = (0, DurationMeasurement_js_1.startDurationMeasurement)();
17
+ const startMetadata = {
18
+ callId: `call-${(0, nanoid_1.nanoid)()}`,
19
+ runId: run?.runId,
20
+ sessionId: run?.sessionId,
21
+ userId: run?.userId,
22
+ functionId: options?.functionId,
23
+ startEpochSeconds: durationMeasurement.startEpochSeconds,
24
+ };
25
+ eventSource.notifyRunFunctionStarted({
26
+ type: "execute-tool-started",
27
+ metadata: startMetadata,
28
+ tool: tool,
29
+ input,
30
+ });
31
+ const result = await (0, runSafe_js_1.runSafe)(() => tool.execute(input, options));
32
+ const finishMetadata = {
33
+ ...startMetadata,
34
+ durationInMs: durationMeasurement.durationInMs,
35
+ };
36
+ if (!result.ok) {
37
+ if (result.isAborted) {
38
+ eventSource.notifyRunFunctionFinished({
39
+ type: "execute-tool-finished",
40
+ status: "abort",
41
+ metadata: finishMetadata,
42
+ tool: tool,
43
+ input,
44
+ });
45
+ throw new AbortError_js_1.AbortError();
46
+ }
47
+ eventSource.notifyRunFunctionFinished({
48
+ type: "execute-tool-finished",
49
+ status: "failure",
50
+ metadata: finishMetadata,
51
+ tool: tool,
52
+ input,
53
+ error: result.error,
54
+ });
55
+ throw new ToolExecutionError_js_1.ToolExecutionError({
56
+ toolName: tool.name,
57
+ input,
58
+ cause: result.error,
59
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
+ message: result.error?.message,
61
+ });
62
+ }
63
+ const output = result.output;
64
+ eventSource.notifyRunFunctionFinished({
65
+ type: "execute-tool-finished",
66
+ status: "success",
67
+ metadata: finishMetadata,
68
+ tool: tool,
69
+ input,
70
+ output,
71
+ });
72
+ return options?.fullResponse === true
73
+ ? {
74
+ output,
75
+ metadata: finishMetadata,
76
+ }
77
+ : output;
78
+ }
79
+ exports.executeTool = executeTool;
@@ -0,0 +1,23 @@
1
+ import { FunctionOptions } from "../model-function/FunctionOptions.js";
2
+ import { Tool } from "./Tool.js";
3
+ export type ExecuteToolMetadata = {
4
+ callId: string;
5
+ runId?: string;
6
+ sessionId?: string;
7
+ userId?: string;
8
+ functionId?: string;
9
+ startEpochSeconds: number;
10
+ durationInMs: number;
11
+ };
12
+ /**
13
+ * `executeTool` directly executes a tool with the given parameters.
14
+ */
15
+ export declare function executeTool<INPUT, OUTPUT>(tool: Tool<string, INPUT, OUTPUT>, input: INPUT, options: FunctionOptions<undefined> & {
16
+ fullResponse: true;
17
+ }): Promise<{
18
+ output: OUTPUT;
19
+ metadata: ExecuteToolMetadata;
20
+ }>;
21
+ export declare function executeTool<INPUT, OUTPUT>(tool: Tool<string, INPUT, OUTPUT>, input: INPUT, options?: FunctionOptions<undefined> & {
22
+ fullResponse?: false;
23
+ }): Promise<OUTPUT>;
@@ -0,0 +1,75 @@
1
+ import { nanoid as createId } from "nanoid";
2
+ import { RunFunctionEventSource } from "../run/RunFunctionEventSource.js";
3
+ import { startDurationMeasurement } from "../util/DurationMeasurement.js";
4
+ import { AbortError } from "../util/api/AbortError.js";
5
+ import { runSafe } from "../util/runSafe.js";
6
+ import { ToolExecutionError } from "./ToolExecutionError.js";
7
+ export async function executeTool(tool, input, options) {
8
+ const run = options?.run;
9
+ const eventSource = new RunFunctionEventSource({
10
+ observers: run?.observers ?? [],
11
+ errorHandler: run?.errorHandler,
12
+ });
13
+ const durationMeasurement = startDurationMeasurement();
14
+ const startMetadata = {
15
+ callId: `call-${createId()}`,
16
+ runId: run?.runId,
17
+ sessionId: run?.sessionId,
18
+ userId: run?.userId,
19
+ functionId: options?.functionId,
20
+ startEpochSeconds: durationMeasurement.startEpochSeconds,
21
+ };
22
+ eventSource.notifyRunFunctionStarted({
23
+ type: "execute-tool-started",
24
+ metadata: startMetadata,
25
+ tool: tool,
26
+ input,
27
+ });
28
+ const result = await runSafe(() => tool.execute(input, options));
29
+ const finishMetadata = {
30
+ ...startMetadata,
31
+ durationInMs: durationMeasurement.durationInMs,
32
+ };
33
+ if (!result.ok) {
34
+ if (result.isAborted) {
35
+ eventSource.notifyRunFunctionFinished({
36
+ type: "execute-tool-finished",
37
+ status: "abort",
38
+ metadata: finishMetadata,
39
+ tool: tool,
40
+ input,
41
+ });
42
+ throw new AbortError();
43
+ }
44
+ eventSource.notifyRunFunctionFinished({
45
+ type: "execute-tool-finished",
46
+ status: "failure",
47
+ metadata: finishMetadata,
48
+ tool: tool,
49
+ input,
50
+ error: result.error,
51
+ });
52
+ throw new ToolExecutionError({
53
+ toolName: tool.name,
54
+ input,
55
+ cause: result.error,
56
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
57
+ message: result.error?.message,
58
+ });
59
+ }
60
+ const output = result.output;
61
+ eventSource.notifyRunFunctionFinished({
62
+ type: "execute-tool-finished",
63
+ status: "success",
64
+ metadata: finishMetadata,
65
+ tool: tool,
66
+ input,
67
+ output,
68
+ });
69
+ return options?.fullResponse === true
70
+ ? {
71
+ output,
72
+ metadata: finishMetadata,
73
+ }
74
+ : output;
75
+ }
package/tool/index.cjs ADDED
@@ -0,0 +1,23 @@
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("./NoSuchToolError.cjs"), exports);
18
+ __exportStar(require("./Tool.cjs"), exports);
19
+ __exportStar(require("./ToolExecutionError.cjs"), exports);
20
+ __exportStar(require("./WebSearchTool.cjs"), exports);
21
+ __exportStar(require("./executeTool.cjs"), exports);
22
+ __exportStar(require("./useTool.cjs"), exports);
23
+ __exportStar(require("./useToolOrGenerateText.cjs"), exports);
@@ -0,0 +1,7 @@
1
+ export * from "./NoSuchToolError.js";
2
+ export * from "./Tool.js";
3
+ export * from "./ToolExecutionError.js";
4
+ export * from "./WebSearchTool.js";
5
+ export * from "./executeTool.js";
6
+ export * from "./useTool.js";
7
+ export * from "./useToolOrGenerateText.js";
package/tool/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./NoSuchToolError.js";
2
+ export * from "./Tool.js";
3
+ export * from "./ToolExecutionError.js";
4
+ export * from "./WebSearchTool.js";
5
+ export * from "./executeTool.js";
6
+ export * from "./useTool.js";
7
+ export * from "./useToolOrGenerateText.js";
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useTool = void 0;
4
+ const generateJson_js_1 = require("../model-function/generate-json/generateJson.cjs");
5
+ const executeTool_js_1 = require("./executeTool.cjs");
6
+ // In this file, using 'any' is required to allow for flexibility in the inputs. The actual types are
7
+ // retrieved through lookups such as TOOL["name"], such that any does not affect any client.
8
+ /* eslint-disable @typescript-eslint/no-explicit-any */
9
+ /**
10
+ * `useTool` uses `generateJson` to generate parameters for a tool and then executes the tool with the parameters.
11
+ *
12
+ * @returns The result contains the name of the tool (`tool` property),
13
+ * the parameters (`parameters` property, typed),
14
+ * and the result of the tool execution (`result` property, typed).
15
+ */
16
+ async function useTool(model, tool, prompt, options) {
17
+ const { value } = await (0, generateJson_js_1.generateJson)(model, {
18
+ name: tool.name,
19
+ description: tool.description,
20
+ schema: tool.inputSchema,
21
+ }, () => prompt(tool), {
22
+ ...(options ?? {}),
23
+ fullResponse: true,
24
+ });
25
+ return {
26
+ tool: tool.name,
27
+ parameters: value,
28
+ result: await (0, executeTool_js_1.executeTool)(tool, value, {
29
+ run: options?.run,
30
+ }),
31
+ };
32
+ }
33
+ exports.useTool = useTool;
@@ -0,0 +1,15 @@
1
+ import { FunctionOptions } from "../model-function/FunctionOptions.js";
2
+ import { GenerateJsonModel, GenerateJsonModelSettings, GenerateJsonPrompt } from "../model-function/generate-json/GenerateJsonModel.js";
3
+ import { Tool } from "./Tool.js";
4
+ /**
5
+ * `useTool` uses `generateJson` to generate parameters for a tool and then executes the tool with the parameters.
6
+ *
7
+ * @returns The result contains the name of the tool (`tool` property),
8
+ * the parameters (`parameters` property, typed),
9
+ * and the result of the tool execution (`result` property, typed).
10
+ */
11
+ export declare function useTool<PROMPT, RESPONSE, SETTINGS extends GenerateJsonModelSettings, TOOL extends Tool<any, any, any>>(model: GenerateJsonModel<PROMPT, RESPONSE, SETTINGS>, tool: TOOL, prompt: (tool: TOOL) => PROMPT & GenerateJsonPrompt<RESPONSE>, options?: FunctionOptions<SETTINGS>): Promise<{
12
+ tool: TOOL["name"];
13
+ parameters: TOOL["inputSchema"];
14
+ result: Awaited<ReturnType<TOOL["execute"]>>;
15
+ }>;
@@ -0,0 +1,29 @@
1
+ import { generateJson } from "../model-function/generate-json/generateJson.js";
2
+ import { executeTool } from "./executeTool.js";
3
+ // In this file, using 'any' is required to allow for flexibility in the inputs. The actual types are
4
+ // retrieved through lookups such as TOOL["name"], such that any does not affect any client.
5
+ /* eslint-disable @typescript-eslint/no-explicit-any */
6
+ /**
7
+ * `useTool` uses `generateJson` to generate parameters for a tool and then executes the tool with the parameters.
8
+ *
9
+ * @returns The result contains the name of the tool (`tool` property),
10
+ * the parameters (`parameters` property, typed),
11
+ * and the result of the tool execution (`result` property, typed).
12
+ */
13
+ export async function useTool(model, tool, prompt, options) {
14
+ const { value } = await generateJson(model, {
15
+ name: tool.name,
16
+ description: tool.description,
17
+ schema: tool.inputSchema,
18
+ }, () => prompt(tool), {
19
+ ...(options ?? {}),
20
+ fullResponse: true,
21
+ });
22
+ return {
23
+ tool: tool.name,
24
+ parameters: value,
25
+ result: await executeTool(tool, value, {
26
+ run: options?.run,
27
+ }),
28
+ };
29
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useToolOrGenerateText = void 0;
4
+ const generateJsonOrText_js_1 = require("../model-function/generate-json/generateJsonOrText.cjs");
5
+ const NoSuchToolError_js_1 = require("./NoSuchToolError.cjs");
6
+ const executeTool_js_1 = require("./executeTool.cjs");
7
+ async function useToolOrGenerateText(model, tools, prompt, options) {
8
+ const expandedPrompt = prompt(tools);
9
+ const modelResponse = await (0, generateJsonOrText_js_1.generateJsonOrText)(model, tools.map((tool) => ({
10
+ name: tool.name,
11
+ description: tool.description,
12
+ schema: tool.inputSchema,
13
+ })), () => expandedPrompt, options);
14
+ const { schema, text } = modelResponse;
15
+ if (schema == null) {
16
+ return {
17
+ tool: null,
18
+ parameters: null,
19
+ result: null,
20
+ text,
21
+ };
22
+ }
23
+ const tool = tools.find((tool) => tool.name === schema);
24
+ if (tool == null) {
25
+ throw new NoSuchToolError_js_1.NoSuchToolError(schema.toString());
26
+ }
27
+ const toolParameters = modelResponse.value;
28
+ const result = await (0, executeTool_js_1.executeTool)(tool, toolParameters, {
29
+ run: options?.run,
30
+ });
31
+ return {
32
+ tool: schema,
33
+ result,
34
+ parameters: toolParameters,
35
+ text: text, // string | null is the expected value here
36
+ };
37
+ }
38
+ exports.useToolOrGenerateText = useToolOrGenerateText;
@@ -1,19 +1,6 @@
1
- import { FunctionOptions } from "../../model-function/FunctionOptions.js";
2
- import { GenerateJsonModel, GenerateJsonModelSettings, GenerateJsonPrompt } from "../../model-function/generate-json/GenerateJsonModel.js";
3
- import { GenerateJsonOrTextModel, GenerateJsonOrTextModelSettings, GenerateJsonOrTextPrompt } from "../../model-function/generate-json/GenerateJsonOrTextModel.js";
1
+ import { FunctionOptions } from "../model-function/FunctionOptions.js";
2
+ import { GenerateJsonOrTextModel, GenerateJsonOrTextModelSettings, GenerateJsonOrTextPrompt } from "../model-function/generate-json/GenerateJsonOrTextModel.js";
4
3
  import { Tool } from "./Tool.js";
5
- /**
6
- * `useTool` uses `generateJson` to generate parameters for a tool and then executes the tool with the parameters.
7
- *
8
- * @returns The result contains the name of the tool (`tool` property),
9
- * the parameters (`parameters` property, typed),
10
- * and the result of the tool execution (`result` property, typed).
11
- */
12
- export declare function useTool<PROMPT, RESPONSE, SETTINGS extends GenerateJsonModelSettings, TOOL extends Tool<any, any, any>>(model: GenerateJsonModel<PROMPT, RESPONSE, SETTINGS>, tool: TOOL, prompt: (tool: TOOL) => PROMPT & GenerateJsonPrompt<RESPONSE>, options?: FunctionOptions<SETTINGS>): Promise<{
13
- tool: TOOL["name"];
14
- parameters: TOOL["inputSchema"];
15
- result: Awaited<ReturnType<TOOL["execute"]>>;
16
- }>;
17
4
  type ToolArray<T extends Tool<any, any, any>[]> = T;
18
5
  type ToToolMap<T extends ToolArray<Tool<any, any, any>[]>> = {
19
6
  [K in T[number]["name"]]: Extract<T[number], Tool<K, any, any>>;
@@ -0,0 +1,34 @@
1
+ import { generateJsonOrText } from "../model-function/generate-json/generateJsonOrText.js";
2
+ import { NoSuchToolError } from "./NoSuchToolError.js";
3
+ import { executeTool } from "./executeTool.js";
4
+ export async function useToolOrGenerateText(model, tools, prompt, options) {
5
+ const expandedPrompt = prompt(tools);
6
+ const modelResponse = await generateJsonOrText(model, tools.map((tool) => ({
7
+ name: tool.name,
8
+ description: tool.description,
9
+ schema: tool.inputSchema,
10
+ })), () => expandedPrompt, options);
11
+ const { schema, text } = modelResponse;
12
+ if (schema == null) {
13
+ return {
14
+ tool: null,
15
+ parameters: null,
16
+ result: null,
17
+ text,
18
+ };
19
+ }
20
+ const tool = tools.find((tool) => tool.name === schema);
21
+ if (tool == null) {
22
+ throw new NoSuchToolError(schema.toString());
23
+ }
24
+ const toolParameters = modelResponse.value;
25
+ const result = await executeTool(tool, toolParameters, {
26
+ run: options?.run,
27
+ });
28
+ return {
29
+ tool: schema,
30
+ result,
31
+ parameters: toolParameters,
32
+ text: text, // string | null is the expected value here
33
+ };
34
+ }
@@ -1,15 +0,0 @@
1
- import { z } from "zod";
2
- import { SchemaDefinition } from "../../model-function/generate-json/SchemaDefinition.js";
3
- export declare class Tool<NAME extends string, INPUT, OUTPUT> {
4
- readonly name: NAME;
5
- readonly description: string;
6
- readonly inputSchema: z.ZodSchema<INPUT>;
7
- readonly execute: (input: INPUT) => PromiseLike<OUTPUT>;
8
- constructor(options: {
9
- name: NAME;
10
- description: string;
11
- inputSchema: z.ZodSchema<INPUT>;
12
- execute(input: INPUT): Promise<OUTPUT>;
13
- });
14
- get inputSchemaDefinition(): SchemaDefinition<NAME, INPUT>;
15
- }
@@ -1,39 +0,0 @@
1
- export class Tool {
2
- constructor(options) {
3
- Object.defineProperty(this, "name", {
4
- enumerable: true,
5
- configurable: true,
6
- writable: true,
7
- value: void 0
8
- });
9
- Object.defineProperty(this, "description", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: void 0
14
- });
15
- Object.defineProperty(this, "inputSchema", {
16
- enumerable: true,
17
- configurable: true,
18
- writable: true,
19
- value: void 0
20
- });
21
- Object.defineProperty(this, "execute", {
22
- enumerable: true,
23
- configurable: true,
24
- writable: true,
25
- value: void 0
26
- });
27
- this.name = options.name;
28
- this.description = options.description;
29
- this.inputSchema = options.inputSchema;
30
- this.execute = options.execute;
31
- }
32
- get inputSchemaDefinition() {
33
- return {
34
- name: this.name,
35
- description: this.description,
36
- schema: this.inputSchema,
37
- };
38
- }
39
- }
@@ -1,62 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useToolOrGenerateText = exports.useTool = void 0;
4
- const generateJson_js_1 = require("../../model-function/generate-json/generateJson.cjs");
5
- const generateJsonOrText_js_1 = require("../../model-function/generate-json/generateJsonOrText.cjs");
6
- const NoSuchToolError_js_1 = require("./NoSuchToolError.cjs");
7
- // In this file, using 'any' is required to allow for flexibility in the inputs. The actual types are
8
- // retrieved through lookups such as TOOL["name"], such that any does not affect any client.
9
- /* eslint-disable @typescript-eslint/no-explicit-any */
10
- /**
11
- * `useTool` uses `generateJson` to generate parameters for a tool and then executes the tool with the parameters.
12
- *
13
- * @returns The result contains the name of the tool (`tool` property),
14
- * the parameters (`parameters` property, typed),
15
- * and the result of the tool execution (`result` property, typed).
16
- */
17
- async function useTool(model, tool, prompt, options) {
18
- const { value } = await (0, generateJson_js_1.generateJson)(model, {
19
- name: tool.name,
20
- description: tool.description,
21
- schema: tool.inputSchema,
22
- }, () => prompt(tool), {
23
- ...(options ?? {}),
24
- fullResponse: true,
25
- });
26
- return {
27
- tool: tool.name,
28
- parameters: value,
29
- result: await tool.execute(value),
30
- };
31
- }
32
- exports.useTool = useTool;
33
- async function useToolOrGenerateText(model, tools, prompt, options) {
34
- const expandedPrompt = prompt(tools);
35
- const modelResponse = await (0, generateJsonOrText_js_1.generateJsonOrText)(model, tools.map((tool) => ({
36
- name: tool.name,
37
- description: tool.description,
38
- schema: tool.inputSchema,
39
- })), () => expandedPrompt, options);
40
- const { schema, text } = modelResponse;
41
- if (schema == null) {
42
- return {
43
- tool: null,
44
- parameters: null,
45
- result: null,
46
- text,
47
- };
48
- }
49
- const tool = tools.find((tool) => tool.name === schema);
50
- if (tool == null) {
51
- throw new NoSuchToolError_js_1.NoSuchToolError(schema.toString());
52
- }
53
- const toolParameters = modelResponse.value;
54
- const result = await tool.execute(toolParameters);
55
- return {
56
- tool: schema,
57
- result,
58
- parameters: toolParameters,
59
- text: text, // string | null is the expected value here
60
- };
61
- }
62
- exports.useToolOrGenerateText = useToolOrGenerateText;