Skip to content

Commit

Permalink
feat: create tool factory
Browse files Browse the repository at this point in the history
  • Loading branch information
thucpn committed Mar 15, 2024
1 parent 4a96da5 commit 1533fbc
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 3 deletions.
12 changes: 11 additions & 1 deletion helpers/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,17 @@ export const installTSTemplate = async ({
cwd: path.join(compPath, "engines", "typescript", "agent"),
});

// TODO: action to install tools
// Write tools_config.json
const configContent: Record<string, any> = {};
tools.forEach((tool) => {
configContent[tool.name] = tool.config ?? {};
});
const configFilePath = path.join(enginePath, "tools_config.json");
console.log(configFilePath)
await fs.writeFile(
configFilePath,
JSON.stringify(configContent, null, 2),
);
} else {
await copy("**", enginePath, {
parents: true,
Expand Down
5 changes: 4 additions & 1 deletion templates/components/engines/typescript/agent/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from "llamaindex";
import { getDataSource } from "./index";
import { STORAGE_CACHE_DIR } from "./constants.mjs";
import ToolFactory from "./tools";

export async function createChatEngine(llm: OpenAI) {
const index = await getDataSource(llm);
Expand All @@ -17,8 +18,10 @@ export async function createChatEngine(llm: OpenAI) {
},
});

const externalTools = await ToolFactory.list();

const agent = new OpenAIAgent({
tools: [queryEngineTool],
tools: [queryEngineTool, ...externalTools],
verbose: true,
llm,
});
Expand Down
36 changes: 35 additions & 1 deletion templates/components/engines/typescript/agent/tools.ts
Original file line number Diff line number Diff line change
@@ -1 +1,35 @@
// Load tools here
import { BaseTool } from "llamaindex";
import config from "./tool_config.json";

enum ExternalTool {
GoogleSearch = "google.GoogleSearchToolSpec",
Wikipedia = "wikipedia.WikipediaToolSpec",
}

type ToolConfig = { [key in ExternalTool]: Record<string, any> };

export default class ToolFactory {
private static async createTool(
key: ExternalTool,
options: Record<string, any>
): Promise<BaseTool> {
if (key === ExternalTool.Wikipedia) {
const WikipediaTool = (await import("llamaindex")).WikipediaTool;
const tool = new WikipediaTool();
return tool;
}

// TODO: Implement GoogleSearchToolSpec

throw new Error(`Sorry! Tool ${key} is not supported yet. Options: ${options}`);
}

public static async list(): Promise<BaseTool[]> {
const tools: BaseTool[] = [];
for (const [key, value] of Object.entries(config as ToolConfig)) {
const tool = await ToolFactory.createTool(key as ExternalTool, value);
tools.push(tool);
}
return tools;
}
}

0 comments on commit 1533fbc

Please sign in to comment.