openai4rs 0.1.8

A non-official Rust crate for calling the OpenAI service
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
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
use super::base::{BaseConfig, BaseConfigBuilder};
use super::http::{HttpConfig, HttpConfigBuilder};
use crate::{Interceptor, OpenAI, interceptor::InterceptorChain};
use std::{collections::HashMap, fmt};

#[derive(Debug)]
pub enum ConfigBuildError {
    /// Required fields missing error
    RequiredFieldMissing(String),
    /// Validation error
    ValidationError(String),
}

impl fmt::Display for ConfigBuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigBuildError::RequiredFieldMissing(field) => {
                write!(f, "Required field missing: {}", field)
            }
            ConfigBuildError::ValidationError(msg) => {
                write!(f, "Validation error: {}", msg)
            }
        }
    }
}

impl std::error::Error for ConfigBuildError {}

// Implement From trait to adapt builder-generated error types
impl From<super::http::HttpConfigBuilderError> for ConfigBuildError {
    fn from(err: super::http::HttpConfigBuilderError) -> Self {
        ConfigBuildError::RequiredFieldMissing(err.to_string())
    }
}

impl From<super::base::BaseConfigBuilderError> for ConfigBuildError {
    fn from(err: super::base::BaseConfigBuilderError) -> Self {
        ConfigBuildError::RequiredFieldMissing(err.to_string())
    }
}

/// Main configuration struct containing all settings for API communication
pub struct Config {
    /// Base configuration containing API key and URL
    base: BaseConfig,
    /// HTTP-specific configuration (timeouts, proxy, etc.)
    http: HttpConfig,
    /// Number of retry attempts for failed requests
    retry_count: u32,
    /// Global interceptors for all requests
    global_interceptors: InterceptorChain,
}
impl Config {
    /// Creates a new Config with the specified API key and base URL
    ///
    /// # Arguments
    ///
    /// * `api_key` - The API key for authentication
    /// * `base_url` - The base URL for API requests
    pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        Self {
            base: BaseConfig::new(api_key.into(), base_url.into()),
            http: HttpConfig::default(),
            retry_count: 5,
            global_interceptors: InterceptorChain::new(),
        }
    }

    /// Creates a new ConfigBuilder for fluent configuration
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder {
            retry_count: 5,
            base_builder: BaseConfigBuilder::default(),
            http_builder: HttpConfigBuilder::default(),
            global_interceptors: InterceptorChain::new(),
        }
    }

    /// Returns the API key
    #[inline]
    pub fn api_key(&self) -> &str {
        self.base.api_key()
    }

    /// Returns the base URL
    #[inline]
    pub fn base_url(&self) -> &str {
        self.base.base_url()
    }

    /// Returns the retry count
    #[inline]
    pub fn retry_count(&self) -> u32 {
        self.retry_count
    }

    /// Returns the request timeout in seconds
    #[inline]
    pub fn timeout_seconds(&self) -> u64 {
        self.http.timeout_seconds()
    }

    /// Returns an optional proxy URL
    #[inline]
    pub fn proxy(&self) -> Option<&String> {
        self.http.proxy()
    }

    /// Returns an optional custom user agent string
    #[inline]
    pub fn user_agent(&self) -> Option<&String> {
        self.http.user_agent()
    }

    /// Returns the connection timeout in seconds
    #[inline]
    pub fn connect_timeout_seconds(&self) -> u64 {
        self.http.connect_timeout_seconds()
    }

    /// Returns a reference to the HTTP configuration
    #[inline]
    pub fn http(&self) -> &HttpConfig {
        &self.http
    }

    /// Returns a reference to the base configuration
    #[inline]
    pub fn base(&self) -> &super::base::BaseConfig {
        &self.base
    }

    /// Returns a reference to the global interceptors
    #[inline]
    pub fn global_interceptors(&self) -> &InterceptorChain {
        &self.global_interceptors
    }

    /// Returns a mutable reference to the global interceptors
    #[inline]
    pub fn global_interceptors_mut(&mut self) -> &mut InterceptorChain {
        &mut self.global_interceptors
    }

    /// Sets a new base URL for this configuration
    ///
    /// # Arguments
    ///
    /// * `base_url` - The new base URL to use
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_base_url(&mut self, base_url: impl Into<String>) -> &mut Self {
        self.base.with_base_url(base_url);
        self
    }

    /// Sets a new API key for this configuration
    ///
    /// # Arguments
    ///
    /// * `api_key` - The new API key to use
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_api_key(&mut self, api_key: impl Into<String>) -> &mut Self {
        self.base.with_api_key(api_key);
        self
    }

    /// Sets the number of retry attempts for failed requests
    ///
    /// # Arguments
    ///
    /// * `retry_count` - The number of retry attempts
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_retry_count(&mut self, retry_count: u32) -> &mut Self {
        self.retry_count = retry_count;
        self
    }

    /// Sets the request timeout in seconds
    ///
    /// # Arguments
    ///
    /// * `timeout_seconds` - The timeout value in seconds
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_timeout_seconds(&mut self, timeout_seconds: u64) -> &mut Self {
        self.http.with_timeout_seconds(timeout_seconds);
        self
    }

    /// Sets the connection timeout in seconds
    ///
    /// # Arguments
    ///
    /// * `connect_timeout_seconds` - The connection timeout value in seconds
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_connect_timeout_seconds(&mut self, connect_timeout_seconds: u64) -> &mut Self {
        self.http
            .with_connect_timeout_seconds(connect_timeout_seconds);
        self
    }

    /// Sets an HTTP proxy for requests
    ///
    /// # Arguments
    ///
    /// * `proxy` - The proxy URL to use
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_proxy(&mut self, proxy: impl Into<String>) -> &mut Self {
        self.http.with_proxy(proxy);
        self
    }

    /// Sets a custom user agent string
    ///
    /// # Arguments
    ///
    /// * `user_agent` - The user agent string to use
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn with_user_agent(&mut self, user_agent: impl Into<String>) -> &mut Self {
        self.http.with_user_agent(user_agent);
        self
    }

    /// Adds a global interceptor
    ///
    /// # Arguments
    ///
    /// * `interceptor` - The interceptor to add
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn add_global_interceptor(&mut self, interceptor: impl Interceptor + 'static) -> &mut Self {
        self.global_interceptors.add_interceptor(interceptor);
        self
    }
}

