Skip to main content

dynamo_protocols/types/responses/
mod.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Dynamo owns the Responses-API input-side type chain. Upstream async-openai
5// is the source for everything else (output-side types, streaming events,
6// individual tool-call payloads, etc.).
7//
8// The input chain is owned because upstream marks fields as required that
9// real-world clients (OpenAI Agents SDK, Codex, etc.) routinely omit when
10// round-tripping a prior assistant turn as input:
11//   - `OutputMessage.id` / `.status` — omitted when echoing a previous output
12//   - `OutputTextContent.annotations` — omitted when the part carried none
13//   - `ReasoningItem.id` — omitted by Codex/OpenCode/agent SDKs on echo
14// Upstream is slow to relax these (the sibling `ReasoningItem.id` fix landed in
15// 64bit/async-openai#535, but after our pinned async-openai, so we mirror it
16// locally as `InputReasoningItem`); OpenAI's own hosted API accepts the relaxed
17// shapes on input regardless.
18//
19// This mirrors the pattern in `crate::types::chat` where Dynamo owns the
20// request types it needs to extend or relax while re-exporting the rest of
21// upstream's type library verbatim.
22//
23// Naming: the relaxed assistant-input message is `InputOutputMessage` (and
24// `InputOutputMessageContent` / `InputOutputTextContent` for its content
25// parts) to avoid colliding with upstream's `OutputMessage`, which remains the
26// canonical type for *output-side* response construction (`OutputItem`,
27// `Response.output`). `MessageItem`, `Item`, `InputItem`, `InputParam`, and
28// `CreateResponse` are input-only and shadow upstream's same-named types
29// without conflict.
30
31use std::collections::HashMap;
32
33use serde::{Deserialize, Serialize, de};
34
35// Re-export all upstream response types (shared structures like ResponseUsage,
36// tool-call item types, streaming events, etc.). The types we own below
37// shadow their upstream counterparts where no dual-side conflict exists.
38pub use async_openai::types::responses::*;
39
40/// Request tool choice extends the pinned SDK with explicit client search selection.
41/// Other variants retain the upstream representation.
42/// Owning the request type preserves fields the pinned SDK cannot round-trip.
43#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
44#[serde(tag = "type", rename_all = "snake_case")]
45pub enum RequestToolChoiceParam {
46    ToolSearch,
47    AllowedTools(ToolChoiceAllowed),
48    Function(ToolChoiceFunction),
49    Mcp(ToolChoiceMCP),
50    Custom(ToolChoiceCustom),
51    ProgrammaticToolCalling,
52    ApplyPatch,
53    Shell,
54    #[serde(untagged)]
55    BuiltIn(ToolChoiceTypes),
56    #[serde(untagged)]
57    Option(ToolChoiceOptions),
58}
59
60impl RequestToolChoiceParam {
61    /// SDK response structs cannot represent search selection. Dynamo's public
62    /// serializers echo the original choice; this value is only their typed base.
63    pub fn sdk_response_choice(&self) -> async_openai::types::responses::ToolChoiceParam {
64        match self {
65            Self::ToolSearch => {
66                async_openai::types::responses::ToolChoiceParam::Option(ToolChoiceOptions::Required)
67            }
68            _ => {
69                serde_json::from_value(serde_json::to_value(self).expect("tool choice serializes"))
70                    .expect("upstream tool choice shape")
71            }
72        }
73    }
74}
75
76mod template_tools;
77pub use template_tools::RequestTool;
78
79// Re-export from parent module for backward compat.
80pub use crate::types::ImageDetail;
81pub use crate::types::ReasoningEffort;
82pub use crate::types::ResponseFormatJsonSchema;
83
84// Backward-compatible type aliases for Dynamo consumer code migration.
85pub type Input = InputParam;
86pub type PromptConfig = Prompt;
87pub type TextConfig = ResponseTextParam;
88pub type TextResponseFormat = TextResponseFormatConfiguration;
89
90/// Stream of response events.
91pub type ResponseStream = std::pin::Pin<
92    Box<dyn futures::Stream<Item = Result<ResponseStreamEvent, crate::error::OpenAIError>> + Send>,
93>;
94
95/// Fields on upstream `Response` that the OpenResponses spec requires as
96/// `T | null` but async-openai declares as `Option<T>` with
97/// `skip_serializing_if = Option::is_none` — meaning `None` disappears from
98/// the wire shape, where the spec wants an explicit `null`.
99///
100/// Colocated here (next to the upstream `Response` re-export) rather than in
101/// `lib/llm/src/protocols/openai/responses/mod.rs` so that when upstream's
102/// `Response` gains a new nullable-required field, the reviewer editing this
103/// module is looking directly at the authoritative list. Keep sorted
104/// alphabetically; entries must match serde field names on `Response` exactly.
105///
106/// Any field we unconditionally populate ourselves during response
107/// construction (e.g. `metadata`, `parallel_tool_calls`, `temperature`,
108/// `text`, `tool_choice`, `tools`, `top_p`, `top_logprobs`, `truncation`,
109/// `service_tier`, `background`) is deliberately absent — it's always
110/// present on the wire, so listing it here would be noise.
111pub const SPEC_NULLABLE_REQUIRED_RESPONSE_FIELDS: &[&str] = &[
112    "billing",
113    "completed_at",
114    "conversation",
115    "error",
116    "incomplete_details",
117    "instructions",
118    "max_output_tokens",
119    "max_tool_calls",
120    "previous_response_id",
121    "prompt",
122    "prompt_cache_key",
123    "prompt_cache_retention",
124    "reasoning",
125    "safety_identifier",
126    "usage",
127];
128
129// ---------------------------------------------------------------------------
130// Input-side assistant message (relaxed vs upstream OutputMessage)
131// ---------------------------------------------------------------------------
132
133/// Deserialize `null` or a missing field as the default empty `Vec`. Plain
134/// `#[serde(default)]` only fires when the field is absent; explicit `null`
135/// would otherwise fail `Vec::deserialize`. Clients (notably some Agents SDK
136/// variants) have been observed to send `"annotations": null`, so treat
137/// omission and explicit null the same.
138fn deserialize_null_as_empty_vec<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
139where
140    T: Deserialize<'de>,
141    D: serde::Deserializer<'de>,
142{
143    Option::<Vec<T>>::deserialize(deserializer).map(Option::unwrap_or_default)
144}
145
146/// Deserialize `null` or a missing field as `T::default()`. Scalar counterpart
147/// to `deserialize_null_as_empty_vec` — plain `#[serde(default)]` rejects
148/// explicit `null` because serde tries to deserialize the null into `T` and
149/// fails. Real clients emit `null` for unset enum-ish fields (e.g. OpenAI
150/// Agents SDK sending `"detail": null` on `input_image` parts).
151fn deserialize_null_as_default<'de, T, D>(deserializer: D) -> Result<T, D::Error>
152where
153    T: Deserialize<'de> + Default,
154    D: serde::Deserializer<'de>,
155{
156    Option::<T>::deserialize(deserializer).map(Option::unwrap_or_default)
157}
158
159/// Deserialize `tool_choice`, coercing the object form `{"type": "auto" |
160/// "none" | "required", ...}` into the upstream `Option` variant.
161///
162/// Upstream `ToolChoiceParam` only accepts `auto`/`none`/`required` as a bare
163/// string; the object form is reserved for naming a *specific* tool
164/// (`{"type": "function", "name": ...}`). But Anthropic-style clients (and
165/// litellm forwarding them verbatim) express the mode as an object, e.g.
166/// `{"type": "auto", "disable_parallel_tool_use": true}`. OpenAI's hosted API
167/// treats `{"type": "auto"}` and the bare `"auto"` identically; we do the same.
168/// Extra keys (e.g. `disable_parallel_tool_use`) are accepted and ignored —
169/// there is no per-call parallel-tool-use toggle to honor.
170///
171/// Any value that is not a mode-typed object falls through to standard
172/// `RequestToolChoiceParam` deserialization, so bare strings and specific-tool /
173/// hosted-tool objects keep working unchanged.
174fn deserialize_tool_choice<'de, D>(
175    deserializer: D,
176) -> Result<Option<RequestToolChoiceParam>, D::Error>
177where
178    D: serde::Deserializer<'de>,
179{
180    let Some(value) = Option::<serde_json::Value>::deserialize(deserializer)? else {
181        return Ok(None);
182    };
183    if let Some(serde_json::Value::String(t)) = value.get("type") {
184        let mode = match t.as_str() {
185            "auto" => Some(ToolChoiceOptions::Auto),
186            "none" => Some(ToolChoiceOptions::None),
187            "required" => Some(ToolChoiceOptions::Required),
188            _ => None,
189        };
190        if let Some(mode) = mode {
191            return Ok(Some(RequestToolChoiceParam::Option(mode)));
192        }
193    }
194    RequestToolChoiceParam::deserialize(value)
195        .map(Some)
196        .map_err(serde::de::Error::custom)
197}
198
199/// Relaxed counterpart to upstream `OutputTextContent` for input-side content.
200/// `annotations` tolerates both missing and explicit `null`; upstream requires
201/// it to be a present non-null array.
202#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
203pub struct InputOutputTextContent {
204    #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
205    pub annotations: Vec<Annotation>,
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub logprobs: Option<Vec<LogProb>>,
208    pub text: String,
209}
210
211/// Content parts of a prior assistant message presented as input.
212#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
213#[serde(tag = "type", rename_all = "snake_case")]
214pub enum InputOutputMessageContent {
215    OutputText(InputOutputTextContent),
216    Refusal(RefusalContent),
217}
218
219/// An assistant message echoed back as input for a subsequent turn. Relaxed
220/// compared to upstream `OutputMessage`: `id`, `status`, and `content` are all
221/// optional. Some clients send a bare assistant shell (`{"type":"message",
222/// "role":"assistant"}`) with no `content` at all, usually on pure tool-call
223/// turns; treat absent `content` as an empty vec, same way we treat a missing
224/// `id`/`status`.
225#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
226pub struct InputOutputMessage {
227    #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
228    pub content: Vec<InputOutputMessageContent>,
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub id: Option<String>,
231    pub role: AssistantRole,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub phase: Option<MessagePhase>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub status: Option<OutputStatus>,
236}
237
238// Re-export upstream's pre-shadow `InputContent` under an explicit alias. Kept
239// for downstream compatibility: since `FunctionCallOutput` is crate-owned, no
240// type in this module carries upstream's `InputContent` any more, so in-crate
241// code should use the Dynamo `InputContent` shadow defined below.
242pub use async_openai::types::responses::InputContent as UpstreamInputContent;
243
244// ---------------------------------------------------------------------------
245// Input-side image / content / message (shadow upstream, relaxed shapes)
246// ---------------------------------------------------------------------------
247
248/// Relaxed counterpart to upstream `InputImageContent`. `detail` defaults to
249/// `ImageDetail::Auto` when the client omits it — OpenAI's hosted API and the
250/// OpenResponses spec both accept this shape, but upstream's struct marks
251/// `detail` as required.
252#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
253pub struct InputImageContent {
254    #[serde(default, deserialize_with = "deserialize_null_as_default")]
255    pub detail: ImageDetail,
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub file_id: Option<String>,
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub image_url: Option<String>,
260}
261
262/// Parts of an input message: text, image, or file. Mirrors upstream
263/// `InputContent` but routes `InputImage` through the Dynamo-owned relaxed
264/// `InputImageContent` above.
265#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
266#[serde(tag = "type", rename_all = "snake_case")]
267pub enum InputContent {
268    InputText(InputTextContent),
269    InputImage(InputImageContent),
270    InputFile(InputFileContent),
271}
272
273/// User / system / developer input message. Shadows upstream `InputMessage`
274/// so we can route through the Dynamo-owned `InputContent` chain.
275#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
276pub struct InputMessage {
277    pub content: Vec<InputContent>,
278    pub role: InputRole,
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub status: Option<OutputStatus>,
281}
282
283/// Content for `EasyInputMessage`. Shadows upstream's same-named enum so the
284/// `ContentList` arm carries Dynamo's relaxed `InputContent` (with optional
285/// `detail` on `InputImageContent`) instead of upstream's strict variant.
286///
287/// Without this shadow, the `InputItem::EasyMessage` fallback in the untagged
288/// `InputItem` enum is the only path that still routes through upstream's
289/// strict types — so any spec-compliant client that omits `type: "message"`
290/// on a multimodal message (the documented default) fails with
291/// "data did not match any variant of untagged enum InputItem". See issue
292/// #9468.
293#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
294#[serde(untagged)]
295pub enum EasyInputContent {
296    /// Plain-text content. Tried first so `"content": "hi"` short-circuits.
297    Text(String),
298    /// Structured content list (text/image/file parts).
299    ContentList(Vec<InputContent>),
300}
301
302impl Default for EasyInputContent {
303    fn default() -> Self {
304        Self::Text(String::new())
305    }
306}
307
308/// Output of a `function_call_output` item. Shadows upstream `FunctionCallOutput`
309/// so the `Content` arm carries the crate's `InputContent` (and so the relaxed
310/// `InputImageContent`), giving tool outputs the same part semantics as message
311/// content. Upstream's arm carries its own `InputContent`, which accepts an
312/// omitted `detail` since async-openai 0.38 but still rejects an explicit
313/// `"detail": null` that message content accepts.
314#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
315#[serde(untagged)]
316pub enum FunctionCallOutput {
317    /// A JSON string of the output of the function tool call.
318    Text(String),
319    /// Text / image / file parts.
320    Content(Vec<InputContent>),
321}
322
323// Same conversions upstream's `FunctionCallOutput` provides, so `output: "…".into()`
324// and `output: parts.into()` keep compiling.
325impl From<&str> for FunctionCallOutput {
326    fn from(text: &str) -> Self {
327        FunctionCallOutput::Text(text.to_string())
328    }
329}
330
331impl From<String> for FunctionCallOutput {
332    fn from(text: String) -> Self {
333        FunctionCallOutput::Text(text)
334    }
335}
336
337impl From<Vec<InputContent>> for FunctionCallOutput {
338    fn from(content: Vec<InputContent>) -> Self {
339        FunctionCallOutput::Content(content)
340    }
341}
342
343/// `function_call_output` input item. Shadows upstream so `output` routes through
344/// the crate-owned `FunctionCallOutput`; field set identical to upstream.
345#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
346pub struct FunctionCallOutputItemParam {
347    pub call_id: String,
348    pub output: FunctionCallOutput,
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub id: Option<String>,
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub status: Option<OutputStatus>,
353}
354
355/// A simplified message input — the spec-default shape when a client omits the
356/// `type` discriminator. Shadows upstream `EasyInputMessage` so the `content`
357/// field routes through Dynamo's relaxed `EasyInputContent` (and transitively
358/// the relaxed `InputContent` / `InputImageContent`). Field set is identical to
359/// upstream for drop-in compatibility with construction sites in lib/llm.
360#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
361pub struct EasyInputMessage {
362    /// Type discriminator. Optional with default `MessageType::Message` —
363    /// matches the OpenAI Responses spec and `openai-python`'s
364    /// `EasyInputMessageParam` (`type: Literal["message"]`, non-Required).
365    #[serde(default)]
366    pub r#type: MessageType,
367    pub role: Role,
368    pub content: EasyInputContent,
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub phase: Option<MessagePhase>,
371}
372
373// ---------------------------------------------------------------------------
374// Input-side Item / Message / InputItem / InputParam (shadow upstream)
375// ---------------------------------------------------------------------------
376
377/// Message item within `Item`. Untagged; disambiguated by the `role` field:
378/// the `Output` variant requires `role: "assistant"` (via `AssistantRole`,
379/// which is a single-variant enum) and `Input` requires `role` in
380/// `"user" | "system" | "developer"` (via `InputRole`). A payload with an
381/// unknown role (e.g. `"tool"`) or a missing `role` produces the generic
382/// untagged-enum error — callers are expected to send a valid role. If you
383/// see the "data did not match any variant of untagged enum" failure on this
384/// type, it is almost always a role mismatch.
385#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
386#[serde(untagged)]
387pub enum MessageItem {
388    /// Prior assistant output echoed back (role: assistant). Tried first — its
389    /// `role` constraint excludes user/system/developer inputs.
390    Output(InputOutputMessage),
391    /// User / system / developer input message.
392    Input(InputMessage),
393}
394
395/// A reasoning item echoed back as input for a subsequent turn. Relaxed
396/// compared to upstream `ReasoningItem`: `id` and `summary` are both optional.
397///
398/// Upstream marks `id` (and a present `summary` array) as required, but real
399/// clients omit them when round-tripping a prior reasoning turn as input:
400/// Codex / OpenCode / agent SDKs send `reasoning` items carrying only
401/// `encrypted_content` (and sometimes a `summary`) with no `id`. OpenAI's own
402/// hosted API accepts this; the OpenAPI spec is wrong. Upstream fixed `id` in
403/// `64bit/async-openai#535` (merged after our pinned async-openai), so we
404/// mirror that one-line relaxation here rather than chase a crate bump.
405///
406/// Named `InputReasoningItem` (not `ReasoningItem`) because upstream's
407/// `ReasoningItem` is dual-side: it is the canonical output-side type in
408/// `OutputItem::Reasoning(..)` / `Response.output`, which must stay strict.
409/// Same naming discipline as `InputOutputMessage` vs `OutputMessage`.
410#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
411pub struct InputReasoningItem {
412    /// Optional on input — upstream requires it; clients drop it on echo.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub id: Option<String>,
415    /// Defaults to empty when absent or null — upstream requires a present array.
416    #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
417    pub summary: Vec<SummaryPart>,
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub content: Option<Vec<ReasoningTextContent>>,
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub encrypted_content: Option<String>,
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub status: Option<OutputStatus>,
424}
425
426/// Private Codex wire shape, normalized to an existing user message.
427#[derive(Deserialize)]
428struct CodexAgentMessage {
429    #[serde(default)]
430    content: Option<CodexAgentMessageContent>,
431}
432
433#[derive(Deserialize)]
434#[serde(untagged)]
435enum CodexAgentMessageContent {
436    Text(String),
437    Parts(Vec<CodexAgentMessageInputContent>),
438}
439
440#[derive(Deserialize)]
441#[serde(tag = "type", rename_all = "snake_case")]
442enum CodexAgentMessageInputContent {
443    InputText(InputTextContent),
444    EncryptedContent { encrypted_content: String },
445}
446
447/// Client search results retain the same namespace and deferral metadata as request tools.
448#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
449pub struct ToolSearchOutputItemParam {
450    #[serde(skip_serializing_if = "Option::is_none")]
451    pub id: Option<String>,
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub call_id: Option<String>,
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub execution: Option<ToolSearchExecutionType>,
456    // Loaded tools must retain the same namespace/deferred metadata as initial tools.
457    pub tools: Vec<RequestTool>,
458    #[serde(skip_serializing_if = "Option::is_none")]
459    pub status: Option<OutputStatus>,
460}
461
462/// Structured input/output item; request-only wrappers retain relaxed replay fields.
463#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
464#[serde(tag = "type", rename_all = "snake_case")]
465pub enum Item {
466    Message(MessageItem),
467    FileSearchCall(FileSearchToolCall),
468    ComputerCall(ComputerToolCall),
469    ComputerCallOutput(ComputerCallOutputItemParam),
470    WebSearchCall(WebSearchToolCall),
471    FunctionCall(FunctionToolCall),
472    FunctionCallOutput(FunctionCallOutputItemParam),
473    ToolSearchCall(ToolSearchCallItemParam),
474    ToolSearchOutput(ToolSearchOutputItemParam),
475    Reasoning(InputReasoningItem),
476    Compaction(CompactionSummaryItemParam),
477    ImageGenerationCall(ImageGenToolCall),
478    CodeInterpreterCall(CodeInterpreterToolCall),
479    LocalShellCall(LocalShellToolCall),
480    LocalShellCallOutput(LocalShellToolCallOutput),
481    ShellCall(FunctionShellCallItemParam),
482    ShellCallOutput(FunctionShellCallOutputItemParam),
483    ApplyPatchCall(ApplyPatchToolCallItemParam),
484    ApplyPatchCallOutput(ApplyPatchToolCallOutputItemParam),
485    McpListTools(MCPListTools),
486    McpApprovalRequest(MCPApprovalRequest),
487    McpApprovalResponse(MCPApprovalResponse),
488    McpCall(MCPToolCall),
489    CustomToolCallOutput(CustomToolCallOutput),
490    CustomToolCall(CustomToolCall),
491}
492
493/// Single input item. Untagged; order matters (most specific first).
494#[derive(Debug, Serialize, Clone, PartialEq)]
495#[serde(untagged)]
496pub enum InputItem {
497    ItemReference(ItemReference),
498    Item(Item),
499    EasyMessage(EasyInputMessage),
500}
501
502#[derive(Deserialize)]
503#[serde(untagged)]
504enum InputItemWire {
505    ItemReference(ItemReference),
506    Item(Item),
507    EasyMessage(EasyInputMessage),
508}
509
510impl<'de> Deserialize<'de> for InputItem {
511    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
512    where
513        D: serde::Deserializer<'de>,
514    {
515        let value = serde_json::Value::deserialize(deserializer)?;
516        if value.get("type").and_then(serde_json::Value::as_str) == Some("agent_message") {
517            let message = CodexAgentMessage::deserialize(value).map_err(de::Error::custom)?;
518            return Ok(normalize_codex_agent_message(message));
519        }
520
521        match InputItemWire::deserialize(value).map_err(de::Error::custom)? {
522            InputItemWire::ItemReference(item) => Ok(Self::ItemReference(item)),
523            InputItemWire::Item(item) => Ok(Self::Item(item)),
524            InputItemWire::EasyMessage(message) => Ok(Self::EasyMessage(message)),
525        }
526    }
527}
528
529fn normalize_codex_agent_message(message: CodexAgentMessage) -> InputItem {
530    let content = match message.content {
531        None => String::new(),
532        Some(CodexAgentMessageContent::Text(text)) => text,
533        Some(CodexAgentMessageContent::Parts(parts)) => parts
534            .into_iter()
535            .map(|part| match part {
536                CodexAgentMessageInputContent::InputText(part) => part.text,
537                CodexAgentMessageInputContent::EncryptedContent { encrypted_content } => {
538                    encrypted_content
539                }
540            })
541            .collect::<Vec<_>>()
542            .join("\n"),
543    };
544    InputItem::EasyMessage(EasyInputMessage {
545        r#type: MessageType::Message,
546        role: Role::User,
547        content: EasyInputContent::Text(content),
548        phase: None,
549    })
550}
551
552/// Input to a `POST /v1/responses` request.
553#[derive(Debug, Serialize, Clone, PartialEq)]
554#[serde(untagged)]
555pub enum InputParam {
556    Text(String),
557    Items(Vec<InputItem>),
558}
559
560impl<'de> Deserialize<'de> for InputParam {
561    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
562    where
563        D: serde::Deserializer<'de>,
564    {
565        match serde_json::Value::deserialize(deserializer)? {
566            serde_json::Value::String(text) => Ok(Self::Text(text)),
567            serde_json::Value::Array(items) => {
568                serde_json::from_value(serde_json::Value::Array(items))
569                    .map(Self::Items)
570                    .map_err(de::Error::custom)
571            }
572            _ => Err(de::Error::custom(
573                "input must be a string or an array of input items",
574            )),
575        }
576    }
577}
578
579impl Default for InputParam {
580    fn default() -> Self {
581        Self::Text(String::new())
582    }
583}
584
585// ---------------------------------------------------------------------------
586// CreateResponse (owned, uses Dynamo-owned InputParam)
587// ---------------------------------------------------------------------------
588
589/// Request body for `POST /v1/responses`. Mirrors upstream `CreateResponse`
590/// field-for-field but uses Dynamo-owned `InputParam`, which transitively
591/// accepts the relaxed input shapes described in this module's header. All
592/// other fields reference upstream types verbatim.
593#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
594pub struct CreateResponse {
595    #[serde(skip_serializing_if = "Option::is_none")]
596    pub background: Option<bool>,
597    #[serde(skip_serializing_if = "Option::is_none")]
598    pub conversation: Option<ConversationParam>,
599    #[serde(skip_serializing_if = "Option::is_none")]
600    pub include: Option<Vec<IncludeEnum>>,
601    pub input: InputParam,
602    #[serde(skip_serializing_if = "Option::is_none")]
603    pub instructions: Option<String>,
604    /// Output cap. Also accepts the Chat Completions spelling `max_tokens`
605    /// as an alias so a caller's cap is honored instead of silently dropped;
606    /// serialization always emits `max_output_tokens`.
607    #[serde(alias = "max_tokens", skip_serializing_if = "Option::is_none")]
608    pub max_output_tokens: Option<u32>,
609    #[serde(skip_serializing_if = "Option::is_none")]
610    pub max_tool_calls: Option<u32>,
611    #[serde(skip_serializing_if = "Option::is_none")]
612    pub metadata: Option<HashMap<String, String>>,
613    #[serde(skip_serializing_if = "Option::is_none")]
614    pub model: Option<String>,
615    #[serde(skip_serializing_if = "Option::is_none")]
616    pub parallel_tool_calls: Option<bool>,
617    #[serde(skip_serializing_if = "Option::is_none")]
618    pub previous_response_id: Option<String>,
619    #[serde(skip_serializing_if = "Option::is_none")]
620    pub prompt: Option<Prompt>,
621    #[serde(skip_serializing_if = "Option::is_none")]
622    pub prompt_cache_key: Option<String>,
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub prompt_cache_retention: Option<PromptCacheRetention>,
625    #[serde(skip_serializing_if = "Option::is_none")]
626    pub reasoning: Option<Reasoning>,
627    #[serde(skip_serializing_if = "Option::is_none")]
628    pub safety_identifier: Option<String>,
629    #[serde(skip_serializing_if = "Option::is_none")]
630    pub service_tier: Option<ServiceTierResponses>,
631    #[serde(skip_serializing_if = "Option::is_none")]
632    pub store: Option<bool>,
633    #[serde(skip_serializing_if = "Option::is_none")]
634    pub stream: Option<bool>,
635    #[serde(skip_serializing_if = "Option::is_none")]
636    pub stream_options: Option<ResponseStreamOptions>,
637    #[serde(skip_serializing_if = "Option::is_none")]
638    pub temperature: Option<f32>,
639    #[serde(skip_serializing_if = "Option::is_none")]
640    pub text: Option<ResponseTextParam>,
641    #[serde(
642        default,
643        deserialize_with = "deserialize_tool_choice",
644        skip_serializing_if = "Option::is_none"
645    )]
646    pub tool_choice: Option<RequestToolChoiceParam>,
647    #[serde(skip_serializing_if = "Option::is_none")]
648    // Preserve namespace deferral, member overrides and custom-tool metadata for rendering.
649    pub tools: Option<Vec<RequestTool>>,
650    #[serde(skip_serializing_if = "Option::is_none")]
651    pub top_logprobs: Option<u8>,
652    #[serde(skip_serializing_if = "Option::is_none")]
653    pub top_p: Option<f32>,
654    #[serde(skip_serializing_if = "Option::is_none")]
655    pub truncation: Option<Truncation>,
656}
657
658// ---------------------------------------------------------------------------
659// CountInputTokens (`POST /v1/responses/input_tokens`)
660// ---------------------------------------------------------------------------
661
662/// The `object` discriminator on a [`CountInputTokensResponse`].
663pub const RESPONSE_INPUT_TOKENS_OBJECT: &str = "response.input_tokens";
664
665/// Request body for `POST /v1/responses/input_tokens`.
666///
667/// A subset of [`CreateResponse`] — only the fields that reach the rendered
668/// prompt. This mirrors `AnthropicCountTokensRequest`, which is the same
669/// subset-of-the-create-request shape for `POST /v1/messages/count_tokens`.
670///
671/// Two deliberate differences from `CreateResponse`: `input` defaults (the
672/// count endpoint accepts a body without one, whereas creating a response
673/// requires it), and unknown fields are ignored, so stateful parameters
674/// Dynamo does not serve (`conversation`, `previous_response_id`) are accepted
675/// and disregarded rather than rejected. This endpoint reports a pre-flight
676/// estimate; it never generates, so there is nothing for them to affect.
677///
678/// Deserialization is forgiving in two further places — an explicit
679/// `"input": null` and unrecognized tool shapes — for the same reason
680/// `AnthropicTool` keeps every field but `name` optional: a pre-flight
681/// estimate that rejects a body it could have scored is strictly worse than
682/// one that scores it approximately. See [`deserialize_lenient_tools`].
683#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
684pub struct CountInputTokensRequest {
685    #[serde(default, skip_serializing_if = "Option::is_none")]
686    pub model: Option<String>,
687    /// `#[serde(default)]` alone covers an absent `input`, but not an explicit
688    /// `"input": null` — serde still hands that null to `InputParam`, whose
689    /// deserializer rejects it. Here both mean "nothing to count".
690    #[serde(default, deserialize_with = "deserialize_null_default_input")]
691    pub input: InputParam,
692    #[serde(default, skip_serializing_if = "Option::is_none")]
693    pub instructions: Option<String>,
694    #[serde(
695        default,
696        skip_serializing_if = "Option::is_none",
697        deserialize_with = "deserialize_lenient_tools"
698    )]
699    pub tools: Option<Vec<Tool>>,
700}
701
702fn deserialize_null_default_input<'de, D>(deserializer: D) -> Result<InputParam, D::Error>
703where
704    D: serde::Deserializer<'de>,
705{
706    Ok(Option::<InputParam>::deserialize(deserializer)?.unwrap_or_default())
707}
708
709/// Drop tool entries that do not deserialize into a known [`Tool`], rather than
710/// failing the whole request.
711///
712/// `Tool` is upstream's `#[serde(tag = "type")]` enum, so it models only the
713/// tool types the pinned `async-openai` knows. A caller that forwards a tool in
714/// a shape upstream does not model — a Chat-Completions-style `{"type":
715/// "custom", "custom": {...}}`, or a tool type newer than the pin — would
716/// otherwise get a 400 for a field that contributes almost nothing to the
717/// estimate.
718///
719/// Dropping costs nothing: [`estimate_tool_len`] already scores every
720/// non-function tool as 0, because `convert_tools` forwards only function tools
721/// to the backend. An unparseable tool was going to be worth 0 either way; this
722/// only decides whether the rest of the body still gets counted. That is the
723/// same trade `estimate_tool_len` documents when it wildcards where
724/// `measure_item` is exhaustive — `Tool` is upstream's type, and we carry
725/// no obligation to mirror its variants.
726fn deserialize_lenient_tools<'de, D>(deserializer: D) -> Result<Option<Vec<Tool>>, D::Error>
727where
728    D: serde::Deserializer<'de>,
729{
730    let Some(raw) = Option::<Vec<serde_json::Value>>::deserialize(deserializer)? else {
731        return Ok(None);
732    };
733    Ok(Some(
734        raw.into_iter()
735            .filter_map(|tool| serde_json::from_value::<Tool>(tool).ok())
736            .collect(),
737    ))
738}
739
740/// Response body for `POST /v1/responses/input_tokens`.
741///
742/// `Deserialize` is derived where the Anthropic count response is
743/// serialize-only: this body is round-tripped by the frontend's integration
744/// tests, which assert on the parsed shape rather than on raw JSON.
745#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
746pub struct CountInputTokensResponse {
747    /// Always [`RESPONSE_INPUT_TOKENS_OBJECT`]. Required by the OpenAI spec.
748    pub object: String,
749    pub input_tokens: u32,
750}
751
752impl CountInputTokensResponse {
753    pub fn new(input_tokens: u32) -> Self {
754        Self {
755            object: RESPONSE_INPUT_TOKENS_OBJECT.to_string(),
756            input_tokens,
757        }
758    }
759}
760
761impl CountInputTokensRequest {
762    /// Estimate input token count using a `len/3` heuristic.
763    ///
764    /// Same contract as `AnthropicCountTokensRequest::estimate_tokens`: sum the
765    /// character lengths of everything that reaches the prompt, divide by three,
766    /// and never report zero for input that carried content.
767    ///
768    /// This is an estimate, not a tokenization. A frontend serving a
769    /// backend that tokenizes for itself has no tokenizer loaded, so this
770    /// endpoint has to be able to answer without one.
771    pub fn estimate_tokens(&self) -> u32 {
772        let mut total_len: usize = 0;
773
774        // `instructions` and a top-level string `input` are not free-floating
775        // text: the converter turns them into a system and a user chat message
776        // respectively, exactly like the item messages below. Charge them the
777        // same role markers, or the identical prompt scores differently
778        // depending on which shape the caller used to express it.
779        //
780        // Both are skipped when empty, because an absent field is not a
781        // message. `InputParam::default()` is `Text("")`, so a body with no
782        // `input` at all lands here — and it must stay worth zero.
783        if let Some(instructions) = &self.instructions.as_ref().filter(|text| !text.is_empty()) {
784            total_len += role_len(Role::System) + instructions.len();
785        }
786
787        match &self.input {
788            InputParam::Text(text) if text.is_empty() => {}
789            InputParam::Text(text) => total_len += role_len(Role::User) + text.len(),
790            InputParam::Items(items) => total_len += estimate_input_items_len(items),
791        }
792
793        if let Some(tools) = &self.tools {
794            for tool in tools {
795                total_len += estimate_tool_len(tool);
796            }
797        }
798
799        let tokens = total_len / 3;
800        if tokens == 0 && total_len > 0 {
801            1
802        } else {
803            tokens as u32
804        }
805    }
806}
807
808/// Approximate character cost of a role marker, using the same constants
809/// `AnthropicCountTokensRequest::estimate_tokens` applies for the same purpose.
810fn role_len(role: Role) -> usize {
811    match role {
812        Role::User => 4,
813        Role::Assistant => 9,
814        Role::System => 6,
815        Role::Developer => 9,
816    }
817}
818
819fn input_role_len(role: InputRole) -> usize {
820    match role {
821        InputRole::User => 4,
822        InputRole::System => 6,
823        InputRole::Developer => 9,
824    }
825}
826
827/// The `tool` role marker on a tool-result message.
828///
829/// `role_len` covers only the roles upstream's `Role` enum models; chat
830/// completions' `tool` role has no variant there, so it gets its own constant
831/// on the same basis the others use — the length of the role word.
832const TOOL_ROLE_LEN: usize = 4;
833
834/// What an input item does to the converter's pending assistant message.
835enum GroupEffect {
836    /// Opens or extends the pending assistant message, emitting no message of
837    /// its own.
838    Assistant,
839    /// Flushes any pending assistant message and emits its own.
840    Flush,
841    /// Neither emits nor flushes — the converter skips it outright.
842    Skip,
843}
844
845/// Sum the input items, mirroring `convert_input_items_to_messages` — including
846/// its coalescing.
847///
848/// Assistant-side items do not each become a message. An echoed assistant
849/// message, a function call, and a reasoning summary all push into one
850/// `PendingAssistant`, which is flushed only by the next non-assistant item or
851/// by the end of the list. So the assistant role marker is charged once per
852/// flushed group, not once per item: two parallel function calls are one
853/// assistant turn and cost one marker between them.
854///
855/// A per-item sum cannot express that, which is why this walks the list rather
856/// than mapping over it.
857fn estimate_input_items_len(items: &[InputItem]) -> usize {
858    let mut total = 0;
859    let mut assistant_open = false;
860
861    for item in items {
862        let (effect, len) = measure_input_item(item);
863        total += len;
864        match effect {
865            GroupEffect::Assistant => {
866                if !assistant_open {
867                    assistant_open = true;
868                    total += role_len(Role::Assistant);
869                }
870            }
871            GroupEffect::Flush => assistant_open = false,
872            GroupEffect::Skip => {}
873        }
874    }
875
876    total
877}
878
879/// Measure one item and report what it does to the pending assistant group.
880///
881/// Assistant-side arms return content only: their role marker is the caller's
882/// to add, once per group.
883fn measure_input_item(item: &InputItem) -> (GroupEffect, usize) {
884    match item {
885        // A pointer to an item held server-side. The content it names is not in
886        // this request, so there is nothing here to measure — and the converter
887        // skips it without flushing, so it cannot split an assistant group.
888        InputItem::ItemReference(_) => (GroupEffect::Skip, 0),
889        InputItem::EasyMessage(message) => {
890            let content = estimate_easy_content_len(&message.content);
891            match message.role {
892                // A prior assistant turn echoed back; coalesces like the strict
893                // `MessageItem::Output` path.
894                Role::Assistant => (GroupEffect::Assistant, content),
895                role => (GroupEffect::Flush, role_len(role) + content),
896            }
897        }
898        InputItem::Item(item) => measure_item(item),
899    }
900}
901
902fn estimate_easy_content_len(content: &EasyInputContent) -> usize {
903    match content {
904        EasyInputContent::Text(text) => text.len(),
905        EasyInputContent::ContentList(parts) => parts.iter().map(estimate_input_content_len).sum(),
906    }
907}
908
909/// Only text parts are measured. An image or file contributes tokens as a
910/// function of its decoded form, which a character count cannot model at all —
911/// the Anthropic estimator skips non-text blocks for the same reason.
912fn estimate_input_content_len(part: &InputContent) -> usize {
913    match part {
914        InputContent::InputText(text) => text.text.len(),
915        InputContent::InputImage(_) | InputContent::InputFile(_) => 0,
916    }
917}
918
919fn measure_item(item: &Item) -> (GroupEffect, usize) {
920    match item {
921        Item::Message(MessageItem::Input(message)) => (
922            GroupEffect::Flush,
923            input_role_len(message.role)
924                + message
925                    .content
926                    .iter()
927                    .map(estimate_input_content_len)
928                    .sum::<usize>(),
929        ),
930        // Assistant-side: pushed into the pending message, so no role marker
931        // here. See `estimate_input_items_len`.
932        Item::Message(MessageItem::Output(message)) => (
933            GroupEffect::Assistant,
934            message
935                .content
936                .iter()
937                .map(|part| match part {
938                    InputOutputMessageContent::OutputText(text) => text.text.len(),
939                    InputOutputMessageContent::Refusal(refusal) => refusal.refusal.len(),
940                })
941                .sum::<usize>(),
942        ),
943        // Rendered as a tool call on the pending assistant message. `call_id`
944        // is excluded deliberately: it is correlation plumbing, not prompt
945        // text, in the templates Dynamo renders.
946        Item::FunctionCall(call) => (
947            GroupEffect::Assistant,
948            call.name.len() + call.arguments.len(),
949        ),
950        // Its own `tool`-role message, one per output, so it both flushes the
951        // assistant group and carries a role marker of its own.
952        Item::FunctionCallOutput(output) => (
953            GroupEffect::Flush,
954            TOOL_ROLE_LEN
955                + match &output.output {
956                    FunctionCallOutput::Text(text) => text.len(),
957                    FunctionCallOutput::Content(parts) => {
958                        parts.iter().map(estimate_input_content_len).sum()
959                    }
960                },
961        ),
962        // Only `summary` is measured, because only `summary` is rendered:
963        // the converter joins the summary parts and drops the rest of the
964        // item. `content` is excluded for that reason alone — if Dynamo
965        // learns to render it, it needs to start counting here too.
966        // `encrypted_content` is excluded on its own merits: it is an opaque
967        // blob the model never sees as prompt text, and it is routinely far
968        // larger than the reasoning it stands for.
969        Item::Reasoning(reasoning) => (
970            GroupEffect::Assistant,
971            reasoning
972                .summary
973                .iter()
974                .map(|part| match part {
975                    SummaryPart::SummaryText(text) => text.text.len(),
976                })
977                .sum(),
978        ),
979        // Everything below contributes nothing, because nothing below reaches
980        // the prompt: Dynamo's `convert_input_items_to_messages` flushes and
981        // skips every one of these ("we do not have a faithful Chat
982        // Completions mapping"). The arms above are exactly its handled set.
983        // Measuring the serialized form instead would bill callers for JSON
984        // scaffolding the model never sees: a bare `web_search_call` is 59
985        // characters, or 19 phantom tokens, and agentic clients echo many
986        // such items per turn.
987        //
988        // Listed out rather than wildcarded on purpose. `Item` is a shadow
989        // enum that "mirrors upstream variant-for-variant" and has to be
990        // extended by hand whenever upstream grows a variant (see CLAUDE.md,
991        // "Owned input chain"). A `_` arm would let that new variant default
992        // to zero silently; an exhaustive match turns it into a compile error
993        // that forces a render-or-not decision here, which is the same
994        // mechanism CLAUDE.md relies on to catch drift in `From` impls.
995        Item::FileSearchCall(_)
996        | Item::ComputerCall(_)
997        | Item::ComputerCallOutput(_)
998        | Item::WebSearchCall(_)
999        | Item::ToolSearchCall(_)
1000        | Item::ToolSearchOutput(_)
1001        | Item::Compaction(_)
1002        | Item::ImageGenerationCall(_)
1003        | Item::CodeInterpreterCall(_)
1004        | Item::LocalShellCall(_)
1005        | Item::LocalShellCallOutput(_)
1006        | Item::ShellCall(_)
1007        | Item::ShellCallOutput(_)
1008        | Item::ApplyPatchCall(_)
1009        | Item::ApplyPatchCallOutput(_)
1010        | Item::McpListTools(_)
1011        | Item::McpApprovalRequest(_)
1012        | Item::McpApprovalResponse(_)
1013        | Item::McpCall(_)
1014        | Item::CustomToolCallOutput(_)
1015        | Item::CustomToolCall(_) => (GroupEffect::Flush, 0),
1016    }
1017}
1018
1019/// Mirrors `convert_tools`: only function tools are forwarded to the backend,
1020/// namespaced ones flattened to their bare function members. Hosted tools
1021/// (web search, file search, computer use) are dropped there and so cost
1022/// nothing here.
1023///
1024/// Wildcarded where `measure_item` is exhaustive, and deliberately so:
1025/// `Tool` is upstream's type, not one of our shadows, so we carry no
1026/// obligation to mirror its variants. Pinning it exhaustively would only
1027/// break the build every time async-openai adds a hosted tool we would
1028/// score as zero anyway.
1029fn estimate_tool_len(tool: &Tool) -> usize {
1030    match tool {
1031        Tool::Function(function) => function_tool_len(
1032            &function.name,
1033            function.description.as_ref(),
1034            function.parameters.as_ref(),
1035        ),
1036        Tool::Namespace(namespace) => namespace
1037            .tools
1038            .iter()
1039            .map(|tool| match tool {
1040                // The namespace name is an origin marker used to detect
1041                // collisions, not prompt text — `push_function` forwards the
1042                // bare function name.
1043                NamespaceToolParamTool::Function(function) => function_tool_len(
1044                    &function.name,
1045                    function.description.as_ref(),
1046                    function.parameters.as_ref(),
1047                ),
1048                NamespaceToolParamTool::Custom(_) => 0,
1049            })
1050            .sum(),
1051        _ => 0,
1052    }
1053}
1054
1055fn function_tool_len(
1056    name: &str,
1057    description: Option<&String>,
1058    parameters: Option<&serde_json::Value>,
1059) -> usize {
1060    name.len()
1061        + description.map_or(0, |description| description.len())
1062        + parameters.map_or(0, |schema| schema.to_string().len())
1063}
1064
1065#[cfg(test)]
1066mod tests {
1067    use super::*;
1068
1069    #[test]
1070    fn request_choices_preserve_upstream_output_choices() {
1071        for value in [
1072            serde_json::json!("auto"),
1073            serde_json::json!("none"),
1074            serde_json::json!("required"),
1075            serde_json::json!({"type":"function","name":"weather"}),
1076            serde_json::json!({"type":"custom","name":"patch"}),
1077            serde_json::json!({"type":"programmatic_tool_calling"}),
1078            serde_json::json!({"type":"apply_patch"}),
1079            serde_json::json!({"type":"shell"}),
1080        ] {
1081            let choice: RequestToolChoiceParam = serde_json::from_value(value.clone()).unwrap();
1082            let upstream: ToolChoiceParam = choice.sdk_response_choice();
1083            assert_eq!(serde_json::to_value(upstream).unwrap(), value);
1084        }
1085        assert_eq!(
1086            serde_json::to_value(RequestToolChoiceParam::ToolSearch.sdk_response_choice()).unwrap(),
1087            "required"
1088        );
1089    }
1090
1091    // ---- tool_choice object form (ai-dynamo/dynamo#10963 CASE 1) ----
1092
1093    fn tool_choice_of(json: serde_json::Value) -> Option<RequestToolChoiceParam> {
1094        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1095            "input": "hi",
1096            "tool_choice": json,
1097        }))
1098        .expect("CreateResponse should deserialize");
1099        req.tool_choice
1100    }
1101
1102    #[test]
1103    fn tool_choice_mode_object_coerces_to_mode() {
1104        // Anthropic-style / litellm shape: a mode expressed as an object with
1105        // extra keys. Must coerce to the corresponding `Option`, ignoring extras.
1106        assert_eq!(
1107            tool_choice_of(serde_json::json!({"type": "auto", "disable_parallel_tool_use": true})),
1108            Some(RequestToolChoiceParam::Option(ToolChoiceOptions::Auto)),
1109        );
1110        assert_eq!(
1111            tool_choice_of(serde_json::json!({"type": "none"})),
1112            Some(RequestToolChoiceParam::Option(ToolChoiceOptions::None)),
1113        );
1114        assert_eq!(
1115            tool_choice_of(serde_json::json!({"type": "required"})),
1116            Some(RequestToolChoiceParam::Option(ToolChoiceOptions::Required)),
1117        );
1118    }
1119
1120    #[test]
1121    fn tool_choice_bare_string_still_works() {
1122        assert_eq!(
1123            tool_choice_of(serde_json::json!("auto")),
1124            Some(RequestToolChoiceParam::Option(ToolChoiceOptions::Auto)),
1125        );
1126    }
1127
1128    #[test]
1129    fn tool_choice_specific_function_object_still_works() {
1130        // The object form naming a specific tool must NOT be swallowed by the
1131        // mode coercion — `type: "function"` is not a mode.
1132        match tool_choice_of(serde_json::json!({"type": "function", "name": "get_weather"})) {
1133            Some(RequestToolChoiceParam::Function(f)) => assert_eq!(f.name, "get_weather"),
1134            other => panic!("expected Function tool choice, got {other:?}"),
1135        }
1136    }
1137
1138    #[test]
1139    fn tool_choice_absent_is_none() {
1140        let req: CreateResponse =
1141            serde_json::from_value(serde_json::json!({"input": "hi"})).unwrap();
1142        assert!(req.tool_choice.is_none());
1143    }
1144
1145    // ---- reasoning item echoed back without id/summary (#10963 CASE 2) ----
1146
1147    #[test]
1148    fn reasoning_input_without_id_deserializes() {
1149        // Codex / OpenCode / agent SDKs echo a reasoning item with no `id`.
1150        let json = serde_json::json!({
1151            "type": "reasoning",
1152            "summary": [{"type": "summary_text", "text": "thinking"}],
1153        });
1154        match serde_json::from_value::<InputItem>(json).expect("should deserialize") {
1155            InputItem::Item(Item::Reasoning(r)) => {
1156                assert!(r.id.is_none());
1157                assert_eq!(r.summary.len(), 1);
1158            }
1159            other => panic!("expected Item::Reasoning, got {other:?}"),
1160        }
1161    }
1162
1163    #[test]
1164    fn reasoning_input_encrypted_without_id_or_summary_deserializes() {
1165        let json = serde_json::json!({
1166            "type": "reasoning",
1167            "encrypted_content": "AB==",
1168        });
1169        match serde_json::from_value::<InputItem>(json).expect("should deserialize") {
1170            InputItem::Item(Item::Reasoning(r)) => {
1171                assert!(r.id.is_none());
1172                assert!(r.summary.is_empty());
1173                assert_eq!(r.encrypted_content.as_deref(), Some("AB=="));
1174            }
1175            other => panic!("expected Item::Reasoning, got {other:?}"),
1176        }
1177    }
1178
1179    #[test]
1180    fn reasoning_input_with_id_still_works() {
1181        let json = serde_json::json!({
1182            "type": "reasoning",
1183            "id": "rs_1",
1184            "summary": [{"type": "summary_text", "text": "x"}],
1185            "status": "completed",
1186        });
1187        match serde_json::from_value::<InputItem>(json).expect("should deserialize") {
1188            InputItem::Item(Item::Reasoning(r)) => assert_eq!(r.id.as_deref(), Some("rs_1")),
1189            other => panic!("expected Item::Reasoning, got {other:?}"),
1190        }
1191    }
1192
1193    #[test]
1194    fn reasoning_input_summary_normalizes_empty_values_and_preserves_fields() {
1195        let populated = serde_json::json!([{"type": "summary_text", "text": "summary"}]);
1196        for (summary, expected_summary) in [
1197            (serde_json::Value::Null, serde_json::json!([])),
1198            (serde_json::json!([]), serde_json::json!([])),
1199            (populated.clone(), populated),
1200        ] {
1201            let mut input = serde_json::json!({
1202                "type": "reasoning",
1203                "id": "rs_1",
1204                "summary": summary,
1205                "content": [{"text": "reasoning content"}],
1206                "encrypted_content": "AB==",
1207                "status": "completed",
1208            });
1209            let request: CreateResponse = serde_json::from_value(serde_json::json!({
1210                "model": "example-model", "input": [input.clone()]
1211            }))
1212            .expect("reasoning summary should deserialize");
1213            input["summary"] = expected_summary;
1214            let serialized = serde_json::to_value(request).unwrap();
1215            assert_eq!(serialized["input"][0], input);
1216        }
1217    }
1218
1219    #[test]
1220    fn reasoning_input_summary_rejects_invalid_values() {
1221        for summary in [
1222            serde_json::json!(false),
1223            serde_json::json!([null]),
1224            serde_json::json!([{"type": "summary_text"}]),
1225            serde_json::json!([{"type": "output_text", "text": "summary"}]),
1226        ] {
1227            assert!(
1228                serde_json::from_value::<InputItem>(serde_json::json!({
1229                    "type": "reasoning", "summary": summary
1230                }))
1231                .is_err(),
1232                "invalid summary must be rejected: {summary}"
1233            );
1234        }
1235    }
1236
1237    #[test]
1238    fn reasoning_output_summary_null_remains_invalid() {
1239        let mut output = serde_json::json!({
1240            "type": "reasoning", "id": "rs_1", "summary": null
1241        });
1242        assert!(serde_json::from_value::<OutputItem>(output.clone()).is_err());
1243        output["summary"] = serde_json::json!([]);
1244        assert!(serde_json::from_value::<OutputItem>(output).is_ok());
1245    }
1246
1247    #[test]
1248    fn full_request_with_idless_reasoning_item_deserializes() {
1249        // The exact failure mode reported in #10963: a turn-2 `input` list
1250        // containing an echoed reasoning item that lost its `id`.
1251        let req: Result<CreateResponse, _> = serde_json::from_value(serde_json::json!({
1252            "model": "m",
1253            "input": [
1254                {"role": "user", "content": "hi"},
1255                {"type": "reasoning", "summary": [{"type": "summary_text", "text": "x"}]},
1256            ],
1257        }));
1258        assert!(
1259            req.is_ok(),
1260            "idless reasoning input should deserialize: {req:?}"
1261        );
1262    }
1263
1264    #[test]
1265    fn codex_agent_message_normalizes_to_user_message() {
1266        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1267            "input": [{
1268                "type": "agent_message",
1269                "author": "/root",
1270                "recipient": "/root/worker",
1271                "content": [
1272                    {"type": "input_text", "text": "First."},
1273                    {"type": "input_text", "text": "Second."},
1274                ],
1275            }],
1276        }))
1277        .expect("Codex agent message should deserialize");
1278
1279        let InputParam::Items(items) = req.input else {
1280            panic!("expected items");
1281        };
1282        assert!(matches!(
1283            &items[0],
1284            InputItem::EasyMessage(EasyInputMessage {
1285                role: Role::User,
1286                content: EasyInputContent::Text(text),
1287                ..
1288            }) if text == "First.\nSecond."
1289        ));
1290    }
1291
1292    #[test]
1293    fn codex_agent_message_string_content_normalizes_to_user_message() {
1294        let item: InputItem = serde_json::from_value(serde_json::json!({
1295            "type": "agent_message",
1296            "author": "/root",
1297            "recipient": "/root/worker",
1298            "content": "Return exactly OK.",
1299        }))
1300        .expect("Codex agent message with string content should deserialize");
1301
1302        assert!(matches!(
1303            item,
1304            InputItem::EasyMessage(EasyInputMessage {
1305                content: EasyInputContent::Text(text),
1306                ..
1307            }) if text == "Return exactly OK."
1308        ));
1309    }
1310
1311    #[test]
1312    fn codex_agent_message_normalizes_encrypted_content() {
1313        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1314            "input": [{
1315                "type": "agent_message",
1316                "content": [
1317                    {"type": "input_text", "text": "Payload:"},
1318                    {"type": "encrypted_content", "encrypted_content": "Return exactly OK."},
1319                ],
1320            }],
1321        }))
1322        .expect("Codex agent message with encrypted content should deserialize");
1323
1324        let InputParam::Items(items) = req.input else {
1325            panic!("expected items");
1326        };
1327        assert!(matches!(
1328            &items[0],
1329            InputItem::EasyMessage(EasyInputMessage {
1330                content: EasyInputContent::Text(text),
1331                ..
1332            }) if text == "Payload:\nReturn exactly OK."
1333        ));
1334    }
1335
1336    #[test]
1337    fn codex_agent_message_missing_content_normalizes_empty() {
1338        let item: InputItem = serde_json::from_value(serde_json::json!({
1339            "type": "agent_message",
1340            "author": "/root",
1341            "recipient": "/root/worker",
1342        }))
1343        .expect("Codex agent message without content should deserialize");
1344        assert!(matches!(
1345            item,
1346            InputItem::EasyMessage(EasyInputMessage {
1347                content: EasyInputContent::Text(text),
1348                ..
1349            }) if text.is_empty()
1350        ));
1351    }
1352
1353    #[test]
1354    fn codex_agent_message_null_content_normalizes_empty() {
1355        let item: InputItem = serde_json::from_value(serde_json::json!({
1356            "type": "agent_message",
1357            "author": "/root",
1358            "recipient": "/root/worker",
1359            "content": null,
1360        }))
1361        .expect("Codex agent message with null content should deserialize");
1362        assert!(matches!(
1363            item,
1364            InputItem::EasyMessage(EasyInputMessage {
1365                content: EasyInputContent::Text(text),
1366                ..
1367            }) if text.is_empty()
1368        ));
1369    }
1370
1371    #[test]
1372    fn relaxed_assistant_message_without_id_or_status() {
1373        let json = serde_json::json!({
1374            "type": "message",
1375            "role": "assistant",
1376            "content": [{"type": "output_text", "text": "hi"}]
1377        });
1378        let item: InputItem = serde_json::from_value(json).unwrap();
1379        match item {
1380            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1381                assert_eq!(out.role, AssistantRole::Assistant);
1382                assert!(out.id.is_none());
1383                assert!(out.status.is_none());
1384            }
1385            other => panic!("expected Item::Message(Output), got {other:?}"),
1386        }
1387    }
1388
1389    #[test]
1390    fn function_call_output_image_part_without_detail_parses() {
1391        let json = serde_json::json!({
1392            "input": [
1393                {"type": "function_call", "call_id": "c1", "name": "screenshot", "arguments": "{}"},
1394                {"type": "function_call_output", "call_id": "c1", "output": [
1395                    {"type": "input_text", "text": "captured"},
1396                    {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo="}
1397                ]}
1398            ]
1399        });
1400        let req: CreateResponse = serde_json::from_value(json).unwrap();
1401        let InputParam::Items(items) = req.input else {
1402            panic!("expected Items")
1403        };
1404        match &items[1] {
1405            InputItem::Item(Item::FunctionCallOutput(fco)) => {
1406                assert_eq!(fco.call_id, "c1");
1407                let FunctionCallOutput::Content(parts) = &fco.output else {
1408                    panic!("expected Content, got {:?}", fco.output)
1409                };
1410                assert_eq!(parts.len(), 2);
1411                match &parts[1] {
1412                    InputContent::InputImage(img) => {
1413                        assert_eq!(img.detail, ImageDetail::Auto);
1414                        assert_eq!(
1415                            img.image_url.as_deref(),
1416                            Some("data:image/png;base64,iVBORw0KGgo=")
1417                        );
1418                    }
1419                    other => panic!("expected InputImage, got {other:?}"),
1420                }
1421            }
1422            other => panic!("expected FunctionCallOutput, got {other:?}"),
1423        }
1424    }
1425
1426    #[test]
1427    fn function_call_output_image_part_with_null_detail_matches_message_content() {
1428        // `"detail": null` is accepted in message content; a tool output must not
1429        // be stricter than the message it answers.
1430        let part = serde_json::json!({
1431            "type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo=", "detail": null
1432        });
1433        let message: Item = serde_json::from_value(serde_json::json!({
1434            "type": "message", "role": "user", "content": [part]
1435        }))
1436        .unwrap();
1437        assert!(matches!(message, Item::Message(_)));
1438        let output: Item = serde_json::from_value(serde_json::json!({
1439            "type": "function_call_output", "call_id": "c1", "output": [part]
1440        }))
1441        .unwrap();
1442        let Item::FunctionCallOutput(fco) = output else {
1443            panic!("expected FunctionCallOutput, got {output:?}")
1444        };
1445        match &fco.output {
1446            FunctionCallOutput::Content(parts) => match &parts[0] {
1447                InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1448                other => panic!("expected InputImage, got {other:?}"),
1449            },
1450            other => panic!("expected Content, got {other:?}"),
1451        }
1452    }
1453
1454    #[test]
1455    fn function_call_output_from_conversions_match_upstream() {
1456        assert_eq!(
1457            FunctionCallOutput::from("ok"),
1458            FunctionCallOutput::Text("ok".to_string())
1459        );
1460        assert_eq!(
1461            FunctionCallOutput::from(String::from("ok")),
1462            FunctionCallOutput::Text("ok".to_string())
1463        );
1464        let parts = vec![InputContent::InputText(InputTextContent {
1465            text: "captured".to_string(),
1466            prompt_cache_breakpoint: None,
1467        })];
1468        let item = FunctionCallOutputItemParam {
1469            call_id: "c1".to_string(),
1470            output: parts.clone().into(),
1471            id: None,
1472            status: None,
1473        };
1474        assert_eq!(item.output, FunctionCallOutput::Content(parts));
1475    }
1476
1477    #[test]
1478    fn function_call_output_string_still_parses() {
1479        let item: Item = serde_json::from_value(serde_json::json!({
1480            "type": "function_call_output", "call_id": "c1", "output": "{\"ok\":true}"
1481        }))
1482        .unwrap();
1483        match item {
1484            Item::FunctionCallOutput(fco) => {
1485                assert!(
1486                    matches!(fco.output, FunctionCallOutput::Text(ref t) if t == "{\"ok\":true}")
1487                );
1488                assert!(fco.id.is_none() && fco.status.is_none());
1489            }
1490            other => panic!("expected FunctionCallOutput, got {other:?}"),
1491        }
1492    }
1493
1494    #[test]
1495    fn input_image_without_detail_defaults_to_auto() {
1496        let json = serde_json::json!({
1497            "type": "input_image",
1498            "image_url": "https://example.com/cat.jpg"
1499        });
1500        let content: InputContent = serde_json::from_value(json).unwrap();
1501        match content {
1502            InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1503            other => panic!("expected InputImage, got {other:?}"),
1504        }
1505    }
1506
1507    #[test]
1508    fn input_image_with_explicit_null_detail_defaults_to_auto() {
1509        let json = serde_json::json!({
1510            "type": "input_image",
1511            "image_url": "https://example.com/cat.jpg",
1512            "detail": null
1513        });
1514        let content: InputContent = serde_json::from_value(json).unwrap();
1515        match content {
1516            InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1517            other => panic!("expected InputImage, got {other:?}"),
1518        }
1519    }
1520
1521    #[test]
1522    fn assistant_message_without_content_field_deserializes() {
1523        // Bare assistant shell — no `content` field at all. Seen in real
1524        // Codex/Agents-SDK traffic on pure tool-call turns. `#[serde(default)]`
1525        // on `content` must accept omission and yield an empty vec.
1526        let json = serde_json::json!({
1527            "type": "message",
1528            "role": "assistant"
1529        });
1530        let item: InputItem = serde_json::from_value(json).unwrap();
1531        match item {
1532            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1533                assert_eq!(out.role, AssistantRole::Assistant);
1534                assert!(out.content.is_empty());
1535                assert!(out.id.is_none());
1536                assert!(out.status.is_none());
1537            }
1538            other => panic!("expected Item::Message(Output), got {other:?}"),
1539        }
1540    }
1541
1542    #[test]
1543    fn assistant_message_with_explicit_null_content_deserializes() {
1544        // Mirrors the `annotations: null` case: some serializers emit JSON null
1545        // for absent fields instead of omitting them. `Vec::deserialize` rejects
1546        // null, so `content` also needs `deserialize_null_as_empty_vec`.
1547        let json = serde_json::json!({
1548            "type": "message",
1549            "role": "assistant",
1550            "content": null
1551        });
1552        let item: InputItem = serde_json::from_value(json).unwrap();
1553        match item {
1554            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1555                assert!(out.content.is_empty());
1556            }
1557            other => panic!("expected Item::Message(Output), got {other:?}"),
1558        }
1559    }
1560
1561    #[test]
1562    fn mcp_call_item_deserializes() {
1563        // Guards against Item variant drift vs upstream — MCP item types were
1564        // added after the initial owned `Item` chain landed.
1565        let json = serde_json::json!({
1566            "type": "mcp_call",
1567            "id": "mcp_1",
1568            "server_label": "srv",
1569            "name": "t",
1570            "arguments": "{}"
1571        });
1572        let item: InputItem = serde_json::from_value(json).unwrap();
1573        assert!(matches!(item, InputItem::Item(Item::McpCall(_))));
1574    }
1575
1576    #[test]
1577    fn strict_assistant_message_still_deserializes() {
1578        let json = serde_json::json!({
1579            "type": "message",
1580            "role": "assistant",
1581            "id": "msg_1",
1582            "status": "completed",
1583            "content": [{"type": "output_text", "text": "hi", "annotations": []}]
1584        });
1585        let item: InputItem = serde_json::from_value(json).unwrap();
1586        match item {
1587            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1588                assert_eq!(out.id.as_deref(), Some("msg_1"));
1589                assert_eq!(out.status, Some(OutputStatus::Completed));
1590            }
1591            other => panic!("expected Item::Message(Output), got {other:?}"),
1592        }
1593    }
1594
1595    #[test]
1596    fn user_message_routes_to_input_variant() {
1597        let json = serde_json::json!({
1598            "type": "message",
1599            "role": "user",
1600            "content": [{"type": "input_text", "text": "hi"}]
1601        });
1602        let item: InputItem = serde_json::from_value(json).unwrap();
1603        assert!(matches!(
1604            item,
1605            InputItem::Item(Item::Message(MessageItem::Input(_)))
1606        ));
1607    }
1608
1609    #[test]
1610    fn function_call_item_still_deserializes() {
1611        let json = serde_json::json!({
1612            "type": "function_call",
1613            "call_id": "c",
1614            "name": "f",
1615            "arguments": "{}"
1616        });
1617        let item: InputItem = serde_json::from_value(json).unwrap();
1618        assert!(matches!(item, InputItem::Item(Item::FunctionCall(_))));
1619    }
1620
1621    #[test]
1622    fn easy_message_string_content_routes_to_easymessage() {
1623        let json = serde_json::json!({"role": "assistant", "content": "x"});
1624        let item: InputItem = serde_json::from_value(json).unwrap();
1625        assert!(matches!(item, InputItem::EasyMessage(_)));
1626    }
1627
1628    #[test]
1629    fn output_text_without_annotations_defaults_empty() {
1630        let json = serde_json::json!({"type": "output_text", "text": "hi"});
1631        let part: InputOutputMessageContent = serde_json::from_value(json).unwrap();
1632        match part {
1633            InputOutputMessageContent::OutputText(t) => {
1634                assert!(t.annotations.is_empty());
1635            }
1636            _ => panic!("expected OutputText"),
1637        }
1638    }
1639
1640    #[test]
1641    fn output_text_with_explicit_null_annotations_deserializes_as_empty() {
1642        // Some clients serialize absent fields as JSON null instead of omitting
1643        // them. `Vec::deserialize` would reject null; the custom deserializer
1644        // treats explicit null identically to a missing field.
1645        let json = serde_json::json!({"type": "output_text", "text": "hi", "annotations": null});
1646        let part: InputOutputMessageContent = serde_json::from_value(json).unwrap();
1647        match part {
1648            InputOutputMessageContent::OutputText(t) => {
1649                assert!(t.annotations.is_empty());
1650            }
1651            _ => panic!("expected OutputText"),
1652        }
1653    }
1654
1655    #[test]
1656    fn assistant_message_with_explicit_null_id_and_status_deserializes() {
1657        // `Option<T>` natively accepts null as `None`, so these explicit-null
1658        // fields should flow through without a custom deserializer. This test
1659        // pins that behavior against accidental regressions (e.g. if someone
1660        // switches the field type away from `Option<_>`).
1661        let json = serde_json::json!({
1662            "type": "message",
1663            "role": "assistant",
1664            "id": null,
1665            "status": null,
1666            "content": [{"type": "output_text", "text": "hi", "annotations": null}]
1667        });
1668        let item: InputItem = serde_json::from_value(json).unwrap();
1669        match item {
1670            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1671                assert!(out.id.is_none());
1672                assert!(out.status.is_none());
1673                assert_eq!(out.content.len(), 1);
1674            }
1675            other => panic!("expected Item::Message(Output), got {other:?}"),
1676        }
1677    }
1678
1679    /// The Chat Completions spelling `max_tokens` is honored as the output cap
1680    /// rather than silently dropped (#207); the wire echo is `max_output_tokens`.
1681    #[test]
1682    fn create_response_accepts_max_tokens_as_alias_for_max_output_tokens() {
1683        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1684            "model": "m", "input": "hi", "max_tokens": 16
1685        }))
1686        .unwrap();
1687        assert_eq!(req.max_output_tokens, Some(16));
1688        let back = serde_json::to_value(&req).unwrap();
1689        assert_eq!(back["max_output_tokens"], 16);
1690        assert!(back.get("max_tokens").is_none());
1691
1692        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1693            "model": "m", "input": "hi", "max_tokens": null
1694        }))
1695        .unwrap();
1696        assert_eq!(req.max_output_tokens, None);
1697
1698        // Both spellings at once is ambiguous and fails as a duplicate field.
1699        let err = serde_json::from_value::<CreateResponse>(serde_json::json!({
1700            "model": "m", "input": "hi", "max_tokens": 16, "max_output_tokens": 32
1701        }))
1702        .unwrap_err();
1703        assert!(err.to_string().contains("duplicate field"), "{err}");
1704    }
1705
1706    #[test]
1707    fn create_response_roundtrip_with_relaxed_input() {
1708        let body = serde_json::json!({
1709            "model": "m",
1710            "input": [
1711                {"type": "message", "role": "user", "content": [
1712                    {"type": "input_text", "text": "hi"}
1713                ]},
1714                {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{}"},
1715                {"type": "message", "role": "assistant", "content": [
1716                    {"type": "output_text", "text": "\n\n"}
1717                ]},
1718                {"type": "function_call_output", "call_id": "c", "output": "x"}
1719            ]
1720        });
1721
1722        let req: CreateResponse = serde_json::from_value(body).unwrap();
1723        let items = match &req.input {
1724            InputParam::Items(items) => items,
1725            _ => panic!("expected Items"),
1726        };
1727        assert_eq!(items.len(), 4);
1728        assert!(matches!(
1729            items[2],
1730            InputItem::Item(Item::Message(MessageItem::Output(_)))
1731        ));
1732    }
1733
1734    // ---- EasyInputMessage / multimodal-without-`type` regression coverage ----
1735    // See issue #9468. Before the EasyInputMessage/EasyInputContent shadow
1736    // landed, the `InputItem::EasyMessage` fallback still routed through
1737    // upstream's strict `InputImageContent` (required `detail`), so any
1738    // multimodal message that omitted the spec-default `type: "message"` would
1739    // fail with "data did not match any variant of untagged enum InputItem".
1740
1741    #[test]
1742    fn easy_message_multimodal_without_type_routes_to_easymessage() {
1743        // AIPerf's pre-PR-931 payload shape: no top-level `type`, content is a
1744        // list containing an `input_image` part with no `detail`.
1745        let json = serde_json::json!({
1746            "role": "user",
1747            "content": [
1748                {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1749            ]
1750        });
1751        let item: InputItem = serde_json::from_value(json).unwrap();
1752        match item {
1753            InputItem::EasyMessage(easy) => {
1754                assert_eq!(easy.role, Role::User);
1755                assert_eq!(easy.r#type, MessageType::Message);
1756                match easy.content {
1757                    EasyInputContent::ContentList(parts) => {
1758                        assert_eq!(parts.len(), 1);
1759                        match &parts[0] {
1760                            InputContent::InputImage(img) => {
1761                                assert_eq!(img.detail, ImageDetail::Auto);
1762                                assert_eq!(
1763                                    img.image_url.as_deref(),
1764                                    Some("data:image/png;base64,abc")
1765                                );
1766                            }
1767                            other => panic!("expected InputImage, got {other:?}"),
1768                        }
1769                    }
1770                    other => panic!("expected ContentList, got {other:?}"),
1771                }
1772            }
1773            other => panic!("expected EasyMessage, got {other:?}"),
1774        }
1775    }
1776
1777    #[test]
1778    fn easy_message_multimodal_with_explicit_null_detail() {
1779        // Same shape as above but with `detail: null` — exercises the
1780        // null-as-default path on the relaxed `InputImageContent` reached via
1781        // the EasyMessage variant.
1782        let json = serde_json::json!({
1783            "role": "user",
1784            "content": [
1785                {"type": "input_image", "image_url": "data:image/png;base64,abc", "detail": null}
1786            ]
1787        });
1788        let item: InputItem = serde_json::from_value(json).unwrap();
1789        assert!(matches!(item, InputItem::EasyMessage(_)));
1790    }
1791
1792    #[test]
1793    fn easy_message_assistant_multimodal_without_type() {
1794        // Mixed-turn shape AIPerf emits when the prior assistant turn carried
1795        // structured (non-string) content: role=assistant, content list, no
1796        // top-level `type`.
1797        let json = serde_json::json!({
1798            "role": "assistant",
1799            "content": [
1800                {"type": "input_text", "text": "ok"}
1801            ]
1802        });
1803        let item: InputItem = serde_json::from_value(json).unwrap();
1804        match item {
1805            InputItem::EasyMessage(easy) => {
1806                assert_eq!(easy.role, Role::Assistant);
1807            }
1808            other => panic!("expected EasyMessage(assistant), got {other:?}"),
1809        }
1810    }
1811
1812    #[test]
1813    fn easy_message_text_only_without_type_unchanged() {
1814        // Regression guard: the pre-existing text-only path was already
1815        // working (no multimodal content -> never hit upstream's strict
1816        // `InputImageContent`). Pin it so a future glob-shadow change can't
1817        // break it.
1818        let json = serde_json::json!({"role": "user", "content": "Hello"});
1819        let item: InputItem = serde_json::from_value(json).unwrap();
1820        match item {
1821            InputItem::EasyMessage(easy) => {
1822                assert_eq!(easy.role, Role::User);
1823                assert!(matches!(easy.content, EasyInputContent::Text(ref s) if s == "Hello"));
1824            }
1825            other => panic!("expected EasyMessage(Text), got {other:?}"),
1826        }
1827    }
1828
1829    #[test]
1830    fn easy_message_with_explicit_type_still_routes_to_item_message() {
1831        // AIPerf's post-PR-931 payload (with `type: "message"`) should still
1832        // hit the structured `Item::Message` path first — proving the existing
1833        // strict path didn't regress when EasyMessage was shadowed.
1834        let json = serde_json::json!({
1835            "type": "message",
1836            "role": "user",
1837            "content": [
1838                {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1839            ]
1840        });
1841        let item: InputItem = serde_json::from_value(json).unwrap();
1842        match item {
1843            InputItem::Item(Item::Message(MessageItem::Input(msg))) => {
1844                assert_eq!(msg.role, InputRole::User);
1845                assert_eq!(msg.content.len(), 1);
1846            }
1847            other => panic!("expected Item::Message(Input), got {other:?}"),
1848        }
1849    }
1850
1851    #[test]
1852    fn create_response_roundtrip_aiperf_pre_pr931_payload() {
1853        // End-to-end shape: the exact request body AIPerf was emitting before
1854        // PR-931 for a multi-turn multimodal conversation. Mirrors what the
1855        // HTTP frontend receives. Must deserialize without error and preserve
1856        // turn ordering.
1857        let body = serde_json::json!({
1858            "model": "Qwen/Qwen2-VL-2B-Instruct",
1859            "input": [
1860                {
1861                    "role": "user",
1862                    "content": [
1863                        {"type": "input_text", "text": "Describe"},
1864                        {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1865                    ]
1866                },
1867                {
1868                    "role": "assistant",
1869                    "content": [{"type": "input_text", "text": "ok"}]
1870                },
1871                {
1872                    "role": "user",
1873                    "content": [{"type": "input_text", "text": "Now describe a different one."}]
1874                }
1875            ]
1876        });
1877        let req: CreateResponse = serde_json::from_value(body).unwrap();
1878        let items = match &req.input {
1879            InputParam::Items(items) => items,
1880            _ => panic!("expected Items"),
1881        };
1882        assert_eq!(items.len(), 3);
1883        // All three turns must land as EasyMessage (no top-level `type`).
1884        for (idx, item) in items.iter().enumerate() {
1885            assert!(
1886                matches!(item, InputItem::EasyMessage(_)),
1887                "turn {idx} did not route to EasyMessage: {item:?}",
1888            );
1889        }
1890    }
1891
1892    // ---- count input tokens (POST /v1/responses/input_tokens) ----
1893
1894    fn count(body: serde_json::Value) -> u32 {
1895        serde_json::from_value::<CountInputTokensRequest>(body)
1896            .expect("count request should deserialize")
1897            .estimate_tokens()
1898    }
1899
1900    #[test]
1901    fn count_tokens_plain_text_input() {
1902        // user role (4) + "Hello, world!" (13) == 17; 17 / 3 == 5.
1903        assert_eq!(
1904            count(serde_json::json!({"model": "m", "input": "Hello, world!"})),
1905            5
1906        );
1907    }
1908
1909    #[test]
1910    fn count_tokens_input_is_optional() {
1911        // The count endpoint accepts a body without `input`, unlike CreateResponse.
1912        assert_eq!(count(serde_json::json!({"model": "m"})), 0);
1913    }
1914
1915    #[test]
1916    fn count_tokens_empty_input_is_zero() {
1917        assert_eq!(count(serde_json::json!({"input": ""})), 0);
1918    }
1919
1920    #[test]
1921    fn count_tokens_short_input_never_rounds_to_zero() {
1922        // Every item that reaches the prompt now carries a role marker of at
1923        // least 4, so no `input` can land under the rounding threshold. Tools
1924        // are the one remaining path: they are appended to the request rather
1925        // than rendered as a message, so they carry no marker. A one-character
1926        // function name is 1, and 1 / 3 == 0 — but content was present, so
1927        // report 1.
1928        assert_eq!(
1929            count(serde_json::json!({"tools": [{"type": "function", "name": "a"}]})),
1930            1
1931        );
1932        // For comparison, the shortest possible input clears the guard on its
1933        // role marker alone: user (4) + "Hi" (2) == 6; 6 / 3 == 2.
1934        assert_eq!(count(serde_json::json!({"input": "Hi"})), 2);
1935    }
1936
1937    #[test]
1938    fn count_tokens_instructions_contribute() {
1939        // system role (6) + "You are helpful." (16)
1940        //   + user role (4) + "Hi" (2) == 28; 28 / 3 == 9.
1941        assert_eq!(
1942            count(serde_json::json!({"input": "Hi", "instructions": "You are helpful."})),
1943            9
1944        );
1945    }
1946
1947    #[test]
1948    fn count_tokens_scores_the_two_spellings_of_a_prompt_identically() {
1949        // `TryFrom<NvCreateResponse>` turns a top-level string `input` into a
1950        // user message and `instructions` into a system message, so these two
1951        // bodies build the same chat request and must score the same. Counting
1952        // the top-level forms as bare text undercounted them by the role
1953        // markers the item forms were already charged.
1954        assert_eq!(
1955            count(serde_json::json!({"input": "Hello"})),
1956            count(serde_json::json!({"input": [{"role": "user", "content": "Hello"}]})),
1957        );
1958        assert_eq!(
1959            count(serde_json::json!({
1960                "input": "Hello",
1961                "instructions": "You are helpful."
1962            })),
1963            count(serde_json::json!({"input": [
1964                {"role": "system", "content": "You are helpful."},
1965                {"role": "user", "content": "Hello"}
1966            ]})),
1967        );
1968    }
1969
1970    #[test]
1971    fn count_tokens_easy_message_counts_role_and_content() {
1972        // user role (4) + "Hello" (5) == 9; 9 / 3 == 3.
1973        assert_eq!(
1974            count(serde_json::json!({"input": [{"role": "user", "content": "Hello"}]})),
1975            3
1976        );
1977    }
1978
1979    #[test]
1980    fn count_tokens_structured_input_message() {
1981        // user role (4) + "Hello" (5) == 9; 9 / 3 == 3.
1982        assert_eq!(
1983            count(serde_json::json!({"input": [{
1984                "type": "message",
1985                "role": "user",
1986                "content": [{"type": "input_text", "text": "Hello"}],
1987            }]})),
1988            3
1989        );
1990    }
1991
1992    #[test]
1993    fn count_tokens_function_call_counts_name_and_arguments() {
1994        // A function call is rendered as a tool call on an assistant message:
1995        // assistant role (9) + "get_weather" (11) + r#"{"city":"SF"}"# (13)
1996        // == 33; 33 / 3 == 11.
1997        assert_eq!(
1998            count(serde_json::json!({"input": [{
1999                "type": "function_call",
2000                "call_id": "call_1",
2001                "name": "get_weather",
2002                "arguments": r#"{"city":"SF"}"#,
2003            }]})),
2004            11
2005        );
2006    }
2007
2008    #[test]
2009    fn count_tokens_charges_one_assistant_marker_per_coalesced_turn() {
2010        // `convert_input_items_to_messages` accumulates assistant-side items
2011        // into one `PendingAssistant`, so two parallel tool calls are a single
2012        // assistant message. Charging a marker per item would invent a turn
2013        // that never reaches the prompt.
2014        let one = serde_json::json!({"input": [
2015            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""}
2016        ]});
2017        let two = serde_json::json!({"input": [
2018            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2019            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2020        ]});
2021        // assistant (9) + "aa" (2) == 11 → 3; adding "bb" (2) == 13 → 4.
2022        // The marker is paid once, not twice.
2023        assert_eq!(count(one), 3);
2024        assert_eq!(count(two), 4);
2025
2026        // Assistant text, reasoning, and a tool call in one turn: still one
2027        // marker across all three.
2028        let mixed = serde_json::json!({"input": [
2029            {"role": "assistant", "content": "aa"},
2030            {"type": "reasoning", "summary": [{"type": "summary_text", "text": "bb"}]},
2031            {"type": "function_call", "call_id": "c1", "name": "cc", "arguments": ""}
2032        ]});
2033        assert_eq!(count(mixed), 5); // 9 + 2 + 2 + 2 == 15 → 5
2034    }
2035
2036    #[test]
2037    fn count_tokens_reopens_the_assistant_turn_after_a_flush() {
2038        // A tool result ends the assistant turn, so the assistant items after
2039        // it are a second turn and pay a second marker.
2040        let two_turns = serde_json::json!({"input": [
2041            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2042            {"type": "function_call_output", "call_id": "c1", "output": ""},
2043            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2044        ]});
2045        // assistant (9) + "aa" (2) + tool (4) + assistant (9) + "bb" (2)
2046        // == 26; 26 / 3 == 8.
2047        assert_eq!(count(two_turns), 8);
2048    }
2049
2050    #[test]
2051    fn count_tokens_item_reference_does_not_split_an_assistant_turn() {
2052        // The converter skips item references without flushing, so one sitting
2053        // between two tool calls must not make them look like two turns.
2054        let split = serde_json::json!({"input": [
2055            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2056            {"type": "item_reference", "id": "item_abc"},
2057            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2058        ]});
2059        let unsplit = serde_json::json!({"input": [
2060            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2061            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2062        ]});
2063        assert_eq!(count(split), count(unsplit));
2064    }
2065
2066    #[test]
2067    fn count_tokens_unsupported_item_splits_an_assistant_turn() {
2068        // The converter flushes before skipping an unsupported variant
2069        // precisely so a later function call cannot coalesce across it. The
2070        // estimate has to agree, or it undercounts the second turn's marker.
2071        let across = serde_json::json!({"input": [
2072            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2073            {"type": "web_search_call", "id": "ws_1", "status": "completed"},
2074            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2075        ]});
2076        // Two turns: 9 + 2 + 9 + 2 == 22; 22 / 3 == 7.
2077        assert_eq!(count(across), 7);
2078    }
2079
2080    #[test]
2081    fn count_tokens_function_call_output_counts_text() {
2082        // Rendered as its own tool-role message: tool role (4) + "sunny" (5)
2083        // == 9; 9 / 3 == 3.
2084        assert_eq!(
2085            count(serde_json::json!({"input": [{
2086                "type": "function_call_output",
2087                "call_id": "call_1",
2088                "output": "sunny",
2089            }]})),
2090            3
2091        );
2092    }
2093
2094    #[test]
2095    fn count_tokens_tools_contribute() {
2096        // "get_weather" (11) + "Get weather" (11) + r#"{"type":"object"}"# (17)
2097        // == 39; 39 / 3 == 13.
2098        assert_eq!(
2099            count(serde_json::json!({
2100                "input": "",
2101                "tools": [{
2102                    "type": "function",
2103                    "name": "get_weather",
2104                    "description": "Get weather",
2105                    "parameters": {"type": "object"},
2106                }],
2107            })),
2108            13
2109        );
2110    }
2111
2112    #[test]
2113    fn count_tokens_images_contribute_nothing() {
2114        // Only the text part is measured; the image part cannot be estimated
2115        // from character length.
2116        let with_image = count(serde_json::json!({"input": [{
2117            "type": "message",
2118            "role": "user",
2119            "content": [
2120                {"type": "input_text", "text": "Describe this"},
2121                {"type": "input_image", "image_url": "https://example.com/a-very-long-url.png"},
2122            ],
2123        }]}));
2124        let without_image = count(serde_json::json!({"input": [{
2125            "type": "message",
2126            "role": "user",
2127            "content": [{"type": "input_text", "text": "Describe this"}],
2128        }]}));
2129        assert_eq!(with_image, without_image);
2130    }
2131
2132    #[test]
2133    fn count_tokens_dropped_item_variants_cost_nothing() {
2134        // Dynamo's `convert_input_items_to_messages` flushes and skips these,
2135        // so they never reach the prompt. Counting their serialized form would
2136        // bill callers for JSON scaffolding the model never sees.
2137        for item in [
2138            serde_json::json!({"type": "web_search_call", "id": "ws_1", "status": "completed"}),
2139            serde_json::json!({
2140                "type": "computer_call",
2141                "call_id": "c_1",
2142                "id": "cu_1",
2143                "action": {"type": "screenshot"},
2144                "pending_safety_checks": [],
2145                "status": "completed",
2146            }),
2147        ] {
2148            assert_eq!(
2149                count(serde_json::json!({ "input": [item.clone()] })),
2150                0,
2151                "dropped item variant should not be counted: {item}"
2152            );
2153        }
2154    }
2155
2156    #[test]
2157    fn count_tokens_counts_exactly_the_variants_the_converter_renders() {
2158        // Guards the coupling documented on `measure_item`: the explicit
2159        // arms are meant to be the same set Dynamo's converter handles. Each
2160        // variant is asserted on its own — a single assertion over an array of
2161        // all four would still pass with three of the arms deleted. If dynamo
2162        // grows support for another variant, this test should gain a case.
2163        for item in [
2164            serde_json::json!({"role": "user", "content": "Hello"}),
2165            serde_json::json!({
2166                "type": "message",
2167                "role": "user",
2168                "content": [{"type": "input_text", "text": "Hello"}],
2169            }),
2170            serde_json::json!({
2171                "type": "message",
2172                "role": "assistant",
2173                "content": [{"type": "output_text", "text": "Hi", "annotations": []}],
2174            }),
2175            serde_json::json!({
2176                "type": "function_call",
2177                "call_id": "c1",
2178                "name": "get_weather",
2179                "arguments": "{}",
2180            }),
2181            serde_json::json!({"type": "function_call_output", "call_id": "c1", "output": "sunny"}),
2182            serde_json::json!({
2183                "type": "reasoning",
2184                "summary": [{"type": "summary_text", "text": "thinking"}],
2185            }),
2186        ] {
2187            assert!(
2188                count(serde_json::json!({ "input": [item.clone()] })) > 0,
2189                "rendered variant should be counted: {item}"
2190            );
2191        }
2192    }
2193
2194    #[test]
2195    fn count_tokens_reasoning_counts_summary_only() {
2196        // The converter joins `summary` and drops everything else on the item,
2197        // so `content` and `encrypted_content` must not inflate the estimate.
2198        let summary_only = serde_json::json!({"input": [{
2199            "type": "reasoning",
2200            "summary": [{"type": "summary_text", "text": "thinking"}],
2201        }]});
2202        let with_dropped_fields = serde_json::json!({"input": [{
2203            "type": "reasoning",
2204            "summary": [{"type": "summary_text", "text": "thinking"}],
2205            "content": [{"type": "reasoning_text", "text": "a much longer private chain of thought"}],
2206            "encrypted_content": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
2207        }]});
2208
2209        // Reasoning rides on the pending assistant message:
2210        // assistant role (9) + "thinking" (8) == 17; 17 / 3 == 5.
2211        assert_eq!(count(summary_only.clone()), 5);
2212        assert_eq!(count(with_dropped_fields), count(summary_only));
2213    }
2214
2215    #[test]
2216    fn count_tokens_hosted_tools_cost_nothing() {
2217        // `convert_tools` forwards only function tools; hosted tools are
2218        // dropped, so they must not inflate the estimate.
2219        assert_eq!(
2220            count(serde_json::json!({
2221                "input": "",
2222                "tools": [{"type": "web_search"}],
2223            })),
2224            0
2225        );
2226    }
2227
2228    #[test]
2229    fn count_tokens_namespaced_tools_count_their_functions() {
2230        // `convert_tools` flattens namespaces to their bare function members,
2231        // so the members count and the namespace name does not.
2232        // "get_weather" (11) + "Get weather" (11) + r#"{"type":"object"}"# (17)
2233        // == 39; 39 / 3 == 13 — the same as the un-namespaced tool above.
2234        assert_eq!(
2235            count(serde_json::json!({
2236                "input": "",
2237                "tools": [{
2238                    "type": "namespace",
2239                    "name": "weather_ns",
2240                    "description": "Weather tools",
2241                    "tools": [{
2242                        "type": "function",
2243                        "name": "get_weather",
2244                        "description": "Get weather",
2245                        "parameters": {"type": "object"},
2246                    }],
2247                }],
2248            })),
2249            13
2250        );
2251    }
2252
2253    #[test]
2254    fn count_tokens_item_reference_contributes_nothing() {
2255        // The referenced content is held server-side and is not in this request.
2256        assert_eq!(
2257            count(serde_json::json!({"input": [{"type": "item_reference", "id": "msg_1"}]})),
2258            0
2259        );
2260    }
2261
2262    #[test]
2263    fn count_tokens_ignores_unsupported_stateful_fields() {
2264        // `previous_response_id` / `conversation` are accepted and disregarded
2265        // rather than rejected — this endpoint only estimates.
2266        assert_eq!(
2267            count(serde_json::json!({
2268                "model": "m",
2269                "input": "Hello, world!",
2270                "previous_response_id": "resp_abc123",
2271                "conversation": {"id": "conv_1"},
2272            })),
2273            5
2274        );
2275    }
2276
2277    #[test]
2278    fn count_tokens_deserializes_the_litellm_request_shape() {
2279        // The exact body LiteLLM's CountTokens handler sends:
2280        // {model, input, instructions?, tools?} with chat tools already
2281        // flattened into the Responses shape.
2282        let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2283            "model": "dynamo/deepseek-ai/deepseek-v4-pro-sglang",
2284            "input": [{"role": "user", "content": "Hello"}],
2285            "instructions": "You are helpful.",
2286            "tools": [{
2287                "type": "function",
2288                "name": "get_weather",
2289                "description": "Get weather",
2290                "parameters": {"type": "object"},
2291            }],
2292        }))
2293        .expect("LiteLLM request shape should deserialize");
2294
2295        assert_eq!(
2296            request.model.as_deref(),
2297            Some("dynamo/deepseek-ai/deepseek-v4-pro-sglang")
2298        );
2299        assert!(matches!(request.input, InputParam::Items(ref items) if items.len() == 1));
2300        assert!(request.estimate_tokens() > 0);
2301    }
2302
2303    #[test]
2304    fn count_tokens_accepts_explicit_null_input() {
2305        // `#[serde(default)]` covers an absent `input`; this covers the null
2306        // an emitter produces when it always writes the key.
2307        assert_eq!(count(serde_json::json!({"model": "m", "input": null})), 0);
2308        assert_eq!(
2309            count(serde_json::json!({
2310                "model": "m",
2311                "input": null,
2312                "instructions": "You are helpful."
2313            })),
2314            7
2315        );
2316    }
2317
2318    #[test]
2319    fn count_tokens_drops_unparseable_tools_instead_of_failing() {
2320        // A Chat-Completions-shaped `custom` tool: `Tool` models the Responses
2321        // shape (`{"type": "custom", "name": ...}`), not the nested chat one.
2322        // It must not take the whole request down with it.
2323        let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2324            "model": "m",
2325            "input": "Hello, world!",
2326            "tools": [{"type": "custom", "custom": {"name": "x"}}],
2327        }))
2328        .expect("an unparseable tool should be dropped, not rejected");
2329        assert_eq!(request.tools.as_deref(), Some(&[][..]));
2330        // Same count as the identical body with no `tools` key at all: the
2331        // dropped tool was worth 0 either way.
2332        assert_eq!(request.estimate_tokens(), 5);
2333    }
2334
2335    #[test]
2336    fn count_tokens_keeps_parseable_tools_alongside_dropped_ones() {
2337        // Dropping is per-entry, not all-or-nothing: a good function tool in
2338        // the same array still gets counted.
2339        let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2340            "model": "m",
2341            "input": "Hello, world!",
2342            "tools": [
2343                {"type": "custom", "custom": {"name": "x"}},
2344                {"type": "function", "name": "get_weather", "description": "Get weather"},
2345            ],
2346        }))
2347        .expect("a mixed tool array should deserialize");
2348        assert_eq!(request.tools.as_ref().map(Vec::len), Some(1));
2349        assert!(
2350            request.estimate_tokens()
2351                > count(serde_json::json!({"model": "m", "input": "Hello, world!"}))
2352        );
2353    }
2354
2355    #[test]
2356    fn count_tokens_distinguishes_absent_tools_from_empty_tools() {
2357        // `None` and `Some([])` both score 0, but the field must round-trip
2358        // its presence: `skip_serializing_if` relies on the distinction.
2359        let absent: CountInputTokensRequest =
2360            serde_json::from_value(serde_json::json!({"input": "hi"})).unwrap();
2361        assert_eq!(absent.tools, None);
2362        let empty: CountInputTokensRequest =
2363            serde_json::from_value(serde_json::json!({"input": "hi", "tools": []})).unwrap();
2364        assert_eq!(empty.tools.as_deref(), Some(&[][..]));
2365        let null: CountInputTokensRequest =
2366            serde_json::from_value(serde_json::json!({"input": "hi", "tools": null})).unwrap();
2367        assert_eq!(null.tools, None);
2368    }
2369
2370    #[test]
2371    fn count_tokens_response_serializes_to_the_openai_shape() {
2372        assert_eq!(
2373            serde_json::to_value(CountInputTokensResponse::new(42)).unwrap(),
2374            serde_json::json!({"object": "response.input_tokens", "input_tokens": 42})
2375        );
2376    }
2377}
2378
2379#[cfg(test)]
2380mod reasoning_effort_tests {
2381    use super::CreateResponse;
2382
2383    #[test]
2384    fn every_reasoning_effort_deserializes() {
2385        for effort in ["none", "minimal", "low", "medium", "high", "xhigh", "max"] {
2386            let body = serde_json::json!({
2387                "model": "m", "input": "hi", "reasoning": {"effort": effort}
2388            });
2389            serde_json::from_value::<CreateResponse>(body)
2390                .unwrap_or_else(|e| panic!("effort {effort} must deserialize: {e}"));
2391        }
2392    }
2393}