Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/modules/image_tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Environment:
- All tools use the storage handler architecture:
- **Storage Handler**: All toolkits accept `storage_handler` parameter (defaults to `LocalStorageHandler`)
- **File Operations**: Automatic path translation and format detection
- **Supported Storage**: Local filesystem and Supabase cloud storage
- **Supported Storage**: Local filesystem, Supabase cloud storage, and Neon cloud storage
- Typical returns:
- OpenAI generation/edit: `{ "results": ["<local_path>", ...] }`
- OpenRouter generation/edit: `{ "saved_paths": ["<local_path>", ...] }`
Expand Down
3 changes: 2 additions & 1 deletion docs/tutorial/image_tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ print(res["file_path"])

- **Storage Support**: All image tools support flexible storage options:
- **Local Storage**: Default option for saving images to local filesystem
- **Remote Storage**: Optional Supabase cloud storage for distributed access
- **Remote Storage**: Optional Supabase or Neon cloud storage for distributed access
- **File Operations**: All file I/O is handled automatically through the storage system
- **Toolkit Parameters**: All toolkits accept `storage_handler` parameter for custom storage
- Both OpenRouter and OpenAI analysis tools support `image_path` (auto-converted to data URL); `image_url` also works.
Expand All @@ -267,6 +267,7 @@ print(res["file_path"])
- **Storage errors?**
- Local storage: Check directory permissions and disk space
- Supabase storage: Verify environment variables and bucket access
- Neon storage: Verify environment variables and bucket access
- **File not found errors?** Check if the storage path is correct and accessible


18 changes: 17 additions & 1 deletion docs/tutorial/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -3012,7 +3012,7 @@ ls evoagentx/tools/image_tools/flux_image_tools/

Image handling tools provide comprehensive capabilities for image analysis, generation, and manipulation using various AI services and APIs. These tools enable agents to work with visual content, generate images from text descriptions, and analyze image content.

**Storage Support**: All image toolkits support flexible file storage options through the `storage_handler` parameter, allowing you to use local storage, remote storage (Supabase), or custom storage implementations.
**Storage Support**: All image toolkits support flexible file storage options through the `storage_handler` parameter, allowing you to use local storage, remote storage (Supabase or Neon), or custom storage implementations.

### 6.1 OpenAIImageToolkit

Expand Down Expand Up @@ -3243,6 +3243,22 @@ storage_handler = SupabaseStorageHandler(bucket_name="my-images")
toolkit = OpenAIImageToolkit(api_key=API_KEY, storage_handler=storage_handler)
```

#### 6.4.3 Remote Storage (Neon)
```python
from evoagentx.tools import NeonStorageHandler
import os

# Set environment variables
os.environ["AWS_ENDPOINT_URL_S3"] = "your-neon-storage-endpoint"
os.environ["AWS_ACCESS_KEY_ID"] = "your-neon-access-key-id"
os.environ["AWS_SECRET_ACCESS_KEY"] = "your-neon-secret-access-key"
os.environ["NEON_BUCKET_STORAGE"] = "your-bucket-name"

