|
| 1 | +import asyncio |
| 2 | +import hashlib |
| 3 | +import json |
| 4 | +import mimetypes |
| 5 | +import os |
| 6 | +from collections.abc import AsyncGenerator |
| 7 | +from dataclasses import asdict, is_dataclass |
| 8 | +from io import BytesIO |
| 9 | +from pathlib import Path |
| 10 | +from typing import Annotated, Any |
| 11 | + |
| 12 | +import httpx |
| 13 | +from pydantic import BaseModel |
| 14 | + |
| 15 | +from thirdweb_ai.services.service import Service |
| 16 | +from thirdweb_ai.tools.tool import tool |
| 17 | + |
| 18 | + |
| 19 | +async def async_read_file_chunks(file_path: str | Path, chunk_size: int = 8192) -> AsyncGenerator[bytes, None]: |
| 20 | + """Read file in chunks asynchronously to avoid loading entire file into memory.""" |
| 21 | + async with asyncio.Lock(): |
| 22 | + path_obj = Path(file_path) if isinstance(file_path, str) else file_path |
| 23 | + with path_obj.open("rb") as f: |
| 24 | + while chunk := f.read(chunk_size): |
| 25 | + yield chunk |
| 26 | + |
| 27 | + |
| 28 | +class Storage(Service): |
| 29 | + def __init__(self, secret_key: str): |
| 30 | + super().__init__(base_url="https://storage.thirdweb.com", secret_key=secret_key) |
| 31 | + self.gateway_url = self._get_gateway_url() |
| 32 | + self.gateway_hostname = "ipfscdn.io" |
| 33 | + |
| 34 | + def _get_gateway_url(self) -> str: |
| 35 | + return hashlib.sha256(self.secret_key.encode()).hexdigest()[:32] |
| 36 | + |
| 37 | + @tool(description="Fetch content from IPFS by hash. Retrieves data stored on IPFS using the thirdweb gateway.") |
| 38 | + def fetch_ipfs_content( |
| 39 | + self, |
| 40 | + ipfs_hash: Annotated[ |
| 41 | + str, "The IPFS hash/URI to fetch content from (e.g., 'ipfs://QmXyZ...'). Must start with 'ipfs://'." |
| 42 | + ], |
| 43 | + ) -> dict[str, Any]: |
| 44 | + if not ipfs_hash.startswith("ipfs://"): |
| 45 | + return {"error": "Invalid IPFS hash"} |
| 46 | + |
| 47 | + ipfs_hash = ipfs_hash.removeprefix("ipfs://") |
| 48 | + path = f"https://{self.gateway_url}.{self.gateway_hostname}.ipfscdn.io/ipfs/{ipfs_hash}" |
| 49 | + return self._get(path) |
| 50 | + |
| 51 | + async def _async_post_file(self, url: str, files: dict[str, Any]) -> dict[str, Any]: |
| 52 | + """Post files to a URL using async client with proper authorization headers.""" |
| 53 | + headers = self._make_headers() |
| 54 | + # Remove the Content-Type as httpx will set it correctly for multipart/form-data |
| 55 | + headers.pop("Content-Type", None) |
| 56 | + |
| 57 | + async with httpx.AsyncClient() as client: |
| 58 | + response = await client.post(url, files=files, headers=headers) |
| 59 | + response.raise_for_status() |
| 60 | + return response.json() |
| 61 | + |
| 62 | + def _is_json_serializable(self, data: Any) -> bool: |
| 63 | + """Check if data is JSON serializable (dict, dataclass, or BaseModel).""" |
| 64 | + return isinstance(data, dict) or is_dataclass(data) or isinstance(data, BaseModel) |
| 65 | + |
| 66 | + def _convert_to_json(self, data: Any) -> str: |
| 67 | + """Convert data to JSON string.""" |
| 68 | + if isinstance(data, dict): |
| 69 | + return json.dumps(data) |
| 70 | + if is_dataclass(data): |
| 71 | + # Handle dataclass properly |
| 72 | + if isinstance(data, type): |
| 73 | + raise ValueError(f"Expected dataclass instance, got dataclass type: {data}") |
| 74 | + return json.dumps(asdict(data)) |
| 75 | + if isinstance(data, BaseModel): |
| 76 | + return data.model_dump_json() |
| 77 | + raise ValueError(f"Cannot convert {type(data)} to JSON") |
| 78 | + |
| 79 | + def _is_valid_path(self, path: str) -> bool: |
| 80 | + """Check if the string is a valid file or directory path.""" |
| 81 | + return Path(path).exists() |
| 82 | + |
| 83 | + async def _prepare_directory_files( |
| 84 | + self, directory_path: Path, chunk_size: int = 8192 |
| 85 | + ) -> list[tuple[str, BytesIO, str]]: |
| 86 | + """ |
| 87 | + Prepare files from a directory for upload, preserving directory structure. |
| 88 | + Returns a list of tuples (relative_path, file_buffer, content_type). |
| 89 | + """ |
| 90 | + files_data = [] |
| 91 | + |
| 92 | + for root, _, files in os.walk(directory_path): |
| 93 | + for file in files: |
| 94 | + file_path = Path(root) / file |
| 95 | + # Preserve the directory structure in the relative path |
| 96 | + relative_path = str(file_path.relative_to(directory_path)) |
| 97 | + content_type = mimetypes.guess_type(str(file_path))[0] or "application/octet-stream" |
| 98 | + |
| 99 | + # Create a buffer and read the file in chunks |
| 100 | + buffer = BytesIO() |
| 101 | + async for chunk in async_read_file_chunks(file_path, chunk_size): |
| 102 | + buffer.write(chunk) |
| 103 | + buffer.seek(0) # Reset buffer position |
| 104 | + |
| 105 | + files_data.append((relative_path, buffer, content_type)) |
| 106 | + |
| 107 | + return files_data |
| 108 | + |
| 109 | + @tool( |
| 110 | + description="Upload a file, directory, or JSON data to IPFS. Stores any type on decentralized storage and returns an IPFS URI." |
| 111 | + ) |
| 112 | + async def upload_to_ipfs( |
| 113 | + self, |
| 114 | + data: Annotated[ |
| 115 | + Any, "Data to upload: can be a file path, directory path, dict, dataclass, or BaseModel instance." |
| 116 | + ], |
| 117 | + ) -> str: |
| 118 | + """ |
| 119 | + Upload data to IPFS and return the IPFS hash. |
| 120 | +
|
| 121 | + Supports: |
| 122 | + - File paths (streams content) |
| 123 | + - Directory paths (preserves directory structure) |
| 124 | + - Dict objects (converted to JSON) |
| 125 | + - Dataclass instances (converted to JSON) |
| 126 | + - Pydantic BaseModel instances (converted to JSON) |
| 127 | +
|
| 128 | + Always uses streaming for file uploads to handle large files efficiently. |
| 129 | + """ |
| 130 | + storage_url = f"{self.base_url}/ipfs/upload" |
| 131 | + |
| 132 | + # Handle JSON-serializable data types |
| 133 | + if self._is_json_serializable(data): |
| 134 | + json_content = self._convert_to_json(data) |
| 135 | + files = {"file": ("data.json", BytesIO(json_content.encode()), "application/json")} |
| 136 | + body = await self._async_post_file(storage_url, files) |
| 137 | + return f"ipfs://{body['IpfsHash']}" |
| 138 | + |
| 139 | + # Handle string paths to files or directories |
| 140 | + if isinstance(data, str) and self._is_valid_path(data): |
| 141 | + path = Path(data) |
| 142 | + |
| 143 | + # Single file upload with streaming |
| 144 | + if path.is_file(): |
| 145 | + content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream" |
| 146 | + |
| 147 | + # Create a buffer to hold chunks for streaming upload |
| 148 | + buffer = BytesIO() |
| 149 | + async for chunk in async_read_file_chunks(path): |
| 150 | + buffer.write(chunk) |
| 151 | + |
| 152 | + buffer.seek(0) # Reset buffer position |
| 153 | + files = {"file": (path.name, buffer, content_type)} |
| 154 | + body = await self._async_post_file(storage_url, files) |
| 155 | + return f"ipfs://{body['IpfsHash']}" |
| 156 | + |
| 157 | + # Directory upload - preserve directory structure |
| 158 | + if path.is_dir(): |
| 159 | + # Prepare all files from the directory with preserved structure |
| 160 | + files_data = await self._prepare_directory_files(path) |
| 161 | + |
| 162 | + if not files_data: |
| 163 | + raise ValueError(f"Directory is empty: {data}") |
| 164 | + |
| 165 | + files_dict = { |
| 166 | + f"file{i}": (relative_path, buffer, content_type) |
| 167 | + for i, (relative_path, buffer, content_type) in enumerate(files_data) |
| 168 | + } |
| 169 | + body = await self._async_post_file(storage_url, files_dict) |
| 170 | + return f"ipfs://{body['IpfsHash']}" |
| 171 | + |
| 172 | + raise ValueError(f"Path exists but is neither a file nor a directory: {data}") |
| 173 | + |
| 174 | + try: |
| 175 | + content_type = mimetypes.guess_type(data)[0] or "application/octet-stream" |
| 176 | + files = {"file": ("data.txt", BytesIO(data.encode()), content_type)} |
| 177 | + body = await self._async_post_file(storage_url, files) |
| 178 | + return f"ipfs://{body['IpfsHash']}" |
| 179 | + except TypeError as e: |
| 180 | + raise TypeError( |
| 181 | + f"Unsupported data type: {type(data)}. Must be a valid file/directory path, dict, dataclass, or BaseModel." |
| 182 | + ) from e |
0 commit comments