use std::collections::HashMap;
use std::fmt;
use serde_json::Value;
use crate::client::{ClientConfig, SystemOneOpts, TypeSafeClient};
use crate::error::{ErrorKind, Result, TypeSafeError};
use crate::questions::Question;
use crate::types::{ListModelsResponse, SystemOneResponse};
#[non_exhaustive]
pub struct BlockingClient {
inner: TypeSafeClient,
runtime: tokio::runtime::Runtime,
}
impl fmt::Debug for BlockingClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BlockingClient")
.field("inner", &self.inner)
.finish_non_exhaustive()
}
}
impl BlockingClient {
fn guard_async_context() -> Result<()> {
if tokio::runtime::Handle::try_current().is_ok() {
Err(TypeSafeError::new(ErrorKind::Runtime(
"Cannot use a BlockingClient from inside an async context. \
Use TypeSafeClient instead, or construct the BlockingClient \
before entering the async runtime."
.to_string(),
)))
} else {
Ok(())
}
}
fn build_runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| {
TypeSafeError::new(ErrorKind::Runtime(format!(
"Failed to create Tokio runtime for blocking client: {e}"
)))
})
}
#[must_use = "the returned client should be used to make API calls"]
pub fn new(api_key: impl Into<String>) -> Result<Self> {
Self::from_config(ClientConfig {
api_key: api_key.into(),
..ClientConfig::default()
})
}
#[must_use = "the returned client should be used to make API calls"]
pub fn from_config(config: ClientConfig) -> Result<Self> {
Self::guard_async_context()?;
let inner = TypeSafeClient::from_config(config)?;
let runtime = Self::build_runtime()?;
Ok(Self { inner, runtime })
}
#[must_use = "the returned client should be used to make API calls"]
pub fn from_env() -> Result<Self> {
Self::guard_async_context()?;
let inner = TypeSafeClient::from_env()?;
let runtime = Self::build_runtime()?;
Ok(Self { inner, runtime })
}
#[must_use]
pub fn base_url(&self) -> &str {
self.inner.base_url()
}
#[must_use]
pub fn default_model(&self) -> &str {
self.inner.default_model()
}
pub fn system_one(
&self,
state: impl Into<Value>,
questions: HashMap<String, Question>,
) -> Result<SystemOneResponse> {
Self::guard_async_context()?;
self.runtime
.block_on(self.inner.system_one(state, questions))
}
pub fn system_one_with_model(
&self,
state: impl Into<Value>,
questions: HashMap<String, Question>,
model: Option<&str>,
) -> Result<SystemOneResponse> {
Self::guard_async_context()?;
self.runtime
.block_on(self.inner.system_one_with_model(state, questions, model))
}
pub fn system_one_with_opts(
&self,
questions: HashMap<String, Question>,
opts: SystemOneOpts,
) -> Result<SystemOneResponse> {
Self::guard_async_context()?;
self.runtime
.block_on(self.inner.system_one_with_opts(questions, opts))
}
pub fn list_models(&self) -> Result<ListModelsResponse> {
Self::guard_async_context()?;
self.runtime.block_on(self.inner.list_models())
}
}