Skip to main content

error_envelope

Function error_envelope 

Source
pub fn error_envelope(body: &str) -> Option<ErrorEnvelope>
Expand description

Recognise a JSON error envelope in an error response body or an in-band error event.

Recognised shapes:

  • OpenAI: {"error": {"message", "type", "code", "param"}}. Current vLLM and Ollama’s OpenAI-compatible /v1 endpoints send it too (vLLM with a numeric code), and Anthropic’s {"type": "error", "error": {"type", "message"}} reads the same way.
  • Legacy vLLM, and other bare error objects: {"object": "error", "message", "type", "param", "code"}.
  • Native Ollama: {"error": "message"}.

Anything else, including an empty or non-JSON body, returns None.

The envelope’s message is the provider’s own text. Attach it with ErrorEnvelope::apply, which puts it in Error::with_upstream_message. Never put it in the constructor message of an authored error: upstream text may echo prompts or input values. The constructor message is the adapter’s own text; for HTTP errors the bundled providers use HTTP {status}, with or without an envelope:

use allama::Error;
use allama_http::{error_envelope, status_error};

fn map_http_error(status: u16, body: &str) -> Error {
    let envelope = error_envelope(body).unwrap_or_default();
    envelope
        .apply(status_error(status, format!("HTTP {status}")).authored())
        .with_body(body.to_owned())
}

let err = map_http_error(
    400,
    r#"{"error": {"message": "bad value 'my SSN is 123-45-6789'", "param": "messages.[0].content"}}"#,
);
assert_eq!(
    err.as_log().to_string(),
    r#"kind=invalid_request status=400 param=messages.[0].content body_len=92 message="HTTP 400""#,
);
assert_eq!(err.upstream_message(), Some("bad value 'my SSN is 123-45-6789'"));

// An unrecognised body never reaches the message.
let err = map_http_error(502, "<html>my SSN is 123-45-6789</html>");
assert_eq!(err.to_string(), "provider error (502): HTTP 502");

A caller that already parsed the body (an NDJSON line, an SSE event’s data) reads it with error_envelope_value.