/// Builder for creating Config instances with fluent API
pub struct ConfigBuilder {
    /// Number of retry attempts for failed requests
    retry_count: u32,
    /// Global interceptors for all requests
    global_interceptors: InterceptorChain,
    /// Builder for BaseConfig
    base_builder: BaseConfigBuilder,
    /// Builder for HttpConfig
    http_builder: HttpConfigBuilder,
}

impl ConfigBuilder {
    /// Builds the Config instance from the current builder state
    ///
    /// # Returns
    ///
    /// A Result containing either the Config instance or a ConfigBuildError
    pub fn build(self) -> Result<Config, ConfigBuildError> {
        Ok(Config {
            base: self.base_builder.build()?,
            http: self.http_builder.build()?,
            retry_count: self.retry_count,
            global_interceptors: self.global_interceptors,
        })
    }

    /// Builds an OpenAI client instance from the current configuration
    ///
    /// # Returns
    ///
    /// A Result containing either the OpenAI client instance or a ConfigBuildError
    pub fn build_openai(self) -> Result<OpenAI, ConfigBuildError> {
        Ok(OpenAI::with_config(self.build()?))
    }

    /// Sets the API key for the configuration
    ///
    /// # Arguments
    ///
    /// * `api_key` - The API key to use
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
        self.base_builder = self.base_builder.api_key(api_key.into());
        self
    }

    /// Sets the base URL for the configuration
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL to use
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_builder = self.base_builder.base_url(base_url.into());
        self
    }

    /// Sets the retry count for the configuration
    ///
    /// # Arguments
    ///
    /// * `retry_count` - The number of retry attempts
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn retry_count(mut self, retry_count: u32) -> Self {
        self.retry_count = retry_count;
        self
    }

    /// Sets the request timeout in seconds for the configuration
    ///
    /// # Arguments
    ///
    /// * `timeout_seconds` - The timeout value in seconds
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn timeout_seconds(mut self, timeout_seconds: u64) -> Self {
        self.http_builder = self.http_builder.timeout_seconds(timeout_seconds);
        self
    }

    /// Sets the connection timeout in seconds for the configuration
    ///
    /// # Arguments
    ///
    /// * `connect_timeout_seconds` - The connection timeout value in seconds
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn connect_timeout_seconds(mut self, connect_timeout_seconds: u64) -> Self {
        self.http_builder = self
            .http_builder
            .connect_timeout_seconds(connect_timeout_seconds);
        self
    }

    /// Sets an HTTP proxy for the configuration
    ///
    /// # Arguments
    ///
    /// * `proxy` - The proxy URL to use
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
        self.http_builder = self.http_builder.proxy(proxy.into());
        self
    }

    /// Sets a custom user agent string for the configuration
    ///
    /// # Arguments
    ///
    /// * `user_agent` - The user agent string to use
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.http_builder = self.http_builder.user_agent(user_agent.into());
        self
    }

    /// Adds a global header to the HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The header name
    /// * `value` - The header value
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.http_builder = self.http_builder.header(key.into(), value.into());
        self
    }

    /// Adds a global query parameter to the HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The query parameter name
    /// * `value` - The query parameter value
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.http_builder = self.http_builder.query(key.into(), value.into());
        self
    }

    /// Adds a global body field to the HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The body field name
    /// * `value` - The body field value
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn body(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
        self.http_builder = self.http_builder.body(key.into(), value.into());
        self
    }

    /// Adds a global interceptor to the configuration.
    ///
    /// # Arguments
    ///
    /// * `interceptor` - The interceptor to add
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn global_interceptor(mut self, interceptor: impl Interceptor + 'static) -> Self {
        self.global_interceptors.add_interceptor(interceptor);
        self
    }

    /// Sets multiple global headers in the HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `headers` - A map of header names to values
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
        self.http_builder = self.http_builder.headers(headers);
        self
    }

    /// Sets multiple global query parameters in the HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `queries` - A map of query parameter names to values
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn querys(mut self, queries: HashMap<String, String>) -> Self {
        self.http_builder = self.http_builder.querys(queries);
        self
    }

    /// Sets multiple global body fields in the HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `bodys` - A map of body field names to values
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn bodys(mut self, bodys: HashMap<String, serde_json::Value>) -> Self {
        self.http_builder = self.http_builder.bodys(bodys);
        self
    }
}