Skip to main content

vtcode_core/llm/
provider_builder.rs

1use crate::config::TimeoutsConfig;
2use crate::config::core::PromptCachingConfig;
3use crate::llm::provider::{LLMError, LLMProvider};
4use std::marker::PhantomData;
5
6/// Generic provider builder to eliminate duplicate provider creation patterns
7pub struct ProviderBuilder<T> {
8    api_key: Option<String>,
9    model: Option<String>,
10    base_url: Option<String>,
11    prompt_cache: Option<PromptCachingConfig>,
12    timeouts: Option<TimeoutsConfig>,
13    _phantom: PhantomData<T>,
14}
15
16impl<T> Default for ProviderBuilder<T> {
17    fn default() -> Self {
18        Self {
19            api_key: None,
20            model: None,
21            base_url: None,
22            prompt_cache: None,
23            timeouts: None,
24            _phantom: PhantomData,
25        }
26    }
27}
28
29impl<T> ProviderBuilder<T>
30where
31    T: ProviderSpec,
32{
33    /// Create a new builder with all fields unset.
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// Set the API key for provider authentication.
39    pub fn api_key(mut self, api_key: String) -> Self {
40        self.api_key = Some(api_key);
41        self
42    }
43
44    /// Set the model identifier to use.
45    pub fn model(mut self, model: String) -> Self {
46        self.model = Some(model);
47        self
48    }
49
50    /// Build the provider, returning an error if creation fails.
51    pub fn try_build(self) -> Result<Box<dyn LLMProvider>, LLMError> {
52        crate::llm::provider_config::create_provider_unified(
53            T::PROVIDER_KEY,
54            self.api_key,
55            self.model,
56            self.base_url,
57            self.prompt_cache,
58            self.timeouts,
59        )
60    }
61
62    /// Build the provider, panicking if creation fails.
63    ///
64    /// This method is intended for use in contexts where provider creation
65    /// should never fail (e.g., after configuration validation). If failure
66    /// is possible, use [`Self::try_build`] instead.
67    ///
68    /// # Panics
69    ///
70    /// Panics if the provider cannot be created. This indicates a bug in the
71    /// configuration validation or provider creation logic.
72    pub fn build(self) -> Box<dyn LLMProvider> {
73        match self.try_build() {
74            Ok(provider) => provider,
75            Err(error) => panic!(
76                "provider builder invariant violated for `{}`: {}. \
77                 This indicates a bug in configuration validation. \
78                 Use try_build() if failure is expected.",
79                T::PROVIDER_KEY,
80                error
81            ),
82        }
83    }
84}
85
86/// Static provider specification: registry metadata plus construction.
87///
88/// Each provider config type implements this once so [`ProviderBuilder`] can
89/// construct it through the canonical factory without per-provider glue.
90pub trait ProviderSpec {
91    /// Registry key used to look up this provider in the factory.
92    const PROVIDER_KEY: &'static str;
93    /// Human-readable display name for this provider.
94    const DISPLAY_NAME: &'static str;
95    /// Default model identifier when none is specified.
96    const DEFAULT_MODEL: &'static str;
97    /// Base URL for the provider's API endpoint.
98    const API_BASE_URL: &'static str;
99    /// Optional environment variable that overrides the base URL.
100    const BASE_URL_ENV_VAR: Option<&'static str>;
101
102    /// Construct a boxed [`LLMProvider`] from the given configuration.
103    fn create_provider(
104        api_key: String,
105        model: String,
106        base_url: String,
107        prompt_cache_enabled: bool,
108        prompt_cache_settings: Self::PromptCacheSettings,
109        timeouts: TimeoutsConfig,
110    ) -> Box<dyn LLMProvider>
111    where
112        Self::PromptCacheSettings: Send + Sync + 'static,
113    {
114        let _ = prompt_cache_settings;
115        let prompt_cache = prompt_cache_enabled.then(|| PromptCachingConfig { enabled: true, ..Default::default() });
116
117        match crate::llm::provider_config::create_provider_unified(
118            Self::PROVIDER_KEY,
119            (!api_key.trim().is_empty()).then_some(api_key),
120            (!model.trim().is_empty()).then_some(model),
121            (!base_url.trim().is_empty()).then_some(base_url),
122            prompt_cache,
123            Some(timeouts),
124        ) {
125            Ok(provider) => provider,
126            Err(error) => {
127                panic!("provider spec invariant violated for `{}`: {}", Self::PROVIDER_KEY, error)
128            }
129        }
130    }
131
132    /// Provider-specific prompt cache configuration type.
133    type PromptCacheSettings: Clone + Default + Send + Sync + 'static;
134}
135
136/// Deprecated alias for [`ProviderSpec`].
137#[deprecated(note = "renamed to `ProviderSpec`")]
138pub use self::ProviderSpec as ProviderConfig;
139
140/// HTTP client pool to avoid creating new clients for each provider
141mod http_client_pool {
142    use crate::config::TimeoutsConfig;
143    use hashbrown::HashMap;
144    use once_cell::sync::Lazy;
145    use reqwest::Client as HttpClient;
146    use std::sync::{Arc, RwLock};
147    use std::time::Duration;
148
149    type HttpClientPool = Arc<RwLock<HashMap<String, Arc<HttpClient>>>>;
150
151    static CLIENT_POOL: Lazy<HttpClientPool> = Lazy::new(|| {
152        // Pooled clients share the installed `[timeouts]` budgets: every entry
153        // carries both a total and a connect timeout, so no pooled caller can
154        // hang on a stalled server or handshake. The helpers log and fall back
155        // internally if a build ever fails.
156        let default = vtcode_commons::http::create_default_client();
157        let timeout_30s = vtcode_commons::http::create_client_with_timeout(Duration::from_secs(30));
158        let timeout_120s = vtcode_commons::http::create_client_with_timeout(Duration::from_secs(120));
159
160        let mut pool = HashMap::new();
161        pool.insert("default".to_string(), Arc::new(default));
162        pool.insert("timeout_30s".to_string(), Arc::new(timeout_30s));
163        pool.insert("timeout_120s".to_string(), Arc::new(timeout_120s));
164        Arc::new(RwLock::new(pool))
165    });
166
167    /// Retrieve a pooled HTTP client by key, falling back to the default client.
168    pub fn get_http_client(key: &str) -> Arc<HttpClient> {
169        let pool_guard = CLIENT_POOL.read();
170        let pool = match pool_guard {
171            Ok(guard) => guard,
172            Err(poisoned) => {
173                tracing::warn!("HTTP client pool poisoned; continuing with recovered state");
174                poisoned.into_inner()
175            }
176        };
177
178        if let Some(client) = pool.get(key).cloned() {
179            return client;
180        }
181
182        if let Some(default_client) = pool.get("default").cloned() {
183            return default_client;
184        }
185
186        tracing::warn!("HTTP client pool missing default client; constructing transient client");
187        Arc::new(vtcode_commons::http::create_default_client())
188    }
189
190    /// Select an appropriate pooled HTTP client based on the timeout ceiling.
191    pub fn get_http_client_for_timeouts(timeouts: &TimeoutsConfig) -> Arc<HttpClient> {
192        let key = if timeouts.default_ceiling_seconds >= 120 {
193            "timeout_120s"
194        } else if timeouts.default_ceiling_seconds >= 30 {
195            "timeout_30s"
196        } else {
197            "default"
198        };
199        get_http_client(key)
200    }
201}
202
203pub use http_client_pool::{get_http_client, get_http_client_for_timeouts};