Skip to main content

agent86_core/provider/
mod.rs

1//! The unified model interface.
2//!
3//! Every backend implements [`Provider::stream`]; [`Provider::complete`] is
4//! derived from it, so one API round-trip yields both live text and the
5//! authoritative result. Streamed and non-streamed calls therefore always agree
6//! on the final text.
7
8pub 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
19/// The prefix of a stop reason that means the provider ended the reply itself
20/// (Gemini's `stopped:SAFETY`, an OpenAI-compatible `stopped:content_filter`, a
21/// model's `stopped:refusal`); the loop announces it once and does not ask again.
22pub 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
36/// llama.cpp's server (`llama-server --port`).
37const LLAMACPP_DEFAULT_BASE_URL: &str = "http://localhost:8080/v1";
38
39/// vLLM's own default port (`vllm serve --port`).
40pub const VLLM_DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";
41
42/// The port LM Studio's docs assume throughout (`lms server start` reuses the last).
43pub const LMSTUDIO_DEFAULT_BASE_URL: &str = "http://localhost:1234/v1";
44
45/// A server agent86 knows beyond the OpenAI-compatible API it speaks (beyond
46/// Python): chosen by a section's `adapter`, or by the built-in section's name.
47/// The requests are the OpenAI adapter's; the kind decides the rest: whether a
48/// key is optional, where the context window comes from, local pricing, and the
49/// hints its errors get.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ServerKind {
52    Vllm,
53    LmStudio,
54}
55
56impl ServerKind {
57    /// The `adapter` value that selects this kind, and the built-in section's name.
58    pub fn name(self) -> &'static str {
59        match self {
60            Self::Vllm => "vllm",
61            Self::LmStudio => "lmstudio",
62        }
63    }
64
65    /// The URL a section of this kind reaches when it sets none.
66    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    /// A key is sent when one resolves, and its absence is not an error: the
74    /// server is open unless it was started with one (vLLM's `--api-key`, LM
75    /// Studio's "Require Authentication").
76    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
89/// The server kind behind section `name`: its `adapter` when it sets one, else
90/// the built-in section's own. `None` for an unknown `adapter`, which
91/// [`provider_for_ref`] refuses; callers that only label or price (the provider
92/// list, the price table) treat it as no kind.
93pub 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
100/// Is a key optional for section `name`? True for every [`ServerKind`]: the
101/// third key state beside "required" (an `api_key_env`) and "none" (no
102/// `api_key_env`), which the provider list, `keys set`, and the editor's model
103/// lists all know.
104pub fn key_optional(name: &str, section: Option<&ProviderConfig>) -> bool {
105    server_kind(name, section).is_some_and(ServerKind::key_optional)
106}
107
108/// Construct the provider that serves `reference`, e.g. `openrouter:openai/gpt-4o-mini`.
109///
110/// Any provider section with a `base_url` is treated as OpenAI-compatible, so
111/// OpenRouter, Groq, and Together work with only a config block; vLLM and LM
112/// Studio have sections of their own, and `adapter` ([`ServerKind`]) for others.
113/// A key is required for `openai` itself, and for other sections only when they
114/// name an `api_key_env`; a `base_url` without one is a keyless local endpoint.
115///
116/// API keys come from the environment variable named by `api_key_env`, then
117/// from the OS keyring (service `agent86`, account = the provider section name).
118pub 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
125/// [`provider_for_ref`] with an explicit secret store, so tests never touch the OS keyring.
126pub 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
136/// [`provider_for_ref`] with a key that was typed but not stored yet: the
137/// connection test sends it as it is, skipping the environment and the keyring,
138/// as Python's `provider_for_ref(..., api_key=key)` does.
139/// A temperature as JSON. Widening an `f32` to `f64` would send 0.7 as
140/// 0.699999988079071, so it goes through its shortest decimal form.
141pub(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    // Beyond Python: a section's own temperature. Gemini takes none (see
175    // google.rs), so it is not applied there.
176    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        // Python leaves the section's timeouts to the SDK's own (see anthropic.rs).
188        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, &section),
202        )?
203        .with_pricing(PriceTable::from_config(config), reference.to_string())
204        .with_temperature(temperature);
205        return Ok(Box::new(provider));
206    }
207
208    // Gemini has its own adapter (beyond Python), for the thought signatures its
209    // OpenAI-compatible endpoint loses.
210    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, &section),
228        )?
229        .with_pricing(PriceTable::from_config(config), reference.to_string());
230        return Ok(Box::new(provider));
231    }
232
233    // Ollama has its own adapter (and no key), whatever its section says.
234    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    // llama.cpp serves the OpenAI-compatible API locally, so this is the OpenAI
252    // adapter under its own name, with a local default and no key.
253    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, &section, false)?;
259        openai_config.adapter = "llamacpp";
260        let provider = OpenAiProvider::new(
261            reference.model.clone(),
262            openai_config,
263            api_key(name, &section),
264        )?
265        .with_pricing(PriceTable::from_config(config), reference.to_string())
266        .with_temperature(temperature);
267        return Ok(Box::new(provider));
268    }
269
270    // A known server (vLLM): the OpenAI adapter under the kind's name, its URL
271    // defaulted, and a key sent only when one resolves.
272    if let Some(kind) = server_kind(name, Some(&section)) {
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, &section, !kind.key_optional())?;
278        openai_config.adapter = kind.name();
279        // `[model.context_window]` wins over what the server reports.
280        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, &section),
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, &section);
311    let openai_config = openai_config(name, &section, 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
339/// A `[providers.<name>]` timeout as a duration, refusing negative or absurd values.
340fn 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
349/// A stream of text deltas whose final item carries `done = true` and the full completion.
350pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;
351
352/// Adapter behind one provider's API.
353pub trait Provider: Send + Sync {
354    /// Short adapter id, e.g. `openai` for every OpenAI-compatible endpoint.
355    fn name(&self) -> &str;
356
357    /// The concrete model this instance targets.
358    fn model(&self) -> &str;
359
360    /// Stream text deltas; the final delta carries `done = true` and the full completion.
361    ///
362    /// After any text delta has been yielded, a failure is surfaced as an error and
363    /// never retried, because a retry would duplicate text the caller already saw.
364    fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;
365
366    /// A copy with the same settings and key and an HTTP client of its own, for a
367    /// specialist sub-agent on a fan-out thread (beyond Python): a pooled
368    /// connection only makes progress while the runtime that opened it is polled,
369    /// so a thread must never reuse one another runtime opened. Never reads the
370    /// keyring. Building the client can fail, which fails that delegation.
371    fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;
372
373    /// The context window the server reports now, for a server that sets it at
374    /// runtime (beyond Python): LM Studio's loaded context length, learned once a
375    /// request has loaded the model and then kept for this provider's life. `None`
376    /// leaves the window computed at startup or on `/model`.
377    fn live_context_window(&self) -> Option<u64> {
378        None
379    }
380
381    /// The `temperature` its config section sets (beyond Python; Python sends
382    /// 0.0 always). `None`, the default, leaves the harness's 0.0, unless a
383    /// specialty sets its own.
384    fn temperature(&self) -> Option<f32> {
385        None
386    }
387
388    /// Consume [`Provider::stream`] and return the assembled completion.
389    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
397/// Assemble a completion from a delta stream, matching the Python `complete()`.
398pub 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/// A provider could not be constructed or reached.
433///
434/// Every message is safe to show: response bodies and transport details are
435/// redacted before they are stored here.
436#[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    /// An HTTP failure from a known server whose body says what to fix (beyond
460    /// Python; see [`hints`]): Python's text, then the hint.
461    #[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    /// A message already worded as Python's adapter words it (Ollama's, Anthropic's).
509    #[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        // No base_url falls back to the local server, and a named key variable
536        // with nothing behind it is still not required.
537        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}