Skip to main content

dynamo_protocols/types/
chat.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Re-exports upstream async-openai chat types and defines inference-serving
5// extensions on top. Types prefixed with `Dynamo` or entirely absent from the
6// upstream spec are documented with the rationale for the extension.
7
8use std::pin::Pin;
9
10use derive_builder::Builder;
11use futures::Stream;
12use serde::{Deserialize, Serialize};
13use url::Url;
14use uuid::Uuid;
15
16use crate::error::OpenAIError;
17
18mod custom_tools;
19pub use custom_tools::*;
20
21// ---------------------------------------------------------------------------
22// Re-exports from upstream async-openai (unchanged types)
23// ---------------------------------------------------------------------------
24// These types are structurally identical to the upstream definitions.
25// Consumers should use them via `dynamo_protocols::types::*` as before.
26
27pub use async_openai::types::chat::{
28    ChatCompletionAudio, ChatCompletionAudioFormat, ChatCompletionAudioVoice,
29    ChatCompletionFunctionCall, ChatCompletionFunctions, ChatCompletionFunctionsArgs,
30    ChatCompletionRequestAssistantMessageAudio, ChatCompletionRequestAssistantMessageContent,
31    ChatCompletionRequestAssistantMessageContentPart, ChatCompletionRequestDeveloperMessage,
32    ChatCompletionRequestDeveloperMessageArgs, ChatCompletionRequestDeveloperMessageContent,
33    ChatCompletionRequestFunctionMessage, ChatCompletionRequestFunctionMessageArgs,
34    ChatCompletionRequestMessageContentPartAudio, ChatCompletionRequestMessageContentPartRefusal,
35    ChatCompletionRequestMessageContentPartText, ChatCompletionRequestSystemMessageContent,
36    ChatCompletionRequestSystemMessageContentPart, ChatCompletionResponseMessageAudio, Choice,
37    CompletionFinishReason, CompletionTokensDetails, CompletionUsage, ImageDetail, InputAudio,
38    InputAudioFormat, Logprobs, PredictionContent, PredictionContentContent, Prompt,
39    PromptTokensDetails, ResponseFormat, ResponseFormatJsonSchema, Role, ServiceTier,
40    WebSearchContextSize, WebSearchLocation, WebSearchOptions, WebSearchUserLocation,
41    WebSearchUserLocationType,
42};
43
44/// OpenAI stop configuration, with Dynamo's token-id stop extension.
45///
46/// The standard OpenAI shape accepts a string or string array. Dynamo also
47/// accepts an integer array, e.g. `"stop": [576]`, to express token-id stop
48/// conditions for tokenized in/out workflows. Strings like `"token_id:576"`
49/// remain ordinary string stops; the `token_id:<id>` format is only an output
50/// display format for logprobs.
51#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
52#[serde(untagged)]
53pub enum Stop {
54    String(String),
55    StringArray(Vec<String>),
56    TokenIdArray(Vec<u32>),
57}
58
59// Use anyOf because an empty array matches both array variants.
60#[cfg(feature = "protocol-schema")]
61impl utoipa::PartialSchema for Stop {
62    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::Schema> {
63        utoipa::openapi::schema::AnyOfBuilder::new()
64            .description(Some(
65                "OpenAI stop configuration, with Dynamo's token-id stop extension.",
66            ))
67            .item(String::schema())
68            .item(Vec::<String>::schema())
69            .item(Vec::<u32>::schema())
70            .into()
71    }
72}
73
74#[cfg(feature = "protocol-schema")]
75impl utoipa::ToSchema for Stop {
76    fn name() -> std::borrow::Cow<'static, str> {
77        "dynamo_protocols.chat.Stop".into()
78    }
79}
80
81impl Stop {
82    pub fn strings(&self) -> Option<Vec<String>> {
83        match self {
84            Stop::String(s) => Some(vec![s.clone()]),
85            Stop::StringArray(arr) => Some(arr.clone()),
86            Stop::TokenIdArray(_) => None,
87        }
88    }
89
90    pub fn token_ids(&self) -> Option<Vec<u32>> {
91        match self {
92            Stop::TokenIdArray(arr) => Some(arr.clone()),
93            Stop::String(_) | Stop::StringArray(_) => None,
94        }
95    }
96}
97
98impl From<String> for Stop {
99    fn from(value: String) -> Self {
100        Stop::String(value)
101    }
102}
103
104impl From<&str> for Stop {
105    fn from(value: &str) -> Self {
106        Stop::String(value.to_string())
107    }
108}
109
110impl From<Vec<String>> for Stop {
111    fn from(value: Vec<String>) -> Self {
112        Stop::StringArray(value)
113    }
114}
115
116impl From<Vec<u32>> for Stop {
117    fn from(value: Vec<u32>) -> Self {
118        Stop::TokenIdArray(value)
119    }
120}
121
122impl From<async_openai::types::chat::StopConfiguration> for Stop {
123    fn from(value: async_openai::types::chat::StopConfiguration) -> Self {
124        match value {
125            async_openai::types::chat::StopConfiguration::String(value) => Stop::String(value),
126            async_openai::types::chat::StopConfiguration::StringArray(value) => {
127                Stop::StringArray(value)
128            }
129        }
130    }
131}
132
133// Upstream renamed FinishReason (streaming) -- re-export
134pub use async_openai::types::chat::FinishReason;
135
136// Keep the historical alias while accepting both OpenAI tool-call kinds.
137pub type FunctionType = ChatCompletionToolType;
138
139/// Reasoning effort values accepted by OpenAI-compatible clients.
140///
141/// async-openai versions used by some Dynamo builds do not include `max`, but
142/// DeepSeek-V4 compatible clients may send it by default. Keep this local enum
143/// wire-compatible with upstream values and include `max`.
144#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
145#[serde(rename_all = "lowercase")]
146#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
147#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ReasoningEffort))]
148pub enum ReasoningEffort {
149    None,
150    Minimal,
151    Low,
152    Medium,
153    High,
154    Xhigh,
155    Max,
156}
157
158impl From<async_openai::types::chat::ReasoningEffort> for ReasoningEffort {
159    fn from(value: async_openai::types::chat::ReasoningEffort) -> Self {
160        match value {
161            async_openai::types::chat::ReasoningEffort::None => ReasoningEffort::None,
162            async_openai::types::chat::ReasoningEffort::Minimal => ReasoningEffort::Minimal,
163            async_openai::types::chat::ReasoningEffort::Low => ReasoningEffort::Low,
164            async_openai::types::chat::ReasoningEffort::Medium => ReasoningEffort::Medium,
165            async_openai::types::chat::ReasoningEffort::High => ReasoningEffort::High,
166            async_openai::types::chat::ReasoningEffort::Xhigh => ReasoningEffort::Xhigh,
167            async_openai::types::chat::ReasoningEffort::Max => ReasoningEffort::Max,
168        }
169    }
170}
171
172// ---------------------------------------------------------------------------
173// Flexible `arguments` deserialisation helpers
174// ---------------------------------------------------------------------------
175// Some agent frameworks (e.g. LangChain, custom harnesses) send tool-call
176// arguments as a pre-parsed JSON object instead of the canonical JSON
177// string.  The helpers below normalise both representations to a `String` so
178// downstream code never needs to branch on the wire format.
179
180fn deserialize_arguments<'de, D>(deserializer: D) -> Result<String, D::Error>
181where
182    D: serde::Deserializer<'de>,
183{
184    use serde::de::Error;
185    let value = serde_json::Value::deserialize(deserializer)?;
186    match value {
187        serde_json::Value::String(s) => Ok(s),
188        v @ serde_json::Value::Object(_) => {
189            // serde_json::to_string on a Value is infallible
190            Ok(serde_json::to_string(&v).unwrap())
191        }
192        other => Err(D::Error::custom(format!(
193            "expected string or object for `arguments`, got {other}"
194        ))),
195    }
196}
197
198fn deserialize_arguments_opt<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
199where
200    D: serde::Deserializer<'de>,
201{
202    use serde::de::Error;
203    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
204    match value {
205        None => Ok(None),
206        Some(serde_json::Value::String(s)) => Ok(Some(s)),
207        Some(v @ serde_json::Value::Object(_)) => serde_json::to_string(&v)
208            .map(Some)
209            .map_err(|e| D::Error::custom(e.to_string())),
210        Some(other) => Err(D::Error::custom(format!(
211            "expected string or object for `arguments`, got {other}"
212        ))),
213    }
214}
215
216/// Deserializes an optional media object, treating `{"url": ""}` as absent.
217///
218/// vLLM's OpenAI-compatible schema requires the media object to be present, so
219/// UUID-cache clients emit an empty URL where Dynamo's canonical form is `null`.
220/// Normalizing at the type boundary leaves `(url, uuid)` validation to consumers.
221fn deserialize_optional_media<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
222where
223    D: serde::Deserializer<'de>,
224    T: serde::de::DeserializeOwned,
225{
226    use serde::de::Error;
227    match Option::<serde_json::Value>::deserialize(deserializer)? {
228        None => Ok(None),
229        Some(value) if value.get("url").and_then(serde_json::Value::as_str) == Some("") => Ok(None),
230        Some(value) => serde_json::from_value(value)
231            .map(Some)
232            .map_err(D::Error::custom),
233    }
234}
235
236// ---------------------------------------------------------------------------
237// FunctionCall / FunctionCallStream — local definitions with flexible deser
238// ---------------------------------------------------------------------------
239// Upstream `async-openai` only accepts a JSON string for `arguments`.
240// We define these locally so we can attach `#[serde(deserialize_with)]` and
241// accept both string and object representations on the wire.
242
243/// The name and arguments of a function that should be called.
244///
245/// Accepts `arguments` as either a JSON string (`"{\"key\":\"value\"}"`) or a
246/// JSON object (`{"key": "value"}`); both are normalised to a JSON string
247/// on deserialisation so callers always see the canonical form.
248#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
249#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
250#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::FunctionCall))]
251pub struct FunctionCall {
252    pub name: String,
253    #[serde(deserialize_with = "deserialize_arguments")]
254    pub arguments: String,
255}
256
257/// Streaming variant of [`FunctionCall`] where both fields are optional.
258/// Continuation chunks carry only `arguments`; `name` is omitted rather
259/// than serialized as `null`, matching OpenAI output.
260#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
261#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
262#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::FunctionCallStream))]
263pub struct FunctionCallStream {
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub name: Option<String>,
266    #[serde(
267        default,
268        skip_serializing_if = "Option::is_none",
269        deserialize_with = "deserialize_arguments_opt"
270    )]
271    pub arguments: Option<String>,
272}
273
274/// Streaming tool-call chunk.
275///
276/// Defined locally (instead of re-exporting from upstream) because its
277/// `function` field references our local [`FunctionCallStream`] with the
278/// flexible `arguments` deserialiser.
279#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
280#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
281#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionMessageToolCallChunk))]
282pub struct ChatCompletionMessageToolCallChunk {
283    pub index: u32,
284    /// Only `index` is required by the spec; `id`, `type`, and `function`
285    /// are omitted on continuation chunks, matching OpenAI output.
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub id: Option<String>,
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub r#type: Option<FunctionType>,
290    #[serde(skip_serializing_if = "Option::is_none")]
291    pub function: Option<FunctionCallStream>,
292    #[serde(skip_serializing_if = "Option::is_none")]
293    pub custom: Option<CustomToolCallStream>,
294}
295
296// ---------------------------------------------------------------------------
297// Types with structural differences from upstream (kept locally)
298// ---------------------------------------------------------------------------
299
300/// Image content part.
301///
302/// vLLM's OpenAI-compatible server accepts an optional top-level `uuid` on the
303/// media content part. For cache-hit-only requests, `uuid` carries the cache
304/// key and the canonical `image_url` is null. Clients constrained by vLLM's
305/// request schema may instead send `{"url": ""}`, which deserializes to the
306/// same representation. This is a vLLM extension, not part of the OpenAI Chat
307/// Completions API.
308#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
309#[builder(name = "ChatCompletionRequestMessageContentPartImageArgs")]
310#[builder(pattern = "mutable")]
311#[builder(setter(into, strip_option))]
312#[builder(derive(Debug))]
313#[builder(build_fn(error = "OpenAIError"))]
314#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
315#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestMessageContentPartImage))]
316pub struct ChatCompletionRequestMessageContentPartImage {
317    #[builder(default)]
318    #[serde(default, deserialize_with = "deserialize_optional_media")]
319    pub image_url: Option<ImageUrl>,
320    #[builder(default)]
321    #[serde(skip_serializing_if = "Option::is_none")]
322    /// vLLM-only multimodal processor-cache identity.
323    pub uuid: Option<String>,
324}
325
326/// Image URL with `url::Url` type and a legacy optional UUID.
327///
328/// New callers should put vLLM processor-cache identities on
329/// [`ChatCompletionRequestMessageContentPartImage::uuid`].
330#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
331#[builder(name = "ImageUrlArgs")]
332#[builder(pattern = "mutable")]
333#[builder(setter(into, strip_option))]
334#[builder(derive(Debug))]
335#[builder(build_fn(error = "OpenAIError"))]
336#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
337#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ImageUrl))]
338pub struct ImageUrl {
339    pub url: Url,
340    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ImageDetail>))]
341    pub detail: Option<ImageDetail>,
342    #[deprecated(note = "use the content-part `uuid` field for vLLM cache identities")]
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub uuid: Option<Uuid>,
345}
346
347/// Experimental modality envelope. The fields object is plugin-owned JSON;
348/// consumers must explicitly document whether they pass the whole map or a payload.
349#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
350#[serde(deny_unknown_fields)]
351#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
352#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::CustomModalityPart))]
353pub struct CustomModalityPart {
354    #[serde(deserialize_with = "deserialize_custom_kind")]
355    pub kind: String,
356    pub fields: serde_json::Map<String, serde_json::Value>,
357}
358
359fn deserialize_custom_kind<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
360    let kind = String::deserialize(d)?;
361    if kind.trim().is_empty() {
362        return Err(serde::de::Error::custom("custom kind must be non-empty"));
363    }
364    Ok(kind)
365}
366
367/// Tool message content part with media observation support.
368///
369/// OpenAI's schema currently limits tool content parts to text, but
370/// OpenAI-compatible multimodal backends also accept image, video, and audio
371/// observations returned by tools.
372#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
373#[serde(tag = "type")]
374#[serde(rename_all = "snake_case")]
375#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
376#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestToolMessageContentPart))]
377pub enum ChatCompletionRequestToolMessageContentPart {
378    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::ChatCompletionRequestMessageContentPartText))]
379    Text(ChatCompletionRequestMessageContentPartText),
380    ImageUrl(ChatCompletionRequestMessageContentPartImage),
381    VideoUrl(ChatCompletionRequestMessageContentPartVideo),
382    AudioUrl(ChatCompletionRequestMessageContentPartAudioUrl),
383    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::CustomContentPart))]
384    Custom(CustomModalityPart),
385}
386
387/// Tool message content, extended to preserve media observations.
388#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
389#[serde(untagged)]
390#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
391#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestToolMessageContent))]
392pub enum ChatCompletionRequestToolMessageContent {
393    Text(String),
394    Array(Vec<ChatCompletionRequestToolMessageContentPart>),
395}
396
397impl Default for ChatCompletionRequestToolMessageContent {
398    fn default() -> Self {
399        Self::Text(String::new())
400    }
401}
402
403impl From<&str> for ChatCompletionRequestToolMessageContent {
404    fn from(value: &str) -> Self {
405        Self::Text(value.into())
406    }
407}
408
409impl From<String> for ChatCompletionRequestToolMessageContent {
410    fn from(value: String) -> Self {
411        Self::Text(value)
412    }
413}
414
415/// Tool message using Dynamo's media-capable content type.
416#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
417#[builder(name = "ChatCompletionRequestToolMessageArgs")]
418#[builder(pattern = "mutable")]
419#[builder(setter(into, strip_option), default)]
420#[builder(derive(Debug))]
421#[builder(build_fn(error = "OpenAIError"))]
422#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
423#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestToolMessage))]
424pub struct ChatCompletionRequestToolMessage {
425    pub content: ChatCompletionRequestToolMessageContent,
426    pub tool_call_id: String,
427}
428
429#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
430#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
431#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatChoiceLogprobs))]
432pub struct ChatChoiceLogprobs {
433    #[cfg_attr(feature = "protocol-schema", schema(required))]
434    pub content: Option<Vec<ChatCompletionTokenLogprob>>,
435    #[cfg_attr(feature = "protocol-schema", schema(required))]
436    pub refusal: Option<Vec<ChatCompletionTokenLogprob>>,
437}
438
439/// Top logprob candidate with an optional backend vocabulary ID.
440///
441/// Different vocabulary IDs may render to the same token string. Retain IDs
442/// supplied by the backend without adding them to ordinary OpenAI responses.
443#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
444#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
445#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::TopLogprobs))]
446pub struct TopLogprobs {
447    pub token: String,
448    pub logprob: f32,
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub token_id: Option<u32>,
451    #[cfg_attr(feature = "protocol-schema", schema(required))]
452    pub bytes: Option<Vec<u8>>,
453}
454
455/// Token logprob entry with optional backend token ID.
456///
457/// Some inference backends can report both the rendered token string and its
458/// vocabulary ID. Keeping this optional preserves the upstream OpenAI shape
459/// when token IDs are unavailable.
460#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
461#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
462#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionTokenLogprob))]
463pub struct ChatCompletionTokenLogprob {
464    pub token: String,
465    pub logprob: f32,
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub token_id: Option<u32>,
468    #[cfg_attr(feature = "protocol-schema", schema(required))]
469    pub bytes: Option<Vec<u8>>,
470    pub top_logprobs: Vec<TopLogprobs>,
471}
472
473#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
474#[serde(rename_all = "lowercase")]
475#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
476#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionToolType))]
477pub enum ChatCompletionToolType {
478    #[default]
479    Function,
480    Custom,
481}
482
483#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
484#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
485#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::FunctionName))]
486pub struct FunctionName {
487    pub name: String,
488}
489
490#[derive(Clone, Default, Debug, PartialEq)]
491pub struct ChatCompletionNamedToolChoice {
492    pub r#type: ChatCompletionToolType,
493    /// Common selected name; serialization chooses `function` or `custom`.
494    pub function: FunctionName,
495}
496
497/// Tool call kept locally for function and custom unary request/response payloads.
498///
499/// Differs from upstream: `type` is serialized by default and also defaults to
500/// `function` when omitted during deserialization, preserving compatibility with
501/// both Dynamo's historical wire format and upstream spec-compliant inputs.
502#[derive(Clone, Debug, PartialEq)]
503pub struct ChatCompletionMessageToolCall {
504    pub id: String,
505    pub r#type: FunctionType,
506    /// Function-oriented internal view; custom calls wrap their text in `input`.
507    pub function: FunctionCall,
508    pub custom: Option<CustomToolCall>,
509}
510
511/// Tool choice enum kept locally because upstream changed variant names.
512#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
513#[serde(rename_all = "lowercase")]
514pub enum ChatCompletionToolChoiceOption {
515    #[default]
516    None,
517    Auto,
518    Required,
519    #[serde(untagged)]
520    Named(ChatCompletionNamedToolChoice),
521}
522
523// utoipa's derive does not honor per-variant serde(untagged). The named
524// choice is an object directly, not {"Named": {...}}.
525#[cfg(feature = "protocol-schema")]
526impl utoipa::PartialSchema for ChatCompletionToolChoiceOption {
527    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::Schema> {
528        use utoipa::openapi::schema::{AnyOfBuilder, ObjectBuilder, Type};
529        AnyOfBuilder::new()
530            .item(
531                ObjectBuilder::new()
532                    .schema_type(Type::String)
533                    .enum_values(Some(["none", "auto", "required"])),
534            )
535            .item(ChatCompletionNamedToolChoice::schema())
536            .into()
537    }
538}
539
540#[cfg(feature = "protocol-schema")]
541impl utoipa::ToSchema for ChatCompletionToolChoiceOption {
542    fn name() -> std::borrow::Cow<'static, str> {
543        "dynamo_protocols.chat.ChatCompletionToolChoiceOption".into()
544    }
545
546    fn schemas(schemas: &mut Vec<(String, utoipa::openapi::RefOr<utoipa::openapi::Schema>)>) {
547        ChatCompletionNamedToolChoice::schemas(schemas);
548    }
549}
550
551/// Chat function definition with the vLLM/SGLang deferred-rendering extension.
552/// Keep this local because the SDK type drops `defer_loading` before rendering.
553#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
554#[builder(name = "FunctionObjectArgs")]
555#[builder(pattern = "mutable")]
556#[builder(setter(into, strip_option), default)]
557#[builder(derive(Debug))]
558#[builder(build_fn(error = "OpenAIError"))]
559#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
560#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::FunctionObject))]
561pub struct FunctionObject {
562    pub name: String,
563    #[serde(skip_serializing_if = "Option::is_none")]
564    pub description: Option<String>,
565    #[serde(skip_serializing_if = "Option::is_none")]
566    pub parameters: Option<serde_json::Value>,
567    #[serde(skip_serializing_if = "Option::is_none")]
568    pub strict: Option<bool>,
569    /// Passed to the chat template; discovery and tool execution remain external.
570    #[serde(skip_serializing_if = "Option::is_none")]
571    pub defer_loading: Option<bool>,
572}
573
574#[derive(Clone, Default, Debug, Builder, PartialEq)]
575#[builder(name = "ChatCompletionToolArgs")]
576#[builder(pattern = "mutable")]
577#[builder(setter(into, strip_option), default)]
578#[builder(derive(Debug))]
579#[builder(build_fn(name = "build_inner", private, error = "OpenAIError"))]
580pub struct ChatCompletionTool {
581    #[builder(default = "ChatCompletionToolType::Function")]
582    pub r#type: ChatCompletionToolType,
583    pub function: FunctionObject,
584    pub custom: Option<ChatCompletionCustomTool>,
585    /// Wrapper-level alias used when `function.defer_loading` is unset,
586    /// including tools constructed or modified directly in Rust.
587    pub defer_loading: Option<bool>,
588}
589
590impl Serialize for ChatCompletionTool {
591    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
592        if self.r#type == ChatCompletionToolType::Custom {
593            use serde::ser::{Error, SerializeStruct};
594            let custom = self
595                .custom
596                .as_ref()
597                .ok_or_else(|| S::Error::custom("custom tool requires custom definition"))?;
598            let mut value = serializer.serialize_struct("ChatCompletionTool", 2)?;
599            value.serialize_field("type", "custom")?;
600            value.serialize_field("custom", custom)?;
601            return value.end();
602        }
603        #[derive(Serialize)]
604        struct FunctionWithDeferral<'a> {
605            #[serde(flatten)]
606            function: &'a FunctionObject,
607            #[serde(skip_serializing_if = "Option::is_none")]
608            defer_loading: Option<bool>,
609        }
610        #[derive(Serialize)]
611        struct Wire<'a> {
612            r#type: &'a ChatCompletionToolType,
613            function: FunctionWithDeferral<'a>,
614            #[serde(skip_serializing_if = "Option::is_none")]
615            defer_loading: Option<bool>,
616        }
617        // Apply the alias at serialization too, without cloning schemas or
618        // mutating the registry. A present function flag must not be emitted twice.
619        Wire {
620            r#type: &self.r#type,
621            function: FunctionWithDeferral {
622                function: &self.function,
623                defer_loading: self
624                    .defer_loading
625                    .filter(|_| self.function.defer_loading.is_none()),
626            },
627            defer_loading: self.defer_loading,
628        }
629        .serialize(serializer)
630    }
631}
632
633impl ChatCompletionTool {
634    fn normalize_defer_loading(&mut self) {
635        // Match both engines: an explicit function-level false wins over the alias.
636        self.function.defer_loading = self.function.defer_loading.or(self.defer_loading);
637    }
638}
639
640impl ChatCompletionToolArgs {
641    pub fn build(&self) -> Result<ChatCompletionTool, OpenAIError> {
642        let mut tool = self.build_inner()?;
643        tool.normalize_defer_loading();
644        Ok(tool)
645    }
646}
647
648// ---------------------------------------------------------------------------
649// Inference-serving extensions (not in upstream)
650// ---------------------------------------------------------------------------
651
652/// Matched stop condition from the backend.
653///
654/// Inference backends (vLLM, SGLang) report which stop condition triggered:
655/// - `String`: a matched user-provided stop sequence
656/// - `Int`: a matched stop token ID
657/// - `IntArray`: matched stop token IDs reported as a sequence
658#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
659#[serde(untagged)]
660#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
661#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::StopReason))]
662pub enum StopReason {
663    String(String),
664    Int(i64),
665    IntArray(Vec<i64>),
666}
667
668/// Reasoning content from a previous assistant turn.
669///
670/// Deserializes from either:
671/// - A plain string: `"reasoning_content": "thinking..."` -> `Text("thinking...")`
672/// - An array of strings: `"reasoning_content": ["seg1", "seg2"]` -> `Segments(["seg1", "seg2"])`
673///
674/// The `Segments` variant preserves interleaved reasoning order needed for KV cache-correct
675/// context reconstruction. `segments[i]` is the reasoning that preceded `tool_calls[i]`;
676/// `segments[tool_calls.len()]` is any trailing reasoning after the last tool call.
677#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
678#[serde(untagged)]
679#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
680#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ReasoningContent))]
681pub enum ReasoningContent {
682    /// Flat string -- single reasoning block or legacy backward-compat form.
683    Text(String),
684    /// Interleaved segments. segments[i] precedes tool_calls[i];
685    /// segments[N] is trailing reasoning after the last tool call.
686    Segments(Vec<String>),
687}
688
689impl ReasoningContent {
690    /// Join all segments (or return text as-is) into a single flat string.
691    pub fn to_flat_string(&self) -> String {
692        match self {
693            ReasoningContent::Text(s) => s.clone(),
694            ReasoningContent::Segments(segs) => segs
695                .iter()
696                .filter(|s| !s.is_empty())
697                .cloned()
698                .collect::<Vec<_>>()
699                .join("\n"),
700        }
701    }
702
703    /// Returns the segments if this is the `Segments` variant, `None` for `Text`.
704    pub fn segments(&self) -> Option<&[String]> {
705        match self {
706            ReasoningContent::Segments(segs) => Some(segs),
707            ReasoningContent::Text(_) => None,
708        }
709    }
710}
711
712// -- Multimodal content types for responses (not in upstream) --
713
714/// Response content part for text in assistant messages
715#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
716#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
717#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionResponseContentPartText))]
718pub struct ChatCompletionResponseContentPartText {
719    pub text: String,
720}
721
722/// Response content part for image URLs in assistant messages
723#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
724#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
725#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionResponseContentPartImageUrl))]
726pub struct ChatCompletionResponseContentPartImageUrl {
727    pub image_url: ImageUrlResponse,
728}
729
730/// Response content part for video URLs in assistant messages
731#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
732#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
733#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionResponseContentPartVideoUrl))]
734pub struct ChatCompletionResponseContentPartVideoUrl {
735    pub video_url: VideoUrlResponse,
736}
737
738/// Response content part for audio URLs in assistant messages
739#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
740#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
741#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionResponseContentPartAudioUrl))]
742pub struct ChatCompletionResponseContentPartAudioUrl {
743    pub audio_url: AudioUrlResponse,
744}
745
746#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
747#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
748#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ImageUrlResponse))]
749pub struct ImageUrlResponse {
750    pub url: String,
751    #[serde(skip_serializing_if = "Option::is_none")]
752    pub detail: Option<String>,
753}
754
755#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
756#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
757#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::VideoUrlResponse))]
758pub struct VideoUrlResponse {
759    pub url: String,
760}
761
762#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
763#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
764#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::AudioUrlResponse))]
765pub struct AudioUrlResponse {
766    pub url: String,
767}
768
769/// Content parts for assistant responses supporting multiple modalities
770#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
771#[serde(tag = "type", rename_all = "snake_case")]
772#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
773#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionResponseContentPart))]
774pub enum ChatCompletionResponseContentPart {
775    Text(ChatCompletionResponseContentPartText),
776    ImageUrl(ChatCompletionResponseContentPartImageUrl),
777    VideoUrl(ChatCompletionResponseContentPartVideoUrl),
778    AudioUrl(ChatCompletionResponseContentPartAudioUrl),
779}
780
781/// Assistant message content -- can be a simple string or multimodal content parts.
782///
783/// Upstream uses `Option<String>` for the content field. We extend this to
784/// support multimodal responses (text + images + video + audio) from backends
785/// like vLLM that can return non-text content.
786#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
787#[serde(untagged)]
788#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
789#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionMessageContent))]
790pub enum ChatCompletionMessageContent {
791    /// Simple text content (backward compatible)
792    Text(String),
793    /// Array of content parts (for multimodal responses)
794    Parts(Vec<ChatCompletionResponseContentPart>),
795}
796
797// -- Multimodal input types (video/audio URL support, not in upstream) --
798
799#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
800#[builder(name = "VideoUrlArgs")]
801#[builder(pattern = "mutable")]
802#[builder(setter(into, strip_option))]
803#[builder(derive(Debug))]
804#[builder(build_fn(error = "OpenAIError"))]
805#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
806#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::VideoUrl))]
807pub struct VideoUrl {
808    pub url: Url,
809    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ImageDetail>))]
810    pub detail: Option<ImageDetail>,
811    #[deprecated(note = "use the content-part `uuid` field for vLLM cache identities")]
812    #[serde(skip_serializing_if = "Option::is_none")]
813    pub uuid: Option<Uuid>,
814}
815
816#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
817#[builder(name = "ChatCompletionRequestMessageContentPartVideoArgs")]
818#[builder(pattern = "mutable")]
819#[builder(setter(into, strip_option))]
820#[builder(derive(Debug))]
821#[builder(build_fn(error = "OpenAIError"))]
822#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
823#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestMessageContentPartVideo))]
824pub struct ChatCompletionRequestMessageContentPartVideo {
825    #[builder(default)]
826    #[serde(default, deserialize_with = "deserialize_optional_media")]
827    pub video_url: Option<VideoUrl>,
828    #[builder(default)]
829    #[serde(skip_serializing_if = "Option::is_none")]
830    /// vLLM-only multimodal processor-cache identity.
831    pub uuid: Option<String>,
832}
833
834#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
835#[builder(name = "AudioUrlArgs")]
836#[builder(pattern = "mutable")]
837#[builder(setter(into, strip_option))]
838#[builder(derive(Debug))]
839#[builder(build_fn(error = "OpenAIError"))]
840#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
841#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::AudioUrl))]
842pub struct AudioUrl {
843    pub url: Url,
844    #[deprecated(note = "use the content-part `uuid` field for vLLM cache identities")]
845    #[serde(skip_serializing_if = "Option::is_none")]
846    pub uuid: Option<Uuid>,
847}
848
849#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
850#[builder(name = "ChatCompletionRequestMessageContentPartAudioUrlArgs")]
851#[builder(pattern = "mutable")]
852#[builder(setter(into, strip_option))]
853#[builder(derive(Debug))]
854#[builder(build_fn(error = "OpenAIError"))]
855#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
856#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestMessageContentPartAudioUrl))]
857pub struct ChatCompletionRequestMessageContentPartAudioUrl {
858    #[builder(default)]
859    #[serde(default, deserialize_with = "deserialize_optional_media")]
860    pub audio_url: Option<AudioUrl>,
861    #[builder(default)]
862    #[serde(skip_serializing_if = "Option::is_none")]
863    /// vLLM-only multimodal processor-cache identity.
864    pub uuid: Option<String>,
865}
866
867// -- Extended request/response types --
868
869/// User message content -- references our extended content part enum.
870#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
871#[serde(untagged)]
872#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
873#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestUserMessageContent))]
874pub enum ChatCompletionRequestUserMessageContent {
875    Text(String),
876    Array(Vec<ChatCompletionRequestUserMessageContentPart>),
877}
878
879#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
880#[builder(name = "ChatCompletionRequestUserMessageArgs")]
881#[builder(pattern = "mutable")]
882#[builder(setter(into, strip_option), default)]
883#[builder(derive(Debug))]
884#[builder(build_fn(error = "OpenAIError"))]
885#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
886#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestUserMessage))]
887pub struct ChatCompletionRequestUserMessage {
888    pub content: ChatCompletionRequestUserMessageContent,
889    #[serde(skip_serializing_if = "Option::is_none")]
890    pub name: Option<String>,
891}
892
893impl Default for ChatCompletionRequestUserMessageContent {
894    fn default() -> Self {
895        Self::Text(String::new())
896    }
897}
898
899impl From<&str> for ChatCompletionRequestUserMessageContent {
900    fn from(value: &str) -> Self {
901        Self::Text(value.into())
902    }
903}
904
905impl From<String> for ChatCompletionRequestUserMessageContent {
906    fn from(value: String) -> Self {
907        Self::Text(value)
908    }
909}
910
911impl From<Vec<ChatCompletionRequestUserMessageContentPart>>
912    for ChatCompletionRequestUserMessageContent
913{
914    fn from(value: Vec<ChatCompletionRequestUserMessageContentPart>) -> Self {
915        Self::Array(value)
916    }
917}
918
919/// User message content part with video and audio URL support.
920///
921/// Extends upstream `ChatCompletionRequestUserMessageContentPart` with:
922/// - `VideoUrl`: video input for multimodal models
923/// - `AudioUrl`: audio URL input (distinct from base64 InputAudio)
924#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
925#[serde(tag = "type")]
926#[serde(rename_all = "snake_case")]
927#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
928#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestUserMessageContentPart))]
929pub enum ChatCompletionRequestUserMessageContentPart {
930    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::ChatCompletionRequestMessageContentPartText))]
931    Text(ChatCompletionRequestMessageContentPartText),
932    ImageUrl(ChatCompletionRequestMessageContentPartImage),
933    VideoUrl(ChatCompletionRequestMessageContentPartVideo),
934    AudioUrl(ChatCompletionRequestMessageContentPartAudioUrl),
935    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::CustomContentPart))]
936    Custom(CustomModalityPart),
937    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::ChatCompletionRequestMessageContentPartAudio))]
938    InputAudio(ChatCompletionRequestMessageContentPartAudio),
939}
940
941/// System message with dynamic tool metadata support.
942///
943/// Extends upstream `ChatCompletionRequestSystemMessage` with:
944/// - `content`: still required in the public Rust type. On the wire only,
945///   Kimi-style messages may omit it (or send `null`) when they declare
946///   non-empty `tools`; deserialization canonicalizes that shape to empty text.
947///   Every other content-less system message is still rejected with upstream's
948///   `missing field \`content\`` error, so spec-conformant clients and non-Kimi
949///   models see no behavior change. Without this guard a bare
950///   `{"role": "system"}` would reach ordinary HF jinja templates and render
951///   an empty system turn instead of failing the request.
952/// - `tools`: passthrough field for model-specific tool metadata rendered by the
953///   chat template. Dynamo does not interpret this field; it is preserved
954///   verbatim for downstream chat-template rendering.
955///
956/// `Default` (and therefore the builder's unset state) uses empty-string
957/// `content`, matching upstream. Keeping `content` non-optional also prevents
958/// programmatic callers from constructing a content-less, tool-less message.
959#[derive(Debug, Serialize, Clone, Builder, PartialEq, Default)]
960#[builder(name = "ChatCompletionRequestSystemMessageArgs")]
961#[builder(pattern = "mutable")]
962#[builder(setter(into, strip_option), default)]
963#[builder(derive(Debug))]
964#[builder(build_fn(error = "OpenAIError"))]
965#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
966#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestSystemMessage))]
967pub struct ChatCompletionRequestSystemMessage {
968    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::ChatCompletionRequestSystemMessageContent))]
969    pub content: ChatCompletionRequestSystemMessageContent,
970    #[serde(skip_serializing_if = "Option::is_none")]
971    pub name: Option<String>,
972    /// Kimi-style dynamic tool metadata carried on a system message.
973    ///
974    /// Moonshot treats omitted, null, and empty `content` as no system text;
975    /// renderers enforce that non-empty `content` and `tools` are mutually
976    /// exclusive and that `tools` is non-empty. The list shape is typed here
977    /// so non-array values are rejected at deserialization.
978    ///
979    /// Entries stay raw JSON rather than a typed schema on purpose: this crate
980    /// only needs to *preserve* them for downstream chat-template rendering,
981    /// which reads them back as generic JSON by key. A typed entry (e.g.
982    /// `FunctionObject`) would silently drop vendor-specific keys serde doesn't
983    /// know about on round-trip, whereas `serde_json::Value` is structurally
984    /// lossless (JSON structure and unknown keys survive; whitespace, number
985    /// spelling, and duplicate keys do not).
986    ///
987    /// Kimi's `encoding_k3.py` renders this through the same tool-declare path
988    /// as the top-level `tools` field and never inspects individual entries, so
989    /// the canonical shape is the same OpenAI wrapped form,
990    /// `{"type": "function", "function": {...}}`. Clients that send bare
991    /// function-schema objects (`{"name": ..., "parameters": ...}`) are passed
992    /// through unchanged as well; this crate takes no position on the shape.
993    #[serde(skip_serializing_if = "Option::is_none")]
994    pub tools: Option<Vec<serde_json::Value>>,
995}
996
997impl<'de> Deserialize<'de> for ChatCompletionRequestSystemMessage {
998    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
999    where
1000        D: serde::Deserializer<'de>,
1001    {
1002        use serde::de::Error;
1003
1004        /// Wire shape with `content` relaxed solely for recognizing Kimi's
1005        /// tools-only form. Deserialized first so field-level errors (bad
1006        /// `content` shape, non-array `tools`) keep serde's own messages.
1007        #[derive(Deserialize)]
1008        struct Wire {
1009            content: Option<ChatCompletionRequestSystemMessageContent>,
1010            name: Option<String>,
1011            tools: Option<Vec<serde_json::Value>>,
1012        }
1013
1014        let Wire {
1015            content,
1016            name,
1017            tools,
1018        } = Wire::deserialize(deserializer)?;
1019        let content = match content {
1020            Some(content) => content,
1021            None if tools.as_ref().is_some_and(|tools| !tools.is_empty()) => {
1022                ChatCompletionRequestSystemMessageContent::Text(String::new())
1023            }
1024            None => {
1025                return Err(D::Error::custom(
1026                    "missing field `content`: a system message needs `content` unless it \
1027                     declares non-empty Kimi-style `tools`",
1028                ));
1029            }
1030        };
1031        Ok(Self {
1032            content,
1033            name,
1034            tools,
1035        })
1036    }
1037}
1038
1039/// Assistant message with reasoning content support.
1040///
1041/// Extends upstream `ChatCompletionRequestAssistantMessage` with:
1042/// - `reasoning_content`: interleaved reasoning segments for KV cache correctness
1043///   (DeepSeek-R1, QwQ models)
1044/// - `partial`: Kimi-style prefill flag marking an assistant turn as an
1045///   incomplete continuation seed rather than a finished turn
1046#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
1047#[builder(name = "ChatCompletionRequestAssistantMessageArgs")]
1048#[builder(pattern = "mutable")]
1049#[builder(setter(into, strip_option), default)]
1050#[builder(derive(Debug))]
1051#[builder(build_fn(error = "OpenAIError"))]
1052#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1053#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestAssistantMessage))]
1054pub struct ChatCompletionRequestAssistantMessage {
1055    #[serde(skip_serializing_if = "Option::is_none")]
1056    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ChatCompletionRequestAssistantMessageContent>))]
1057    pub content: Option<ChatCompletionRequestAssistantMessageContent>,
1058    /// Reasoning content from a previous assistant turn.
1059    /// Accept both `reasoning_content` (DeepSeek /
1060    /// SGLang / TRT-LLM / Vercel AI SDK openai-compatible / LangChain / LiteLLM
1061    /// canonical) and `reasoning` (vLLM native / OpenRouter / OpenAI GPT-OSS
1062    /// guidance) on inbound assistant messages, normalizing both to this field.
1063    #[serde(default, alias = "reasoning", skip_serializing_if = "Option::is_none")]
1064    pub reasoning_content: Option<ReasoningContent>,
1065    #[serde(skip_serializing_if = "Option::is_none")]
1066    pub refusal: Option<String>,
1067    #[serde(skip_serializing_if = "Option::is_none")]
1068    pub name: Option<String>,
1069    #[serde(skip_serializing_if = "Option::is_none")]
1070    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ChatCompletionRequestAssistantMessageAudio>))]
1071    pub audio: Option<ChatCompletionRequestAssistantMessageAudio>,
1072    #[serde(skip_serializing_if = "Option::is_none")]
1073    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
1074    #[deprecated]
1075    #[serde(skip_serializing_if = "Option::is_none")]
1076    pub function_call: Option<FunctionCall>,
1077    #[serde(skip_serializing_if = "Option::is_none")]
1078    pub partial: Option<bool>,
1079}
1080
1081/// Chat completion request message enum.
1082///
1083/// Redefined to use our extended `ChatCompletionRequestAssistantMessage`
1084/// (with reasoning_content) and `ChatCompletionRequestUserMessage`
1085/// (which references our extended content parts with video/audio).
1086///
1087/// Deserialization rejects Kimi-specific fields on roles that cannot carry
1088/// them (`tools` off `system`, `partial` off `assistant`) instead of letting
1089/// serde's ignore-unknown-fields default drop them silently; Moonshot's
1090/// negative tests expect a request error for these shapes.
1091#[derive(Debug, Serialize, Clone, PartialEq)]
1092#[serde(tag = "role")]
1093#[serde(rename_all = "lowercase")]
1094#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1095#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionRequestMessage))]
1096pub enum ChatCompletionRequestMessage {
1097    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::ChatCompletionRequestDeveloperMessage))]
1098    Developer(ChatCompletionRequestDeveloperMessage),
1099    System(ChatCompletionRequestSystemMessage),
1100    User(ChatCompletionRequestUserMessage),
1101    Assistant(ChatCompletionRequestAssistantMessage),
1102    Tool(ChatCompletionRequestToolMessage),
1103    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::ChatCompletionRequestFunctionMessage))]
1104    Function(ChatCompletionRequestFunctionMessage),
1105}
1106
1107impl<'de> Deserialize<'de> for ChatCompletionRequestMessage {
1108    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1109    where
1110        D: serde::Deserializer<'de>,
1111    {
1112        use serde::de::Error;
1113
1114        #[derive(Deserialize)]
1115        struct ForbidToolsAndPartial<T> {
1116            tools: Option<serde::de::IgnoredAny>,
1117            partial: Option<serde::de::IgnoredAny>,
1118            #[serde(flatten)]
1119            message: T,
1120        }
1121
1122        #[derive(Deserialize)]
1123        struct ForbidTools<T> {
1124            tools: Option<serde::de::IgnoredAny>,
1125            #[serde(flatten)]
1126            message: T,
1127        }
1128
1129        #[derive(Deserialize)]
1130        struct ForbidPartial<T> {
1131            partial: Option<serde::de::IgnoredAny>,
1132            #[serde(flatten)]
1133            message: T,
1134        }
1135
1136        #[derive(Deserialize)]
1137        #[serde(tag = "role")]
1138        #[serde(rename_all = "lowercase")]
1139        enum Wire {
1140            Developer(ForbidToolsAndPartial<ChatCompletionRequestDeveloperMessage>),
1141            System(ForbidPartial<ChatCompletionRequestSystemMessage>),
1142            User(ForbidToolsAndPartial<ChatCompletionRequestUserMessage>),
1143            Assistant(ForbidTools<ChatCompletionRequestAssistantMessage>),
1144            Tool(ForbidToolsAndPartial<ChatCompletionRequestToolMessage>),
1145            Function(ForbidToolsAndPartial<ChatCompletionRequestFunctionMessage>),
1146        }
1147
1148        fn reject_forbidden<E: Error>(
1149            value: Option<serde::de::IgnoredAny>,
1150            field: &str,
1151            allowed_role: &str,
1152            actual_role: &str,
1153        ) -> Result<(), E> {
1154            if value.is_some() {
1155                return Err(E::custom(format!(
1156                    "`{field}` is only accepted on {allowed_role} messages, not on role {actual_role}"
1157                )));
1158            }
1159            Ok(())
1160        }
1161
1162        let wire = Wire::deserialize(deserializer)?;
1163        Ok(match wire {
1164            Wire::Developer(ForbidToolsAndPartial {
1165                tools,
1166                partial,
1167                message,
1168            }) => {
1169                reject_forbidden::<D::Error>(tools, "tools", "system", "developer")?;
1170                reject_forbidden::<D::Error>(partial, "partial", "assistant", "developer")?;
1171                ChatCompletionRequestMessage::Developer(message)
1172            }
1173            Wire::System(ForbidPartial { partial, message }) => {
1174                reject_forbidden::<D::Error>(partial, "partial", "assistant", "system")?;
1175                ChatCompletionRequestMessage::System(message)
1176            }
1177            Wire::User(ForbidToolsAndPartial {
1178                tools,
1179                partial,
1180                message,
1181            }) => {
1182                reject_forbidden::<D::Error>(tools, "tools", "system", "user")?;
1183                reject_forbidden::<D::Error>(partial, "partial", "assistant", "user")?;
1184                ChatCompletionRequestMessage::User(message)
1185            }
1186            Wire::Assistant(ForbidTools { tools, message }) => {
1187                reject_forbidden::<D::Error>(tools, "tools", "system", "assistant")?;
1188                ChatCompletionRequestMessage::Assistant(message)
1189            }
1190            Wire::Tool(ForbidToolsAndPartial {
1191                tools,
1192                partial,
1193                message,
1194            }) => {
1195                reject_forbidden::<D::Error>(tools, "tools", "system", "tool")?;
1196                reject_forbidden::<D::Error>(partial, "partial", "assistant", "tool")?;
1197                ChatCompletionRequestMessage::Tool(message)
1198            }
1199            Wire::Function(ForbidToolsAndPartial {
1200                tools,
1201                partial,
1202                message,
1203            }) => {
1204                reject_forbidden::<D::Error>(tools, "tools", "system", "function")?;
1205                reject_forbidden::<D::Error>(partial, "partial", "assistant", "function")?;
1206                ChatCompletionRequestMessage::Function(message)
1207            }
1208        })
1209    }
1210}
1211
1212/// Backward-compatible name for the service tier reported in responses.
1213pub type ServiceTierResponse = ServiceTier;
1214
1215/// Chat completion response message with multimodal content and reasoning.
1216///
1217/// Extends upstream `ChatCompletionResponseMessage` with:
1218/// - `content`: `Option<ChatCompletionMessageContent>` (multimodal) instead of `Option<String>`
1219/// - `reasoning_content`: model reasoning output (DeepSeek-R1, QwQ)
1220#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1221#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1222#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionResponseMessage))]
1223pub struct ChatCompletionResponseMessage {
1224    /// Always serialized (as `null` when None) so clients can rely on the
1225    /// `content` key being present alongside `reasoning_content` or
1226    /// `tool_calls`. Matches the upstream OpenAI API shape (DGH-651).
1227    #[cfg_attr(feature = "protocol-schema", schema(required))]
1228    pub content: Option<ChatCompletionMessageContent>,
1229    /// Always serialized (as `null` when None): the spec marks `refusal` as
1230    /// required-and-nullable, and OpenAI emits `"refusal": null` on every
1231    /// non-refusal response.
1232    #[cfg_attr(feature = "protocol-schema", schema(required))]
1233    pub refusal: Option<String>,
1234    #[serde(skip_serializing_if = "Option::is_none")]
1235    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
1236    #[cfg_attr(feature = "protocol-schema", schema(value_type = crate::schema::Role))]
1237    pub role: Role,
1238    #[serde(skip_serializing_if = "Option::is_none")]
1239    #[deprecated]
1240    pub function_call: Option<FunctionCall>,
1241    #[serde(skip_serializing_if = "Option::is_none")]
1242    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ChatCompletionResponseMessageAudio>))]
1243    pub audio: Option<ChatCompletionResponseMessageAudio>,
1244    /// Reasoning content produced by the model (DeepSeek-R1, QwQ).
1245    /// Accepts either `reasoning_content` (DeepSeek / SGLang / TRT-LLM
1246    /// canonical) or `reasoning` (vLLM native / OpenRouter / OpenAI GPT-OSS)
1247    /// on input via the alias; output-side key selection is handled at the
1248    /// HTTP boundary by ai-dynamo/dynamo#11464's `RoutedReasoning` wrapper.
1249    /// Not part of the OpenAI spec, so it is omitted entirely when absent.
1250    #[serde(default, alias = "reasoning", skip_serializing_if = "Option::is_none")]
1251    pub reasoning_content: Option<String>,
1252}
1253
1254fn deserialize_null_as_false<'de, D>(deserializer: D) -> Result<bool, D::Error>
1255where
1256    D: serde::Deserializer<'de>,
1257{
1258    Option::<bool>::deserialize(deserializer).map(Option::unwrap_or_default)
1259}
1260
1261/// Stream options with per-chunk usage reporting.
1262///
1263/// Extends upstream `ChatCompletionStreamOptions` with:
1264/// - `continuous_usage_stats`: emit usage in every chunk, not just the final one
1265#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
1266#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1267#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionStreamOptions))]
1268pub struct ChatCompletionStreamOptions {
1269    #[serde(default, deserialize_with = "deserialize_null_as_false")]
1270    pub include_usage: bool,
1271    /// When true, usage statistics are included in every streaming chunk.
1272    /// Backends like vLLM/SGLang support this for real-time token counting.
1273    #[serde(default, deserialize_with = "deserialize_null_as_false")]
1274    pub continuous_usage_stats: bool,
1275}
1276
1277/// Chat completion request with multimodal processor support.
1278///
1279/// Extends upstream `CreateChatCompletionRequest` with:
1280/// - `mm_processor_kwargs`: multimodal processor configuration (vLLM-specific)
1281/// - Uses our extended `ChatCompletionRequestMessage` (with reasoning, video/audio)
1282/// - Uses our extended `ChatCompletionStreamOptions` (with continuous_usage_stats)
1283#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
1284#[builder(name = "CreateChatCompletionRequestArgs")]
1285#[builder(pattern = "mutable")]
1286#[builder(setter(into, strip_option), default)]
1287#[builder(derive(Debug))]
1288#[builder(build_fn(error = "OpenAIError"))]
1289#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1290#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::CreateChatCompletionRequest))]
1291pub struct CreateChatCompletionRequest {
1292    pub messages: Vec<ChatCompletionRequestMessage>,
1293    pub model: String,
1294    /// Multimodal processor configuration (vLLM-specific)
1295    #[serde(skip_serializing_if = "Option::is_none")]
1296    pub mm_processor_kwargs: Option<serde_json::Value>,
1297    #[serde(skip_serializing_if = "Option::is_none")]
1298    pub store: Option<bool>,
1299    #[serde(skip_serializing_if = "Option::is_none")]
1300    pub reasoning_effort: Option<ReasoningEffort>,
1301    #[serde(skip_serializing_if = "Option::is_none")]
1302    pub metadata: Option<serde_json::Value>,
1303    #[serde(skip_serializing_if = "Option::is_none")]
1304    pub frequency_penalty: Option<f32>,
1305    #[serde(skip_serializing_if = "Option::is_none")]
1306    pub logit_bias: Option<std::collections::HashMap<String, serde_json::Value>>,
1307    #[serde(skip_serializing_if = "Option::is_none")]
1308    pub logprobs: Option<bool>,
1309    #[serde(skip_serializing_if = "Option::is_none")]
1310    pub top_logprobs: Option<u8>,
1311    #[deprecated]
1312    #[serde(skip_serializing_if = "Option::is_none")]
1313    pub max_tokens: Option<u32>,
1314    #[serde(skip_serializing_if = "Option::is_none")]
1315    pub max_completion_tokens: Option<u32>,
1316    #[serde(skip_serializing_if = "Option::is_none")]
1317    pub n: Option<u8>,
1318    #[serde(skip_serializing_if = "Option::is_none")]
1319    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<Vec<crate::schema::ResponseModalities>>))]
1320    pub modalities: Option<Vec<async_openai::types::chat::ResponseModalities>>,
1321    #[serde(skip_serializing_if = "Option::is_none")]
1322    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::PredictionContent>))]
1323    pub prediction: Option<PredictionContent>,
1324    #[serde(skip_serializing_if = "Option::is_none")]
1325    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ChatCompletionAudio>))]
1326    pub audio: Option<ChatCompletionAudio>,
1327    #[serde(skip_serializing_if = "Option::is_none")]
1328    pub presence_penalty: Option<f32>,
1329    #[serde(skip_serializing_if = "Option::is_none")]
1330    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ResponseFormat>))]
1331    pub response_format: Option<ResponseFormat>,
1332    #[serde(skip_serializing_if = "Option::is_none")]
1333    pub seed: Option<i64>,
1334    #[serde(skip_serializing_if = "Option::is_none")]
1335    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ServiceTier>))]
1336    pub service_tier: Option<ServiceTier>,
1337    #[serde(skip_serializing_if = "Option::is_none")]
1338    pub stop: Option<Stop>,
1339    #[serde(default, skip_serializing_if = "Option::is_none")]
1340    pub stream: Option<bool>,
1341    #[serde(skip_serializing_if = "Option::is_none")]
1342    pub stream_options: Option<ChatCompletionStreamOptions>,
1343    #[serde(skip_serializing_if = "Option::is_none")]
1344    pub temperature: Option<f32>,
1345    #[serde(skip_serializing_if = "Option::is_none")]
1346    pub top_p: Option<f32>,
1347    #[serde(skip_serializing_if = "Option::is_none")]
1348    pub tools: Option<Vec<ChatCompletionTool>>,
1349    #[serde(skip_serializing_if = "Option::is_none")]
1350    pub tool_choice: Option<ChatCompletionToolChoiceOption>,
1351    #[serde(skip_serializing_if = "Option::is_none")]
1352    pub parallel_tool_calls: Option<bool>,
1353    #[serde(skip_serializing_if = "Option::is_none")]
1354    pub user: Option<String>,
1355    /// OpenAI cache-affinity hint: requests sharing a prompt prefix send the
1356    /// same key (Kimi Code CLI sends its session id on every request).
1357    ///
1358    /// NOTICE: accepted and preserved only. Nothing in this crate or in Dynamo
1359    /// acts on it yet — Dynamo's KV-aware router keys on prompt-prefix block
1360    /// hashes, not on this value.
1361    // TODO(routing): decide whether `prompt_cache_key` should feed router
1362    // affinity (e.g. as a tie-breaker or session pin) and plumb it through.
1363    #[serde(skip_serializing_if = "Option::is_none")]
1364    pub prompt_cache_key: Option<String>,
1365    #[deprecated]
1366    #[serde(skip_serializing_if = "Option::is_none")]
1367    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ChatCompletionFunctionCall>))]
1368    pub function_call: Option<ChatCompletionFunctionCall>,
1369    #[deprecated]
1370    #[serde(skip_serializing_if = "Option::is_none")]
1371    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<Vec<crate::schema::ChatCompletionFunctions>>))]
1372    pub functions: Option<Vec<ChatCompletionFunctions>>,
1373    #[serde(skip_serializing_if = "Option::is_none")]
1374    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::WebSearchOptions>))]
1375    pub web_search_options: Option<WebSearchOptions>,
1376}
1377
1378impl CreateChatCompletionRequest {
1379    /// Kimi-style dynamic tools declared on `system` messages, in message order.
1380    ///
1381    /// Kimi defines these as coexisting with the top-level `tools` list: a
1382    /// dynamic declaration keeps its position in the message history so the
1383    /// prompt prefix (and any KV cache built on it) stays intact. Do not fold
1384    /// them into `tools`; reason about the union with
1385    /// [`Self::has_effective_tools`] and [`Self::effective_tool_contains`].
1386    ///
1387    /// Only `system` messages can carry `tools` in the typed schema; the
1388    /// `developer` message is the upstream type and has no such field.
1389    pub fn dynamic_system_tools(&self) -> impl Iterator<Item = &serde_json::Value> {
1390        self.messages
1391            .iter()
1392            .filter_map(|message| match message {
1393                ChatCompletionRequestMessage::System(system) => system.tools.as_deref(),
1394                _ => None,
1395            })
1396            .flatten()
1397    }
1398
1399    /// Whether the request declares any tool, either top-level or through a
1400    /// dynamic system-message declaration.
1401    ///
1402    /// Gates that decide whether model output may be interpreted as tool
1403    /// calls must use this rather than `tools` alone, or a call to a
1404    /// dynamically declared tool is stripped from the response.
1405    pub fn has_effective_tools(&self) -> bool {
1406        self.tools.as_ref().is_some_and(|tools| !tools.is_empty())
1407            || self.dynamic_system_tools().next().is_some()
1408    }
1409
1410    /// Names of every tool the model can see: top-level `tools` first, then
1411    /// dynamic system-message tools in message order.
1412    pub fn effective_tool_names(&self) -> impl Iterator<Item = &str> {
1413        self.tools
1414            .iter()
1415            .flatten()
1416            .map(|tool| tool.function.name.as_str())
1417            .chain(self.dynamic_system_tools().filter_map(dynamic_tool_name))
1418    }
1419
1420    /// Whether `name` is declared anywhere in the effective tool set.
1421    ///
1422    /// Use this to validate a named `tool_choice` so a forced call to a
1423    /// dynamically declared tool is not rejected as "not present in tools".
1424    pub fn effective_tool_contains(&self, name: &str) -> bool {
1425        self.effective_tool_names().any(|tool| tool == name)
1426    }
1427}
1428
1429/// Name of a dynamic system-message tool entry.
1430///
1431/// Accepts both the OpenAI wrapped form
1432/// `{"type": "function", "function": {"name": ...}}` and the bare
1433/// function-schema form `{"name": ...}` that some Kimi clients send. Returns
1434/// `None` for entries with no string name.
1435pub fn dynamic_tool_name(tool: &serde_json::Value) -> Option<&str> {
1436    tool.get("function")
1437        .and_then(serde_json::Value::as_object)
1438        .and_then(|function| function.get("name"))
1439        .or_else(|| tool.get("name"))
1440        .and_then(serde_json::Value::as_str)
1441}
1442
1443/// Chat choice with extended response message.
1444///
1445/// Uses our `ChatCompletionResponseMessage` (multimodal content + reasoning).
1446#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1447#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1448#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatChoice))]
1449pub struct ChatChoice {
1450    pub index: u32,
1451    pub message: ChatCompletionResponseMessage,
1452    // These keys are always serialized, including explicit nulls.
1453    #[cfg_attr(feature = "protocol-schema", schema(required, value_type = Option<crate::schema::FinishReason>))]
1454    pub finish_reason: Option<FinishReason>,
1455    #[cfg_attr(feature = "protocol-schema", schema(required))]
1456    pub logprobs: Option<ChatChoiceLogprobs>,
1457}
1458
1459/// Serializes `usage` through a shadow struct that omits absent optional
1460/// fields.
1461///
1462/// Upstream async-openai derives serialize `None` usage-details fields as
1463/// explicit `null` (e.g. `"audio_tokens": null`), but the spec marks every
1464/// usage-details field optional and non-nullable, so absent fields must be
1465/// omitted (OpenAI emits `"audio_tokens": 0`, never `null`). The shadow
1466/// keeps upstream `CompletionUsage` in the public API — replacing it with a
1467/// same-named local type would break callers that pass upstream values.
1468fn serialize_usage_omitting_absent<S>(
1469    usage: &Option<CompletionUsage>,
1470    serializer: S,
1471) -> Result<S::Ok, S::Error>
1472where
1473    S: serde::Serializer,
1474{
1475    #[derive(Serialize)]
1476    struct PromptDetailsShadow {
1477        #[serde(skip_serializing_if = "Option::is_none")]
1478        audio_tokens: Option<u32>,
1479        #[serde(skip_serializing_if = "Option::is_none")]
1480        cached_tokens: Option<u32>,
1481    }
1482
1483    #[derive(Serialize)]
1484    struct CompletionDetailsShadow {
1485        #[serde(skip_serializing_if = "Option::is_none")]
1486        accepted_prediction_tokens: Option<u32>,
1487        #[serde(skip_serializing_if = "Option::is_none")]
1488        audio_tokens: Option<u32>,
1489        #[serde(skip_serializing_if = "Option::is_none")]
1490        reasoning_tokens: Option<u32>,
1491        #[serde(skip_serializing_if = "Option::is_none")]
1492        rejected_prediction_tokens: Option<u32>,
1493    }
1494
1495    #[derive(Serialize)]
1496    struct UsageShadow {
1497        prompt_tokens: u32,
1498        completion_tokens: u32,
1499        total_tokens: u32,
1500        #[serde(skip_serializing_if = "Option::is_none")]
1501        prompt_tokens_details: Option<PromptDetailsShadow>,
1502        #[serde(skip_serializing_if = "Option::is_none")]
1503        completion_tokens_details: Option<CompletionDetailsShadow>,
1504    }
1505
1506    match usage {
1507        None => serializer.serialize_none(),
1508        Some(u) => UsageShadow {
1509            prompt_tokens: u.prompt_tokens,
1510            completion_tokens: u.completion_tokens,
1511            total_tokens: u.total_tokens,
1512            prompt_tokens_details: u
1513                .prompt_tokens_details
1514                .as_ref()
1515                .map(|d| PromptDetailsShadow {
1516                    audio_tokens: d.audio_tokens,
1517                    cached_tokens: d.cached_tokens,
1518                }),
1519            completion_tokens_details: u.completion_tokens_details.as_ref().map(|d| {
1520                CompletionDetailsShadow {
1521                    accepted_prediction_tokens: d.accepted_prediction_tokens,
1522                    audio_tokens: d.audio_tokens,
1523                    reasoning_tokens: d.reasoning_tokens,
1524                    rejected_prediction_tokens: d.rejected_prediction_tokens,
1525                }
1526            }),
1527        }
1528        .serialize(serializer),
1529    }
1530}
1531
1532/// Non-streaming chat completion response.
1533///
1534/// `service_tier`, `system_fingerprint`, and `usage` are optional in the
1535/// spec and omitted (not serialized as `null`) when absent, matching
1536/// OpenAI output. `choices[].finish_reason` and `choices[].logprobs` stay
1537/// always-present: the spec marks them required (nullable for `logprobs`).
1538#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
1539#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1540#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::CreateChatCompletionResponse))]
1541pub struct CreateChatCompletionResponse {
1542    pub id: String,
1543    pub choices: Vec<ChatChoice>,
1544    pub created: u32,
1545    pub model: String,
1546    #[serde(skip_serializing_if = "Option::is_none")]
1547    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ServiceTier>))]
1548    pub service_tier: Option<ServiceTierResponse>,
1549    #[serde(skip_serializing_if = "Option::is_none")]
1550    pub system_fingerprint: Option<String>,
1551    pub object: String,
1552    #[serde(
1553        skip_serializing_if = "Option::is_none",
1554        serialize_with = "serialize_usage_omitting_absent"
1555    )]
1556    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::CompletionUsage>))]
1557    pub usage: Option<CompletionUsage>,
1558}
1559
1560pub type ChatCompletionResponseStream =
1561    Pin<Box<dyn Stream<Item = Result<CreateChatCompletionStreamResponse, OpenAIError>> + Send>>;
1562
1563/// Streaming delta with reasoning content.
1564///
1565/// Extends upstream `ChatCompletionStreamResponseDelta` with:
1566/// - `content`: `Option<ChatCompletionMessageContent>` (multimodal) instead of `Option<String>`
1567/// - `reasoning_content`: streaming reasoning tokens (DeepSeek-R1, QwQ)
1568#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1569#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1570#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionStreamResponseDelta))]
1571pub struct ChatCompletionStreamResponseDelta {
1572    #[serde(skip_serializing_if = "Option::is_none")]
1573    pub content: Option<ChatCompletionMessageContent>,
1574    #[serde(skip_serializing_if = "Option::is_none")]
1575    pub function_call: Option<ChatCompletionStreamResponseDeltaFunctionCall>,
1576    #[serde(skip_serializing_if = "Option::is_none")]
1577    pub tool_calls: Option<Vec<ChatCompletionMessageToolCallChunk>>,
1578    #[serde(skip_serializing_if = "Option::is_none")]
1579    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::Role>))]
1580    pub role: Option<Role>,
1581    #[serde(skip_serializing_if = "Option::is_none")]
1582    pub refusal: Option<String>,
1583    /// Streaming reasoning content (DeepSeek-R1, QwQ models).
1584    /// Accepts either `reasoning_content` (DeepSeek / SGLang / TRT-LLM
1585    /// canonical) or `reasoning` (vLLM native / OpenRouter / OpenAI GPT-OSS)
1586    /// on input via the alias; output-side key selection is handled at the
1587    /// HTTP boundary by ai-dynamo/dynamo#11464's `RoutedReasoning` wrapper.
1588    #[serde(default, alias = "reasoning", skip_serializing_if = "Option::is_none")]
1589    pub reasoning_content: Option<String>,
1590}
1591
1592#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
1593#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1594#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatCompletionStreamResponseDeltaFunctionCall))]
1595pub struct ChatCompletionStreamResponseDeltaFunctionCall {
1596    #[serde(skip_serializing_if = "Option::is_none")]
1597    pub name: Option<String>,
1598    #[serde(
1599        default,
1600        deserialize_with = "deserialize_arguments_opt",
1601        skip_serializing_if = "Option::is_none"
1602    )]
1603    pub arguments: Option<String>,
1604}
1605
1606/// Streaming chat choice.
1607#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
1608#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1609#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::ChatChoiceStream))]
1610pub struct ChatChoiceStream {
1611    pub index: u32,
1612    pub delta: ChatCompletionStreamResponseDelta,
1613    // These keys are always serialized, including explicit nulls.
1614    #[cfg_attr(feature = "protocol-schema", schema(required, value_type = Option<crate::schema::FinishReason>))]
1615    pub finish_reason: Option<FinishReason>,
1616    #[cfg_attr(feature = "protocol-schema", schema(required))]
1617    pub logprobs: Option<ChatChoiceLogprobs>,
1618}
1619
1620/// Streaming chat completion response with extended choices.
1621///
1622/// `service_tier`, `system_fingerprint`, and `usage` are optional in the
1623/// spec and omitted (not serialized as `null`) when absent. Note: with
1624/// `stream_options.include_usage`, OpenAI emits `"usage": null` on every
1625/// chunk before the final one; callers needing that exact shape must
1626/// inject the key at the HTTP boundary.
1627#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
1628#[cfg_attr(feature = "protocol-schema", derive(utoipa::ToSchema))]
1629#[cfg_attr(feature = "protocol-schema", schema(as = dynamo_protocols::chat::CreateChatCompletionStreamResponse))]
1630pub struct CreateChatCompletionStreamResponse {
1631    pub id: String,
1632    pub choices: Vec<ChatChoiceStream>,
1633    pub created: u32,
1634    pub model: String,
1635    #[serde(skip_serializing_if = "Option::is_none")]
1636    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::ServiceTier>))]
1637    pub service_tier: Option<ServiceTierResponse>,
1638    #[serde(skip_serializing_if = "Option::is_none")]
1639    pub system_fingerprint: Option<String>,
1640    pub object: String,
1641    #[serde(
1642        skip_serializing_if = "Option::is_none",
1643        serialize_with = "serialize_usage_omitting_absent"
1644    )]
1645    #[cfg_attr(feature = "protocol-schema", schema(value_type = Option<crate::schema::CompletionUsage>))]
1646    pub usage: Option<CompletionUsage>,
1647}
1648
1649#[cfg(test)]
1650mod tests {
1651    use super::*;
1652
1653    #[test]
1654    fn stream_options_default_missing_and_null_flags_to_false() {
1655        for (payload, expected) in [
1656            (serde_json::json!({}), (false, false)),
1657            (
1658                serde_json::json!({
1659                    "include_usage": null,
1660                    "continuous_usage_stats": true,
1661                }),
1662                (false, true),
1663            ),
1664            (
1665                serde_json::json!({
1666                    "include_usage": true,
1667                    "continuous_usage_stats": null,
1668                }),
1669                (true, false),
1670            ),
1671        ] {
1672            let options: ChatCompletionStreamOptions = serde_json::from_value(payload).unwrap();
1673            assert_eq!(
1674                (options.include_usage, options.continuous_usage_stats),
1675                expected
1676            );
1677        }
1678    }
1679
1680    #[test]
1681    fn stream_options_preserve_boolean_wire_shape_and_reject_other_types() {
1682        let options: ChatCompletionStreamOptions = serde_json::from_value(serde_json::json!({
1683            "include_usage": true,
1684            "continuous_usage_stats": false,
1685        }))
1686        .unwrap();
1687        assert!(options.include_usage);
1688        assert!(!options.continuous_usage_stats);
1689        assert_eq!(
1690            serde_json::to_value(options).unwrap(),
1691            serde_json::json!({
1692                "include_usage": true,
1693                "continuous_usage_stats": false,
1694            })
1695        );
1696
1697        for payload in [
1698            serde_json::json!({"include_usage": "true"}),
1699            serde_json::json!({"continuous_usage_stats": 1}),
1700        ] {
1701            serde_json::from_value::<ChatCompletionStreamOptions>(payload).unwrap_err();
1702        }
1703    }
1704
1705    #[test]
1706    fn stop_accepts_token_id_array() {
1707        let stop: Stop = serde_json::from_value(serde_json::json!([32, 34])).unwrap();
1708
1709        assert_eq!(stop, Stop::TokenIdArray(vec![32, 34]));
1710    }
1711
1712    #[test]
1713    fn stop_accepts_string_and_string_array() {
1714        let stop: Stop = serde_json::from_value(serde_json::json!(" The")).unwrap();
1715
1716        assert_eq!(stop, Stop::String(" The".to_string()));
1717
1718        let stop: Stop = serde_json::from_value(serde_json::json!(["A", "B"])).unwrap();
1719
1720        assert_eq!(
1721            stop,
1722            Stop::StringArray(vec!["A".to_string(), "B".to_string()])
1723        );
1724    }
1725
1726    #[test]
1727    fn stop_token_id_display_string_remains_string_stop() {
1728        let stop: Stop = serde_json::from_value(serde_json::json!("token_id:576")).unwrap();
1729
1730        assert_eq!(stop, Stop::String("token_id:576".to_string()));
1731
1732        let stop: Stop = serde_json::from_value(serde_json::json!(["token_id:576"])).unwrap();
1733
1734        assert_eq!(stop, Stop::StringArray(vec!["token_id:576".to_string()]));
1735    }
1736
1737    #[test]
1738    fn stop_rejects_single_token_id() {
1739        let result = serde_json::from_value::<Stop>(serde_json::json!(576));
1740
1741        assert!(result.is_err());
1742    }
1743
1744    #[test]
1745    fn stop_converts_from_upstream_stop_configuration() {
1746        let upstream =
1747            async_openai::types::chat::StopConfiguration::StringArray(vec!["END".to_string()]);
1748
1749        assert_eq!(
1750            Stop::from(upstream),
1751            Stop::StringArray(vec!["END".to_string()])
1752        );
1753    }
1754
1755    #[test]
1756    fn request_builder_accepts_upstream_reasoning_effort() {
1757        let request = CreateChatCompletionRequestArgs::default()
1758            .reasoning_effort(async_openai::types::chat::ReasoningEffort::High)
1759            .build()
1760            .unwrap();
1761
1762        assert_eq!(request.reasoning_effort, Some(ReasoningEffort::High));
1763    }
1764
1765    #[test]
1766    fn tool_call_defaults_type_on_deserialize() {
1767        let tool_call: ChatCompletionMessageToolCall = serde_json::from_value(serde_json::json!({
1768            "id": "call_123",
1769            "function": {
1770                "name": "get_weather",
1771                "arguments": "{\"location\":\"SF\"}"
1772            }
1773        }))
1774        .unwrap();
1775
1776        assert_eq!(tool_call.r#type, FunctionType::Function);
1777    }
1778
1779    #[test]
1780    fn tool_call_serializes_type_for_wire_compat() {
1781        let tool_call = ChatCompletionMessageToolCall {
1782            custom: None,
1783            id: "call_123".into(),
1784            r#type: FunctionType::Function,
1785            function: FunctionCall {
1786                name: "get_weather".into(),
1787                arguments: "{\"location\":\"SF\"}".into(),
1788            },
1789        };
1790
1791        let json = serde_json::to_value(tool_call).unwrap();
1792        assert_eq!(json["type"], "function");
1793    }
1794
1795    // -- dict-format arguments tests --
1796
1797    #[test]
1798    fn function_call_accepts_string_arguments() {
1799        let fc: FunctionCall = serde_json::from_value(serde_json::json!({
1800            "name": "get_weather",
1801            "arguments": "{\"location\":\"SF\"}"
1802        }))
1803        .unwrap();
1804        assert_eq!(fc.arguments, "{\"location\":\"SF\"}");
1805    }
1806
1807    #[test]
1808    fn function_call_accepts_dict_arguments() {
1809        let fc: FunctionCall = serde_json::from_value(serde_json::json!({
1810            "name": "get_weather",
1811            "arguments": {"location": "SF"}
1812        }))
1813        .unwrap();
1814        assert_eq!(fc.arguments, "{\"location\":\"SF\"}");
1815    }
1816
1817    #[test]
1818    fn function_call_rejects_integer_arguments() {
1819        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
1820            "name": "f",
1821            "arguments": 42
1822        }));
1823        assert!(result.is_err());
1824    }
1825
1826    #[test]
1827    fn function_call_rejects_boolean_arguments() {
1828        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
1829            "name": "f",
1830            "arguments": true
1831        }));
1832        assert!(result.is_err());
1833    }
1834
1835    #[test]
1836    fn function_call_rejects_null_arguments() {
1837        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
1838            "name": "f",
1839            "arguments": null
1840        }));
1841        assert!(result.is_err());
1842    }
1843
1844    #[test]
1845    fn function_call_rejects_array_arguments() {
1846        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
1847            "name": "f",
1848            "arguments": [1, 2, 3]
1849        }));
1850        assert!(result.is_err());
1851    }
1852
1853    #[test]
1854    fn function_call_stream_null_arguments_produces_none() {
1855        let fcs: FunctionCallStream = serde_json::from_value(serde_json::json!({
1856            "name": "f",
1857            "arguments": null
1858        }))
1859        .unwrap();
1860        assert_eq!(fcs.arguments, None);
1861    }
1862
1863    #[test]
1864    fn function_call_stream_rejects_integer_arguments() {
1865        let result = serde_json::from_value::<FunctionCallStream>(serde_json::json!({
1866            "name": "f",
1867            "arguments": 42
1868        }));
1869        assert!(result.is_err());
1870    }
1871
1872    #[test]
1873    fn function_call_stream_rejects_boolean_arguments() {
1874        let result = serde_json::from_value::<FunctionCallStream>(serde_json::json!({
1875            "name": "f",
1876            "arguments": true
1877        }));
1878        assert!(result.is_err());
1879    }
1880
1881    #[test]
1882    fn function_call_stream_accepts_dict_arguments() {
1883        let fcs: FunctionCallStream = serde_json::from_value(serde_json::json!({
1884            "name": "get_weather",
1885            "arguments": {"location": "SF"}
1886        }))
1887        .unwrap();
1888        assert_eq!(fcs.arguments.as_deref(), Some("{\"location\":\"SF\"}"));
1889    }
1890
1891    #[test]
1892    fn function_call_stream_accepts_null_arguments() {
1893        let fcs: FunctionCallStream = serde_json::from_value(serde_json::json!({
1894            "name": "get_weather"
1895        }))
1896        .unwrap();
1897        assert_eq!(fcs.arguments, None);
1898    }
1899
1900    #[test]
1901    fn tool_call_with_dict_arguments_roundtrip() {
1902        let tc: ChatCompletionMessageToolCall = serde_json::from_value(serde_json::json!({
1903            "id": "call_abc",
1904            "type": "function",
1905            "function": {
1906                "name": "search",
1907                "arguments": {"query": "hello", "limit": 10}
1908            }
1909        }))
1910        .unwrap();
1911        // Compare as parsed JSON values since key order is non-deterministic
1912        let parsed: serde_json::Value = serde_json::from_str(&tc.function.arguments).unwrap();
1913        assert_eq!(parsed, serde_json::json!({"query": "hello", "limit": 10}));
1914        // Re-serialisation produces a string, not an object
1915        let json = serde_json::to_value(&tc).unwrap();
1916        assert!(json["function"]["arguments"].is_string());
1917    }
1918
1919    #[test]
1920    fn stream_delta_function_call_accepts_dict_arguments() {
1921        let delta: ChatCompletionStreamResponseDeltaFunctionCall =
1922            serde_json::from_value(serde_json::json!({
1923                "name": "get_weather",
1924                "arguments": {"location": "SF"}
1925            }))
1926            .unwrap();
1927        assert_eq!(delta.arguments.as_deref(), Some("{\"location\":\"SF\"}"));
1928    }
1929
1930    fn parse_content_part(json: serde_json::Value) -> ChatCompletionRequestUserMessageContentPart {
1931        serde_json::from_value(json).expect("content part deserialization failed")
1932    }
1933
1934    #[test]
1935    fn image_url_url_and_top_level_uuid() {
1936        let part = parse_content_part(serde_json::json!({
1937            "type": "image_url",
1938            "image_url": {"url": "https://x.example/y.png"},
1939            "uuid": "image-123"
1940        }));
1941
1942        match part {
1943            ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => {
1944                assert_eq!(part.uuid.as_deref(), Some("image-123"));
1945                assert_eq!(
1946                    part.image_url.as_ref().map(|image| image.url.as_str()),
1947                    Some("https://x.example/y.png")
1948                );
1949            }
1950            _ => panic!("expected image_url part"),
1951        }
1952    }
1953
1954    #[test]
1955    fn image_url_null_and_top_level_uuid() {
1956        let part = parse_content_part(serde_json::json!({
1957            "type": "image_url",
1958            "image_url": null,
1959            "uuid": "sku-1234-a"
1960        }));
1961
1962        match part {
1963            ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => {
1964                assert!(part.image_url.is_none());
1965                assert_eq!(part.uuid.as_deref(), Some("sku-1234-a"));
1966            }
1967            _ => panic!("expected image_url part"),
1968        }
1969    }
1970
1971    #[test]
1972    fn empty_media_urls_deserialize_as_uuid_only() {
1973        for (part_type, media_field, uuid) in [
1974            ("image_url", "image_url", "image-cache-key"),
1975            ("video_url", "video_url", "video-cache-key"),
1976            ("audio_url", "audio_url", "audio-cache-key"),
1977        ] {
1978            let part = parse_content_part(serde_json::json!({
1979                "type": part_type,
1980                (media_field): {"url": ""},
1981                "uuid": uuid
1982            }));
1983            let json = serde_json::to_value(part).unwrap();
1984
1985            assert!(json[media_field].is_null());
1986            assert_eq!(json["uuid"], uuid);
1987        }
1988    }
1989
1990    #[test]
1991    fn image_url_null_without_uuid_deserializes_for_use_site_validation() {
1992        let part = parse_content_part(serde_json::json!({
1993            "type": "image_url",
1994            "image_url": null
1995        }));
1996
1997        match part {
1998            ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => {
1999                assert!(part.image_url.is_none());
2000                assert!(part.uuid.is_none());
2001            }
2002            _ => panic!("expected image_url part"),
2003        }
2004    }
2005
2006    #[test]
2007    fn image_url_serialize_uuid_only_uses_null_image_url() {
2008        let part = ChatCompletionRequestMessageContentPartImage {
2009            image_url: None,
2010            uuid: Some("image-123".to_string()),
2011        };
2012        let json = serde_json::to_value(part).unwrap();
2013
2014        assert!(json["image_url"].is_null());
2015        assert_eq!(json["uuid"], "image-123");
2016    }
2017
2018    #[test]
2019    fn cached_media_builders_allow_omitting_urls() {
2020        let image = ChatCompletionRequestMessageContentPartImageArgs::default()
2021            .uuid("image-123")
2022            .build()
2023            .unwrap();
2024        let video = ChatCompletionRequestMessageContentPartVideoArgs::default()
2025            .uuid("video-123")
2026            .build()
2027            .unwrap();
2028        let audio = ChatCompletionRequestMessageContentPartAudioUrlArgs::default()
2029            .uuid("audio-123")
2030            .build()
2031            .unwrap();
2032
2033        let image_json = serde_json::to_value(image).unwrap();
2034        let video_json = serde_json::to_value(video).unwrap();
2035        let audio_json = serde_json::to_value(audio).unwrap();
2036        assert!(image_json["image_url"].is_null());
2037        assert!(video_json["video_url"].is_null());
2038        assert!(audio_json["audio_url"].is_null());
2039    }
2040
2041    #[test]
2042    fn image_url_uuid_accepts_opaque_string() {
2043        let part = parse_content_part(serde_json::json!({
2044            "type": "image_url",
2045            "image_url": {"url": "https://x.example/y.png"},
2046            "uuid": "img-ac3921de680bb217"
2047        }));
2048
2049        match part {
2050            ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => {
2051                assert_eq!(part.uuid.as_deref(), Some("img-ac3921de680bb217"));
2052            }
2053            _ => panic!("expected image_url part"),
2054        }
2055    }
2056
2057    #[test]
2058    fn url_conversions_preserve_required_urls() {
2059        let image: ImageUrl = "https://x.example/image.png".into();
2060        let video: VideoUrl = "https://x.example/video.mp4".into();
2061        let audio: AudioUrl = "https://x.example/audio.wav".into();
2062
2063        assert_eq!(image.url.as_str(), "https://x.example/image.png");
2064        assert_eq!(video.url.as_str(), "https://x.example/video.mp4");
2065        assert_eq!(audio.url.as_str(), "https://x.example/audio.wav");
2066    }
2067
2068    #[test]
2069    fn invalid_media_urls_remain_rejected() {
2070        for (part_type, media_field) in [
2071            ("image_url", "image_url"),
2072            ("video_url", "video_url"),
2073            ("audio_url", "audio_url"),
2074        ] {
2075            let result = serde_json::from_value::<ChatCompletionRequestUserMessageContentPart>(
2076                serde_json::json!({
2077                    "type": part_type,
2078                    (media_field): {"url": "not a url"},
2079                    "uuid": "cache-key"
2080                }),
2081            );
2082
2083            assert!(result.is_err(), "{part_type} accepted an invalid URL");
2084        }
2085    }
2086
2087    #[test]
2088    fn legacy_nested_media_uuids_remain_accepted() {
2089        let legacy_uuid = "92b888ad-e64a-478f-b688-5091e16544e3";
2090
2091        for (part_type, media_field, url) in [
2092            ("image_url", "image_url", "https://x.example/image.png"),
2093            ("video_url", "video_url", "https://x.example/video.mp4"),
2094            ("audio_url", "audio_url", "https://x.example/audio.wav"),
2095        ] {
2096            let part = parse_content_part(serde_json::json!({
2097                "type": part_type,
2098                (media_field): {"url": url, "uuid": legacy_uuid}
2099            }));
2100            let json = serde_json::to_value(part).unwrap();
2101
2102            assert_eq!(json[media_field]["url"], url);
2103            assert_eq!(json[media_field]["uuid"], legacy_uuid);
2104            assert!(json.get("uuid").is_none());
2105        }
2106    }
2107
2108    #[test]
2109    fn video_url_null_and_top_level_uuid() {
2110        let part = parse_content_part(serde_json::json!({
2111            "type": "video_url",
2112            "video_url": null,
2113            "uuid": "video-cache-key"
2114        }));
2115
2116        match part {
2117            ChatCompletionRequestUserMessageContentPart::VideoUrl(part) => {
2118                assert!(part.video_url.is_none());
2119                assert_eq!(part.uuid.as_deref(), Some("video-cache-key"));
2120            }
2121            _ => panic!("expected video_url part"),
2122        }
2123    }
2124
2125    #[test]
2126    fn audio_url_null_and_top_level_uuid() {
2127        let part = parse_content_part(serde_json::json!({
2128            "type": "audio_url",
2129            "audio_url": null,
2130            "uuid": "audio-cache-key"
2131        }));
2132
2133        match part {
2134            ChatCompletionRequestUserMessageContentPart::AudioUrl(part) => {
2135                assert!(part.audio_url.is_none());
2136                assert_eq!(part.uuid.as_deref(), Some("audio-cache-key"));
2137            }
2138            _ => panic!("expected audio_url part"),
2139        }
2140    }
2141
2142    #[test]
2143    fn message_content_array_preserves_uuid_alignment() {
2144        let payload = serde_json::json!({
2145            "role": "user",
2146            "content": [
2147                {"type": "text", "text": "describe these"},
2148                {
2149                    "type": "image_url",
2150                    "image_url": {"url": "https://x.example/img1.png"},
2151                    "uuid": "image-1"
2152                },
2153                {"type": "image_url", "image_url": null, "uuid": "image-1"}
2154            ]
2155        });
2156        let message: ChatCompletionRequestUserMessage = serde_json::from_value(payload).unwrap();
2157        let ChatCompletionRequestUserMessageContent::Array(parts) = message.content else {
2158            panic!("expected content array");
2159        };
2160
2161        assert_eq!(parts.len(), 3);
2162        match &parts[1] {
2163            ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => {
2164                assert!(
2165                    part.image_url
2166                        .as_ref()
2167                        .map(|image| image.url.as_str())
2168                        .is_some()
2169                );
2170                assert_eq!(part.uuid.as_deref(), Some("image-1"));
2171            }
2172            _ => panic!("parts[1] should be image_url"),
2173        }
2174        match &parts[2] {
2175            ChatCompletionRequestUserMessageContentPart::ImageUrl(part) => {
2176                assert!(part.image_url.is_none());
2177                assert_eq!(part.uuid.as_deref(), Some("image-1"));
2178            }
2179            _ => panic!("parts[2] should be image_url"),
2180        }
2181    }
2182
2183    #[test]
2184    fn tool_message_accepts_media_content() {
2185        let message: ChatCompletionRequestMessage = serde_json::from_value(serde_json::json!({
2186            "role": "tool",
2187            "tool_call_id": "call_media",
2188            "content": [
2189                {"type": "text", "text": "Screenshot captured"},
2190                {
2191                    "type": "image_url",
2192                    "image_url": {
2193                        "url": "data:image/png;base64,aGVsbG8="
2194                    }
2195                },
2196                {
2197                    "type": "video_url",
2198                    "video_url": {
2199                        "url": "https://example.com/clip.mp4"
2200                    }
2201                },
2202                {
2203                    "type": "audio_url",
2204                    "audio_url": {
2205                        "url": "https://example.com/audio.wav"
2206                    }
2207                }
2208            ]
2209        }))
2210        .unwrap();
2211
2212        let ChatCompletionRequestMessage::Tool(tool) = message else {
2213            panic!("expected tool message");
2214        };
2215        let ChatCompletionRequestToolMessageContent::Array(parts) = tool.content else {
2216            panic!("expected array content");
2217        };
2218        assert!(matches!(
2219            parts[1],
2220            ChatCompletionRequestToolMessageContentPart::ImageUrl(_)
2221        ));
2222        assert!(matches!(
2223            parts[2],
2224            ChatCompletionRequestToolMessageContentPart::VideoUrl(_)
2225        ));
2226        assert!(matches!(
2227            parts[3],
2228            ChatCompletionRequestToolMessageContentPart::AudioUrl(_)
2229        ));
2230    }
2231
2232    #[test]
2233    fn chat_logprob_serializes_token_id_when_present() {
2234        let logprob = ChatCompletionTokenLogprob {
2235            token: " hello".into(),
2236            logprob: -0.12,
2237            token_id: Some(123),
2238            bytes: Some(vec![32, 104, 101, 108, 108, 111]),
2239            top_logprobs: vec![],
2240        };
2241
2242        let json = serde_json::to_value(logprob).unwrap();
2243
2244        assert_eq!(json["token_id"], 123);
2245    }
2246
2247    #[test]
2248    fn chat_logprob_deserializes_optional_fields() {
2249        let choice_logprobs: ChatChoiceLogprobs = serde_json::from_value(serde_json::json!({
2250            "content": [{
2251                "token": " hello",
2252                "logprob": -0.12,
2253                "top_logprobs": []
2254            }]
2255        }))
2256        .unwrap();
2257        let token_logprob: ChatCompletionTokenLogprob = serde_json::from_value(serde_json::json!({
2258            "token": " hello",
2259            "logprob": -0.12,
2260            "token_id": 123,
2261            "bytes": [32, 104, 101, 108, 108, 111],
2262            "top_logprobs": []
2263        }))
2264        .unwrap();
2265
2266        assert_eq!(choice_logprobs.content.as_ref().unwrap()[0].token_id, None);
2267        assert!(choice_logprobs.refusal.is_none());
2268        assert_eq!(token_logprob.token_id, Some(123));
2269        assert_eq!(token_logprob.bytes, Some(vec![32, 104, 101, 108, 108, 111]));
2270    }
2271
2272    #[test]
2273    fn chat_logprob_preserves_nullable_fields() {
2274        let choice_logprobs = ChatChoiceLogprobs {
2275            content: None,
2276            refusal: None,
2277        };
2278        let token_logprob = ChatCompletionTokenLogprob {
2279            token: " hello".into(),
2280            logprob: -0.12,
2281            token_id: None,
2282            bytes: None,
2283            top_logprobs: vec![],
2284        };
2285
2286        let choice_json = serde_json::to_value(choice_logprobs).unwrap();
2287        let token_json = serde_json::to_value(token_logprob).unwrap();
2288
2289        assert_eq!(choice_json["content"], serde_json::Value::Null);
2290        assert_eq!(choice_json["refusal"], serde_json::Value::Null);
2291        assert!(token_json.get("token_id").is_none());
2292        assert_eq!(token_json["bytes"], serde_json::Value::Null);
2293    }
2294
2295    #[test]
2296    #[allow(deprecated)]
2297    fn chat_response_omits_absent_optional_fields() {
2298        let response = CreateChatCompletionResponse {
2299            id: "chatcmpl_dummy".into(),
2300            choices: vec![ChatChoice {
2301                index: 0,
2302                message: ChatCompletionResponseMessage {
2303                    content: Some(ChatCompletionMessageContent::Text("hello".into())),
2304                    refusal: None,
2305                    tool_calls: None,
2306                    role: Role::Assistant,
2307                    function_call: None,
2308                    audio: None,
2309                    reasoning_content: None,
2310                },
2311                finish_reason: Some(FinishReason::Stop),
2312                logprobs: None,
2313            }],
2314            created: 0,
2315            model: "dummy-model".into(),
2316            service_tier: None,
2317            system_fingerprint: None,
2318            object: "chat.completion".into(),
2319            usage: None,
2320        };
2321
2322        let json = serde_json::to_value(response).unwrap();
2323
2324        for absent in ["usage", "service_tier", "system_fingerprint"] {
2325            assert!(json.get(absent).is_none(), "{absent} should be omitted");
2326        }
2327        let choice = &json["choices"][0];
2328        assert_eq!(choice["finish_reason"], "stop");
2329        assert_eq!(choice["logprobs"], serde_json::Value::Null);
2330        let message = &choice["message"];
2331        assert_eq!(message["refusal"], serde_json::Value::Null);
2332        for absent in ["tool_calls", "function_call", "audio", "reasoning_content"] {
2333            assert!(
2334                message.get(absent).is_none(),
2335                "message.{absent} should be omitted"
2336            );
2337        }
2338    }
2339
2340    #[test]
2341    fn stream_response_omits_absent_optional_fields() {
2342        let chunk = CreateChatCompletionStreamResponse {
2343            id: "chatcmpl_dummy".into(),
2344            choices: vec![ChatChoiceStream {
2345                index: 0,
2346                delta: ChatCompletionStreamResponseDelta {
2347                    content: Some(ChatCompletionMessageContent::Text("hello".into())),
2348                    function_call: None,
2349                    tool_calls: None,
2350                    role: None,
2351                    refusal: None,
2352                    reasoning_content: None,
2353                },
2354                finish_reason: None,
2355                logprobs: None,
2356            }],
2357            created: 0,
2358            model: "dummy-model".into(),
2359            service_tier: None,
2360            system_fingerprint: None,
2361            object: "chat.completion.chunk".into(),
2362            usage: None,
2363        };
2364
2365        let json = serde_json::to_value(chunk).unwrap();
2366
2367        for absent in ["usage", "service_tier", "system_fingerprint"] {
2368            assert!(json.get(absent).is_none(), "{absent} should be omitted");
2369        }
2370    }
2371
2372    #[test]
2373    fn stream_tool_call_continuation_chunk_omits_absent_fields() {
2374        let chunk = ChatCompletionMessageToolCallChunk {
2375            custom: None,
2376            index: 0,
2377            id: None,
2378            r#type: None,
2379            function: Some(FunctionCallStream {
2380                name: None,
2381                arguments: Some("{\"a\":".into()),
2382            }),
2383        };
2384
2385        let json = serde_json::to_value(chunk).unwrap();
2386
2387        assert!(json.get("id").is_none());
2388        assert!(json.get("type").is_none());
2389        assert!(json["function"].get("name").is_none());
2390        assert_eq!(json["function"]["arguments"], "{\"a\":");
2391    }
2392
2393    #[test]
2394    fn stream_delta_function_call_omits_absent_fields() {
2395        let function_call = ChatCompletionStreamResponseDeltaFunctionCall {
2396            name: None,
2397            arguments: Some("{}".into()),
2398        };
2399
2400        let json = serde_json::to_value(function_call).unwrap();
2401
2402        assert!(json.get("name").is_none());
2403        assert_eq!(json["arguments"], "{}");
2404    }
2405
2406    #[test]
2407    fn usage_details_omit_absent_fields() {
2408        let response = CreateChatCompletionResponse {
2409            id: "chatcmpl_dummy".into(),
2410            choices: vec![],
2411            created: 0,
2412            model: "dummy-model".into(),
2413            service_tier: None,
2414            system_fingerprint: None,
2415            object: "chat.completion".into(),
2416            usage: Some(CompletionUsage {
2417                prompt_tokens: 10,
2418                completion_tokens: 25,
2419                total_tokens: 35,
2420                prompt_tokens_details: Some(PromptTokensDetails {
2421                    audio_tokens: None,
2422                    cached_tokens: Some(0),
2423                    ..Default::default()
2424                }),
2425                completion_tokens_details: Some(CompletionTokensDetails {
2426                    reasoning_tokens: Some(5),
2427                    ..Default::default()
2428                }),
2429            }),
2430        };
2431
2432        let json = serde_json::to_value(&response).unwrap();
2433        let usage = &json["usage"];
2434
2435        assert_eq!(usage["total_tokens"], 35);
2436        assert_eq!(usage["prompt_tokens_details"]["cached_tokens"], 0);
2437        assert!(
2438            usage["prompt_tokens_details"].get("audio_tokens").is_none(),
2439            "audio_tokens should be omitted, not null"
2440        );
2441        assert_eq!(usage["completion_tokens_details"]["reasoning_tokens"], 5);
2442        for absent in [
2443            "accepted_prediction_tokens",
2444            "audio_tokens",
2445            "rejected_prediction_tokens",
2446        ] {
2447            assert!(
2448                usage["completion_tokens_details"].get(absent).is_none(),
2449                "{absent} should be omitted"
2450            );
2451        }
2452
2453        let roundtrip: CreateChatCompletionResponse = serde_json::from_value(json).unwrap();
2454        assert_eq!(roundtrip, response);
2455    }
2456
2457    // -- Kimi-style system tools / assistant partial tests --
2458
2459    #[test]
2460    fn effective_tool_set_unions_top_level_and_dynamic_system_tools() {
2461        let request: CreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
2462            "model": "dummy-kimi-model",
2463            "tools": [{
2464                "type": "function",
2465                "function": {"name": "add", "parameters": {"type": "object"}}
2466            }],
2467            "messages": [
2468                {"role": "user", "content": "start"},
2469                {
2470                    "role": "system",
2471                    "tools": [
2472                        {
2473                            "type": "function",
2474                            "function": {"name": "lookup", "parameters": {"type": "object"}}
2475                        },
2476                        {"name": "search", "parameters": {"type": "object"}},
2477                        {"description": "no name, skipped"}
2478                    ]
2479                },
2480                {"role": "user", "content": "continue"}
2481            ]
2482        }))
2483        .unwrap();
2484
2485        assert!(request.has_effective_tools());
2486        assert_eq!(request.dynamic_system_tools().count(), 3);
2487        assert_eq!(
2488            request.effective_tool_names().collect::<Vec<_>>(),
2489            ["add", "lookup", "search"],
2490            "top-level first, then dynamic in message order; wrapped and bare shapes both resolve"
2491        );
2492        for name in ["add", "lookup", "search"] {
2493            assert!(
2494                request.effective_tool_contains(name),
2495                "{name} should be found"
2496            );
2497        }
2498        assert!(!request.effective_tool_contains("missing"));
2499        assert!(
2500            !request.effective_tool_contains("no name, skipped"),
2501            "a description is not a name"
2502        );
2503    }
2504
2505    #[test]
2506    fn effective_tool_set_is_empty_without_any_declaration() {
2507        for payload in [
2508            serde_json::json!({
2509                "model": "m",
2510                "messages": [{"role": "user", "content": "hi"}]
2511            }),
2512            serde_json::json!({
2513                "model": "m",
2514                "tools": [],
2515                "messages": [{"role": "system", "content": "plain system text"}]
2516            }),
2517        ] {
2518            let request: CreateChatCompletionRequest = serde_json::from_value(payload).unwrap();
2519            assert!(!request.has_effective_tools());
2520            assert_eq!(request.effective_tool_names().count(), 0);
2521            assert!(!request.effective_tool_contains("anything"));
2522        }
2523    }
2524
2525    #[test]
2526    fn dynamic_system_tools_alone_count_as_effective_tools() {
2527        let request: CreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
2528            "model": "dummy-kimi-model",
2529            "messages": [
2530                {"role": "system", "tools": [{"name": "lookup"}]},
2531                {"role": "user", "content": "go"}
2532            ]
2533        }))
2534        .unwrap();
2535
2536        assert!(
2537            request.tools.is_none(),
2538            "nothing was folded into top-level tools"
2539        );
2540        assert!(request.has_effective_tools());
2541        assert!(request.effective_tool_contains("lookup"));
2542    }
2543
2544    #[test]
2545    fn dynamic_tool_name_handles_wrapped_bare_and_invalid_shapes() {
2546        assert_eq!(
2547            dynamic_tool_name(&serde_json::json!({"type": "function", "function": {"name": "a"}})),
2548            Some("a")
2549        );
2550        assert_eq!(
2551            dynamic_tool_name(&serde_json::json!({"name": "b"})),
2552            Some("b")
2553        );
2554        assert_eq!(dynamic_tool_name(&serde_json::json!({"name": 7})), None);
2555    }
2556
2557    #[test]
2558    fn system_message_without_content_is_rejected_unless_it_declares_tools() {
2559        // Same leading text as upstream's derived error, so clients and
2560        // tests matching on "missing field `content`" keep working.
2561        for (label, message) in [
2562            ("nothing", serde_json::json!({"role": "system"})),
2563            (
2564                "empty tools",
2565                serde_json::json!({"role": "system", "tools": []}),
2566            ),
2567        ] {
2568            let error =
2569                serde_json::from_value::<ChatCompletionRequestMessage>(message).expect_err(label);
2570            assert!(
2571                error.to_string().starts_with("missing field `content`"),
2572                "{label}: unexpected error {error}"
2573            );
2574        }
2575    }
2576
2577    #[test]
2578    fn system_message_guard_leaves_valid_shapes_alone() {
2579        for (label, message) in [
2580            (
2581                "content only",
2582                serde_json::json!({"role": "system", "content": "hi"}),
2583            ),
2584            (
2585                "content parts",
2586                serde_json::json!({"role": "system", "content": [{"type": "text", "text": "hi"}]}),
2587            ),
2588            (
2589                "tools only",
2590                serde_json::json!({"role": "system", "tools": [{"name": "lookup"}]}),
2591            ),
2592            (
2593                "content and tools (renderer decides)",
2594                serde_json::json!({"role": "system", "content": "hi", "tools": [{"name": "lookup"}]}),
2595            ),
2596        ] {
2597            let parsed: ChatCompletionRequestMessage =
2598                serde_json::from_value(message).unwrap_or_else(|e| panic!("{label}: {e}"));
2599            assert!(
2600                matches!(parsed, ChatCompletionRequestMessage::System(_)),
2601                "{label}"
2602            );
2603        }
2604    }
2605
2606    #[test]
2607    fn message_rejects_tools_and_partial_on_wrong_roles() {
2608        let tools = serde_json::json!([{"name": "lookup"}]);
2609        for (label, message, needle) in [
2610            (
2611                "tools on user",
2612                serde_json::json!({"role": "user", "content": "hi", "tools": tools}),
2613                "`tools` is only accepted on system messages, not on role user",
2614            ),
2615            (
2616                "tools on assistant",
2617                serde_json::json!({"role": "assistant", "content": "hi", "tools": tools}),
2618                "`tools` is only accepted on system messages, not on role assistant",
2619            ),
2620            (
2621                // Upstream type without a `tools` field: accepting would drop them.
2622                "tools on developer",
2623                serde_json::json!({"role": "developer", "content": "hi", "tools": tools}),
2624                "`tools` is only accepted on system messages, not on role developer",
2625            ),
2626            (
2627                "partial on user",
2628                serde_json::json!({"role": "user", "content": "hi", "partial": true}),
2629                "`partial` is only accepted on assistant messages, not on role user",
2630            ),
2631            (
2632                "partial on system",
2633                serde_json::json!({"role": "system", "content": "hi", "partial": false}),
2634                "`partial` is only accepted on assistant messages, not on role system",
2635            ),
2636        ] {
2637            let error = serde_json::from_value::<ChatCompletionRequestMessage>(message)
2638                .expect_err(label)
2639                .to_string();
2640            assert!(error.contains(needle), "{label}: {error}");
2641        }
2642
2643        for message in [
2644            serde_json::json!({"role": "user", "content": "hi", "tools": null}),
2645            serde_json::json!({"role": "user", "content": "hi", "partial": null}),
2646        ] {
2647            serde_json::from_value::<ChatCompletionRequestMessage>(message).unwrap();
2648        }
2649
2650        for message in [
2651            serde_json::json!({"role": "system", "tools": tools}),
2652            serde_json::json!({"role": "assistant", "content": "seed", "partial": true}),
2653            serde_json::json!({"role": "user", "content": "hi", "x_vendor": 1}),
2654        ] {
2655            serde_json::from_value::<ChatCompletionRequestMessage>(message).unwrap();
2656        }
2657    }
2658
2659    #[test]
2660    fn message_rejects_duplicate_top_level_keys() {
2661        for (label, raw) in [
2662            (
2663                "role twice",
2664                r#"{"role":"user","content":"hi","role":"system"}"#,
2665            ),
2666            (
2667                "content twice",
2668                r#"{"role":"user","content":"a","content":"b"}"#,
2669            ),
2670        ] {
2671            let error = serde_json::from_str::<ChatCompletionRequestMessage>(raw)
2672                .expect_err(label)
2673                .to_string();
2674            assert!(error.contains("duplicate field"), "{label}: {error}");
2675        }
2676    }
2677
2678    #[test]
2679    fn message_rejects_duplicate_fields_in_nested_typed_objects() {
2680        let tool_call = r#"{
2681            "role":"assistant",
2682            "content":null,
2683            "tool_calls":[{
2684                "id":"first",
2685                "id":"second",
2686                "type":"function",
2687                "function":{"name":"lookup","arguments":"{}"}
2688            }]
2689        }"#;
2690        let error = serde_json::from_str::<ChatCompletionRequestMessage>(tool_call)
2691            .unwrap_err()
2692            .to_string();
2693        assert!(error.contains("duplicate field `id`"), "{error}");
2694
2695        let content_part = r#"{
2696            "role":"user",
2697            "content":[{"type":"text","text":"first","text":"second"}]
2698        }"#;
2699        assert!(serde_json::from_str::<ChatCompletionRequestMessage>(content_part).is_err());
2700    }
2701
2702    #[test]
2703    fn default_system_message_round_trips() {
2704        let message = ChatCompletionRequestSystemMessage::default();
2705        let json = serde_json::to_value(&message).unwrap();
2706        assert_eq!(json, serde_json::json!({"content": ""}));
2707        let back: ChatCompletionRequestSystemMessage = serde_json::from_value(json).unwrap();
2708        assert_eq!(back, message);
2709
2710        let built = ChatCompletionRequestSystemMessageArgs::default()
2711            .name("ops")
2712            .build()
2713            .unwrap();
2714        let json = serde_json::to_value(&built).unwrap();
2715        assert_eq!(json, serde_json::json!({"content": "", "name": "ops"}));
2716        serde_json::from_value::<ChatCompletionRequestSystemMessage>(json).unwrap();
2717    }
2718
2719    #[test]
2720    fn system_message_guard_keeps_field_level_errors() {
2721        let error = serde_json::from_value::<ChatCompletionRequestMessage>(serde_json::json!({
2722            "role": "system",
2723            "tools": "lookup"
2724        }))
2725        .unwrap_err();
2726        assert!(
2727            !error.to_string().starts_with("missing field `content`"),
2728            "field error expected, got {error}"
2729        );
2730    }
2731
2732    #[test]
2733    fn system_message_canonicalizes_missing_content_with_tools() {
2734        let request: CreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
2735            "model": "dummy-kimi-model",
2736            "messages": [
2737                {
2738                    "role": "system",
2739                    "tools": [
2740                        {
2741                            "name": "lookup",
2742                            "description": "dummy lookup tool",
2743                            "parameters": {
2744                                "type": "object",
2745                                "properties": {
2746                                    "query": { "type": "string" }
2747                                }
2748                            }
2749                        }
2750                    ]
2751                },
2752                {
2753                    "role": "assistant",
2754                    "content": "synthetic prefill",
2755                    "partial": true
2756                },
2757                {
2758                    "role": "user",
2759                    "content": "continue"
2760                }
2761            ]
2762        }))
2763        .unwrap();
2764
2765        match &request.messages[0] {
2766            ChatCompletionRequestMessage::System(system) => {
2767                assert_eq!(
2768                    system.content,
2769                    ChatCompletionRequestSystemMessageContent::Text(String::new())
2770                );
2771                let tools = system.tools.as_ref().expect("tools should be present");
2772                assert_eq!(tools.len(), 1);
2773                assert_eq!(tools[0]["name"], "lookup");
2774            }
2775            other => panic!("expected system message, got {other:?}"),
2776        }
2777
2778        match &request.messages[1] {
2779            ChatCompletionRequestMessage::Assistant(assistant) => {
2780                assert_eq!(assistant.partial, Some(true));
2781            }
2782            other => panic!("expected assistant message, got {other:?}"),
2783        }
2784
2785        // Explicit null has the same wire meaning as omission. Both serialize
2786        // to the canonical required-content shape.
2787        let message: ChatCompletionRequestMessage = serde_json::from_value(serde_json::json!({
2788            "role": "system",
2789            "content": null,
2790            "tools": [{"name": "lookup"}]
2791        }))
2792        .unwrap();
2793        let ChatCompletionRequestMessage::System(system) = &message else {
2794            panic!("expected system message");
2795        };
2796        assert_eq!(
2797            system.content,
2798            ChatCompletionRequestSystemMessageContent::Text(String::new())
2799        );
2800        assert_eq!(
2801            serde_json::to_value(message).unwrap(),
2802            serde_json::json!({
2803                "role": "system",
2804                "content": "",
2805                "tools": [{"name": "lookup"}]
2806            })
2807        );
2808    }
2809
2810    #[test]
2811    fn kimi_style_request_preserves_tools_and_canonicalizes_content() {
2812        let payload = serde_json::json!({
2813            "model": "dummy-kimi-model",
2814            "messages": [
2815                {
2816                    "role": "system",
2817                    "tools": [
2818                        {
2819                            "name": "lookup",
2820                            "description": "dummy lookup tool",
2821                            "parameters": {
2822                                "type": "object",
2823                                "properties": {
2824                                    "query": { "type": "string" }
2825                                }
2826                            },
2827                            "vendor_hint": { "priority": 3 }
2828                        }
2829                    ]
2830                },
2831                {
2832                    "role": "assistant",
2833                    "content": "synthetic prefill",
2834                    "partial": true
2835                },
2836                {
2837                    "role": "user",
2838                    "content": "continue"
2839                }
2840            ]
2841        });
2842
2843        let request: CreateChatCompletionRequest = serde_json::from_value(payload.clone()).unwrap();
2844        let serialized = serde_json::to_value(request).unwrap();
2845        let mut canonical = payload;
2846        canonical["messages"][0]["content"] = serde_json::json!("");
2847
2848        assert_eq!(serialized, canonical);
2849    }
2850
2851    #[test]
2852    fn system_message_tools_preserve_official_wrapped_shape() {
2853        let payload = serde_json::json!({
2854            "model": "dummy-kimi-model",
2855            "messages": [
2856                {
2857                    "role": "system",
2858                    "tools": [
2859                        {
2860                            "type": "function",
2861                            "function": {
2862                                "name": "lookup",
2863                                "description": "dummy lookup tool",
2864                                "parameters": {
2865                                    "type": "object",
2866                                    "properties": {
2867                                        "query": { "type": "string" }
2868                                    },
2869                                    "required": ["query"]
2870                                },
2871                                "strict": true
2872                            }
2873                        }
2874                    ]
2875                },
2876                { "role": "user", "content": "continue" }
2877            ]
2878        });
2879
2880        let request: CreateChatCompletionRequest = serde_json::from_value(payload.clone()).unwrap();
2881        match &request.messages[0] {
2882            ChatCompletionRequestMessage::System(system) => {
2883                let tools = system.tools.as_ref().expect("tools should be present");
2884                assert_eq!(tools[0]["type"], "function");
2885                assert_eq!(tools[0]["function"]["name"], "lookup");
2886            }
2887            other => panic!("expected system message, got {other:?}"),
2888        }
2889
2890        let mut canonical = payload;
2891        canonical["messages"][0]["content"] = serde_json::json!("");
2892        assert_eq!(serde_json::to_value(request).unwrap(), canonical);
2893    }
2894
2895    #[test]
2896    fn assistant_message_omits_partial_when_absent() {
2897        let assistant = ChatCompletionRequestAssistantMessageArgs::default()
2898            .content("hello")
2899            .build()
2900            .unwrap();
2901
2902        assert_eq!(assistant.partial, None);
2903        let json = serde_json::to_value(&assistant).unwrap();
2904        assert!(
2905            json.get("partial").is_none(),
2906            "partial should be omitted when absent"
2907        );
2908    }
2909
2910    #[test]
2911    fn assistant_message_serializes_partial_when_present() {
2912        let assistant = ChatCompletionRequestAssistantMessageArgs::default()
2913            .content("synthetic prefill")
2914            .partial(true)
2915            .build()
2916            .unwrap();
2917
2918        let json = serde_json::to_value(&assistant).unwrap();
2919        assert_eq!(json["partial"], true);
2920
2921        let roundtrip: ChatCompletionRequestAssistantMessage =
2922            serde_json::from_value(json).unwrap();
2923        assert_eq!(roundtrip, assistant);
2924    }
2925
2926    #[test]
2927    fn system_message_from_upstream_preserves_content_and_leaves_tools_none() {
2928        let upstream = async_openai::types::chat::ChatCompletionRequestSystemMessage {
2929            content: async_openai::types::chat::ChatCompletionRequestSystemMessageContent::Text(
2930                "hi".into(),
2931            ),
2932            name: None,
2933        };
2934
2935        let owned: ChatCompletionRequestSystemMessage = upstream.into();
2936        assert!(owned.tools.is_none());
2937        match owned.content {
2938            ChatCompletionRequestSystemMessageContent::Text(text) => assert_eq!(text, "hi"),
2939            other => panic!("expected text content, got {other:?}"),
2940        }
2941    }
2942
2943    #[test]
2944    fn system_message_restores_upstream_convenience_conversions() {
2945        let from_content = ChatCompletionRequestSystemMessage::from(
2946            ChatCompletionRequestSystemMessageContent::Text("from content".into()),
2947        );
2948        let from_str = ChatCompletionRequestSystemMessage::from("from str");
2949        let from_string = ChatCompletionRequestSystemMessage::from(String::from("from string"));
2950
2951        for (message, expected) in [
2952            (from_content, "from content"),
2953            (from_str, "from str"),
2954            (from_string, "from string"),
2955        ] {
2956            assert_eq!(
2957                message.content,
2958                ChatCompletionRequestSystemMessageContent::Text(expected.into())
2959            );
2960            assert!(message.name.is_none());
2961            assert!(message.tools.is_none());
2962        }
2963    }
2964}