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 — upstream requires a present array.
416    #[serde(default)]
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 full_request_with_idless_reasoning_item_deserializes() {
1195        // The exact failure mode reported in #10963: a turn-2 `input` list
1196        // containing an echoed reasoning item that lost its `id`.
1197        let req: Result<CreateResponse, _> = serde_json::from_value(serde_json::json!({
1198            "model": "m",
1199            "input": [
1200                {"role": "user", "content": "hi"},
1201                {"type": "reasoning", "summary": [{"type": "summary_text", "text": "x"}]},
1202            ],
1203        }));
1204        assert!(
1205            req.is_ok(),
1206            "idless reasoning input should deserialize: {req:?}"
1207        );
1208    }
1209
1210    #[test]
1211    fn codex_agent_message_normalizes_to_user_message() {
1212        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1213            "input": [{
1214                "type": "agent_message",
1215                "author": "/root",
1216                "recipient": "/root/worker",
1217                "content": [
1218                    {"type": "input_text", "text": "First."},
1219                    {"type": "input_text", "text": "Second."},
1220                ],
1221            }],
1222        }))
1223        .expect("Codex agent message should deserialize");
1224
1225        let InputParam::Items(items) = req.input else {
1226            panic!("expected items");
1227        };
1228        assert!(matches!(
1229            &items[0],
1230            InputItem::EasyMessage(EasyInputMessage {
1231                role: Role::User,
1232                content: EasyInputContent::Text(text),
1233                ..
1234            }) if text == "First.\nSecond."
1235        ));
1236    }
1237
1238    #[test]
1239    fn codex_agent_message_string_content_normalizes_to_user_message() {
1240        let item: InputItem = serde_json::from_value(serde_json::json!({
1241            "type": "agent_message",
1242            "author": "/root",
1243            "recipient": "/root/worker",
1244            "content": "Return exactly OK.",
1245        }))
1246        .expect("Codex agent message with string content should deserialize");
1247
1248        assert!(matches!(
1249            item,
1250            InputItem::EasyMessage(EasyInputMessage {
1251                content: EasyInputContent::Text(text),
1252                ..
1253            }) if text == "Return exactly OK."
1254        ));
1255    }
1256
1257    #[test]
1258    fn codex_agent_message_normalizes_encrypted_content() {
1259        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1260            "input": [{
1261                "type": "agent_message",
1262                "content": [
1263                    {"type": "input_text", "text": "Payload:"},
1264                    {"type": "encrypted_content", "encrypted_content": "Return exactly OK."},
1265                ],
1266            }],
1267        }))
1268        .expect("Codex agent message with encrypted content should deserialize");
1269
1270        let InputParam::Items(items) = req.input else {
1271            panic!("expected items");
1272        };
1273        assert!(matches!(
1274            &items[0],
1275            InputItem::EasyMessage(EasyInputMessage {
1276                content: EasyInputContent::Text(text),
1277                ..
1278            }) if text == "Payload:\nReturn exactly OK."
1279        ));
1280    }
1281
1282    #[test]
1283    fn codex_agent_message_missing_content_normalizes_empty() {
1284        let item: InputItem = serde_json::from_value(serde_json::json!({
1285            "type": "agent_message",
1286            "author": "/root",
1287            "recipient": "/root/worker",
1288        }))
1289        .expect("Codex agent message without content should deserialize");
1290        assert!(matches!(
1291            item,
1292            InputItem::EasyMessage(EasyInputMessage {
1293                content: EasyInputContent::Text(text),
1294                ..
1295            }) if text.is_empty()
1296        ));
1297    }
1298
1299    #[test]
1300    fn codex_agent_message_null_content_normalizes_empty() {
1301        let item: InputItem = serde_json::from_value(serde_json::json!({
1302            "type": "agent_message",
1303            "author": "/root",
1304            "recipient": "/root/worker",
1305            "content": null,
1306        }))
1307        .expect("Codex agent message with null content should deserialize");
1308        assert!(matches!(
1309            item,
1310            InputItem::EasyMessage(EasyInputMessage {
1311                content: EasyInputContent::Text(text),
1312                ..
1313            }) if text.is_empty()
1314        ));
1315    }
1316
1317    #[test]
1318    fn relaxed_assistant_message_without_id_or_status() {
1319        let json = serde_json::json!({
1320            "type": "message",
1321            "role": "assistant",
1322            "content": [{"type": "output_text", "text": "hi"}]
1323        });
1324        let item: InputItem = serde_json::from_value(json).unwrap();
1325        match item {
1326            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1327                assert_eq!(out.role, AssistantRole::Assistant);
1328                assert!(out.id.is_none());
1329                assert!(out.status.is_none());
1330            }
1331            other => panic!("expected Item::Message(Output), got {other:?}"),
1332        }
1333    }
1334
1335    #[test]
1336    fn function_call_output_image_part_without_detail_parses() {
1337        let json = serde_json::json!({
1338            "input": [
1339                {"type": "function_call", "call_id": "c1", "name": "screenshot", "arguments": "{}"},
1340                {"type": "function_call_output", "call_id": "c1", "output": [
1341                    {"type": "input_text", "text": "captured"},
1342                    {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo="}
1343                ]}
1344            ]
1345        });
1346        let req: CreateResponse = serde_json::from_value(json).unwrap();
1347        let InputParam::Items(items) = req.input else {
1348            panic!("expected Items")
1349        };
1350        match &items[1] {
1351            InputItem::Item(Item::FunctionCallOutput(fco)) => {
1352                assert_eq!(fco.call_id, "c1");
1353                let FunctionCallOutput::Content(parts) = &fco.output else {
1354                    panic!("expected Content, got {:?}", fco.output)
1355                };
1356                assert_eq!(parts.len(), 2);
1357                match &parts[1] {
1358                    InputContent::InputImage(img) => {
1359                        assert_eq!(img.detail, ImageDetail::Auto);
1360                        assert_eq!(
1361                            img.image_url.as_deref(),
1362                            Some("data:image/png;base64,iVBORw0KGgo=")
1363                        );
1364                    }
1365                    other => panic!("expected InputImage, got {other:?}"),
1366                }
1367            }
1368            other => panic!("expected FunctionCallOutput, got {other:?}"),
1369        }
1370    }
1371
1372    #[test]
1373    fn function_call_output_image_part_with_null_detail_matches_message_content() {
1374        // `"detail": null` is accepted in message content; a tool output must not
1375        // be stricter than the message it answers.
1376        let part = serde_json::json!({
1377            "type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo=", "detail": null
1378        });
1379        let message: Item = serde_json::from_value(serde_json::json!({
1380            "type": "message", "role": "user", "content": [part]
1381        }))
1382        .unwrap();
1383        assert!(matches!(message, Item::Message(_)));
1384        let output: Item = serde_json::from_value(serde_json::json!({
1385            "type": "function_call_output", "call_id": "c1", "output": [part]
1386        }))
1387        .unwrap();
1388        let Item::FunctionCallOutput(fco) = output else {
1389            panic!("expected FunctionCallOutput, got {output:?}")
1390        };
1391        match &fco.output {
1392            FunctionCallOutput::Content(parts) => match &parts[0] {
1393                InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1394                other => panic!("expected InputImage, got {other:?}"),
1395            },
1396            other => panic!("expected Content, got {other:?}"),
1397        }
1398    }
1399
1400    #[test]
1401    fn function_call_output_from_conversions_match_upstream() {
1402        assert_eq!(
1403            FunctionCallOutput::from("ok"),
1404            FunctionCallOutput::Text("ok".to_string())
1405        );
1406        assert_eq!(
1407            FunctionCallOutput::from(String::from("ok")),
1408            FunctionCallOutput::Text("ok".to_string())
1409        );
1410        let parts = vec![InputContent::InputText(InputTextContent {
1411            text: "captured".to_string(),
1412            prompt_cache_breakpoint: None,
1413        })];
1414        let item = FunctionCallOutputItemParam {
1415            call_id: "c1".to_string(),
1416            output: parts.clone().into(),
1417            id: None,
1418            status: None,
1419        };
1420        assert_eq!(item.output, FunctionCallOutput::Content(parts));
1421    }
1422
1423    #[test]
1424    fn function_call_output_string_still_parses() {
1425        let item: Item = serde_json::from_value(serde_json::json!({
1426            "type": "function_call_output", "call_id": "c1", "output": "{\"ok\":true}"
1427        }))
1428        .unwrap();
1429        match item {
1430            Item::FunctionCallOutput(fco) => {
1431                assert!(
1432                    matches!(fco.output, FunctionCallOutput::Text(ref t) if t == "{\"ok\":true}")
1433                );
1434                assert!(fco.id.is_none() && fco.status.is_none());
1435            }
1436            other => panic!("expected FunctionCallOutput, got {other:?}"),
1437        }
1438    }
1439
1440    #[test]
1441    fn input_image_without_detail_defaults_to_auto() {
1442        let json = serde_json::json!({
1443            "type": "input_image",
1444            "image_url": "https://example.com/cat.jpg"
1445        });
1446        let content: InputContent = serde_json::from_value(json).unwrap();
1447        match content {
1448            InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1449            other => panic!("expected InputImage, got {other:?}"),
1450        }
1451    }
1452
1453    #[test]
1454    fn input_image_with_explicit_null_detail_defaults_to_auto() {
1455        let json = serde_json::json!({
1456            "type": "input_image",
1457            "image_url": "https://example.com/cat.jpg",
1458            "detail": null
1459        });
1460        let content: InputContent = serde_json::from_value(json).unwrap();
1461        match content {
1462            InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1463            other => panic!("expected InputImage, got {other:?}"),
1464        }
1465    }
1466
1467    #[test]
1468    fn assistant_message_without_content_field_deserializes() {
1469        // Bare assistant shell — no `content` field at all. Seen in real
1470        // Codex/Agents-SDK traffic on pure tool-call turns. `#[serde(default)]`
1471        // on `content` must accept omission and yield an empty vec.
1472        let json = serde_json::json!({
1473            "type": "message",
1474            "role": "assistant"
1475        });
1476        let item: InputItem = serde_json::from_value(json).unwrap();
1477        match item {
1478            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1479                assert_eq!(out.role, AssistantRole::Assistant);
1480                assert!(out.content.is_empty());
1481                assert!(out.id.is_none());
1482                assert!(out.status.is_none());
1483            }
1484            other => panic!("expected Item::Message(Output), got {other:?}"),
1485        }
1486    }
1487
1488    #[test]
1489    fn assistant_message_with_explicit_null_content_deserializes() {
1490        // Mirrors the `annotations: null` case: some serializers emit JSON null
1491        // for absent fields instead of omitting them. `Vec::deserialize` rejects
1492        // null, so `content` also needs `deserialize_null_as_empty_vec`.
1493        let json = serde_json::json!({
1494            "type": "message",
1495            "role": "assistant",
1496            "content": null
1497        });
1498        let item: InputItem = serde_json::from_value(json).unwrap();
1499        match item {
1500            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1501                assert!(out.content.is_empty());
1502            }
1503            other => panic!("expected Item::Message(Output), got {other:?}"),
1504        }
1505    }
1506
1507    #[test]
1508    fn mcp_call_item_deserializes() {
1509        // Guards against Item variant drift vs upstream — MCP item types were
1510        // added after the initial owned `Item` chain landed.
1511        let json = serde_json::json!({
1512            "type": "mcp_call",
1513            "id": "mcp_1",
1514            "server_label": "srv",
1515            "name": "t",
1516            "arguments": "{}"
1517        });
1518        let item: InputItem = serde_json::from_value(json).unwrap();
1519        assert!(matches!(item, InputItem::Item(Item::McpCall(_))));
1520    }
1521
1522    #[test]
1523    fn strict_assistant_message_still_deserializes() {
1524        let json = serde_json::json!({
1525            "type": "message",
1526            "role": "assistant",
1527            "id": "msg_1",
1528            "status": "completed",
1529            "content": [{"type": "output_text", "text": "hi", "annotations": []}]
1530        });
1531        let item: InputItem = serde_json::from_value(json).unwrap();
1532        match item {
1533            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1534                assert_eq!(out.id.as_deref(), Some("msg_1"));
1535                assert_eq!(out.status, Some(OutputStatus::Completed));
1536            }
1537            other => panic!("expected Item::Message(Output), got {other:?}"),
1538        }
1539    }
1540
1541    #[test]
1542    fn user_message_routes_to_input_variant() {
1543        let json = serde_json::json!({
1544            "type": "message",
1545            "role": "user",
1546            "content": [{"type": "input_text", "text": "hi"}]
1547        });
1548        let item: InputItem = serde_json::from_value(json).unwrap();
1549        assert!(matches!(
1550            item,
1551            InputItem::Item(Item::Message(MessageItem::Input(_)))
1552        ));
1553    }
1554
1555    #[test]
1556    fn function_call_item_still_deserializes() {
1557        let json = serde_json::json!({
1558            "type": "function_call",
1559            "call_id": "c",
1560            "name": "f",
1561            "arguments": "{}"
1562        });
1563        let item: InputItem = serde_json::from_value(json).unwrap();
1564        assert!(matches!(item, InputItem::Item(Item::FunctionCall(_))));
1565    }
1566
1567    #[test]
1568    fn easy_message_string_content_routes_to_easymessage() {
1569        let json = serde_json::json!({"role": "assistant", "content": "x"});
1570        let item: InputItem = serde_json::from_value(json).unwrap();
1571        assert!(matches!(item, InputItem::EasyMessage(_)));
1572    }
1573
1574    #[test]
1575    fn output_text_without_annotations_defaults_empty() {
1576        let json = serde_json::json!({"type": "output_text", "text": "hi"});
1577        let part: InputOutputMessageContent = serde_json::from_value(json).unwrap();
1578        match part {
1579            InputOutputMessageContent::OutputText(t) => {
1580                assert!(t.annotations.is_empty());
1581            }
1582            _ => panic!("expected OutputText"),
1583        }
1584    }
1585
1586    #[test]
1587    fn output_text_with_explicit_null_annotations_deserializes_as_empty() {
1588        // Some clients serialize absent fields as JSON null instead of omitting
1589        // them. `Vec::deserialize` would reject null; the custom deserializer
1590        // treats explicit null identically to a missing field.
1591        let json = serde_json::json!({"type": "output_text", "text": "hi", "annotations": null});
1592        let part: InputOutputMessageContent = serde_json::from_value(json).unwrap();
1593        match part {
1594            InputOutputMessageContent::OutputText(t) => {
1595                assert!(t.annotations.is_empty());
1596            }
1597            _ => panic!("expected OutputText"),
1598        }
1599    }
1600
1601    #[test]
1602    fn assistant_message_with_explicit_null_id_and_status_deserializes() {
1603        // `Option<T>` natively accepts null as `None`, so these explicit-null
1604        // fields should flow through without a custom deserializer. This test
1605        // pins that behavior against accidental regressions (e.g. if someone
1606        // switches the field type away from `Option<_>`).
1607        let json = serde_json::json!({
1608            "type": "message",
1609            "role": "assistant",
1610            "id": null,
1611            "status": null,
1612            "content": [{"type": "output_text", "text": "hi", "annotations": null}]
1613        });
1614        let item: InputItem = serde_json::from_value(json).unwrap();
1615        match item {
1616            InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1617                assert!(out.id.is_none());
1618                assert!(out.status.is_none());
1619                assert_eq!(out.content.len(), 1);
1620            }
1621            other => panic!("expected Item::Message(Output), got {other:?}"),
1622        }
1623    }
1624
1625    /// The Chat Completions spelling `max_tokens` is honored as the output cap
1626    /// rather than silently dropped (#207); the wire echo is `max_output_tokens`.
1627    #[test]
1628    fn create_response_accepts_max_tokens_as_alias_for_max_output_tokens() {
1629        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1630            "model": "m", "input": "hi", "max_tokens": 16
1631        }))
1632        .unwrap();
1633        assert_eq!(req.max_output_tokens, Some(16));
1634        let back = serde_json::to_value(&req).unwrap();
1635        assert_eq!(back["max_output_tokens"], 16);
1636        assert!(back.get("max_tokens").is_none());
1637
1638        let req: CreateResponse = serde_json::from_value(serde_json::json!({
1639            "model": "m", "input": "hi", "max_tokens": null
1640        }))
1641        .unwrap();
1642        assert_eq!(req.max_output_tokens, None);
1643
1644        // Both spellings at once is ambiguous and fails as a duplicate field.
1645        let err = serde_json::from_value::<CreateResponse>(serde_json::json!({
1646            "model": "m", "input": "hi", "max_tokens": 16, "max_output_tokens": 32
1647        }))
1648        .unwrap_err();
1649        assert!(err.to_string().contains("duplicate field"), "{err}");
1650    }
1651
1652    #[test]
1653    fn create_response_roundtrip_with_relaxed_input() {
1654        let body = serde_json::json!({
1655            "model": "m",
1656            "input": [
1657                {"type": "message", "role": "user", "content": [
1658                    {"type": "input_text", "text": "hi"}
1659                ]},
1660                {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{}"},
1661                {"type": "message", "role": "assistant", "content": [
1662                    {"type": "output_text", "text": "\n\n"}
1663                ]},
1664                {"type": "function_call_output", "call_id": "c", "output": "x"}
1665            ]
1666        });
1667
1668        let req: CreateResponse = serde_json::from_value(body).unwrap();
1669        let items = match &req.input {
1670            InputParam::Items(items) => items,
1671            _ => panic!("expected Items"),
1672        };
1673        assert_eq!(items.len(), 4);
1674        assert!(matches!(
1675            items[2],
1676            InputItem::Item(Item::Message(MessageItem::Output(_)))
1677        ));
1678    }
1679
1680    // ---- EasyInputMessage / multimodal-without-`type` regression coverage ----
1681    // See issue #9468. Before the EasyInputMessage/EasyInputContent shadow
1682    // landed, the `InputItem::EasyMessage` fallback still routed through
1683    // upstream's strict `InputImageContent` (required `detail`), so any
1684    // multimodal message that omitted the spec-default `type: "message"` would
1685    // fail with "data did not match any variant of untagged enum InputItem".
1686
1687    #[test]
1688    fn easy_message_multimodal_without_type_routes_to_easymessage() {
1689        // AIPerf's pre-PR-931 payload shape: no top-level `type`, content is a
1690        // list containing an `input_image` part with no `detail`.
1691        let json = serde_json::json!({
1692            "role": "user",
1693            "content": [
1694                {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1695            ]
1696        });
1697        let item: InputItem = serde_json::from_value(json).unwrap();
1698        match item {
1699            InputItem::EasyMessage(easy) => {
1700                assert_eq!(easy.role, Role::User);
1701                assert_eq!(easy.r#type, MessageType::Message);
1702                match easy.content {
1703                    EasyInputContent::ContentList(parts) => {
1704                        assert_eq!(parts.len(), 1);
1705                        match &parts[0] {
1706                            InputContent::InputImage(img) => {
1707                                assert_eq!(img.detail, ImageDetail::Auto);
1708                                assert_eq!(
1709                                    img.image_url.as_deref(),
1710                                    Some("data:image/png;base64,abc")
1711                                );
1712                            }
1713                            other => panic!("expected InputImage, got {other:?}"),
1714                        }
1715                    }
1716                    other => panic!("expected ContentList, got {other:?}"),
1717                }
1718            }
1719            other => panic!("expected EasyMessage, got {other:?}"),
1720        }
1721    }
1722
1723    #[test]
1724    fn easy_message_multimodal_with_explicit_null_detail() {
1725        // Same shape as above but with `detail: null` — exercises the
1726        // null-as-default path on the relaxed `InputImageContent` reached via
1727        // the EasyMessage variant.
1728        let json = serde_json::json!({
1729            "role": "user",
1730            "content": [
1731                {"type": "input_image", "image_url": "data:image/png;base64,abc", "detail": null}
1732            ]
1733        });
1734        let item: InputItem = serde_json::from_value(json).unwrap();
1735        assert!(matches!(item, InputItem::EasyMessage(_)));
1736    }
1737
1738    #[test]
1739    fn easy_message_assistant_multimodal_without_type() {
1740        // Mixed-turn shape AIPerf emits when the prior assistant turn carried
1741        // structured (non-string) content: role=assistant, content list, no
1742        // top-level `type`.
1743        let json = serde_json::json!({
1744            "role": "assistant",
1745            "content": [
1746                {"type": "input_text", "text": "ok"}
1747            ]
1748        });
1749        let item: InputItem = serde_json::from_value(json).unwrap();
1750        match item {
1751            InputItem::EasyMessage(easy) => {
1752                assert_eq!(easy.role, Role::Assistant);
1753            }
1754            other => panic!("expected EasyMessage(assistant), got {other:?}"),
1755        }
1756    }
1757
1758    #[test]
1759    fn easy_message_text_only_without_type_unchanged() {
1760        // Regression guard: the pre-existing text-only path was already
1761        // working (no multimodal content -> never hit upstream's strict
1762        // `InputImageContent`). Pin it so a future glob-shadow change can't
1763        // break it.
1764        let json = serde_json::json!({"role": "user", "content": "Hello"});
1765        let item: InputItem = serde_json::from_value(json).unwrap();
1766        match item {
1767            InputItem::EasyMessage(easy) => {
1768                assert_eq!(easy.role, Role::User);
1769                assert!(matches!(easy.content, EasyInputContent::Text(ref s) if s == "Hello"));
1770            }
1771            other => panic!("expected EasyMessage(Text), got {other:?}"),
1772        }
1773    }
1774
1775    #[test]
1776    fn easy_message_with_explicit_type_still_routes_to_item_message() {
1777        // AIPerf's post-PR-931 payload (with `type: "message"`) should still
1778        // hit the structured `Item::Message` path first — proving the existing
1779        // strict path didn't regress when EasyMessage was shadowed.
1780        let json = serde_json::json!({
1781            "type": "message",
1782            "role": "user",
1783            "content": [
1784                {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1785            ]
1786        });
1787        let item: InputItem = serde_json::from_value(json).unwrap();
1788        match item {
1789            InputItem::Item(Item::Message(MessageItem::Input(msg))) => {
1790                assert_eq!(msg.role, InputRole::User);
1791                assert_eq!(msg.content.len(), 1);
1792            }
1793            other => panic!("expected Item::Message(Input), got {other:?}"),
1794        }
1795    }
1796
1797    #[test]
1798    fn create_response_roundtrip_aiperf_pre_pr931_payload() {
1799        // End-to-end shape: the exact request body AIPerf was emitting before
1800        // PR-931 for a multi-turn multimodal conversation. Mirrors what the
1801        // HTTP frontend receives. Must deserialize without error and preserve
1802        // turn ordering.
1803        let body = serde_json::json!({
1804            "model": "Qwen/Qwen2-VL-2B-Instruct",
1805            "input": [
1806                {
1807                    "role": "user",
1808                    "content": [
1809                        {"type": "input_text", "text": "Describe"},
1810                        {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1811                    ]
1812                },
1813                {
1814                    "role": "assistant",
1815                    "content": [{"type": "input_text", "text": "ok"}]
1816                },
1817                {
1818                    "role": "user",
1819                    "content": [{"type": "input_text", "text": "Now describe a different one."}]
1820                }
1821            ]
1822        });
1823        let req: CreateResponse = serde_json::from_value(body).unwrap();
1824        let items = match &req.input {
1825            InputParam::Items(items) => items,
1826            _ => panic!("expected Items"),
1827        };
1828        assert_eq!(items.len(), 3);
1829        // All three turns must land as EasyMessage (no top-level `type`).
1830        for (idx, item) in items.iter().enumerate() {
1831            assert!(
1832                matches!(item, InputItem::EasyMessage(_)),
1833                "turn {idx} did not route to EasyMessage: {item:?}",
1834            );
1835        }
1836    }
1837
1838    // ---- count input tokens (POST /v1/responses/input_tokens) ----
1839
1840    fn count(body: serde_json::Value) -> u32 {
1841        serde_json::from_value::<CountInputTokensRequest>(body)
1842            .expect("count request should deserialize")
1843            .estimate_tokens()
1844    }
1845
1846    #[test]
1847    fn count_tokens_plain_text_input() {
1848        // user role (4) + "Hello, world!" (13) == 17; 17 / 3 == 5.
1849        assert_eq!(
1850            count(serde_json::json!({"model": "m", "input": "Hello, world!"})),
1851            5
1852        );
1853    }
1854
1855    #[test]
1856    fn count_tokens_input_is_optional() {
1857        // The count endpoint accepts a body without `input`, unlike CreateResponse.
1858        assert_eq!(count(serde_json::json!({"model": "m"})), 0);
1859    }
1860
1861    #[test]
1862    fn count_tokens_empty_input_is_zero() {
1863        assert_eq!(count(serde_json::json!({"input": ""})), 0);
1864    }
1865
1866    #[test]
1867    fn count_tokens_short_input_never_rounds_to_zero() {
1868        // Every item that reaches the prompt now carries a role marker of at
1869        // least 4, so no `input` can land under the rounding threshold. Tools
1870        // are the one remaining path: they are appended to the request rather
1871        // than rendered as a message, so they carry no marker. A one-character
1872        // function name is 1, and 1 / 3 == 0 — but content was present, so
1873        // report 1.
1874        assert_eq!(
1875            count(serde_json::json!({"tools": [{"type": "function", "name": "a"}]})),
1876            1
1877        );
1878        // For comparison, the shortest possible input clears the guard on its
1879        // role marker alone: user (4) + "Hi" (2) == 6; 6 / 3 == 2.
1880        assert_eq!(count(serde_json::json!({"input": "Hi"})), 2);
1881    }
1882
1883    #[test]
1884    fn count_tokens_instructions_contribute() {
1885        // system role (6) + "You are helpful." (16)
1886        //   + user role (4) + "Hi" (2) == 28; 28 / 3 == 9.
1887        assert_eq!(
1888            count(serde_json::json!({"input": "Hi", "instructions": "You are helpful."})),
1889            9
1890        );
1891    }
1892
1893    #[test]
1894    fn count_tokens_scores_the_two_spellings_of_a_prompt_identically() {
1895        // `TryFrom<NvCreateResponse>` turns a top-level string `input` into a
1896        // user message and `instructions` into a system message, so these two
1897        // bodies build the same chat request and must score the same. Counting
1898        // the top-level forms as bare text undercounted them by the role
1899        // markers the item forms were already charged.
1900        assert_eq!(
1901            count(serde_json::json!({"input": "Hello"})),
1902            count(serde_json::json!({"input": [{"role": "user", "content": "Hello"}]})),
1903        );
1904        assert_eq!(
1905            count(serde_json::json!({
1906                "input": "Hello",
1907                "instructions": "You are helpful."
1908            })),
1909            count(serde_json::json!({"input": [
1910                {"role": "system", "content": "You are helpful."},
1911                {"role": "user", "content": "Hello"}
1912            ]})),
1913        );
1914    }
1915
1916    #[test]
1917    fn count_tokens_easy_message_counts_role_and_content() {
1918        // user role (4) + "Hello" (5) == 9; 9 / 3 == 3.
1919        assert_eq!(
1920            count(serde_json::json!({"input": [{"role": "user", "content": "Hello"}]})),
1921            3
1922        );
1923    }
1924
1925    #[test]
1926    fn count_tokens_structured_input_message() {
1927        // user role (4) + "Hello" (5) == 9; 9 / 3 == 3.
1928        assert_eq!(
1929            count(serde_json::json!({"input": [{
1930                "type": "message",
1931                "role": "user",
1932                "content": [{"type": "input_text", "text": "Hello"}],
1933            }]})),
1934            3
1935        );
1936    }
1937
1938    #[test]
1939    fn count_tokens_function_call_counts_name_and_arguments() {
1940        // A function call is rendered as a tool call on an assistant message:
1941        // assistant role (9) + "get_weather" (11) + r#"{"city":"SF"}"# (13)
1942        // == 33; 33 / 3 == 11.
1943        assert_eq!(
1944            count(serde_json::json!({"input": [{
1945                "type": "function_call",
1946                "call_id": "call_1",
1947                "name": "get_weather",
1948                "arguments": r#"{"city":"SF"}"#,
1949            }]})),
1950            11
1951        );
1952    }
1953
1954    #[test]
1955    fn count_tokens_charges_one_assistant_marker_per_coalesced_turn() {
1956        // `convert_input_items_to_messages` accumulates assistant-side items
1957        // into one `PendingAssistant`, so two parallel tool calls are a single
1958        // assistant message. Charging a marker per item would invent a turn
1959        // that never reaches the prompt.
1960        let one = serde_json::json!({"input": [
1961            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""}
1962        ]});
1963        let two = serde_json::json!({"input": [
1964            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
1965            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
1966        ]});
1967        // assistant (9) + "aa" (2) == 11 → 3; adding "bb" (2) == 13 → 4.
1968        // The marker is paid once, not twice.
1969        assert_eq!(count(one), 3);
1970        assert_eq!(count(two), 4);
1971
1972        // Assistant text, reasoning, and a tool call in one turn: still one
1973        // marker across all three.
1974        let mixed = serde_json::json!({"input": [
1975            {"role": "assistant", "content": "aa"},
1976            {"type": "reasoning", "summary": [{"type": "summary_text", "text": "bb"}]},
1977            {"type": "function_call", "call_id": "c1", "name": "cc", "arguments": ""}
1978        ]});
1979        assert_eq!(count(mixed), 5); // 9 + 2 + 2 + 2 == 15 → 5
1980    }
1981
1982    #[test]
1983    fn count_tokens_reopens_the_assistant_turn_after_a_flush() {
1984        // A tool result ends the assistant turn, so the assistant items after
1985        // it are a second turn and pay a second marker.
1986        let two_turns = serde_json::json!({"input": [
1987            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
1988            {"type": "function_call_output", "call_id": "c1", "output": ""},
1989            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
1990        ]});
1991        // assistant (9) + "aa" (2) + tool (4) + assistant (9) + "bb" (2)
1992        // == 26; 26 / 3 == 8.
1993        assert_eq!(count(two_turns), 8);
1994    }
1995
1996    #[test]
1997    fn count_tokens_item_reference_does_not_split_an_assistant_turn() {
1998        // The converter skips item references without flushing, so one sitting
1999        // between two tool calls must not make them look like two turns.
2000        let split = serde_json::json!({"input": [
2001            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2002            {"type": "item_reference", "id": "item_abc"},
2003            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2004        ]});
2005        let unsplit = serde_json::json!({"input": [
2006            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2007            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2008        ]});
2009        assert_eq!(count(split), count(unsplit));
2010    }
2011
2012    #[test]
2013    fn count_tokens_unsupported_item_splits_an_assistant_turn() {
2014        // The converter flushes before skipping an unsupported variant
2015        // precisely so a later function call cannot coalesce across it. The
2016        // estimate has to agree, or it undercounts the second turn's marker.
2017        let across = serde_json::json!({"input": [
2018            {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2019            {"type": "web_search_call", "id": "ws_1", "status": "completed"},
2020            {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2021        ]});
2022        // Two turns: 9 + 2 + 9 + 2 == 22; 22 / 3 == 7.
2023        assert_eq!(count(across), 7);
2024    }
2025
2026    #[test]
2027    fn count_tokens_function_call_output_counts_text() {
2028        // Rendered as its own tool-role message: tool role (4) + "sunny" (5)
2029        // == 9; 9 / 3 == 3.
2030        assert_eq!(
2031            count(serde_json::json!({"input": [{
2032                "type": "function_call_output",
2033                "call_id": "call_1",
2034                "output": "sunny",
2035            }]})),
2036            3
2037        );
2038    }
2039
2040    #[test]
2041    fn count_tokens_tools_contribute() {
2042        // "get_weather" (11) + "Get weather" (11) + r#"{"type":"object"}"# (17)
2043        // == 39; 39 / 3 == 13.
2044        assert_eq!(
2045            count(serde_json::json!({
2046                "input": "",
2047                "tools": [{
2048                    "type": "function",
2049                    "name": "get_weather",
2050                    "description": "Get weather",
2051                    "parameters": {"type": "object"},
2052                }],
2053            })),
2054            13
2055        );
2056    }
2057
2058    #[test]
2059    fn count_tokens_images_contribute_nothing() {
2060        // Only the text part is measured; the image part cannot be estimated
2061        // from character length.
2062        let with_image = count(serde_json::json!({"input": [{
2063            "type": "message",
2064            "role": "user",
2065            "content": [
2066                {"type": "input_text", "text": "Describe this"},
2067                {"type": "input_image", "image_url": "https://example.com/a-very-long-url.png"},
2068            ],
2069        }]}));
2070        let without_image = count(serde_json::json!({"input": [{
2071            "type": "message",
2072            "role": "user",
2073            "content": [{"type": "input_text", "text": "Describe this"}],
2074        }]}));
2075        assert_eq!(with_image, without_image);
2076    }
2077
2078    #[test]
2079    fn count_tokens_dropped_item_variants_cost_nothing() {
2080        // Dynamo's `convert_input_items_to_messages` flushes and skips these,
2081        // so they never reach the prompt. Counting their serialized form would
2082        // bill callers for JSON scaffolding the model never sees.
2083        for item in [
2084            serde_json::json!({"type": "web_search_call", "id": "ws_1", "status": "completed"}),
2085            serde_json::json!({
2086                "type": "computer_call",
2087                "call_id": "c_1",
2088                "id": "cu_1",
2089                "action": {"type": "screenshot"},
2090                "pending_safety_checks": [],
2091                "status": "completed",
2092            }),
2093        ] {
2094            assert_eq!(
2095                count(serde_json::json!({ "input": [item.clone()] })),
2096                0,
2097                "dropped item variant should not be counted: {item}"
2098            );
2099        }
2100    }
2101
2102    #[test]
2103    fn count_tokens_counts_exactly_the_variants_the_converter_renders() {
2104        // Guards the coupling documented on `measure_item`: the explicit
2105        // arms are meant to be the same set Dynamo's converter handles. Each
2106        // variant is asserted on its own — a single assertion over an array of
2107        // all four would still pass with three of the arms deleted. If dynamo
2108        // grows support for another variant, this test should gain a case.
2109        for item in [
2110            serde_json::json!({"role": "user", "content": "Hello"}),
2111            serde_json::json!({
2112                "type": "message",
2113                "role": "user",
2114                "content": [{"type": "input_text", "text": "Hello"}],
2115            }),
2116            serde_json::json!({
2117                "type": "message",
2118                "role": "assistant",
2119                "content": [{"type": "output_text", "text": "Hi", "annotations": []}],
2120            }),
2121            serde_json::json!({
2122                "type": "function_call",
2123                "call_id": "c1",
2124                "name": "get_weather",
2125                "arguments": "{}",
2126            }),
2127            serde_json::json!({"type": "function_call_output", "call_id": "c1", "output": "sunny"}),
2128            serde_json::json!({
2129                "type": "reasoning",
2130                "summary": [{"type": "summary_text", "text": "thinking"}],
2131            }),
2132        ] {
2133            assert!(
2134                count(serde_json::json!({ "input": [item.clone()] })) > 0,
2135                "rendered variant should be counted: {item}"
2136            );
2137        }
2138    }
2139
2140    #[test]
2141    fn count_tokens_reasoning_counts_summary_only() {
2142        // The converter joins `summary` and drops everything else on the item,
2143        // so `content` and `encrypted_content` must not inflate the estimate.
2144        let summary_only = serde_json::json!({"input": [{
2145            "type": "reasoning",
2146            "summary": [{"type": "summary_text", "text": "thinking"}],
2147        }]});
2148        let with_dropped_fields = serde_json::json!({"input": [{
2149            "type": "reasoning",
2150            "summary": [{"type": "summary_text", "text": "thinking"}],
2151            "content": [{"type": "reasoning_text", "text": "a much longer private chain of thought"}],
2152            "encrypted_content": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
2153        }]});
2154
2155        // Reasoning rides on the pending assistant message:
2156        // assistant role (9) + "thinking" (8) == 17; 17 / 3 == 5.
2157        assert_eq!(count(summary_only.clone()), 5);
2158        assert_eq!(count(with_dropped_fields), count(summary_only));
2159    }
2160
2161    #[test]
2162    fn count_tokens_hosted_tools_cost_nothing() {
2163        // `convert_tools` forwards only function tools; hosted tools are
2164        // dropped, so they must not inflate the estimate.
2165        assert_eq!(
2166            count(serde_json::json!({
2167                "input": "",
2168                "tools": [{"type": "web_search"}],
2169            })),
2170            0
2171        );
2172    }
2173
2174    #[test]
2175    fn count_tokens_namespaced_tools_count_their_functions() {
2176        // `convert_tools` flattens namespaces to their bare function members,
2177        // so the members count and the namespace name does not.
2178        // "get_weather" (11) + "Get weather" (11) + r#"{"type":"object"}"# (17)
2179        // == 39; 39 / 3 == 13 — the same as the un-namespaced tool above.
2180        assert_eq!(
2181            count(serde_json::json!({
2182                "input": "",
2183                "tools": [{
2184                    "type": "namespace",
2185                    "name": "weather_ns",
2186                    "description": "Weather tools",
2187                    "tools": [{
2188                        "type": "function",
2189                        "name": "get_weather",
2190                        "description": "Get weather",
2191                        "parameters": {"type": "object"},
2192                    }],
2193                }],
2194            })),
2195            13
2196        );
2197    }
2198
2199    #[test]
2200    fn count_tokens_item_reference_contributes_nothing() {
2201        // The referenced content is held server-side and is not in this request.
2202        assert_eq!(
2203            count(serde_json::json!({"input": [{"type": "item_reference", "id": "msg_1"}]})),
2204            0
2205        );
2206    }
2207
2208    #[test]
2209    fn count_tokens_ignores_unsupported_stateful_fields() {
2210        // `previous_response_id` / `conversation` are accepted and disregarded
2211        // rather than rejected — this endpoint only estimates.
2212        assert_eq!(
2213            count(serde_json::json!({
2214                "model": "m",
2215                "input": "Hello, world!",
2216                "previous_response_id": "resp_abc123",
2217                "conversation": {"id": "conv_1"},
2218            })),
2219            5
2220        );
2221    }
2222
2223    #[test]
2224    fn count_tokens_deserializes_the_litellm_request_shape() {
2225        // The exact body LiteLLM's CountTokens handler sends:
2226        // {model, input, instructions?, tools?} with chat tools already
2227        // flattened into the Responses shape.
2228        let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2229            "model": "dynamo/deepseek-ai/deepseek-v4-pro-sglang",
2230            "input": [{"role": "user", "content": "Hello"}],
2231            "instructions": "You are helpful.",
2232            "tools": [{
2233                "type": "function",
2234                "name": "get_weather",
2235                "description": "Get weather",
2236                "parameters": {"type": "object"},
2237            }],
2238        }))
2239        .expect("LiteLLM request shape should deserialize");
2240
2241        assert_eq!(
2242            request.model.as_deref(),
2243            Some("dynamo/deepseek-ai/deepseek-v4-pro-sglang")
2244        );
2245        assert!(matches!(request.input, InputParam::Items(ref items) if items.len() == 1));
2246        assert!(request.estimate_tokens() > 0);
2247    }
2248
2249    #[test]
2250    fn count_tokens_accepts_explicit_null_input() {
2251        // `#[serde(default)]` covers an absent `input`; this covers the null
2252        // an emitter produces when it always writes the key.
2253        assert_eq!(count(serde_json::json!({"model": "m", "input": null})), 0);
2254        assert_eq!(
2255            count(serde_json::json!({
2256                "model": "m",
2257                "input": null,
2258                "instructions": "You are helpful."
2259            })),
2260            7
2261        );
2262    }
2263
2264    #[test]
2265    fn count_tokens_drops_unparseable_tools_instead_of_failing() {
2266        // A Chat-Completions-shaped `custom` tool: `Tool` models the Responses
2267        // shape (`{"type": "custom", "name": ...}`), not the nested chat one.
2268        // It must not take the whole request down with it.
2269        let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2270            "model": "m",
2271            "input": "Hello, world!",
2272            "tools": [{"type": "custom", "custom": {"name": "x"}}],
2273        }))
2274        .expect("an unparseable tool should be dropped, not rejected");
2275        assert_eq!(request.tools.as_deref(), Some(&[][..]));
2276        // Same count as the identical body with no `tools` key at all: the
2277        // dropped tool was worth 0 either way.
2278        assert_eq!(request.estimate_tokens(), 5);
2279    }
2280
2281    #[test]
2282    fn count_tokens_keeps_parseable_tools_alongside_dropped_ones() {
2283        // Dropping is per-entry, not all-or-nothing: a good function tool in
2284        // the same array still gets counted.
2285        let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2286            "model": "m",
2287            "input": "Hello, world!",
2288            "tools": [
2289                {"type": "custom", "custom": {"name": "x"}},
2290                {"type": "function", "name": "get_weather", "description": "Get weather"},
2291            ],
2292        }))
2293        .expect("a mixed tool array should deserialize");
2294        assert_eq!(request.tools.as_ref().map(Vec::len), Some(1));
2295        assert!(
2296            request.estimate_tokens()
2297                > count(serde_json::json!({"model": "m", "input": "Hello, world!"}))
2298        );
2299    }
2300
2301    #[test]
2302    fn count_tokens_distinguishes_absent_tools_from_empty_tools() {
2303        // `None` and `Some([])` both score 0, but the field must round-trip
2304        // its presence: `skip_serializing_if` relies on the distinction.
2305        let absent: CountInputTokensRequest =
2306            serde_json::from_value(serde_json::json!({"input": "hi"})).unwrap();
2307        assert_eq!(absent.tools, None);
2308        let empty: CountInputTokensRequest =
2309            serde_json::from_value(serde_json::json!({"input": "hi", "tools": []})).unwrap();
2310        assert_eq!(empty.tools.as_deref(), Some(&[][..]));
2311        let null: CountInputTokensRequest =
2312            serde_json::from_value(serde_json::json!({"input": "hi", "tools": null})).unwrap();
2313        assert_eq!(null.tools, None);
2314    }
2315
2316    #[test]
2317    fn count_tokens_response_serializes_to_the_openai_shape() {
2318        assert_eq!(
2319            serde_json::to_value(CountInputTokensResponse::new(42)).unwrap(),
2320            serde_json::json!({"object": "response.input_tokens", "input_tokens": 42})
2321        );
2322    }
2323}
2324
2325#[cfg(test)]
2326mod reasoning_effort_tests {
2327    use super::CreateResponse;
2328
2329    #[test]
2330    fn every_reasoning_effort_deserializes() {
2331        for effort in ["none", "minimal", "low", "medium", "high", "xhigh", "max"] {
2332            let body = serde_json::json!({
2333                "model": "m", "input": "hi", "reasoning": {"effort": effort}
2334            });
2335            serde_json::from_value::<CreateResponse>(body)
2336                .unwrap_or_else(|e| panic!("effort {effort} must deserialize: {e}"));
2337        }
2338    }
2339}