mirror of
https://github.com/openai/codex.git
synced 2026-11-26 23:40:43 +00:00
Support audio input
This commit is contained in:
@@ -113,9 +113,8 @@ impl ContextManager {
|
||||
}
|
||||
|
||||
/// Returns the history prepared for sending to the model. This applies a proper
|
||||
/// normalization and drops un-suited items. When `input_modalities` does not
|
||||
/// include `InputModality::Image`, images are stripped from messages and tool
|
||||
/// outputs.
|
||||
/// normalization and drops un-suited items. Unsupported media content is
|
||||
/// stripped from messages and tool outputs according to `input_modalities`.
|
||||
pub(crate) fn for_prompt(mut self, input_modalities: &[InputModality]) -> Vec<ResponseItem> {
|
||||
self.normalize_history(input_modalities);
|
||||
self.items
|
||||
@@ -365,8 +364,8 @@ impl ContextManager {
|
||||
// all outputs must have a corresponding function/tool call
|
||||
normalize::remove_orphan_outputs(&mut self.items);
|
||||
|
||||
// strip images when model does not support them
|
||||
normalize::strip_images_when_unsupported(input_modalities, &mut self.items);
|
||||
// strip unsupported media content before sending history to the model
|
||||
normalize::strip_unsupported_media_content(input_modalities, &mut self.items);
|
||||
}
|
||||
|
||||
fn process_item(&self, item: &ResponseItem, policy: TruncationPolicy) -> ResponseItem {
|
||||
|
||||
@@ -10,6 +10,7 @@ use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageDetail;
|
||||
use codex_protocol::models::InputAudio;
|
||||
use codex_protocol::models::LocalShellAction;
|
||||
use codex_protocol::models::LocalShellExecAction;
|
||||
use codex_protocol::models::LocalShellStatus;
|
||||
@@ -513,6 +514,85 @@ fn for_prompt_strips_images_when_model_does_not_support_images() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_prompt_strips_audio_when_model_does_not_support_audio() {
|
||||
let items = vec![
|
||||
ResponseItem::FunctionCall {
|
||||
id: None,
|
||||
name: "audio_tool".to_string(),
|
||||
namespace: None,
|
||||
arguments: "{}".to_string(),
|
||||
call_id: "call-1".to_string(),
|
||||
},
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: "call-1".to_string(),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "audio result".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
input_audio: InputAudio {
|
||||
data: "UklGRg==".to_string(),
|
||||
format: "wav".to_string(),
|
||||
},
|
||||
},
|
||||
]),
|
||||
},
|
||||
];
|
||||
let history = create_history_with_items(items);
|
||||
let default_modalities = default_input_modalities();
|
||||
let stripped = history.clone().for_prompt(&default_modalities);
|
||||
|
||||
assert_eq!(
|
||||
stripped,
|
||||
vec![
|
||||
ResponseItem::FunctionCall {
|
||||
id: None,
|
||||
name: "audio_tool".to_string(),
|
||||
namespace: None,
|
||||
arguments: "{}".to_string(),
|
||||
call_id: "call-1".to_string(),
|
||||
},
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: "call-1".to_string(),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "audio result".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "audio content omitted because you do not support audio input"
|
||||
.to_string(),
|
||||
},
|
||||
]),
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
let audio_modalities = vec![
|
||||
InputModality::Text,
|
||||
InputModality::Image,
|
||||
InputModality::Audio,
|
||||
];
|
||||
let with_audio = history.for_prompt(&audio_modalities);
|
||||
assert_eq!(
|
||||
with_audio[1],
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: "call-1".to_string(),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "audio result".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
input_audio: InputAudio {
|
||||
data: "UklGRg==".to_string(),
|
||||
format: "wav".to_string(),
|
||||
},
|
||||
},
|
||||
]),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_prompt_preserves_image_generation_calls_when_images_are_supported() {
|
||||
let history = create_history_with_items(vec![
|
||||
@@ -1048,6 +1128,46 @@ fn record_items_truncates_function_call_output_content() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_items_omits_over_budget_audio_content() {
|
||||
let mut history = ContextManager::new();
|
||||
let audio_data = "A".repeat(1_000);
|
||||
let item = ResponseItem::FunctionCallOutput {
|
||||
call_id: "call-audio".to_string(),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
input_audio: InputAudio {
|
||||
data: audio_data.clone(),
|
||||
format: "wav".to_string(),
|
||||
},
|
||||
},
|
||||
]),
|
||||
};
|
||||
|
||||
history.record_items([&item], TruncationPolicy::Bytes(32));
|
||||
|
||||
assert_eq!(history.items.len(), 1);
|
||||
match &history.items[0] {
|
||||
ResponseItem::FunctionCallOutput { output, .. } => {
|
||||
assert_eq!(
|
||||
output,
|
||||
&FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text:
|
||||
"[omitted 1 audio item because its size exceeds the output truncation budget]"
|
||||
.to_string(),
|
||||
},
|
||||
])
|
||||
);
|
||||
assert!(
|
||||
!format!("{output:?}").contains(&audio_data),
|
||||
"over-budget audio data should not be retained"
|
||||
);
|
||||
}
|
||||
other => panic!("unexpected history item: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_items_truncates_custom_tool_call_output_content() {
|
||||
let mut history = ContextManager::new();
|
||||
|
||||
@@ -10,6 +10,8 @@ use tracing::info;
|
||||
|
||||
const IMAGE_CONTENT_OMITTED_PLACEHOLDER: &str =
|
||||
"image content omitted because you do not support image input";
|
||||
const AUDIO_CONTENT_OMITTED_PLACEHOLDER: &str =
|
||||
"audio content omitted because you do not support audio input";
|
||||
|
||||
pub(crate) fn ensure_call_outputs_present(items: &mut Vec<ResponseItem>) {
|
||||
// Collect synthetic outputs to insert immediately after their calls.
|
||||
@@ -290,14 +292,14 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip image content from messages and tool outputs when the model does not support images.
|
||||
/// When `input_modalities` contains `InputModality::Image`, no stripping is performed.
|
||||
pub(crate) fn strip_images_when_unsupported(
|
||||
/// Strip unsupported media content from messages and tool outputs.
|
||||
pub(crate) fn strip_unsupported_media_content(
|
||||
input_modalities: &[InputModality],
|
||||
items: &mut [ResponseItem],
|
||||
) {
|
||||
let supports_images = input_modalities.contains(&InputModality::Image);
|
||||
if supports_images {
|
||||
let supports_audio = input_modalities.contains(&InputModality::Audio);
|
||||
if supports_images && supports_audio {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -307,7 +309,7 @@ pub(crate) fn strip_images_when_unsupported(
|
||||
let mut normalized_content = Vec::with_capacity(content.len());
|
||||
for content_item in content.iter() {
|
||||
match content_item {
|
||||
ContentItem::InputImage { .. } => {
|
||||
ContentItem::InputImage { .. } if !supports_images => {
|
||||
normalized_content.push(ContentItem::InputText {
|
||||
text: IMAGE_CONTENT_OMITTED_PLACEHOLDER.to_string(),
|
||||
});
|
||||
@@ -323,20 +325,29 @@ pub(crate) fn strip_images_when_unsupported(
|
||||
let mut normalized_content_items = Vec::with_capacity(content_items.len());
|
||||
for content_item in content_items.iter() {
|
||||
match content_item {
|
||||
FunctionCallOutputContentItem::InputImage { .. } => {
|
||||
FunctionCallOutputContentItem::InputImage { .. }
|
||||
if !supports_images =>
|
||||
{
|
||||
normalized_content_items.push(
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: IMAGE_CONTENT_OMITTED_PLACEHOLDER.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
FunctionCallOutputContentItem::InputAudio { .. } if !supports_audio => {
|
||||
normalized_content_items.push(
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: AUDIO_CONTENT_OMITTED_PLACEHOLDER.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
_ => normalized_content_items.push(content_item.clone()),
|
||||
}
|
||||
}
|
||||
*content_items = normalized_content_items;
|
||||
}
|
||||
}
|
||||
ResponseItem::ImageGenerationCall { result, .. } => {
|
||||
ResponseItem::ImageGenerationCall { result, .. } if !supports_images => {
|
||||
result.clear();
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -582,13 +582,8 @@ async fn execute_mcp_tool_call(
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("tool call error: {e:?}"))?;
|
||||
let result = sanitize_mcp_tool_result_for_model(
|
||||
turn_context
|
||||
.model_info
|
||||
.input_modalities
|
||||
.contains(&InputModality::Image),
|
||||
Ok(result),
|
||||
)?;
|
||||
let result =
|
||||
sanitize_mcp_tool_result_for_model(&turn_context.model_info.input_modalities, Ok(result))?;
|
||||
Ok(maybe_request_codex_apps_auth_elicitation(
|
||||
sess,
|
||||
turn_context,
|
||||
@@ -776,36 +771,61 @@ async fn maybe_mark_thread_memory_mode_polluted(
|
||||
}
|
||||
|
||||
fn sanitize_mcp_tool_result_for_model(
|
||||
supports_image_input: bool,
|
||||
input_modalities: &[InputModality],
|
||||
result: Result<CallToolResult, String>,
|
||||
) -> Result<CallToolResult, String> {
|
||||
if supports_image_input {
|
||||
return result;
|
||||
}
|
||||
let supports_image_input = input_modalities.contains(&InputModality::Image);
|
||||
let supports_audio_input = input_modalities.contains(&InputModality::Audio);
|
||||
|
||||
result.map(|call_tool_result| CallToolResult {
|
||||
content: call_tool_result
|
||||
.content
|
||||
.iter()
|
||||
.map(|block| {
|
||||
if let Some(content_type) = block.get("type").and_then(serde_json::Value::as_str)
|
||||
&& content_type == "image"
|
||||
{
|
||||
return serde_json::json!({
|
||||
"type": "text",
|
||||
"text": "<image content omitted because you do not support image input>",
|
||||
});
|
||||
}
|
||||
result.and_then(|call_tool_result| {
|
||||
if !supports_audio_input
|
||||
&& !has_non_null_structured_content(&call_tool_result)
|
||||
&& call_tool_result
|
||||
.content
|
||||
.iter()
|
||||
.any(|block| block.get("type").and_then(serde_json::Value::as_str) == Some("audio"))
|
||||
{
|
||||
return Err(
|
||||
"audio content returned by MCP tool but the selected model does not support audio input"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
block.clone()
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
structured_content: call_tool_result.structured_content,
|
||||
is_error: call_tool_result.is_error,
|
||||
meta: call_tool_result.meta,
|
||||
if supports_image_input {
|
||||
return Ok(call_tool_result);
|
||||
}
|
||||
|
||||
Ok(CallToolResult {
|
||||
content: call_tool_result
|
||||
.content
|
||||
.iter()
|
||||
.map(|block| {
|
||||
if let Some(content_type) = block.get("type").and_then(serde_json::Value::as_str)
|
||||
&& content_type == "image"
|
||||
{
|
||||
return serde_json::json!({
|
||||
"type": "text",
|
||||
"text": "<image content omitted because you do not support image input>",
|
||||
});
|
||||
}
|
||||
|
||||
block.clone()
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
structured_content: call_tool_result.structured_content,
|
||||
is_error: call_tool_result.is_error,
|
||||
meta: call_tool_result.meta,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn has_non_null_structured_content(call_tool_result: &CallToolResult) -> bool {
|
||||
call_tool_result
|
||||
.structured_content
|
||||
.as_ref()
|
||||
.is_some_and(|structured_content| !structured_content.is_null())
|
||||
}
|
||||
|
||||
fn truncate_mcp_tool_result_for_event(
|
||||
result: &Result<CallToolResult, String>,
|
||||
) -> Result<CallToolResult, String> {
|
||||
|
||||
@@ -924,7 +924,7 @@ fn sanitize_mcp_tool_result_for_model_rewrites_image_content() {
|
||||
meta: None,
|
||||
});
|
||||
|
||||
let got = sanitize_mcp_tool_result_for_model(/*supports_image_input*/ false, result)
|
||||
let got = sanitize_mcp_tool_result_for_model(&[InputModality::Text], result)
|
||||
.expect("sanitized result");
|
||||
|
||||
assert_eq!(
|
||||
@@ -956,7 +956,7 @@ fn sanitize_mcp_tool_result_for_model_preserves_image_when_supported() {
|
||||
};
|
||||
|
||||
let got = sanitize_mcp_tool_result_for_model(
|
||||
/*supports_image_input*/ true,
|
||||
&[InputModality::Text, InputModality::Image],
|
||||
Ok(original.clone()),
|
||||
)
|
||||
.expect("unsanitized result");
|
||||
@@ -964,6 +964,73 @@ fn sanitize_mcp_tool_result_for_model_preserves_image_when_supported() {
|
||||
assert_eq!(got, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_mcp_tool_result_for_model_rejects_audio_when_unsupported() {
|
||||
let result = Ok(CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "audio",
|
||||
"data": "UklGRg==",
|
||||
"mimeType": "audio/wav",
|
||||
})],
|
||||
structured_content: None,
|
||||
is_error: Some(false),
|
||||
meta: None,
|
||||
});
|
||||
|
||||
let err = sanitize_mcp_tool_result_for_model(&[InputModality::Text], result)
|
||||
.expect_err("unsupported audio should fail");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"audio content returned by MCP tool but the selected model does not support audio input"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_mcp_tool_result_for_model_preserves_audio_when_supported() {
|
||||
let original = CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "audio",
|
||||
"data": "UklGRg==",
|
||||
"mimeType": "audio/wav",
|
||||
})],
|
||||
structured_content: None,
|
||||
is_error: Some(false),
|
||||
meta: Some(serde_json::json!({"k": "v"})),
|
||||
};
|
||||
|
||||
let got = sanitize_mcp_tool_result_for_model(
|
||||
&[
|
||||
InputModality::Text,
|
||||
InputModality::Image,
|
||||
InputModality::Audio,
|
||||
],
|
||||
Ok(original.clone()),
|
||||
)
|
||||
.expect("supported audio should remain unchanged");
|
||||
|
||||
assert_eq!(got, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_mcp_tool_result_for_model_lets_structured_content_take_precedence_over_audio() {
|
||||
let original = CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "audio",
|
||||
"data": "UklGRg==",
|
||||
"mimeType": "audio/wav",
|
||||
})],
|
||||
structured_content: Some(serde_json::json!({"answer": "structured"})),
|
||||
is_error: Some(false),
|
||||
meta: None,
|
||||
};
|
||||
|
||||
let got = sanitize_mcp_tool_result_for_model(&[InputModality::Text], Ok(original.clone()))
|
||||
.expect("structured content should take precedence");
|
||||
|
||||
assert_eq!(got, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_mcp_tool_result_for_event_preserves_small_result() {
|
||||
let original = CallToolResult {
|
||||
|
||||
@@ -7,8 +7,7 @@ use std::collections::BTreeMap;
|
||||
pub(crate) fn create_code_mode_tool(
|
||||
enabled_tools: &[CodeModeToolDefinition],
|
||||
namespace_descriptions: &BTreeMap<String, codex_code_mode::ToolNamespaceDescription>,
|
||||
code_mode_only: bool,
|
||||
deferred_tools_available: bool,
|
||||
options: codex_code_mode::ExecToolDescriptionOptions,
|
||||
) -> ToolSpec {
|
||||
const CODE_MODE_FREEFORM_GRAMMAR: &str = r#"
|
||||
start: pragma_source | plain_source
|
||||
@@ -25,8 +24,7 @@ SOURCE: /[\s\S]+/
|
||||
description: codex_code_mode::build_exec_tool_description(
|
||||
enabled_tools,
|
||||
namespace_descriptions,
|
||||
code_mode_only,
|
||||
deferred_tools_available,
|
||||
options,
|
||||
),
|
||||
format: FreeformToolFormat {
|
||||
r#type: "grammar".to_string(),
|
||||
@@ -57,16 +55,22 @@ mod tests {
|
||||
create_code_mode_tool(
|
||||
&enabled_tools,
|
||||
&BTreeMap::new(),
|
||||
/*code_mode_only*/ true,
|
||||
/*deferred_tools_available*/ false,
|
||||
codex_code_mode::ExecToolDescriptionOptions {
|
||||
code_mode_only: true,
|
||||
deferred_tools_available: false,
|
||||
supports_audio_input: false,
|
||||
},
|
||||
),
|
||||
ToolSpec::Freeform(FreeformTool {
|
||||
name: codex_code_mode::PUBLIC_TOOL_NAME.to_string(),
|
||||
description: codex_code_mode::build_exec_tool_description(
|
||||
&enabled_tools,
|
||||
&BTreeMap::new(),
|
||||
/*code_mode_only*/ true,
|
||||
/*deferred_tools_available*/ false
|
||||
codex_code_mode::ExecToolDescriptionOptions {
|
||||
code_mode_only: true,
|
||||
deferred_tools_available: false,
|
||||
supports_audio_input: false,
|
||||
}
|
||||
),
|
||||
format: FreeformToolFormat {
|
||||
r#type: "grammar".to_string(),
|
||||
|
||||
@@ -14,6 +14,7 @@ use codex_code_mode::RuntimeResponse;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::openai_models::InputModality;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -168,6 +169,9 @@ pub(super) async fn handle_runtime_response(
|
||||
match response {
|
||||
RuntimeResponse::Yielded { content_items, .. } => {
|
||||
let mut content_items = into_function_call_output_content_items(content_items);
|
||||
if let Some(output) = unsupported_audio_output(exec.turn.as_ref(), &content_items) {
|
||||
return Ok(output);
|
||||
}
|
||||
sanitize_runtime_image_detail(exec.turn.as_ref(), &mut content_items);
|
||||
content_items = truncate_code_mode_result(content_items, max_output_tokens);
|
||||
prepend_script_status(&mut content_items, &script_status, started_at.elapsed());
|
||||
@@ -175,6 +179,9 @@ pub(super) async fn handle_runtime_response(
|
||||
}
|
||||
RuntimeResponse::Terminated { content_items, .. } => {
|
||||
let mut content_items = into_function_call_output_content_items(content_items);
|
||||
if let Some(output) = unsupported_audio_output(exec.turn.as_ref(), &content_items) {
|
||||
return Ok(output);
|
||||
}
|
||||
sanitize_runtime_image_detail(exec.turn.as_ref(), &mut content_items);
|
||||
content_items = truncate_code_mode_result(content_items, max_output_tokens);
|
||||
prepend_script_status(&mut content_items, &script_status, started_at.elapsed());
|
||||
@@ -187,12 +194,15 @@ pub(super) async fn handle_runtime_response(
|
||||
..
|
||||
} => {
|
||||
let mut content_items = into_function_call_output_content_items(content_items);
|
||||
sanitize_runtime_image_detail(exec.turn.as_ref(), &mut content_items);
|
||||
exec.session
|
||||
.services
|
||||
.code_mode_service
|
||||
.replace_stored_values(stored_values)
|
||||
.await;
|
||||
if let Some(output) = unsupported_audio_output(exec.turn.as_ref(), &content_items) {
|
||||
return Ok(output);
|
||||
}
|
||||
sanitize_runtime_image_detail(exec.turn.as_ref(), &mut content_items);
|
||||
let success = error_text.is_none();
|
||||
if let Some(error_text) = error_text {
|
||||
content_items.push(FunctionCallOutputContentItem::InputText {
|
||||
@@ -209,6 +219,29 @@ pub(super) async fn handle_runtime_response(
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_audio_output(
|
||||
turn: &TurnContext,
|
||||
items: &[FunctionCallOutputContentItem],
|
||||
) -> Option<FunctionToolOutput> {
|
||||
let supports_audio = turn
|
||||
.model_info
|
||||
.input_modalities
|
||||
.contains(&InputModality::Audio);
|
||||
if supports_audio
|
||||
|| !items
|
||||
.iter()
|
||||
.any(|item| matches!(item, FunctionCallOutputContentItem::InputAudio { .. }))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(FunctionToolOutput::from_text(
|
||||
"audio content emitted by code mode but the selected model does not support audio input"
|
||||
.to_string(),
|
||||
Some(false),
|
||||
))
|
||||
}
|
||||
|
||||
fn sanitize_runtime_image_detail(turn: &TurnContext, items: &mut [FunctionCallOutputContentItem]) {
|
||||
sanitize_image_detail_items(can_request_original_image_detail(&turn.model_info), items);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,14 @@ impl IntoProtocol<FunctionCallOutputContentItem>
|
||||
.or(Some(DEFAULT_IMAGE_DETAIL)),
|
||||
}
|
||||
}
|
||||
codex_code_mode::FunctionCallOutputContentItem::InputAudio { input_audio } => {
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
input_audio: codex_protocol::models::InputAudio {
|
||||
data: input_audio.data,
|
||||
format: input_audio.format,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,8 +253,11 @@ fn build_code_mode_executors(
|
||||
create_code_mode_tool(
|
||||
&enabled_tools,
|
||||
&namespace_descriptions,
|
||||
config.code_mode_only_enabled,
|
||||
deferred_tools_available,
|
||||
codex_code_mode::ExecToolDescriptionOptions {
|
||||
code_mode_only: config.code_mode_only_enabled,
|
||||
deferred_tools_available,
|
||||
supports_audio_input: config.supports_audio_input,
|
||||
},
|
||||
),
|
||||
code_mode_nested_tool_specs,
|
||||
)),
|
||||
|
||||
@@ -2352,6 +2352,70 @@ fn code_mode_exec_description_omits_nested_tool_details_when_not_code_mode_only(
|
||||
assert!(!description.contains("### `view_image`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_exec_audio_helper_docs_require_audio_input_support() {
|
||||
let unsupported_model_info = model_info();
|
||||
let mut supported_model_info = unsupported_model_info.clone();
|
||||
supported_model_info.input_modalities = vec![
|
||||
InputModality::Text,
|
||||
InputModality::Image,
|
||||
InputModality::Audio,
|
||||
];
|
||||
let mut features = Features::with_defaults();
|
||||
features.enable(Feature::CodeMode);
|
||||
let available_models = Vec::new();
|
||||
let unsupported_tools_config = ToolsConfig::new(&ToolsConfigParams {
|
||||
model_info: &unsupported_model_info,
|
||||
available_models: &available_models,
|
||||
features: &features,
|
||||
image_generation_tool_auth_allowed: true,
|
||||
web_search_mode: Some(WebSearchMode::Cached),
|
||||
session_source: SessionSource::Cli,
|
||||
permission_profile: &PermissionProfile::Disabled,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
});
|
||||
let supported_tools_config = ToolsConfig::new(&ToolsConfigParams {
|
||||
model_info: &supported_model_info,
|
||||
available_models: &available_models,
|
||||
features: &features,
|
||||
image_generation_tool_auth_allowed: true,
|
||||
web_search_mode: Some(WebSearchMode::Cached),
|
||||
session_source: SessionSource::Cli,
|
||||
permission_profile: &PermissionProfile::Disabled,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
});
|
||||
|
||||
let (unsupported_tools, _) = build_specs(
|
||||
&unsupported_tools_config,
|
||||
/*mcp_tools*/ None,
|
||||
/*deferred_mcp_tools*/ None,
|
||||
&[],
|
||||
);
|
||||
let ToolSpec::Freeform(FreeformTool {
|
||||
description: unsupported_description,
|
||||
..
|
||||
}) = find_tool(&unsupported_tools, "exec")
|
||||
else {
|
||||
panic!("expected freeform tool");
|
||||
};
|
||||
assert!(!unsupported_description.contains("`audio(audioItem"));
|
||||
|
||||
let (supported_tools, _) = build_specs(
|
||||
&supported_tools_config,
|
||||
/*mcp_tools*/ None,
|
||||
/*deferred_mcp_tools*/ None,
|
||||
&[],
|
||||
);
|
||||
let ToolSpec::Freeform(FreeformTool {
|
||||
description: supported_description,
|
||||
..
|
||||
}) = find_tool(&supported_tools, "exec")
|
||||
else {
|
||||
panic!("expected freeform tool");
|
||||
};
|
||||
assert!(supported_description.contains("`audio(audioItem"));
|
||||
}
|
||||
|
||||
fn model_info() -> ModelInfo {
|
||||
serde_json::from_value(json!({
|
||||
"slug": "gpt-5-codex",
|
||||
|
||||
@@ -12,6 +12,7 @@ use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::InputModality;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::Op;
|
||||
@@ -175,6 +176,54 @@ async fn run_code_mode_turn(
|
||||
Ok((test, second_mock))
|
||||
}
|
||||
|
||||
async fn run_code_mode_turn_with_audio_model(
|
||||
server: &MockServer,
|
||||
prompt: &str,
|
||||
code: &str,
|
||||
) -> Result<(TestCodex, ResponseMock)> {
|
||||
let mut builder = test_codex()
|
||||
.with_model("gpt-5.4")
|
||||
.with_config(move |config| {
|
||||
let _ = config.features.enable(Feature::CodeMode);
|
||||
let mut model_catalog = bundled_models_response()
|
||||
.unwrap_or_else(|err| panic!("bundled models.json should parse: {err}"));
|
||||
let model = model_catalog
|
||||
.models
|
||||
.iter_mut()
|
||||
.find(|model| model.slug == "gpt-5.4")
|
||||
.expect("gpt-5.4 exists in bundled models.json");
|
||||
model.input_modalities = vec![
|
||||
InputModality::Text,
|
||||
InputModality::Image,
|
||||
InputModality::Audio,
|
||||
];
|
||||
config.model_catalog = Some(model_catalog);
|
||||
});
|
||||
let test = builder.build(server).await?;
|
||||
|
||||
responses::mount_sse_once(
|
||||
server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-1"),
|
||||
ev_custom_tool_call("call-1", "exec", code),
|
||||
ev_completed("resp-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let second_mock = responses::mount_sse_once(
|
||||
server,
|
||||
sse(vec![
|
||||
ev_assistant_message("msg-1", "done"),
|
||||
ev_completed("resp-2"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
test.submit_turn(prompt).await?;
|
||||
Ok((test, second_mock))
|
||||
}
|
||||
|
||||
async fn run_code_mode_turn_with_rmcp(
|
||||
server: &MockServer,
|
||||
prompt: &str,
|
||||
@@ -1974,6 +2023,77 @@ image("data:image/png;base64,AAA");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn code_mode_can_output_audio_via_global_helper_for_audio_model() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let (_test, second_mock) = run_code_mode_turn_with_audio_model(
|
||||
&server,
|
||||
"use exec to return audio",
|
||||
r#"
|
||||
audio({ data: "BASE64", format: "wav" });
|
||||
audio({ data: "data:audio/mpeg;base64,MP3BASE64" });
|
||||
"#,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let req = second_mock.single_request();
|
||||
let items = custom_tool_output_items(&req, "call-1");
|
||||
let (_, success) = custom_tool_output_body_and_success(&req, "call-1");
|
||||
assert_ne!(
|
||||
success,
|
||||
Some(false),
|
||||
"code_mode audio output failed unexpectedly"
|
||||
);
|
||||
assert_eq!(items.len(), 3);
|
||||
assert_regex_match(
|
||||
concat!(
|
||||
r"(?s)\A",
|
||||
r"Script completed\nWall time \d+\.\d seconds\nOutput:\n\z"
|
||||
),
|
||||
text_item(&items, /*index*/ 0),
|
||||
);
|
||||
assert_eq!(
|
||||
items[1],
|
||||
serde_json::json!({
|
||||
"type": "input_audio",
|
||||
"input_audio": { "data": "BASE64", "format": "wav" }
|
||||
}),
|
||||
);
|
||||
assert_eq!(
|
||||
items[2],
|
||||
serde_json::json!({
|
||||
"type": "input_audio",
|
||||
"input_audio": { "data": "MP3BASE64", "format": "mp3" }
|
||||
}),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn code_mode_audio_output_fails_for_non_audio_model() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let (_test, second_mock) = run_code_mode_turn(
|
||||
&server,
|
||||
"use exec to return audio",
|
||||
r#"audio({ data: "BASE64", format: "wav" });"#,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let req = second_mock.single_request();
|
||||
let (output, _success) = custom_tool_output_body_and_success(&req, "call-1");
|
||||
assert_eq!(
|
||||
output,
|
||||
"audio content emitted by code mode but the selected model does not support audio input"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn code_mode_can_use_view_image_result_with_image_helper() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -2404,6 +2524,7 @@ text(JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()));
|
||||
"WeakSet",
|
||||
"__codexContentItems",
|
||||
"add_content",
|
||||
"audio",
|
||||
"decodeURI",
|
||||
"decodeURIComponent",
|
||||
"encodeURI",
|
||||
|
||||
@@ -93,6 +93,50 @@ fn assert_wall_time_header(output: &str) {
|
||||
assert_eq!(marker, "Output:");
|
||||
}
|
||||
|
||||
fn test_model_info_with_modalities(
|
||||
slug: &str,
|
||||
description: &str,
|
||||
input_modalities: Vec<InputModality>,
|
||||
) -> ModelInfo {
|
||||
ModelInfo {
|
||||
slug: slug.to_string(),
|
||||
display_name: slug.to_string(),
|
||||
description: Some(description.to_string()),
|
||||
default_reasoning_level: None,
|
||||
supported_reasoning_levels: vec![ReasoningEffortPreset {
|
||||
effort: codex_protocol::openai_models::ReasoningEffort::Medium,
|
||||
description: "Medium".to_string(),
|
||||
}],
|
||||
shell_type: ConfigShellToolType::Default,
|
||||
visibility: ModelVisibility::List,
|
||||
supported_in_api: true,
|
||||
priority: 1,
|
||||
additional_speed_tiers: Vec::new(),
|
||||
service_tiers: Vec::new(),
|
||||
upgrade: None,
|
||||
base_instructions: "base instructions".to_string(),
|
||||
model_messages: None,
|
||||
supports_reasoning_summaries: false,
|
||||
default_reasoning_summary: ReasoningSummary::Auto,
|
||||
support_verbosity: false,
|
||||
default_verbosity: None,
|
||||
availability_nux: None,
|
||||
apply_patch_tool_type: None,
|
||||
web_search_tool_type: Default::default(),
|
||||
truncation_policy: TruncationPolicyConfig::bytes(/*limit*/ 10_000),
|
||||
supports_parallel_tool_calls: false,
|
||||
supports_image_detail_original: false,
|
||||
context_window: Some(272_000),
|
||||
max_context_window: None,
|
||||
auto_compact_token_limit: None,
|
||||
effective_context_window_percent: 95,
|
||||
experimental_supported_tools: Vec::new(),
|
||||
input_modalities,
|
||||
used_fallback_model_metadata: false,
|
||||
supports_search_tool: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_only_user_turn(fixture: &TestCodex, text: impl Into<String>) -> Op {
|
||||
read_only_user_turn_with_model(fixture, text, fixture.session_configured.model.clone())
|
||||
}
|
||||
@@ -154,7 +198,7 @@ fn remote_aware_stdio_server_bin() -> anyhow::Result<String> {
|
||||
return Ok(bin);
|
||||
};
|
||||
|
||||
// Keep the Docker path rewrite scoped to tests that use `build_remote_aware`.
|
||||
// Keep the Docker path rewrite scoped to tests that use `build_with_remote_env`.
|
||||
// Other MCP tests still start their stdio server from the orchestrator test
|
||||
// process, even when the full-ci remote env is present.
|
||||
//
|
||||
@@ -1386,6 +1430,257 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
#[serial(mcp_test_value)]
|
||||
async fn stdio_audio_responses_are_forwarded_for_audio_model() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
|
||||
let call_id = "audio-supported-1";
|
||||
let server_name = "rmcp";
|
||||
let namespace = format!("mcp__{server_name}__");
|
||||
let audio_model_slug = "rmcp-audio-model";
|
||||
|
||||
let models_mock = mount_models_once(
|
||||
&server,
|
||||
ModelsResponse {
|
||||
models: vec![test_model_info_with_modalities(
|
||||
audio_model_slug,
|
||||
"Test model with audio input support",
|
||||
vec![
|
||||
InputModality::Text,
|
||||
InputModality::Image,
|
||||
InputModality::Audio,
|
||||
],
|
||||
)],
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
responses::ev_function_call_with_namespace(call_id, &namespace, "audio", "{}"),
|
||||
responses::ev_completed("resp-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let final_mock = mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("msg-1", "rmcp audio tool completed successfully."),
|
||||
responses::ev_completed("resp-2"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let rmcp_test_server_bin = remote_aware_stdio_server_bin()?;
|
||||
|
||||
let fixture = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(move |config| {
|
||||
insert_mcp_server(
|
||||
config,
|
||||
server_name,
|
||||
stdio_transport(
|
||||
rmcp_test_server_bin,
|
||||
Some(HashMap::from([
|
||||
("MCP_TEST_AUDIO_DATA".to_string(), "UklGRg==".to_string()),
|
||||
(
|
||||
"MCP_TEST_AUDIO_MIME_TYPE".to_string(),
|
||||
"audio/mpeg".to_string(),
|
||||
),
|
||||
])),
|
||||
Vec::new(),
|
||||
),
|
||||
TestMcpServerOptions {
|
||||
experimental_environment: remote_aware_experimental_environment(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
})
|
||||
.build_with_remote_env(&server)
|
||||
.await?;
|
||||
|
||||
fixture
|
||||
.thread_manager
|
||||
.get_models_manager()
|
||||
.list_models(RefreshStrategy::Online)
|
||||
.await;
|
||||
assert_eq!(models_mock.requests().len(), 1);
|
||||
|
||||
fixture
|
||||
.codex
|
||||
.submit(read_only_user_turn_with_model(
|
||||
&fixture,
|
||||
"call the rmcp audio tool",
|
||||
audio_model_slug.to_string(),
|
||||
))
|
||||
.await?;
|
||||
|
||||
wait_for_event(&fixture.codex, |ev| {
|
||||
matches!(ev, EventMsg::McpToolCallBegin(_))
|
||||
})
|
||||
.await;
|
||||
wait_for_event(&fixture.codex, |ev| {
|
||||
matches!(ev, EventMsg::McpToolCallEnd(_))
|
||||
})
|
||||
.await;
|
||||
wait_for_event(&fixture.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
|
||||
|
||||
let output_item = final_mock.single_request().function_call_output(call_id);
|
||||
let output = output_item["output"]
|
||||
.as_array()
|
||||
.expect("audio MCP output should be content items");
|
||||
assert_eq!(output.len(), 2);
|
||||
assert_wall_time_header(
|
||||
output[0]["text"]
|
||||
.as_str()
|
||||
.expect("first MCP audio output item should be wall-time text"),
|
||||
);
|
||||
assert_eq!(
|
||||
output[1],
|
||||
json!({
|
||||
"type": "input_audio",
|
||||
"input_audio": {
|
||||
"data": "UklGRg==",
|
||||
"format": "mp3",
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
#[serial(mcp_test_value)]
|
||||
async fn stdio_audio_responses_fail_for_text_only_model() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
|
||||
let call_id = "audio-text-only-1";
|
||||
let server_name = "rmcp";
|
||||
let namespace = format!("mcp__{server_name}__");
|
||||
let text_only_model_slug = "rmcp-audio-text-only-model";
|
||||
|
||||
let models_mock = mount_models_once(
|
||||
&server,
|
||||
ModelsResponse {
|
||||
models: vec![test_model_info_with_modalities(
|
||||
text_only_model_slug,
|
||||
"Test model without audio input support",
|
||||
vec![InputModality::Text, InputModality::Image],
|
||||
)],
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
responses::ev_function_call_with_namespace(call_id, &namespace, "audio", "{}"),
|
||||
responses::ev_completed("resp-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let final_mock = mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("msg-1", "rmcp audio tool failed."),
|
||||
responses::ev_completed("resp-2"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let rmcp_test_server_bin = remote_aware_stdio_server_bin()?;
|
||||
|
||||
let fixture = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(move |config| {
|
||||
insert_mcp_server(
|
||||
config,
|
||||
server_name,
|
||||
stdio_transport(
|
||||
rmcp_test_server_bin,
|
||||
Some(HashMap::from([
|
||||
("MCP_TEST_AUDIO_DATA".to_string(), "UklGRg==".to_string()),
|
||||
(
|
||||
"MCP_TEST_AUDIO_MIME_TYPE".to_string(),
|
||||
"audio/wav".to_string(),
|
||||
),
|
||||
])),
|
||||
Vec::new(),
|
||||
),
|
||||
TestMcpServerOptions {
|
||||
experimental_environment: remote_aware_experimental_environment(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
})
|
||||
.build_with_remote_env(&server)
|
||||
.await?;
|
||||
|
||||
fixture
|
||||
.thread_manager
|
||||
.get_models_manager()
|
||||
.list_models(RefreshStrategy::Online)
|
||||
.await;
|
||||
assert_eq!(models_mock.requests().len(), 1);
|
||||
|
||||
fixture
|
||||
.codex
|
||||
.submit(read_only_user_turn_with_model(
|
||||
&fixture,
|
||||
"call the rmcp audio tool",
|
||||
text_only_model_slug.to_string(),
|
||||
))
|
||||
.await?;
|
||||
|
||||
wait_for_event(&fixture.codex, |ev| {
|
||||
matches!(ev, EventMsg::McpToolCallBegin(_))
|
||||
})
|
||||
.await;
|
||||
let end_event = wait_for_event(&fixture.codex, |ev| {
|
||||
matches!(ev, EventMsg::McpToolCallEnd(_))
|
||||
})
|
||||
.await;
|
||||
let EventMsg::McpToolCallEnd(end) = end_event else {
|
||||
unreachable!("event guard guarantees McpToolCallEnd");
|
||||
};
|
||||
assert_eq!(
|
||||
end.result,
|
||||
Err(
|
||||
"audio content returned by MCP tool but the selected model does not support audio input"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
wait_for_event(&fixture.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
|
||||
|
||||
let output_item = final_mock.single_request().function_call_output(call_id);
|
||||
let output_text = output_item
|
||||
.get("output")
|
||||
.and_then(Value::as_str)
|
||||
.expect("function_call_output output should be a JSON string");
|
||||
let wrapped_payload = split_wall_time_wrapped_output(output_text);
|
||||
let output_json: Value = serde_json::from_str(wrapped_payload)
|
||||
.expect("function_call_output output should be valid JSON");
|
||||
assert_eq!(
|
||||
output_json,
|
||||
json!([{
|
||||
"type": "text",
|
||||
"text": "audio content returned by MCP tool but the selected model does not support audio input"
|
||||
}])
|
||||
);
|
||||
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
#[serial(mcp_test_value)]
|
||||
async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> {
|
||||
|
||||
Reference in New Issue
Block a user