File size: 1,214 Bytes
01faebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a0b5ad
 
 
 
01faebd
 
 
 
 
 
 
 
 
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
import os
from pathlib import Path

import httpx
from colorama import Fore, Style  # type: ignore[import]
from langchain_core.tools import tool

WORKSPACE_DIR = Path(__file__).resolve().parents[2] / "workspace"


@tool
def file_downloader(url: str) -> str:
    """Download a file from a URL and save it to the workspace directory.

    Args:
        url: The URL of the file to download.

    Returns:
        The local file path of the downloaded file, or an error message.
    """
    try:
        filename = url.rstrip("/").split("/")[-1].split("?")[0] or "downloaded_file"
        dest = WORKSPACE_DIR / filename

        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        }
        with httpx.stream("GET", url, headers=headers, follow_redirects=True, timeout=60) as r:
            r.raise_for_status()
            with open(dest, "wb") as f:
                for chunk in r.iter_bytes():
                    f.write(chunk)

        print(f"{Fore.GREEN}[FileDownloader] Saved: {dest}{Style.RESET_ALL}")
        return str(dest)
    except Exception as e:
        return f"Error downloading file: {e}"