Prerequisites

  • Python 3.10 or higher
  • PraisonAI Agents package installed
  • Basic understanding of file operations

File Tools

Use File Tools to perform file system operations with AI agents.

1

Install Dependencies

First, install the required package:

pip install praisonaiagents
2

Import Components

Import the necessary components:

from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file
3

Create Agent

Create a file management agent:

file_agent = Agent(
    name="FileManager",
    role="File System Specialist",
    goal="Manage files and directories efficiently.",
    backstory="Expert in file system operations and organization.",
    tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file],
    self_reflect=False
)
4

Define Task

Define the file management task:

file_task = Task(
    description="Organize files in the downloads directory by file type.",
    expected_output="Organized directory structure with categorized files.",
    agent=file_agent,
    name="organize_files"
)
5

Run Agent

Initialize and run the agent:

agents = PraisonAIAgents(
    agents=[file_agent],
    tasks=[file_task],
    process="sequential"
)
agents.start()

Understanding File Tools

What are File Tools?

File Tools provide file system management capabilities for AI agents:

  • File operations (read, write, copy, move)
  • Directory management
  • File information retrieval
  • File organization
  • Path manipulation

Key Components

File Agent

Create specialized file agents:

Agent(tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file])

File Task

Define file tasks:

Task(description="file_operation")

Process Types

Sequential or parallel processing:

process="sequential"

File Options

Customize file operations:

recursive=True, overwrite=False

Available Functions

from praisonaiagents.tools import read_file
from praisonaiagents.tools import write_file
from praisonaiagents.tools import list_files
from praisonaiagents.tools import get_file_info
from praisonaiagents.tools import copy_file
from praisonaiagents.tools import move_file
from praisonaiagents.tools import delete_file

Function Details

read_file(filepath: str, encoding: str = ‘utf-8’)

Reads content from a file:

  • Supports different encodings
  • Error handling for missing files
  • Automatic encoding detection
# Basic usage
content = read_file("example.txt")

# With specific encoding
content = read_file("data.txt", encoding="latin-1")

# Returns: str (file content)
# Error case: Returns error message as string

write_file(filepath: str, content: str, encoding: str = ‘utf-8’)

Writes content to a file:

  • Creates directories if they don’t exist
  • Supports different encodings
  • Overwrites existing files
# Basic usage
success = write_file("output.txt", "Hello World")

# With specific encoding and nested path
success = write_file(
    "path/to/data/output.txt",
    "Content with special chars: áéíóú",
    encoding="utf-8"
)
# Returns: bool (True if successful)

list_files(directory: str, pattern: Optional[str] = None)

Lists files in a directory:

  • Optional pattern matching
  • Detailed file information
  • Recursive directory support
# List all files
files = list_files("/path/to/directory")

# With pattern matching
files = list_files("/path/to/directory", pattern="*.txt")

# Returns: List[Dict[str, Union[str, int]]]
# Example: [
#   {
#     'name': 'example.txt',
#     'path': '/path/to/directory/example.txt',
#     'size': 1024,
#     'modified': 1609459200.0,
#     'created': 1609459100.0
#   },
#   ...
# ]

get_file_info(filepath: str)

Gets detailed information about a file:

  • File metadata
  • Size and timestamps
  • Type information
  • Path details
# Get file information
info = get_file_info("example.txt")

# Returns: Dict[str, Union[str, int]]
# Example: {
#   'name': 'example.txt',
#   'path': '/absolute/path/to/example.txt',
#   'size': 1024,
#   'modified': 1609459200.0,
#   'created': 1609459100.0,
#   'is_file': True,
#   'is_dir': False,
#   'extension': '.txt',
#   'parent': '/absolute/path/to'
# }

copy_file(src: str, dst: str)

Copies a file with metadata:

  • Preserves timestamps
  • Creates destination directories
  • Handles existing files
# Basic copy
success = copy_file("source.txt", "destination.txt")

# Copy to new directory
success = copy_file(
    "data.txt",
    "backup/2023/data_backup.txt"
)
# Returns: bool (True if successful)

move_file(src: str, dst: str)

Moves or renames a file:

  • Creates destination directories
  • Handles existing files
  • Cross-device moves
