mirror of
https://github.com/openai/codex.git
synced 2026-11-30 00:10:49 +00:00
test: cover chat stream aggregation and tool calls
This commit is contained in:
@@ -462,3 +462,221 @@ pub(crate) trait AggregateStreamExt: Stream<Item = Result<ResponseEvent>> + Size
|
||||
}
|
||||
|
||||
impl<T> AggregateStreamExt for T where T: Stream<Item = Result<ResponseEvent>> + Sized {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use crate::models::{
|
||||
FunctionCallOutputPayload, LocalShellAction, LocalShellExecAction, LocalShellStatus,
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
|
||||
/// Helper constructing a minimal assistant text chunk.
|
||||
fn text_chunk(txt: &str) -> ResponseEvent {
|
||||
ResponseEvent::OutputItemDone(ResponseItem::Message {
|
||||
role: "assistant".to_string(),
|
||||
content: vec![ContentItem::OutputText { text: txt.into() }],
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aggregates_consecutive_message_chunks() {
|
||||
let events = vec![
|
||||
Ok(text_chunk("Hello")),
|
||||
Ok(text_chunk(", world")),
|
||||
Ok(ResponseEvent::Completed {
|
||||
response_id: "r1".to_string(),
|
||||
token_usage: None,
|
||||
}),
|
||||
];
|
||||
|
||||
let stream = stream::iter(events).aggregate();
|
||||
let collected: Vec<_> = stream.map(Result::unwrap).collect().await;
|
||||
|
||||
assert_eq!(collected.len(), 2, "only final message and Completed");
|
||||
|
||||
match &collected[0] {
|
||||
ResponseEvent::OutputItemDone(ResponseItem::Message { content, .. }) => {
|
||||
let text = match &content[0] {
|
||||
ContentItem::OutputText { text } => text,
|
||||
_ => panic!("unexpected content item"),
|
||||
};
|
||||
assert_eq!(text, "Hello, world");
|
||||
}
|
||||
other => panic!("unexpected first event: {other:?}"),
|
||||
}
|
||||
|
||||
assert!(matches!(
|
||||
collected[1],
|
||||
ResponseEvent::Completed { response_id: ref id, token_usage: None } if id == "r1"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forwards_non_text_items_without_merging() {
|
||||
let func_call = ResponseItem::FunctionCall {
|
||||
name: "shell".to_string(),
|
||||
arguments: "{}".to_string(),
|
||||
call_id: "call1".to_string(),
|
||||
};
|
||||
|
||||
let events = vec![
|
||||
Ok(text_chunk("foo")),
|
||||
Ok(ResponseEvent::OutputItemDone(func_call.clone())),
|
||||
Ok(text_chunk("bar")),
|
||||
Ok(ResponseEvent::Completed {
|
||||
response_id: "r2".to_string(),
|
||||
token_usage: None,
|
||||
}),
|
||||
];
|
||||
|
||||
let stream = stream::iter(events).aggregate();
|
||||
let collected: Vec<_> = stream.map(Result::unwrap).collect().await;
|
||||
|
||||
assert_eq!(collected.len(), 3);
|
||||
|
||||
// First event should be the function call forwarded directly.
|
||||
assert!(matches!(
|
||||
collected[0],
|
||||
ResponseEvent::OutputItemDone(ResponseItem::FunctionCall { .. })
|
||||
));
|
||||
|
||||
// Second is the combined assistant message.
|
||||
match &collected[1] {
|
||||
ResponseEvent::OutputItemDone(ResponseItem::Message { content, .. }) => {
|
||||
let text = match &content[0] {
|
||||
ContentItem::OutputText { text } => text,
|
||||
_ => panic!("unexpected content item"),
|
||||
};
|
||||
assert_eq!(text, "foobar");
|
||||
}
|
||||
other => panic!("unexpected second event: {other:?}"),
|
||||
}
|
||||
|
||||
// Final Completed event.
|
||||
assert!(matches!(
|
||||
collected[2],
|
||||
ResponseEvent::Completed { response_id: ref id, token_usage: None } if id == "r2"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn formats_tool_calls_in_chat_payload() {
|
||||
use serde_json::Value;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use wiremock::{
|
||||
Mock, MockServer, Request, Respond, ResponseTemplate, matchers::method, matchers::path,
|
||||
};
|
||||
|
||||
struct CaptureResponder(Arc<Mutex<Option<Value>>>);
|
||||
impl Respond for CaptureResponder {
|
||||
fn respond(&self, req: &Request) -> ResponseTemplate {
|
||||
let v: Value = serde_json::from_slice(&req.body).unwrap();
|
||||
*self.0.lock().unwrap() = Some(v);
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_raw(
|
||||
"event: response.completed\n\
|
||||
data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp\",\"output\":[]}}\n\n",
|
||||
"text/event-stream",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let captured = Arc::new(Mutex::new(None));
|
||||
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/chat/completions"))
|
||||
.respond_with(CaptureResponder(captured.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
unsafe {
|
||||
std::env::set_var("OPENAI_REQUEST_MAX_RETRIES", "0");
|
||||
}
|
||||
|
||||
let provider = ModelProviderInfo {
|
||||
name: "openai".into(),
|
||||
base_url: format!("{}/v1", server.uri()),
|
||||
env_key: Some("PATH".into()),
|
||||
env_key_instructions: None,
|
||||
wire_api: crate::WireApi::Chat,
|
||||
query_params: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
};
|
||||
|
||||
let mut prompt = Prompt::default();
|
||||
prompt.input.push(ResponseItem::Message {
|
||||
role: "user".into(),
|
||||
content: vec![ContentItem::InputText { text: "hi".into() }],
|
||||
});
|
||||
prompt.input.push(ResponseItem::FunctionCall {
|
||||
name: "shell".into(),
|
||||
arguments: "[]".into(),
|
||||
call_id: "call123".into(),
|
||||
});
|
||||
prompt.input.push(ResponseItem::FunctionCallOutput {
|
||||
call_id: "call123".into(),
|
||||
output: FunctionCallOutputPayload {
|
||||
content: "ok".into(),
|
||||
success: Some(true),
|
||||
},
|
||||
});
|
||||
prompt.input.push(ResponseItem::LocalShellCall {
|
||||
id: Some("ls1".into()),
|
||||
call_id: Some("call456".into()),
|
||||
status: LocalShellStatus::Completed,
|
||||
action: LocalShellAction::Exec(LocalShellExecAction {
|
||||
command: vec!["echo".into(), "hi".into()],
|
||||
timeout_ms: Some(1),
|
||||
working_directory: None,
|
||||
env: None,
|
||||
user: None,
|
||||
}),
|
||||
});
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let _ = stream_chat_completions(&prompt, "model", &client, &provider)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let body = captured.lock().unwrap().take().unwrap();
|
||||
let messages = body.get("messages").unwrap().as_array().unwrap();
|
||||
|
||||
// function_call
|
||||
let call = messages[2].get("tool_calls").unwrap().as_array().unwrap()[0].clone();
|
||||
assert_eq!(call.get("id").unwrap().as_str().unwrap(), "call123");
|
||||
assert_eq!(call.get("type").unwrap().as_str().unwrap(), "function");
|
||||
let func = call.get("function").unwrap();
|
||||
assert_eq!(func.get("name").unwrap().as_str().unwrap(), "shell");
|
||||
assert_eq!(func.get("arguments").unwrap().as_str().unwrap(), "[]");
|
||||
|
||||
// function_call_output
|
||||
assert_eq!(messages[3].get("role").unwrap().as_str().unwrap(), "tool");
|
||||
assert_eq!(
|
||||
messages[3].get("tool_call_id").unwrap().as_str().unwrap(),
|
||||
"call123"
|
||||
);
|
||||
assert_eq!(messages[3].get("content").unwrap().as_str().unwrap(), "ok");
|
||||
|
||||
// local_shell_call
|
||||
let shell_call = messages[4].get("tool_calls").unwrap().as_array().unwrap()[0].clone();
|
||||
assert_eq!(
|
||||
shell_call.get("type").unwrap().as_str().unwrap(),
|
||||
"local_shell_call"
|
||||
);
|
||||
assert_eq!(shell_call.get("id").unwrap().as_str().unwrap(), "ls1");
|
||||
let action = shell_call.get("action").unwrap();
|
||||
assert_eq!(
|
||||
action.get("command").unwrap().as_array().unwrap()[0]
|
||||
.as_str()
|
||||
.unwrap(),
|
||||
"echo"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,3 +391,77 @@ async fn stream_from_fixture(path: impl AsRef<Path>) -> Result<ResponseStream> {
|
||||
tokio::spawn(process_sse(stream, tx_event));
|
||||
Ok(ResponseStream { rx_event })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use crate::models::{LocalShellAction, LocalShellStatus};
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
/// Build a tiny SSE string with the provided events.
|
||||
fn build_sse(chunks: &[&str]) -> String {
|
||||
let mut out = String::new();
|
||||
for c in chunks {
|
||||
out.push_str(c);
|
||||
out.push_str("\n\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parses_function_and_local_shell_items() {
|
||||
let func = "event: response.output_item.done\n\
|
||||
data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call_output\",\"call_id\":\"call1\",\"output\":{\"content\":\"ok\",\"success\":true}}}";
|
||||
let shell = "event: response.output_item.done\n\
|
||||
data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"local_shell_call\",\"id\":\"ls1\",\"call_id\":\"call2\",\"status\":\"in_progress\",\"action\":{\"type\":\"exec\",\"command\":[\"echo\",\"hi\"],\"timeout_ms\":123,\"working_directory\":null,\"env\":null,\"user\":null}}}";
|
||||
let done = "event: response.completed\n\
|
||||
data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp\",\"output\":[]}}";
|
||||
|
||||
let content = build_sse(&[func, shell, done]);
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<ResponseEvent>>(8);
|
||||
let stream = ReaderStream::new(std::io::Cursor::new(content)).map_err(CodexErr::Io);
|
||||
tokio::spawn(super::process_sse(stream, tx));
|
||||
|
||||
// function_call_output
|
||||
match rx.recv().await.unwrap().unwrap() {
|
||||
ResponseEvent::OutputItemDone(ResponseItem::FunctionCallOutput { call_id, output }) => {
|
||||
assert_eq!(call_id, "call1");
|
||||
assert_eq!(output.content, "ok");
|
||||
assert_eq!(output.success, Some(true));
|
||||
}
|
||||
other => panic!("unexpected first event: {other:?}"),
|
||||
}
|
||||
|
||||
// local_shell_call
|
||||
match rx.recv().await.unwrap().unwrap() {
|
||||
ResponseEvent::OutputItemDone(ResponseItem::LocalShellCall {
|
||||
id,
|
||||
call_id,
|
||||
status,
|
||||
action,
|
||||
}) => {
|
||||
assert_eq!(id.as_deref(), Some("ls1"));
|
||||
assert_eq!(call_id.as_deref(), Some("call2"));
|
||||
if !matches!(status, LocalShellStatus::InProgress) {
|
||||
panic!("unexpected status: {status:?}");
|
||||
}
|
||||
match action {
|
||||
LocalShellAction::Exec(act) => {
|
||||
assert_eq!(act.command, vec!["echo".to_string(), "hi".to_string()]);
|
||||
assert_eq!(act.timeout_ms, Some(123));
|
||||
}
|
||||
}
|
||||
}
|
||||
other => panic!("unexpected second event: {other:?}"),
|
||||
}
|
||||
|
||||
// completed
|
||||
assert!(matches!(
|
||||
rx.recv().await.unwrap().unwrap(),
|
||||
ResponseEvent::Completed { response_id, .. } if response_id == "resp"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user