createReadTool function

Tool<JsonMap, String> createReadTool(
  1. Genkit ai, {
  2. required ToolRuntime runtime,
})

Builds the tool that reads text files with line numbers.

Implementation

Tool<JsonMap, String> createReadTool(
  Genkit ai, {
  required ToolRuntime runtime,
}) {
  return defineTextTool(
    ai,
    runtime: runtime,
    name: 'read',
    description: _description,
    properties: <String, Object?>{
      'file_path': stringProperty('The absolute path of the file to read.'),
      'offset': integerProperty('The 1-based line number to start reading from. Only provide it for large files.'),
      'limit': integerProperty('The number of lines to read. Only provide it for large files.'),
    },
    required: <String>['file_path'],
    run: (input) async {
      final path = runtime.resolvePath(requireString(input, 'file_path'));
      final offset = readInt(input, 'offset') ?? 1;
      final limit = readInt(input, 'limit') ?? _defaultLineLimit;

      if (await FileSystemEntity.isDirectory(path)) {
        throw ToolFailure('$path is a directory. Use the glob tool or `ls` to list its contents.');
      }
      final file = File(path);
      if (!await file.exists()) {
        throw ToolFailure('File does not exist: $path');
      }

      runtime.startTool('read', runtime.displayPath(path));
      final String content;
      try {
        content = await file.readAsString();
      } on FileSystemException {
        throw ToolFailure('$path is not a UTF-8 text file and cannot be read with this tool.');
      }
      runtime.recordFileRead(path, content, await file.stat());

      if (content.isEmpty) {
        return '(The file exists but is empty.)';
      }
      return formatNumberedLines(
        content,
        offset: offset < 1 ? 1 : offset,
        limit: limit < 1 ? _defaultLineLimit : limit,
      );
    },
  );
}