1use std::collections::HashMap;
32
33use serde::{Deserialize, Serialize, de};
34
35pub use async_openai::types::responses::*;
39
40#[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 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
79pub use crate::types::ImageDetail;
81pub use crate::types::ReasoningEffort;
82pub use crate::types::ResponseFormatJsonSchema;
83
84pub type Input = InputParam;
86pub type PromptConfig = Prompt;
87pub type TextConfig = ResponseTextParam;
88pub type TextResponseFormat = TextResponseFormatConfiguration;
89
90pub type ResponseStream = std::pin::Pin<
92 Box<dyn futures::Stream<Item = Result<ResponseStreamEvent, crate::error::OpenAIError>> + Send>,
93>;
94
95pub 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
129fn 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
146fn 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
159fn 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#[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#[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#[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
238pub use async_openai::types::responses::InputContent as UpstreamInputContent;
243
244#[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#[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#[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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
294#[serde(untagged)]
295pub enum EasyInputContent {
296 Text(String),
298 ContentList(Vec<InputContent>),
300}
301
302impl Default for EasyInputContent {
303 fn default() -> Self {
304 Self::Text(String::new())
305 }
306}
307
308#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
315#[serde(untagged)]
316pub enum FunctionCallOutput {
317 Text(String),
319 Content(Vec<InputContent>),
321}
322
323impl 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#[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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
361pub struct EasyInputMessage {
362 #[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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
386#[serde(untagged)]
387pub enum MessageItem {
388 Output(InputOutputMessage),
391 Input(InputMessage),
393}
394
395#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
411pub struct InputReasoningItem {
412 #[serde(default, skip_serializing_if = "Option::is_none")]
414 pub id: Option<String>,
415 #[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#[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#[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 pub tools: Vec<RequestTool>,
458 #[serde(skip_serializing_if = "Option::is_none")]
459 pub status: Option<OutputStatus>,
460}
461
462#[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#[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#[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#[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 #[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 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
658pub const RESPONSE_INPUT_TOKENS_OBJECT: &str = "response.input_tokens";
664
665#[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, 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
709fn 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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
746pub struct CountInputTokensResponse {
747 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 pub fn estimate_tokens(&self) -> u32 {
772 let mut total_len: usize = 0;
773
774 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
808fn 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
827const TOOL_ROLE_LEN: usize = 4;
833
834enum GroupEffect {
836 Assistant,
839 Flush,
841 Skip,
843}
844
845fn 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
879fn measure_input_item(item: &InputItem) -> (GroupEffect, usize) {
884 match item {
885 InputItem::ItemReference(_) => (GroupEffect::Skip, 0),
889 InputItem::EasyMessage(message) => {
890 let content = estimate_easy_content_len(&message.content);
891 match message.role {
892 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
909fn 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 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 Item::FunctionCall(call) => (
947 GroupEffect::Assistant,
948 call.name.len() + call.arguments.len(),
949 ),
950 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 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 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
1019fn 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 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 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 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 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 #[test]
1148 fn reasoning_input_without_id_deserializes() {
1149 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 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 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 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 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 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 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 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 #[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 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 #[test]
1688 fn easy_message_multimodal_without_type_routes_to_easymessage() {
1689 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 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 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 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 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 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 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 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 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 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 assert_eq!(
1875 count(serde_json::json!({"tools": [{"type": "function", "name": "a"}]})),
1876 1
1877 );
1878 assert_eq!(count(serde_json::json!({"input": "Hi"})), 2);
1881 }
1882
1883 #[test]
1884 fn count_tokens_instructions_contribute() {
1885 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 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 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 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 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 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 assert_eq!(count(one), 3);
1970 assert_eq!(count(two), 4);
1971
1972 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); }
1981
1982 #[test]
1983 fn count_tokens_reopens_the_assistant_turn_after_a_flush() {
1984 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 assert_eq!(count(two_turns), 8);
1994 }
1995
1996 #[test]
1997 fn count_tokens_item_reference_does_not_split_an_assistant_turn() {
1998 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 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 assert_eq!(count(across), 7);
2024 }
2025
2026 #[test]
2027 fn count_tokens_function_call_output_counts_text() {
2028 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(request.estimate_tokens(), 5);
2279 }
2280
2281 #[test]
2282 fn count_tokens_keeps_parseable_tools_alongside_dropped_ones() {
2283 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 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}