Read-only mirror of github.com/ondeinference/ed.
Mirrored from https://github.com/ondeinference/ed.git
Synced Nov 23, 01:00 UTC
| 1 | //! Streaming client for OpenAI-compatible `/chat/completions` endpoints (Onde Cloud by default, |
| 2 | //! or any other with the `OPENAI_*` variables): text and reasoning deltas, tool-call |
| 3 | //! accumulation, token usage, and `GET /models`. |
| 4 | //! |
| 5 | //! Superseded by `onde-backend` once it exists (Onde Agent Platform §5.2); the agent depends |
| 6 | //! only on this module's public types so that swap stays local. |
| 7 | |
| 8 | use anyhow::{Context, Result, bail}; |
| 9 | use futures::StreamExt; |
| 10 | use serde::Deserialize; |
| 11 | use serde_json::{Value, json}; |
| 12 | |
| 13 | /// Onde Cloud's OpenAI-compatible endpoint. |
| 14 | pub const DEFAULT_BASE_URL: &str = "https://cloud.ondeinference.com/v1"; |
| 15 | /// The model used when neither the profile nor the environment names one. |
| 16 | pub const DEFAULT_MODEL: &str = "onde-kkk"; |
| 17 | /// The credential every Onde agent reads: `app-id:app-secret`. |
| 18 | pub const API_KEY_VAR: &str = "ONDE_API_KEY"; |
| 19 | /// Base URL of a generic OpenAI API compatible endpoint when `OPENAI_BASE_URL` is unset. |
| 20 | pub const OPENAI_DEFAULT_BASE_URL: &str = "https://api.openai.com/v1"; |
| 21 | /// Model for a generic endpoint when neither `<PREFIX>_MODEL` nor `OPENAI_MODEL` is set. |
| 22 | pub const OPENAI_DEFAULT_MODEL: &str = "gpt-4o-mini"; |
| 23 | |
| 24 | /// The on-device model when `<PREFIX>_MODEL` is unset: Qwen3 1.7B on phones, where memory is |
| 25 | /// tight, Qwen3 4B Instruct 2507 elsewhere. Both are in onde's tool-calling catalog. |
| 26 | #[cfg(any(target_os = "ios", target_os = "android"))] |
| 27 | pub const LOCAL_DEFAULT_MODEL: &str = "bartowski/Qwen_Qwen3-1.7B-GGUF"; |
| 28 | /// The on-device model when `<PREFIX>_MODEL` is unset: Qwen3 1.7B on phones, where memory is |
| 29 | /// tight, Qwen3 4B Instruct 2507 elsewhere. Both are in onde's tool-calling catalog. |
| 30 | #[cfg(not(any(target_os = "ios", target_os = "android")))] |
| 31 | pub const LOCAL_DEFAULT_MODEL: &str = "bartowski/Qwen_Qwen3-4B-Instruct-2507-GGUF"; |
| 32 | |
| 33 | /// Where completions come from. Both speak the OpenAI chat completions API. |
| 34 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 35 | pub enum Provider { |
| 36 | /// Onde Cloud: `ONDE_API_KEY` (`app-id:app-secret`), `<PREFIX>_BASE_URL` or |
| 37 | /// `ONDE_BASE_URL` for a local or staging deployment. |
| 38 | Onde, |
| 39 | /// Any OpenAI API compatible endpoint: `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL`. |
| 40 | OpenAi, |
| 41 | /// On-device inference with onde: no endpoint and no key. `<PREFIX>_MODEL` names a model |
| 42 | /// from onde's tool-calling catalog. Needs the `local` feature; without it every turn fails |
| 43 | /// with an error saying so. |
| 44 | Local, |
| 45 | } |
| 46 | |
| 47 | impl Provider { |
| 48 | /// `onde` or `openai`, as written to `<PREFIX>_PROVIDER`. |
| 49 | pub fn name(self) -> &'static str { |
| 50 | match self { |
| 51 | Self::Onde => "onde", |
| 52 | Self::OpenAi => "openai", |
| 53 | Self::Local => "local", |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn parse(name: &str) -> Option<Self> { |
| 58 | match name.to_ascii_lowercase().as_str() { |
| 59 | "onde" | "onde-cloud" | "ondeinference" => Some(Self::Onde), |
| 60 | "openai" => Some(Self::OpenAi), |
| 61 | "local" | "on-device" | "ondevice" => Some(Self::Local), |
| 62 | _ => None, |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | /// The variable holding this provider's key. Empty for [`Provider::Local`], which has none. |
| 67 | pub fn key_var(self) -> &'static str { |
| 68 | match self { |
| 69 | Self::Onde => API_KEY_VAR, |
| 70 | Self::OpenAi => "OPENAI_API_KEY", |
| 71 | Self::Local => "", |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// Name shown to people, e.g. in setup and errors. |
| 76 | pub fn display_name(self) -> &'static str { |
| 77 | match self { |
| 78 | Self::Onde => "Onde Inference", |
| 79 | Self::OpenAi => "the OpenAI API compatible endpoint", |
| 80 | Self::Local => "on-device inference", |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// Where an agent's settings come from: `<PREFIX>_BASE_URL`, `<PREFIX>_MODEL` and |
| 86 | /// `<PREFIX>_DATA_DIR` in the environment, then `<config dir>/<dir_name>/env`. |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 88 | pub struct LlmEnv { |
| 89 | /// Environment prefix, e.g. `SPLITFIRE`. |
| 90 | pub prefix: &'static str, |
| 91 | /// Directory name under the platform config dir, e.g. `splitfire-agent`. |
| 92 | pub dir_name: &'static str, |
| 93 | /// Model when `<PREFIX>_MODEL` is unset. |
| 94 | pub default_model: &'static str, |
| 95 | } |
| 96 | |
| 97 | impl LlmEnv { |
| 98 | pub fn var(&self, suffix: &str) -> String { |
| 99 | format!("{}_{suffix}", self.prefix) |
| 100 | } |
| 101 | |
| 102 | /// Directory for the stored `env` file: `~/.config/<dir_name>` on Linux, |
| 103 | /// `~/Library/Application Support/<dir_name>` on macOS, `%APPDATA%\\<dir_name>` on |
| 104 | /// Windows. `<PREFIX>_DATA_DIR` overrides it (tests). `None` without a home directory. |
| 105 | pub fn config_dir(&self) -> Option<std::path::PathBuf> { |
| 106 | if let Some(dir) = std::env::var_os(self.var("DATA_DIR")).filter(|v| !v.is_empty()) { |
| 107 | return Some(dir.into()); |
| 108 | } |
| 109 | directories::BaseDirs::new().map(|dirs| { |
| 110 | #[cfg(target_os = "linux")] |
| 111 | let base = dirs.config_dir(); |
| 112 | #[cfg(not(target_os = "linux"))] |
| 113 | let base = dirs.data_dir(); |
| 114 | base.join(self.dir_name) |
| 115 | }) |
| 116 | } |
| 117 | |
| 118 | /// The stored `env` file `--setup` writes and `logout` removes. |
| 119 | pub fn config_file(&self) -> Option<std::path::PathBuf> { |
| 120 | self.config_dir().map(|d| d.join("env")) |
| 121 | } |
| 122 | |
| 123 | /// Where the stored `env` file is looked for, most preferred first: [`Self::config_file`], |
| 124 | /// then `~/.config/<dir_name>/env`, where agents on macOS kept it before they moved to the |
| 125 | /// platform directory. Only the first is used when `<PREFIX>_DATA_DIR` is set. |
| 126 | pub fn config_file_candidates(&self) -> Vec<std::path::PathBuf> { |
| 127 | let mut paths: Vec<std::path::PathBuf> = self.config_file().into_iter().collect(); |
| 128 | let overridden = std::env::var_os(self.var("DATA_DIR")).is_some_and(|v| !v.is_empty()); |
| 129 | #[cfg(not(target_os = "windows"))] |
| 130 | if !overridden && let Some(dirs) = directories::BaseDirs::new() { |
| 131 | let legacy = dirs |
| 132 | .home_dir() |
| 133 | .join(".config") |
| 134 | .join(self.dir_name) |
| 135 | .join("env"); |
| 136 | if !paths.contains(&legacy) { |
| 137 | paths.push(legacy); |
| 138 | } |
| 139 | } |
| 140 | #[cfg(target_os = "windows")] |
| 141 | let _ = overridden; |
| 142 | paths |
| 143 | } |
| 144 | |
| 145 | /// Where durable state (sessions, audio scratch) lives. Same directory as the `env` file. |
| 146 | pub fn data_dir(&self) -> std::path::PathBuf { |
| 147 | self.config_dir() |
| 148 | .unwrap_or_else(|| std::env::temp_dir().join(self.dir_name)) |
| 149 | } |
| 150 | |
| 151 | fn load_file_vars(&self) -> std::collections::HashMap<String, String> { |
| 152 | let mut vars = std::collections::HashMap::new(); |
| 153 | let content = self |
| 154 | .config_file_candidates() |
| 155 | .iter() |
| 156 | .find_map(|p| std::fs::read_to_string(p).ok()); |
| 157 | let Some(content) = content else { |
| 158 | return vars; |
| 159 | }; |
| 160 | for line in content.lines() { |
| 161 | let line = line.trim(); |
| 162 | if line.is_empty() || line.starts_with('#') { |
| 163 | continue; |
| 164 | } |
| 165 | let line = line.strip_prefix("export ").unwrap_or(line).trim(); |
| 166 | if let Some((k, v)) = line.split_once('=') { |
| 167 | let mut v = v.trim(); |
| 168 | if v.len() >= 2 |
| 169 | && ((v.starts_with('"') && v.ends_with('"')) |
| 170 | || (v.starts_with('\'') && v.ends_with('\''))) |
| 171 | { |
| 172 | v = &v[1..v.len() - 1]; |
| 173 | } |
| 174 | vars.insert(k.trim().to_string(), v.to_string()); |
| 175 | } |
| 176 | } |
| 177 | vars |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 182 | pub struct LlmConfig { |
| 183 | pub provider: Provider, |
| 184 | pub base_url: String, |
| 185 | /// Sent as the bearer token. For Onde Cloud, `app-id:app-secret`. |
| 186 | pub api_key: Option<String>, |
| 187 | pub model: String, |
| 188 | } |
| 189 | |
| 190 | impl LlmConfig { |
| 191 | /// Settings from the environment, falling back to the stored `env` file. |
| 192 | /// |
| 193 | /// The provider is `<PREFIX>_PROVIDER` (`onde` or `openai`) when set, else Onde Cloud |
| 194 | /// whenever `ONDE_API_KEY` is set, else a generic endpoint when `OPENAI_API_KEY` is, else |
| 195 | /// Onde Cloud. Onde Cloud reads only `ONDE_API_KEY`, and its own URL unless |
| 196 | /// `<PREFIX>_BASE_URL` or `ONDE_BASE_URL` names another deployment, so stray `OPENAI_*` |
| 197 | /// variables can't redirect it or send it the wrong key. A generic endpoint reads |
| 198 | /// `OPENAI_BASE_URL`, `OPENAI_API_KEY` and `OPENAI_MODEL`. `<PREFIX>_MODEL` picks the |
| 199 | /// model for either. |
| 200 | /// |
| 201 | /// Empty values are ignored: GUI launchers (e.g. Zed via launchd) often export |
| 202 | /// variables set to "", which must not mask the config file. |
| 203 | pub fn from_env(env: &LlmEnv) -> Self { |
| 204 | let file_vars = env.load_file_vars(); |
| 205 | Self::from_lookup(env, |name| { |
| 206 | std::env::var(name) |
| 207 | .ok() |
| 208 | .filter(|v| !v.is_empty()) |
| 209 | .or_else(|| file_vars.get(name).cloned()) |
| 210 | }) |
| 211 | } |
| 212 | |
| 213 | /// Build a config from an arbitrary variable lookup (tests, setup). |
| 214 | pub fn from_lookup(env: &LlmEnv, lookup: impl Fn(&str) -> Option<String>) -> Self { |
| 215 | let get = |name: &str| lookup(name).filter(|v| !v.is_empty()); |
| 216 | let provider = match get(&env.var("PROVIDER")) { |
| 217 | Some(name) => Provider::parse(&name).unwrap_or_else(|| { |
| 218 | tracing::warn!("unknown {} {name:?}; using onde", env.var("PROVIDER")); |
| 219 | Provider::Onde |
| 220 | }), |
| 221 | None if get(API_KEY_VAR).is_some() => Provider::Onde, |
| 222 | None if get("OPENAI_API_KEY").is_some() => Provider::OpenAi, |
| 223 | None => Provider::Onde, |
| 224 | }; |
| 225 | let (base_url, model) = match provider { |
| 226 | Provider::Onde => ( |
| 227 | get(&env.var("BASE_URL")) |
| 228 | .or_else(|| get("ONDE_BASE_URL")) |
| 229 | .unwrap_or_else(|| DEFAULT_BASE_URL.into()), |
| 230 | get(&env.var("MODEL")).unwrap_or_else(|| env.default_model.into()), |
| 231 | ), |
| 232 | Provider::OpenAi => ( |
| 233 | get("OPENAI_BASE_URL").unwrap_or_else(|| OPENAI_DEFAULT_BASE_URL.into()), |
| 234 | get(&env.var("MODEL")) |
| 235 | .or_else(|| get("OPENAI_MODEL")) |
| 236 | .unwrap_or_else(|| OPENAI_DEFAULT_MODEL.into()), |
| 237 | ), |
| 238 | Provider::Local => ( |
| 239 | String::new(), |
| 240 | get(&env.var("MODEL")).unwrap_or_else(|| LOCAL_DEFAULT_MODEL.into()), |
| 241 | ), |
| 242 | }; |
| 243 | Self { |
| 244 | provider, |
| 245 | base_url: base_url.trim_end_matches('/').to_string(), |
| 246 | // On-device inference has no key, and `get("")` must not find one in an env file. |
| 247 | api_key: match provider { |
| 248 | Provider::Local => None, |
| 249 | _ => get(provider.key_var()), |
| 250 | }, |
| 251 | model, |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | /// A non-2xx answer from the LLM endpoint, with the provider's message pulled out of the body. |
| 257 | #[derive(Debug, Clone)] |
| 258 | pub struct EndpointError { |
| 259 | pub source_name: String, |
| 260 | pub status: u16, |
| 261 | pub message: String, |
| 262 | } |
| 263 | |
| 264 | impl std::fmt::Display for EndpointError { |
| 265 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 266 | match reqwest::StatusCode::from_u16(self.status) { |
| 267 | Ok(status) => write!( |
| 268 | f, |
| 269 | "{} returned {status}: {}", |
| 270 | self.source_name, self.message |
| 271 | ), |
| 272 | Err(_) => write!( |
| 273 | f, |
| 274 | "{} returned {}: {}", |
| 275 | self.source_name, self.status, self.message |
| 276 | ), |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | impl std::error::Error for EndpointError {} |
| 282 | |
| 283 | /// Best human-readable text in an error body: `error.message`, `message`, or a string `error` |
| 284 | /// from a JSON body; otherwise the trimmed raw text, or the status reason when it is empty. |
| 285 | fn endpoint_message(status: u16, body: &str) -> String { |
| 286 | if let Ok(v) = serde_json::from_str::<Value>(body) { |
| 287 | let found = v |
| 288 | .pointer("/error/message") |
| 289 | .and_then(Value::as_str) |
| 290 | .or_else(|| v.get("message").and_then(Value::as_str)) |
| 291 | .or_else(|| v.get("error").and_then(Value::as_str)) |
| 292 | .map(str::trim) |
| 293 | .filter(|m| !m.is_empty()); |
| 294 | if let Some(m) = found { |
| 295 | return m.to_string(); |
| 296 | } |
| 297 | } |
| 298 | let text = body.trim(); |
| 299 | if text.is_empty() { |
| 300 | return reqwest::StatusCode::from_u16(status) |
| 301 | .ok() |
| 302 | .and_then(|s| s.canonical_reason()) |
| 303 | .unwrap_or("no response body") |
| 304 | .to_string(); |
| 305 | } |
| 306 | text.to_string() |
| 307 | } |
| 308 | |
| 309 | async fn endpoint_error(source_name: &str, resp: reqwest::Response) -> anyhow::Error { |
| 310 | let status = resp.status().as_u16(); |
| 311 | let body = resp.text().await.unwrap_or_default(); |
| 312 | endpoint_error_from_body(source_name, status, &body) |
| 313 | } |
| 314 | |
| 315 | fn endpoint_error_from_body(source_name: &str, status: u16, body: &str) -> anyhow::Error { |
| 316 | anyhow::Error::new(EndpointError { |
| 317 | source_name: source_name.to_string(), |
| 318 | status, |
| 319 | message: endpoint_message(status, body), |
| 320 | }) |
| 321 | } |
| 322 | |
| 323 | #[cfg(test)] |
| 324 | mod tests { |
| 325 | use super::*; |
| 326 | |
| 327 | #[test] |
| 328 | fn endpoint_message_prefers_error_message() { |
| 329 | let body = r#"{"error":{"message":"Rate limit reached","type":"rate_limit"}}"#; |
| 330 | assert_eq!(endpoint_message(429, body), "Rate limit reached"); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn endpoint_message_falls_back_to_top_level_fields() { |
| 335 | assert_eq!(endpoint_message(400, r#"{"message":"bad"}"#), "bad"); |
| 336 | assert_eq!(endpoint_message(400, r#"{"error":"nope"}"#), "nope"); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn endpoint_message_keeps_non_json_text() { |
| 341 | assert_eq!( |
| 342 | endpoint_message(502, " <html>Bad Gateway</html>\n"), |
| 343 | "<html>Bad Gateway</html>" |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn endpoint_message_json_without_message_keeps_raw() { |
| 349 | let body = r#"{"detail":"x"}"#; |
| 350 | assert_eq!(endpoint_message(422, body), body); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn endpoint_message_empty_body_uses_reason() { |
| 355 | assert_eq!(endpoint_message(503, " "), "Service Unavailable"); |
| 356 | } |
| 357 | |
| 358 | #[test] |
| 359 | fn endpoint_error_display_keeps_prefix() { |
| 360 | let e = EndpointError { |
| 361 | source_name: "LLM endpoint".into(), |
| 362 | status: 429, |
| 363 | message: "slow down".into(), |
| 364 | }; |
| 365 | assert_eq!( |
| 366 | e.to_string(), |
| 367 | "LLM endpoint returned 429 Too Many Requests: slow down" |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | const ENV: LlmEnv = LlmEnv { |
| 372 | prefix: "SPLITFIRE", |
| 373 | dir_name: "splitfire-agent", |
| 374 | default_model: DEFAULT_MODEL, |
| 375 | }; |
| 376 | |
| 377 | fn config(vars: &[(&str, &str)]) -> LlmConfig { |
| 378 | LlmConfig::from_lookup(&ENV, |name| { |
| 379 | vars.iter() |
| 380 | .find(|(k, _)| *k == name) |
| 381 | .map(|(_, v)| v.to_string()) |
| 382 | }) |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn defaults_point_at_onde_cloud() { |
| 387 | let c = config(&[("ONDE_API_KEY", "app:secret")]); |
| 388 | assert_eq!(c.base_url, "https://cloud.ondeinference.com/v1"); |
| 389 | assert_eq!(c.api_key.as_deref(), Some("app:secret")); |
| 390 | assert_eq!(c.model, "onde-kkk"); |
| 391 | assert_eq!(config(&[]).api_key, None); |
| 392 | assert_eq!(config(&[("ONDE_API_KEY", "")]).api_key, None); |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | fn local_needs_no_key() { |
| 397 | let c = config(&[ |
| 398 | ("SPLITFIRE_PROVIDER", "local"), |
| 399 | ("ONDE_API_KEY", "app:secret"), |
| 400 | ]); |
| 401 | assert_eq!(c.provider, Provider::Local); |
| 402 | assert_eq!(c.model, LOCAL_DEFAULT_MODEL); |
| 403 | // A stored Onde key is not this provider's. |
| 404 | assert_eq!(c.api_key, None); |
| 405 | assert!(LlmClient::new(c).has_api_key()); |
| 406 | assert_eq!(Provider::parse("on-device"), Some(Provider::Local)); |
| 407 | let picked = config(&[ |
| 408 | ("SPLITFIRE_PROVIDER", "local"), |
| 409 | ("SPLITFIRE_MODEL", "bartowski/Qwen_Qwen3-8B-GGUF"), |
| 410 | ]); |
| 411 | assert_eq!(picked.model, "bartowski/Qwen_Qwen3-8B-GGUF"); |
| 412 | } |
| 413 | |
| 414 | #[test] |
| 415 | fn base_url_and_model_overrides_apply() { |
| 416 | let c = config(&[ |
| 417 | ("ONDE_API_KEY", "app:secret"), |
| 418 | ("SPLITFIRE_MODEL", "onde-prism"), |
| 419 | ("SPLITFIRE_BASE_URL", "http://x/v1/"), |
| 420 | ]); |
| 421 | assert_eq!( |
| 422 | (c.base_url.as_str(), c.model.as_str()), |
| 423 | ("http://x/v1", "onde-prism") |
| 424 | ); |
| 425 | } |
| 426 | |
| 427 | #[test] |
| 428 | fn onde_base_url_points_onde_at_another_deployment() { |
| 429 | let c = config(&[ |
| 430 | ("ONDE_API_KEY", "app:secret"), |
| 431 | ("ONDE_BASE_URL", "http://localhost:8090/v1/"), |
| 432 | ]); |
| 433 | assert_eq!(c.base_url, "http://localhost:8090/v1"); |
| 434 | let both = config(&[ |
| 435 | ("ONDE_BASE_URL", "http://a/v1"), |
| 436 | ("SPLITFIRE_BASE_URL", "http://b/v1"), |
| 437 | ]); |
| 438 | assert_eq!(both.base_url, "http://b/v1"); |
| 439 | } |
| 440 | |
| 441 | #[test] |
| 442 | fn openai_key_selects_a_generic_endpoint() { |
| 443 | let c = config(&[ |
| 444 | ("OPENAI_API_KEY", "sk"), |
| 445 | ("OPENAI_MODEL", "my-model"), |
| 446 | ("OPENAI_BASE_URL", "http://x/v1/"), |
| 447 | ("ONDE_BASE_URL", "http://onde/v1"), |
| 448 | ]); |
| 449 | assert_eq!( |
| 450 | ( |
| 451 | c.provider, |
| 452 | c.base_url.as_str(), |
| 453 | c.api_key.as_deref(), |
| 454 | c.model.as_str() |
| 455 | ), |
| 456 | (Provider::OpenAi, "http://x/v1", Some("sk"), "my-model") |
| 457 | ); |
| 458 | let plain = config(&[("OPENAI_API_KEY", "sk")]); |
| 459 | assert_eq!( |
| 460 | (plain.base_url.as_str(), plain.model.as_str()), |
| 461 | ("https://api.openai.com/v1", "gpt-4o-mini") |
| 462 | ); |
| 463 | assert_eq!(config(&[]).provider, Provider::Onde); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn onde_wins_over_openai_variables() { |
| 468 | let c = config(&[ |
| 469 | ("ONDE_API_KEY", "app:secret"), |
| 470 | ("OPENAI_API_KEY", "sk-other"), |
| 471 | ("OPENAI_BASE_URL", "http://elsewhere/v1"), |
| 472 | ("OPENAI_MODEL", "gpt-x"), |
| 473 | ]); |
| 474 | assert_eq!(c.provider, Provider::Onde); |
| 475 | assert_eq!(c.api_key.as_deref(), Some("app:secret")); |
| 476 | assert_eq!(c.base_url, "https://cloud.ondeinference.com/v1"); |
| 477 | assert_eq!(c.model, "onde-kkk"); |
| 478 | } |
| 479 | |
| 480 | #[test] |
| 481 | fn explicit_provider_wins_over_detected_keys() { |
| 482 | let c = config(&[ |
| 483 | ("ONDE_API_KEY", "app:secret"), |
| 484 | ("OPENAI_API_KEY", "sk"), |
| 485 | ("SPLITFIRE_PROVIDER", "openai"), |
| 486 | ("SPLITFIRE_MODEL", "m"), |
| 487 | ]); |
| 488 | assert_eq!( |
| 489 | (c.provider, c.api_key.as_deref(), c.model.as_str()), |
| 490 | (Provider::OpenAi, Some("sk"), "m") |
| 491 | ); |
| 492 | let onde = config(&[("SPLITFIRE_PROVIDER", "onde"), ("OPENAI_API_KEY", "sk")]); |
| 493 | assert_eq!((onde.provider, onde.api_key), (Provider::Onde, None)); |
| 494 | } |
| 495 | |
| 496 | /// One test touches the process environment, so it can't race another. |
| 497 | #[test] |
| 498 | fn key_from_env_then_file_ignoring_empty_env() { |
| 499 | let dir = std::env::temp_dir().join(format!("sf-llm-{}", uuid::Uuid::new_v4())); |
| 500 | std::fs::create_dir_all(&dir).unwrap(); |
| 501 | std::fs::write( |
| 502 | dir.join("env"), |
| 503 | "# comment\nexport ONDE_API_KEY=\"file:key\"\nSPLITFIRE_MODEL=m1\n", |
| 504 | ) |
| 505 | .unwrap(); |
| 506 | // SAFETY: only this test mutates these variables. |
| 507 | unsafe { |
| 508 | std::env::set_var("SPLITFIRE_DATA_DIR", &dir); |
| 509 | std::env::set_var("ONDE_API_KEY", ""); |
| 510 | } |
| 511 | assert_eq!(ENV.config_file_candidates(), vec![dir.join("env")]); |
| 512 | let c = LlmConfig::from_env(&ENV); |
| 513 | assert_eq!(c.api_key.as_deref(), Some("file:key")); |
| 514 | assert_eq!(c.model, "m1"); |
| 515 | unsafe { std::env::set_var("ONDE_API_KEY", "env:key") }; |
| 516 | assert_eq!( |
| 517 | LlmConfig::from_env(&ENV).api_key.as_deref(), |
| 518 | Some("env:key") |
| 519 | ); |
| 520 | unsafe { |
| 521 | std::env::remove_var("ONDE_API_KEY"); |
| 522 | std::env::remove_var("SPLITFIRE_DATA_DIR"); |
| 523 | } |
| 524 | let _ = std::fs::remove_dir_all(dir); |
| 525 | } |
| 526 | |
| 527 | #[test] |
| 528 | fn usage_tolerates_missing_total() { |
| 529 | let chunk: Chunk = serde_json::from_str( |
| 530 | r#"{"choices":[],"usage":{"prompt_tokens":7,"completion_tokens":3}}"#, |
| 531 | ) |
| 532 | .unwrap(); |
| 533 | assert_eq!(chunk.usage.unwrap().used(), 10); |
| 534 | let full = Usage { |
| 535 | prompt_tokens: 1, |
| 536 | completion_tokens: 1, |
| 537 | total_tokens: 5, |
| 538 | }; |
| 539 | assert_eq!(full.used(), 5); |
| 540 | } |
| 541 | |
| 542 | #[test] |
| 543 | fn parses_models_response() { |
| 544 | let body = r#"{ |
| 545 | "object": "list", |
| 546 | "data": [ |
| 547 | {"id": "onde-balanced", "object": "model", "created": 1700000000, "owned_by": "onde"}, |
| 548 | {"id": "custom-model"} |
| 549 | ] |
| 550 | }"#; |
| 551 | let parsed: ModelsResponse = serde_json::from_str(body).unwrap(); |
| 552 | assert_eq!(parsed.data.len(), 2); |
| 553 | assert_eq!(parsed.data[0].owned_by.as_deref(), Some("onde")); |
| 554 | assert_eq!(parsed.data[1].owned_by, None); |
| 555 | } |
| 556 | |
| 557 | /// An Onde Cloud stand-in for one app allowed only `onde-air`: `good:key` is accepted, |
| 558 | /// other keys get 401, and any other model gets 503, as Onde Cloud answers a model outside |
| 559 | /// the app's allowed set. Returns the base URL. |
| 560 | async fn app_limited_to_onde_air() -> String { |
| 561 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 562 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 563 | let addr = listener.local_addr().unwrap(); |
| 564 | tokio::spawn(async move { |
| 565 | loop { |
| 566 | let Ok((mut sock, _)) = listener.accept().await else { |
| 567 | return; |
| 568 | }; |
| 569 | tokio::spawn(async move { |
| 570 | let mut buf = Vec::new(); |
| 571 | let mut chunk = [0u8; 4096]; |
| 572 | // Headers, then as much body as Content-Length says. |
| 573 | let request = loop { |
| 574 | let n = sock.read(&mut chunk).await.unwrap_or(0); |
| 575 | if n == 0 { |
| 576 | return; |
| 577 | } |
| 578 | buf.extend_from_slice(&chunk[..n]); |
| 579 | let text = String::from_utf8_lossy(&buf).to_string(); |
| 580 | if let Some(end) = text.find("\r\n\r\n") { |
| 581 | let len = text[..end] |
| 582 | .lines() |
| 583 | .find_map(|l| { |
| 584 | l.to_ascii_lowercase() |
| 585 | .strip_prefix("content-length:") |
| 586 | .map(|v| v.trim().parse::<usize>().unwrap_or(0)) |
| 587 | }) |
| 588 | .unwrap_or(0); |
| 589 | if buf.len() >= end + 4 + len { |
| 590 | break text; |
| 591 | } |
| 592 | } |
| 593 | }; |
| 594 | let authorized = request.contains("Bearer good:key"); |
| 595 | let (status, body) = if !authorized { |
| 596 | ("401 Unauthorized", r#"{"error":{}}"#) |
| 597 | } else if request.starts_with("GET /v1/models") { |
| 598 | ("200 OK", r#"{"object":"list","data":[{"id":"onde-air"}]}"#) |
| 599 | } else if request.contains(r#""model":"onde-air""#) { |
| 600 | ("200 OK", r#"{"choices":[]}"#) |
| 601 | } else { |
| 602 | ( |
| 603 | "503 Service Unavailable", |
| 604 | r#"{"error":{"message":"model onde-kkk is not available"}}"#, |
| 605 | ) |
| 606 | }; |
| 607 | let reply = format!( |
| 608 | "HTTP/1.1 {status}\r\ncontent-type: application/json\r\n\ |
| 609 | content-length: {}\r\nconnection: close\r\n\r\n{body}", |
| 610 | body.len() |
| 611 | ); |
| 612 | let _ = sock.write_all(reply.as_bytes()).await; |
| 613 | }); |
| 614 | } |
| 615 | }); |
| 616 | format!("http://{addr}/v1") |
| 617 | } |
| 618 | |
| 619 | fn client(base_url: &str, key: &str, model: &str) -> LlmClient { |
| 620 | LlmClient::new(LlmConfig { |
| 621 | provider: Provider::Onde, |
| 622 | base_url: base_url.to_string(), |
| 623 | api_key: Some(key.to_string()), |
| 624 | model: model.to_string(), |
| 625 | }) |
| 626 | } |
| 627 | |
| 628 | #[tokio::test] |
| 629 | async fn verify_key_falls_back_to_a_model_the_app_allows() { |
| 630 | let url = app_limited_to_onde_air().await; |
| 631 | // Regression: a new app without the default tier failed setup with exit code 1. |
| 632 | let fallback = client(&url, "good:key", DEFAULT_MODEL).verify_key().await; |
| 633 | assert_eq!(fallback.unwrap(), "onde-air"); |
| 634 | let allowed = client(&url, "good:key", "onde-air").verify_key().await; |
| 635 | assert_eq!(allowed.unwrap(), "onde-air"); |
| 636 | let err = client(&url, "bad:key", DEFAULT_MODEL) |
| 637 | .verify_key() |
| 638 | .await |
| 639 | .unwrap_err(); |
| 640 | assert!(err.to_string().contains("rejected the API key"), "{err:#}"); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | #[derive(Debug, Clone, Default)] |
| 645 | pub struct ToolCallRequest { |
| 646 | pub id: String, |
| 647 | pub name: String, |
| 648 | pub arguments: String, |
| 649 | /// Provider extras that must be echoed back (e.g. Gemini's `thought_signature`). |
| 650 | pub extra_content: Option<Value>, |
| 651 | } |
| 652 | |
| 653 | #[derive(Debug, Default)] |
| 654 | pub struct Completion { |
| 655 | pub content: String, |
| 656 | pub tool_calls: Vec<ToolCallRequest>, |
| 657 | pub finish_reason: Option<String>, |
| 658 | /// Token usage, when the endpoint reports it (`stream_options.include_usage`). |
| 659 | pub usage: Option<Usage>, |
| 660 | } |
| 661 | |
| 662 | #[derive(Debug, Clone, Copy, Default, Deserialize)] |
| 663 | pub struct Usage { |
| 664 | #[serde(default)] |
| 665 | pub prompt_tokens: u64, |
| 666 | #[serde(default)] |
| 667 | pub completion_tokens: u64, |
| 668 | #[serde(default)] |
| 669 | pub total_tokens: u64, |
| 670 | } |
| 671 | |
| 672 | impl Usage { |
| 673 | /// Tokens in the context after this completion. Some servers leave `total_tokens` at 0. |
| 674 | pub fn used(&self) -> u64 { |
| 675 | self.total_tokens |
| 676 | .max(self.prompt_tokens + self.completion_tokens) |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | impl Completion { |
| 681 | /// The assistant message to append to the conversation history. |
| 682 | pub fn to_message(&self) -> Value { |
| 683 | let mut msg = json!({ "role": "assistant", "content": self.content }); |
| 684 | if !self.tool_calls.is_empty() { |
| 685 | msg["tool_calls"] = self |
| 686 | .tool_calls |
| 687 | .iter() |
| 688 | .map(|tc| { |
| 689 | let mut call = json!({ |
| 690 | "id": tc.id, |
| 691 | "type": "function", |
| 692 | "function": { "name": tc.name, "arguments": tc.arguments }, |
| 693 | }); |
| 694 | if let Some(extra) = &tc.extra_content { |
| 695 | call["extra_content"] = extra.clone(); |
| 696 | } |
| 697 | call |
| 698 | }) |
| 699 | .collect(); |
| 700 | } |
| 701 | msg |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | /// Streamed pieces surfaced to the caller as they arrive. |
| 706 | pub enum Delta<'a> { |
| 707 | Text(&'a str), |
| 708 | Reasoning(&'a str), |
| 709 | } |
| 710 | |
| 711 | #[derive(Deserialize)] |
| 712 | struct Chunk { |
| 713 | #[serde(default)] |
| 714 | choices: Vec<Choice>, |
| 715 | usage: Option<Usage>, |
| 716 | } |
| 717 | |
| 718 | #[derive(Deserialize)] |
| 719 | struct Choice { |
| 720 | #[serde(default)] |
| 721 | delta: ChunkDelta, |
| 722 | finish_reason: Option<String>, |
| 723 | } |
| 724 | |
| 725 | #[derive(Deserialize, Default)] |
| 726 | struct ChunkDelta { |
| 727 | content: Option<String>, |
| 728 | // Non-standard but common (DeepSeek, vLLM, OpenRouter, llama.cpp). |
| 729 | reasoning_content: Option<String>, |
| 730 | reasoning: Option<String>, |
| 731 | #[serde(default)] |
| 732 | tool_calls: Vec<ToolCallDelta>, |
| 733 | } |
| 734 | |
| 735 | #[derive(Deserialize)] |
| 736 | struct ToolCallDelta { |
| 737 | #[serde(default)] |
| 738 | index: usize, |
| 739 | id: Option<String>, |
| 740 | function: Option<FunctionDelta>, |
| 741 | extra_content: Option<Value>, |
| 742 | } |
| 743 | |
| 744 | #[derive(Deserialize)] |
| 745 | struct FunctionDelta { |
| 746 | name: Option<String>, |
| 747 | arguments: Option<String>, |
| 748 | } |
| 749 | |
| 750 | /// A model from `GET /v1/models`. Extra fields in the response are ignored. |
| 751 | #[derive(Debug, Clone, Deserialize)] |
| 752 | pub struct ModelInfo { |
| 753 | pub id: String, |
| 754 | #[serde(default)] |
| 755 | pub owned_by: Option<String>, |
| 756 | } |
| 757 | |
| 758 | #[derive(Deserialize)] |
| 759 | struct ModelsResponse { |
| 760 | data: Vec<ModelInfo>, |
| 761 | } |
| 762 | |
| 763 | #[derive(Debug, Clone)] |
| 764 | pub struct LlmClient { |
| 765 | http: reqwest::Client, |
| 766 | config: LlmConfig, |
| 767 | } |
| 768 | |
| 769 | impl LlmClient { |
| 770 | pub fn new(config: LlmConfig) -> Self { |
| 771 | Self { |
| 772 | http: reqwest::Client::new(), |
| 773 | config, |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | pub fn model(&self) -> &str { |
| 778 | &self.config.model |
| 779 | } |
| 780 | |
| 781 | pub fn config(&self) -> &LlmConfig { |
| 782 | &self.config |
| 783 | } |
| 784 | |
| 785 | /// Whether the provider can be used: an API key is configured, or the provider needs none |
| 786 | /// ([`Provider::Local`]). The agent answers `AUTH_REQUIRED` when this is false. |
| 787 | pub fn has_api_key(&self) -> bool { |
| 788 | self.config.provider == Provider::Local || self.config.api_key.is_some() |
| 789 | } |
| 790 | |
| 791 | /// Verify the configured key with a minimal chat completion. |
| 792 | /// Returns `Err` when no key is set, the key is rejected, or the endpoint is unreachable. |
| 793 | pub async fn check_auth(&self) -> Result<()> { |
| 794 | self.verify_key().await.map(drop) |
| 795 | } |
| 796 | |
| 797 | /// [`Self::check_auth`], returning the model the check passed with: the configured one, |
| 798 | /// unless the endpoint refuses it while listing others for this key. Onde Cloud answers a |
| 799 | /// model outside an app's allowed set with 503 "not available", so a new app limited to, |
| 800 | /// say, `onde-air` would otherwise fail setup on the default tier. Then the first listed |
| 801 | /// model is tried and returned, for the caller to store as `<PREFIX>_MODEL`. |
| 802 | pub async fn verify_key(&self) -> Result<String> { |
| 803 | let provider = self.config.provider; |
| 804 | let model = &self.config.model; |
| 805 | if provider == Provider::Local { |
| 806 | return Ok(model.clone()); |
| 807 | } |
| 808 | let Some(key) = &self.config.api_key else { |
| 809 | bail!("no {} configured", provider.key_var()); |
| 810 | }; |
| 811 | let (status, text) = self.ping(key, model).await?; |
| 812 | if status.is_success() { |
| 813 | return Ok(model.clone()); |
| 814 | } |
| 815 | if matches!(status.as_u16(), 401 | 403) { |
| 816 | bail!( |
| 817 | "{} rejected the API key ({status})", |
| 818 | provider.display_name() |
| 819 | ); |
| 820 | } |
| 821 | // The key got past authentication; the model may be what was refused. |
| 822 | if let Ok(models) = self.models().await |
| 823 | && !models.iter().any(|m| &m.id == model) |
| 824 | && let Some(other) = models.first() |
| 825 | && self.ping(key, &other.id).await?.0.is_success() |
| 826 | { |
| 827 | return Ok(other.id.clone()); |
| 828 | } |
| 829 | Err(endpoint_error_from_body( |
| 830 | provider.display_name(), |
| 831 | status.as_u16(), |
| 832 | &text, |
| 833 | )) |
| 834 | } |
| 835 | |
| 836 | /// A one-token, non-streaming chat completion with `model`: its status and body. |
| 837 | async fn ping(&self, key: &str, model: &str) -> Result<(reqwest::StatusCode, String)> { |
| 838 | let body = json!({ |
| 839 | "model": model, |
| 840 | "messages": [{ "role": "user", "content": "ping" }], |
| 841 | "max_tokens": 1, |
| 842 | "stream": false, |
| 843 | }); |
| 844 | let resp = self |
| 845 | .http |
| 846 | .post(format!("{}/chat/completions", self.config.base_url)) |
| 847 | .json(&body) |
| 848 | .bearer_auth(key) |
| 849 | .send() |
| 850 | .await |
| 851 | .with_context(|| format!("reaching {}", self.config.provider.display_name()))?; |
| 852 | let status = resp.status(); |
| 853 | let text = resp.text().await.unwrap_or_default(); |
| 854 | Ok((status, text)) |
| 855 | } |
| 856 | |
| 857 | /// List the models the configured endpoint serves (`GET {base_url}/models`). |
| 858 | pub async fn models(&self) -> Result<Vec<ModelInfo>> { |
| 859 | if self.config.provider == Provider::Local { |
| 860 | return Ok(crate::local::catalog()); |
| 861 | } |
| 862 | let url = format!("{}/models", self.config.base_url); |
| 863 | let mut req = self.http.get(&url); |
| 864 | if let Some(key) = &self.config.api_key { |
| 865 | req = req.bearer_auth(key); |
| 866 | } |
| 867 | let mut resp = req.send().await.context("sending models request")?; |
| 868 | // Some endpoints (Onde Cloud) list models publicly but reject an invalid key, so a |
| 869 | // bad key shouldn't hide the catalog: retry without auth. |
| 870 | if self.config.api_key.is_some() && matches!(resp.status().as_u16(), 401 | 403) { |
| 871 | resp = self |
| 872 | .http |
| 873 | .get(&url) |
| 874 | .send() |
| 875 | .await |
| 876 | .context("sending models request")?; |
| 877 | } |
| 878 | if !resp.status().is_success() { |
| 879 | return Err(endpoint_error("models endpoint", resp).await); |
| 880 | } |
| 881 | let mut models = resp |
| 882 | .json::<ModelsResponse>() |
| 883 | .await |
| 884 | .context("parsing models response")? |
| 885 | .data; |
| 886 | models.sort_by(|a, b| a.id.cmp(&b.id)); |
| 887 | Ok(models) |
| 888 | } |
| 889 | |
| 890 | /// Run one streaming chat completion, invoking `on_delta` for every text fragment. |
| 891 | pub async fn complete( |
| 892 | &self, |
| 893 | model: &str, |
| 894 | messages: &[Value], |
| 895 | tools: &Value, |
| 896 | mut on_delta: impl FnMut(Delta<'_>), |
| 897 | ) -> Result<Completion> { |
| 898 | if self.config.provider == Provider::Local { |
| 899 | return crate::local::complete(model, messages, tools, on_delta).await; |
| 900 | } |
| 901 | if self.config.api_key.is_none() { |
| 902 | bail!( |
| 903 | "No API key configured. Set {} in the environment or run the agent's `--setup`", |
| 904 | self.config.provider.key_var() |
| 905 | ); |
| 906 | } |
| 907 | let mut body = json!({ |
| 908 | "model": model, |
| 909 | "messages": messages, |
| 910 | "tools": tools, |
| 911 | "stream": true, |
| 912 | "stream_options": { "include_usage": true }, |
| 913 | }); |
| 914 | let send = |body: &Value| { |
| 915 | let mut req = self |
| 916 | .http |
| 917 | .post(format!("{}/chat/completions", self.config.base_url)) |
| 918 | .json(body); |
| 919 | if let Some(key) = &self.config.api_key { |
| 920 | req = req.bearer_auth(key); |
| 921 | } |
| 922 | req.send() |
| 923 | }; |
| 924 | let mut resp = send(&body) |
| 925 | .await |
| 926 | .context("sending chat completion request")?; |
| 927 | // Not every OpenAI-compatible server knows `stream_options`; retry without it. |
| 928 | if matches!(resp.status().as_u16(), 400 | 422) { |
| 929 | body.as_object_mut().unwrap().remove("stream_options"); |
| 930 | resp = send(&body) |
| 931 | .await |
| 932 | .context("sending chat completion request")?; |
| 933 | } |
| 934 | if !resp.status().is_success() { |
| 935 | return Err(endpoint_error("LLM endpoint", resp).await); |
| 936 | } |
| 937 | |
| 938 | let mut out = Completion::default(); |
| 939 | let mut stream = resp.bytes_stream(); |
| 940 | let mut buf: Vec<u8> = Vec::new(); |
| 941 | while let Some(bytes) = stream.next().await { |
| 942 | buf.extend_from_slice(&bytes.context("reading response stream")?); |
| 943 | while let Some(pos) = buf.iter().position(|&b| b == b'\n') { |
| 944 | let line: Vec<u8> = buf.drain(..=pos).collect(); |
| 945 | let line = String::from_utf8_lossy(&line); |
| 946 | let Some(data) = line.trim().strip_prefix("data:") else { |
| 947 | continue; |
| 948 | }; |
| 949 | let data = data.trim(); |
| 950 | if data == "[DONE]" { |
| 951 | return Ok(out); |
| 952 | } |
| 953 | let chunk: Chunk = match serde_json::from_str(data) { |
| 954 | Ok(c) => c, |
| 955 | Err(e) => { |
| 956 | tracing::warn!("skipping unparseable chunk ({e}): {data}"); |
| 957 | continue; |
| 958 | } |
| 959 | }; |
| 960 | if chunk.usage.is_some() { |
| 961 | out.usage = chunk.usage; |
| 962 | } |
| 963 | for choice in chunk.choices { |
| 964 | let d = choice.delta; |
| 965 | if let Some(r) = d.reasoning_content.as_deref().or(d.reasoning.as_deref()) |
| 966 | && !r.is_empty() |
| 967 | { |
| 968 | on_delta(Delta::Reasoning(r)); |
| 969 | } |
| 970 | if let Some(t) = d.content.as_deref() |
| 971 | && !t.is_empty() |
| 972 | { |
| 973 | out.content.push_str(t); |
| 974 | on_delta(Delta::Text(t)); |
| 975 | } |
| 976 | for tc in d.tool_calls { |
| 977 | if out.tool_calls.len() <= tc.index { |
| 978 | out.tool_calls |
| 979 | .resize(tc.index + 1, ToolCallRequest::default()); |
| 980 | } |
| 981 | let slot = &mut out.tool_calls[tc.index]; |
| 982 | if let Some(id) = tc.id { |
| 983 | slot.id = id; |
| 984 | } |
| 985 | if tc.extra_content.is_some() { |
| 986 | slot.extra_content = tc.extra_content; |
| 987 | } |
| 988 | if let Some(f) = tc.function { |
| 989 | if let Some(n) = f.name { |
| 990 | slot.name.push_str(&n); |
| 991 | } |
| 992 | if let Some(a) = f.arguments { |
| 993 | slot.arguments.push_str(&a); |
| 994 | } |
| 995 | } |
| 996 | } |
| 997 | if choice.finish_reason.is_some() { |
| 998 | out.finish_reason = choice.finish_reason; |
| 999 | } |
| 1000 | } |
| 1001 | } |
| 1002 | } |
| 1003 | Ok(out) |
| 1004 | } |
| 1005 | } |