Skip to content

Commit ddaf90e

Browse files
committed
Solution
1 parent 67e29cc commit ddaf90e

File tree

1 file changed

+35
-14
lines changed

1 file changed

+35
-14
lines changed

crates/server/src/main.rs

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1-
use std::sync::{Arc, LazyLock};
1+
use std::{
2+
path::PathBuf,
3+
sync::{Arc, LazyLock},
4+
};
25

36
use miniserve::{http::StatusCode, Content, Request, Response};
47
use serde::{Deserialize, Serialize};
58
use tokio::{
6-
join,
9+
fs, join,
710
sync::{mpsc, oneshot},
11+
task::JoinSet,
812
};
913

1014
async fn index(_req: Request) -> Response {
@@ -17,19 +21,36 @@ struct Messages {
1721
messages: Vec<String>,
1822
}
1923

20-
async fn query_chat(messages: &Arc<Vec<String>>) -> Vec<String> {
21-
type Payload = (Arc<Vec<String>>, oneshot::Sender<Vec<String>>);
22-
static SENDER: LazyLock<mpsc::Sender<Payload>> = LazyLock::new(|| {
23-
let (tx, mut rx) = mpsc::channel::<Payload>(1024);
24-
tokio::spawn(async move {
25-
let mut chatbot = chatbot::Chatbot::new(vec![":-)".into(), "^^".into()]);
26-
while let Some((messages, responder)) = rx.recv().await {
27-
let response = chatbot.query_chat(&messages).await;
28-
responder.send(response).unwrap();
29-
}
30-
});
31-
tx
24+
async fn load_docs(paths: Vec<PathBuf>) -> Vec<String> {
25+
let mut doc_futs = paths
26+
.into_iter()
27+
.map(fs::read_to_string)
28+
.collect::<JoinSet<_>>();
29+
let mut docs = Vec::new();
30+
while let Some(result) = doc_futs.join_next().await {
31+
docs.push(result.unwrap().unwrap());
32+
}
33+
docs
34+
}
35+
36+
type Payload = (Arc<Vec<String>>, oneshot::Sender<Vec<String>>);
37+
38+
fn chatbot_thread() -> mpsc::Sender<Payload> {
39+
let (tx, mut rx) = mpsc::channel::<Payload>(1024);
40+
tokio::spawn(async move {
41+
let mut chatbot = chatbot::Chatbot::new(vec![":-)".into(), "^^".into()]);
42+
while let Some((messages, responder)) = rx.recv().await {
43+
let doc_paths = chatbot.retrieval_documents(&messages);
44+
let docs = load_docs(doc_paths).await;
45+
let response = chatbot.query_chat(&messages, &docs).await;
46+
responder.send(response).unwrap();
47+
}
3248
});
49+
tx
50+
}
51+
52+
async fn query_chat(messages: &Arc<Vec<String>>) -> Vec<String> {
53+
static SENDER: LazyLock<mpsc::Sender<Payload>> = LazyLock::new(chatbot_thread);
3354

3455
let (tx, rx) = oneshot::channel();
3556
SENDER.send((Arc::clone(messages), tx)).await.unwrap();

0 commit comments

Comments
 (0)