rai-sdk 0.1.0

Rust AI SDK — unified client for OpenAI, Anthropic, and OpenRouter with typed models, structured output, tool calling, and streaming
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Client-level configuration: credentials, endpoints, timeouts, retries.
//!
//! [`Config`] holds everything that is scoped to a client rather than to a
//! single request. It can be built explicitly, loaded from the environment
//! with [`Config::from_env`], or mixed: the getters fall back to environment
//! variables when a field was not set programmatically, so an explicit value
//! always wins over the environment.
//!
//! # Environment variables
//!
//! * `OPENAI_API_KEY`, `OPENAI_BASE_URL`
//! * `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`
//! * `OPENROUTER_API_KEY`, `OPENROUTER_BASE_URL`
//! * `OPENROUTER_HTTP_REFERER` (or the legacy `OPENROUTER_APP_URL`),
//!   `OPENROUTER_TITLE` (or the legacy `OPENROUTER_APP_TITLE`),
//!   `OPENROUTER_CATEGORIES` (comma-separated)
//! * `AI_TIMEOUT_SECONDS`
//! * `AI_MAX_RETRIES`, `AI_RETRY_INITIAL_DELAY_MS`, `AI_RETRY_MAX_DELAY_MS`,
//!   `AI_RETRY_BACKOFF_MULTIPLIER`, `AI_RETRY_JITTER`
//!
//! # Examples
//!
//! ```no_run
//! use std::time::Duration;
//! use rai_sdk::{Config, RetryConfig};
//!
//! // Start from the environment, then override selected values.
//! let config = Config::from_env()
//!     .with_timeout(30)
//!     .with_default_max_tokens(2048)
//!     .with_retry_config(RetryConfig::new().with_initial_delay(Duration::from_millis(250)));
//!
//! assert_eq!(config.timeout(), 30);
//! ```

use serde::{Deserialize, Serialize};

#[cfg(any(feature = "openai", feature = "anthropic", feature = "openrouter"))]
use crate::error;
use crate::retry::RetryConfig;

/// Configuration for the AI SDK client.
///
/// Every field is optional. Unset credentials simply mean the corresponding
/// provider is unavailable rather than an error at construction time; the
/// failure surfaces as [`Error::ProviderNotConfigured`](crate::Error::ProviderNotConfigured)
/// when that provider is actually used.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    /// OpenAI API key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openai_api_key: Option<String>,

    /// OpenAI API base URL (for proxies or Azure OpenAI).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openai_base_url: Option<String>,

    /// Anthropic API key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anthropic_api_key: Option<String>,

    /// Anthropic API base URL (for proxies).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anthropic_base_url: Option<String>,

    /// OpenRouter API key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_api_key: Option<String>,

    /// OpenRouter API base URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_base_url: Option<String>,

    /// Optional app URL for OpenRouter attribution headers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_http_referer: Option<String>,

    /// Optional app title for OpenRouter attribution headers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_title: Option<String>,

    /// Optional app categories for OpenRouter attribution headers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_categories: Option<Vec<String>>,

    /// OpenRouter App URL (sent in headers).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_app_url: Option<String>,

    /// OpenRouter App Title (sent in headers).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openrouter_app_title: Option<String>,

    /// Request timeout in seconds (default: 120).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<u64>,

    /// Default max tokens for generation (can be overridden per request).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_max_tokens: Option<i32>,

    /// Retry configuration for transient errors.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_config: Option<RetryConfig>,
}

