mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-09 08:08:32 +00:00
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.
This commit is contained in:
@@ -2,32 +2,45 @@ from typing import Optional, Type, Any
|
|||||||
from pydantic.v1 import BaseModel, Field
|
from pydantic.v1 import BaseModel, Field
|
||||||
from ..base_tool import BaseTool
|
from ..base_tool import BaseTool
|
||||||
|
|
||||||
|
|
||||||
class FixedFileReadToolSchema(BaseModel):
|
class FixedFileReadToolSchema(BaseModel):
|
||||||
"""Input for FileReadTool."""
|
"""Input for FileReadTool."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class FileReadToolSchema(FixedFileReadToolSchema):
|
class FileReadToolSchema(FixedFileReadToolSchema):
|
||||||
"""Input for FileReadTool."""
|
"""Input for FileReadTool."""
|
||||||
file_path: str = Field(..., description="Mandatory file full path to read the file")
|
file_path: str = Field(
|
||||||
|
...,
|
||||||
|
description="Mandatory file full path to read the file"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class FileReadTool(BaseTool):
|
class FileReadTool(BaseTool):
|
||||||
name: str = "Read a file's content"
|
name: str = "Read a file's content"
|
||||||
description: str = "A tool that can be used to read a file's content."
|
description: str = "A tool that can be used to read a file's content."
|
||||||
args_schema: Type[BaseModel] = FileReadToolSchema
|
args_schema: Type[BaseModel] = FileReadToolSchema
|
||||||
file_path: Optional[str] = None
|
file_path: Optional[str] = None
|
||||||
|
|
||||||
def __init__(self, file_path: Optional[str] = None, **kwargs):
|
def __init__(
|
||||||
super().__init__(**kwargs)
|
self,
|
||||||
if file_path is not None:
|
file_path: Optional[str] = None,
|
||||||
self.file_path = file_path
|
**kwargs
|
||||||
self.description = f"A tool that can be used to read {file_path}'s content."
|
):
|
||||||
self.args_schema = FixedFileReadToolSchema
|
super().__init__(**kwargs)
|
||||||
self._generate_description()
|
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(
|
def _run(
|
||||||
self,
|
self,
|
||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
file_path = kwargs.get('file_path', self.file_path)
|
try:
|
||||||
with open(file_path, 'r') as file:
|
file_path = kwargs.get('file_path', self.file_path)
|
||||||
return file.read()
|
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}"
|
||||||
|
|||||||
Reference in New Issue
Block a user