vtcode_core/llm/
provider_builder.rs1use crate::config::TimeoutsConfig;
2use crate::config::core::PromptCachingConfig;
3use crate::llm::provider::{LLMError, LLMProvider};
4use std::marker::PhantomData;
5
6pub 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 pub fn new() -> Self {
35 Self::default()
36 }
37
38 pub fn api_key(mut self, api_key: String) -> Self {
40 self.api_key = Some(api_key);
41 self
42 }
43
44 pub fn model(mut self, model: String) -> Self {
46 self.model = Some(model);
47 self
48 }
49
50 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 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
86pub trait ProviderSpec {
91 const PROVIDER_KEY: &'static str;
93 const DISPLAY_NAME: &'static str;
95 const DEFAULT_MODEL: &'static str;
97 const API_BASE_URL: &'static str;
99 const BASE_URL_ENV_VAR: Option<&'static str>;
101
102 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 type PromptCacheSettings: Clone + Default + Send + Sync + 'static;
134}
135
136#[deprecated(note = "renamed to `ProviderSpec`")]
138pub use self::ProviderSpec as ProviderConfig;
139
140mod http_client_pool {
142 use crate::config::TimeoutsConfig;
143 use hashbrown::HashMap;
144 use reqwest::Client as HttpClient;
145 use std::sync::LazyLock;
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: LazyLock<HttpClientPool> = LazyLock::new(|| {
152 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 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 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};