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, deserialize_with = "deserialize_null_as_empty_vec")]
417 pub summary: Vec<SummaryPart>,
418 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub content: Option<Vec<ReasoningTextContent>>,
420 #[serde(default, skip_serializing_if = "Option::is_none")]
421 pub encrypted_content: Option<String>,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 pub status: Option<OutputStatus>,
424}
425
426#[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 reasoning_input_summary_normalizes_empty_values_and_preserves_fields() {
1195 let populated = serde_json::json!([{"type": "summary_text", "text": "summary"}]);
1196 for (summary, expected_summary) in [
1197 (serde_json::Value::Null, serde_json::json!([])),
1198 (serde_json::json!([]), serde_json::json!([])),
1199 (populated.clone(), populated),
1200 ] {
1201 let mut input = serde_json::json!({
1202 "type": "reasoning",
1203 "id": "rs_1",
1204 "summary": summary,
1205 "content": [{"text": "reasoning content"}],
1206 "encrypted_content": "AB==",
1207 "status": "completed",
1208 });
1209 let request: CreateResponse = serde_json::from_value(serde_json::json!({
1210 "model": "example-model", "input": [input.clone()]
1211 }))
1212 .expect("reasoning summary should deserialize");
1213 input["summary"] = expected_summary;
1214 let serialized = serde_json::to_value(request).unwrap();
1215 assert_eq!(serialized["input"][0], input);
1216 }
1217 }
1218
1219 #[test]
1220 fn reasoning_input_summary_rejects_invalid_values() {
1221 for summary in [
1222 serde_json::json!(false),
1223 serde_json::json!([null]),
1224 serde_json::json!([{"type": "summary_text"}]),
1225 serde_json::json!([{"type": "output_text", "text": "summary"}]),
1226 ] {
1227 assert!(
1228 serde_json::from_value::<InputItem>(serde_json::json!({
1229 "type": "reasoning", "summary": summary
1230 }))
1231 .is_err(),
1232 "invalid summary must be rejected: {summary}"
1233 );
1234 }
1235 }
1236
1237 #[test]
1238 fn reasoning_output_summary_null_remains_invalid() {
1239 let mut output = serde_json::json!({
1240 "type": "reasoning", "id": "rs_1", "summary": null
1241 });
1242 assert!(serde_json::from_value::<OutputItem>(output.clone()).is_err());
1243 output["summary"] = serde_json::json!([]);
1244 assert!(serde_json::from_value::<OutputItem>(output).is_ok());
1245 }
1246
1247 #[test]
1248 fn full_request_with_idless_reasoning_item_deserializes() {
1249 let req: Result<CreateResponse, _> = serde_json::from_value(serde_json::json!({
1252 "model": "m",
1253 "input": [
1254 {"role": "user", "content": "hi"},
1255 {"type": "reasoning", "summary": [{"type": "summary_text", "text": "x"}]},
1256 ],
1257 }));
1258 assert!(
1259 req.is_ok(),
1260 "idless reasoning input should deserialize: {req:?}"
1261 );
1262 }
1263
1264 #[test]
1265 fn codex_agent_message_normalizes_to_user_message() {
1266 let req: CreateResponse = serde_json::from_value(serde_json::json!({
1267 "input": [{
1268 "type": "agent_message",
1269 "author": "/root",
1270 "recipient": "/root/worker",
1271 "content": [
1272 {"type": "input_text", "text": "First."},
1273 {"type": "input_text", "text": "Second."},
1274 ],
1275 }],
1276 }))
1277 .expect("Codex agent message should deserialize");
1278
1279 let InputParam::Items(items) = req.input else {
1280 panic!("expected items");
1281 };
1282 assert!(matches!(
1283 &items[0],
1284 InputItem::EasyMessage(EasyInputMessage {
1285 role: Role::User,
1286 content: EasyInputContent::Text(text),
1287 ..
1288 }) if text == "First.\nSecond."
1289 ));
1290 }
1291
1292 #[test]
1293 fn codex_agent_message_string_content_normalizes_to_user_message() {
1294 let item: InputItem = serde_json::from_value(serde_json::json!({
1295 "type": "agent_message",
1296 "author": "/root",
1297 "recipient": "/root/worker",
1298 "content": "Return exactly OK.",
1299 }))
1300 .expect("Codex agent message with string content should deserialize");
1301
1302 assert!(matches!(
1303 item,
1304 InputItem::EasyMessage(EasyInputMessage {
1305 content: EasyInputContent::Text(text),
1306 ..
1307 }) if text == "Return exactly OK."
1308 ));
1309 }
1310
1311 #[test]
1312 fn codex_agent_message_normalizes_encrypted_content() {
1313 let req: CreateResponse = serde_json::from_value(serde_json::json!({
1314 "input": [{
1315 "type": "agent_message",
1316 "content": [
1317 {"type": "input_text", "text": "Payload:"},
1318 {"type": "encrypted_content", "encrypted_content": "Return exactly OK."},
1319 ],
1320 }],
1321 }))
1322 .expect("Codex agent message with encrypted content should deserialize");
1323
1324 let InputParam::Items(items) = req.input else {
1325 panic!("expected items");
1326 };
1327 assert!(matches!(
1328 &items[0],
1329 InputItem::EasyMessage(EasyInputMessage {
1330 content: EasyInputContent::Text(text),
1331 ..
1332 }) if text == "Payload:\nReturn exactly OK."
1333 ));
1334 }
1335
1336 #[test]
1337 fn codex_agent_message_missing_content_normalizes_empty() {
1338 let item: InputItem = serde_json::from_value(serde_json::json!({
1339 "type": "agent_message",
1340 "author": "/root",
1341 "recipient": "/root/worker",
1342 }))
1343 .expect("Codex agent message without content should deserialize");
1344 assert!(matches!(
1345 item,
1346 InputItem::EasyMessage(EasyInputMessage {
1347 content: EasyInputContent::Text(text),
1348 ..
1349 }) if text.is_empty()
1350 ));
1351 }
1352
1353 #[test]
1354 fn codex_agent_message_null_content_normalizes_empty() {
1355 let item: InputItem = serde_json::from_value(serde_json::json!({
1356 "type": "agent_message",
1357 "author": "/root",
1358 "recipient": "/root/worker",
1359 "content": null,
1360 }))
1361 .expect("Codex agent message with null content should deserialize");
1362 assert!(matches!(
1363 item,
1364 InputItem::EasyMessage(EasyInputMessage {
1365 content: EasyInputContent::Text(text),
1366 ..
1367 }) if text.is_empty()
1368 ));
1369 }
1370
1371 #[test]
1372 fn relaxed_assistant_message_without_id_or_status() {
1373 let json = serde_json::json!({
1374 "type": "message",
1375 "role": "assistant",
1376 "content": [{"type": "output_text", "text": "hi"}]
1377 });
1378 let item: InputItem = serde_json::from_value(json).unwrap();
1379 match item {
1380 InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1381 assert_eq!(out.role, AssistantRole::Assistant);
1382 assert!(out.id.is_none());
1383 assert!(out.status.is_none());
1384 }
1385 other => panic!("expected Item::Message(Output), got {other:?}"),
1386 }
1387 }
1388
1389 #[test]
1390 fn function_call_output_image_part_without_detail_parses() {
1391 let json = serde_json::json!({
1392 "input": [
1393 {"type": "function_call", "call_id": "c1", "name": "screenshot", "arguments": "{}"},
1394 {"type": "function_call_output", "call_id": "c1", "output": [
1395 {"type": "input_text", "text": "captured"},
1396 {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo="}
1397 ]}
1398 ]
1399 });
1400 let req: CreateResponse = serde_json::from_value(json).unwrap();
1401 let InputParam::Items(items) = req.input else {
1402 panic!("expected Items")
1403 };
1404 match &items[1] {
1405 InputItem::Item(Item::FunctionCallOutput(fco)) => {
1406 assert_eq!(fco.call_id, "c1");
1407 let FunctionCallOutput::Content(parts) = &fco.output else {
1408 panic!("expected Content, got {:?}", fco.output)
1409 };
1410 assert_eq!(parts.len(), 2);
1411 match &parts[1] {
1412 InputContent::InputImage(img) => {
1413 assert_eq!(img.detail, ImageDetail::Auto);
1414 assert_eq!(
1415 img.image_url.as_deref(),
1416 Some("data:image/png;base64,iVBORw0KGgo=")
1417 );
1418 }
1419 other => panic!("expected InputImage, got {other:?}"),
1420 }
1421 }
1422 other => panic!("expected FunctionCallOutput, got {other:?}"),
1423 }
1424 }
1425
1426 #[test]
1427 fn function_call_output_image_part_with_null_detail_matches_message_content() {
1428 let part = serde_json::json!({
1431 "type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo=", "detail": null
1432 });
1433 let message: Item = serde_json::from_value(serde_json::json!({
1434 "type": "message", "role": "user", "content": [part]
1435 }))
1436 .unwrap();
1437 assert!(matches!(message, Item::Message(_)));
1438 let output: Item = serde_json::from_value(serde_json::json!({
1439 "type": "function_call_output", "call_id": "c1", "output": [part]
1440 }))
1441 .unwrap();
1442 let Item::FunctionCallOutput(fco) = output else {
1443 panic!("expected FunctionCallOutput, got {output:?}")
1444 };
1445 match &fco.output {
1446 FunctionCallOutput::Content(parts) => match &parts[0] {
1447 InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1448 other => panic!("expected InputImage, got {other:?}"),
1449 },
1450 other => panic!("expected Content, got {other:?}"),
1451 }
1452 }
1453
1454 #[test]
1455 fn function_call_output_from_conversions_match_upstream() {
1456 assert_eq!(
1457 FunctionCallOutput::from("ok"),
1458 FunctionCallOutput::Text("ok".to_string())
1459 );
1460 assert_eq!(
1461 FunctionCallOutput::from(String::from("ok")),
1462 FunctionCallOutput::Text("ok".to_string())
1463 );
1464 let parts = vec![InputContent::InputText(InputTextContent {
1465 text: "captured".to_string(),
1466 prompt_cache_breakpoint: None,
1467 })];
1468 let item = FunctionCallOutputItemParam {
1469 call_id: "c1".to_string(),
1470 output: parts.clone().into(),
1471 id: None,
1472 status: None,
1473 };
1474 assert_eq!(item.output, FunctionCallOutput::Content(parts));
1475 }
1476
1477 #[test]
1478 fn function_call_output_string_still_parses() {
1479 let item: Item = serde_json::from_value(serde_json::json!({
1480 "type": "function_call_output", "call_id": "c1", "output": "{\"ok\":true}"
1481 }))
1482 .unwrap();
1483 match item {
1484 Item::FunctionCallOutput(fco) => {
1485 assert!(
1486 matches!(fco.output, FunctionCallOutput::Text(ref t) if t == "{\"ok\":true}")
1487 );
1488 assert!(fco.id.is_none() && fco.status.is_none());
1489 }
1490 other => panic!("expected FunctionCallOutput, got {other:?}"),
1491 }
1492 }
1493
1494 #[test]
1495 fn input_image_without_detail_defaults_to_auto() {
1496 let json = serde_json::json!({
1497 "type": "input_image",
1498 "image_url": "https://example.com/cat.jpg"
1499 });
1500 let content: InputContent = serde_json::from_value(json).unwrap();
1501 match content {
1502 InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1503 other => panic!("expected InputImage, got {other:?}"),
1504 }
1505 }
1506
1507 #[test]
1508 fn input_image_with_explicit_null_detail_defaults_to_auto() {
1509 let json = serde_json::json!({
1510 "type": "input_image",
1511 "image_url": "https://example.com/cat.jpg",
1512 "detail": null
1513 });
1514 let content: InputContent = serde_json::from_value(json).unwrap();
1515 match content {
1516 InputContent::InputImage(img) => assert_eq!(img.detail, ImageDetail::Auto),
1517 other => panic!("expected InputImage, got {other:?}"),
1518 }
1519 }
1520
1521 #[test]
1522 fn assistant_message_without_content_field_deserializes() {
1523 let json = serde_json::json!({
1527 "type": "message",
1528 "role": "assistant"
1529 });
1530 let item: InputItem = serde_json::from_value(json).unwrap();
1531 match item {
1532 InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1533 assert_eq!(out.role, AssistantRole::Assistant);
1534 assert!(out.content.is_empty());
1535 assert!(out.id.is_none());
1536 assert!(out.status.is_none());
1537 }
1538 other => panic!("expected Item::Message(Output), got {other:?}"),
1539 }
1540 }
1541
1542 #[test]
1543 fn assistant_message_with_explicit_null_content_deserializes() {
1544 let json = serde_json::json!({
1548 "type": "message",
1549 "role": "assistant",
1550 "content": null
1551 });
1552 let item: InputItem = serde_json::from_value(json).unwrap();
1553 match item {
1554 InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1555 assert!(out.content.is_empty());
1556 }
1557 other => panic!("expected Item::Message(Output), got {other:?}"),
1558 }
1559 }
1560
1561 #[test]
1562 fn mcp_call_item_deserializes() {
1563 let json = serde_json::json!({
1566 "type": "mcp_call",
1567 "id": "mcp_1",
1568 "server_label": "srv",
1569 "name": "t",
1570 "arguments": "{}"
1571 });
1572 let item: InputItem = serde_json::from_value(json).unwrap();
1573 assert!(matches!(item, InputItem::Item(Item::McpCall(_))));
1574 }
1575
1576 #[test]
1577 fn strict_assistant_message_still_deserializes() {
1578 let json = serde_json::json!({
1579 "type": "message",
1580 "role": "assistant",
1581 "id": "msg_1",
1582 "status": "completed",
1583 "content": [{"type": "output_text", "text": "hi", "annotations": []}]
1584 });
1585 let item: InputItem = serde_json::from_value(json).unwrap();
1586 match item {
1587 InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1588 assert_eq!(out.id.as_deref(), Some("msg_1"));
1589 assert_eq!(out.status, Some(OutputStatus::Completed));
1590 }
1591 other => panic!("expected Item::Message(Output), got {other:?}"),
1592 }
1593 }
1594
1595 #[test]
1596 fn user_message_routes_to_input_variant() {
1597 let json = serde_json::json!({
1598 "type": "message",
1599 "role": "user",
1600 "content": [{"type": "input_text", "text": "hi"}]
1601 });
1602 let item: InputItem = serde_json::from_value(json).unwrap();
1603 assert!(matches!(
1604 item,
1605 InputItem::Item(Item::Message(MessageItem::Input(_)))
1606 ));
1607 }
1608
1609 #[test]
1610 fn function_call_item_still_deserializes() {
1611 let json = serde_json::json!({
1612 "type": "function_call",
1613 "call_id": "c",
1614 "name": "f",
1615 "arguments": "{}"
1616 });
1617 let item: InputItem = serde_json::from_value(json).unwrap();
1618 assert!(matches!(item, InputItem::Item(Item::FunctionCall(_))));
1619 }
1620
1621 #[test]
1622 fn easy_message_string_content_routes_to_easymessage() {
1623 let json = serde_json::json!({"role": "assistant", "content": "x"});
1624 let item: InputItem = serde_json::from_value(json).unwrap();
1625 assert!(matches!(item, InputItem::EasyMessage(_)));
1626 }
1627
1628 #[test]
1629 fn output_text_without_annotations_defaults_empty() {
1630 let json = serde_json::json!({"type": "output_text", "text": "hi"});
1631 let part: InputOutputMessageContent = serde_json::from_value(json).unwrap();
1632 match part {
1633 InputOutputMessageContent::OutputText(t) => {
1634 assert!(t.annotations.is_empty());
1635 }
1636 _ => panic!("expected OutputText"),
1637 }
1638 }
1639
1640 #[test]
1641 fn output_text_with_explicit_null_annotations_deserializes_as_empty() {
1642 let json = serde_json::json!({"type": "output_text", "text": "hi", "annotations": null});
1646 let part: InputOutputMessageContent = serde_json::from_value(json).unwrap();
1647 match part {
1648 InputOutputMessageContent::OutputText(t) => {
1649 assert!(t.annotations.is_empty());
1650 }
1651 _ => panic!("expected OutputText"),
1652 }
1653 }
1654
1655 #[test]
1656 fn assistant_message_with_explicit_null_id_and_status_deserializes() {
1657 let json = serde_json::json!({
1662 "type": "message",
1663 "role": "assistant",
1664 "id": null,
1665 "status": null,
1666 "content": [{"type": "output_text", "text": "hi", "annotations": null}]
1667 });
1668 let item: InputItem = serde_json::from_value(json).unwrap();
1669 match item {
1670 InputItem::Item(Item::Message(MessageItem::Output(out))) => {
1671 assert!(out.id.is_none());
1672 assert!(out.status.is_none());
1673 assert_eq!(out.content.len(), 1);
1674 }
1675 other => panic!("expected Item::Message(Output), got {other:?}"),
1676 }
1677 }
1678
1679 #[test]
1682 fn create_response_accepts_max_tokens_as_alias_for_max_output_tokens() {
1683 let req: CreateResponse = serde_json::from_value(serde_json::json!({
1684 "model": "m", "input": "hi", "max_tokens": 16
1685 }))
1686 .unwrap();
1687 assert_eq!(req.max_output_tokens, Some(16));
1688 let back = serde_json::to_value(&req).unwrap();
1689 assert_eq!(back["max_output_tokens"], 16);
1690 assert!(back.get("max_tokens").is_none());
1691
1692 let req: CreateResponse = serde_json::from_value(serde_json::json!({
1693 "model": "m", "input": "hi", "max_tokens": null
1694 }))
1695 .unwrap();
1696 assert_eq!(req.max_output_tokens, None);
1697
1698 let err = serde_json::from_value::<CreateResponse>(serde_json::json!({
1700 "model": "m", "input": "hi", "max_tokens": 16, "max_output_tokens": 32
1701 }))
1702 .unwrap_err();
1703 assert!(err.to_string().contains("duplicate field"), "{err}");
1704 }
1705
1706 #[test]
1707 fn create_response_roundtrip_with_relaxed_input() {
1708 let body = serde_json::json!({
1709 "model": "m",
1710 "input": [
1711 {"type": "message", "role": "user", "content": [
1712 {"type": "input_text", "text": "hi"}
1713 ]},
1714 {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{}"},
1715 {"type": "message", "role": "assistant", "content": [
1716 {"type": "output_text", "text": "\n\n"}
1717 ]},
1718 {"type": "function_call_output", "call_id": "c", "output": "x"}
1719 ]
1720 });
1721
1722 let req: CreateResponse = serde_json::from_value(body).unwrap();
1723 let items = match &req.input {
1724 InputParam::Items(items) => items,
1725 _ => panic!("expected Items"),
1726 };
1727 assert_eq!(items.len(), 4);
1728 assert!(matches!(
1729 items[2],
1730 InputItem::Item(Item::Message(MessageItem::Output(_)))
1731 ));
1732 }
1733
1734 #[test]
1742 fn easy_message_multimodal_without_type_routes_to_easymessage() {
1743 let json = serde_json::json!({
1746 "role": "user",
1747 "content": [
1748 {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1749 ]
1750 });
1751 let item: InputItem = serde_json::from_value(json).unwrap();
1752 match item {
1753 InputItem::EasyMessage(easy) => {
1754 assert_eq!(easy.role, Role::User);
1755 assert_eq!(easy.r#type, MessageType::Message);
1756 match easy.content {
1757 EasyInputContent::ContentList(parts) => {
1758 assert_eq!(parts.len(), 1);
1759 match &parts[0] {
1760 InputContent::InputImage(img) => {
1761 assert_eq!(img.detail, ImageDetail::Auto);
1762 assert_eq!(
1763 img.image_url.as_deref(),
1764 Some("data:image/png;base64,abc")
1765 );
1766 }
1767 other => panic!("expected InputImage, got {other:?}"),
1768 }
1769 }
1770 other => panic!("expected ContentList, got {other:?}"),
1771 }
1772 }
1773 other => panic!("expected EasyMessage, got {other:?}"),
1774 }
1775 }
1776
1777 #[test]
1778 fn easy_message_multimodal_with_explicit_null_detail() {
1779 let json = serde_json::json!({
1783 "role": "user",
1784 "content": [
1785 {"type": "input_image", "image_url": "data:image/png;base64,abc", "detail": null}
1786 ]
1787 });
1788 let item: InputItem = serde_json::from_value(json).unwrap();
1789 assert!(matches!(item, InputItem::EasyMessage(_)));
1790 }
1791
1792 #[test]
1793 fn easy_message_assistant_multimodal_without_type() {
1794 let json = serde_json::json!({
1798 "role": "assistant",
1799 "content": [
1800 {"type": "input_text", "text": "ok"}
1801 ]
1802 });
1803 let item: InputItem = serde_json::from_value(json).unwrap();
1804 match item {
1805 InputItem::EasyMessage(easy) => {
1806 assert_eq!(easy.role, Role::Assistant);
1807 }
1808 other => panic!("expected EasyMessage(assistant), got {other:?}"),
1809 }
1810 }
1811
1812 #[test]
1813 fn easy_message_text_only_without_type_unchanged() {
1814 let json = serde_json::json!({"role": "user", "content": "Hello"});
1819 let item: InputItem = serde_json::from_value(json).unwrap();
1820 match item {
1821 InputItem::EasyMessage(easy) => {
1822 assert_eq!(easy.role, Role::User);
1823 assert!(matches!(easy.content, EasyInputContent::Text(ref s) if s == "Hello"));
1824 }
1825 other => panic!("expected EasyMessage(Text), got {other:?}"),
1826 }
1827 }
1828
1829 #[test]
1830 fn easy_message_with_explicit_type_still_routes_to_item_message() {
1831 let json = serde_json::json!({
1835 "type": "message",
1836 "role": "user",
1837 "content": [
1838 {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1839 ]
1840 });
1841 let item: InputItem = serde_json::from_value(json).unwrap();
1842 match item {
1843 InputItem::Item(Item::Message(MessageItem::Input(msg))) => {
1844 assert_eq!(msg.role, InputRole::User);
1845 assert_eq!(msg.content.len(), 1);
1846 }
1847 other => panic!("expected Item::Message(Input), got {other:?}"),
1848 }
1849 }
1850
1851 #[test]
1852 fn create_response_roundtrip_aiperf_pre_pr931_payload() {
1853 let body = serde_json::json!({
1858 "model": "Qwen/Qwen2-VL-2B-Instruct",
1859 "input": [
1860 {
1861 "role": "user",
1862 "content": [
1863 {"type": "input_text", "text": "Describe"},
1864 {"type": "input_image", "image_url": "data:image/png;base64,abc"}
1865 ]
1866 },
1867 {
1868 "role": "assistant",
1869 "content": [{"type": "input_text", "text": "ok"}]
1870 },
1871 {
1872 "role": "user",
1873 "content": [{"type": "input_text", "text": "Now describe a different one."}]
1874 }
1875 ]
1876 });
1877 let req: CreateResponse = serde_json::from_value(body).unwrap();
1878 let items = match &req.input {
1879 InputParam::Items(items) => items,
1880 _ => panic!("expected Items"),
1881 };
1882 assert_eq!(items.len(), 3);
1883 for (idx, item) in items.iter().enumerate() {
1885 assert!(
1886 matches!(item, InputItem::EasyMessage(_)),
1887 "turn {idx} did not route to EasyMessage: {item:?}",
1888 );
1889 }
1890 }
1891
1892 fn count(body: serde_json::Value) -> u32 {
1895 serde_json::from_value::<CountInputTokensRequest>(body)
1896 .expect("count request should deserialize")
1897 .estimate_tokens()
1898 }
1899
1900 #[test]
1901 fn count_tokens_plain_text_input() {
1902 assert_eq!(
1904 count(serde_json::json!({"model": "m", "input": "Hello, world!"})),
1905 5
1906 );
1907 }
1908
1909 #[test]
1910 fn count_tokens_input_is_optional() {
1911 assert_eq!(count(serde_json::json!({"model": "m"})), 0);
1913 }
1914
1915 #[test]
1916 fn count_tokens_empty_input_is_zero() {
1917 assert_eq!(count(serde_json::json!({"input": ""})), 0);
1918 }
1919
1920 #[test]
1921 fn count_tokens_short_input_never_rounds_to_zero() {
1922 assert_eq!(
1929 count(serde_json::json!({"tools": [{"type": "function", "name": "a"}]})),
1930 1
1931 );
1932 assert_eq!(count(serde_json::json!({"input": "Hi"})), 2);
1935 }
1936
1937 #[test]
1938 fn count_tokens_instructions_contribute() {
1939 assert_eq!(
1942 count(serde_json::json!({"input": "Hi", "instructions": "You are helpful."})),
1943 9
1944 );
1945 }
1946
1947 #[test]
1948 fn count_tokens_scores_the_two_spellings_of_a_prompt_identically() {
1949 assert_eq!(
1955 count(serde_json::json!({"input": "Hello"})),
1956 count(serde_json::json!({"input": [{"role": "user", "content": "Hello"}]})),
1957 );
1958 assert_eq!(
1959 count(serde_json::json!({
1960 "input": "Hello",
1961 "instructions": "You are helpful."
1962 })),
1963 count(serde_json::json!({"input": [
1964 {"role": "system", "content": "You are helpful."},
1965 {"role": "user", "content": "Hello"}
1966 ]})),
1967 );
1968 }
1969
1970 #[test]
1971 fn count_tokens_easy_message_counts_role_and_content() {
1972 assert_eq!(
1974 count(serde_json::json!({"input": [{"role": "user", "content": "Hello"}]})),
1975 3
1976 );
1977 }
1978
1979 #[test]
1980 fn count_tokens_structured_input_message() {
1981 assert_eq!(
1983 count(serde_json::json!({"input": [{
1984 "type": "message",
1985 "role": "user",
1986 "content": [{"type": "input_text", "text": "Hello"}],
1987 }]})),
1988 3
1989 );
1990 }
1991
1992 #[test]
1993 fn count_tokens_function_call_counts_name_and_arguments() {
1994 assert_eq!(
1998 count(serde_json::json!({"input": [{
1999 "type": "function_call",
2000 "call_id": "call_1",
2001 "name": "get_weather",
2002 "arguments": r#"{"city":"SF"}"#,
2003 }]})),
2004 11
2005 );
2006 }
2007
2008 #[test]
2009 fn count_tokens_charges_one_assistant_marker_per_coalesced_turn() {
2010 let one = serde_json::json!({"input": [
2015 {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""}
2016 ]});
2017 let two = serde_json::json!({"input": [
2018 {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2019 {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2020 ]});
2021 assert_eq!(count(one), 3);
2024 assert_eq!(count(two), 4);
2025
2026 let mixed = serde_json::json!({"input": [
2029 {"role": "assistant", "content": "aa"},
2030 {"type": "reasoning", "summary": [{"type": "summary_text", "text": "bb"}]},
2031 {"type": "function_call", "call_id": "c1", "name": "cc", "arguments": ""}
2032 ]});
2033 assert_eq!(count(mixed), 5); }
2035
2036 #[test]
2037 fn count_tokens_reopens_the_assistant_turn_after_a_flush() {
2038 let two_turns = serde_json::json!({"input": [
2041 {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2042 {"type": "function_call_output", "call_id": "c1", "output": ""},
2043 {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2044 ]});
2045 assert_eq!(count(two_turns), 8);
2048 }
2049
2050 #[test]
2051 fn count_tokens_item_reference_does_not_split_an_assistant_turn() {
2052 let split = serde_json::json!({"input": [
2055 {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2056 {"type": "item_reference", "id": "item_abc"},
2057 {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2058 ]});
2059 let unsplit = serde_json::json!({"input": [
2060 {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2061 {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2062 ]});
2063 assert_eq!(count(split), count(unsplit));
2064 }
2065
2066 #[test]
2067 fn count_tokens_unsupported_item_splits_an_assistant_turn() {
2068 let across = serde_json::json!({"input": [
2072 {"type": "function_call", "call_id": "c1", "name": "aa", "arguments": ""},
2073 {"type": "web_search_call", "id": "ws_1", "status": "completed"},
2074 {"type": "function_call", "call_id": "c2", "name": "bb", "arguments": ""}
2075 ]});
2076 assert_eq!(count(across), 7);
2078 }
2079
2080 #[test]
2081 fn count_tokens_function_call_output_counts_text() {
2082 assert_eq!(
2085 count(serde_json::json!({"input": [{
2086 "type": "function_call_output",
2087 "call_id": "call_1",
2088 "output": "sunny",
2089 }]})),
2090 3
2091 );
2092 }
2093
2094 #[test]
2095 fn count_tokens_tools_contribute() {
2096 assert_eq!(
2099 count(serde_json::json!({
2100 "input": "",
2101 "tools": [{
2102 "type": "function",
2103 "name": "get_weather",
2104 "description": "Get weather",
2105 "parameters": {"type": "object"},
2106 }],
2107 })),
2108 13
2109 );
2110 }
2111
2112 #[test]
2113 fn count_tokens_images_contribute_nothing() {
2114 let with_image = count(serde_json::json!({"input": [{
2117 "type": "message",
2118 "role": "user",
2119 "content": [
2120 {"type": "input_text", "text": "Describe this"},
2121 {"type": "input_image", "image_url": "https://example.com/a-very-long-url.png"},
2122 ],
2123 }]}));
2124 let without_image = count(serde_json::json!({"input": [{
2125 "type": "message",
2126 "role": "user",
2127 "content": [{"type": "input_text", "text": "Describe this"}],
2128 }]}));
2129 assert_eq!(with_image, without_image);
2130 }
2131
2132 #[test]
2133 fn count_tokens_dropped_item_variants_cost_nothing() {
2134 for item in [
2138 serde_json::json!({"type": "web_search_call", "id": "ws_1", "status": "completed"}),
2139 serde_json::json!({
2140 "type": "computer_call",
2141 "call_id": "c_1",
2142 "id": "cu_1",
2143 "action": {"type": "screenshot"},
2144 "pending_safety_checks": [],
2145 "status": "completed",
2146 }),
2147 ] {
2148 assert_eq!(
2149 count(serde_json::json!({ "input": [item.clone()] })),
2150 0,
2151 "dropped item variant should not be counted: {item}"
2152 );
2153 }
2154 }
2155
2156 #[test]
2157 fn count_tokens_counts_exactly_the_variants_the_converter_renders() {
2158 for item in [
2164 serde_json::json!({"role": "user", "content": "Hello"}),
2165 serde_json::json!({
2166 "type": "message",
2167 "role": "user",
2168 "content": [{"type": "input_text", "text": "Hello"}],
2169 }),
2170 serde_json::json!({
2171 "type": "message",
2172 "role": "assistant",
2173 "content": [{"type": "output_text", "text": "Hi", "annotations": []}],
2174 }),
2175 serde_json::json!({
2176 "type": "function_call",
2177 "call_id": "c1",
2178 "name": "get_weather",
2179 "arguments": "{}",
2180 }),
2181 serde_json::json!({"type": "function_call_output", "call_id": "c1", "output": "sunny"}),
2182 serde_json::json!({
2183 "type": "reasoning",
2184 "summary": [{"type": "summary_text", "text": "thinking"}],
2185 }),
2186 ] {
2187 assert!(
2188 count(serde_json::json!({ "input": [item.clone()] })) > 0,
2189 "rendered variant should be counted: {item}"
2190 );
2191 }
2192 }
2193
2194 #[test]
2195 fn count_tokens_reasoning_counts_summary_only() {
2196 let summary_only = serde_json::json!({"input": [{
2199 "type": "reasoning",
2200 "summary": [{"type": "summary_text", "text": "thinking"}],
2201 }]});
2202 let with_dropped_fields = serde_json::json!({"input": [{
2203 "type": "reasoning",
2204 "summary": [{"type": "summary_text", "text": "thinking"}],
2205 "content": [{"type": "reasoning_text", "text": "a much longer private chain of thought"}],
2206 "encrypted_content": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
2207 }]});
2208
2209 assert_eq!(count(summary_only.clone()), 5);
2212 assert_eq!(count(with_dropped_fields), count(summary_only));
2213 }
2214
2215 #[test]
2216 fn count_tokens_hosted_tools_cost_nothing() {
2217 assert_eq!(
2220 count(serde_json::json!({
2221 "input": "",
2222 "tools": [{"type": "web_search"}],
2223 })),
2224 0
2225 );
2226 }
2227
2228 #[test]
2229 fn count_tokens_namespaced_tools_count_their_functions() {
2230 assert_eq!(
2235 count(serde_json::json!({
2236 "input": "",
2237 "tools": [{
2238 "type": "namespace",
2239 "name": "weather_ns",
2240 "description": "Weather tools",
2241 "tools": [{
2242 "type": "function",
2243 "name": "get_weather",
2244 "description": "Get weather",
2245 "parameters": {"type": "object"},
2246 }],
2247 }],
2248 })),
2249 13
2250 );
2251 }
2252
2253 #[test]
2254 fn count_tokens_item_reference_contributes_nothing() {
2255 assert_eq!(
2257 count(serde_json::json!({"input": [{"type": "item_reference", "id": "msg_1"}]})),
2258 0
2259 );
2260 }
2261
2262 #[test]
2263 fn count_tokens_ignores_unsupported_stateful_fields() {
2264 assert_eq!(
2267 count(serde_json::json!({
2268 "model": "m",
2269 "input": "Hello, world!",
2270 "previous_response_id": "resp_abc123",
2271 "conversation": {"id": "conv_1"},
2272 })),
2273 5
2274 );
2275 }
2276
2277 #[test]
2278 fn count_tokens_deserializes_the_litellm_request_shape() {
2279 let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2283 "model": "dynamo/deepseek-ai/deepseek-v4-pro-sglang",
2284 "input": [{"role": "user", "content": "Hello"}],
2285 "instructions": "You are helpful.",
2286 "tools": [{
2287 "type": "function",
2288 "name": "get_weather",
2289 "description": "Get weather",
2290 "parameters": {"type": "object"},
2291 }],
2292 }))
2293 .expect("LiteLLM request shape should deserialize");
2294
2295 assert_eq!(
2296 request.model.as_deref(),
2297 Some("dynamo/deepseek-ai/deepseek-v4-pro-sglang")
2298 );
2299 assert!(matches!(request.input, InputParam::Items(ref items) if items.len() == 1));
2300 assert!(request.estimate_tokens() > 0);
2301 }
2302
2303 #[test]
2304 fn count_tokens_accepts_explicit_null_input() {
2305 assert_eq!(count(serde_json::json!({"model": "m", "input": null})), 0);
2308 assert_eq!(
2309 count(serde_json::json!({
2310 "model": "m",
2311 "input": null,
2312 "instructions": "You are helpful."
2313 })),
2314 7
2315 );
2316 }
2317
2318 #[test]
2319 fn count_tokens_drops_unparseable_tools_instead_of_failing() {
2320 let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2324 "model": "m",
2325 "input": "Hello, world!",
2326 "tools": [{"type": "custom", "custom": {"name": "x"}}],
2327 }))
2328 .expect("an unparseable tool should be dropped, not rejected");
2329 assert_eq!(request.tools.as_deref(), Some(&[][..]));
2330 assert_eq!(request.estimate_tokens(), 5);
2333 }
2334
2335 #[test]
2336 fn count_tokens_keeps_parseable_tools_alongside_dropped_ones() {
2337 let request: CountInputTokensRequest = serde_json::from_value(serde_json::json!({
2340 "model": "m",
2341 "input": "Hello, world!",
2342 "tools": [
2343 {"type": "custom", "custom": {"name": "x"}},
2344 {"type": "function", "name": "get_weather", "description": "Get weather"},
2345 ],
2346 }))
2347 .expect("a mixed tool array should deserialize");
2348 assert_eq!(request.tools.as_ref().map(Vec::len), Some(1));
2349 assert!(
2350 request.estimate_tokens()
2351 > count(serde_json::json!({"model": "m", "input": "Hello, world!"}))
2352 );
2353 }
2354
2355 #[test]
2356 fn count_tokens_distinguishes_absent_tools_from_empty_tools() {
2357 let absent: CountInputTokensRequest =
2360 serde_json::from_value(serde_json::json!({"input": "hi"})).unwrap();
2361 assert_eq!(absent.tools, None);
2362 let empty: CountInputTokensRequest =
2363 serde_json::from_value(serde_json::json!({"input": "hi", "tools": []})).unwrap();
2364 assert_eq!(empty.tools.as_deref(), Some(&[][..]));
2365 let null: CountInputTokensRequest =
2366 serde_json::from_value(serde_json::json!({"input": "hi", "tools": null})).unwrap();
2367 assert_eq!(null.tools, None);
2368 }
2369
2370 #[test]
2371 fn count_tokens_response_serializes_to_the_openai_shape() {
2372 assert_eq!(
2373 serde_json::to_value(CountInputTokensResponse::new(42)).unwrap(),
2374 serde_json::json!({"object": "response.input_tokens", "input_tokens": 42})
2375 );
2376 }
2377}
2378
2379#[cfg(test)]
2380mod reasoning_effort_tests {
2381 use super::CreateResponse;
2382
2383 #[test]
2384 fn every_reasoning_effort_deserializes() {
2385 for effort in ["none", "minimal", "low", "medium", "high", "xhigh", "max"] {
2386 let body = serde_json::json!({
2387 "model": "m", "input": "hi", "reasoning": {"effort": effort}
2388 });
2389 serde_json::from_value::<CreateResponse>(body)
2390 .unwrap_or_else(|e| panic!("effort {effort} must deserialize: {e}"));
2391 }
2392 }
2393}