openai-ergonomic 0.22.0

Ergonomic Rust wrapper for OpenAI API
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Configuration for the `OpenAI` ergonomic client.
//!
//! This module provides configuration options for the `OpenAI` client,
//! including API key management, base URLs, timeouts, and retry settings.

use crate::auth::{AuthProvider, SharedAuthProvider};
use crate::provider::{Provider, ProviderKind, OPENAI_BASE_URL};
#[cfg(not(target_family = "wasm"))]
use crate::{errors::Result, Error};
#[cfg(not(target_family = "wasm"))]
use std::env;
use timvw_rust_runtime::Client as HttpClient;

/// The model of `client.chat()` and `client.responses()` when neither
/// `ConfigBuilder::default_model` nor `OPENAI_DEFAULT_MODEL` sets one.
pub(crate) const DEFAULT_MODEL: &str = "gpt-4";

/// Configuration for the `OpenAI` client.
///
/// The configuration can be created from environment variables or
/// manually constructed with the builder pattern.
///
/// # Environment Variables
///
/// ## Standard `OpenAI`
/// - `OPENAI_API_KEY`: The `OpenAI` API key (required)
/// - `OPENAI_API_BASE`: Custom base URL for the API (optional)
/// - `OPENAI_ORGANIZATION`: Organization ID (optional)
/// - `OPENAI_PROJECT`: Project ID (optional)
/// - `OPENAI_MAX_RETRIES`: Maximum number of retries (optional, default: 3)
///
/// ## Azure `OpenAI`
/// - `AZURE_OPENAI_API_KEY`: The Azure `OpenAI` API key (alternative to `OPENAI_API_KEY`)
/// - `AZURE_OPENAI_ENDPOINT`: Azure `OpenAI` endpoint (e.g., `<https://my-resource.openai.azure.com>`)
/// - `AZURE_OPENAI_DEPLOYMENT`: Deployment name (required for Azure)
/// - `AZURE_OPENAI_API_VERSION`: API version (optional, default: 2024-02-01)
///
/// # Example
///
/// ```rust,no_run
/// # use openai_ergonomic::Config;
/// // From environment variables
/// let config = Config::from_env().unwrap();
///
/// // Manual configuration for OpenAI
/// let config = Config::builder()
///     .api_key("your-api-key")
///     .max_retries(5)
///     .build();
///
/// // Manual configuration for Azure OpenAI
/// let config = Config::builder()
///     .api_key("your-azure-api-key")
///     .api_base("https://my-resource.openai.azure.com")
///     .azure_deployment("my-deployment")
///     .azure_api_version("2024-02-01")
///     .build();
///
/// // Another provider: base URL, authentication, headers and paths in one go
/// use openai_ergonomic::Provider;
/// let config = Config::builder()
///     .provider(Provider::openrouter("sk-or-..."))
///     .build();
/// ```
#[derive(Clone)]
pub struct Config {
    api_key: String,
    api_base: String,
    organization: Option<String>,
    project: Option<String>,
    max_retries: u32,
    default_model: String,
    http_client: Option<HttpClient>,
    azure_deployment: Option<String>,
    azure_api_version: Option<String>,
    provider: Option<Provider>,
    auth_provider: Option<SharedAuthProvider>,
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("api_key", &"***")
            .field("api_base", &self.api_base)
            .field("organization", &self.organization)
            .field("project", &self.project)
            .field("max_retries", &self.max_retries)
            .field("default_model", &self.default_model)
            .field(
                "http_client",
                &self
                    .http_client
                    .as_ref()
                    .map(|_| "<timvw_rust_runtime::Client>"),
            )
            .field("azure_deployment", &self.azure_deployment)
            .field("azure_api_version", &self.azure_api_version)
            .field("provider", &self.provider)
            .field("auth_provider", &self.auth_provider)
            .finish()
    }
}

