Hmbown/CodeWhale · error · anyhow::Error

FIM response missing choices[0].text

Error message

FIM response missing choices[0].text

What it means

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.

Solutions

  1. Print/log response_text (and HTTP status) before parsing to confirm what the endpoint actually returned
  2. Verify the configured FIM URL is the legacy /v1/completions (FIM) endpoint, not /v1/chat/completions
  3. Check the API key/auth — providers often return error JSON with HTTP 200; handle the /error field explicitly
  4. Confirm the model ID supports completions with text responses for the provider in use
  5. Add a pre-check for an /error object or empty /choices array before extracting text

Example fix

// before
let text = value
    .pointer("/choices/0/text")
    .and_then(serde_json::Value::as_str)
    .ok_or_else(|| anyhow::anyhow!("FIM response missing choices[0].text"))?;
// after
if let Some(err) = value.pointer("/error") {
    anyhow::bail!("FIM API returned error: {err}");
}
let text = value
    .pointer("/choices/0/text")
    .and_then(serde_json::Value::as_str)
    .ok_or_else(|| {
        anyhow::anyhow!("FIM response missing choices[0].text: {}", response_text)
    })?;
Defensive patterns

Strategy: validation

Validate before calling

let value: serde_json::Value = serde_json::from_str(&response_text)?;
if value.get("error").is_some() {
    return Err(anyhow!("FIM API error: {}", value["error"]));
}
let has_text = value
    .pointer("/choices/0/text")
    .map(|v| v.is_string())
    .unwrap_or(false);
if !has_text {
    return Err(anyhow!("unexpected FIM response: {response_text}"));
}

Type guard

fn is_valid_fim_response(v: &serde_json::Value) -> bool {
    v.pointer("/choices/0/text").map(serde_json::Value::is_string).unwrap_or(false)
}

Try / catch

match parse_fim_response(&response_text) {
    Ok(text) => text,
    Err(e) => { log::warn!("FIM response malformed: {e:#}; body={response_text}"); fallback_to_local_completion() }
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Background: "invalid response format", "malformed payload", "missing data field": when an API returns 200 but the response shape is wrong — this error's family across 23 libraries.

Related errors


AI-assisted analysis of Hmbown/CodeWhale@73e0f67d83 (2026-09-22). Data as JSON: /api/errors/8156c77f24aaddf8. Report an issue: GitHub.

Appendix: source

Thrown at crates/tui/src/client.rs:5144

        if !status.is_success() {
            let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await;
            let error_text = sanitize_http_error_body(
                Some(self.api_provider.display_name()),
                status.as_u16(),
                &raw_error_text,
            );
            anyhow::bail!("FIM API error: HTTP {status}: {error_text}");
        }
        let response_text = response
            .text()
            .await
            .context("Failed to read FIM API response body")?;
        let value: serde_json::Value =
            serde_json::from_str(&response_text).context("Failed to parse FIM API response")?;
        let text = value
            .pointer("/choices/0/text")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| anyhow::anyhow!("FIM response missing choices[0].text"))?;
        Ok(text.to_string())
    }
}

mod anthropic;
mod chat;
mod deepseek_effort;
#[cfg(test)]
mod ds4_tests;
mod prepared;
mod provider_native_search;
mod responses;
mod role_placement;
mod stream_entry;
mod wire;

// Retain the crate-visible accounting helpers at the existing client seam.
pub(super) use wire::{parse_usage, saturating_u32};

View on GitHub (pinned to 73e0f67d83)