impl Config {
    /// Create a new empty configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create configuration from environment variables.
    ///
    /// Reads every variable listed in the [module docs](self). Missing or
    /// unparseable values are ignored, leaving the corresponding field unset
    /// (and therefore at its default). The retry configuration is only
    /// populated when at least one `AI_RETRY_*`/`AI_MAX_RETRIES` variable was
    /// recognized.
    pub fn from_env() -> Self {
        let mut config = Self::new();

        if let Ok(key) = std::env::var("OPENAI_API_KEY") {
            config.openai_api_key = Some(key);
        }
        if let Ok(url) = std::env::var("OPENAI_BASE_URL") {
            config.openai_base_url = Some(url);
        }
        if let Ok(key) = std::env::var("ANTHROPIC_API_KEY") {
            config.anthropic_api_key = Some(key);
        }
        if let Ok(url) = std::env::var("ANTHROPIC_BASE_URL") {
            config.anthropic_base_url = Some(url);
        }
        if let Ok(key) = std::env::var("OPENROUTER_API_KEY") {
            config.openrouter_api_key = Some(key);
        }
        if let Ok(url) = std::env::var("OPENROUTER_BASE_URL") {
            config.openrouter_base_url = Some(url);
        }
        if let Ok(referer) = std::env::var("OPENROUTER_HTTP_REFERER") {
            config.openrouter_http_referer = Some(referer);
        } else if let Ok(url) = std::env::var("OPENROUTER_APP_URL") {
            config.openrouter_app_url = Some(url.clone());
            config.openrouter_http_referer = Some(url);
        }
        if let Ok(title) = std::env::var("OPENROUTER_TITLE") {
            config.openrouter_title = Some(title);
        } else if let Ok(title) = std::env::var("OPENROUTER_APP_TITLE") {
            config.openrouter_app_title = Some(title.clone());
            config.openrouter_title = Some(title);
        }
        if let Ok(categories) = std::env::var("OPENROUTER_CATEGORIES") {
            let categories = parse_openrouter_categories(&categories);
            if !categories.is_empty() {
                config.openrouter_categories = Some(categories);
            }
        }
        if let Ok(timeout) = std::env::var("AI_TIMEOUT_SECONDS") {
            if let Ok(secs) = timeout.parse() {
                config.timeout_seconds = Some(secs);
            }
        }

        let mut retry = RetryConfig::default();
        let mut retry_customized = false;

        if let Ok(value) = std::env::var("AI_MAX_RETRIES") {
            if let Ok(max_retries) = value.parse() {
                retry.max_retries = max_retries;
                retry_customized = true;
            }
        }
        if let Ok(value) = std::env::var("AI_RETRY_INITIAL_DELAY_MS") {
            if let Ok(milliseconds) = value.parse() {
                retry.initial_delay = std::time::Duration::from_millis(milliseconds);
                retry_customized = true;
            }
        }
        if let Ok(value) = std::env::var("AI_RETRY_MAX_DELAY_MS") {
            if let Ok(milliseconds) = value.parse() {
                retry.max_delay = std::time::Duration::from_millis(milliseconds);
                retry_customized = true;
            }
        }
        if let Ok(value) = std::env::var("AI_RETRY_BACKOFF_MULTIPLIER") {
            if let Ok(multiplier) = value.parse() {
                retry.backoff_multiplier = multiplier;
                retry_customized = true;
            }
        }
        if let Ok(value) = std::env::var("AI_RETRY_JITTER") {
            if let Some(jitter) = parse_bool(&value) {
                retry.jitter = jitter;
                retry_customized = true;
            }
        }

        if retry_customized {
            config.retry_config = Some(retry);
        }

        config
    }

    // ── Builder methods ──

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

    /// Set the OpenAI base URL, for proxies or Azure OpenAI deployments.
    pub fn with_openai_base_url(mut self, url: impl Into<String>) -> Self {
        self.openai_base_url = Some(url.into());
        self
    }

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

    /// Set the Anthropic base URL, for proxies.
    pub fn with_anthropic_base_url(mut self, url: impl Into<String>) -> Self {
        self.anthropic_base_url = Some(url.into());
        self
    }

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

    /// Set the OpenRouter base URL, for proxies.
    pub fn with_openrouter_base_url(mut self, url: impl Into<String>) -> Self {
        self.openrouter_base_url = Some(url.into());
        self
    }

    /// Set the OpenRouter `HTTP-Referer` attribution header.
    pub fn with_openrouter_http_referer(mut self, referer: impl Into<String>) -> Self {
        self.openrouter_http_referer = Some(referer.into());
        self
    }

    /// Set the OpenRouter app title attribution header.
    pub fn with_openrouter_title(mut self, title: impl Into<String>) -> Self {
        self.openrouter_title = Some(title.into());
        self
    }

