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
use crate::Config;
use crate::common::types::{Bodies, Headers, QueryParams};
use crate::interceptor::InterceptorChain;
use reqwest::{Method, RequestBuilder as ReqwestRequestBuilder};
use serde_json::Value;
use std::collections::HashMap;
use std::time::Duration;

/// Parameters for HTTP requests that encapsulate all necessary information
/// for making a request through the HTTP pipeline.
///
/// This structure holds the functions and configuration needed to build and execute
/// an HTTP request, including URL generation, request building, retry logic, and interceptors.
///
/// # Type Parameters
/// * `U` - A function type that takes a Config reference and returns a String (for URL generation)
/// * `F` - A function type that takes a Config reference and a mutable RequestBuilder reference
///
pub struct RequestSpec<U, F>
where
    U: FnOnce(&Config) -> String,
    F: FnOnce(&Config, &mut RequestBuilder),
{
    /// Function that generates the URL based on the provided configuration
    /// Takes a Config reference and returns the complete URL string for the request
    pub url_fn: U,
    /// Function that configures the RequestBuilder with specific parameters
    /// Takes the Config and a mutable reference to RequestBuilder to set up headers, body, etc.
    pub builder_fn: F,
    /// Number of times to retry the request in case of failure
    pub retry_count: u32,
    /// Optional interceptors specific to the calling module
    /// These interceptors will be applied in addition to any global interceptors
    pub module_interceptors: Option<InterceptorChain>,
}

impl<U, F> RequestSpec<U, F>
where
    U: FnOnce(&Config) -> String,
    F: FnOnce(&Config, &mut RequestBuilder),
{
    /// Creates a new HttpParams instance
    pub fn new(
        url_fn: U,
        builder_fn: F,
        retry_count: u32,
        module_interceptors: Option<InterceptorChain>,
    ) -> Self {
        Self {
            url_fn,
            builder_fn,
            retry_count,
            module_interceptors,
        }
    }

    /// Creates a new HttpParams instance with default retry count (0)
    pub fn new_with_defaults(url_fn: U, builder_fn: F) -> Self {
        Self {
            url_fn,
            builder_fn,
            retry_count: 0,
            module_interceptors: None,
        }
    }

    /// Sets the retry count
    pub fn with_retry_count(mut self, retry_count: u32) -> Self {
        self.retry_count = retry_count;
        self
    }

    /// Sets the module interceptors
    pub fn with_interceptors(mut self, interceptors: Option<InterceptorChain>) -> Self {
        self.module_interceptors = interceptors;
        self
    }
}

#[derive(Debug, Clone)]
/// Represents an HTTP request with all its components.
pub struct Request {
    /// The HTTP method for the request (GET, POST, PUT, DELETE, etc.)
    method: Method,
    /// The URL for the request
    url: String,
    /// Headers to be included in the request
    headers: Headers,
    /// Query parameters to be appended to the URL
    query_params: QueryParams,
    /// Optional body fields to be included in the request body
    body_fields: Option<Bodies>,
    /// Optional timeout for the request
    timeout: Option<Duration>,
}

impl Request {
    /// Gets a reference to the HTTP method of this request
    ///
    /// # Returns
    /// A reference to the Method enum representing the HTTP method (GET, POST, etc.)
    #[inline]
    pub fn method(&self) -> &Method {
        &self.method
    }

    /// Gets a reference to the URL of this request
    ///
    /// # Returns
    /// A string slice containing the request URL
    #[inline]
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Gets a reference to the headers of this request
    ///
    /// # Returns
    /// A reference to the HashMap containing request headers
    #[inline]
    pub fn headers(&self) -> &Headers {
        &self.headers
    }

    /// Gets a reference to the query parameters of this request
    ///
    /// # Returns
    /// A reference to the HashMap containing query parameters
    #[inline]
    pub fn query_params(&self) -> &QueryParams {
        &self.query_params
    }

    /// Gets a reference to the body fields of this request
    ///
    /// # Returns
    /// An Option containing a reference to the HashMap of body fields, or None if no body is set
    #[inline]
    pub fn body(&self) -> Option<&Bodies> {
        self.body_fields.as_ref()
    }

    /// Gets a mutable reference to the URL of this request
    ///
    /// # Returns
    /// A mutable reference to the URL string for modification
    #[inline]
    pub fn url_mut(&mut self) -> &mut String {
        &mut self.url
    }

    /// Gets a mutable reference to the headers of this request
    ///
    /// # Returns
    /// A mutable reference to the HashMap containing request headers
    #[inline]
    pub fn headers_mut(&mut self) -> &mut Headers {
        &mut self.headers
    }

    /// Gets a mutable reference to the query parameters of this request
    ///
    /// # Returns
    /// A mutable reference to the HashMap containing query parameters
    #[inline]
    pub fn query_params_mut(&mut self) -> &mut QueryParams {
        &mut self.query_params
    }

    /// Gets a mutable reference to the body fields of this request
    ///
    /// # Returns
    /// A mutable reference to the Option containing the HashMap of body fields
    #[inline]
    pub fn body_mut(&mut self) -> &mut Option<Bodies> {
        &mut self.body_fields
    }

    /// Gets a reference to the timeout duration of this request
    ///
    /// # Returns
    /// An Option containing a reference to the Duration if a timeout is set, or None
    #[inline]
    pub fn timeout(&self) -> Option<&Duration> {
        self.timeout.as_ref()
    }

