-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
114 lines (99 loc) · 3.49 KB
/
Copy pathlib.rs
File metadata and controls
114 lines (99 loc) · 3.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use form_urlencoded;
use wstd::http::body::Body;
use wstd::http::{Error, Request, Response, StatusCode};
use wstd::time::{Duration, Instant};
mod bindings {
wit_bindgen::generate!({
path: "wit",
world: "app",
});
}
#[wstd::http_server]
async fn main(req: Request<Body>) -> Result<Response<Body>, Error> {
match req.uri().path() {
"/" => hi(req).await,
"/wait" => wait(req).await,
"/echo" => echo(req).await,
"/echo-headers" => echo_headers(req).await,
"/api/chat-completion" => chat_completion(req).await,
_ => not_found(req).await,
}
}
fn query_param(req: &Request<Body>, key: &str) -> Option<String> {
req.uri().query().and_then(|query| {
form_urlencoded::parse(query.as_bytes()).find_map(|(k, v)| {
if k == key {
Some(v.into_owned())
} else {
None
}
})
})
}
async fn chat_completion(req: Request<Body>) -> Result<Response<Body>, Error> {
let Some(api_key) = query_param(&req, "apiKey") else {
return bad_request("missing query param `apiKey`\n").await;
};
let Some(message) = query_param(&req, "message") else {
return bad_request("missing query param `message`\n").await;
};
let model = query_param(&req, "model").unwrap_or_else(|| "gpt-4o-mini".to_string());
let payload = serde_json::json!({
"model": model,
"messages": [
{
"role": "user",
"content": message,
}
]
})
.to_string();
let output = bindings::local::app::helpers_interface::chat_completion(&api_key, &payload);
Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(output.into())?)
}
async fn bad_request(message: &str) -> Result<Response<Body>, Error> {
Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(message.to_string().into())?)
}
async fn hi(_req: Request<Body>) -> Result<Response<Body>, Error> {
Ok(Response::new("hi!\n".to_string().into()))
}
async fn not_found(_req: Request<Body>) -> Result<Response<Body>, Error> {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body("404\n".to_string().into())?)
}
async fn wait(_req: Request<Body>) -> Result<Response<Body>, Error> {
let now = Instant::now();
wstd::task::sleep(Duration::from_secs(1)).await;
let elapsed = Instant::now().duration_since(now).as_millis();
Ok(Response::new(
format!("slept for {elapsed} millis\n").into(),
))
}
async fn echo(req: Request<Body>) -> Result<Response<Body>, Error> {
let (_parts, body) = req.into_parts();
Ok(Response::new(body))
}
async fn echo_headers(req: Request<Body>) -> Result<Response<Body>, Error> {
let (parts, _body) = req.into_parts();
let mut headers_json: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
for (name, value) in &parts.headers {
let key = name.as_str().to_string();
let val = match value.to_str() {
Ok(s) => s.to_string(),
Err(_) => String::from_utf8_lossy(value.as_bytes()).to_string(),
};
headers_json.entry(key).or_default().push(val);
}
let body = serde_json::to_string_pretty(&headers_json).unwrap_or_else(|_| "{}".to_string());
Ok(Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(body.into())?)
}