use super::Client;
use crate::{Error, MaybeSend, Result};
use futures::stream::{Stream, StreamExt};
use http::header::{ACCEPT, USER_AGENT};
use http::Method;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::future::Future;
use timvw_rust_runtime::{RequestBuilder, Response};
impl<T> Client<T> {
pub(super) fn raw_request(&self, method: Method, path: &str) -> RequestBuilder {
let configuration = &self.base_configuration;
let base = configuration.base_path.trim_end_matches('/');
let url = if path.starts_with('/') {
format!("{base}{path}")
} else {
format!("{base}/{path}")
};
let mut request = self.http.request(method, &url);
if let Some(user_agent) = &configuration.user_agent {
request = request.header(USER_AGENT, user_agent.as_str());
}
request
}
pub fn send_json<I, O>(
&self,
method: Method,
path: &str,
body: Option<&I>,
) -> impl Future<Output = Result<O>> + MaybeSend + 'static
where
I: Serialize + ?Sized,
O: DeserializeOwned,
{
let mut request = self
.raw_request(method, path)
.header(ACCEPT, "application/json");
if let Some(body) = body {
request = request.json(body);
}
async move {
let response = check_status(request.send().await?).await?;
Ok(response.json::<O>().await?)
}
}
pub fn post_json<I, O>(
&self,
path: &str,
body: &I,
) -> impl Future<Output = Result<O>> + MaybeSend + 'static
where
I: Serialize + ?Sized,
O: DeserializeOwned,
{
self.send_json(Method::POST, path, Some(body))
}
pub fn get_json<O>(&self, path: &str) -> impl Future<Output = Result<O>> + MaybeSend + 'static
where
O: DeserializeOwned,
{
self.send_json(Method::GET, path, None::<&()>)
}
pub fn send_json_stream<I, O>(
&self,
path: &str,
body: &I,
) -> impl Future<Output = Result<impl Stream<Item = Result<O>> + MaybeSend + Unpin + 'static>>
+ MaybeSend
+ 'static
where
I: Serialize + ?Sized,
O: DeserializeOwned + 'static,
{
let request = self
.raw_request(Method::POST, path)
.header(ACCEPT, "text/event-stream")
.json(body);
async move {
let response = check_status(request.send().await?).await?;
Ok(decode_events::<O>(response))
}
}
}
impl<T> Client<T> {
pub(super) fn send_event_stream_request<I: Serialize + ?Sized>(
&self,
method: Method,
path: &str,
body: &I,
) -> impl Future<Output = Result<Response>> + MaybeSend + 'static {
let request = self
.raw_request(method, path)
.header(ACCEPT, "text/event-stream")
.json(body);
async move { check_status(request.send().await?).await }
}
}
fn decode_events<O: DeserializeOwned + 'static>(
response: Response,
) -> impl Stream<Item = Result<O>> + MaybeSend + Unpin + 'static {
Box::pin(response.events().filter_map(|event| async move {
match event {
Ok(event) if event.data.trim().is_empty() => None,
Ok(event) => {
Some(
serde_json::from_str::<O>(&event.data).map_err(|error| Error::StreamParsing {
message: format!("Failed to deserialize event: {error}"),
chunk: event.data,
}),
)
}
Err(error) => Some(Err(Error::StreamConnection {
message: format!("Stream connection error: {error}"),
})),
}
}))
}
pub(super) async fn check_status(response: Response) -> Result<Response> {
let status = response.status();
if status.is_success() {
return Ok(response);
}
let message = response.text().await?;
let (error_type, error_code) = openai_error_details(&message);
Err(Error::Api {
status: status.as_u16(),
message,
error_type,
error_code,
})
}
pub(super) fn openai_error_details(body: &str) -> (Option<String>, Option<String>) {
let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
return (None, None);
};
let field = |name: &str| match &value["error"][name] {
serde_json::Value::String(text) => Some(text.clone()),
serde_json::Value::Number(number) => Some(number.to_string()),
_ => None,
};
(field("type"), field("code"))
}
#[cfg(test)]
mod tests {
use super::openai_error_details;
#[test]
fn reads_openai_error_details() {
let body = r#"{"error":{"message":"bad","type":"invalid_request_error","code":"model_not_found"}}"#;
assert_eq!(
openai_error_details(body),
(
Some("invalid_request_error".to_string()),
Some("model_not_found".to_string())
)
);
assert_eq!(
openai_error_details(r#"{"error":{"message":"x","type":null,"code":429}}"#),
(None, Some("429".to_string()))
);
assert_eq!(openai_error_details("not json"), (None, None));
}
}