From a73d70d6ac402f465e0d568d83acffddfe619f4a Mon Sep 17 00:00:00 2001 From: Ovidiu Stinga Date: Fri, 20 Dec 2024 14:31:01 +0200 Subject: [PATCH] Integrate chatbot crate -- Closes #5 --- crates/server/Cargo.toml | 1 + crates/server/src/main.rs | 13 +++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 35bf364..5953cb7 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -8,3 +8,4 @@ miniserve = { path = "../miniserve" } serde = { version = "1.0.216", features = ["derive"] } serde_json = "1.0.133" tokio = { workspace = true, features = ["full"] } +chatbot = { path = "../chatbot" } diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 7418132..e1dcd3f 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -1,5 +1,7 @@ -use miniserve::{http, Content, Request, Response}; +use chatbot::{gen_random_number, query_chat}; +use miniserve::{http::StatusCode, Content, Request, Response}; use serde::{Deserialize, Serialize}; +use tokio::join; // Define the data structure for incoming JSON #[derive(Deserialize)] @@ -20,16 +22,19 @@ async fn index(_req: Request) -> Response { async fn chat(req: Request) -> Response { match req { - Request::Get => Err(http::StatusCode::METHOD_NOT_ALLOWED), + Request::Get => Err(StatusCode::METHOD_NOT_ALLOWED), Request::Post(body) => { if let Ok(chat_request) = serde_json::from_str::(&body) { let mut messages = chat_request.messages; - messages.push(String::from("And how does that make you feel?")); + let (r, mut responses) = join!(gen_random_number(), query_chat(&messages)); + + let response = responses.remove(r % responses.len()); + messages.push(response); let response_body = serde_json::to_string(&ChatResponse { messages }).unwrap(); Ok(Content::Json(response_body)) } else { - Err(http::StatusCode::BAD_REQUEST) + Err(StatusCode::INTERNAL_SERVER_ERROR) } } }