{"record":{"id":"98c947532f7ecebe","repo":"xtekky/gpt4free","slug":"failed-to-upload-file-res-json","errorCode":null,"errorMessage":"Failed to upload file: {res_json}","messagePattern":"Failed to upload file: (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"g4f/Provider/DeepAI.py","lineNumber":75,"sourceCode":"            k: v\n            for k, v in headers.items()\n            if k.lower() not in [\"content-type\", \"api-key\"]\n        }\n        async with session.post(\n            \"https://api.deepai.org/chat_attachments/upload\",\n            headers=upload_headers,\n            data=data,\n            proxy=proxy,\n        ) as response:\n            if not response.ok:\n                error_text = await response.text()\n                raise RuntimeError(\n                    f\"Failed to upload file: {response.status} {error_text}\"\n                )\n            res_json = await response.json()\n            if res_json.get(\"success\"):\n                return res_json[\"attachment\"][\"uuid\"]\n            raise RuntimeError(f\"Failed to upload file: {res_json}\")\n\n    @classmethod\n    def generate_api_key(cls, user_agent: str) -> str:\n        myrandomstr = str(round(random.random() * 100000000000))\n\n        def myhashfunction(input_str: str) -> str:\n            return hashlib.md5(input_str.encode(\"utf-8\")).hexdigest()[::-1]\n\n        hash1 = myhashfunction(\n            user_agent\n            + myrandomstr\n            + \"hackers_become_a_little_stinkier_every_time_they_hack\"\n        )\n        hash2 = myhashfunction(user_agent + hash1)\n        hash3 = myhashfunction(user_agent + hash2)\n\n        return f\"tryit-{myrandomstr}-{hash3}\"\n","sourceCodeStart":57,"sourceCodeEnd":93,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/Provider/DeepAI.py#L57-L93","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Inspect the res_json embedded in the message to see the exact upstream reason (type/size/key rejection).","Convert or re-encode the media to a common format (png/jpg for images) and retry with a smaller file.","Update g4f to the latest version so DeepAI.py matches the current DeepAI upload API.","If the API changed, patch g4f/Provider/DeepAI.py locally to follow the new success/uuid response shape."],"exampleFix":"// before\nmedia = open('heic_file.heic', 'rb').read()\nresult = await DeepAI.create_async_generator(model, messages, media=[('heic_file.heic', media)])\n\n// after\nfrom PIL import Image\nimg = Image.open('heic_file.heic').convert('RGB').resize((1024, 1024))\nbuf = io.BytesIO(); img.save(buf, format='JPEG', quality=85)\nresult = await DeepAI.create_async_generator(model, messages, media=[('file.jpg', buf.getvalue())])","handlingStrategy":"try-catch","validationCode":"from pathlib import Path\nALLOWED = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}\n\ndef media_ok(name: str, size: int) -> bool:\n    return Path(name).suffix.lower() in ALLOWED and 0 < size <= 10 * 1024 * 1024","typeGuard":null,"tryCatchPattern":"try:\n    result = await DeepAI.create_async_generator(model, messages, media=media)\nexcept RuntimeError as e:\n    if 'Failed to upload file' in str(e):\n        # inspect embedded JSON, convert media, or fall back to text-only\n        result = await DeepAI.create_async_generator(model, messages)\n    else:\n        raise","preventionTips":["Pre-convert media to png/jpg before passing to DeepAI","Cap file size client-side (~10MB)","Log the embedded res_json to distinguish type vs key rejection","Keep g4f updated — DeepAI upload API shifts often"],"tags":["deepai","file-upload","media","image","upstream-api"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}