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