# Move file
success = move_file("old/path/file.txt", "new/path/file.txt")

# Rename file
success = move_file(
    "document.txt",
    "document_v2.txt"
)
# Returns: bool (True if successful)

delete_file(filepath: str)

Deletes a file:

  • Safe deletion
  • Error handling
  • Non-recursive (files only)
# Delete file
success = delete_file("unwanted.txt")
# Returns: bool (True if successful)

Example Agent Configuration

from praisonaiagents import Agent
from praisonaiagents.tools import (
    read_file, write_file, list_files,
    get_file_info, copy_file, move_file, delete_file
)

agent = Agent(
    name="FileManager",
    description="An agent that manages files",
    tools=[
        read_file, write_file, list_files,
        get_file_info, copy_file, move_file, delete_file
    ]
)

Error Handling

All functions include comprehensive error handling:

  • File not found errors
  • Permission errors
  • Path errors
  • I/O errors
  • Encoding errors

Errors are handled consistently:

  • File operations return bool for success/failure
  • Information functions return error details in result
  • All errors are logged for debugging

Common Use Cases

  1. File Organization:
# List and organize files by extension
files = list_files("downloads", pattern="*.*")
for file in files:
    ext = file['extension']
    if ext:
        dst = f"organized/{ext[1:]}/{file['name']}"
        move_file(file['path'], dst)
  1. File Backup:
# Create timestamped backups
import time
files = list_files("important_data")
backup_time = time.strftime("%Y%m%d_%H%M%S")
for file in files:
    dst = f"backup/{backup_time}/{file['name']}"
    copy_file(file['path'], dst)
  1. File Processing:
# Read, process, and write files
content = read_file("input.txt")
processed = process_content(content)  # Your processing function
write_file("output.txt", processed)

Examples

Basic File Management Agent

from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import read_file, write_file, list_files, get_file_info

# Create file management agent
file_agent = Agent(
    name="FileExpert",
    role="File Manager",
    goal="Process and organize files efficiently.",
    backstory="Expert in file system operations and organization.",
    tools=[read_file, write_file, list_files, get_file_info],
    self_reflect=False
)

# Define file task
file_task = Task(
    description="Organize and process documents.",
    expected_output="Organized file structure.",
    agent=file_agent,
    name="file_organization"
)

# Run agent
agents = PraisonAIAgents(
    agents=[file_agent],
    tasks=[file_task],
    process="sequential"
)
agents.start()

Advanced File Operations with Multiple Agents

# Create file IO agent
io_agent = Agent(
    name="FileIO",
    role="File IO Specialist",
    goal="Handle file read/write operations efficiently.",
    tools=[read_file, write_file],
    self_reflect=False
)

# Create file management agent
management_agent = Agent(
    name="FileManager",
    role="File Management Specialist",
    goal="Handle file organization and movement.",
    tools=[list_files, get_file_info, copy_file, move_file, delete_file],
    self_reflect=False
)

# Define tasks
io_task = Task(
    description="Read and write files.",
    expected_output="File operations completed successfully.",
    agent=io_agent,
    name="file_io"
)

management_task = Task(
    description="Organize and move files.",
    expected_output="File management completed successfully.",
    agent=management_agent,
    name="file_management"
)

# Run agents
agents = PraisonAIAgents(
    agents=[io_agent, management_agent],
    tasks=[io_task, management_task],
    process="sequential"
)
agents.start()

Best Practices

Common Patterns

File Organization Pipeline

# Organization agent
organizer = Agent(
    name="Organizer",
    role="File Organizer",
    tools=[read_file, write_file, list_files, get_file_info, copy_file, move_file, delete_file]
)

# Cleanup agent
cleaner = Agent(
    name="Cleaner",
    role="File Cleaner"
)

# Define tasks
organize_task = Task(
    description="Organize files by type",
    agent=organizer
)

cleanup_task = Task(
    description="Remove temporary files",
    agent=cleaner
)

# Run workflow
agents = PraisonAIAgents(
    agents=[organizer, cleaner],
    tasks=[organize_task, cleanup_task]
)

Was this page helpful?