impl Config {
    /// Create a new configuration builder.
    #[must_use]
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::default()
    }

    /// Create configuration from environment variables.
    ///
    /// Supports both standard `OpenAI` and Azure `OpenAI` configurations.
    /// For Azure `OpenAI`, set `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, and `AZURE_OPENAI_DEPLOYMENT`.
    ///
    /// Not available on WebAssembly, which has no process environment: configure
    /// [`Config::builder`] explicitly there.
    #[cfg(not(target_family = "wasm"))]
    pub fn from_env() -> Result<Self> {
        // Check for Azure OpenAI configuration first
        let azure_endpoint = env::var("AZURE_OPENAI_ENDPOINT").ok();
        let azure_deployment = env::var("AZURE_OPENAI_DEPLOYMENT").ok();
        let azure_api_version = env::var("AZURE_OPENAI_API_VERSION").ok();

        let (api_key, api_base) = if let Some(endpoint) = azure_endpoint {
            // Azure OpenAI configuration
            let key = env::var("AZURE_OPENAI_API_KEY")
                .or_else(|_| env::var("OPENAI_API_KEY"))
                .map_err(|_| {
                    Error::Config(
                        "AZURE_OPENAI_API_KEY or OPENAI_API_KEY environment variable is required"
                            .to_string(),
                    )
                })?;
            // Trim trailing slash from Azure endpoint
            let endpoint = endpoint.trim_end_matches('/').to_string();
            (key, endpoint)
        } else {
            // Standard OpenAI configuration
            let key = env::var("OPENAI_API_KEY").map_err(|_| {
                Error::Config("OPENAI_API_KEY environment variable is required".to_string())
            })?;
            let base = env::var("OPENAI_API_BASE").unwrap_or_else(|_| OPENAI_BASE_URL.to_string());
            (key, base)
        };

        let organization = env::var("OPENAI_ORGANIZATION").ok();
        let project = env::var("OPENAI_PROJECT").ok();

        let max_retries = env::var("OPENAI_MAX_RETRIES")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(3);

        let default_model =
            env::var("OPENAI_DEFAULT_MODEL").unwrap_or_else(|_| DEFAULT_MODEL.to_string());

        Ok(Self {
            api_key,
            api_base,
            organization,
            project,
            max_retries,
            default_model,
            http_client: None,
            azure_deployment,
            azure_api_version,
            provider: None,
            auth_provider: None,
        })
    }

    /// Get the API key: the key of the [provider](ConfigBuilder::provider) when one is set
    /// (empty when it has none).
    pub fn api_key(&self) -> &str {
        match &self.provider {
            Some(provider) => provider.api_key().unwrap_or_default(),
            None => &self.api_key,
        }
    }

    /// Get the API base URL: the base URL of the [provider](ConfigBuilder::provider) when one
    /// is set.
    pub fn api_base(&self) -> &str {
        match &self.provider {
            Some(provider) => provider.api_base(),
            None => &self.api_base,
        }
    }

    /// The provider requests go to: the one set with [`ConfigBuilder::provider`], or else the
    /// one the other settings describe (Azure `OpenAI` when [`Config::is_azure`], `OpenAI` at
    /// [`Config::api_base`] otherwise).
    pub fn provider(&self) -> Provider {
        if let Some(provider) = &self.provider {
            return provider.clone();
        }
        if self.is_azure() {
            // Without a deployment: the key, and the paths as they are.
            let mut provider = self.azure_deployment.as_ref().map_or_else(
                || {
                    Provider::custom(self.api_base.clone())
                        .api_key_header("api-key", self.api_key.clone())
                },
                |deployment| {
                    Provider::azure(self.api_base.clone(), self.api_key.clone(), deployment)
                },
            );
            if let Some(version) = &self.azure_api_version {
                provider = provider.api_version(version.clone());
            }
            return provider;
        }
        let provider = Provider::openai(self.api_key.clone());
        if self.api_base.trim_end_matches('/') == OPENAI_BASE_URL {
            provider
        } else {
            provider.base_url(self.api_base.clone())
        }
    }

    /// The [`AuthProvider`] set with [`ConfigBuilder::auth_provider`], if any.
    pub(crate) fn auth_provider(&self) -> Option<&SharedAuthProvider> {
        self.auth_provider.as_ref()
    }

    /// Whether an [`AuthProvider`] is set.
    pub fn has_auth_provider(&self) -> bool {
        self.auth_provider.is_some()
    }

    /// Get the organization ID, if set.
    pub fn organization(&self) -> Option<&str> {
        self.organization.as_deref()
    }

    /// Get the project ID, if set.
    pub fn project(&self) -> Option<&str> {
        self.project.as_deref()
    }

    /// Get the maximum number of retries.
    pub fn max_retries(&self) -> u32 {
        self.max_retries
    }

    /// Get the default model to use.
    pub fn default_model(&self) -> Option<&str> {
        if self.default_model.is_empty() {
            None
        } else {
            Some(&self.default_model)
        }
    }

    /// Get the base URL, if different from default.
    pub fn base_url(&self) -> Option<&str> {
        let base = self.api_base();
        if base.trim_end_matches('/') == OPENAI_BASE_URL {
            None
        } else {
            Some(base)
        }
    }

    /// Get the organization ID, if set.
    pub fn organization_id(&self) -> Option<&str> {
        self.organization.as_deref()
    }

    /// Create an authorization header value.
    pub fn auth_header(&self) -> String {
        format!("Bearer {}", self.api_key())
    }

    /// Get the custom HTTP client, if set.
    pub fn http_client(&self) -> Option<&HttpClient> {
        self.http_client.as_ref()
    }

    /// Get the Azure deployment name, if set.
    pub fn azure_deployment(&self) -> Option<&str> {
        self.provider
            .as_ref()
            .map_or(self.azure_deployment.as_deref(), Provider::azure_deployment)
    }

    /// Get the Azure API version, if set.
    pub fn azure_api_version(&self) -> Option<&str> {
        match &self.provider {
            Some(provider) if provider.kind() == ProviderKind::Azure => {
                provider.query_param("api-version")
            }
            Some(_) => None,
            None => self.azure_api_version.as_deref(),
        }
    }

    /// Check if this configuration is for Azure `OpenAI`.
    pub fn is_azure(&self) -> bool {
        if let Some(provider) = &self.provider {
            return provider.kind() == ProviderKind::Azure;
        }
        self.azure_deployment.is_some() || self.api_base.contains(".openai.azure.com")
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            api_base: "https://api.openai.com/v1".to_string(),
            organization: None,
            project: None,
            max_retries: 3,
            default_model: DEFAULT_MODEL.to_string(),
            http_client: None,
            azure_deployment: None,
            azure_api_version: None,
            provider: None,
            auth_provider: None,
        }
    }
}

