Skip to content

Commit

Permalink
append file tool fixed (TransformerOptimus#1293)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tarraann authored Sep 29, 2023
1 parent 73e5906 commit 0a24481
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions superagi/tools/file/append_file.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import os
from typing import Type
from typing import Type, Optional

from pydantic import BaseModel, Field

from superagi.helper.resource_helper import ResourceHelper
from superagi.models.agent_execution import AgentExecution
from superagi.tools.base_tool import BaseTool
from superagi.models.agent import Agent

from superagi.types.storage_types import StorageType
from superagi.config.config import get_config
from superagi.helper.s3_helper import S3Helper
from superagi.resource_manager.file_manager import FileManager

class AppendFileInput(BaseModel):
"""Input for CopyFileTool."""
Expand All @@ -30,6 +33,7 @@ class AppendFileTool(BaseTool):
agent_execution_id: int = None
args_schema: Type[BaseModel] = AppendFileInput
description: str = "Append text to a file"
resource_manager: Optional[FileManager] = None

def _execute(self, file_name: str, content: str):
"""
Expand All @@ -42,12 +46,24 @@ def _execute(self, file_name: str, content: str):
Returns:
success or error message.
"""

final_path = ResourceHelper.get_agent_write_resource_path(file_name, Agent.get_agent_from_id(
session=self.toolkit_config.session,
agent_id=self.agent_id),
AgentExecution.get_agent_execution_from_id(
session=self.toolkit_config.session,
agent_execution_id=self.agent_execution_id))

if StorageType.get_storage_type(get_config("STORAGE_TYPE", StorageType.FILE.value)) == StorageType.S3:
previous_content = self.get_previous_content(final_path)
if previous_content is None:
return "Append file only supported for .txt Files."
if not previous_content:
return "File not Found."
S3Helper().delete_file(final_path)
new_content = previous_content + content
return self.resource_manager.write_file(file_name, new_content)

try:
directory = os.path.dirname(final_path)
os.makedirs(directory, exist_ok=True)
Expand All @@ -56,3 +72,10 @@ def _execute(self, file_name: str, content: str):
return "File written to successfully."
except Exception as err:
return f"Error: {err}"

def get_previous_content(self, final_path):
if final_path.split('/')[-1].lower().endswith('.txt'):
try:
return S3Helper().read_from_s3(final_path)
except Exception:
return False

0 comments on commit 0a24481

Please sign in to comment.