Skip to content
Snippets Groups Projects
Unverified Commit a285f8ba authored by Alex Yang's avatar Alex Yang Committed by GitHub
Browse files

feat: improve `ToolsFactory` type (#713)

parent 663821cd
No related branches found
No related tags found
No related merge requests found
import { WikipediaTool } from "./WikipediaTool.js";
export namespace ToolsFactory {
type ToolsMap = {
[Tools.Wikipedia]: typeof WikipediaTool;
};
export enum Tools {
Wikipedia = "wikipedia.WikipediaToolSpec",
}
export async function createTool<Tool extends Tools>(
key: Tool,
...params: ConstructorParameters<ToolsMap[Tool]>
): Promise<InstanceType<ToolsMap[Tool]>> {
if (key === Tools.Wikipedia) {
return new WikipediaTool(...params) as InstanceType<ToolsMap[Tool]>;
}
throw new Error(
`Sorry! Tool ${key} is not supported yet. Options: ${params}`,
);
}
export async function createTools<const Tool extends Tools>(record: {
[key in Tool]: ConstructorParameters<ToolsMap[Tool]>[1] extends any // backward compatibility for `create-llama` script // if parameters are an array, use them as is
? ConstructorParameters<ToolsMap[Tool]>[0]
: ConstructorParameters<ToolsMap[Tool]>;
}): Promise<InstanceType<ToolsMap[Tool]>[]> {
const tools: InstanceType<ToolsMap[Tool]>[] = [];
for (const key in record) {
const params = record[key];
tools.push(
await createTool(
key,
// @ts-expect-error
Array.isArray(params) ? params : [params],
),
);
}
return tools;
}
}
import { ToolsFactory } from "llamaindex/tools/ToolsFactory";
import { WikipediaTool } from "llamaindex/tools/WikipediaTool";
import { assertType, describe, test } from "vitest";
describe("ToolsFactory", async () => {
test("createTool", async () => {
await ToolsFactory.createTool(ToolsFactory.Tools.Wikipedia, {
metadata: {
name: "wikipedia_tool",
description: "A tool that uses a query engine to search Wikipedia.",
},
});
});
test("createTools", async () => {
await ToolsFactory.createTools({
[ToolsFactory.Tools.Wikipedia]: {
metadata: {
name: "wikipedia_tool",
description: "A tool that uses a query engine to search Wikipedia.",
},
},
});
});
test("type", () => {
assertType<
(
key: ToolsFactory.Tools.Wikipedia,
params: ConstructorParameters<typeof WikipediaTool>[0],
) => Promise<WikipediaTool>
>(ToolsFactory.createTool<ToolsFactory.Tools.Wikipedia>);
});
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment