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 think: section.think.clone(),
246 },
247 )?
248 .with_temperature(temperature);
249 return Ok(Box::new(provider));
250 }
251
252 if name == "llamacpp" {
255 let mut section = section;
256 section
257 .base_url
258 .get_or_insert_with(|| LLAMACPP_DEFAULT_BASE_URL.to_owned());
259 let mut openai_config = openai_config(name, §ion, false)?;
260 openai_config.adapter = "llamacpp";
261 let provider = OpenAiProvider::new(
262 reference.model.clone(),
263 openai_config,
264 api_key(name, §ion),
265 )?
266 .with_pricing(PriceTable::from_config(config), reference.to_string())
267 .with_temperature(temperature);
268 return Ok(Box::new(provider));
269 }
270
271 if let Some(kind) = server_kind(name, Some(§ion)) {
274 let mut section = section;
275 section
276 .base_url
277 .get_or_insert_with(|| kind.default_base_url().to_owned());
278 let mut openai_config = openai_config(name, §ion, !kind.key_optional())?;
279 openai_config.adapter = kind.name();
280 let overridden = [reference.to_string().as_str(), reference.model.as_str()]
282 .iter()
283 .any(|key| {
284 config
285 .model
286 .context_window
287 .get(*key)
288 .is_some_and(|&w| w > 0)
289 });
290 openai_config.live_window = kind == ServerKind::LmStudio && !overridden;
291 let provider = OpenAiProvider::new(
292 reference.model.clone(),
293 openai_config,
294 api_key(name, §ion),
295 )?
296 .with_pricing(PriceTable::from_config(config), reference.to_string())
297 .with_temperature(temperature);
298 return Ok(Box::new(provider));
299 }
300
301 let require_key = match name {
302 "openai" | "openai-compatible" => true,
303 _ if section.base_url.is_some() => section.api_key_env.is_some(),
304 _ => {
305 return Err(ProviderError::UnknownProvider {
306 provider: name.to_owned(),
307 })
308 }
309 };
310
311 let api_key = api_key(name, §ion);
312 let openai_config = openai_config(name, §ion, require_key)?;
313 let provider = OpenAiProvider::new(reference.model.clone(), openai_config, api_key)?
314 .with_pricing(PriceTable::from_config(config), reference.to_string())
315 .with_temperature(temperature);
316 Ok(Box::new(provider))
317}
318
319fn openai_config(
320 name: &str,
321 section: &ProviderConfig,
322 require_key: bool,
323) -> Result<OpenAiConfig, ProviderError> {
324 let seconds = durations(name);
325 Ok(OpenAiConfig {
326 base_url: section.base_url.clone(),
327 api_key_env: section.api_key_env.clone(),
328 config_name: name.to_owned(),
329 adapter: "openai",
330 require_key,
331 max_tokens: section.max_tokens,
332 connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
333 read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
334 max_retries: section.max_retries,
335 routing: section.routing.clone(),
336 live_window: false,
337 })
338}
339
340fn durations(name: &str) -> impl Fn(&str, f64) -> Result<Duration, ProviderError> + '_ {
342 move |field, value| {
343 Duration::try_from_secs_f64(value).map_err(|_| ProviderError::InvalidSetting {
344 provider: name.to_owned(),
345 detail: format!("{field} must be a non-negative number of seconds, not {value}"),
346 })
347 }
348}
349
350pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;
352
353pub trait Provider: Send + Sync {
355 fn name(&self) -> &str;
357
358 fn model(&self) -> &str;
360
361 fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;
366
367 fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;
373
374 fn live_context_window(&self) -> Option<u64> {
379 None
380 }
381
382 fn temperature(&self) -> Option<f32> {
386 None
387 }
388
389 fn complete(
391 &self,
392 request: CompletionRequest,
393 ) -> BoxFuture<'_, Result<Completion, ProviderError>> {
394 Box::pin(collect_completion(self.model(), self.stream(request)))
395 }
396}
397
398pub async fn collect_completion(
400 model: &str,
401 mut deltas: DeltaStream<'_>,
402) -> Result<Completion, ProviderError> {
403 let mut text = String::new();
404 let mut thinking = String::new();
405 let mut last = None;
406 while let Some(delta) = deltas.next().await {
407 let delta = delta?;
408 text.push_str(&delta.text);
409 thinking.push_str(&delta.thinking);
410 if delta.done && delta.completion.is_some() {
411 last = delta.completion;
412 }
413 }
414 Ok(match last {
415 None => Completion {
416 text,
417 thinking,
418 model: Some(model.to_owned()),
419 ..Completion::default()
420 },
421 Some(mut completion) => {
422 if completion.text.is_empty() {
423 completion.text = text;
424 }
425 if completion.thinking.is_empty() {
426 completion.thinking = thinking;
427 }
428 completion
429 }
430 })
431}
432
433#[derive(Debug, Clone, PartialEq, Error)]
438pub enum ProviderError {
439 #[error(
440 "Unknown provider '{provider}'. Built-in: anthropic, google, openai, ollama, llamacpp, vllm, lmstudio. \
441 For an OpenAI-compatible endpoint, add a [providers.{provider}] block with a base_url \
442 (e.g. OpenRouter, Groq, Together) to your config."
443 )]
444 UnknownProvider { provider: String },
445
446 #[error("Invalid [providers.{provider}] setting: {detail}")]
447 InvalidSetting { provider: String, detail: String },
448
449 #[error(
450 "No API key found. Set the {env} environment variable or store a key in the OS keyring (service \"agent86\", account \"{account}\")."
451 )]
452 MissingApiKey { env: String, account: String },
453
454 #[error("Could not construct the HTTP client: {detail}")]
455 Client { detail: String },
456
457 #[error("HTTP {status}: {body}")]
458 Http { status: u16, body: String },
459
460 #[error("HTTP {status}: {body} -- {hint}")]
463 HttpHint {
464 status: u16,
465 body: String,
466 hint: String,
467 },
468
469 #[error("Cannot reach {endpoint}: {detail}")]
470 Connect { endpoint: String, detail: String },
471
472 #[error(
473 "Timed out connecting to {endpoint} after {seconds}s (connect_timeout_s). \
474 Raise connect_timeout_s in the [providers.*] block for this endpoint to allow more time."
475 )]
476 ConnectTimeout { endpoint: String, seconds: f64 },
477
478 #[error(
479 "Timed out waiting for {endpoint} after {seconds}s with no data received (read_timeout_s). \
480 This is the maximum gap between streamed chunks, not the total generation time — \
481 a long but still-progressing generation is not affected. \
482 Raise read_timeout_s in the [providers.*] block for this endpoint if this endpoint is just slow to respond."
483 )]
484 ReadTimeout { endpoint: String, seconds: f64 },
485
486 #[error(
487 "{provider}: {endpoint} returned a malformed streaming chunk for model {model:?} — \
488 could not parse the SSE 'data:' line as JSON ({detail}). \
489 The stream was probably truncated, or the endpoint is not OpenAI-compatible."
490 )]
491 MalformedChunk {
492 provider: String,
493 endpoint: String,
494 model: String,
495 detail: String,
496 },
497
498 #[error(
499 "{provider}: the connection to {endpoint} failed while streaming model {model:?} — {detail}. \
500 The server closed the stream early; retry, or check the endpoint and network."
501 )]
502 StreamInterrupted {
503 provider: String,
504 endpoint: String,
505 model: String,
506 detail: String,
507 },
508
509 #[error("{0}")]
511 Message(String),
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517 use crate::config::{load_config, ConfigPaths, Overrides};
518 use crate::secrets::NoSecretStore;
519
520 fn builtin_config() -> Config {
521 let paths = ConfigPaths {
522 user: None,
523 project: std::path::PathBuf::from("no-such-dir/config.toml"),
524 project_trust: crate::config::ProjectTrust::Trusted,
525 };
526 load_config(&paths, &Overrides::default()).unwrap()
527 }
528
529 #[test]
530 fn llamacpp_is_the_openai_adapter_under_its_own_name_without_a_key() {
531 let mut config = builtin_config();
532 let reference = ModelRef::parse("llamacpp:qwen3").unwrap();
533 let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
534 assert_eq!((provider.name(), provider.model()), ("llamacpp", "qwen3"));
535
536 let section = config.providers.get_mut("llamacpp").unwrap();
539 section.base_url = None;
540 section.api_key_env = Some("AGENT86_TEST_UNSET_LLAMACPP_KEY".to_owned());
541 let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
542 assert_eq!(provider.name(), "llamacpp");
543 }
544}