From 92abe0b726845f4b7aacdd0b844f0dacb745265e Mon Sep 17 00:00:00 2001 From: Victor C Tavernari Date: Sun, 31 Mar 2024 23:32:40 +0100 Subject: [PATCH] Enhance file reading with error handling - Wrapped the file reading functionality inside a `_run` method. - Added error handling to return a descriptive error message if an exception occurs during file reading. --- .../tools/file_read_tool/file_read_tool.py | 57 ++++++++++++------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/src/crewai_tools/tools/file_read_tool/file_read_tool.py b/src/crewai_tools/tools/file_read_tool/file_read_tool.py index 8c7643852..38aeeeb2e 100644 --- a/src/crewai_tools/tools/file_read_tool/file_read_tool.py +++ b/src/crewai_tools/tools/file_read_tool/file_read_tool.py @@ -2,32 +2,45 @@ from typing import Optional, Type, Any from pydantic.v1 import BaseModel, Field from ..base_tool import BaseTool + class FixedFileReadToolSchema(BaseModel): - """Input for FileReadTool.""" - pass + """Input for FileReadTool.""" + pass + class FileReadToolSchema(FixedFileReadToolSchema): - """Input for FileReadTool.""" - file_path: str = Field(..., description="Mandatory file full path to read the file") + """Input for FileReadTool.""" + file_path: str = Field( + ..., + description="Mandatory file full path to read the file" + ) + class FileReadTool(BaseTool): - name: str = "Read a file's content" - description: str = "A tool that can be used to read a file's content." - args_schema: Type[BaseModel] = FileReadToolSchema - file_path: Optional[str] = None + name: str = "Read a file's content" + description: str = "A tool that can be used to read a file's content." + args_schema: Type[BaseModel] = FileReadToolSchema + file_path: Optional[str] = None - def __init__(self, file_path: Optional[str] = None, **kwargs): - super().__init__(**kwargs) - if file_path is not None: - self.file_path = file_path - self.description = f"A tool that can be used to read {file_path}'s content." - self.args_schema = FixedFileReadToolSchema - self._generate_description() + def __init__( + self, + file_path: Optional[str] = None, + **kwargs + ): + super().__init__(**kwargs) + if file_path is not None: + self.file_path = file_path + self.description = f"A tool that can be used to read {file_path}'s content." + self.args_schema = FixedFileReadToolSchema + self._generate_description() - def _run( - self, - **kwargs: Any, - ) -> Any: - file_path = kwargs.get('file_path', self.file_path) - with open(file_path, 'r') as file: - return file.read() \ No newline at end of file + def _run( + self, + **kwargs: Any, + ) -> Any: + try: + file_path = kwargs.get('file_path', self.file_path) + with open(file_path, 'r') as file: + return file.read() + except Exception as e: + return f"Fail to read the file {file_path}. Error: {e}"