File size: 15,234 Bytes
5374a2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 |
#!/usr/bin/env python3
"""
File System Tools Examples for EvoAgentX
This module provides comprehensive examples for:
- StorageToolkit: Comprehensive file storage operations with flexible storage backends
- CMDToolkit: Command-line execution capabilities with timeout handling
The examples demonstrate various file operations and system interactions including:
- File save, read, append, list, delete, and existence checks
- Command execution with working directory and timeout support
- Cross-platform command handling
- Storage handler management
"""
import os
import sys
from pathlib import Path
# Add the parent directory to sys.path to import from evoagentx
sys.path.append(str(Path(__file__).parent.parent))
from evoagentx.tools import (
StorageToolkit,
CMDToolkit
)
def run_file_tool_example():
"""
Run an example using the StorageToolkit to read and write files with the new storage handler system.
"""
print("\n===== STORAGE TOOL EXAMPLE =====\n")
try:
# Initialize the storage toolkit with default storage handler
storage_toolkit = StorageToolkit(name="DemoStorageToolkit")
# Get individual tools from the toolkit
save_tool = storage_toolkit.get_tool("save")
read_tool = storage_toolkit.get_tool("read")
append_tool = storage_toolkit.get_tool("append")
list_tool = storage_toolkit.get_tool("list_files")
exists_tool = storage_toolkit.get_tool("exists")
# Create sample content for different file types
sample_text = """This is a sample text document created using the StorageToolkit.
This tool provides comprehensive file operations with automatic format detection.
It supports various file types including text, JSON, CSV, YAML, XML, Excel, and more."""
sample_json = {
"name": "Sample Document",
"type": "test",
"content": "This is a JSON document for testing",
"metadata": {
"created": "2024-01-01",
"version": "1.0"
}
}
# Test file operations with default storage paths
print("1. Testing file save operations...")
# Save text file
text_result = save_tool(
file_path="sample_document.txt",
content=sample_text
)
print("Text file save result:")
print("-" * 30)
print(text_result)
print("-" * 30)
# Save JSON file
# Note: StorageToolkit expects Python objects for JSON, not JSON strings
# For other formats like CSV, YAML, text - pass strings directly
json_result = save_tool(
file_path="sample_data.json",
content=sample_json # Pass the Python dict directly, not json.dumps()
)
print("JSON file save result:")
print("-" * 30)
print(json_result)
print("-" * 30)
# Test file read operations
print("\n2. Testing file read operations...")
# Read text file
text_read_result = read_tool(file_path="sample_document.txt")
print("Text file read result:")
print("-" * 30)
print(text_read_result)
print("-" * 30)
# Read JSON file
json_read_result = read_tool(file_path="sample_data.json")
print("JSON file read result:")
print("-" * 30)
print(json_read_result)
print("-" * 30)
# Test file append operations
print("\n3. Testing file append operations...")
# Append to text file
append_text_result = append_tool(
file_path="sample_document.txt",
content="\n\nThis content was appended to the text file."
)
print("Text file append result:")
print("-" * 30)
print(append_text_result)
print("-" * 30)
# Update JSON file with new data
# Note: For JSON files, we use save_tool to update, not append_tool
# The append_tool for JSON expects Python objects, not JSON strings
updated_json_data = {**sample_json, "additional": "data", "timestamp": "2024-01-01T12:00:00Z"}
update_json_result = save_tool(
file_path="sample_data.json",
content=updated_json_data # Pass the Python dict directly
)
print("JSON file update result:")
print("-" * 30)
print(update_json_result)
print("-" * 30)
# Test file listing
print("\n4. Testing file listing...")
list_result = list_tool(path=".", max_depth=2, include_hidden=False)
print("File listing result:")
print("-" * 30)
print(list_result)
print("-" * 30)
# Test file existence
print("\n5. Testing file existence...")
exists_result = exists_tool(path="sample_document.txt")
print("File existence check result:")
print("-" * 30)
print(exists_result)
print("-" * 30)
# Test supported formats
print("\n6. Testing supported formats...")
formats_tool = storage_toolkit.get_tool("list_supported_formats")
formats_result = formats_tool()
print("Supported formats result:")
print("-" * 30)
print(formats_result)
print("-" * 30)
print("\nβ StorageToolkit test completed successfully!")
print("β All file operations working with default storage handler")
print("β Automatic format detection working")
print("β File operations working (including JSON updates)")
print("β File listing and existence checks working")
except Exception as e:
print(f"Error running storage tool example: {str(e)}")
def run_cmd_tool_example():
"""Simple example using CMDToolkit for command line operations."""
print("\n===== CMD TOOL EXAMPLE =====\n")
try:
# Initialize the CMD toolkit
cmd_toolkit = CMDToolkit(name="DemoCMDToolkit")
execute_tool = cmd_toolkit.get_tool("execute_command")
print("β CMDToolkit initialized")
# Test basic command execution
print("1. Testing basic command execution...")
result = execute_tool(command="echo 'Hello from CMD toolkit'")
if result.get("success"):
print("β Command executed successfully")
print(f"Output: {result.get('stdout', 'No output')}")
else:
print(f"β Command failed: {result.get('error', 'Unknown error')}")
# Test system information commands
print("\n2. Testing system information commands...")
# Get current working directory
pwd_result = execute_tool(command="pwd")
if pwd_result.get("success"):
print(f"β Current directory: {pwd_result.get('stdout', '').strip()}")
# Get system information
if os.name == 'posix': # Linux/Mac
uname_result = execute_tool(command="uname -a")
if uname_result.get("success"):
print(f"β System info: {uname_result.get('stdout', '').strip()}")
else: # Windows
ver_result = execute_tool(command="ver")
if ver_result.get("success"):
print(f"β System info: {ver_result.get('stdout', '').strip()}")
# Test file listing
print("\n3. Testing file listing...")
if os.name == 'posix':
ls_result = execute_tool(command="ls -la", working_directory=".")
else:
ls_result = execute_tool(command="dir", working_directory=".")
if ls_result.get("success"):
print("β File listing successful")
print(f"Output length: {len(ls_result.get('stdout', ''))} characters")
else:
print(f"β File listing failed: {ls_result.get('error', 'Unknown error')}")
# Test with timeout
print("\n4. Testing command timeout...")
timeout_result = execute_tool(command="sleep 5", timeout=12)
if not timeout_result.get("success"):
print("β Timeout working correctly (command was interrupted)")
else:
print("β Timeout may not be working as expected")
print("\nβ CMDToolkit test completed")
except Exception as e:
print(f"Error: {str(e)}")
def run_storage_handler_examples():
"""
Run examples demonstrating different storage handlers and configurations.
"""
print("\n===== STORAGE HANDLER EXAMPLES =====\n")
try:
# Test with custom base path
print("1. Testing custom base path storage...")
custom_storage_toolkit = StorageToolkit(
name="CustomPathStorageToolkit",
storage_handler=None, # Will use default LocalStorageHandler
base_path="./custom_storage"
)
# Create a test file in custom location
custom_save_tool = custom_storage_toolkit.get_tool("save")
custom_result = custom_save_tool(
file_path="custom_test.txt",
content="This file is stored in a custom location"
)
if custom_result.get("success"):
print("β Custom path storage working")
print(f"File saved to: {custom_result.get('file_path')}")
else:
print(f"β Custom path storage failed: {custom_result.get('error')}")
# Test file operations in custom location
custom_read_tool = custom_storage_toolkit.get_tool("read")
custom_read_result = custom_read_tool(file_path="custom_test.txt")
if custom_read_result.get("success"):
print("β Custom path file reading working")
print(f"Content: {custom_read_result.get('content', '')[:50]}...")
# Test file listing in custom location
custom_list_tool = custom_storage_toolkit.get_tool("list_files")
custom_list_result = custom_list_tool(path=".", max_depth=1, include_hidden=False)
if custom_list_result.get("success"):
print("β Custom path file listing working")
files = custom_list_result.get("files", [])
print(f"Found {len(files)} files in custom location")
print("\nβ Storage handler examples completed")
except Exception as e:
print(f"Error running storage handler examples: {str(e)}")
def run_advanced_file_operations():
"""
Run examples demonstrating advanced file operations and format handling.
"""
print("\n===== ADVANCED FILE OPERATIONS =====\n")
try:
# Initialize storage toolkit
storage_toolkit = StorageToolkit()
save_tool = storage_toolkit.get_tool("save")
read_tool = storage_toolkit.get_tool("read")
# Test CSV file operations
print("1. Testing CSV file operations...")
csv_content = """name,age,city
John Doe,30,New York
Jane Smith,25,Los Angeles
Bob Johnson,35,Chicago"""
csv_result = save_tool(
file_path="sample_data.csv",
content=csv_content
)
if csv_result.get("success"):
print("β CSV file saved successfully")
# Read CSV file
csv_read_result = read_tool(file_path="sample_data.csv")
if csv_read_result.get("success"):
print("β CSV file read successfully")
print(f"Content: {csv_read_result.get('content', '')[:100]}...")
else:
print(f"β Failed to read CSV file: {csv_read_result.get('error')}")
else:
print(f"β Failed to save CSV file: {csv_result.get('error')}")
# Test YAML file operations
print("\n2. Testing YAML file operations...")
yaml_content = """name: Sample YAML
version: 1.0
features:
- feature1
- feature2
metadata:
author: Test User
date: 2024-01-01"""
yaml_result = save_tool(
file_path="sample_config.yaml",
content=yaml_content
)
if yaml_result.get("success"):
print("β YAML file saved successfully")
# Read YAML file
yaml_read_result = read_tool(file_path="sample_config.yaml")
if yaml_read_result.get("success"):
print("β YAML file read successfully")
print(f"Content: {yaml_read_result.get('content', '')[:100]}...")
else:
print(f"β Failed to read YAML file: {yaml_read_result.get('error')}")
else:
print(f"β Failed to save YAML file: {yaml_result.get('error')}")
# Test PDF file operations
print("\n3. Testing PDF file operations...")
# Create PDF file first
pdf_content = """Test PDF Document
This is a test PDF created by EvoAgentX.
Features:
β’ PDF creation from text
β’ Automatic formatting
β’ Professional layout
This demonstrates the storage system's PDF capabilities."""
pdf_result = save_tool(
file_path="test_pdf.pdf",
content=pdf_content
)
if pdf_result.get("success"):
print("β PDF file created successfully")
else:
print(f"β Failed to create PDF file: {pdf_result.get('error')}")
# Read PDF file
pdf_read_result = read_tool(file_path="test_pdf.pdf")
if pdf_read_result.get("success"):
print("β PDF file read successfully")
print(f"Content: {pdf_read_result.get('content', '')[:100]}...")
else:
print(f"β Failed to read PDF file: {pdf_read_result.get('error')}")
# Test file deletion
print("\n4. Testing file deletion...")
delete_tool = storage_toolkit.get_tool("delete")
# Delete test files
test_files = ["sample_document.txt", "sample_data.json", "custom_test.txt"]
for test_file in test_files:
if os.path.exists(test_file):
delete_result = delete_tool(path=test_file)
if delete_result.get("success"):
print(f"β Deleted {test_file}")
else:
print(f"β Failed to delete {test_file}: {delete_result.get('error')}")
print("\nβ Advanced file operations completed")
except Exception as e:
print(f"Error running advanced file operations: {str(e)}")
def main():
"""Main function to run all file system examples"""
print("===== FILE SYSTEM TOOLS EXAMPLES =====")
# # Run storage tool example
# run_file_tool_example()
# # Run CMD tool example
# run_cmd_tool_example()
# # Run storage handler examples
# run_storage_handler_examples()
# Run advanced file operations
run_advanced_file_operations()
print("\n===== ALL FILE SYSTEM EXAMPLES COMPLETED =====")
if __name__ == "__main__":
main()
|