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
use crate::common::types::{Bodies, Headers, QueryParams};
use derive_builder::Builder;
use std::collections::HashMap;

/// HTTP client configuration for connecting to an API service.
///
/// This struct holds settings related to the underlying HTTP transport layer,
/// such as timeouts, proxy settings, and user agent. It is designed to be
/// reusable and independent of any specific API's business logic.
///
/// The configuration uses the builder pattern for flexible construction, allowing
/// users to set only the options they need while using sensible defaults for others.
#[derive(Debug, Clone, Builder)]
#[builder(name = "HttpConfigBuilder", pattern = "owned", setter(strip_option))]
pub struct HttpConfig {
    /// Request timeout in seconds. Default: 300
    ///
    /// This is the total time allowed for a request to complete, including
    /// DNS resolution, connection establishment, sending the request,
    /// and receiving the response.
    #[builder(default = 300)]
    timeout_seconds: u64,

    /// Connection timeout in seconds. Default: 10
    ///
    /// This is the maximum time allowed to establish a connection to the server.
    /// It is a subset of the overall request timeout.
    #[builder(default = 10)]
    connect_timeout_seconds: u64,

    /// HTTP proxy URL (if any)
    ///
    /// If set, all HTTP requests will be routed through this proxy server.
    /// Supported proxy schemes include HTTP, HTTPS, and SOCKS.
    #[builder(default = None)]
    proxy: Option<String>,

    /// User agent string
    ///
    /// If set, this value will be used as the User-Agent header for all requests.
    /// If not set, the default reqwest User-Agent will be used.
    #[builder(default = None)]
    user_agent: Option<String>,

    /// Global headers to be included in all requests
    ///
    /// These headers will be automatically added to every HTTP request made with this configuration.
    #[builder(default = HashMap::new())]
    headers: Headers,

    /// Global query parameters to be appended to all request URLs
    ///
    /// These query parameters will be automatically appended to every request URL.
    #[builder(default = HashMap::new())]
    querys: QueryParams,

    /// Global body fields to be included in all requests that have a body
    ///
    /// These fields will be automatically merged into the body of every request that includes a body.
    #[builder(default = HashMap::new())]
    bodys: Bodies,
}

impl HttpConfig {
    /// Creates a new configuration builder.
    ///
    /// This is the preferred way to construct an HttpConfig, allowing for
    /// flexible configuration with sensible defaults.
    ///
    /// # Examples
    ///
    /// ```
    /// use openai4rs::config::HttpConfig;
    ///
    /// let config = HttpConfig::builder()
    ///     .timeout_seconds(60)
    ///     .proxy("http://proxy.example.com:8080".to_string())
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> HttpConfigBuilder {
        HttpConfigBuilder::default()
    }

    /// Returns the request timeout in seconds.
    ///
    /// This value determines the total time allowed for a request to complete,
    /// including DNS resolution, connection establishment, sending the request,
    /// and receiving the response.
    #[inline]
    pub fn timeout_seconds(&self) -> u64 {
        self.timeout_seconds
    }

    /// Returns the connection timeout in seconds.
    ///
    /// This value determines the maximum time allowed to establish a connection to the server.
    /// It is a subset of the overall request timeout.
    #[inline]
    pub fn connect_timeout_seconds(&self) -> u64 {
        self.connect_timeout_seconds
    }

    /// Returns an optional reference to the proxy URL.
    ///
    /// If a proxy is configured, this method returns Some containing a reference to the proxy URL.
    /// Otherwise, it returns None.
    #[inline]
    pub fn proxy(&self) -> Option<&String> {
        self.proxy.as_ref()
    }

    /// Returns an optional reference to the user agent string.
    ///
    /// If a custom user agent is configured, this method returns Some containing a reference to the user agent string.
    /// Otherwise, it returns None, which means the default reqwest User-Agent will be used.
    #[inline]
    pub fn user_agent(&self) -> Option<&String> {
        self.user_agent.as_ref()
    }

    /// Returns a reference to the global headers map.
    ///
    /// This map contains headers that will be automatically added to all requests.
    #[inline]
    pub fn headers(&self) -> &Headers {
        &self.headers
    }

    /// Returns a reference to the global query parameters map.
    ///
    /// This map contains query parameters that will be automatically appended to all request URLs.
    #[inline]
    pub fn querys(&self) -> &QueryParams {
        &self.querys
    }

    /// Returns a reference to the global body fields map.
    ///
    /// This map contains body fields that will be automatically included in all request bodies.
    #[inline]
    pub fn bodys(&self) -> &Bodies {
        &self.bodys
    }

    /// Gets a specific global body field by key.
    ///
    /// # Arguments
    ///
    /// * `key` - The key of the body field to retrieve
    ///
    /// # Returns
    ///
    /// An Option containing a reference to the global body field value if it exists, or None otherwise
    #[inline]
    pub fn get_body(&self, key: &str) -> Option<&serde_json::Value> {
        self.bodys.get(key)
    }

