{"record":{"id":"a55737b42b82e6ce","repo":"BerriAI/litellm","slug":"bfl-initial-request-failed-initial-response-text-a55737","errorCode":null,"errorMessage":"BFL initial request failed: {initial_response.text}","messagePattern":"BFL initial request failed: (.+?)","errorType":"exception","errorClass":"BlackForestLabsError","httpStatus":null,"severity":"error","filePath":"litellm/llms/black_forest_labs/image_generation/handler.py","lineNumber":301,"sourceCode":"            litellm_params=litellm_params_dict,\n            encoding=None,\n        )\n\n    def _poll_for_result_sync(\n        self,\n        initial_response: httpx.Response,\n        headers: dict,\n        sync_client: HTTPHandler,\n        max_wait: float = DEFAULT_MAX_POLLING_TIME,\n        interval: float = DEFAULT_POLLING_INTERVAL,\n        timeout: float | httpx.Timeout | None = None,\n    ) -> httpx.Response:\n        \"\"\"\n        Poll BFL API until result is ready (sync version).\n        \"\"\"\n        # Validate initial response status code\n        if initial_response.status_code >= 400:\n            raise BlackForestLabsError(\n                status_code=initial_response.status_code,\n                message=f\"BFL initial request failed: {initial_response.text}\",\n            )\n\n        # Parse initial response to get polling URL\n        try:\n            response_data: Final = initial_response.json()\n        except Exception as e:\n            raise BlackForestLabsError(\n                status_code=initial_response.status_code,\n                message=f\"Error parsing initial response: {e}\",\n            )\n\n        # Check for immediate errors\n        if \"errors\" in response_data:\n            raise BlackForestLabsError(\n                status_code=initial_response.status_code,\n                message=f\"BFL error: {response_data['errors']}\",","sourceCodeStart":283,"sourceCodeEnd":319,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/llms/black_forest_labs/image_generation/handler.py#L283-L319","documentation":"In the sync BFL polling flow, the initial generation POST returned an HTTP status >= 400 and the handler re-raises it verbatim as BlackForestLabsError with the upstream status code and body text. Unlike 'Request failed', this is a real HTTP response from BFL (or whatever serves your base_url), so the status code and body carry the diagnosis (401 bad key, 422 bad params, 429 rate limit, 404 wrong endpoint/model).","triggerScenarios":"Invalid or revoked BFL API key (401/403); wrong model name like `flux-pro-1.2-ultra` when the account lacks access (403/404); malformed request params - bad aspect_ratio, width/height not in allowed set (422); exceeding credits or rate limits (429); custom base_url missing the `/v1` prefix producing 404.","commonSituations":"New integration with an unset/expired BFL_API_KEY env var; copy-pasting a model id from BFL docs that the key's plan doesn't cover; passing width/height values BFL doesn't support; free-tier credit exhaustion during a demo; base_url configured without the correct path.","solutions":["Match the status code: 401/403 -> fix BFL_API_KEY / plan access; 422 -> fix request params per the BFL API docs; 429 -> slow down or add retries with backoff; 404 -> fix base_url/model id.","Print the full message body - BFL includes a human-readable reason in the JSON it returns.","Confirm the key works directly: `curl -H \"x-key: $BFL_API_KEY\" https://api.bfl.ai/v1/...`.","Check your BFL account credits/billing if generation previously worked."],"exampleFix":"# before: model id typo / unsupported params\nresp = litellm.image_generation(model=\"flux-pro-1.5\", width=123, height=456, prompt=\"sunset\")\n\n# after: valid model + allowed dimensions\nresp = litellm.image_generation(model=\"flux-pro-1.1\", width=1024, height=768, prompt=\"sunset\")","handlingStrategy":"try-catch","validationCode":"import os, urllib.request, json\n\ndef bfl_key_valid(key: str) -> bool:\n    req = urllib.request.Request(\n        \"https://api.bfl.ai/v1/flux-pro-1.1\",  # lightweight endpoint per BFL docs\n        headers={\"x-key\": key, \"Content-Type\": \"application/json\"},\n        method=\"POST\", data=json.dumps({\"prompt\": \"ping\"}).encode(),\n    )\n    try:\n        urllib.request.urlopen(req, timeout=10)\n        return True\n    except urllib.error.HTTPError as e:\n        return e.code not in (401, 403)   # 422/429 still means the key is accepted\n    except Exception:\n        return False\n\nassert bfl_key_valid(os.environ[\"BFL_API_KEY\"]) or warn(\"BFL key rejected\")","typeGuard":null,"tryCatchPattern":"from litellm.llms.black_forest_labs.common_utils import BlackForestLabsError\n\ntry:\n    resp = litellm.image_generation(model=\"flux-pro-1.1\", prompt=p)\nexcept BlackForestLabsError as e:\n    if e.status_code in (401, 403):\n        rotate_bfl_key()                      # auth path\n    elif e.status_code == 422:\n        fix_request_params(e)                 # body names the bad field\n    elif e.status_code == 429:\n        schedule_retry_backoff(e)\n    else:\n        raise","preventionTips":["Fail fast on missing BFL_API_KEY at startup rather than at first request.","Validate model-specific params (width/height/aspect_ratio) against BFL docs before sending.","Branch handling on status_code - auth, validation, and rate limit need different responses."],"tags":["litellm","black-forest-labs","flux","http-4xx","auth","rate-limit","bad-request"],"backgroundTag":"http-4xx-client-error","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}