from typing import Optional from smolagents import tool @tool def download_file_from_url(url: str, filename: Optional[str] = None) -> str: """ Downloads a file from the given URL to a temporary local location. The file is saved in the system's temporary directory. The filename is either passed as argument or inferred from the URL's path; if it cannot be determined, a generic name is used. Args: url: The URL of the file to download (str). filename: Optional filename, will generate one based on URL if not provided Returns: The full local file path (str) of the downloaded file if successful, or an error message string detailing the failure. """ import requests, tempfile, os from urllib.parse import urlparse try: if not filename: filename = os.path.basename(urlparse(url).path) or "downloaded_file" filepath = os.path.join(tempfile.gettempdir(), filename) response = requests.get(url, stream=True) response.raise_for_status() with open(filepath, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) return filepath except Exception as e: return f"Download error: {e}"