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
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
31/// llama.cpp's server (`llama-server --port`).
32const LLAMACPP_DEFAULT_BASE_URL: &str = "http://localhost:8080/v1";
33
34/// vLLM's own default port (`vllm serve --port`).
35pub const VLLM_DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";
36
37/// The port LM Studio's docs assume throughout (`lms server start` reuses the last).
38pub const LMSTUDIO_DEFAULT_BASE_URL: &str = "http://localhost:1234/v1";
39
40/// A server agent86 knows beyond the OpenAI-compatible API it speaks (beyond
41/// Python): chosen by a section's `adapter`, or by the built-in section's name.
42/// The requests are the OpenAI adapter's; the kind decides the rest: whether a
43/// key is optional, where the context window comes from, local pricing, and the
44/// hints its errors get.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum ServerKind {
47    Vllm,
48    LmStudio,
49}
50
51impl ServerKind {
52    /// The `adapter` value that selects this kind, and the built-in section's name.
53    pub fn name(self) -> &'static str {
54        match self {
55            Self::Vllm => "vllm",
56            Self::LmStudio => "lmstudio",
57        }
58    }
59
60    /// The URL a section of this kind reaches when it sets none.
61    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    /// A key is sent when one resolves, and its absence is not an error: the
69    /// server is open unless it was started with one (vLLM's `--api-key`, LM
70    /// Studio's "Require Authentication").
71    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
84/// The server kind behind section `name`: its `adapter` when it sets one, else
85/// the built-in section's own. `None` for an unknown `adapter`, which
86/// [`provider_for_ref`] refuses; callers that only label or price (the provider
87/// list, the price table) treat it as no kind.
88pub 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
95/// Is a key optional for section `name`? True for every [`ServerKind`]: the
96/// third key state beside "required" (an `api_key_env`) and "none" (no
97/// `api_key_env`), which the provider list, `keys set`, and the editor's model
98/// lists all know.
99pub fn key_optional(name: &str, section: Option<&ProviderConfig>) -> bool {
100    server_kind(name, section).is_some_and(ServerKind::key_optional)
101}
102
103/// Construct the provider that serves `reference`, e.g. `openrouter:openai/gpt-4o-mini`.
104///
105/// Any provider section with a `base_url` is treated as OpenAI-compatible, so
106/// OpenRouter, Groq, and Together work with only a config block; vLLM and LM
107/// Studio have sections of their own, and `adapter` ([`ServerKind`]) for others.
108/// A key is required for `openai` itself, and for other sections only when they
109/// name an `api_key_env`; a `base_url` without one is a keyless local endpoint.
110///
111/// API keys come from the environment variable named by `api_key_env`, then
112/// from the OS keyring (service `agent86`, account = the provider section name).
113pub 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
120/// [`provider_for_ref`] with an explicit secret store, so tests never touch the OS keyring.
121pub 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
131/// [`provider_for_ref`] with a key that was typed but not stored yet: the
132/// connection test sends it as it is, skipping the environment and the keyring,
133/// as Python's `provider_for_ref(..., api_key=key)` does.
134pub 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        // Python leaves the section's timeouts to the SDK's own (see anthropic.rs).
164        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, &section),
178        )?
179        .with_pricing(PriceTable::from_config(config), reference.to_string());
180        return Ok(Box::new(provider));
181    }
182
183    // Gemini has its own adapter (beyond Python), for the thought signatures its
184    // OpenAI-compatible endpoint loses.
185    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, &section),
203        )?
204        .with_pricing(PriceTable::from_config(config), reference.to_string());
205        return Ok(Box::new(provider));
206    }
207
208    // Ollama has its own adapter (and no key), whatever its section says.
209    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    // llama.cpp serves the OpenAI-compatible API locally, so this is the OpenAI
226    // adapter under its own name, with a local default and no key.
227    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, &section, false)?;
233        openai_config.adapter = "llamacpp";
234        let provider = OpenAiProvider::new(
235            reference.model.clone(),
236            openai_config,
237            api_key(name, &section),
238        )?
239        .with_pricing(PriceTable::from_config(config), reference.to_string());
240        return Ok(Box::new(provider));
241    }
242
243    // A known server (vLLM): the OpenAI adapter under the kind's name, its URL
244    // defaulted, and a key sent only when one resolves.
245    if let Some(kind) = server_kind(name, Some(&section)) {
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, &section, !kind.key_optional())?;
251        openai_config.adapter = kind.name();
252        // `[model.context_window]` wins over what the server reports.
253        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, &section),
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, &section);
283    let openai_config = openai_config(name, &section, 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
310/// A `[providers.<name>]` timeout as a duration, refusing negative or absurd values.
311fn 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
320/// A stream of text deltas whose final item carries `done = true` and the full completion.
321pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;
322
323/// Adapter behind one provider's API.
324pub trait Provider: Send + Sync {
325    /// Short adapter id, e.g. `openai` for every OpenAI-compatible endpoint.
326    fn name(&self) -> &str;
327
328    /// The concrete model this instance targets.
329    fn model(&self) -> &str;
330
331    /// Stream text deltas; the final delta carries `done = true` and the full completion.
332    ///
333    /// After any text delta has been yielded, a failure is surfaced as an error and
334    /// never retried, because a retry would duplicate text the caller already saw.
335    fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;
336
337    /// A copy with the same settings and key and an HTTP client of its own, for a
338    /// specialist sub-agent on a fan-out thread (beyond Python): a pooled
339    /// connection only makes progress while the runtime that opened it is polled,
340    /// so a thread must never reuse one another runtime opened. Never reads the
341    /// keyring. Building the client can fail, which fails that delegation.
342    fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;
343
344    /// The context window the server reports now, for a server that sets it at
345    /// runtime (beyond Python): LM Studio's loaded context length, learned once a
346    /// request has loaded the model and then kept for this provider's life. `None`
347    /// leaves the window computed at startup or on `/model`.
348    fn live_context_window(&self) -> Option<u64> {
349        None
350    }
351
352    /// Consume [`Provider::stream`] and return the assembled completion.
353    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
361/// Assemble a completion from a delta stream, matching the Python `complete()`.
362pub 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/// A provider could not be constructed or reached.
397///
398/// Every message is safe to show: response bodies and transport details are
399/// redacted before they are stored here.
400#[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    /// An HTTP failure from a known server whose body says what to fix (beyond
424    /// Python; see [`hints`]): Python's text, then the hint.
425    #[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    /// A message already worded as Python's adapter words it (Ollama's, Anthropic's).
473    #[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        // No base_url falls back to the local server, and a named key variable
500        // with nothing behind it is still not required.
501        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}