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                think: section.think.clone(),
246            },
247        )?
248        .with_temperature(temperature);
249        return Ok(Box::new(provider));
250    }
251
252    // llama.cpp serves the OpenAI-compatible API locally, so this is the OpenAI
253    // adapter under its own name, with a local default and no key.
254    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, &section, false)?;
260        openai_config.adapter = "llamacpp";
261        let provider = OpenAiProvider::new(
262            reference.model.clone(),
263            openai_config,
264            api_key(name, &section),
265        )?
266        .with_pricing(PriceTable::from_config(config), reference.to_string())
267        .with_temperature(temperature);
268        return Ok(Box::new(provider));
269    }
270
271    // A known server (vLLM): the OpenAI adapter under the kind's name, its URL
272    // defaulted, and a key sent only when one resolves.
273    if let Some(kind) = server_kind(name, Some(&section)) {
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, &section, !kind.key_optional())?;
279        openai_config.adapter = kind.name();
280        // `[model.context_window]` wins over what the server reports.
281        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, &section),
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, &section);
312    let openai_config = openai_config(name, &section, 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
340/// A `[providers.<name>]` timeout as a duration, refusing negative or absurd values.
341fn 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
350/// A stream of text deltas whose final item carries `done = true` and the full completion.
351pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;
352
353/// Adapter behind one provider's API.
354pub trait Provider: Send + Sync {
355    /// Short adapter id, e.g. `openai` for every OpenAI-compatible endpoint.
356    fn name(&self) -> &str;
357
358    /// The concrete model this instance targets.
359    fn model(&self) -> &str;
360
361    /// Stream text deltas; the final delta carries `done = true` and the full completion.
362    ///
363    /// After any text delta has been yielded, a failure is surfaced as an error and
364    /// never retried, because a retry would duplicate text the caller already saw.
365    fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;
366
367    /// A copy with the same settings and key and an HTTP client of its own, for a
368    /// specialist sub-agent on a fan-out thread (beyond Python): a pooled
369    /// connection only makes progress while the runtime that opened it is polled,
370    /// so a thread must never reuse one another runtime opened. Never reads the
371    /// keyring. Building the client can fail, which fails that delegation.
372    fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;
373
374    /// The context window the server reports now, for a server that sets it at
375    /// runtime (beyond Python): LM Studio's loaded context length, learned once a
376    /// request has loaded the model and then kept for this provider's life. `None`
377    /// leaves the window computed at startup or on `/model`.
378    fn live_context_window(&self) -> Option<u64> {
379        None
380    }
381
382    /// The `temperature` its config section sets (beyond Python; Python sends
383    /// 0.0 always). `None`, the default, leaves the harness's 0.0, unless a
384    /// specialty sets its own.
385    fn temperature(&self) -> Option<f32> {
386        None
387    }
388
389    /// Consume [`Provider::stream`] and return the assembled completion.
390    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
398/// Assemble a completion from a delta stream, matching the Python `complete()`.
399pub 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/// A provider could not be constructed or reached.
434///
435/// Every message is safe to show: response bodies and transport details are
436/// redacted before they are stored here.
437#[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    /// An HTTP failure from a known server whose body says what to fix (beyond
461    /// Python; see [`hints`]): Python's text, then the hint.
462    #[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    /// A message already worded as Python's adapter words it (Ollama's, Anthropic's).
510    #[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        // No base_url falls back to the local server, and a named key variable
537        // with nothing behind it is still not required.
538        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}