Skip to main content

vtcode_llm/
provider_base.rs

1//! Base traits and utilities for LLM providers
2//!
3//! This module provides shared functionality to eliminate duplicate code
4//! across the 15+ LLM provider implementations.
5
6use anyhow::{Context, Result};
7use async_trait::async_trait;
8use futures::StreamExt;
9use reqwest::Client as HttpClient;
10use serde_json::Value;
11use std::time::Duration;
12
13use crate::provider::{LLMError, LLMRequest, LLMStreamEvent};
14use vtcode_config::TimeoutsConfig;
15
16/// Default timeout configurations
17const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
18const DEFAULT_STREAM_TIMEOUT: Duration = Duration::from_secs(300);
19/// Fallback connect budget when `[timeouts] http_connect_seconds` is `0`.
20const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
21
22/// Base configuration shared by all providers
23#[derive(Debug, Clone)]
24pub struct BaseProviderConfig {
25    api_key: String,
26    base_url: String,
27    model: String,
28    http_client: HttpClient,
29    prompt_cache_enabled: bool,
30    request_timeout: Duration,
31    stream_timeout: Duration,
32}
33
34impl BaseProviderConfig {
35    /// Create base configuration from common parameters
36    fn from_options(
37        api_key: Option<String>,
38        model: Option<String>,
39        base_url: Option<String>,
40        default_model: &'static str,
41        default_url: &'static str,
42        env_var: &'static str,
43        timeouts: Option<TimeoutsConfig>,
44    ) -> Result<Self> {
45        let api_key_value = api_key.unwrap_or_default();
46        let model_value = model.unwrap_or_else(|| default_model.to_string());
47        let base_url_value = Self::resolve_base_url(base_url, default_url, env_var)?;
48
49        let timeout_config = timeouts.unwrap_or_default();
50        let http_timeout = timeout_config
51            .ceiling_duration(timeout_config.streaming_ceiling_seconds)
52            .unwrap_or(DEFAULT_REQUEST_TIMEOUT);
53        // reqwest leaves the connect phase unbounded unless it is set
54        // explicitly, so a request timeout alone never caps a stalled handshake.
55        let connect_timeout = timeout_config
56            .ceiling_duration(timeout_config.http_connect_seconds)
57            .unwrap_or(DEFAULT_CONNECT_TIMEOUT);
58        let http_client = HttpClient::builder()
59            .timeout(http_timeout)
60            .connect_timeout(connect_timeout)
61            .build()
62            .context("Failed to build HTTP client")?;
63
64        Ok(Self {
65            api_key: api_key_value,
66            base_url: base_url_value,
67            model: model_value,
68            http_client,
69            prompt_cache_enabled: false,
70            request_timeout: http_timeout,
71            stream_timeout: timeout_config
72                .ceiling_duration(timeout_config.streaming_ceiling_seconds)
73                .unwrap_or(DEFAULT_STREAM_TIMEOUT),
74        })
75    }
76
77    /// Resolve base URL with environment variable fallback
78    fn resolve_base_url(base_url: Option<String>, default_url: &'static str, env_var: &'static str) -> Result<String> {
79        if let Some(url) = base_url {
80            Ok(url.trim().to_string())
81        } else if let Ok(env_val) = std::env::var(env_var) {
82            Ok(env_val.trim().to_string())
83        } else {
84            Ok(default_url.to_string())
85        }
86    }
87
88    /// Validate that required API key is present
89    pub fn validate_api_key(&self) -> Result<()> {
90        if self.api_key.is_empty() {
91            anyhow::bail!("API key is required")
92        }
93        Ok(())
94    }
95}
96
97/// Trait for providers that support standard OpenAI-compatible APIs
98#[async_trait]
99trait OpenAICompatibleProvider: Send + Sync {
100    fn provider_name(&self) -> &'static str;
101    fn supports_prompt_caching(&self) -> bool;
102
103    /// Parse request from OpenAI format
104    fn parse_openai_request(&self, value: &Value, default_model: &str) -> Option<LLMRequest> {
105        crate::utils::parse_chat_request_openai_format(value, default_model)
106    }
107
108    /// Serialize messages to OpenAI format
109    fn serialize_openai_messages(&self, request: &LLMRequest) -> Value {
110        use crate::providers::common::serialize_messages_openai_format;
111        match serialize_messages_openai_format(request, self.provider_name()) {
112            Ok(messages) => serde_json::json!({ "messages": messages }),
113            Err(_) => serde_json::json!({ "messages": [] }),
114        }
115    }
116
117    /// Parse response from OpenAI format
118    fn parse_openai_response(
119        &self,
120        response: Value,
121        model: String,
122        include_cache: bool,
123    ) -> Result<crate::provider::LLMResponse> {
124        crate::utils::parse_response_openai_format(response, self.provider_name(), model, include_cache, None)
125    }
126}
127
128/// Shared error handling utilities
129struct ErrorHandler {
130    _provider_name: &'static str,
131}
132
133impl ErrorHandler {
134    fn new(provider_name: &'static str) -> Self {
135        Self { _provider_name: provider_name }
136    }
137
138    /// Handle HTTP errors consistently across providers
139    fn handle_http_error(&self, status: reqwest::StatusCode, error_text: &str) -> LLMError {
140        use reqwest::StatusCode;
141
142        let error_message = match status {
143            StatusCode::UNAUTHORIZED => "Authentication failed: Invalid API key".to_string(),
144            StatusCode::TOO_MANY_REQUESTS => "Rate limit exceeded".to_string(),
145            StatusCode::BAD_REQUEST => format!("Bad request: {}", error_text.trim()),
146            s if s.as_u16() == 402 => "Insufficient balance".to_string(),
147            _ => format!("HTTP {}: {}", status, error_text.trim()),
148        };
149
150        let formatted_error = crate::error_display::format_llm_error(self._provider_name, &error_message);
151
152        // Handle different error types based on status code
153        if status == StatusCode::TOO_MANY_REQUESTS {
154            LLMError::RateLimit { metadata: None }
155        } else {
156            LLMError::Provider { message: formatted_error, metadata: None }
157        }
158    }
159
160    /// Handle request validation errors
161    pub fn validate_request(&self, request: &LLMRequest) -> Result<()> {
162        if request.messages.is_empty() {
163            anyhow::bail!("Request must contain at least one message")
164        }
165
166        if request.model.is_empty() {
167            anyhow::bail!("Request must specify a model")
168        }
169
170        // Check if model is supported (this would need to be customized per provider)
171        if !self.is_model_supported(&request.model) {
172            anyhow::bail!("Unsupported model: {}", request.model)
173        }
174
175        Ok(())
176    }
177
178    /// Check if model is supported (default implementation, override as needed)
179    fn is_model_supported(&self, model: &str) -> bool {
180        // Default implementation assumes all models are supported
181        // Individual providers should override this with their specific model lists
182        !model.is_empty()
183    }
184}
185
186/// Shared streaming utilities
187pub struct StreamProcessor {
188    provider_name: &'static str,
189    supports_reasoning: bool,
190}
191
192impl StreamProcessor {
193    pub fn new(provider_name: &'static str, supports_reasoning: bool) -> Self {
194        Self { provider_name, supports_reasoning }
195    }
196
197    /// Process SSE stream chunk consistently
198    pub fn process_stream_chunk(&self, chunk: &str) -> Vec<LLMStreamEvent> {
199        let mut events = Vec::new();
200
201        for line in chunk.lines() {
202            let line = line.trim();
203            if line.is_empty() {
204                continue;
205            }
206
207            if let Some(data) = line.strip_prefix("data: ") {
208                if data == "[DONE]" {
209                    // Stream completion indicated by DONE marker
210                    continue;
211                }
212
213                match serde_json::from_str::<Value>(data) {
214                    Ok(json) => {
215                        if let Some(event) = self.parse_stream_event(json) {
216                            events.push(event);
217                        }
218                    }
219                    Err(_) => {
220                        // Skip invalid JSON
221                        continue;
222                    }
223                }
224            }
225        }
226
227        events
228    }
229
230    /// Parse individual stream event (override for provider-specific logic)
231    fn parse_stream_event(&self, json: Value) -> Option<LLMStreamEvent> {
232        // Default implementation for OpenAI-compatible providers
233        crate::utils::parse_stream_event_openai_format(json, self.provider_name)
234    }
235
236    /// Extract reasoning content if supported
237    pub fn extract_reasoning(&self, content: &str) -> (Vec<String>, Option<String>) {
238        if !self.supports_reasoning {
239            return (Vec::new(), None);
240        }
241
242        // Default implementation - providers can override
243        crate::utils::extract_reasoning_content(content)
244    }
245}
246
247/// Unified authentication header handling
248pub struct AuthHandler {
249    auth_type: AuthType,
250    api_key: String,
251}
252
253#[derive(Debug, Clone, Copy)]
254pub enum AuthType {
255    BearerToken,
256    ApiKeyHeader(&'static str),
257    QueryParam(&'static str),
258}
259
260impl AuthHandler {
261    pub fn new(auth_type: AuthType, api_key: String) -> Self {
262        Self { auth_type, api_key }
263    }
264
265    /// Apply authentication to request builder
266    pub fn apply_auth(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
267        match self.auth_type {
268            AuthType::BearerToken => builder.bearer_auth(&self.api_key),
269            AuthType::ApiKeyHeader(header_name) => builder.header(header_name, &self.api_key),
270            AuthType::QueryParam(param_name) => builder.query(&[(param_name, &self.api_key)]),
271        }
272    }
273}
274
275/// Shared request/response processing utilities
276pub struct RequestProcessor {
277    provider_name: &'static str,
278}
279
280impl RequestProcessor {
281    pub fn new(provider_name: &'static str) -> Self {
282        Self { provider_name }
283    }
284
285    /// Build HTTP request with consistent error handling
286    pub async fn build_request(
287        &self,
288        client: &HttpClient,
289        method: reqwest::Method,
290        url: String,
291        auth: Option<&AuthHandler>,
292        body: Option<Value>,
293    ) -> Result<reqwest::RequestBuilder> {
294        let mut builder = client.request(method, &url);
295
296        if let Some(auth_handler) = auth {
297            builder = auth_handler.apply_auth(builder);
298        }
299
300        builder = builder
301            .header("Content-Type", "application/json")
302            .header("User-Agent", "VT Code/1.0");
303
304        if let Some(body_value) = body {
305            builder = builder.json(&body_value);
306        }
307
308        Ok(builder)
309    }
310
311    /// Handle response with consistent error processing
312    pub async fn handle_response(&self, response: reqwest::Response) -> Result<Value> {
313        let status = response.status();
314
315        if !status.is_success() {
316            let error_text = crate::providers::common::read_provider_error_body(response).await;
317            let error_handler = ErrorHandler::new(self.provider_name);
318            return Err(error_handler.handle_http_error(status, &error_text).into());
319        }
320
321        let response_text = response.text().await.context("Failed to read response body")?;
322
323        serde_json::from_str(&response_text).context("Failed to parse JSON response")
324    }
325
326    /// Handle streaming response
327    pub async fn handle_stream_response(
328        &self,
329        response: reqwest::Response,
330    ) -> Result<impl futures::Stream<Item = Result<String>>> {
331        let status = response.status();
332
333        if !status.is_success() {
334            let error_text = crate::providers::common::read_provider_error_body(response).await;
335            let error_handler = ErrorHandler::new(self.provider_name);
336            return Err(error_handler.handle_http_error(status, &error_text).into());
337        }
338
339        Ok(response.bytes_stream().map(|result| {
340            result
341                .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
342                .map_err(|e| anyhow::anyhow!("Stream error: {e}"))
343        }))
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    /// Test-only model resolution utilities. The production `ModelResolver`
352    /// lives in [`crate::model_resolver`] — this private duplicate exists only
353    /// to exercise fallback/validation logic in unit tests below.
354    struct ModelResolver {
355        provider_name: &'static str,
356        default_model: &'static str,
357        supported_models: &'static [&'static str],
358    }
359
360    impl ModelResolver {
361        fn new(
362            provider_name: &'static str,
363            default_model: &'static str,
364            supported_models: &'static [&'static str],
365        ) -> Self {
366            Self { provider_name, default_model, supported_models }
367        }
368
369        /// Resolve model with fallback to default
370        fn resolve_model(&self, model: Option<String>) -> String {
371            model.unwrap_or_else(|| self.default_model.to_string())
372        }
373
374        /// Validate model is supported
375        fn validate_model(&self, model: &str) -> Result<()> {
376            if self.supported_models.is_empty() {
377                // If no specific supported models listed, accept any non-empty model
378                if model.is_empty() {
379                    anyhow::bail!("Model cannot be empty")
380                }
381                return Ok(());
382            }
383
384            if !self.supported_models.contains(&model) {
385                anyhow::bail!("Unsupported model: {}. Supported models: {:?}", model, self.supported_models)
386            }
387
388            Ok(())
389        }
390    }
391
392    #[test]
393    fn test_base_provider_config() {
394        let config = BaseProviderConfig::from_options(
395            Some("test_key".to_string()),
396            Some("test_model".to_string()),
397            None,
398            "default_model",
399            "https://api.example.com",
400            "TEST_API_KEY",
401            None,
402        )
403        .unwrap();
404
405        assert_eq!(config.api_key, "test_key");
406        assert_eq!(config.model, "test_model");
407        assert_eq!(config.base_url, "https://api.example.com");
408    }
409
410    #[test]
411    fn test_error_handler() {
412        let handler = ErrorHandler::new("test_provider");
413
414        let unauthorized = handler.handle_http_error(reqwest::StatusCode::UNAUTHORIZED, "Invalid API key");
415        let rate_limited = handler.handle_http_error(reqwest::StatusCode::TOO_MANY_REQUESTS, "");
416
417        assert!(matches!(unauthorized, LLMError::Provider { message: _, metadata: _ }));
418        assert!(matches!(rate_limited, LLMError::RateLimit { metadata: _ }));
419    }
420
421    #[test]
422    fn test_model_resolver() {
423        let resolver = ModelResolver::new("test_provider", "default-model", &["model1", "model2"]);
424
425        assert_eq!(resolver.resolve_model(None), "default-model");
426        assert_eq!(resolver.resolve_model(Some("custom".to_string())), "custom");
427
428        resolver.validate_model("model1").unwrap();
429        assert!(resolver.validate_model("unsupported").is_err());
430    }
431}