# Use Neon storage
storage_handler = NeonStorageHandler(bucket_name="my-images")
toolkit = OpenAIImageToolkit(api_key=API_KEY, storage_handler=storage_handler)
```

---

### 6.5 Image Handling Tools Summary
Expand Down
3 changes: 2 additions & 1 deletion evoagentx/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .gmail_tools import GmailToolkit
from .database_mongodb import MongoDBToolkit
from .database_postgresql import PostgreSQLToolkit
from .storage_handler import FileStorageHandler, LocalStorageHandler, SupabaseStorageHandler
from .storage_handler import FileStorageHandler, LocalStorageHandler, SupabaseStorageHandler, NeonStorageHandler
from .storage_file import StorageToolkit
from .image_tools.flux_image_tools.image_generation_edit import FluxImageGenerationEditTool
from .image_tools.flux_image_tools.toolkit import FluxImageGenerationToolkit
Expand Down Expand Up @@ -57,6 +57,7 @@
"FileStorageHandler",
"LocalStorageHandler",
"SupabaseStorageHandler",
"NeonStorageHandler",
"StorageToolkit",
"FluxImageGenerationEditTool",
"FluxImageGenerationToolkit",
Expand Down
12 changes: 8 additions & 4 deletions evoagentx/tools/storage_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ def _create_directory_raw(self, path: str) -> bool:


# ____________________ PATH TRANSLATION ____________________ #
def _is_remote_storage(self) -> bool:
"""Check if this handler stores files in a remote bucket (Supabase or Neon)"""
return hasattr(self, 'bucket_name') and (hasattr(self, 'supabase') or hasattr(self, 's3_client'))

def translate_in(self, file_path: str) -> str:
"""
Translate input file path by combining it with base_path.
Expand All @@ -119,8 +123,8 @@ def translate_in(self, file_path: str) -> str:
return file_path

# Always combine base_path with file_path to ensure working directory is respected
# Check if this is a remote storage handler (like Supabase)
if hasattr(self, 'bucket_name') and hasattr(self, 'supabase'):
# Check if this is a remote storage handler (like Supabase or Neon)
if self._is_remote_storage():
# For remote storage, treat base_path as a prefix within the bucket
# Don't use os.path.join as it's designed for local filesystems
if self.base_path.startswith('/'):
Expand Down Expand Up @@ -154,8 +158,8 @@ def translate_out(self, full_path: str) -> str:
if self.base_path in [".", "", None]:
return full_path

# Check if this is a remote storage handler (like Supabase)
if hasattr(self, 'bucket_name') and hasattr(self, 'supabase'):
# Check if this is a remote storage handler (like Supabase or Neon)
if self._is_remote_storage():
# For remote storage, handle path prefix removal
if self.base_path.startswith('/'):
clean_base = self.base_path.lstrip('/')
Expand Down
272 changes: 271 additions & 1 deletion evoagentx/tools/storage_handler.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import shutil
import mimetypes
from typing import Dict, Any, List
from pathlib import Path
from datetime import datetime
Expand Down Expand Up @@ -506,4 +507,273 @@ def _create_directory_raw(self, path: str) -> bool:
logger.error(f"Error creating directory {path} in Supabase: {str(e)}")
return False




class NeonStorageHandler(FileStorageHandler):
"""
Neon remote storage implementation.
Provides file operations via Neon's S3-compatible storage API with environment-based configuration.
"""

def __init__(self, bucket_name: str = None, base_path: str = "/",
endpoint_url: str = None, access_key_id: str = None,
secret_access_key: str = None, region: str = None, **kwargs):
"""
Initialize Neon storage handler.

Args:
bucket_name: Neon storage bucket name (default: from NEON_BUCKET_STORAGE)
base_path: Base path (key prefix) for storage operations (default: "/")
endpoint_url: Branch storage endpoint (default: from AWS_ENDPOINT_URL_S3)
access_key_id: Neon access key ID (default: from AWS_ACCESS_KEY_ID)
secret_access_key: Neon secret access key (default: from AWS_SECRET_ACCESS_KEY)
region: Region used for request signing (default: from AWS_REGION, then the endpoint host)
**kwargs: Additional keyword arguments for parent class initialization
"""
# Call parent constructor first
super().__init__(base_path=base_path, **kwargs)

self.bucket_name = bucket_name or os.getenv("NEON_BUCKET_STORAGE")
self.endpoint_url = endpoint_url or os.getenv("AWS_ENDPOINT_URL_S3")
access_key_id = access_key_id or os.getenv("AWS_ACCESS_KEY_ID")
secret_access_key = secret_access_key or os.getenv("AWS_SECRET_ACCESS_KEY")
self.region = region or os.getenv("AWS_REGION") or self._region_from_endpoint(self.endpoint_url)

if not self.bucket_name:
raise ValueError(
"Neon bucket name not found. "
"Pass bucket_name or set the NEON_BUCKET_STORAGE environment variable."
)
if not self.endpoint_url or not access_key_id or not secret_access_key:
raise ValueError(
"Neon storage configuration not found in environment variables. "
"Please set AWS_ENDPOINT_URL_S3/AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables."
)

# Initialize S3 client against the Neon branch endpoint
try:
import boto3
from botocore.config import Config
# Neon serves buckets under the branch endpoint, so requests must be path-style
self.s3_client = boto3.client(
"s3",
endpoint_url=self.endpoint_url,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key,
region_name=self.region,
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
logger.info(f"Successfully initialized Neon storage client for bucket: {self.bucket_name}")
except ImportError:
raise ImportError(
"boto3 not installed. "
"Please install it with: pip install boto3"
)
except Exception as e:
logger.error(f"Failed to initialize Neon storage client: {str(e)}")
raise Exception(f"Failed to initialize Neon storage client: {str(e)}")

# Initialize storage after all attributes are set
self._initialize_storage()

@staticmethod
def _region_from_endpoint(endpoint_url: str) -> str:
"""Read the region from a host like br-x.storage.c-1.us-east-2.aws.neon.tech"""
if endpoint_url:
parts = endpoint_url.split("://")[-1].split("/")[0].split(".")
if "storage" in parts and len(parts) > parts.index("storage") + 2:
return parts[parts.index("storage") + 2]
return "us-east-1"

def _initialize_storage(self):
"""Initialize remote storage - verify bucket exists and is accessible"""
# Check if required attributes are available
if not hasattr(self, 'bucket_name') or not hasattr(self, 's3_client'):
# If attributes aren't set yet, skip initialization
# This will be called again after attributes are set in __init__
return

try:
logger.info(f"Testing bucket access for: {self.bucket_name}")
self.s3_client.head_bucket(Bucket=self.bucket_name)
logger.info(f"Successfully connected to Neon bucket: {self.bucket_name}")
except Exception as e:
logger.warning(f"Could not verify bucket access: {str(e)}")
# Don't raise error as the credential might only allow object access

def translate_in(self, file_path: str) -> str:
"""Resolve file path for remote storage"""
if self.base_path == "/":
# If base_path is "/", just clean the file_path
return file_path.lstrip('/')
else:
return super().translate_in(file_path)

@staticmethod
def _is_not_found(error: Exception) -> bool:
"""Check whether a botocore error is a 404"""
response = getattr(error, "response", None) or {}
code = str(response.get("Error", {}).get("Code", ""))
return code in ("404", "NoSuchKey", "NotFound")

def _list_keys(self, prefix: str) -> List[Dict[str, Any]]:
"""List every object under a key prefix"""
objects = []
paginator = self.s3_client.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=self.bucket_name, Prefix=prefix):
objects.extend(page.get("Contents", []))
return objects

def _read_raw(self, path: str, **kwargs) -> bytes:
"""Read raw file content from Neon Object Storage"""
try:
key = path.lstrip('/')
response = self.s3_client.get_object(Bucket=self.bucket_name, Key=key)
return response["Body"].read()
except Exception as e:
logger.error(f"Error reading file {path} from Neon: {str(e)}")
raise

def _write_raw(self, path: str, content: bytes, **kwargs) -> bool:
"""Write raw file content to Neon Object Storage (PUT overwrites existing objects)"""
try:
key = path.lstrip('/')
content_type = (
kwargs.get("content_type")
or mimetypes.guess_type(key)[0]
or "application/octet-stream"
)
self.s3_client.put_object(
Bucket=self.bucket_name,
Key=key,
Body=content,
ContentType=content_type,
)
logger.info(f"Successfully uploaded file to Neon: {key}")
return True
except Exception as e:
logger.error(f"Error writing file {path} to Neon: {str(e)}")
return False

def _delete_raw(self, path: str) -> bool:
"""Delete a file, or every object under a directory prefix, from Neon Object Storage"""
try:
key = path.lstrip('/')
if key and self._object_exists(key):
self.s3_client.delete_object(Bucket=self.bucket_name, Key=key)
logger.info(f"Successfully deleted file from Neon: {key}")
return True

# Treat the path as a directory and remove everything under it
prefix = f"{key.rstrip('/')}/" if key else ""
if not prefix:
logger.error("Refusing to delete the whole bucket")
return False
objects = self._list_keys(prefix)
if not objects:
return False
for i in range(0, len(objects), 1000):
batch = [{"Key": obj["Key"]} for obj in objects[i:i + 1000]]
self.s3_client.delete_objects(Bucket=self.bucket_name, Delete={"Objects": batch, "Quiet": True})
logger.info(f"Successfully deleted {len(objects)} objects under {prefix} from Neon")
return True
except Exception as e:
logger.error(f"Error deleting {path} from Neon: {str(e)}")
return False

def _list_raw(self, path: str = None, max_depth: int = 3, include_hidden: bool = False) -> List[Dict[str, Any]]:
"""List files and directories in Neon Object Storage"""
try:
list_path = (path or self.base_path).strip('/')
prefix = f"{list_path}/" if list_path else ""

items = []
seen_dirs = set()
for obj in self._list_keys(prefix):
parts = obj["Key"][len(prefix):].split('/')

# Directories implied by the key, up to max_depth levels below the listed path
for depth in range(min(len(parts) - 1, max_depth + 1)):
dir_parts = parts[:depth + 1]
if not include_hidden and any(p.startswith('.') for p in dir_parts):
break
dir_path = prefix + '/'.join(dir_parts)
if dir_path not in seen_dirs:
seen_dirs.add(dir_path)
items.append({
"name": dir_parts[-1],
"path": dir_path,
"type": "directory",
"size_bytes": 0,
"size_mb": 0,
"modified_time": "",
"extension": "",
"is_hidden": dir_parts[-1].startswith('.')
})

# Directory markers ("dir/") end with an empty name
name = parts[-1]
if not name or len(parts) - 1 > max_depth:
continue
if not include_hidden and any(p.startswith('.') for p in parts):
continue

size = obj.get("Size", 0)
modified = obj.get("LastModified")
items.append({
"name": name,
"path": obj["Key"],
"type": "file",
"size_bytes": size,
"size_mb": round(size / (1024 * 1024), 2),
"modified_time": modified.isoformat() if modified else "",
"extension": Path(name).suffix.lower(),
"is_hidden": name.startswith('.')
})

return items

except Exception as e:
logger.error(f"Error listing directory {path} from Neon: {str(e)}")
return []

def _object_exists(self, key: str) -> bool:
"""Check if a single object exists"""
try:
self.s3_client.head_object(Bucket=self.bucket_name, Key=key)
return True
except Exception as e:
if self._is_not_found(e):
return False
raise

def _exists_raw(self, path: str) -> bool:
"""Check if a file or directory prefix exists in Neon Object Storage"""
try:
key = path.lstrip('/')
if not key:
return True
if self._object_exists(key):
return True
response = self.s3_client.list_objects_v2(
Bucket=self.bucket_name, Prefix=f"{key.rstrip('/')}/", MaxKeys=1
)
return response.get("KeyCount", 0) > 0
except Exception as e:
logger.warning(f"Error checking if file {path} exists: {str(e)}")
return False

def _create_directory_raw(self, path: str) -> bool:
"""Create directory in Neon Object Storage"""
try:
dir_path = path.strip('/')
if not dir_path:
return True

# Object storage has no real directories, so write an empty "dir/" marker object
self.s3_client.put_object(Bucket=self.bucket_name, Key=f"{dir_path}/", Body=b"")
return True

except Exception as e:
logger.error(f"Error creating directory {path} in Neon: {str(e)}")
return False