    /// Set the OpenRouter app categories attribution header.
    pub fn with_openrouter_categories(mut self, categories: Vec<String>) -> Self {
        self.openrouter_categories = Some(categories);
        self
    }

    /// Set the legacy OpenRouter app URL, which also sets the canonical
    /// `HTTP-Referer` value.
    pub fn with_openrouter_app_url(mut self, url: impl Into<String>) -> Self {
        let url = url.into();
        self.openrouter_app_url = Some(url.clone());
        self.openrouter_http_referer = Some(url);
        self
    }

    /// Set the legacy OpenRouter app title, which also sets the canonical
    /// title value.
    pub fn with_openrouter_app_title(mut self, title: impl Into<String>) -> Self {
        let title = title.into();
        self.openrouter_app_title = Some(title.clone());
        self.openrouter_title = Some(title);
        self
    }

    /// Set the HTTP request timeout, in seconds.
    pub fn with_timeout(mut self, seconds: u64) -> Self {
        self.timeout_seconds = Some(seconds);
        self
    }

    /// Set the default `max_tokens` used when a request does not specify one.
    pub fn with_default_max_tokens(mut self, max_tokens: i32) -> Self {
        self.default_max_tokens = Some(max_tokens);
        self
    }

    /// Set the retry policy applied to transient errors.
    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
        self.retry_config = Some(retry_config);
        self
    }

    // ── Getters with env-var fallback ──

    /// The OpenAI API key, falling back to `OPENAI_API_KEY`.
    pub fn openai_key(&self) -> Option<String> {
        self.openai_api_key
            .clone()
            .or_else(|| std::env::var("OPENAI_API_KEY").ok())
    }

    /// The Anthropic API key, falling back to `ANTHROPIC_API_KEY`.
    pub fn anthropic_key(&self) -> Option<String> {
        self.anthropic_api_key
            .clone()
            .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok())
    }

    /// The OpenRouter API key, falling back to `OPENROUTER_API_KEY`.
    pub fn openrouter_key(&self) -> Option<String> {
        self.openrouter_api_key
            .clone()
            .or_else(|| std::env::var("OPENROUTER_API_KEY").ok())
    }

    /// The OpenRouter base URL, falling back to `OPENROUTER_BASE_URL`.
    ///
    /// `None` means the provider uses its built-in default endpoint.
    pub fn openrouter_base_url(&self) -> Option<String> {
        self.openrouter_base_url
            .clone()
            .or_else(|| std::env::var("OPENROUTER_BASE_URL").ok())
    }

    /// The OpenRouter `HTTP-Referer` value.
    ///
    /// Resolution order: the explicit referer, the legacy app URL,
    /// `OPENROUTER_HTTP_REFERER`, then `OPENROUTER_APP_URL`.
    pub fn openrouter_http_referer(&self) -> Option<String> {
        self.openrouter_http_referer
            .clone()
            .or_else(|| self.openrouter_app_url.clone())
            .or_else(|| std::env::var("OPENROUTER_HTTP_REFERER").ok())
            .or_else(|| std::env::var("OPENROUTER_APP_URL").ok())
    }

    /// The OpenRouter app title used for attribution headers.
    ///
    /// Resolution order: the explicit title, the legacy app title,
    /// `OPENROUTER_TITLE`, then `OPENROUTER_APP_TITLE`.
    pub fn openrouter_title(&self) -> Option<String> {
        self.openrouter_title
            .clone()
            .or_else(|| self.openrouter_app_title.clone())
            .or_else(|| std::env::var("OPENROUTER_TITLE").ok())
            .or_else(|| std::env::var("OPENROUTER_APP_TITLE").ok())
    }

    /// The OpenRouter app categories, falling back to the comma-separated
    /// `OPENROUTER_CATEGORIES` variable. Empty lists are treated as unset.
    pub fn openrouter_categories(&self) -> Option<Vec<String>> {
        self.openrouter_categories.clone().or_else(|| {
            std::env::var("OPENROUTER_CATEGORIES")
                .ok()
                .map(|categories| parse_openrouter_categories(&categories))
                .filter(|categories| !categories.is_empty())
        })
    }

    /// Deprecated alias for [`Config::openrouter_http_referer`], kept for
    /// callers written against the older attribution field names.
    pub fn openrouter_app_url(&self) -> Option<String> {
        self.openrouter_http_referer()
    }

    /// Deprecated alias for [`Config::openrouter_title`], kept for callers
    /// written against the older attribution field names.
    pub fn openrouter_app_title(&self) -> Option<String> {
        self.openrouter_title()
    }

    /// The effective retry policy, or [`RetryConfig::default`] when unset.
    pub fn retry_config(&self) -> RetryConfig {
        self.retry_config.clone().unwrap_or_default()
    }

    /// The effective HTTP timeout in seconds (defaults to 120).
    pub fn timeout(&self) -> u64 {
        self.timeout_seconds.unwrap_or(120)
    }

    // ── Validation ──

    /// Check that OpenAI is usable.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`](crate::Error::Config) if no OpenAI API key is
    /// set programmatically or in `OPENAI_API_KEY`.
    #[cfg(feature = "openai")]
    pub fn validate_openai(&self) -> error::Result<()> {
        if self.openai_key().is_none() {
            return Err(error::Error::Config(
                "OpenAI API key not configured. Set OPENAI_API_KEY env var or provide via config."
                    .into(),
            ));
        }
        Ok(())
    }

    /// Check that Anthropic is usable.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`](crate::Error::Config) if no Anthropic API key
    /// is set programmatically or in `ANTHROPIC_API_KEY`.
    #[cfg(feature = "anthropic")]
    pub fn validate_anthropic(&self) -> error::Result<()> {
        if self.anthropic_key().is_none() {
            return Err(error::Error::Config(
                "Anthropic API key not configured. Set ANTHROPIC_API_KEY env var or provide via config."
                    .into(),
            ));
        }
        Ok(())
    }

    /// Check that OpenRouter is usable.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`](crate::Error::Config) if no OpenRouter API key
    /// is set programmatically or in `OPENROUTER_API_KEY`.
    #[cfg(feature = "openrouter")]
    pub fn validate_openrouter(&self) -> error::Result<()> {
        if self.openrouter_key().is_none() {
            return Err(error::Error::Config(
                "OpenRouter API key not configured. Set OPENROUTER_API_KEY env var or provide via config."
                    .into(),
            ));
        }
        Ok(())
    }
}

