Skip to content

Commit

Permalink
Integrate chatbot crate -- Closes #5
Browse files Browse the repository at this point in the history
  • Loading branch information
ovstinga committed Dec 20, 2024
1 parent ad5e105 commit a73d70d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
1 change: 1 addition & 0 deletions crates/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
13 changes: 9 additions & 4 deletions crates/server/src/main.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand All @@ -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::<ChatRequest>(&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)
}
}
}
Expand Down

0 comments on commit a73d70d

Please sign in to comment.