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
19use crate::config::{Config, ProviderConfig};
20use crate::pricing::PriceTable;
21use crate::secrets::{resolve_api_key, OsKeyring, SecretStore};
22use crate::types::{Completion, CompletionDelta, CompletionRequest, ModelRef};
23use anthropic::{AnthropicConfig, AnthropicProvider};
24use futures_util::future::BoxFuture;
25use futures_util::stream::{BoxStream, StreamExt};
26use ollama::{OllamaConfig, OllamaProvider};
27use openai::{OpenAiConfig, OpenAiProvider};
28use std::time::Duration;
29use thiserror::Error;
30
31const LLAMACPP_DEFAULT_BASE_URL: &str = "http://localhost:8080/v1";
33
34pub const VLLM_DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";
36
37pub const LMSTUDIO_DEFAULT_BASE_URL: &str = "http://localhost:1234/v1";
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum ServerKind {
47 Vllm,
48 LmStudio,
49}
50
51impl ServerKind {
52 pub fn name(self) -> &'static str {
54 match self {
55 Self::Vllm => "vllm",
56 Self::LmStudio => "lmstudio",
57 }
58 }
59
60 pub fn default_base_url(self) -> &'static str {
62 match self {
63 Self::Vllm => VLLM_DEFAULT_BASE_URL,
64 Self::LmStudio => LMSTUDIO_DEFAULT_BASE_URL,
65 }
66 }
67
68 pub fn key_optional(self) -> bool {
72 true
73 }
74
75 pub(crate) fn parse(adapter: &str) -> Option<Self> {
76 match adapter.trim() {
77 "vllm" => Some(Self::Vllm),
78 "lmstudio" => Some(Self::LmStudio),
79 _ => None,
80 }
81 }
82}
83
84pub fn server_kind(name: &str, section: Option<&ProviderConfig>) -> Option<ServerKind> {
89 match section.and_then(|section| section.adapter.as_deref()) {
90 Some(adapter) => ServerKind::parse(adapter),
91 None => ServerKind::parse(name),
92 }
93}
94
95pub fn key_optional(name: &str, section: Option<&ProviderConfig>) -> bool {
100 server_kind(name, section).is_some_and(ServerKind::key_optional)
101}
102
103pub fn provider_for_ref(
114 reference: &ModelRef,
115 config: &Config,
116) -> Result<Box<dyn Provider>, ProviderError> {
117 provider_for_ref_with_store(reference, config, &OsKeyring)
118}
119
120pub fn provider_for_ref_with_store(
122 reference: &ModelRef,
123 config: &Config,
124 store: &dyn SecretStore,
125) -> Result<Box<dyn Provider>, ProviderError> {
126 build_provider(reference, config, |name, section| {
127 resolve_api_key(name, section.api_key_env.as_deref(), store)
128 })
129}
130
131pub fn provider_for_ref_with_key(
135 reference: &ModelRef,
136 config: &Config,
137 api_key: &str,
138) -> Result<Box<dyn Provider>, ProviderError> {
139 build_provider(reference, config, |_, _| Some(api_key.to_owned()))
140}
141
142fn build_provider(
143 reference: &ModelRef,
144 config: &Config,
145 api_key: impl FnOnce(&str, &ProviderConfig) -> Option<String>,
146) -> Result<Box<dyn Provider>, ProviderError> {
147 let name = reference.provider.as_str();
148 let section = config.providers.get(name).cloned().unwrap_or_default();
149
150 if let Some(adapter) = section.adapter.as_deref() {
151 if ServerKind::parse(adapter).is_none() {
152 return Err(ProviderError::InvalidSetting {
153 provider: name.to_owned(),
154 detail: format!(
155 "adapter must be \"vllm\" or \"lmstudio\", not {adapter:?}; remove it \
156 for a plain OpenAI-compatible endpoint"
157 ),
158 });
159 }
160 }
161
162 if name == "anthropic" {
163 let provider = AnthropicProvider::new(
165 reference.model.clone(),
166 AnthropicConfig {
167 base_url: section.base_url.clone(),
168 api_key_env: section
169 .api_key_env
170 .clone()
171 .unwrap_or_else(|| anthropic::DEFAULT_API_KEY_ENV.to_owned()),
172 max_tokens: section.max_tokens,
173 prompt_cache: section.prompt_cache,
174 max_retries: section.max_retries,
175 ..AnthropicConfig::default()
176 },
177 api_key(name, §ion),
178 )?
179 .with_pricing(PriceTable::from_config(config), reference.to_string());
180 return Ok(Box::new(provider));
181 }
182
183 if name == "google" {
186 let seconds = durations(name);
187 let provider = google::GoogleProvider::new(
188 reference.model.clone(),
189 google::GoogleConfig {
190 base_url: section.base_url.clone(),
191 api_key_env: section
192 .api_key_env
193 .clone()
194 .unwrap_or_else(|| google::DEFAULT_API_KEY_ENV.to_owned()),
195 config_name: name.to_owned(),
196 max_tokens: section.max_tokens,
197 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
198 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
199 max_retries: section.max_retries,
200 store: section.store,
201 },
202 api_key(name, §ion),
203 )?
204 .with_pricing(PriceTable::from_config(config), reference.to_string());
205 return Ok(Box::new(provider));
206 }
207
208 if name == "ollama" {
210 let seconds = durations(name);
211 let provider = OllamaProvider::new(
212 reference.model.clone(),
213 OllamaConfig {
214 base_url: section.base_url.clone(),
215 num_ctx: section.num_ctx,
216 max_tokens: section.max_tokens,
217 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
218 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
219 max_retries: section.max_retries,
220 },
221 )?;
222 return Ok(Box::new(provider));
223 }
224
225 if name == "llamacpp" {
228 let mut section = section;
229 section
230 .base_url
231 .get_or_insert_with(|| LLAMACPP_DEFAULT_BASE_URL.to_owned());
232 let mut openai_config = openai_config(name, §ion, false)?;
233 openai_config.adapter = "llamacpp";
234 let provider = OpenAiProvider::new(
235 reference.model.clone(),
236 openai_config,
237 api_key(name, §ion),
238 )?
239 .with_pricing(PriceTable::from_config(config), reference.to_string());
240 return Ok(Box::new(provider));
241 }
242
243 if let Some(kind) = server_kind(name, Some(§ion)) {
246 let mut section = section;
247 section
248 .base_url
249 .get_or_insert_with(|| kind.default_base_url().to_owned());
250 let mut openai_config = openai_config(name, §ion, !kind.key_optional())?;
251 openai_config.adapter = kind.name();
252 let overridden = [reference.to_string().as_str(), reference.model.as_str()]
254 .iter()
255 .any(|key| {
256 config
257 .model
258 .context_window
259 .get(*key)
260 .is_some_and(|&w| w > 0)
261 });
262 openai_config.live_window = kind == ServerKind::LmStudio && !overridden;
263 let provider = OpenAiProvider::new(
264 reference.model.clone(),
265 openai_config,
266 api_key(name, §ion),
267 )?
268 .with_pricing(PriceTable::from_config(config), reference.to_string());
269 return Ok(Box::new(provider));
270 }
271
272 let require_key = match name {
273 "openai" | "openai-compatible" => true,
274 _ if section.base_url.is_some() => section.api_key_env.is_some(),
275 _ => {
276 return Err(ProviderError::UnknownProvider {
277 provider: name.to_owned(),
278 })
279 }
280 };
281
282 let api_key = api_key(name, §ion);
283 let openai_config = openai_config(name, §ion, require_key)?;
284 let provider = OpenAiProvider::new(reference.model.clone(), openai_config, api_key)?
285 .with_pricing(PriceTable::from_config(config), reference.to_string());
286 Ok(Box::new(provider))
287}
288
289fn openai_config(
290 name: &str,
291 section: &ProviderConfig,
292 require_key: bool,
293) -> Result<OpenAiConfig, ProviderError> {
294 let seconds = durations(name);
295 Ok(OpenAiConfig {
296 base_url: section.base_url.clone(),
297 api_key_env: section.api_key_env.clone(),
298 config_name: name.to_owned(),
299 adapter: "openai",
300 require_key,
301 max_tokens: section.max_tokens,
302 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
303 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
304 max_retries: section.max_retries,
305 routing: section.routing.clone(),
306 live_window: false,
307 })
308}
309
310fn durations(name: &str) -> impl Fn(&str, f64) -> Result<Duration, ProviderError> + '_ {
312 move |field, value| {
313 Duration::try_from_secs_f64(value).map_err(|_| ProviderError::InvalidSetting {
314 provider: name.to_owned(),
315 detail: format!("{field} must be a non-negative number of seconds, not {value}"),
316 })
317 }
318}
319
320pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;
322
323pub trait Provider: Send + Sync {
325 fn name(&self) -> &str;
327
328 fn model(&self) -> &str;
330
331 fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;
336
337 fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;
343
344 fn live_context_window(&self) -> Option<u64> {
349 None
350 }
351
352 fn complete(
354 &self,
355 request: CompletionRequest,
356 ) -> BoxFuture<'_, Result<Completion, ProviderError>> {
357 Box::pin(collect_completion(self.model(), self.stream(request)))
358 }
359}
360
361pub async fn collect_completion(
363 model: &str,
364 mut deltas: DeltaStream<'_>,
365) -> Result<Completion, ProviderError> {
366 let mut text = String::new();
367 let mut thinking = String::new();
368 let mut last = None;
369 while let Some(delta) = deltas.next().await {
370 let delta = delta?;
371 text.push_str(&delta.text);
372 thinking.push_str(&delta.thinking);
373 if delta.done && delta.completion.is_some() {
374 last = delta.completion;
375 }
376 }
377 Ok(match last {
378 None => Completion {
379 text,
380 thinking,
381 model: Some(model.to_owned()),
382 ..Completion::default()
383 },
384 Some(mut completion) => {
385 if completion.text.is_empty() {
386 completion.text = text;
387 }
388 if completion.thinking.is_empty() {
389 completion.thinking = thinking;
390 }
391 completion
392 }
393 })
394}
395
396#[derive(Debug, Clone, PartialEq, Error)]
401pub enum ProviderError {
402 #[error(
403 "Unknown provider '{provider}'. Built-in: anthropic, google, openai, ollama, llamacpp, vllm, lmstudio. \
404 For an OpenAI-compatible endpoint, add a [providers.{provider}] block with a base_url \
405 (e.g. OpenRouter, Groq, Together) to your config."
406 )]
407 UnknownProvider { provider: String },
408
409 #[error("Invalid [providers.{provider}] setting: {detail}")]
410 InvalidSetting { provider: String, detail: String },
411
412 #[error(
413 "No API key found. Set the {env} environment variable or store a key in the OS keyring (service \"agent86\", account \"{account}\")."
414 )]
415 MissingApiKey { env: String, account: String },
416
417 #[error("Could not construct the HTTP client: {detail}")]
418 Client { detail: String },
419
420 #[error("HTTP {status}: {body}")]
421 Http { status: u16, body: String },
422
423 #[error("HTTP {status}: {body} -- {hint}")]
426 HttpHint {
427 status: u16,
428 body: String,
429 hint: String,
430 },
431
432 #[error("Cannot reach {endpoint}: {detail}")]
433 Connect { endpoint: String, detail: String },
434
435 #[error(
436 "Timed out connecting to {endpoint} after {seconds}s (connect_timeout_s). \
437 Raise connect_timeout_s in the [providers.*] block for this endpoint to allow more time."
438 )]
439 ConnectTimeout { endpoint: String, seconds: f64 },
440
441 #[error(
442 "Timed out waiting for {endpoint} after {seconds}s with no data received (read_timeout_s). \
443 This is the maximum gap between streamed chunks, not the total generation time — \
444 a long but still-progressing generation is not affected. \
445 Raise read_timeout_s in the [providers.*] block for this endpoint if this endpoint is just slow to respond."
446 )]
447 ReadTimeout { endpoint: String, seconds: f64 },
448
449 #[error(
450 "{provider}: {endpoint} returned a malformed streaming chunk for model {model:?} — \
451 could not parse the SSE 'data:' line as JSON ({detail}). \
452 The stream was probably truncated, or the endpoint is not OpenAI-compatible."
453 )]
454 MalformedChunk {
455 provider: String,
456 endpoint: String,
457 model: String,
458 detail: String,
459 },
460
461 #[error(
462 "{provider}: the connection to {endpoint} failed while streaming model {model:?} — {detail}. \
463 The server closed the stream early; retry, or check the endpoint and network."
464 )]
465 StreamInterrupted {
466 provider: String,
467 endpoint: String,
468 model: String,
469 detail: String,
470 },
471
472 #[error("{0}")]
474 Message(String),
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480 use crate::config::{load_config, ConfigPaths, Overrides};
481 use crate::secrets::NoSecretStore;
482
483 fn builtin_config() -> Config {
484 let paths = ConfigPaths {
485 user: None,
486 project: std::path::PathBuf::from("no-such-dir/config.toml"),
487 project_trust: crate::config::ProjectTrust::Trusted,
488 };
489 load_config(&paths, &Overrides::default()).unwrap()
490 }
491
492 #[test]
493 fn llamacpp_is_the_openai_adapter_under_its_own_name_without_a_key() {
494 let mut config = builtin_config();
495 let reference = ModelRef::parse("llamacpp:qwen3").unwrap();
496 let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
497 assert_eq!((provider.name(), provider.model()), ("llamacpp", "qwen3"));
498
499 let section = config.providers.get_mut("llamacpp").unwrap();
502 section.base_url = None;
503 section.api_key_env = Some("AGENT86_TEST_UNSET_LLAMACPP_KEY".to_owned());
504 let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
505 assert_eq!(provider.name(), "llamacpp");
506 }
507}