{"record":{"id":"46ba26e41b8f5049","repo":"nikivdev/code","slug":"openai-api-error","errorCode":null,"errorMessage":"OpenAI API error {}: {}","messagePattern":"OpenAI API error (.+?): (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/commit.rs","lineNumber":12947,"sourceCode":"            let delay = Duration::from_secs(2u64.pow(attempt));\n            print!(\"Retrying in {}s... \", delay.as_secs());\n            io::stdout().flush().ok();\n            std::thread::sleep(delay);\n        }\n\n        match client\n            .post(\"https://api.openai.com/v1/chat/completions\")\n            .header(\"Authorization\", format!(\"Bearer {}\", api_key))\n            .json(&body)\n            .send()\n        {\n            Ok(resp) => {\n                if !resp.status().is_success() {\n                    let status = resp.status();\n                    let text = resp.text().unwrap_or_default();\n                    // Don't retry client errors (4xx)\n                    if status.is_client_error() {\n                        bail!(\"OpenAI API error {}: {}\", status, text);\n                    }\n                    last_error = Some(format!(\"OpenAI API error {}: {}\", status, text));\n                    continue;\n                }\n\n                let parsed: ChatResponse =\n                    resp.json().context(\"failed to parse OpenAI response\")?;\n\n                let message = parsed\n                    .choices\n                    .first()\n                    .and_then(|c| c.message.as_ref())\n                    .map(|m| m.content.trim().to_string())\n                    .unwrap_or_default();\n\n                if message.is_empty() {\n                    bail!(\"OpenAI returned empty commit message\");\n                }","sourceCodeStart":12929,"sourceCodeEnd":12965,"githubUrl":"https://github.com/nikivdev/code/blob/a747e741ae92c09071d0ae946ab48488adcff1ce/src/commit.rs#L12929-L12965","documentation":"Thrown inside the OpenAI retry loop when the API returns a 4xx client error, which is treated as non-retryable. The status code and response body are embedded in the bail message; 5xx errors instead go to `last_error` and are retried.","triggerScenarios":"OpenAI API returns 400/401/403/404/422: invalid API key, malformed request body, unsupported/retired model name, or request exceeding the model's context window.","commonSituations":"Expired or revoked OPENAI_API_KEY; model renamed/retired (old model id in config); request payload too large for the model's context window; organization blocked or billing disabled.","solutions":["Verify the API key is valid and has quota (e.g. GET /v1/models with the key).","Check the model name in configuration matches a current OpenAI model.","Reduce the prompt/diff size if the error body mentions token/context limits.","Read the response body embedded in the error — it contains OpenAI's specific error code."],"exampleFix":"// before\nbail!(\"OpenAI API error {}: {}\", status, text);\n// after\nbail!(\"OpenAI API error {}: {} (check OPENAI_API_KEY and model name)\", status, text);","handlingStrategy":"validation","validationCode":"// Pre-check API key before calling OpenAI\nif std::env::var(\"OPENAI_API_KEY\").map(|k| k.is_empty()).unwrap_or(true) {\n    return Err(anyhow!(\"OPENAI_API_KEY is not set\"));\n}","typeGuard":null,"tryCatchPattern":"match result {\n    Err(e) if e.to_string().contains(\"OpenAI API error 401\") => {\n        eprintln!(\"Invalid OpenAI key: run the key setup again\");\n        Err(e)\n    }\n    Err(e) if e.to_string().contains(\"OpenAI API error 4\") => {\n        eprintln!(\"Client error, not retrying: {e}\");\n        Err(e)\n    }\n    other => other,\n}","preventionTips":["Verify OPENAI_API_KEY validity before scripted runs.","Keep model names up to date with OpenAI's current catalog.","Respect the context-window limit when sending diffs.","Never retry 4xx errors; fix the request instead."],"tags":["api","openai","http-4xx","authentication"],"backgroundTag":"openai-api-client-error","analyzedSha":"a747e741ae92c09071d0ae946ab48488adcff1ce","analyzedAt":"2026-09-01T22:43:55.719Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}