    /// Gets a mutable reference to the timeout duration of this request
    ///
    /// # Returns
    /// A mutable reference to the Option containing the timeout Duration
    #[inline]
    pub fn timeout_mut(&mut self) -> &mut Option<Duration> {
        &mut self.timeout
    }

    /// Converts this Request to a reqwest::RequestBuilder
    ///
    /// This method creates a reqwest RequestBuilder from the current Request,
    /// applying all headers, body fields, and timeout settings.
    ///
    /// # Parameters
    /// * `client` - A reference to the reqwest client to use for building the request
    ///
    /// # Returns
    /// A new ReqwestRequestBuilder instance with all the properties from this Request
    pub fn to_reqwest(&self, client: &reqwest::Client) -> ReqwestRequestBuilder {
        let mut builder = client.request(self.method.clone(), &self.url);

        if !self.query_params.is_empty() {
            builder = builder.query(&self.query_params);
        }

        for (k, v) in &self.headers {
            builder = builder.header(k, v);
        }

        if let Some(body) = &self.body_fields {
            builder = builder.json(body);
        }

        if let Some(timeout_val) = self.timeout {
            builder = builder.timeout(timeout_val);
        }

        builder
    }
}

/// A builder for constructing HTTP requests with various components.
pub struct RequestBuilder {
    /// The underlying Request being built
    request: Request,
}

impl RequestBuilder {
    /// Creates a new RequestBuilder with the specified HTTP method and base URL.
    ///
    /// # Arguments
    ///
    /// * `method` - The HTTP method for the request (GET, POST, PUT, etc.)
    /// * `base_url` - The base URL for the request
    ///
    /// # Returns
    ///
    /// A new RequestBuilder instance initialized with the specified method and URL
    pub fn new(method: Method, base_url: &str) -> RequestBuilder {
        RequestBuilder {
            request: Request {
                method,
                url: base_url.to_string(),
                headers: HashMap::new(),
                query_params: HashMap::new(),
                body_fields: None,
                timeout: None,
            },
        }
    }

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

    /// Sets the Bearer authentication token.
    ///
    /// This adds an 'Authorization' header with the value 'Bearer {token}'.
    ///
    /// # Arguments
    ///
    /// * `token` - The authentication token
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn bearer_auth(&mut self, token: &str) -> &mut Self {
        self.request
            .headers_mut()
            .insert("Authorization".to_string(), format!("Bearer {}", token));
        self
    }

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

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

    /// Adds multiple fields to the request body.
    ///
    /// # Arguments
    ///
    /// * `fields` - A map of field names to values to add to the body
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn body_fields(&mut self, fields: Bodies) -> &mut Self {
        self.request
            .body_mut()
            .get_or_insert_with(HashMap::new)
            .extend(fields);
        self
    }

    /// Sets the entire request body as a map of fields.
    ///
    /// # Arguments
    ///
    /// * `body_map` - A map representing the complete request body
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn body_fields_map(&mut self, body_map: Bodies) -> &mut Self {
        *self.request.body_mut() = Some(body_map);
        self
    }

    /// Clears the request body.
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn without_body(&mut self) -> &mut Self {
        *self.request.body_mut() = None;
        self
    }

    /// Sets the timeout for the request.
    ///
    /// # Arguments
    ///
    /// * `timeout` - The timeout duration for the request
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
        *self.request.timeout_mut() = Some(timeout);
        self
    }

    /// Checks if a specific header exists in the request.
    ///
    /// # Arguments
    ///
    /// * `key` - The header name to check for
    ///
    /// # Returns
    ///
    /// true if the header exists, false otherwise
    #[inline]
    pub fn has_header(&self, key: &str) -> bool {
        self.request.headers().contains_key(key)
    }

    /// Checks if a specific query parameter exists in the request.
    ///
    /// # Arguments
    ///
    /// * `key` - The query parameter name to check for
    ///
    /// # Returns
    ///
    /// true if the query parameter exists, false otherwise
    #[inline]
    pub fn has_query(&self, key: &str) -> bool {
        self.request.query_params().contains_key(key)
    }

    /// Checks if a specific body field exists in the request.
    ///
    /// # Arguments
    ///
    /// * `key` - The body field name to check for
    ///
    /// # Returns
    ///
    /// true if the body field exists, false otherwise
    #[inline]
    pub fn has_body_field(&self, key: &str) -> bool {
        match self.request.body() {
            Some(body_fields) => body_fields.contains_key(key),
            None => false,
        }
    }

    /// Checks if any headers exist in the request.
    ///
    /// # Returns
    ///
    /// true if there are any headers, false otherwise
    #[inline]
    pub fn has_any_headers(&self) -> bool {
        !self.request.headers().is_empty()
    }

    /// Checks if any query parameters exist in the request.
    ///
    /// # Returns
    ///
    /// true if there are any query parameters, false otherwise
    #[inline]
    pub fn has_any_query_params(&self) -> bool {
        !self.request.query_params().is_empty()
    }

    /// Checks if any body fields exist in the request.
    ///
    /// # Returns
    ///
    /// true if there are any body fields, false otherwise
    #[inline]
    pub fn has_any_body_fields(&self) -> bool {
        match self.request.body() {
            Some(body_fields) => !body_fields.is_empty(),
            None => false,
        }
    }

    /// Builds the Request from the builder.
    ///
    /// This method finalizes the request by returning the internal Request instance.
    /// The actual HTTP request construction with query parameters happens when
    /// converting to reqwest::RequestBuilder via the to_reqwest method.
    ///
    /// # Returns
    ///
    /// The constructed Request instance
    pub fn build(self) -> Request {
        self.request
    }
}