xtekky/gpt4free · error · RuntimeError

Failed to upload file: {res_json}

Error message

Failed to upload file: {res_json}

What it means

Raised by DeepAI's file upload step when the POST to the attachment endpoint returns 200 but the JSON body does not contain success=true, so no attachment uuid can be returned. The upload flow is a prerequisite for chatting with images/files on api.deepai.org. The error embeds the raw response JSON, which usually reveals a size/type rejection or an invalid generated api key.

Source

Thrown at g4f/Provider/DeepAI.py:75

            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"
        )
        hash2 = myhashfunction(user_agent + hash1)
        hash3 = myhashfunction(user_agent + hash2)

        return f"tryit-{myrandomstr}-{hash3}"

View on GitHub (pinned to 973504e177)

Solutions

  1. Inspect the res_json embedded in the message to see the exact upstream reason (type/size/key rejection).
  2. Convert or re-encode the media to a common format (png/jpg for images) and retry with a smaller file.
  3. Update g4f to the latest version so DeepAI.py matches the current DeepAI upload API.
  4. If the API changed, patch g4f/Provider/DeepAI.py locally to follow the new success/uuid response shape.

Example fix

// before
media = open('heic_file.heic', 'rb').read()
result = await DeepAI.create_async_generator(model, messages, media=[('heic_file.heic', media)])

// after
from PIL import Image
img = Image.open('heic_file.heic').convert('RGB').resize((1024, 1024))
buf = io.BytesIO(); img.save(buf, format='JPEG', quality=85)
result = await DeepAI.create_async_generator(model, messages, media=[('file.jpg', buf.getvalue())])
Defensive patterns

Strategy: try-catch

Validate before calling

from pathlib import Path
ALLOWED = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}

def media_ok(name: str, size: int) -> bool:
    return Path(name).suffix.lower() in ALLOWED and 0 < size <= 10 * 1024 * 1024

Try / catch

try:
    result = await DeepAI.create_async_generator(model, messages, media=media)
except RuntimeError as e:
    if 'Failed to upload file' in str(e):
        # inspect embedded JSON, convert media, or fall back to text-only
        result = await DeepAI.create_async_generator(model, messages)
    else:
        raise

Prevention

When it happens

Trigger: Calling DeepAI chat with image/file attachments; the upload POST to the DeepAI attachment endpoint succeeds HTTP-wise but returns JSON with success=false or missing 'attachment.uuid' (e.g. unsupported media type, file too large, or the client-generated api key from generate_api_key being rejected).

Common situations: Passing a media type DeepAI's attachment API does not accept; oversized files; upstream DeepAI changing its upload API contract (field names, uuid path); stale g4f version where generate_api_key hash recipe no longer matches.

Related errors


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