use super::request::RequestBuilder;
use crate::Config;
use crate::error::OpenAIError;
use crate::service::request::RequestSpec;
use crate::service::transport::HttpTransport;
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio_stream::wrappers::ReceiverStream;
pub struct HttpClient {
transport: Arc<HttpTransport>,
}
impl HttpClient {
pub fn new(config: Config) -> HttpClient {
HttpClient {
transport: Arc::new(HttpTransport::new(config)),
}
}
pub(crate) fn config(&self) -> Arc<RwLock<Config>> {
self.transport.config()
}
pub async fn refresh_client(&self) {
self.transport.refresh_client().await;
}
pub async fn post_json<U, F, T>(&self, params: RequestSpec<U, F>) -> Result<T, OpenAIError>
where
U: FnOnce(&Config) -> String,
F: FnOnce(&Config, &mut RequestBuilder),
T: serde::de::DeserializeOwned,
{
self.transport.post_json(params).await
}
pub async fn get_json<U, F, T>(&self, params: RequestSpec<U, F>) -> Result<T, OpenAIError>
where
U: FnOnce(&Config) -> String,
F: FnOnce(&Config, &mut RequestBuilder),
T: serde::de::DeserializeOwned,
{
self.transport.get_json(params).await
}
pub async fn post_json_stream<U, F, T>(
&self,
params: RequestSpec<U, F>,
) -> Result<ReceiverStream<Result<T, OpenAIError>>, OpenAIError>
where
U: FnOnce(&Config) -> String,
F: FnOnce(&Config, &mut RequestBuilder),
T: serde::de::DeserializeOwned + Send + 'static,
{
self.transport.post_json_stream(params).await
}
}
impl Clone for HttpClient {
fn clone(&self) -> Self {
HttpClient {
transport: Arc::clone(&self.transport),
}
}
}