fn parse_openrouter_categories(value: &str) -> Vec<String> {
    value
        .split(',')
        .map(str::trim)
        .filter(|category| !category.is_empty())
        .map(ToOwned::to_owned)
        .collect()
}

fn parse_bool(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    #[test]
    fn openrouter_attribution_builders_set_canonical_fields() {
        let config = Config::new()
            .with_openrouter_base_url("https://proxy.example.com/api/v1")
            .with_openrouter_http_referer("https://app.example.com")
            .with_openrouter_title("Example App")
            .with_openrouter_categories(vec!["productivity".to_string(), "agents".to_string()]);

        assert_eq!(
            config.openrouter_base_url(),
            Some("https://proxy.example.com/api/v1".to_string())
        );
        assert_eq!(
            config.openrouter_http_referer(),
            Some("https://app.example.com".to_string())
        );
        assert_eq!(config.openrouter_title(), Some("Example App".to_string()));
        assert_eq!(
            config.openrouter_categories(),
            Some(vec!["productivity".to_string(), "agents".to_string()])
        );
    }

    #[test]
    fn retry_config_defaults_when_not_set() {
        assert_eq!(Config::new().retry_config().max_retries, 3);
    }

    #[test]
    fn retry_config_builder_overrides_defaults() {
        let retry = RetryConfig::new().with_initial_delay(Duration::from_millis(250));
        let config = Config::new().with_retry_config(retry);

        assert_eq!(
            config.retry_config().initial_delay,
            Duration::from_millis(250)
        );
    }

    #[test]
    fn openrouter_category_parser_trims_empty_values() {
        assert_eq!(
            parse_openrouter_categories(" agents, , productivity "),
            vec!["agents".to_string(), "productivity".to_string()]
        );
    }
}