1use 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
41pub struct Chat {
42 pub provider: OpenAIConfig,
44 pub model: String,
46 pub strict_tools: bool,
50 pub tool_result_array_content: bool,
52 #[serde(skip)]
54 pub facts: ModelFacts,
55}
56
57fn unsendable(what: &str) -> EncodeError {
61 EncodeError::request(format!("Chat Completions cannot carry {what} in this form"))
62}
63
64fn 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
74fn 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
90fn 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 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
128fn 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
154fn 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 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 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 pub fn with_facts(mut self, facts: ModelFacts) -> Self {
215 self.facts = facts;
216 self
217 }
218
219 pub fn with_strict_tools(mut self) -> Self {
225 self.strict_tools = true;
226 self
227 }
228
229 pub fn with_tool_result_array_content(mut self) -> Self {
231 self.tool_result_array_content = true;
232 self
233 }
234
235 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 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 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 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 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 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 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 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 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
490pub(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 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
558pub(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
580fn 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
630fn 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
648fn 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
663fn 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
672fn 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
694fn finalize_mistral(map: &mut Map<String, Value>) {
697 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
724fn 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 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 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 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 fn catalog_priced(&self) -> bool {
844 self.provider.dialect.quirks.catalog_priced
845 }
846
847 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 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 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 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 && !(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 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 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 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 fn result_parts(&self, _model: &str) -> bool {
1010 self.tool_result_array_content
1011 }
1012
1013 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
1038fn 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
1067fn 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
1082pub enum ChatEvent {
1084 Chunk(Value),
1086 Whole(Value),
1088 Done,
1090 Failure(ProviderError),
1092 BareText(String),
1095}
1096
1097const REASONING_TEXT_KEYS: [&str; 3] = ["reasoning_content", "reasoning", "reasoning_text"];
1101
1102const REASONING_DETAIL_KEYS: [&str; 2] = ["reasoning_details", "thinking_blocks"];
1106
1107#[derive(Debug, PartialEq)]
1109pub(crate) enum Part {
1110 Text(String),
1112 Thinking(String),
1114 Image,
1116 Unknown,
1118}
1119
1120impl Part {
1121 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#[derive(Debug, PartialEq)]
1144pub(crate) enum CallKind {
1145 Function,
1147 Custom,
1149 Unknown,
1151}
1152
1153impl CallKind {
1154 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#[derive(Clone, Copy, PartialEq)]
1168enum Writing {
1169 Text,
1170 Thinking,
1171}
1172
1173struct OpenCall {
1177 at: usize,
1178 id: Option<String>,
1179 opaque: bool,
1180 arguments: String,
1181}
1182
1183#[derive(Default)]
1194pub struct ChatDecoder {
1195 quirks: Quirks,
1196 writing: Option<(Writing, usize)>,
1198 thinking_text: String,
1199 reasoning: Option<usize>,
1203 reasoning_field: Option<&'static str>,
1204 reasoning_text: String,
1205 reasoning_details: Map<String, Value>,
1206 audio_id: Option<Value>,
1208 calls: Vec<OpenCall>,
1210 usage: Option<Value>,
1211 reply_fields: Map<String, Value>,
1213 first_text: Option<usize>,
1216 last_text: Option<usize>,
1219 turn_citations: Vec<crate::wire::WireCitation>,
1222 finish: Option<FinishReason>,
1223 response_id: Option<String>,
1224 response_model: Option<String>,
1225 ended: bool,
1227 chunked: bool,
1229}
1230
1231impl ChatDecoder {
1232 fn new(quirks: Quirks) -> Self {
1233 Self {
1234 quirks,
1235 ..Self::default()
1236 }
1237 }
1238
1239 fn absorb<'f>(&mut self, frame: &'f Value) -> Option<&'f Value> {
1242 keep_text(&mut self.response_id, frame.str("id"));
1244 keep_text(&mut self.response_model, frame.str("model"));
1245 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 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 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 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 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 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 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 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 #[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 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 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 remove_preserving_order(item, "index");
1593 }
1594 })
1595 }
1596
1597 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 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 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 if self.finish == Some(FinishReason::ToolCalls) {
1669 self.close_calls(out, false)?;
1670 }
1671 Ok(())
1672 }
1673
1674 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 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 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 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
1757fn 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
1766fn 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 if data == "[DONE]" {
1820 return WireEvent::Known(ChatEvent::Done);
1821 }
1822 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 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 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 fn eof(&mut self, out: Out<'id, Completion>) -> Result<Flow, ProviderError> {
1881 self.finish(out)
1882 }
1883}
1884
1885fn 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 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;