/// Builder for creating `OpenAI` client configuration.
#[derive(Clone, Default)]
pub struct ConfigBuilder {
    api_key: Option<String>,
    api_base: Option<String>,
    organization: Option<String>,
    project: Option<String>,
    max_retries: Option<u32>,
    default_model: Option<String>,
    http_client: Option<HttpClient>,
    azure_deployment: Option<String>,
    azure_api_version: Option<String>,
    provider: Option<Provider>,
    auth_provider: Option<SharedAuthProvider>,
}

impl std::fmt::Debug for ConfigBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConfigBuilder")
            .field("api_key", &self.api_key.as_ref().map(|_| "***"))
            .field("api_base", &self.api_base)
            .field("provider", &self.provider)
            .finish_non_exhaustive()
    }
}

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

    /// Set the API base URL.
    #[must_use]
    pub fn api_base(mut self, api_base: impl Into<String>) -> Self {
        self.api_base = Some(api_base.into());
        self
    }

    /// Set the organization ID.
    #[must_use]
    pub fn organization(mut self, organization: impl Into<String>) -> Self {
        self.organization = Some(organization.into());
        self
    }

    /// Set the project ID.
    #[must_use]
    pub fn project(mut self, project: impl Into<String>) -> Self {
        self.project = Some(project.into());
        self
    }

    /// Set the maximum number of retries (default: 3).
    ///
    /// The default HTTP client retries `429`, `408` and `5xx` responses and failed connections
    /// up to this many times, with exponential backoff that honours `Retry-After`. `0` disables
    /// retries. It has no effect on a client set with [`ConfigBuilder::http_client`].
    #[must_use]
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    /// Set the default model to use.
    #[must_use]
    pub fn default_model(mut self, default_model: impl Into<String>) -> Self {
        self.default_model = Some(default_model.into());
        self
    }

    /// Set a custom HTTP client.
    ///
    /// The client is a [`timvw_rust_runtime::Client`]: a [tower](https://docs.rs/tower) service
    /// stack around an HTTP client (reqwest by default). Use it to configure retries, timeouts,
    /// proxies, connection pooling, logging or any other tower layer.
    ///
    /// When a custom client is set, [`ConfigBuilder::max_retries`] and the default 120 second
    /// timeout do not apply: the client's own layers do. The client still gets the
    /// [provider](ConfigBuilder::provider)'s layer (base URL, credentials, headers, query
    /// parameters and paths, including Azure's), the organization and project headers, and the
    /// [`AuthProvider`], if any.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_ergonomic::Config;
    /// use std::time::Duration;
    /// use timvw_rust_runtime::retry::RetryPolicy;
    /// use timvw_rust_runtime::{Client, ReqwestService};
    /// use tower::retry::RetryLayer;
    ///
    /// let reqwest_client = reqwest::Client::builder()
    ///     .connect_timeout(Duration::from_secs(5))
    ///     .timeout(Duration::from_secs(60))
    ///     .build()
    ///     .unwrap();
    ///
    /// // A bare reqwest service, wrapped in a retry layer with up to 5 retries.
    /// let client = Client::from_service(ReqwestService::new(reqwest_client))
    ///     .layer(RetryLayer::new(RetryPolicy::new(5)));
    ///
    /// let config = Config::builder()
    ///     .api_key("sk-...")
    ///     .http_client(client)
    ///     .build();
    /// ```
    #[must_use]
    pub fn http_client(mut self, client: HttpClient) -> Self {
        self.http_client = Some(client);
        self
    }

    /// Set the Azure deployment name.
    ///
    /// Required when using Azure `OpenAI`.
    #[must_use]
    pub fn azure_deployment(mut self, deployment: impl Into<String>) -> Self {
        self.azure_deployment = Some(deployment.into());
        self
    }

    /// Set the Azure API version.
    ///
    /// Defaults to [`AZURE_DEFAULT_API_VERSION`](crate::provider::AZURE_DEFAULT_API_VERSION) ("2024-02-01") if not specified.
    #[must_use]
    pub fn azure_api_version(mut self, version: impl Into<String>) -> Self {
        self.azure_api_version = Some(version.into());
        self
    }

    /// Set the provider: where requests go and how they are authenticated (see
    /// [`Provider`]). It takes the place of [`ConfigBuilder::api_key`],
    /// [`ConfigBuilder::api_base`] and the Azure settings.
    ///
    /// ```rust
    /// use openai_ergonomic::{Config, Provider};
    ///
    /// let config = Config::builder()
    ///     .provider(Provider::groq("gsk-..."))
    ///     .default_model("llama-3.3-70b-versatile")
    ///     .build();
    /// assert_eq!(config.api_base(), "https://api.groq.com/openai/v1");
    /// ```
    #[must_use]
    pub fn provider(mut self, provider: Provider) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Set an [`AuthProvider`] that supplies (and refreshes) the credentials of each request to
    /// the provider, such as [`BearerTokenAuth`](crate::auth::BearerTokenAuth). See the
    /// [`auth`](crate::auth) module.
    #[must_use]
    pub fn auth_provider(mut self, auth_provider: impl AuthProvider) -> Self {
        self.auth_provider = Some(SharedAuthProvider::new(auth_provider));
        self
    }

    /// Build the configuration.
    #[must_use]
    pub fn build(self) -> Config {
        Config {
            api_key: self.api_key.unwrap_or_default(),
            api_base: self
                .api_base
                .unwrap_or_else(|| "https://api.openai.com/v1".to_string()),
            organization: self.organization,
            project: self.project,
            max_retries: self.max_retries.unwrap_or(3),
            default_model: self
                .default_model
                .unwrap_or_else(|| DEFAULT_MODEL.to_string()),
            http_client: self.http_client,
            azure_deployment: self.azure_deployment,
            azure_api_version: self.azure_api_version,
            provider: self.provider,
            auth_provider: self.auth_provider,
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_config_builder() {
        let config = Config::builder().api_key("test-key").max_retries(5).build();

        assert_eq!(config.api_key(), "test-key");
        assert_eq!(config.max_retries(), 5);
        assert_eq!(config.api_base(), "https://api.openai.com/v1");
    }

    #[test]
    fn test_auth_header() {
        let config = Config::builder().api_key("test-key").build();

        assert_eq!(config.auth_header(), "Bearer test-key");
    }

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.max_retries(), 3);
        assert_eq!(config.default_model(), Some("gpt-4"));
    }

    #[test]
    fn test_config_with_custom_http_client() {
        let http_client = HttpClient::from_reqwest(
            reqwest::Client::builder()
                .timeout(Duration::from_secs(30))
                .build()
                .unwrap(),
        );

        let config = Config::builder()
            .api_key("test-key")
            .http_client(http_client)
            .build();

        assert!(config.http_client().is_some());
    }

    #[test]
    fn test_config_without_custom_http_client() {
        let config = Config::builder().api_key("test-key").build();

        assert!(config.http_client().is_none());
    }

    #[test]
    fn test_config_debug_hides_sensitive_data() {
        let config = Config::builder().api_key("secret-key-12345").build();

        let debug_output = format!("{config:?}");

        // Should not contain the actual API key
        assert!(!debug_output.contains("secret-key-12345"));
        // Should contain the masked version
        assert!(debug_output.contains("***"));
    }

    #[test]
    fn test_config_debug_with_http_client() {
        let http_client = HttpClient::default();
        let config = Config::builder()
            .api_key("test-key")
            .http_client(http_client)
            .build();

        let debug_output = format!("{config:?}");

        // Should show placeholder for HTTP client
        assert!(debug_output.contains("<timvw_rust_runtime::Client>"));
    }
}