#![allow(unused)]
use crate::core::Swarm;
use crate::types::{Agent, ContextVariables, Instructions, Message};
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde_json::json;
use serde_json::Value;
use std::collections::HashMap;
async fn completions_mock_handler(req_body: web::Json<Value>) -> impl Responder {
let prompt = req_body.get("prompt");
if let Some(Value::String(prompt_str)) = prompt {
if prompt_str == "Hello!" {
let response = json!({
"choices": [
{
"message": {
"role": "assistant",
"content": "Hi there! How can I assist you today?"
}
}
],
"agent": {
"name": "test_agent",
"model": "gpt-4",
"instructions": {
"text": "You are a helpful assistant."
},
"functions": [],
"function_call": null,
"parallel_tool_calls": false
}
});
return HttpResponse::Ok().json(response);
}
}
let default_response = json!({
"choices": [
{
"message": {
"role": "assistant",
"content": "I'm not sure how to respond to that."
}
}
],
"agent": null
});
HttpResponse::Ok().json(default_response)
}
async fn setup_mock_server() -> anyhow::Result<actix_web::dev::Server> {
let server = HttpServer::new(|| {
App::new().route("/completions", web::post().to(completions_mock_handler))
})
.bind(("127.0.0.1", 8000))?
.run();
Ok(server)
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::test;
#[actix_web::test]
async fn test_simple_conversation() -> anyhow::Result<()> {
let app = test::init_service(
App::new().route("/completions", web::post().to(completions_mock_handler)),
)
.await;
let agent = Agent::new(
"test_agent",
"gpt-4",
Instructions::Text("You are a helpful assistant.".to_string()),
)?;
let swarm = Swarm::builder()
.with_api_key("sk-test123456789".to_string()) .with_api_url("http://localhost:8000".to_string())
.with_agent(agent.clone())
.build()?;
let messages = [Message::user("Hello!").expect("Failed to create request message")];
let req = test::TestRequest::post()
.uri("/completions")
.set_json(json!({
"prompt": "Hello!",
"model": "gpt-4"
}))
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
let response: serde_json::Value = test::read_body_json(resp).await;
assert_eq!(
response["choices"][0]["message"]["content"],
"Hi there! How can I assist you today?"
);
assert_eq!(response["choices"][0]["message"]["role"], "assistant");
Ok(())
}
}