vectorless 0.1.21

Hierarchical, reasoning-native document intelligence engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0

//! LLM configuration types.

use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Retry configuration for LLM calls.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    /// Maximum number of retry attempts (including initial call).
    /// e.g., max_attempts=3 means 1 initial + 2 retries.
    #[serde(default = "default_max_attempts")]
    pub max_attempts: usize,

    /// Initial delay before first retry (milliseconds).
    #[serde(default = "default_initial_delay_ms")]
    pub initial_delay_ms: u64,

    /// Maximum delay between retries (milliseconds).
    #[serde(default = "default_max_delay_ms")]
    pub max_delay_ms: u64,

    /// Multiplier for exponential backoff.
    #[serde(default = "default_multiplier")]
    pub multiplier: f64,

    /// Whether to retry on rate limit errors.
    #[serde(default = "default_true")]
    pub retry_on_rate_limit: bool,
}

fn default_max_attempts() -> usize {
    3
}
fn default_initial_delay_ms() -> u64 {
    500
}
fn default_max_delay_ms() -> u64 {
    30000
}
fn default_multiplier() -> f64 {
    2.0
}
fn default_true() -> bool {
    true
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: default_max_attempts(),
            initial_delay_ms: default_initial_delay_ms(),
            max_delay_ms: default_max_delay_ms(),
            multiplier: default_multiplier(),
            retry_on_rate_limit: default_true(),
        }
    }
}

impl RetryConfig {
    /// Create a new retry config with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum number of attempts.
    pub fn with_max_attempts(mut self, max_attempts: usize) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    /// Set the initial delay (milliseconds).
    pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
        self.initial_delay_ms = delay_ms;
        self
    }

    /// Set the maximum delay (milliseconds).
    pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
        self.max_delay_ms = delay_ms;
        self
    }

    /// Set the backoff multiplier.
    pub fn with_multiplier(mut self, multiplier: f64) -> Self {
        self.multiplier = multiplier;
        self
    }

    /// Set whether to retry on rate limit.
    pub fn with_retry_on_rate_limit(mut self, retry: bool) -> Self {
        self.retry_on_rate_limit = retry;
        self
    }

    /// Calculate delay for a given attempt (0-indexed).
    pub fn delay_for_attempt(&self, attempt: usize) -> Duration {
        let delay_ms = (self.initial_delay_ms as f64) * self.multiplier.powf(attempt as f64);
        let delay_ms = delay_ms.min(self.max_delay_ms as f64);
        Duration::from_millis(delay_ms as u64)
    }
}

/// LLM client configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfig {
    /// Model name (e.g., "gpt-4o-mini", "gpt-4o").
    #[serde(default = "default_model")]
    pub model: String,

    /// API endpoint URL.
    #[serde(default = "default_endpoint")]
    pub endpoint: String,

    /// API key (optional, will use environment variable if not set).
    #[serde(default)]
    pub api_key: Option<String>,

    /// Maximum tokens for response.
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,

    /// Temperature for generation.
    #[serde(default = "default_temperature")]
    pub temperature: f32,

    /// Retry configuration.
    #[serde(default)]
    pub retry: RetryConfig,
}

fn default_model() -> String {
    "gpt-4o-mini".to_string()
}
fn default_endpoint() -> String {
    "https://api.openai.com/v1".to_string()
}
fn default_max_tokens() -> usize {
    2000
}
fn default_temperature() -> f32 {
    0.0
}

impl Default for LlmConfig {
    fn default() -> Self {
        Self {
            model: default_model(),
            endpoint: default_endpoint(),
            api_key: None,
            max_tokens: default_max_tokens(),
            temperature: default_temperature(),
            retry: RetryConfig::default(),
        }
    }
}

impl LlmConfig {
    /// Create a new config with a specific model.
    pub fn new(model: impl Into<String>) -> Self {
        Self {
            model: model.into(),
            ..Self::default()
        }
    }

    /// Set the model.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    /// Set the endpoint.
    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = endpoint.into();
        self
    }

    /// Set the API key.
    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Set the max tokens.
    pub fn with_max_tokens(mut self, max_tokens: usize) -> Self {
        self.max_tokens = max_tokens;
        self
    }

    /// Set the temperature.
    pub fn with_temperature(mut self, temperature: f32) -> Self {
        self.temperature = temperature;
        self
    }

    /// Set the retry configuration.
    pub fn with_retry(mut self, retry: RetryConfig) -> Self {
        self.retry = retry;
        self
    }

    /// Get the API key from config or environment.
    pub fn get_api_key(&self) -> Option<String> {
        self.api_key
            .clone()
            .or_else(|| std::env::var("OPENAI_API_KEY").ok())
            .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok())
            .or_else(|| std::env::var("AZURE_OPENAI_API_KEY").ok())
    }

    /// Auto-detect the best endpoint based on available API keys.
    pub fn auto_detect_endpoint(&self) -> String {
        if self.endpoint != default_endpoint() {
            return self.endpoint.clone();
        }

        if std::env::var("OPENAI_API_KEY").is_ok() {
            "https://api.openai.com/v1".to_string()
        } else if std::env::var("AZURE_OPENAI_ENDPOINT").is_ok() {
            std::env::var("AZURE_OPENAI_ENDPOINT").unwrap_or_default()
        } else if std::env::var("ANTHROPIC_API_KEY").is_ok() {
            // Anthropic uses different API structure
            "https://api.anthropic.com/v1".to_string()
        } else {
            self.endpoint.clone()
        }
    }

    /// Auto-detect the best model based on available API keys.
    pub fn auto_detect_model(&self) -> String {
        if self.model != default_model() {
            return self.model.clone();
        }

        if std::env::var("OPENAI_API_KEY").is_ok() {
            "gpt-4o-mini".to_string()
        } else if std::env::var("ANTHROPIC_API_KEY").is_ok() {
            "claude-3-haiku-20240307".to_string()
        } else {
            self.model.clone()
        }
    }
}

