#![forbid(unsafe_code)]
use std::cell::RefCell;
use std::time::Duration;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
pub use web_time::Instant;
pub use wasm_bindgen_futures::spawn_local;
pub use console_error_panic_hook::set_once as set_panic_hook;
#[derive(Debug, Clone)]
pub struct WasmLlmConfig {
pub api_key: String,
pub base_url: String,
pub model: String,
}
impl Default for WasmLlmConfig {
fn default() -> Self {
Self {
api_key: String::new(),
base_url: "https://api.openai.com/v1".to_string(),
model: "gpt-4o-mini".to_string(),
}
}
}
thread_local! {
static WASM_LLM_CONFIG: RefCell<WasmLlmConfig> = RefCell::new(WasmLlmConfig::default());
}
#[wasm_bindgen]
pub fn sage_configure(base_url: &str, model: &str, api_key: &str) {
WASM_LLM_CONFIG.with(|c| {
*c.borrow_mut() = WasmLlmConfig {
api_key: api_key.to_string(),
base_url: base_url.to_string(),
model: model.to_string(),
};
});
}
pub fn get_llm_config() -> WasmLlmConfig {
WASM_LLM_CONFIG.with(|c| c.borrow().clone())
}
pub async fn sleep(duration: Duration) {
let ms = duration.as_millis() as i32;
let promise = js_sys::Promise::new(&mut |resolve, _| {
let global = js_sys::global();
let _ = js_sys::Reflect::apply(
&js_sys::Function::from(js_sys::Reflect::get(&global, &"setTimeout".into()).unwrap()),
&global,
&js_sys::Array::of2(&resolve, &JsValue::from(ms)),
);
});
let _ = JsFuture::from(promise).await;
}
pub fn console_log(msg: &str) {
web_sys::console::log_1(&msg.into());
}
pub fn console_warn(msg: &str) {
web_sys::console::warn_1(&msg.into());
}
pub fn console_error(msg: &str) {
web_sys::console::error_1(&msg.into());
}