xtekky/gpt4free · error · RuntimeError

Failed to upload file: {response.status} {error_text}

Error message

Failed to upload file: {response.status} {error_text}

What it means

DeepAI's file-attachment helper POSTs to https://api.deepai.org/chat_attachments/upload and raises on any non-OK status, including the body text. Common failures: 401/403 (invalid or missing api-key header), 413 (file too large), 422/400 (unsupported file type), and 429 (rate limit). Note the upload headers deliberately strip content-type and api-key from the generic header set, so auth may ride on cookies/other headers.

Source

Thrown at g4f/Provider/DeepAI.py:69

        content_type, _ = mimetypes.guess_type(filename)
        content_type = content_type or "image/png"

        data = FormData()
        data.add_field("file", file_data, filename=filename, content_type=content_type)
        upload_headers = {
            k: v
            for k, v in headers.items()
            if k.lower() not in ["content-type", "api-key"]
        }
        async with session.post(
            "https://api.deepai.org/chat_attachments/upload",
            headers=upload_headers,
            data=data,
            proxy=proxy,
        ) as response:
            if not response.ok:
                error_text = await response.text()
                raise RuntimeError(
                    f"Failed to upload file: {response.status} {error_text}"
                )
            res_json = await response.json()
            if res_json.get("success"):
                return res_json["attachment"]["uuid"]
            raise RuntimeError(f"Failed to upload file: {res_json}")

    @classmethod
    def generate_api_key(cls, user_agent: str) -> str:
        myrandomstr = str(round(random.random() * 100000000000))

        def myhashfunction(input_str: str) -> str:
            return hashlib.md5(input_str.encode("utf-8")).hexdigest()[::-1]

        hash1 = myhashfunction(
            user_agent
            + myrandomstr
            + "hackers_become_a_little_stinkier_every_time_they_hack"

View on GitHub (pinned to 973504e177)

Solutions

  1. Read the status in the message: 401/403 → regenerate the API key (cls.generate_api_key) or refresh session; 413 → compress/resize the file; 422 → convert to a supported format; 429 → back off
  2. Verify the media tuple format (mime type, filename, bytes) matches what the provider expects
  3. Check file size against DeepAI's documented attachment limit before uploading

Example fix

# before
async for chunk in DeepAI.create_async_generator(model, messages, media=[("image/png", "pic.png", huge_bytes)]):
    ...

# after — validate before upload
if len(huge_bytes) > 10 * 1024 * 1024:
    raise ValueError('Attachment exceeds 10MB limit')
async for chunk in DeepAI.create_async_generator(model, messages, media=[("image/png", "pic.png", huge_bytes)]):
    ...
Defensive patterns

Strategy: validation

Validate before calling

MAX_UPLOAD_BYTES = 10 * 1024 * 1024
SUPPORTED_MIMES = {"image/png", "image/jpeg", "image/gif", "image/webp"}

def media_is_uploadable(media):
    mime, name, data = media
    return (
        mime in SUPPORTED_MIMES
        and len(data) <= MAX_UPLOAD_BYTES
        and len(data) > 0
    )

assert all(media_is_uploadable(m) for m in media or [])

Type guard

def is_valid_media_list(media) -> bool:
    if not media:
        return True
    return all(
        isinstance(m, (tuple, list)) and len(m) == 3
        and isinstance(m[0], str) and '/' in m[0]
        and isinstance(m[1], str)
        and isinstance(m[2], (bytes, bytearray)) and len(m[2]) > 0
        for m in media
    )

Try / catch

try:
    async for chunk in DeepAI.create_async_generator(model, messages, media=media):
        yield chunk
except RuntimeError as e:
    text = str(e)
    if ' 413 ' in text:
        raise ValueError('Attachment too large for DeepAI')
    elif ' 401 ' in text or ' 403 ' in text:
        raise AuthNeeded('DeepAI API key/session invalid')
    else:
        raise

Prevention

When it happens

Trigger: Uploading an oversized or unsupported file type; expired/invalid DeepAI API key or session; uploading with media bytes that are empty or corrupted; rate-limited after repeated uploads.

Common situations: Passing images larger than DeepAI's limit; api-key header excluded and session not established beforehand; sending a filename without a recognized extension; MIME sniffing failing on binary data.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/efddb9132460bec7. Report an issue: GitHub.