|
| 1 | +import { StructuredTool } from "@langchain/core/tools"; |
| 2 | +import fsOperation from "fileSystem"; |
| 3 | +import { addedFolder } from "lib/openFolder"; |
| 4 | +import { z } from "zod"; |
| 5 | + |
| 6 | +/** |
| 7 | + * Tool for reading file contents in Acode |
| 8 | + */ |
| 9 | +class ReadFileTool extends StructuredTool { |
| 10 | + name = "readFile"; |
| 11 | + description = "Reads the content of the given file in the project."; |
| 12 | + schema = z.object({ |
| 13 | + path: z |
| 14 | + .string() |
| 15 | + .describe( |
| 16 | + "The relative path of the file to read. This path should never be absolute, and the first component of the path should always be a root directory in a project (opened in sidebar). For example, if root directories are 'directory1' and 'directory2', to access 'file.txt' in 'directory1', use 'directory1/file.txt'. To access 'file.txt' in 'directory2', use 'directory2/file.txt'.", |
| 17 | + ), |
| 18 | + startLine: z |
| 19 | + .number() |
| 20 | + .min(1) |
| 21 | + .optional() |
| 22 | + .describe("line number to start reading on (1-based index)"), |
| 23 | + endLine: z |
| 24 | + .number() |
| 25 | + .min(1) |
| 26 | + .optional() |
| 27 | + .describe("line number to end reading on (1-based index, inclusive)"), |
| 28 | + }); |
| 29 | + |
| 30 | + async _call({ path, startLine, endLine }) { |
| 31 | + try { |
| 32 | + // Split the path to get project name and file path |
| 33 | + const pathParts = path.split("/"); |
| 34 | + const projectName = pathParts[0]; |
| 35 | + const filePath = pathParts.slice(1).join("/"); |
| 36 | + |
| 37 | + // Find the project in addedFolder array |
| 38 | + const project = addedFolder.find( |
| 39 | + (folder) => folder.title === projectName, |
| 40 | + ); |
| 41 | + if (!project) { |
| 42 | + return `Error: Project '${projectName}' not found in opened projects`; |
| 43 | + } |
| 44 | + |
| 45 | + // Construct the full file URL |
| 46 | + const fileUrl = project.url + "/" + filePath; |
| 47 | + |
| 48 | + // Read the file content |
| 49 | + const content = await fsOperation(fileUrl).readFile("utf8"); |
| 50 | + |
| 51 | + // If startLine or endLine are specified, filter the content |
| 52 | + if (startLine !== undefined || endLine !== undefined) { |
| 53 | + const lines = content.split("\n"); |
| 54 | + const start = startLine ? startLine - 1 : 0; |
| 55 | + const end = endLine ? endLine : lines.length; |
| 56 | + return lines.slice(start, end).join("\n"); |
| 57 | + } |
| 58 | + |
| 59 | + return content; |
| 60 | + } catch (error) { |
| 61 | + return `Error reading file: ${error.message}`; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +export const readFile = new ReadFileTool(); |
0 commit comments