import weave
import requests
from typing import Tuple, List, Dict, Any
import base64
# Tool definition
WEB_DOWNLOAD_TOOL = {
"definition": {
"type": "function",
"function": {
"name": "web-download_file",
"description": "Download a file from a URL and return it as an attachment",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL of the file to download"
},
"timeout": {
"type": "integer",
"description": "Timeout in seconds",
"default": 30
}
},
"required": ["url"]
}
}
},
"implementation": download_file,
"type": "standard"
}
# Tool implementation
@weave.op(name="web-download_file")
def download_file(*, url: str, timeout: int = 30) -> Tuple[str, List[Dict[str, Any]]]:
"""Download a file from URL."""
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status()
# Get filename from URL
filename = url.split('/')[-1] or "download"
# Encode content
content = base64.b64encode(response.content).decode()
# Detect MIME type
mime_type = response.headers.get('content-type', 'application/octet-stream')
files = [{
"filename": filename,
"content": content,
"mime_type": mime_type
}]
size_mb = len(response.content) / (1024 * 1024)
return f"Downloaded {filename} ({size_mb:.2f} MB)", files
except requests.exceptions.Timeout:
return f"Error: Download timed out after {timeout} seconds", []
except requests.exceptions.RequestException as e:
return f"Error downloading file: {str(e)}", []
except Exception as e:
return f"Unexpected error: {str(e)}", []