Skip to content

download_file

autogen.tools.experimental.google.drive.drive_functions.download_file #

download_file(service, file_id, file_name, mime_type, download_folder)

Download or export file based on its MIME type.

Source code in autogen/tools/experimental/google/drive/drive_functions.py
@require_optional_import(
    [
        "googleapiclient",
    ],
    "google-api",
)
def download_file(service: Any, file_id: str, file_name: str, mime_type: str, download_folder: Path) -> str:
    """Download or export file based on its MIME type."""
    file_extension = _get_file_extension(mime_type)
    if file_extension and (not file_name.endswith(file_extension)):
        file_name = f"{file_name}.{file_extension}"

    # Define export formats for Google Docs, Sheets, and Slides
    export_mime_types = {
        "application/vnd.google-apps.document": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",  # Google Docs → Word
        "application/vnd.google-apps.spreadsheet": "text/csv",  # Google Sheets → CSV
        "application/vnd.google-apps.presentation": "application/vnd.openxmlformats-officedocument.presentationml.presentation",  # Google Slides → PowerPoint
    }

    # Google Docs, Sheets, and Slides cannot be downloaded directly using service.files().get_media() because they are Google-native files
    if mime_type in export_mime_types:
        request = service.files().export(fileId=file_id, mimeType=export_mime_types[mime_type])
    else:
        # Download normal files (videos, images, etc.)
        request = service.files().get_media(fileId=file_id)

    # Save file
    with io.BytesIO() as buffer:
        downloader = MediaIoBaseDownload(buffer, request)
        done = False
        while not done:
            _, done = downloader.next_chunk()

        file_path = download_folder / file_name
        with open(file_path, "wb") as f:
            f.write(buffer.getvalue())

    return f"✅ Downloaded: {file_name}"