createReadTool function
Builds the tool that reads text files from disk.
Implementation
Tool<JsonMap, String> createReadTool(
Genkit ai, {
required ToolRuntime runtime,
}) {
const toolName = 'read';
return ai.defineTool(
name: toolName,
description: 'Reads a text file from an absolute path.',
inputSchema: createJsonObjectSchema(
description: 'Input for the read tool.',
properties: <String, $Schema>{
'file_path': $Schema.string(
description: 'Absolute path to the file to read.',
),
'offset': $Schema.integer(
description: 'Optional 1-based starting line number.',
),
'limit': $Schema.integer(
description: 'Optional maximum number of lines to return.',
),
},
required: <String>['file_path'],
),
outputSchema: stringOutputSchema,
fn: (input, _) async {
final filePath = readString(input, 'file_path')?.trim();
final offset = readInt(input, 'offset') ?? 1;
final limit = readInt(input, 'limit');
if (filePath == null || filePath.isEmpty) {
const error = 'Error: `file_path` is required.';
runtime.endTool(toolName, error);
return error;
}
if (!_isAbsolutePath(filePath)) {
const error = 'Error: `file_path` must be an absolute path.';
runtime.endTool(toolName, error);
return error;
}
final file = File(filePath);
if (!await file.exists()) {
final error = 'Error: file not found at $filePath.';
runtime.endTool(toolName, error);
return error;
}
runtime.startTool(toolName, filePath);
final content = await file.readAsString();
final stat = await file.stat();
runtime.recordFileRead(file.path, content, stat);
final numbered = _formatNumberedLines(
content: content,
offset: offset < 1 ? 1 : offset,
limit: limit,
);
runtime.endTool(toolName, numbered);
return numbered;
},
);
}