Skip to main content

dynamo_protocols/types/
chat.rs

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