Skip to main content

rig_core/providers/openai/wire/
chat.rs

1//! Chat Completions: the request built as JSON, and one lenient decoder for
2//! a whole reply and a stream of chunks.
3//!
4//! ```
5//! use rig_core::providers::openai::OpenAI;
6//! let wire = OpenAI::new("key").chat("gpt-5.2");
7//! ```
8
9use serde::{Deserialize, Serialize};
10use serde_json::{Map, Value, json};
11use std::borrow::Cow;
12use std::sync::Arc;
13
14use crate::catalog::ModelFacts;
15use crate::completion::options::{BaseInput, RawAt, Rewrite, request_params};
16use crate::completion::{CompletionRequest, FinishReason, ProviderCapabilities, Replay};
17use crate::error::{EncodeError, ProviderError};
18use crate::json_utils::Lenient;
19use crate::json_utils::remove_preserving_order;
20use crate::message::{
21    AssistantContent, AssistantMessage, DocumentData, DocumentMediaType,
22    DocumentSourceKind as Source, Message, MimeType, ToolCall, ToolResult, ToolResultContent,
23    UserContent,
24};
25use crate::operation::{Block, CallFragment, Completion, Finish};
26use crate::providers::internal::object;
27use crate::providers::internal::wire::classify_chat_completions_frame;
28use crate::providers::internal::wire_ids::WireIds;
29use crate::wire::{
30    Capabilities, Decoder, Descriptor, Encoded, Flow, Framing, Mode, Out, Wire, WireEvent,
31    WireFrame,
32};
33use finish::{finish_reason, native_finish_reason, provider_error_envelope};
34
35use super::dto::merge_fields;
36use super::{BodyRewrite, OpenAIConfig, OutputCap, Quirks};
37
38/// The chat-completions wire: a provider configuration, a model, and the
39/// per-turn options the endpoint takes.
40#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
41pub struct Chat {
42    /// Which provider, and how to reach it.
43    pub provider: OpenAIConfig,
44    /// The model this wire addresses.
45    pub model: String,
46    /// Whether tool schemas are sanitized for OpenAI's strict mode:
47    /// `additionalProperties: false` on every object, every property
48    /// required, and `strict: true` on each function definition.
49    pub strict_tools: bool,
50    /// Whether tool-result messages serialize their content as arrays.
51    pub tool_result_array_content: bool,
52    /// The model facts the encoder reads and replies are priced by.
53    #[serde(skip)]
54    pub facts: ModelFacts,
55}
56
57/// The error for media in a form Chat Completions cannot carry, which the
58/// adapter replaces before a request is encoded
59/// ([`ReplayTarget::encodes`](crate::completion::ReplayTarget::encodes)).
60fn unsendable(what: &str) -> EncodeError {
61    EncodeError::request(format!("Chat Completions cannot carry {what} in this form"))
62}
63
64/// `data` as a URL a content part names: a URL, or typed base64 data as a
65/// data URI.
66fn media_url(data: &Source, mime: Option<&str>) -> Option<String> {
67    match (data, mime) {
68        (Source::Url(url), _) => Some(url.clone()),
69        (Source::Base64(data), Some(mime)) => Some(format!("data:{mime};base64,{data}")),
70        _ => None,
71    }
72}
73
74/// The `image_url` part an image is sent as; a user image always names a
75/// detail level, `auto` by default.
76fn image_url(image: &crate::message::Image, user: bool) -> Result<Value, EncodeError> {
77    let mime = image.media_type.as_ref().map(MimeType::to_mime_type);
78    let url = media_url(&image.data, mime).ok_or_else(|| unsendable("an image"))?;
79    let mut part = Map::from_iter([("url".to_owned(), Value::String(url))]);
80    let detail = match &image.detail {
81        Some(detail) => Some(detail.clone()),
82        None => user.then(Default::default),
83    };
84    if let Some(detail) = detail {
85        part.insert("detail".to_owned(), serde_json::to_value(detail)?);
86    }
87    Ok(object! {"type": "image_url", "image_url": part})
88}
89
90/// One user content part as Chat Completions carries it.
91fn user_part(part: &UserContent) -> Result<Value, EncodeError> {
92    let file = |file: Value| object! {"type": "file", "file": file};
93    Ok(match part {
94        UserContent::Text(text) => json!({"type": "text", "text": text.text}),
95        UserContent::Image(image) => image_url(image, true)?,
96        UserContent::Document(document) => {
97            let pdf = document.media_type == Some(DocumentMediaType::PDF);
98            match &document.data {
99                DocumentData::Text(text) => json!({"type": "text", "text": text}),
100                DocumentData::File(Source::FileId(id)) => file(json!({ "file_id": id })),
101                DocumentData::File(Source::Base64(data)) if pdf => file(object! {
102                    "file_data": format!("data:application/pdf;base64,{data}"),
103                    "filename": "document.pdf",
104                }),
105                // OpenRouter and Mistral fetch a PDF a URL names.
106                DocumentData::File(Source::Url(url)) if pdf => {
107                    file(json!({"file_data": url, "filename": "document.pdf"}))
108                }
109                DocumentData::File(_) => return Err(unsendable("a document")),
110            }
111        }
112        UserContent::Audio(audio) => match &audio.data {
113            Source::Base64(data) => json!({"type": "input_audio", "input_audio": {
114                "data": data,
115                "format": audio.media_type.clone().unwrap_or(crate::message::AudioMediaType::MP3),
116            }}),
117            _ => return Err(unsendable("audio")),
118        },
119        UserContent::Video(video) => {
120            let mime = video.media_type.as_ref().map(MimeType::to_mime_type);
121            let url = media_url(&video.data, mime).ok_or_else(|| unsendable("a video"))?;
122            object! {"type": "video_url", "video_url": object! {"url": url}}
123        }
124        UserContent::ToolResult(_) => return Err(unsendable("a tool result as a content part")),
125    })
126}
127
128/// A result as the `tool` message that answers its call: its text joined
129/// into one string, or its parts as an array when the wire asks for one or
130/// it holds an image, which has no string form.
131fn tool_message(result: &ToolResult, ids: &WireIds, array: bool) -> Result<Value, EncodeError> {
132    fn text(part: &ToolResultContent) -> Option<Cow<'_, str>> {
133        match part {
134            ToolResultContent::Text(text) => Some(Cow::Borrowed(&text.text)),
135            ToolResultContent::Json { value } => Some(Cow::Owned(value.to_string())),
136            ToolResultContent::Image(_) => None,
137        }
138    }
139    let image = |part: &ToolResultContent| matches!(part, ToolResultContent::Image(_));
140    let content = if array || result.content.iter().any(image) {
141        let parts = result.content.iter().map(|part| match part {
142            ToolResultContent::Image(image) => image_url(image, false),
143            _ => Ok(object! {"type": "text", "text": text(part).unwrap_or_default()}),
144        });
145        Value::Array(parts.collect::<Result<_, EncodeError>>()?)
146    } else {
147        let texts: Vec<Cow<'_, str>> = result.content.iter().filter_map(text).collect();
148        Value::String(texts.join("\n"))
149    };
150    let id = ids.spell(&result.call);
151    Ok(object! {"role": "tool", "tool_call_id": id, "content": content})
152}
153
154/// Push the user parts gathered so far as one message: a lone text part as
155/// a plain string.
156fn user_message(messages: &mut Vec<Value>, parts: &mut Vec<Value>) {
157    let content = match parts.as_mut_slice() {
158        [] => return,
159        [part] if part.str("type") == Some("text") => {
160            part.get_mut("text").map(Value::take).unwrap_or_default()
161        }
162        _ => Value::Array(std::mem::take(parts)),
163    };
164    parts.clear();
165    messages.push(object! {"role": "user", "content": content});
166}
167
168impl Chat {
169    /// The field every assistant message carries its reasoning under,
170    /// empty when the turn has none: the dialect's own,
171    /// `reasoning_content` for DeepSeek at any base URL, and the field a
172    /// catalog entry names for the model on this dialect, on Moonshot's own
173    /// API under its last path segment (Kimi K3 behind any gateway), or on
174    /// OpenRouter under its full id (`moonshotai/kimi-k2.6` behind any
175    /// gateway). Each lookup is asked for the field, not just the entry, so a
176    /// gateway's own row without one does not hide the vendor's.
177    fn reasoning_field<'a>(&'a self, model: &str) -> Option<&'a str> {
178        use crate::providers::openai::wire::{MOONSHOT, OPENROUTER};
179        let deepseek = self
180            .provider
181            .base_url
182            .to_ascii_lowercase()
183            .contains("deepseek.com");
184        let name = model.rsplit('/').next().unwrap_or(model);
185        let field = |vendor: &str, id: &str| {
186            self.facts
187                .for_model(vendor, id)
188                .and_then(|spec| spec.compat.reasoning_field.as_deref())
189        };
190        let listed = field(self.provider.dialect.name, model)
191            .or_else(|| field(MOONSHOT.name, name))
192            .or_else(|| field(OPENROUTER.name, model));
193        self.provider
194            .dialect
195            .quirks
196            .reasoning_field
197            .or(deepseek.then_some("reasoning_content"))
198            .or(listed)
199    }
200
201    /// The wire for `model` on `provider`, with every option off.
202    pub fn new(provider: OpenAIConfig, model: impl Into<String>) -> Self {
203        Self {
204            provider,
205            model: model.into(),
206            strict_tools: false,
207            tool_result_array_content: false,
208            facts: ModelFacts::default(),
209        }
210    }
211
212    /// The same wire, encoding with `facts` and pricing its replies by
213    /// them.
214    pub fn with_facts(mut self, facts: ModelFacts) -> Self {
215        self.facts = facts;
216        self
217    }
218
219    /// Sanitize tool schemas for the dialect's strict mode
220    /// ([`Quirks::strict_schema`]), so the provider can guarantee a tool
221    /// call matches its schema exactly. A dialect that
222    /// serves strict mode under a path prefix of its own
223    /// ([`Quirks::strict_tools_prefix`]) is sent there.
224    pub fn with_strict_tools(mut self) -> Self {
225        self.strict_tools = true;
226        self
227    }
228
229    /// Serialize tool-result content as arrays.
230    pub fn with_tool_result_array_content(mut self) -> Self {
231        self.tool_result_array_content = true;
232        self
233    }
234
235    /// The wire's own encoding of `request`: messages, tools and the typed
236    /// fields. The mapped options and `additional_params` merge over it.
237    fn base(
238        &self,
239        request: &CompletionRequest,
240        input: &mut BaseInput<'_>,
241    ) -> Result<Map<String, Value>, EncodeError> {
242        let quirks = &self.provider.dialect.quirks;
243        let model = request.model.clone().unwrap_or_else(|| self.model.clone());
244        let passthrough = input.raw_tools()?;
245        // A call to a custom tool the request declares is a custom call (pi).
246        let custom: Vec<String> = passthrough
247            .iter()
248            .filter(|tool| tool.str("type") == Some("custom"))
249            .filter_map(|tool| tool.at("/custom/name").and_then(Value::as_str))
250            .map(str::to_owned)
251            .collect();
252        let messages = self.messages(&request.chat_history, &model, &custom)?;
253
254        let mut tools: Vec<Value> = Vec::new();
255        let mut tool_choice = None;
256        if quirks.supports_tools {
257            for tool in &request.tools {
258                let mut parameters = tool.parameters.clone();
259                let mut function = json!({"name": tool.name, "description": tool.description});
260                let mut strict = self.strict_tools;
261                if strict {
262                    let mut sanitized = parameters.clone();
263                    match crate::providers::openai::sanitize_tool_schema(&mut sanitized, quirks) {
264                        Ok(()) => parameters = sanitized,
265                        Err(reason) => {
266                            tracing::warn!(
267                                tool = %tool.name,
268                                "sending the tool without strict mode: its schema holds {reason}, \
269                                 which this provider's strict mode cannot express"
270                            );
271                            strict = false;
272                        }
273                    }
274                }
275                if let Some(function) = function.as_object_mut() {
276                    function.insert("parameters".to_owned(), parameters);
277                    if strict {
278                        function.insert("strict".to_owned(), Value::Bool(true));
279                    }
280                }
281                tools.push(object! {"type": "function", "function": function});
282            }
283            // Passthrough tools, function or native (Groq's `browser_search`),
284            // join the typed ones in one array.
285            tools.extend(passthrough);
286            tool_choice = request
287                .tool_choice
288                .clone()
289                .map(tool_choice_value)
290                .transpose()?
291                .filter(|_| !tools.is_empty());
292        } else {
293            if !request.tools.is_empty() {
294                tracing::warn!("Tool use is not supported by this provider; tools will be ignored");
295            }
296            if request.tool_choice.is_some() {
297                tracing::warn!("Tool choice is not supported by this provider and will be ignored");
298            }
299            // The caller's own tools still reach a dialect that takes none,
300            // as `additional_params` always did.
301            tools.extend(passthrough);
302        }
303
304        if request.output_schema.is_some() && !quirks.supports_response_format {
305            tracing::warn!(
306                "Structured outputs are not supported by this provider; ignoring output_schema"
307            );
308        }
309        // Defer schemas until a tool result exists unless the dialect supports both at once.
310        let answered = messages
311            .iter()
312            .any(|message| message.str("role") == Some("tool"));
313        let response_format = match request.output_schema.clone() {
314            Some(schema)
315                if quirks.supports_response_format
316                    && (quirks.response_format_with_tools || tools.is_empty() || answered) =>
317            {
318                let (name, schema) = crate::providers::openai::structured_output_schema(schema);
319                Some(json!({"type": "json_schema",
320                    "json_schema": {"name": name, "strict": true, "schema": schema}}))
321            }
322            _ => None,
323        };
324
325        Ok(crate::providers::internal::set_fields([
326            ("model", Some(Value::String(model))),
327            ("messages", Some(Value::Array(messages))),
328            ("tools", (!tools.is_empty()).then_some(Value::Array(tools))),
329            ("tool_choice", tool_choice),
330            ("temperature", request.temperature.map(Value::from)),
331            ("max_tokens", request.max_tokens.map(Value::from)),
332            ("response_format", response_format),
333        ]))
334    }
335
336    /// The history as Chat messages, each call and result spelled by one
337    /// [`WireIds`].
338    fn messages(
339        &self,
340        history: &[Arc<Message>],
341        model: &str,
342        custom: &[String],
343    ) -> Result<Vec<Value>, EncodeError> {
344        let ids = WireIds::for_target(history, self, model);
345        let reasoning_field = self.reasoning_field(model);
346        let mut messages = Vec::new();
347        for message in history {
348            match &**message {
349                Message::System { content } => messages.push(json!({"role": "system",
350                    "content": [{"type": "text", "text": content}]})),
351                Message::User { content } => {
352                    let mut parts = Vec::new();
353                    for part in content {
354                        if let UserContent::ToolResult(result) = part {
355                            user_message(&mut messages, &mut parts);
356                            let array = self.tool_result_array_content;
357                            messages.push(tool_message(result, &ids, array)?);
358                        } else {
359                            parts.push(user_part(part)?);
360                        }
361                    }
362                    user_message(&mut messages, &mut parts);
363                }
364                Message::Assistant(turn) => {
365                    messages.extend(self.assistant(turn, &ids, custom, reasoning_field));
366                }
367            }
368        }
369        if messages.is_empty() {
370            return Err(EncodeError::request(
371                "OpenAI Chat Completions request has no provider-compatible messages after \
372                 conversion",
373            ));
374        }
375        Ok(messages)
376    }
377
378    /// One assistant turn rebuilt for the wire: text joined into a `content`
379    /// string, or a part array when a block is a content part (Mistral's
380    /// thinking); reasoning under the field it arrived in, or the dialect's;
381    /// an item's other fields beside it; and each call with its canonical
382    /// name and arguments. A message with neither content nor calls is
383    /// `None`.
384    fn assistant(
385        &self,
386        turn: &AssistantMessage,
387        ids: &WireIds,
388        custom: &[String],
389        reasoning_field: Option<&str>,
390    ) -> Option<Value> {
391        let (mut text, mut parts, mut has_parts) = (String::new(), Vec::new(), false);
392        let mut reasoning: Vec<(String, String)> = Vec::new();
393        let (mut fields, mut calls) = (Map::new(), Vec::new());
394        for block in &turn.content {
395            let replay = block.replay(self, ids);
396            match block {
397                AssistantContent::Text(block) => {
398                    text.push_str(&block.text);
399                    parts.push(json!({"type": "text", "text": block.text}));
400                    // A text item is message fields: an answer's audio.
401                    if let Replay::Item(item) = replay
402                        && let Value::Object(item) = item.into_owned()
403                    {
404                        fields.extend(item);
405                    }
406                }
407                AssistantContent::Reasoning(block) => {
408                    let field = match replay {
409                        Replay::Item(item) if item.get("type").is_some() => {
410                            has_parts = true;
411                            parts.push(item.into_owned());
412                            None
413                        }
414                        Replay::Item(item) => {
415                            let mut field = None;
416                            for (key, value) in item.as_object().into_iter().flatten() {
417                                if value.is_string() {
418                                    field.get_or_insert_with(|| key.clone());
419                                } else {
420                                    let detail = Map::from_iter([(key.clone(), value.clone())]);
421                                    merge_fields(&mut fields, &detail);
422                                }
423                            }
424                            field
425                        }
426                        Replay::Identity(identity)
427                            if identity.get("type").and_then(Value::as_str) == Some("thinking") =>
428                        {
429                            has_parts = true;
430                            parts.push(json!({"type": "thinking",
431                                "thinking": [{"type": "text", "text": block.text}]}));
432                            None
433                        }
434                        Replay::Identity(identity) => identity.keys().next().cloned(),
435                        Replay::Rebuild => reasoning_field.map(str::to_owned),
436                    };
437                    if let Some(field) = field {
438                        match reasoning.iter_mut().find(|(name, _)| *name == field) {
439                            Some((_, joined)) => {
440                                joined.push('\n');
441                                joined.push_str(&block.text);
442                            }
443                            None => reasoning.push((field, block.text.clone())),
444                        }
445                    }
446                }
447                AssistantContent::ToolCall(call) => {
448                    calls.push(call_item(call, replay, ids, custom));
449                }
450                // An opaque is a content part; one with no `type` is not
451                // sent, so its keys never land on the message.
452                AssistantContent::Opaque(opaque) if opaque.replay => {
453                    if opaque.item.get("type").is_some() {
454                        has_parts = true;
455                        parts.push(opaque.item.clone());
456                    }
457                }
458                AssistantContent::Opaque(_) | AssistantContent::Image(_) => {}
459            }
460        }
461        let mut message = Map::from_iter([("role".to_owned(), Value::from("assistant"))]);
462        if has_parts {
463            message.insert("content".to_owned(), Value::Array(parts));
464        } else if !text.is_empty() {
465            message.insert("content".to_owned(), Value::String(text));
466        }
467        for (field, text) in reasoning {
468            message.insert(field, Value::String(text));
469        }
470        message.extend(fields);
471        if !calls.is_empty() {
472            message.insert("tool_calls".to_owned(), Value::Array(calls));
473        }
474        let has_content = message.contains_key("audio")
475            || message.contains_key("tool_calls")
476            || match message.get("content") {
477                Some(Value::String(text)) => !text.is_empty(),
478                Some(Value::Array(parts)) => !parts.is_empty(),
479                _ => false,
480            };
481        if let Some(field) = reasoning_field {
482            message
483                .entry(field)
484                .or_insert_with(|| Value::String(String::new()));
485        }
486        has_content.then_some(Value::Object(message))
487    }
488}
489
490/// The dialect's rewrite of the finished body ([`BodyRewrite`]): a refusal
491/// where the provider would answer with an error or silently do something
492/// else, Moonshot's steering for `required`, and each dialect's spellings and
493/// content shapes. It runs after the merge and reads the merged body.
494pub(crate) fn rewrite_body(
495    kind: BodyRewrite,
496    map: &mut Map<String, Value>,
497) -> Result<(), EncodeError> {
498    let forced = map
499        .get("tool_choice")
500        .and_then(|choice| choice.at("/function/name"))
501        .and_then(Value::as_str)
502        .map(str::to_owned);
503    match kind {
504        BodyRewrite::LlamaCpp => {
505            if let Some(name) = forced {
506                return Err(EncodeError::request(format!(
507                    "llama.cpp cannot force a specific tool: `llama-server` accepts only \
508                     `auto`, `none` or `required` for tool_choice and silently treats \
509                     anything else as `auto`, so requesting `{name}` would return whichever \
510                     tool the model picked. Use `ToolChoice::Required` to force a call, or \
511                     advertise only `{name}` in `tools`."
512                )));
513            }
514        }
515        BodyRewrite::Moonshot => {
516            if forced.is_some() {
517                return Err(EncodeError::request(
518                    "Moonshot does not support forcing a specific tool",
519                ));
520            }
521            if map.get("tool_choice").and_then(Value::as_str) == Some("required") {
522                tracing::warn!(
523                    "Moonshot does not support tool_choice=required; coercing to auto with an \
524                     additional steering message"
525                );
526                map.insert("tool_choice".to_owned(), Value::from("auto"));
527                if let Some(Value::Array(messages)) = map.get_mut("messages") {
528                    messages.push(json!({"role": "user",
529                        "content": "Please select a tool to handle the current issue."}));
530                }
531            }
532        }
533        // The gateway takes every message's content as one string.
534        // Perplexity spends output budget on a text-part array (a short
535        // `max_tokens` comes back empty at `length`, checked live), so
536        // text-only arrays go as one string; the gateway takes every
537        // content as one string.
538        BodyRewrite::Perplexity | BodyRewrite::Mira => {
539            let all = kind == BodyRewrite::Mira;
540            for content in messages_mut(map).filter_map(|message| message.get_mut("content")) {
541                if let Value::Array(parts) = content
542                    && (all || parts.iter().all(|part| part.str("type") == Some("text")))
543                {
544                    let texts: Vec<&str> =
545                        parts.iter().filter_map(|part| part.str("text")).collect();
546                    *content = Value::String(texts.join("\n"));
547                }
548            }
549        }
550        BodyRewrite::DeepSeek => finalize_deepseek(map),
551        BodyRewrite::Mistral => finalize_mistral(map),
552        BodyRewrite::Ollama => finalize_ollama(map)?,
553        BodyRewrite::None | BodyRewrite::OpenRouter | BodyRewrite::HuggingFaceRouter => {}
554    }
555    Ok(())
556}
557
558/// Select `route` on the Hugging Face router by suffixing the merged body's
559/// `model` with `:slug`. A model already selecting another provider or
560/// policy is an error rather than a model with two suffixes.
561pub(crate) fn select_router_provider(
562    route: &super::SubRoute,
563    map: &mut Map<String, Value>,
564) -> Result<(), EncodeError> {
565    let Some(Value::String(model)) = map.get_mut("model") else {
566        return Ok(());
567    };
568    if let Some((_, selected)) = model.rsplit_once(':')
569        && selected != route.slug()
570    {
571        return Err(EncodeError::request(format!(
572            "the model `{model}` already selects `{selected}` on the Hugging Face router, \
573             which conflicts with the configured sub-provider `{route}`"
574        )));
575    }
576    *model = route.model_identifier(model);
577    Ok(())
578}
579
580/// `call` as the item the wire sends, from what replay hands the encoder:
581/// the current item, an edited one's kind, or nothing. A call is `custom`
582/// when its item or kept kind says so, or when it is rebuilt and the request
583/// declares a custom tool by its name; its arguments' `input` is then
584/// its input. Any other is a function call with its arguments as JSON text.
585fn call_item(call: &ToolCall, replay: Replay<'_>, ids: &WireIds, custom: &[String]) -> Value {
586    let mut item = match replay {
587        Replay::Item(item) => match item.into_owned() {
588            Value::Object(item) => item,
589            _ => Map::new(),
590        },
591        Replay::Identity(identity) => identity,
592        Replay::Rebuild => Map::new(),
593    };
594    let name = call.function.name.as_str();
595    let custom = match item.get("type").and_then(Value::as_str) {
596        Some(kind) => kind == "custom",
597        None => {
598            let declared = custom.iter().any(|tool| tool == name);
599            let kind = if declared { "custom" } else { "function" };
600            item.insert("type".to_owned(), Value::from(kind));
601            declared
602        }
603    };
604    let id = ids.spell(&call.id);
605    item.insert("id".to_owned(), Value::String(id));
606    let (slot, key, value) = if custom {
607        let input = match call.function.arguments.get("input") {
608            Some(Value::String(input)) => input.clone(),
609            Some(input) => input.to_string(),
610            None => String::new(),
611        };
612        ("custom", "input", input)
613    } else {
614        let arguments = serde_json::to_string(&call.function.arguments).unwrap_or_default();
615        ("function", "arguments", arguments)
616    };
617    let slot = item
618        .entry(slot)
619        .or_insert_with(|| Value::Object(Map::new()));
620    if !slot.is_object() {
621        *slot = Value::Object(Map::new());
622    }
623    if let Value::Object(fields) = slot {
624        fields.insert("name".to_owned(), Value::from(name));
625        fields.insert(key.to_owned(), Value::String(value));
626    }
627    Value::Object(item)
628}
629
630/// The Chat `tool_choice` for a canonical one.
631fn tool_choice_value(choice: crate::message::ToolChoice) -> Result<Value, EncodeError> {
632    use crate::message::ToolChoice;
633    Ok(match choice {
634        ToolChoice::Auto => Value::from("auto"),
635        ToolChoice::None => Value::from("none"),
636        ToolChoice::Required => Value::from("required"),
637        ToolChoice::Specific { function_names } => {
638            let [name] = function_names.as_slice() else {
639                return Err(EncodeError::request(
640                    "Provider only supports forcing exactly one specific tool",
641                ));
642            };
643            json!({"type": "function", "function": {"name": name}})
644        }
645    })
646}
647
648/// Ollama's OpenAI-compatible body: `num_ctx` and `options` are refused,
649/// because this API ignores them and only the native route sends them.
650fn finalize_ollama(map: &mut Map<String, Value>) -> Result<(), EncodeError> {
651    if let Some(key) = ["num_ctx", "options"]
652        .into_iter()
653        .find(|key| map.contains_key(*key))
654    {
655        return Err(EncodeError::request(format!(
656            "Ollama's OpenAI-compatible API ignores `{key}`; send it through the native \
657             route (`Ollama::native_completion`)"
658        )));
659    }
660    Ok(())
661}
662
663/// The body's messages, each as its object.
664fn messages_mut(map: &mut Map<String, Value>) -> impl Iterator<Item = &mut Map<String, Value>> {
665    let messages = map.get_mut("messages").and_then(Value::as_array_mut);
666    messages
667        .into_iter()
668        .flatten()
669        .filter_map(Value::as_object_mut)
670}
671
672/// DeepSeek rejects a forced tool choice while thinking, and every model
673/// but `deepseek-chat` thinks unless `thinking` says `disabled` (checked
674/// live), so the choice is relaxed to the default there.
675fn finalize_deepseek(map: &mut Map<String, Value>) {
676    let thinking = match map
677        .get("thinking")
678        .and_then(|thinking| thinking.str("type"))
679    {
680        Some(mode) => !mode.eq_ignore_ascii_case("disabled"),
681        None => map.get("model").and_then(Value::as_str) != Some("deepseek-chat"),
682    };
683    let forced = map
684        .get("tool_choice")
685        .is_some_and(|choice| choice.is_object() || choice.as_str() == Some("required"));
686    if thinking && forced {
687        tracing::debug!(
688            "dropping tool_choice: DeepSeek rejects a forced tool choice while thinking"
689        );
690        remove_preserving_order(map, "tool_choice");
691    }
692}
693
694/// Mistral's wire-level differences: a forced tool choice relaxed beside a
695/// structured format, and its content chunks.
696fn finalize_mistral(map: &mut Map<String, Value>) {
697    // Mistral rejects forced tool calls beside JSON response formats: the
698    // choice is relaxed rather than the schema discarded.
699    let forces_a_tool_call = map
700        .get("tool_choice")
701        .is_some_and(|choice| !matches!(choice.as_str(), Some("auto" | "none")));
702    let has_tools = map
703        .get("tools")
704        .and_then(Value::as_array)
705        .is_some_and(|tools| !tools.is_empty());
706    let structured = map
707        .get("response_format")
708        .and_then(|format| format.str("type"))
709        .is_some_and(|kind| matches!(kind, "json_schema" | "json_object"));
710    if forces_a_tool_call && has_tools && structured {
711        tracing::debug!(
712            "relaxing tool_choice to `auto`: Mistral rejects a forced tool choice \
713             alongside a response format"
714        );
715        map.insert("tool_choice".to_owned(), Value::from("auto"));
716    }
717    for content in messages_mut(map).filter_map(|message| message.get_mut("content")) {
718        for part in content.as_array_mut().into_iter().flatten() {
719            *part = mistral_chunk(part);
720        }
721    }
722}
723
724/// One content part as the Mistral chunk that carries it, by its `type`:
725/// text and refusal parts are `text` chunks, a file's data is a
726/// `document_url` and its id a `file` chunk, audio is its base64 string,
727/// and an image keeps only its `image_url`, for every chunk forbids unknown
728/// keys. A part the conversion does not emit stays as it is.
729fn mistral_chunk(part: &Value) -> Value {
730    let field = |pointer: &str| part.at(pointer).and_then(Value::as_str);
731    match part.str("type") {
732        Some("image_url") => {
733            json!({"type": "image_url", "image_url": part.get("image_url")})
734        }
735        Some("input_audio") => json!({"type": "input_audio",
736            "input_audio": field("/input_audio/data")}),
737        Some("file") => match field("/file/file_data") {
738            Some(data) => json!({"type": "document_url", "document_url": data,
739                "document_name": field("/file/filename")}),
740            None => json!({"type": "file", "file_id": field("/file/file_id")}),
741        },
742        _ => part.clone(),
743    }
744}
745
746impl Wire for Chat {
747    type Op = crate::operation::Completion;
748    type Payload = crate::wire::Encoded;
749    type Frame = crate::wire::WireFrame;
750    type Event = ChatEvent;
751    type Decoder<'id> = ChatDecoder;
752    type Reassembler = document::ChatCompletion;
753
754    /// Format deferral permits tool composition; dialects without schema
755    /// support require the agent's tool-mode enforcement instead.
756    fn describe(&self) -> Descriptor<'_> {
757        Descriptor::new(self.provider.dialect.name)
758            .model(self.model.as_str())
759            .facts(&self.facts)
760            .capabilities(Capabilities::completion(
761                ProviderCapabilities::default().with_native_output_tool_composition(
762                    self.provider.dialect.quirks.supports_response_format,
763                ),
764            ))
765            .replay(self)
766    }
767
768    fn encode(&self, request: CompletionRequest, mode: Mode) -> Result<Encoded, EncodeError> {
769        let quirks = &self.provider.dialect.quirks;
770        let base = self.provider.base_url.trim_end_matches('/');
771        let prefix = quirks
772            .strict_tools_prefix
773            .filter(|prefix| self.strict_tools && !base.ends_with(prefix))
774            .unwrap_or_default();
775        let path = format!("{prefix}{}", quirks.completion_path);
776        // Azure's deployment URL remains pinned to the handle, not a request override.
777        let uri = self
778            .provider
779            .uri(&path, self.provider.deployment(&self.model));
780        let builder = self.provider.completion_headers(
781            &request,
782            http::Request::post(uri).header("Content-Type", "application/json"),
783        );
784        let mut rewrites = Vec::new();
785        if quirks.output_cap == OutputCap::OpenAiReasoningFamilies {
786            rewrites.push(Rewrite::OutputCapRename);
787        }
788        if mode == Mode::Streaming {
789            // A caller's own stream options, `include_usage` among them, stand.
790            if quirks.stream_include_usage {
791                rewrites.push(Rewrite::StreamUsage);
792            }
793            rewrites.push(Rewrite::Stream(true));
794        }
795        rewrites.push(Rewrite::ChatDialect(quirks.rewrite));
796        if quirks.rewrite == BodyRewrite::HuggingFaceRouter
797            && let Some(route) = &self.provider.sub_route
798        {
799            rewrites.push(Rewrite::RouterProvider(route.clone()));
800        }
801        let raw_at = match quirks.rewrite {
802            BodyRewrite::Mira => RawAt::Ignored(
803                "Additional parameters are not supported by Mira and will be ignored",
804            ),
805            _ => RawAt::Top,
806        };
807        let body = request_params(
808            self,
809            &request,
810            |input| self.base(&request, input),
811            raw_at,
812            &rewrites,
813        )?;
814        let body = crate::providers::openai::options::check_body(
815            self,
816            &self.facts,
817            &request,
818            body,
819            crate::providers::openai::options::Endpoint::ChatCompletions,
820        )?;
821        crate::providers::internal::trace_json(
822            crate::providers::internal::LogTarget::Completions,
823            "OpenAI Chat Completions request",
824            &body,
825        );
826        let request = builder.body(body.into_body())?;
827        let framing = match mode {
828            Mode::Streaming => Framing::Sse,
829            Mode::Unary => Framing::Whole,
830        };
831        Ok(Encoded::new(request, framing)
832            .with_request_id_header(self.provider.dialect.request_id_header))
833    }
834
835    fn decoder<'id>(&self) -> Self::Decoder<'id> {
836        ChatDecoder::new(self.provider.dialect.quirks)
837    }
838}
839
840impl crate::completion::ReplayTarget for Chat {
841    /// Whether the catalog prices this dialect's replies
842    /// ([`Quirks::catalog_priced`]).
843    fn catalog_priced(&self) -> bool {
844        self.provider.dialect.quirks.catalog_priced
845    }
846
847    /// Section 6.2 of the typed-options design, by dialect.
848    fn map_options(
849        &self,
850        request: &CompletionRequest,
851        fields: crate::completion::options::OptionFields<'_>,
852    ) -> crate::completion::options::OptionMap {
853        crate::providers::openai::options::chat_options(self, request, fields)
854    }
855
856    fn facts(&self) -> Option<&ModelFacts> {
857        Some(&self.facts)
858    }
859
860    fn api(&self) -> crate::message::Api {
861        crate::message::Api::from_static("openai.chat")
862    }
863
864    fn provider(&self) -> &str {
865        self.provider.dialect.name
866    }
867
868    fn model(&self) -> &str {
869        &self.model
870    }
871
872    /// Chat reads no images in assistant messages, images in tool results
873    /// only on a dialect that says so, and tools where the dialect takes
874    /// them. Which models read user images follows each provider's
875    /// documented model rules (`reads_images`). Another model's reasoning
876    /// goes under the model's reasoning field, when it has one.
877    fn accepts(&self, model: &str) -> crate::completion::Accepts {
878        let quirks = &self.provider.dialect.quirks;
879        let user_images = reads_images(&self.facts, &self.provider.dialect, model);
880        crate::completion::Accepts {
881            user_images,
882            assistant_images: false,
883            tool_result_images: user_images && quirks.supports_image_tool_results,
884            tools: quirks.supports_tools,
885            foreign_reasoning: self.reasoning_field(model).is_some(),
886        }
887    }
888
889    /// What the Chat encoder carries, by dialect: an image as a URL or
890    /// typed data; audio as data; video as a URL or typed data, except to
891    /// OpenAI, Azure and Mistral; a PDF as data, or as a URL OpenRouter or
892    /// Mistral fetches; a file id where the dialect takes one; and a text
893    /// document as text. Mira takes text only; DeepSeek, Perplexity and
894    /// Cohere take no media but images, and Ollama only images as data.
895    fn encodes(&self, _model: &str, media: crate::completion::Media<'_>) -> bool {
896        use crate::completion::Media;
897        let dialect = &self.provider.dialect;
898        let rewrite = dialect.quirks.rewrite;
899        let parts = rewrite != BodyRewrite::Mira;
900        // DeepSeek, Cohere and Ollama read images and text, and no other media.
901        let files = parts
902            && !matches!(rewrite, BodyRewrite::Perplexity | BodyRewrite::DeepSeek)
903            && ![super::dialects::COHERE.name, super::dialects::OLLAMA.name]
904                .contains(&dialect.name);
905        let linked = |source: &Source, typed: bool| match source {
906            Source::Url(_) => true,
907            Source::Base64(_) => typed,
908            Source::Raw(_) | Source::FileId(_) | Source::Unknown => false,
909        };
910        match media {
911            Media::Image(image, place) => {
912                parts
913                    && place != crate::completion::Place::Assistant
914                    && linked(&image.data, image.media_type.is_some())
915                    // Ollama reads an image as data and never fetches a URL.
916                    && !(dialect.name == super::dialects::OLLAMA.name
917                        && matches!(image.data, Source::Url(_)))
918            }
919            Media::Audio(audio) => files && matches!(audio.data, Source::Base64(_)),
920            Media::Video(video) => {
921                files
922                    && rewrite != BodyRewrite::Mistral
923                    && ![super::dialects::OPENAI.name, super::dialects::AZURE.name]
924                        .contains(&dialect.name)
925                    && linked(&video.data, video.media_type.is_some())
926            }
927            Media::Document(document) => {
928                let pdf = document.media_type == Some(DocumentMediaType::PDF);
929                match &document.data {
930                    DocumentData::Text(_) => true,
931                    DocumentData::File(Source::FileId(_)) => {
932                        files && dialect.quirks.accepts_file_ids
933                    }
934                    DocumentData::File(Source::Base64(_)) => files && pdf,
935                    DocumentData::File(Source::Url(_)) => {
936                        pdf && matches!(rewrite, BodyRewrite::OpenRouter | BodyRewrite::Mistral)
937                    }
938                    DocumentData::File(Source::Raw(_) | Source::Unknown) => false,
939                }
940            }
941        }
942    }
943
944    /// A `call|item` id joins its sanitized halves with `_`, ending a result
945    /// over 40 characters in a hash of the whole id; OpenAI's own ids are
946    /// cut to 40; any other id is kept. Mistral takes any such id (checked
947    /// live on eight models).
948    fn normalize_tool_call_id(
949        &self,
950        id: &str,
951        _model: &str,
952        _: Option<&crate::message::Origin>,
953    ) -> String {
954        let sanitized =
955            |part: &str| crate::providers::internal::wire_ids::legal_call_id(part, usize::MAX);
956        if let Some((call, item)) = id.split_once('|') {
957            let call = sanitized(call);
958            let item = sanitized(item);
959            let combined = if item.is_empty() {
960                call.clone()
961            } else {
962                format!("{call}_{item}")
963            };
964            if combined.len() <= 40 {
965                return combined;
966            }
967            let hash: String = crate::providers::internal::wire_ids::short_hash(id)
968                .chars()
969                .take(8)
970                .collect();
971            let prefix: String = call.chars().take((40 - hash.len() - 1).max(1)).collect();
972            return format!("{prefix}_{hash}");
973        }
974        if self.provider.dialect.name == super::dialects::OPENAI.name {
975            return id.chars().take(40).collect();
976        }
977        id.to_owned()
978    }
979
980    /// What an edited block keeps of its item: a custom call's kind and
981    /// Mistral's thinking part (`type`), or the field reasoning arrived in.
982    /// Signed data such as `reasoning_details` or `thinking_blocks` never
983    /// survives an edit.
984    fn identity(&self, item: &Value) -> Map<String, Value> {
985        if let Some(kind @ ("custom" | "thinking")) = item.str("type") {
986            return Map::from_iter([("type".to_owned(), Value::from(kind))]);
987        }
988        REASONING_TEXT_KEYS
989            .iter()
990            .find(|key| item.get(**key).is_some_and(Value::is_string))
991            .map(|key| Map::from_iter([((*key).to_owned(), Value::String(String::new()))]))
992            .unwrap_or_default()
993    }
994
995    fn call_id_slot(&self) -> Option<&'static str> {
996        Some("/id")
997    }
998
999    /// A `thinking_blocks` entry's signature, or a redacted entry's data.
1000    fn blob_slots(&self) -> &'static [&'static str] {
1001        &["/thinking_blocks/*/signature", "/thinking_blocks/*/data"]
1002    }
1003
1004    fn later_system(&self, _model: &str) -> crate::completion::LaterSystem {
1005        self.provider.dialect.quirks.later_system
1006    }
1007
1008    /// In array mode a result's parts go as an array.
1009    fn result_parts(&self, _model: &str) -> bool {
1010        self.tool_result_array_content
1011    }
1012
1013    /// A Chat message needs content or calls: text
1014    /// only when it is not empty or its item carries audio, reasoning only
1015    /// as a content part (Mistral's thinking), an opaque item only as a
1016    /// typed part, and never an image.
1017    fn sends_alone(&self, block: &AssistantContent) -> bool {
1018        let replay = || block.replay(self, &WireIds::default());
1019        match block {
1020            AssistantContent::ToolCall(_) => true,
1021            AssistantContent::Text(text) => {
1022                !text.text.is_empty()
1023                    || matches!(replay(), Replay::Item(item) if item.get("audio").is_some())
1024            }
1025            AssistantContent::Reasoning(_) => match replay() {
1026                Replay::Item(item) => item.get("type").is_some(),
1027                Replay::Identity(identity) => {
1028                    identity.get("type").and_then(Value::as_str) == Some("thinking")
1029                }
1030                Replay::Rebuild => false,
1031            },
1032            AssistantContent::Opaque(opaque) => opaque.item.get("type").is_some(),
1033            AssistantContent::Image(_) => false,
1034        }
1035    }
1036}
1037
1038/// The catalog vendor whose entries say which models `vendor` serves read
1039/// images, and the naming rule for an id the catalog does not list:
1040/// `vendor` is a dialect's name or the vendor an OpenRouter model id starts
1041/// with. Groq reads images on its Llama 4 models; Mistral's Codestral and
1042/// Devstral are text models; OpenAI (on Azure too), xAI, Cohere, Z.AI,
1043/// Moonshot, MiniMax and MiMo apply the rules their other wires share;
1044/// DeepSeek's unlisted models do not read them, since its text models take
1045/// an image part and ignore it; any other vendor's unlisted model reads
1046/// them. `None` for Mira's gateway, which takes text, whatever the model.
1047fn image_rule(vendor: &str) -> Option<(&str, fn(&str) -> bool)> {
1048    use crate::providers::{minimax, moonshot, xiaomimimo, zai};
1049    Some(match vendor {
1050        "mira" => return None,
1051        "deepseek" => ("deepseek", |_| false),
1052        "groq" => ("groq", |model| model.contains("llama-4")),
1053        "mistral" | "mistralai" => ("mistral", |model| {
1054            !(model.starts_with("codestral") || model.starts_with("devstral"))
1055        }),
1056        "openai" | "azure.openai" => ("openai", crate::providers::openai::reads_images),
1057        "xai" | "x-ai" => ("xai", crate::providers::xai::reads_images),
1058        "cohere" => ("cohere", crate::providers::cohere::reads_images),
1059        "zai" | "z-ai" => ("zai", zai::reads_images),
1060        "moonshot" | "moonshotai" => ("moonshot", moonshot::reads_images),
1061        "minimax" => ("minimax", minimax::reads_images),
1062        "xiaomimimo" | "xiaomi" => ("xiaomimimo", xiaomimimo::reads_images),
1063        vendor => (vendor, |_| true),
1064    })
1065}
1066
1067/// Whether `model` reads user images on `dialect`, as the model catalog
1068/// lists it, or by the naming rule of [`image_rule`] for a model it does not
1069/// list. OpenRouter names a model `vendor/model`: its own catalog entry
1070/// decides, or failing that the vendor's naming rule.
1071fn reads_images(facts: &ModelFacts, dialect: &super::Dialect, model: &str) -> bool {
1072    match model.split_once('/') {
1073        Some((vendor, upstream)) if dialect.quirks.rewrite == BodyRewrite::OpenRouter => facts
1074            .reads_images_or(dialect.name, model, |_| {
1075                image_rule(vendor).is_some_and(|(_, rule)| rule(upstream))
1076            }),
1077        _ => image_rule(dialect.name)
1078            .is_some_and(|(vendor, rule)| facts.reads_images_or(vendor, model, rule)),
1079    }
1080}
1081
1082/// Classified Chat Completions frame, including whole replies and terminal signals.
1083pub enum ChatEvent {
1084    /// A `chat.completion.chunk`: one step of a streamed turn.
1085    Chunk(Value),
1086    /// A `chat.completion`: the whole turn in one frame.
1087    Whole(Value),
1088    /// The `[DONE]` sentinel: the provider ended the stream.
1089    Done,
1090    /// The wire's in-band error envelope, delivered with a 200 status.
1091    Failure(ProviderError),
1092    /// A bare JSON string where an envelope belongs: the whole answer, with
1093    /// no metadata and no terminal reason. Mira's gateway sends this.
1094    BareText(String),
1095}
1096
1097/// The keys an assistant message carries reasoning under, in the order
1098/// their text is read: compatible servers that send several send the same
1099/// text under each, so the first that carries text is the one replayed.
1100const REASONING_TEXT_KEYS: [&str; 3] = ["reasoning_content", "reasoning", "reasoning_text"];
1101
1102/// The keys an assistant message carries structured reasoning under, each
1103/// kept verbatim with the reasoning text: `reasoning_details`, and the
1104/// signed `thinking_blocks` a LiteLLM proxy returns for Claude.
1105const REASONING_DETAIL_KEYS: [&str; 2] = ["reasoning_details", "thinking_blocks"];
1106
1107/// What one content part of a Chat message is. Every part becomes a block.
1108#[derive(Debug, PartialEq)]
1109pub(crate) enum Part {
1110    /// Answer text: a `text` part, or a `refusal` part's text.
1111    Text(String),
1112    /// Mistral and Magistral reasoning: a `thinking` part's text.
1113    Thinking(String),
1114    /// An image the model produced.
1115    Image,
1116    /// A part rig has no canonical meaning for, kept as it came.
1117    Unknown,
1118}
1119
1120impl Part {
1121    /// The part `part` is, by its `type`. A part with no `type` and a
1122    /// string `text` is text.
1123    pub(crate) fn of(part: &Value) -> Self {
1124        let text = |key: &str| part.str(key).unwrap_or_default().to_owned();
1125        match part.str("type") {
1126            Some("text") => Self::Text(text("text")),
1127            None if part.str("text").is_some() => Self::Text(text("text")),
1128            Some("refusal") => Self::Text(text("refusal")),
1129            Some("thinking") => Self::Thinking(match part.get("thinking") {
1130                Some(Value::Array(chunks)) => chunks
1131                    .iter()
1132                    .filter_map(|chunk| chunk.str("text"))
1133                    .collect(),
1134                _ => text("thinking"),
1135            }),
1136            Some("image_url") => Self::Image,
1137            _ => Self::Unknown,
1138        }
1139    }
1140}
1141
1142/// What one tool call of a Chat message is.
1143#[derive(Debug, PartialEq)]
1144pub(crate) enum CallKind {
1145    /// A function call: its arguments are JSON text.
1146    Function,
1147    /// A custom tool call: its input is free text, the call's `{"input"}`.
1148    Custom,
1149    /// A call kind rig cannot answer, kept but never sent back.
1150    Unknown,
1151}
1152
1153impl CallKind {
1154    /// The kind of `call`, by its `type`; a call without one is a function
1155    /// call.
1156    pub(crate) fn of(call: &Value) -> Self {
1157        match call.str("type") {
1158            None | Some("function") => Self::Function,
1159            Some("custom") => Self::Custom,
1160            Some(_) => Self::Unknown,
1161        }
1162    }
1163}
1164
1165/// The kind of run a decoder is writing: answer text, or Mistral's
1166/// thinking parts, kept apart.
1167#[derive(Clone, Copy, PartialEq)]
1168enum Writing {
1169    Text,
1170    Thinking,
1171}
1172
1173/// A tool call the reply has open: its writer index, the id it states,
1174/// whether its kind is one rig cannot answer (an opaque item), and the
1175/// function arguments streamed so far.
1176struct OpenCall {
1177    at: usize,
1178    id: Option<String>,
1179    opaque: bool,
1180    arguments: String,
1181}
1182
1183/// The chat-completions decoder: one state machine for a whole reply and a
1184/// stream of chunks, reading every frame leniently as JSON. A whole reply
1185/// is the one chunk carrying its message. All of a message's reasoning is
1186/// one block, open until the message
1187/// ends; the turn holds it first however late it arrived, while its events
1188/// keep their arrival order. A run of text is a block, as is a run of
1189/// Mistral thinking parts, and each tool call, image and unknown content
1190/// part is a block of its own; a run closes when another block starts. An
1191/// answer's audio transcript is its text when it has no other, and its
1192/// first text block holds the audio's id.
1193#[derive(Default)]
1194pub struct ChatDecoder {
1195    quirks: Quirks,
1196    /// The run being written, its writer index, and a thinking run's text.
1197    writing: Option<(Writing, usize)>,
1198    thinking_text: String,
1199    /// The writer index of the message's reasoning block while it is open,
1200    /// and its item as it will hold it: the field its text arrived in, its
1201    /// text, and every structured reasoning entry in order, by key.
1202    reasoning: Option<usize>,
1203    reasoning_field: Option<&'static str>,
1204    reasoning_text: String,
1205    reasoning_details: Map<String, Value>,
1206    /// The id of the answer's audio.
1207    audio_id: Option<Value>,
1208    /// The calls still open, in the order they opened.
1209    calls: Vec<OpenCall>,
1210    usage: Option<Value>,
1211    /// The top-level [`reported::REPLY_FIELDS`] as last stated.
1212    reply_fields: Map<String, Value>,
1213    /// The writer index of the message's first text block, which the
1214    /// message-level citations cite.
1215    first_text: Option<usize>,
1216    /// The writer index of the latest text block, which a Mistral
1217    /// `reference` chunk after it cites.
1218    last_text: Option<usize>,
1219    /// Citations of the turn's first text block held until it opens:
1220    /// message annotations, and references that came before any text.
1221    turn_citations: Vec<crate::wire::WireCitation>,
1222    finish: Option<FinishReason>,
1223    response_id: Option<String>,
1224    response_model: Option<String>,
1225    /// Whether a finish reason or a whole reply ended the turn.
1226    ended: bool,
1227    /// Whether a stream chunk arrived.
1228    chunked: bool,
1229}
1230
1231impl ChatDecoder {
1232    fn new(quirks: Quirks) -> Self {
1233        Self {
1234            quirks,
1235            ..Self::default()
1236        }
1237    }
1238
1239    /// Absorb the metadata every frame carries, and take its primary choice.
1240    /// Usage is the frame's, or its choice's where Moonshot reports it.
1241    fn absorb<'f>(&mut self, frame: &'f Value) -> Option<&'f Value> {
1242        // Every chunk restates these; each is stored only when it changes.
1243        keep_text(&mut self.response_id, frame.str("id"));
1244        keep_text(&mut self.response_model, frame.str("model"));
1245        // `n > 1` streams interleave candidates told apart only by
1246        // `choices[].index`; candidate 0 is the turn, as in a whole reply.
1247        let choice = frame.arr("choices").iter().find(|choice| {
1248            let index = choice.get("index").and_then(Value::as_u64);
1249            index.is_none_or(|index| index == 0)
1250        });
1251        if let Some(usage) = frame
1252            .at("/usage")
1253            .or_else(|| choice.and_then(|choice| choice.at("/usage")))
1254            && self.usage.as_ref() != Some(usage)
1255        {
1256            self.usage = Some(usage.clone());
1257        }
1258        for key in reported::REPLY_FIELDS {
1259            if let Some(value) = frame.get(key).filter(|value| !value.is_null())
1260                && self.reply_fields.get(key) != Some(value)
1261            {
1262                self.reply_fields.insert(key.to_owned(), value.clone());
1263            }
1264        }
1265        let choice = choice?;
1266        // A gateway's upstream-native reason is consulted only when the
1267        // normalized field is absent or empty (OpenRouter's precedence).
1268        let reason = match choice
1269            .str("finish_reason")
1270            .filter(|reason| !reason.is_empty())
1271        {
1272            Some(reason) => Some(finish_reason(reason, &self.quirks)),
1273            None => choice
1274                .str("native_finish_reason")
1275                .filter(|reason| self.quirks.native_finish_reason && !reason.is_empty())
1276                .map(native_finish_reason),
1277        };
1278        if let Some(reason) = reason {
1279            self.finish = Some(reason);
1280            self.ended = true;
1281        }
1282        Some(choice)
1283    }
1284
1285    /// One delta of the assistant message: its reasoning text and
1286    /// structured reasoning into the reasoning block, then the content,
1287    /// images and calls.
1288    fn delta(
1289        &mut self,
1290        delta: &Map<String, Value>,
1291        out: &mut Out<'_, Completion>,
1292    ) -> Result<(), ProviderError> {
1293        let reasoning = REASONING_TEXT_KEYS.iter().find_map(|key| {
1294            delta
1295                .get(*key)
1296                .and_then(Value::as_str)
1297                .filter(|text| !text.is_empty())
1298                .map(|text| (*key, text))
1299        });
1300        if let Some((key, text)) = reasoning {
1301            self.reason(text, out)?;
1302            self.reasoning_field.get_or_insert(key);
1303        }
1304        for key in REASONING_DETAIL_KEYS {
1305            if let Some(Value::Array(details)) = delta.get(key)
1306                && !details.is_empty()
1307            {
1308                self.reason("", out)?;
1309                merge_details(&mut self.reasoning_details, key, details.clone());
1310            }
1311        }
1312        let audio = delta.get("audio");
1313        if let Some(id) = audio.and_then(|audio| audio.at("/id")) {
1314            self.audio_id = Some(id.clone());
1315        }
1316        match delta.get("content") {
1317            Some(Value::Array(parts)) => {
1318                for part in parts {
1319                    self.part(part, out)?;
1320                }
1321            }
1322            Some(part @ Value::Object(_)) => self.part(part, out)?,
1323            _ => {
1324                let text = ["content", "refusal"]
1325                    .iter()
1326                    .find_map(|key| {
1327                        delta
1328                            .get(*key)
1329                            .and_then(Value::as_str)
1330                            .filter(|text| !text.is_empty())
1331                    })
1332                    .or_else(|| audio.and_then(|audio| audio.str("transcript")))
1333                    .filter(|text| !text.is_empty());
1334                if let Some(text) = text {
1335                    self.write(Writing::Text, text, out)?;
1336                }
1337            }
1338        }
1339        for image in delta
1340            .get("images")
1341            .and_then(Value::as_array)
1342            .into_iter()
1343            .flatten()
1344        {
1345            self.image(image, out)?;
1346        }
1347        for call in delta
1348            .get("tool_calls")
1349            .and_then(Value::as_array)
1350            .into_iter()
1351            .flatten()
1352        {
1353            self.call(call, out)?;
1354        }
1355        self.turn_citations.extend(
1356            delta
1357                .get("annotations")
1358                .and_then(Value::as_array)
1359                .into_iter()
1360                .flatten()
1361                .filter_map(reported::annotation),
1362        );
1363        self.cite_turn(out);
1364        Ok(())
1365    }
1366
1367    /// Cite the turn's first text block with the citations held for it, as
1368    /// soon as it exists, so a reply cut off before its end keeps them.
1369    fn cite_turn(&mut self, out: &mut Out<'_, Completion>) {
1370        if let Some(text) = self.first_text {
1371            for citation in self.turn_citations.drain(..) {
1372                out.cite(text, citation);
1373            }
1374        }
1375    }
1376
1377    /// Append `text` to the message's reasoning block, opening it first.
1378    fn reason(&mut self, text: &str, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1379        let at = match self.reasoning {
1380            Some(at) => at,
1381            None => {
1382                let at = out.fresh_index();
1383                out.open(at, Block::Reasoning { redacted: false }, Value::Null)?;
1384                out.lead(at)?;
1385                self.reasoning = Some(at);
1386                at
1387            }
1388        };
1389        self.reasoning_text.push_str(text);
1390        out.push(at, text)
1391    }
1392
1393    /// Close the message's reasoning block, holding its item: the field its
1394    /// text arrived in and its details.
1395    fn close_reasoning(&mut self, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1396        let Some(at) = self.reasoning.take() else {
1397            return Ok(());
1398        };
1399        let text = std::mem::take(&mut self.reasoning_text);
1400        let mut item = Map::new();
1401        if let Some(field) = self.reasoning_field.take() {
1402            item.insert(field.to_owned(), text.into());
1403        }
1404        item.append(&mut self.reasoning_details);
1405        out.edit(at, |slot| *slot = Value::Object(item))?;
1406        out.finish(at)
1407    }
1408
1409    /// Append `text` to a block of kind `writing`, first closing the block
1410    /// being written and opening a new one when that is of another kind.
1411    fn write(
1412        &mut self,
1413        writing: Writing,
1414        text: &str,
1415        out: &mut Out<'_, Completion>,
1416    ) -> Result<(), ProviderError> {
1417        let index = match self.writing {
1418            Some((current, index)) if current == writing => index,
1419            _ => {
1420                self.close_writing(out)?;
1421                let index = out.fresh_index();
1422                let block = match writing {
1423                    Writing::Thinking => Block::Reasoning { redacted: false },
1424                    Writing::Text => {
1425                        self.first_text.get_or_insert(index);
1426                        self.last_text = Some(index);
1427                        Block::Text
1428                    }
1429                };
1430                out.open(index, block, Value::Null)?;
1431                self.writing = Some((writing, index));
1432                index
1433            }
1434        };
1435        if writing == Writing::Thinking {
1436            self.thinking_text.push_str(text);
1437        }
1438        out.push(index, text)
1439    }
1440
1441    /// Close the run being written, holding its item: the thinking part,
1442    /// or the audio's id.
1443    fn close_writing(&mut self, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1444        let (index, item) = match self.writing.take() {
1445            None => return Ok(()),
1446            Some((Writing::Text, index)) => (
1447                index,
1448                self.audio_id
1449                    .take()
1450                    .map(|id| json!({ "audio": { "id": id } })),
1451            ),
1452            Some((Writing::Thinking, index)) => {
1453                let text = std::mem::take(&mut self.thinking_text);
1454                (
1455                    index,
1456                    Some(json!({"type": "thinking", "thinking": [{"type": "text", "text": text}]})),
1457                )
1458            }
1459        };
1460        if let Some(item) = item {
1461            out.edit(index, |slot| *slot = item)?;
1462        }
1463        out.finish(index)
1464    }
1465
1466    /// One content part, through [`Part::of`].
1467    #[deny(clippy::wildcard_enum_match_arm)]
1468    fn part(&mut self, part: &Value, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1469        match Part::of(part) {
1470            Part::Text(text) => self.write(Writing::Text, &text, out),
1471            Part::Thinking(text) => self.write(Writing::Thinking, &text, out),
1472            Part::Image => self.image(part, out),
1473            Part::Unknown => {
1474                self.close_writing(out)?;
1475                if let Some(citation) = reported::reference(part) {
1476                    match self.last_text {
1477                        Some(text) => out.cite(text, citation),
1478                        None => self.turn_citations.push(citation),
1479                    }
1480                }
1481                let index = out.fresh_index();
1482                out.whole(index, Block::Opaque { replay: true }, part.clone(), "")
1483            }
1484        }
1485    }
1486
1487    /// One image the model produced, an `image_url` part, whole: a data URL
1488    /// becomes base64 data, any other URL stays a URL.
1489    fn image(&mut self, part: &Value, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1490        use crate::message::{Image, ImageMediaType};
1491        let url = part
1492            .at("/image_url/url")
1493            .or_else(|| part.get("image_url"))
1494            .and_then(Value::as_str)
1495            .unwrap_or_default();
1496        let inline = url
1497            .strip_prefix("data:")
1498            .and_then(|rest| rest.split_once(";base64,"));
1499        let mut image = Image::default();
1500        let data = match inline {
1501            Some((mime, data)) => {
1502                image.data = Source::Base64(String::new());
1503                image.media_type = ImageMediaType::from_mime_type(mime);
1504                data
1505            }
1506            None => {
1507                image.data = Source::Url(url.to_owned());
1508                ""
1509            }
1510        };
1511        self.close_writing(out)?;
1512        let index = out.fresh_index();
1513        out.whole(index, Block::Image(image), part.clone(), data)
1514    }
1515
1516    /// One tool-call fragment. It goes to the call at its wire index, where
1517    /// the writer tells a new id under it from the call it held. Without an
1518    /// index (or with `null`) it goes to the open call that states its id;
1519    /// one that states no id continues the latest call while that call's
1520    /// arguments are not yet a whole object, and otherwise opens a new call
1521    /// when it brings a name or arguments. Its fields merge into the call's
1522    /// item.
1523    fn call(&mut self, call: &Value, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1524        self.close_writing(out)?;
1525        let id = call.as_object().and_then(document::stated_id);
1526        let index = call
1527            .get("index")
1528            .and_then(Value::as_u64)
1529            .and_then(|index| usize::try_from(index).ok());
1530        let arguments = call
1531            .at("/function/arguments")
1532            .map(crate::json_utils::value_to_json_string);
1533        let name = call
1534            .at("/function/name")
1535            .or_else(|| call.at("/custom/name"))
1536            .and_then(Value::as_str);
1537        let starts = name.is_some_and(|name| !name.is_empty())
1538            || arguments.as_deref().is_some_and(|text| !text.is_empty());
1539        let at = match index {
1540            Some(index) => index,
1541            None => match id.as_deref() {
1542                Some(id) => self
1543                    .calls
1544                    .iter()
1545                    .find(|open| open.id.as_deref() == Some(id)),
1546                None => self.calls.last().filter(|open| {
1547                    open.opaque || !crate::json_utils::is_whole_object(&open.arguments) || !starts
1548                }),
1549            }
1550            .map_or_else(|| out.fresh_index(), |open| open.at),
1551        };
1552        let opaque = match self.calls.iter_mut().find(|open| open.at == at) {
1553            Some(open) => {
1554                if id.is_some() {
1555                    open.id.clone_from(&id);
1556                }
1557                open.arguments
1558                    .push_str(arguments.as_deref().unwrap_or_default());
1559                open.opaque
1560            }
1561            None => {
1562                let opaque = CallKind::of(call) == CallKind::Unknown;
1563                if opaque {
1564                    out.open(at, Block::Opaque { replay: false }, Value::Null)?;
1565                }
1566                self.calls.push(OpenCall {
1567                    at,
1568                    id: id.clone(),
1569                    opaque,
1570                    arguments: arguments.clone().unwrap_or_default(),
1571                });
1572                opaque
1573            }
1574        };
1575        if !opaque {
1576            out.fragment(
1577                Some(at),
1578                CallFragment {
1579                    id: id.as_deref(),
1580                    name,
1581                    arguments: arguments.as_deref(),
1582                },
1583            )?;
1584        }
1585        out.edit(at, |item| {
1586            if !item.is_object() {
1587                *item = Value::Object(Map::new());
1588            }
1589            if let (Value::Object(item), Some(fields)) = (item, call.as_object()) {
1590                merge_fields(item, fields);
1591                // The index orders the stream; the call it assembles has none.
1592                remove_preserving_order(item, "index");
1593            }
1594        })
1595    }
1596
1597    /// Close the open calls, with their items as natives: every one at the
1598    /// end (`all`), only those whose arguments are whole at a finish chunk,
1599    /// since a provider may still send fragments after it. A custom call's
1600    /// arguments are its `{"input"}`. A call the output budget cut before
1601    /// its arguments were a whole object, or before any came, closes with
1602    /// no native: the provider never stated it complete.
1603    fn close_calls(
1604        &mut self,
1605        out: &mut Out<'_, Completion>,
1606        all: bool,
1607    ) -> Result<(), ProviderError> {
1608        let cut = self.finish == Some(FinishReason::Length);
1609        let mut waiting = Vec::new();
1610        for call in std::mem::take(&mut self.calls) {
1611            if call.opaque {
1612                out.finish(call.at)?;
1613                continue;
1614            }
1615            let (mut input, mut complete) = (None, false);
1616            out.edit(call.at, |item| {
1617                if CallKind::of(item) == CallKind::Custom {
1618                    let custom = item.at("/custom/input").cloned();
1619                    input = Some(custom.unwrap_or_else(|| Value::from("")));
1620                }
1621                complete = match item.at("/function/arguments") {
1622                    // Blank text reads as `{}`, but under the limit it is a
1623                    // call cut before its arguments.
1624                    Some(Value::String(text)) if cut && text.trim().is_empty() => false,
1625                    Some(Value::String(text)) => matches!(
1626                        crate::json_utils::parse_tool_arguments(text),
1627                        Ok(Value::Object(_))
1628                    ),
1629                    Some(arguments) => arguments.is_object(),
1630                    None => input.is_some(),
1631                };
1632            })?;
1633            if !all && !complete {
1634                waiting.push(call);
1635                continue;
1636            }
1637            if let Some(input) = input {
1638                out.announce(call.at, json!({ "input": input }))?;
1639            }
1640            if cut && !complete {
1641                out.close(call.at)?;
1642            } else {
1643                out.finish(call.at)?;
1644            }
1645        }
1646        self.calls = waiting;
1647        Ok(())
1648    }
1649
1650    /// One `chat.completion.chunk`.
1651    fn chunk(&mut self, frame: &Value, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
1652        let choice = self.absorb(frame);
1653        if let Some(usage) = self.usage.as_ref() {
1654            out.usage(
1655                normalized_usage(usage, &self.quirks)
1656                    .cost(reported::cost(self.usage.as_ref(), &self.reply_fields)),
1657            );
1658        }
1659        let Some(choice) = choice else {
1660            return Ok(());
1661        };
1662        if let Some(delta) = choice.obj("delta") {
1663            self.delta(delta, out)?;
1664        }
1665        // Text and reasoning stay open until the stream ends, as pi closes
1666        // its blocks (`openai-completions.ts` around 680): a provider may
1667        // still send either after the finish chunk.
1668        if self.finish == Some(FinishReason::ToolCalls) {
1669            self.close_calls(out, false)?;
1670        }
1671        Ok(())
1672    }
1673
1674    /// The `chat.completion` body: the one chunk whose delta is its whole
1675    /// message, each call at its position in the list, then the end.
1676    fn whole(
1677        &mut self,
1678        frame: &Value,
1679        mut out: Out<'_, Completion>,
1680    ) -> Result<Flow, ProviderError> {
1681        let Some(choice) = self.absorb(frame) else {
1682            return Err(ProviderError::Response(
1683                "Response contained no choices".to_owned(),
1684            ));
1685        };
1686        let Some(mut message) = choice.obj("message").cloned() else {
1687            return Err(ProviderError::Response(
1688                "Response did not contain a valid message or tool call".to_owned(),
1689            ));
1690        };
1691        self.ended = true;
1692        if let Some(Value::Array(calls)) = message.get_mut("tool_calls") {
1693            for (index, call) in calls.iter_mut().enumerate() {
1694                if let Some(call) = call.as_object_mut() {
1695                    call.insert("index".to_owned(), index.into());
1696                }
1697            }
1698        }
1699        self.delta(&message, &mut out)?;
1700        self.close_calls(&mut out, true)?;
1701        self.end(out)
1702    }
1703
1704    /// Write the provider's end of the reply. Its `raw` is the wire's
1705    /// reassembler's.
1706    fn end(&mut self, mut out: Out<'_, Completion>) -> Result<Flow, ProviderError> {
1707        self.close_writing(&mut out)?;
1708        self.close_reasoning(&mut out)?;
1709        self.cite_turn(&mut out);
1710        if let Some(text) = self.first_text {
1711            for citation in reported::listed(&self.reply_fields) {
1712                out.cite(text, citation);
1713            }
1714        }
1715        let cost = reported::cost(self.usage.as_ref(), &self.reply_fields);
1716        let usage = self
1717            .usage
1718            .as_ref()
1719            .map(|usage| normalized_usage(usage, &self.quirks))
1720            .unwrap_or_default()
1721            .cost(cost);
1722        Ok(out.end(Finish {
1723            usage,
1724            reason: self.finish.take(),
1725            response_id: self.response_id.take(),
1726            model: self.response_model.take(),
1727            ..Finish::default()
1728        }))
1729    }
1730
1731    /// The stream ended: flush the calls the provider delivered, then end
1732    /// the reply. A stream no finish reason ended was cut short.
1733    fn finish(&mut self, mut out: Out<'_, Completion>) -> Result<Flow, ProviderError> {
1734        if !self.ended {
1735            return Err(ProviderError::Truncated);
1736        }
1737        self.close_calls(&mut out, true)?;
1738        self.end(out)
1739    }
1740
1741    /// The `[DONE]` sentinel. A dialect whose streams omit the finish reason
1742    /// ends a turn that streamed a chunk as a tool call when it holds one,
1743    /// else a stop.
1744    fn done(&mut self, out: Out<'_, Completion>) -> Result<Flow, ProviderError> {
1745        if !self.ended && self.chunked && self.quirks.done_without_finish_reason {
1746            self.finish = Some(if self.calls.is_empty() {
1747                FinishReason::Stop
1748            } else {
1749                FinishReason::ToolCalls
1750            });
1751            self.ended = true;
1752        }
1753        self.finish(out)
1754    }
1755}
1756
1757/// `slot` holding `text` when it is given, allocating only when it changed.
1758fn keep_text(slot: &mut Option<String>, text: Option<&str>) {
1759    if let Some(text) = text
1760        && slot.as_deref() != Some(text)
1761    {
1762        *slot = Some(text.to_owned());
1763    }
1764}
1765
1766/// Append streamed structured reasoning under `key` to the block's. A text
1767/// or summary fragment continues the last entry of its type and index, and
1768/// a `thinking` fragment the last `thinking` entry not yet signed, so a
1769/// signature closes its block; either appends its text and fills the
1770/// fields that entry lacks. Any other entry, encrypted or redacted, stays
1771/// whole.
1772fn merge_details(block: &mut Map<String, Value>, key: &str, details: Vec<Value>) {
1773    let Value::Array(merged) = block.entry(key).or_insert_with(|| Value::Array(Vec::new())) else {
1774        return;
1775    };
1776    for detail in details {
1777        let kind = detail.str("type");
1778        let continues = merged.last().is_some_and(|last| {
1779            last.str("type") == kind
1780                && match kind {
1781                    Some("reasoning.text" | "reasoning.summary") => {
1782                        last.get("index") == detail.get("index")
1783                    }
1784                    Some("thinking") => last.str("signature").is_none_or(str::is_empty),
1785                    _ => false,
1786                }
1787        });
1788        match (continues, merged.last_mut(), detail) {
1789            (true, Some(Value::Object(last)), Value::Object(fields)) => {
1790                for (field, value) in fields {
1791                    let missing = last
1792                        .get(&field)
1793                        .is_none_or(|existing| existing.is_null() || existing.as_str() == Some(""));
1794                    match (last.get_mut(&field), value) {
1795                        (Some(Value::String(text)), Value::String(more))
1796                            if matches!(field.as_str(), "text" | "summary" | "thinking") =>
1797                        {
1798                            text.push_str(&more);
1799                        }
1800                        (_, value) if missing => {
1801                            last.insert(field, value);
1802                        }
1803                        _ => {}
1804                    }
1805                }
1806            }
1807            (_, _, detail) => merged.push(detail),
1808        }
1809    }
1810}
1811
1812#[deny(clippy::wildcard_enum_match_arm)]
1813impl<'id> Decoder<'id, Completion> for ChatDecoder {
1814    type Event = ChatEvent;
1815
1816    fn classify(&self, frame: WireFrame) -> WireEvent<ChatEvent> {
1817        let data = frame.as_str();
1818        // `[DONE]` is the wire's terminal sentinel, not JSON.
1819        if data == "[DONE]" {
1820            return WireEvent::Known(ChatEvent::Done);
1821        }
1822        // The in-band error envelope arrives with a 200 status and is this
1823        // wire's own terminal failure, whatever else the frame is.
1824        let envelope = |value: &Value| provider_error_envelope(value, &data);
1825        match classify_chat_completions_frame::<Value>(&data) {
1826            WireEvent::Known(frame) => WireEvent::Known(match envelope(&frame) {
1827                Some(error) => ChatEvent::Failure(error),
1828                None => Self::chunk_or_whole(frame),
1829            }),
1830            WireEvent::Unknown { event_type, value } => {
1831                if let Some(error) = envelope(value.value()) {
1832                    WireEvent::Known(ChatEvent::Failure(error))
1833                } else if let (true, Some(text)) = (
1834                    self.quirks.accepts_bare_string_reply,
1835                    value.value().as_str(),
1836                ) {
1837                    WireEvent::Known(ChatEvent::BareText(text.to_owned()))
1838                } else {
1839                    WireEvent::Unknown { event_type, value }
1840                }
1841            }
1842            // A frame with a duplicate `object` or `choices` is still JSON.
1843            WireEvent::Corrupt(error) => match serde_json::from_str::<Value>(&data)
1844                .ok()
1845                .and_then(|value| envelope(&value))
1846            {
1847                Some(error) => WireEvent::Known(ChatEvent::Failure(error)),
1848                None => WireEvent::Corrupt(error),
1849            },
1850        }
1851    }
1852
1853    fn decode(
1854        &mut self,
1855        event: ChatEvent,
1856        mut out: Out<'id, Completion>,
1857    ) -> Result<Flow, ProviderError> {
1858        match event {
1859            ChatEvent::Chunk(frame) => {
1860                self.chunked = true;
1861                self.chunk(&frame, &mut out)?;
1862                Ok(Flow::More)
1863            }
1864            ChatEvent::Whole(frame) => self.whole(&frame, out),
1865            ChatEvent::Done => self.done(out),
1866            // A bare string is the whole answer, ended: pi's stop for a
1867            // reply that names no reason.
1868            ChatEvent::BareText(text) => {
1869                self.ended = true;
1870                self.finish = Some(FinishReason::Stop);
1871                self.write(Writing::Text, &text, &mut out)?;
1872                self.end(out)
1873            }
1874            ChatEvent::Failure(error) => Err(error),
1875        }
1876    }
1877
1878    /// A stream that stops after a finish reason without `[DONE]` still
1879    /// ended: some dialects (Perplexity) never send the sentinel.
1880    fn eof(&mut self, out: Out<'id, Completion>) -> Result<Flow, ProviderError> {
1881        self.finish(out)
1882    }
1883}
1884
1885/// A Chat usage object, normalized for a dialect with `quirks` and read
1886/// leniently, so no usage shape fails a reply: a counter that is absent,
1887/// `null` or not a non-negative integer is unreported, and one inside a
1888/// details object the usage has is zero. Cached input falls back to
1889/// Mistral's `num_cached_tokens` and then DeepSeek's
1890/// `prompt_cache_hit_tokens`; audio input counts as input when the total
1891/// says it sits beside the prompt; output is the remainder of the total when
1892/// unreported; and the reasoning count is left out where the dialect's
1893/// cannot be trusted ([`Quirks::reliable_reasoning_count`]).
1894fn normalized_usage(usage: &Value, quirks: &Quirks) -> crate::completion::Usage {
1895    let count = |pointer: &str| usage.at(pointer).and_then(Value::as_u64);
1896    let detail = |object: &str, key: &str| {
1897        count(&format!("/{object}/{key}")).or(usage.obj(object).map(|_| 0))
1898    };
1899    let (prompt, completion, total) = (
1900        count("/prompt_tokens"),
1901        count("/completion_tokens"),
1902        count("/total_tokens"),
1903    );
1904    let audio = count("/prompt_tokens_details/audio_tokens").unwrap_or(0);
1905    let input = prompt.map(|prompt| {
1906        let beside = prompt.saturating_add(audio);
1907        let accounted = beside.saturating_add(completion.unwrap_or(0));
1908        if audio != 0 && Some(accounted) == total {
1909            beside
1910        } else {
1911            prompt
1912        }
1913    });
1914    crate::completion::Usage {
1915        input_tokens: input,
1916        output_tokens: completion
1917            .or_else(|| total.map(|total| total.saturating_sub(input.unwrap_or(0)))),
1918        total_tokens: total,
1919        cached_input_tokens: detail("prompt_tokens_details", "cached_tokens")
1920            .or(count("/num_cached_tokens"))
1921            .or(count("/prompt_cache_hit_tokens")),
1922        cache_creation_input_tokens: count("/prompt_tokens_details/cache_write_tokens"),
1923        reasoning_tokens: detail("completion_tokens_details", "reasoning_tokens")
1924            .filter(|_| quirks.reliable_reasoning_count),
1925        ..Default::default()
1926    }
1927}
1928
1929impl ChatDecoder {
1930    /// A classified frame as the chunk or whole reply it is. The `object`
1931    /// tag decides when the dialect sends one: stream chunks may carry whole
1932    /// messages. Several gateways omit it.
1933    fn chunk_or_whole(frame: Value) -> ChatEvent {
1934        let whole = match frame.str("object") {
1935            Some(object) => object == "chat.completion",
1936            None => frame
1937                .arr("choices")
1938                .iter()
1939                .any(|choice| choice.obj("message").is_some()),
1940        };
1941        if whole {
1942            ChatEvent::Whole(frame)
1943        } else {
1944            ChatEvent::Chunk(frame)
1945        }
1946    }
1947}
1948
1949mod document;
1950pub(crate) mod finish;
1951pub(in crate::providers::openai) mod reported;
1952
1953#[cfg(test)]
1954mod tests;
1955
1956#[cfg(test)]
1957mod hard_case_tests;
1958
1959#[cfg(test)]
1960mod history_tests;
1961
1962#[cfg(test)]
1963mod request_tests;