1pub mod anthropic;
9pub mod capabilities;
10pub mod catalog;
11pub mod google;
12pub mod hints;
13pub mod ollama;
14pub mod openai;
15pub mod reasoning;
16pub mod remote_windows;
17pub mod retry;
18
19pub const STOPPED_PREFIX: &str = "stopped:";
23
24use crate::config::{Config, ProviderConfig};
25use crate::pricing::PriceTable;
26use crate::secrets::{resolve_api_key, OsKeyring, SecretStore};
27use crate::types::{Completion, CompletionDelta, CompletionRequest, ModelRef};
28use anthropic::{AnthropicConfig, AnthropicProvider};
29use futures_util::future::BoxFuture;
30use futures_util::stream::{BoxStream, StreamExt};
31use ollama::{OllamaConfig, OllamaProvider};
32use openai::{OpenAiConfig, OpenAiProvider};
33use std::time::Duration;
34use thiserror::Error;
35
36const LLAMACPP_DEFAULT_BASE_URL: &str = "http://localhost:8080/v1";
38
39pub const VLLM_DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";
41
42pub const LMSTUDIO_DEFAULT_BASE_URL: &str = "http://localhost:1234/v1";
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ServerKind {
52 Vllm,
53 LmStudio,
54}
55
56impl ServerKind {
57 pub fn name(self) -> &'static str {
59 match self {
60 Self::Vllm => "vllm",
61 Self::LmStudio => "lmstudio",
62 }
63 }
64
65 pub fn default_base_url(self) -> &'static str {
67 match self {
68 Self::Vllm => VLLM_DEFAULT_BASE_URL,
69 Self::LmStudio => LMSTUDIO_DEFAULT_BASE_URL,
70 }
71 }
72
73 pub fn key_optional(self) -> bool {
77 true
78 }
79
80 pub(crate) fn parse(adapter: &str) -> Option<Self> {
81 match adapter.trim() {
82 "vllm" => Some(Self::Vllm),
83 "lmstudio" => Some(Self::LmStudio),
84 _ => None,
85 }
86 }
87}
88
89pub fn server_kind(name: &str, section: Option<&ProviderConfig>) -> Option<ServerKind> {
94 match section.and_then(|section| section.adapter.as_deref()) {
95 Some(adapter) => ServerKind::parse(adapter),
96 None => ServerKind::parse(name),
97 }
98}
99
100pub fn key_optional(name: &str, section: Option<&ProviderConfig>) -> bool {
105 server_kind(name, section).is_some_and(ServerKind::key_optional)
106}
107
108pub fn provider_for_ref(
119 reference: &ModelRef,
120 config: &Config,
121) -> Result<Box<dyn Provider>, ProviderError> {
122 provider_for_ref_with_store(reference, config, &OsKeyring)
123}
124
125pub fn provider_for_ref_with_store(
127 reference: &ModelRef,
128 config: &Config,
129 store: &dyn SecretStore,
130) -> Result<Box<dyn Provider>, ProviderError> {
131 build_provider(reference, config, |name, section| {
132 resolve_api_key(name, section.api_key_env.as_deref(), store)
133 })
134}
135
136pub(crate) fn temperature_json(temperature: f32) -> serde_json::Value {
142 let value = temperature.to_string().parse::<f64>().unwrap_or(0.0);
143 serde_json::json!(value)
144}
145
146pub fn provider_for_ref_with_key(
147 reference: &ModelRef,
148 config: &Config,
149 api_key: &str,
150) -> Result<Box<dyn Provider>, ProviderError> {
151 build_provider(reference, config, |_, _| Some(api_key.to_owned()))
152}
153
154fn build_provider(
155 reference: &ModelRef,
156 config: &Config,
157 api_key: impl FnOnce(&str, &ProviderConfig) -> Option<String>,
158) -> Result<Box<dyn Provider>, ProviderError> {
159 let name = reference.provider.as_str();
160 let section = config.providers.get(name).cloned().unwrap_or_default();
161
162 if let Some(adapter) = section.adapter.as_deref() {
163 if ServerKind::parse(adapter).is_none() {
164 return Err(ProviderError::InvalidSetting {
165 provider: name.to_owned(),
166 detail: format!(
167 "adapter must be \"vllm\" or \"lmstudio\", not {adapter:?}; remove it \
168 for a plain OpenAI-compatible endpoint"
169 ),
170 });
171 }
172 }
173
174 let temperature = section.temperature;
177 if let Some(value) = temperature {
178 if !(0.0..=2.0).contains(&value) {
179 return Err(ProviderError::InvalidSetting {
180 provider: name.to_owned(),
181 detail: format!("temperature must be between 0 and 2, not {value}"),
182 });
183 }
184 }
185
186 if name == "anthropic" {
187 let provider = AnthropicProvider::new(
189 reference.model.clone(),
190 AnthropicConfig {
191 base_url: section.base_url.clone(),
192 api_key_env: section
193 .api_key_env
194 .clone()
195 .unwrap_or_else(|| anthropic::DEFAULT_API_KEY_ENV.to_owned()),
196 max_tokens: section.max_tokens,
197 prompt_cache: section.prompt_cache,
198 max_retries: section.max_retries,
199 ..AnthropicConfig::default()
200 },
201 api_key(name, §ion),
202 )?
203 .with_pricing(PriceTable::from_config(config), reference.to_string())
204 .with_temperature(temperature);
205 return Ok(Box::new(provider));
206 }
207
208 if name == "google" {
211 let seconds = durations(name);
212 let provider = google::GoogleProvider::new(
213 reference.model.clone(),
214 google::GoogleConfig {
215 base_url: section.base_url.clone(),
216 api_key_env: section
217 .api_key_env
218 .clone()
219 .unwrap_or_else(|| google::DEFAULT_API_KEY_ENV.to_owned()),
220 config_name: name.to_owned(),
221 max_tokens: section.max_tokens,
222 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
223 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
224 max_retries: section.max_retries,
225 store: section.store,
226 },
227 api_key(name, §ion),
228 )?
229 .with_pricing(PriceTable::from_config(config), reference.to_string());
230 return Ok(Box::new(provider));
231 }
232
233 if name == "ollama" {
235 let seconds = durations(name);
236 let provider = OllamaProvider::new(
237 reference.model.clone(),
238 OllamaConfig {
239 base_url: section.base_url.clone(),
240 num_ctx: section.num_ctx,
241 max_tokens: section.max_tokens,
242 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
243 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
244 max_retries: section.max_retries,
245 },
246 )?
247 .with_temperature(temperature);
248 return Ok(Box::new(provider));
249 }
250
251 if name == "llamacpp" {
254 let mut section = section;
255 section
256 .base_url
257 .get_or_insert_with(|| LLAMACPP_DEFAULT_BASE_URL.to_owned());
258 let mut openai_config = openai_config(name, §ion, false)?;
259 openai_config.adapter = "llamacpp";
260 let provider = OpenAiProvider::new(
261 reference.model.clone(),
262 openai_config,
263 api_key(name, §ion),
264 )?
265 .with_pricing(PriceTable::from_config(config), reference.to_string())
266 .with_temperature(temperature);
267 return Ok(Box::new(provider));
268 }
269
270 if let Some(kind) = server_kind(name, Some(§ion)) {
273 let mut section = section;
274 section
275 .base_url
276 .get_or_insert_with(|| kind.default_base_url().to_owned());
277 let mut openai_config = openai_config(name, §ion, !kind.key_optional())?;
278 openai_config.adapter = kind.name();
279 let overridden = [reference.to_string().as_str(), reference.model.as_str()]
281 .iter()
282 .any(|key| {
283 config
284 .model
285 .context_window
286 .get(*key)
287 .is_some_and(|&w| w > 0)
288 });
289 openai_config.live_window = kind == ServerKind::LmStudio && !overridden;
290 let provider = OpenAiProvider::new(
291 reference.model.clone(),
292 openai_config,
293 api_key(name, §ion),
294 )?
295 .with_pricing(PriceTable::from_config(config), reference.to_string())
296 .with_temperature(temperature);
297 return Ok(Box::new(provider));
298 }
299
300 let require_key = match name {
301 "openai" | "openai-compatible" => true,
302 _ if section.base_url.is_some() => section.api_key_env.is_some(),
303 _ => {
304 return Err(ProviderError::UnknownProvider {
305 provider: name.to_owned(),
306 })
307 }
308 };
309
310 let api_key = api_key(name, §ion);
311 let openai_config = openai_config(name, §ion, require_key)?;
312 let provider = OpenAiProvider::new(reference.model.clone(), openai_config, api_key)?
313 .with_pricing(PriceTable::from_config(config), reference.to_string())
314 .with_temperature(temperature);
315 Ok(Box::new(provider))
316}
317
318fn openai_config(
319 name: &str,
320 section: &ProviderConfig,
321 require_key: bool,
322) -> Result<OpenAiConfig, ProviderError> {
323 let seconds = durations(name);
324 Ok(OpenAiConfig {
325 base_url: section.base_url.clone(),
326 api_key_env: section.api_key_env.clone(),
327 config_name: name.to_owned(),
328 adapter: "openai",
329 require_key,
330 max_tokens: section.max_tokens,
331 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
332 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
333 max_retries: section.max_retries,
334 routing: section.routing.clone(),
335 live_window: false,
336 })
337}
338
339fn durations(name: &str) -> impl Fn(&str, f64) -> Result<Duration, ProviderError> + '_ {
341 move |field, value| {
342 Duration::try_from_secs_f64(value).map_err(|_| ProviderError::InvalidSetting {
343 provider: name.to_owned(),
344 detail: format!("{field} must be a non-negative number of seconds, not {value}"),
345 })
346 }
347}
348
349pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;
351
352pub trait Provider: Send + Sync {
354 fn name(&self) -> &str;
356
357 fn model(&self) -> &str;
359
360 fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;
365
366 fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;
372
373 fn live_context_window(&self) -> Option<u64> {
378 None
379 }
380
381 fn temperature(&self) -> Option<f32> {
385 None
386 }
387
388 fn complete(
390 &self,
391 request: CompletionRequest,
392 ) -> BoxFuture<'_, Result<Completion, ProviderError>> {
393 Box::pin(collect_completion(self.model(), self.stream(request)))
394 }
395}
396
397pub async fn collect_completion(
399 model: &str,
400 mut deltas: DeltaStream<'_>,
401) -> Result<Completion, ProviderError> {
402 let mut text = String::new();
403 let mut thinking = String::new();
404 let mut last = None;
405 while let Some(delta) = deltas.next().await {
406 let delta = delta?;
407 text.push_str(&delta.text);
408 thinking.push_str(&delta.thinking);
409 if delta.done && delta.completion.is_some() {
410 last = delta.completion;
411 }
412 }
413 Ok(match last {
414 None => Completion {
415 text,
416 thinking,
417 model: Some(model.to_owned()),
418 ..Completion::default()
419 },
420 Some(mut completion) => {
421 if completion.text.is_empty() {
422 completion.text = text;
423 }
424 if completion.thinking.is_empty() {
425 completion.thinking = thinking;
426 }
427 completion
428 }
429 })
430}
431
432#[derive(Debug, Clone, PartialEq, Error)]
437pub enum ProviderError {
438 #[error(
439 "Unknown provider '{provider}'. Built-in: anthropic, google, openai, ollama, llamacpp, vllm, lmstudio. \
440 For an OpenAI-compatible endpoint, add a [providers.{provider}] block with a base_url \
441 (e.g. OpenRouter, Groq, Together) to your config."
442 )]
443 UnknownProvider { provider: String },
444
445 #[error("Invalid [providers.{provider}] setting: {detail}")]
446 InvalidSetting { provider: String, detail: String },
447
448 #[error(
449 "No API key found. Set the {env} environment variable or store a key in the OS keyring (service \"agent86\", account \"{account}\")."
450 )]
451 MissingApiKey { env: String, account: String },
452
453 #[error("Could not construct the HTTP client: {detail}")]
454 Client { detail: String },
455
456 #[error("HTTP {status}: {body}")]
457 Http { status: u16, body: String },
458
459 #[error("HTTP {status}: {body} -- {hint}")]
462 HttpHint {
463 status: u16,
464 body: String,
465 hint: String,
466 },
467
468 #[error("Cannot reach {endpoint}: {detail}")]
469 Connect { endpoint: String, detail: String },
470
471 #[error(
472 "Timed out connecting to {endpoint} after {seconds}s (connect_timeout_s). \
473 Raise connect_timeout_s in the [providers.*] block for this endpoint to allow more time."
474 )]
475 ConnectTimeout { endpoint: String, seconds: f64 },
476
477 #[error(
478 "Timed out waiting for {endpoint} after {seconds}s with no data received (read_timeout_s). \
479 This is the maximum gap between streamed chunks, not the total generation time — \
480 a long but still-progressing generation is not affected. \
481 Raise read_timeout_s in the [providers.*] block for this endpoint if this endpoint is just slow to respond."
482 )]
483 ReadTimeout { endpoint: String, seconds: f64 },
484
485 #[error(
486 "{provider}: {endpoint} returned a malformed streaming chunk for model {model:?} — \
487 could not parse the SSE 'data:' line as JSON ({detail}). \
488 The stream was probably truncated, or the endpoint is not OpenAI-compatible."
489 )]
490 MalformedChunk {
491 provider: String,
492 endpoint: String,
493 model: String,
494 detail: String,
495 },
496
497 #[error(
498 "{provider}: the connection to {endpoint} failed while streaming model {model:?} — {detail}. \
499 The server closed the stream early; retry, or check the endpoint and network."
500 )]
501 StreamInterrupted {
502 provider: String,
503 endpoint: String,
504 model: String,
505 detail: String,
506 },
507
508 #[error("{0}")]
510 Message(String),
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use crate::config::{load_config, ConfigPaths, Overrides};
517 use crate::secrets::NoSecretStore;
518
519 fn builtin_config() -> Config {
520 let paths = ConfigPaths {
521 user: None,
522 project: std::path::PathBuf::from("no-such-dir/config.toml"),
523 project_trust: crate::config::ProjectTrust::Trusted,
524 };
525 load_config(&paths, &Overrides::default()).unwrap()
526 }
527
528 #[test]
529 fn llamacpp_is_the_openai_adapter_under_its_own_name_without_a_key() {
530 let mut config = builtin_config();
531 let reference = ModelRef::parse("llamacpp:qwen3").unwrap();
532 let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
533 assert_eq!((provider.name(), provider.model()), ("llamacpp", "qwen3"));
534
535 let section = config.providers.get_mut("llamacpp").unwrap();
538 section.base_url = None;
539 section.api_key_env = Some("AGENT86_TEST_UNSET_LLAMACPP_KEY".to_owned());
540 let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
541 assert_eq!(provider.name(), "llamacpp");
542 }
543}