{"record":{"id":"8156c77f24aaddf8","repo":"Hmbown/CodeWhale","slug":"fim-response-missing-choices-0-text","errorCode":null,"errorMessage":"FIM response missing choices[0].text","messagePattern":"FIM response missing choices\\[0\\]\\.text","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"crates/tui/src/client.rs","lineNumber":5144,"sourceCode":"        if !status.is_success() {\n            let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await;\n            let error_text = sanitize_http_error_body(\n                Some(self.api_provider.display_name()),\n                status.as_u16(),\n                &raw_error_text,\n            );\n            anyhow::bail!(\"FIM API error: HTTP {status}: {error_text}\");\n        }\n        let response_text = response\n            .text()\n            .await\n            .context(\"Failed to read FIM API response body\")?;\n        let value: serde_json::Value =\n            serde_json::from_str(&response_text).context(\"Failed to parse FIM API response\")?;\n        let text = value\n            .pointer(\"/choices/0/text\")\n            .and_then(serde_json::Value::as_str)\n            .ok_or_else(|| anyhow::anyhow!(\"FIM response missing choices[0].text\"))?;\n        Ok(text.to_string())\n    }\n}\n\nmod anthropic;\nmod chat;\nmod deepseek_effort;\n#[cfg(test)]\nmod ds4_tests;\nmod prepared;\nmod provider_native_search;\nmod responses;\nmod role_placement;\nmod stream_entry;\nmod wire;\n\n// Retain the crate-visible accounting helpers at the existing client seam.\npub(super) use wire::{parse_usage, saturating_u32};","sourceCodeStart":5126,"sourceCodeEnd":5162,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/73e0f67d83c59909b571efdfc88c4bc28c309cb1/crates/tui/src/client.rs#L5126-L5162","documentation":"The FIM (fill-in-the-middle) completion endpoint returned JSON that parsed successfully but has no string at /choices/0/text. The library expects an OpenAI-style completion response with a non-empty choices array whose first element carries a text field; anything else (error JSON, different schema, empty choices) triggers this anyhow error.","triggerScenarios":"The provider returned a JSON body without choices[0].text — e.g. an OpenAI-style error object ({\"error\":{...}}) returned with HTTP 200, an empty choices array, a chat-completions response (choices[0].message instead of text), or a proxy/gateway rewriting the response schema.","commonSituations":"Pointing the FIM client at a chat-completions endpoint instead of a legacy completions endpoint; auth failure where the provider returns an error body with 200; an API version change changing the response shape; a misconfigured base URL hitting a dashboard or HTML-to-JSON gateway response.","solutions":["Print/log response_text (and HTTP status) before parsing to confirm what the endpoint actually returned","Verify the configured FIM URL is the legacy /v1/completions (FIM) endpoint, not /v1/chat/completions","Check the API key/auth — providers often return error JSON with HTTP 200; handle the /error field explicitly","Confirm the model ID supports completions with text responses for the provider in use","Add a pre-check for an /error object or empty /choices array before extracting text"],"exampleFix":"// before\nlet text = value\n    .pointer(\"/choices/0/text\")\n    .and_then(serde_json::Value::as_str)\n    .ok_or_else(|| anyhow::anyhow!(\"FIM response missing choices[0].text\"))?;\n// after\nif let Some(err) = value.pointer(\"/error\") {\n    anyhow::bail!(\"FIM API returned error: {err}\");\n}\nlet text = value\n    .pointer(\"/choices/0/text\")\n    .and_then(serde_json::Value::as_str)\n    .ok_or_else(|| {\n        anyhow::anyhow!(\"FIM response missing choices[0].text: {}\", response_text)\n    })?;","handlingStrategy":"validation","validationCode":"let value: serde_json::Value = serde_json::from_str(&response_text)?;\nif value.get(\"error\").is_some() {\n    return Err(anyhow!(\"FIM API error: {}\", value[\"error\"]));\n}\nlet has_text = value\n    .pointer(\"/choices/0/text\")\n    .map(|v| v.is_string())\n    .unwrap_or(false);\nif !has_text {\n    return Err(anyhow!(\"unexpected FIM response: {response_text}\"));\n}","typeGuard":"fn is_valid_fim_response(v: &serde_json::Value) -> bool {\n    v.pointer(\"/choices/0/text\").map(serde_json::Value::is_string).unwrap_or(false)\n}","tryCatchPattern":"match parse_fim_response(&response_text) {\n    Ok(text) => text,\n    Err(e) => { log::warn!(\"FIM response malformed: {e:#}; body={response_text}\"); fallback_to_local_completion() }\n}","preventionTips":["Point FIM calls at the completions endpoint, not chat-completions","Log the raw response body on parse failure so schema drift is visible","Validate the response status code and /error object before extracting choices","Pin and test against the provider API version in CI"],"tags":["api","json","unexpected-response-shape"],"backgroundTag":"unexpected-api-response-shape","analyzedSha":"73e0f67d83c59909b571efdfc88c4bc28c309cb1","analyzedAt":"2026-09-22T01:30:00.501Z","contentChangedAt":"2026-09-22T01:30:00.501Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}