    /// Gets a specific global header by key.
    ///
    /// # Arguments
    ///
    /// * `key` - The key of the header to retrieve
    ///
    /// # Returns
    ///
    /// An Option containing a reference to the global header value if it exists, or None otherwise
    #[inline]
    pub fn get_header(&self, key: &str) -> Option<&String> {
        self.headers.get(key)
    }

    /// Gets a specific global query parameter by key.
    ///
    /// # Arguments
    ///
    /// * `key` - The key of the query parameter to retrieve
    ///
    /// # Returns
    ///
    /// An Option containing a reference to the global query parameter value if it exists, or None otherwise
    #[inline]
    pub fn get_query(&self, key: &str) -> Option<&String> {
        self.querys.get(key)
    }

    /// Adds a global header to the configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The header name
    /// * `value` - The header value
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn add_header(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// Removes a global header from the configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The header name to remove
    ///
    /// # Returns
    ///
    /// An Option containing the removed header value if it existed, or None otherwise
    pub fn remove_header(&mut self, key: &str) -> Option<String> {
        self.headers.remove(key)
    }

    /// Adds a global query parameter to the configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The query parameter name
    /// * `value` - The query parameter value
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn add_query(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.querys.insert(key.into(), value.into());
        self
    }

    /// Removes a global query parameter from the configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The query parameter name to remove
    ///
    /// # Returns
    ///
    /// An Option containing the removed query parameter value if it existed, or None otherwise
    pub fn remove_query(&mut self, key: &str) -> Option<String> {
        self.querys.remove(key)
    }

    /// Adds a global body field to the configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The body field name
    /// * `value` - The body field value
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn add_body(
        &mut self,
        key: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> &mut Self {
        self.bodys.insert(key.into(), value.into());
        self
    }

    /// Removes a global body field from the configuration.
    ///
    /// # Arguments
    ///
    /// * `key` - The body field name to remove
    ///
    /// # Returns
    ///
    /// An Option containing the removed body field value if it existed, or None otherwise
    pub fn remove_body(&mut self, key: &str) -> Option<serde_json::Value> {
        self.bodys.remove(key)
    }

    /// Sets the request timeout in seconds.
    ///
    /// This value determines the total time allowed for a request to complete,
    /// including DNS resolution, connection establishment, sending the request,
    /// and receiving the response.
    ///
    /// # 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.timeout_seconds = timeout_seconds;
        self
    }

    /// Sets the connection timeout in seconds.
    ///
    /// This value determines the maximum time allowed to establish a connection to the server.
    /// It is a subset of the overall request timeout.
    ///
    /// # 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.connect_timeout_seconds = connect_timeout_seconds;
        self
    }

    /// Sets the HTTP proxy URL.
    ///
    /// If set, all HTTP requests will be routed through this proxy server.
    /// Supported proxy schemes include HTTP, HTTPS, and SOCKS.
    ///
    /// # 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.proxy = Some(proxy.into());
        self
    }

    /// Sets the user agent string.
    ///
    /// If set, this value will be used as the User-Agent header for all requests.
    /// If not set, the default reqwest User-Agent will be used.
    ///
    /// # 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.user_agent = Some(user_agent.into());
        self
    }

    /// Builds a reqwest::Client instance based on this configuration.
    ///
    /// This method creates a new reqwest client with the configured timeouts,
    /// proxy, and user agent settings.
    ///
    /// # Returns
    ///
    /// A reqwest::Client instance configured according to this HttpConfig
    pub fn build_reqwest_client(&self) -> reqwest::Client {
        let mut client_builder = reqwest::ClientBuilder::new()
            .timeout(std::time::Duration::from_secs(self.timeout_seconds))
            .connect_timeout(std::time::Duration::from_secs(self.connect_timeout_seconds));

        if let Some(ref proxy_url) = self.proxy {
            if let Ok(proxy) = reqwest::Proxy::all(proxy_url) {
                client_builder = client_builder.proxy(proxy);
            }
        }

        if let Some(ref user_agent) = self.user_agent {
            client_builder = client_builder.user_agent(user_agent);
        }

        client_builder
            .build()
            .unwrap_or_else(|_| reqwest::Client::new())
    }
}

impl Default for HttpConfig {
    /// Returns the default HTTP configuration.
    ///
    /// The default configuration includes:
    /// - 300 second request timeout
    /// - 10 second connection timeout
    /// - No proxy
    /// - No custom user agent
    fn default() -> Self {
        Self {
            timeout_seconds: 300,
            connect_timeout_seconds: 10,
            proxy: None,
            user_agent: None,
            headers: HashMap::new(),
            querys: HashMap::new(),
            bodys: HashMap::new(),
        }
    }
}

impl HttpConfigBuilder {
    /// Adds a global header to the 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 {
        let headers_map = self.headers.get_or_insert_with(HashMap::new);
        headers_map.insert(key.into(), value.into());
        self
    }

    /// Adds a global query parameter to the 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 {
        let query_map = self.querys.get_or_insert_with(HashMap::new);
        query_map.insert(key.into(), value.into());
        self
    }

    /// Adds a global body field to the 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 {
        let body_map = self.bodys.get_or_insert_with(HashMap::new);
        body_map.insert(key.into(), value.into());
        self
    }
}