#[cfg(test)]
mod tests {
use crate::stream::Streamer;
use crate::types::{Agent, ApiKey, ContextVariables, Instructions, Message};
#[allow(unused)]
use crate::SwarmError;
use futures_util::{pin_mut, StreamExt};
use reqwest::Client;
use std::time::Duration;
use tokio;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn test_agent() -> Agent {
Agent::new(
"test_agent",
"gpt-4",
Instructions::Text("You are a helpful assistant.".to_string()),
)
.expect("Failed to create test agent")
}
#[tokio::test]
async fn test_stream_chat_returns_messages() {
let mock_server = MockServer::start().await;
let body = "data: {\"id\":\"dummy\",\"object\":\"chat.completion\",\"created\":0,\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"Hello from stream!\",\"name\":null,\"function_call\":null},\"finish_reason\":null}]}\n\
data: [DONE]\n";
let response = ResponseTemplate::new(200).set_body_raw(body, "text/event-stream");
Mock::given(method("POST"))
.and(path("/completions"))
.respond_with(response)
.mount(&mock_server)
.await;
let api_url = format!("{}/completions", &mock_server.uri());
let client = Client::builder()
.timeout(Duration::from_secs(30))
.build()
.expect("Failed to build client");
let api_key = ApiKey::new("sk-test123456789").expect("valid test key");
let streamer = Streamer::new(client, api_key, api_url);
let agent = test_agent();
let history: Vec<Message> =
vec![Message::user("Hello!").expect("Failed to create history message")];
let context_variables = ContextVariables::new();
let stream = streamer.stream_chat(&agent, &history, &context_variables, None, true);
pin_mut!(stream);
if let Some(result) = stream.next().await {
match result {
Ok(message) => {
assert_eq!(message.role().as_str(), "assistant");
assert_eq!(message.content(), Some("Hello from stream!"));
}
Err(e) => {
panic!("Stream returned an error: {:?}", e);
}
}
} else {
panic!("No messages returned from the stream");
}
}
}