/// Pool of LLM configurations for different purposes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfigs {
    /// Configuration for summarization tasks.
    #[serde(default = "default_summary_config")]
    pub summary: LlmConfig,

    /// Configuration for retrieval/navigation tasks.
    #[serde(default = "default_retrieval_config")]
    pub retrieval: LlmConfig,

    /// Configuration for TOC processing tasks.
    #[serde(default = "default_toc_config")]
    pub toc: LlmConfig,
}

fn default_summary_config() -> LlmConfig {
    LlmConfig {
        model: auto_detect_summary_model(),
        max_tokens: 200,
        temperature: 0.0,
        ..LlmConfig::default()
    }
}

fn default_retrieval_config() -> LlmConfig {
    LlmConfig {
        model: auto_detect_retrieval_model(),
        max_tokens: 100,
        temperature: 0.0,
        ..LlmConfig::default()
    }
}

fn default_toc_config() -> LlmConfig {
    LlmConfig {
        model: auto_detect_toc_model(),
        max_tokens: 2000,
        temperature: 0.0,
        ..LlmConfig::default()
    }
}

fn auto_detect_summary_model() -> String {
    if std::env::var("OPENAI_API_KEY").is_ok() {
        "gpt-4o-mini".to_string()
    } else if std::env::var("ANTHROPIC_API_KEY").is_ok() {
        "claude-3-haiku-20240307".to_string()
    } else {
        "glm-4-flash".to_string()
    }
}

fn auto_detect_retrieval_model() -> String {
    if std::env::var("OPENAI_API_KEY").is_ok() {
        "gpt-4o".to_string()
    } else if std::env::var("ANTHROPIC_API_KEY").is_ok() {
        "claude-3-sonnet-20240229".to_string()
    } else {
        "glm-4".to_string()
    }
}

fn auto_detect_toc_model() -> String {
    if std::env::var("OPENAI_API_KEY").is_ok() {
        "gpt-4o-mini".to_string()
    } else if std::env::var("ANTHROPIC_API_KEY").is_ok() {
        "claude-3-haiku-20240307".to_string()
    } else {
        "glm-4-flash".to_string()
    }
}

impl Default for LlmConfigs {
    fn default() -> Self {
        Self {
            summary: default_summary_config(),
            retrieval: default_retrieval_config(),
            toc: default_toc_config(),
        }
    }
}

// ============================================================================
// Conversion from old config types (for backward compatibility)
// ============================================================================

impl From<crate::config::LlmConfig> for LlmConfig {
    fn from(old: crate::config::LlmConfig) -> Self {
        Self {
            model: old.model,
            endpoint: old.endpoint,
            api_key: old.api_key,
            max_tokens: old.max_tokens,
            temperature: old.temperature,
            retry: RetryConfig::default(),
        }
    }
}

impl From<crate::config::SummaryConfig> for LlmConfig {
    fn from(old: crate::config::SummaryConfig) -> Self {
        Self {
            model: old.model,
            endpoint: old.endpoint,
            api_key: old.api_key,
            max_tokens: old.max_tokens,
            temperature: old.temperature,
            retry: RetryConfig::default(),
        }
    }
}

impl From<crate::config::RetrievalConfig> for LlmConfig {
    fn from(old: crate::config::RetrievalConfig) -> Self {
        Self {
            model: old.model,
            endpoint: old.endpoint,
            api_key: old.api_key,
            max_tokens: old.max_tokens,
            temperature: old.temperature,
            retry: RetryConfig::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_retry_delay_calculation() {
        let config = RetryConfig::default();

        // Initial delay is 500ms
        assert_eq!(config.delay_for_attempt(0), Duration::from_millis(500));

        // Second attempt: 500 * 2 = 1000ms
        assert_eq!(config.delay_for_attempt(1), Duration::from_millis(1000));

        // Third attempt: 500 * 4 = 2000ms
        assert_eq!(config.delay_for_attempt(2), Duration::from_millis(2000));
    }

    #[test]
    fn test_retry_delay_max_cap() {
        let config = RetryConfig {
            max_delay_ms: 1500,
            ..RetryConfig::default()
        };

        // Should cap at max_delay_ms
        assert_eq!(config.delay_for_attempt(5), Duration::from_millis(1500));
    }

    #[test]
    fn test_llm_config_builder() {
        let config = LlmConfig::new("gpt-4o")
            .with_max_tokens(1000)
            .with_temperature(0.5);

        assert_eq!(config.model, "gpt-4o");
        assert_eq!(config.max_tokens, 1000);
        assert!((config.temperature - 0.5).abs() < 0.001);
    }
}