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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! This library is generated by [`openapi-client-generator`](https://crates.io/crates/openapi-client-generator).
//!
//! The [`OpenAiClient`] is the main entry point for this library.
#![allow(non_camel_case_types)]

use serde_json::json;
use httpclient::RequestBuilder;
pub mod model;
use crate::model::*;

pub struct OpenAiAuthentication {
    pub api_key: String,
}

impl OpenAiAuthentication {
    pub fn new(api_key: String) -> Self {
        Self { api_key }
    }

    pub fn from_env() -> Self {
        let api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set");
        Self::new(api_key)
    }
}

impl OpenAiClient {
    pub fn from_env() -> Self {
        Self::new("https://api.openai.com/v1")
            .with_authentication(OpenAiAuthentication::from_env())
    }
}

trait Authenticatable {
    fn authenticate(self, authenticator: &Option<OpenAiAuthentication>) -> Self;
}

impl<'a> Authenticatable for RequestBuilder<'a> {
    fn authenticate(self, authenticator: &Option<OpenAiAuthentication>) -> Self {
        if let Some(authenticator) = authenticator {
            self
                .header("Authorization", &format!("Bearer {}", authenticator.api_key))
        } else {
            self
        }
    }
}
pub struct OpenAiClient {
    client: httpclient::Client,
    authentication: Option<OpenAiAuthentication>,
}
impl OpenAiClient {
    pub fn new(url: &str) -> Self {
        let client = httpclient::Client::new(Some(url.to_string()));
        let authentication = None;
        Self { client, authentication }
    }
    pub fn with_authentication(mut self, authentication: OpenAiAuthentication) -> Self {
        self.authentication = Some(authentication);
        self
    }
    pub fn with_middleware<M: httpclient::Middleware + 'static>(
        mut self,
        middleware: M,
    ) -> Self {
        self.client = self.client.with_middleware(middleware);
        self
    }
    /**Lists the currently available engines, and provides basic information about each one such as the owner and availability.

See endpoint docs at <https://beta.openai.com/docs/api-reference/engines/list>.*/
    pub async fn list_engines(&self) -> anyhow::Result<ListEnginesResponse> {
        let res = self
            .client
            .get("/engines")
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Retrieves an engine instance, providing basic information about the engine such as the owner and availability.
    pub async fn retrieve_engine(&self, engine_id: String) -> anyhow::Result<Engine> {
        let res = self
            .client
            .get(&format!("/engines/{engine_id}"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Creates a new completion for the provided prompt and parameters
    pub async fn create_completion(
        &self,
        engine_id: String,
        prompt: Option<serde_json::Value>,
        suffix: Option<serde_json::Value>,
        max_tokens: Option<i64>,
        temperature: Option<f64>,
        top_p: Option<f64>,
        n: Option<i64>,
        stream: Option<bool>,
        logprobs: Option<i64>,
        echo: Option<bool>,
        stop: Option<serde_json::Value>,
        presence_penalty: Option<f64>,
        frequency_penalty: Option<f64>,
        best_of: Option<i64>,
        logit_bias: Option<serde_json::Value>,
        user: String,
    ) -> anyhow::Result<CreateCompletionResponse> {
        let res = self
            .client
            .post(&format!("/engines/{engine_id}/completions"))
            .json(
                json!(
                    { "prompt" : prompt, "suffix" : suffix, "max_tokens" : max_tokens,
                    "temperature" : temperature, "top_p" : top_p, "n" : n, "stream" :
                    stream, "logprobs" : logprobs, "echo" : echo, "stop" : stop,
                    "presence_penalty" : presence_penalty, "frequency_penalty" :
                    frequency_penalty, "best_of" : best_of, "logit_bias" : logit_bias,
                    "user" : user }
                ),
            )
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Creates a completion using a fine-tuned model
    pub async fn create_completion_from_model(
        &self,
    ) -> anyhow::Result<CreateCompletionResponse> {
        let res = self
            .client
            .post("/completions")
            .json(json!({}))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Creates a new edit for the provided input, instruction, and parameters
    pub async fn create_edit(
        &self,
        engine_id: String,
        input: Option<String>,
        instruction: String,
        temperature: Option<f64>,
        top_p: Option<f64>,
    ) -> anyhow::Result<CreateEditResponse> {
        let res = self
            .client
            .post(&format!("/engines/{engine_id}/edits"))
            .json(
                json!(
                    { "input" : input, "instruction" : instruction, "temperature" :
                    temperature, "top_p" : top_p }
                ),
            )
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them.

To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores.

The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query.
*/
    pub async fn create_search(
        &self,
        engine_id: String,
        query: String,
        documents: Option<Vec<String>>,
        file: Option<String>,
        max_rerank: Option<i64>,
        return_metadata: Option<bool>,
        user: String,
    ) -> anyhow::Result<CreateSearchResponse> {
        let res = self
            .client
            .post(&format!("/engines/{engine_id}/search"))
            .json(
                json!(
                    { "query" : query, "documents" : documents, "file" : file,
                    "max_rerank" : max_rerank, "return_metadata" : return_metadata,
                    "user" : user }
                ),
            )
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Returns a list of files that belong to the user's organization.
    pub async fn list_files(&self) -> anyhow::Result<ListFilesResponse> {
        let res = self
            .client
            .get("/files")
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit.
*/
    pub async fn create_file(&self) -> anyhow::Result<OpenAIFile> {
        let res = self
            .client
            .post("/files")
            .json(json!({}))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Returns information about a specific file.
    pub async fn retrieve_file(&self, file_id: String) -> anyhow::Result<OpenAIFile> {
        let res = self
            .client
            .get(&format!("/files/{file_id}"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Delete a file.
    pub async fn delete_file(
        &self,
        file_id: String,
    ) -> anyhow::Result<DeleteFileResponse> {
        let res = self
            .client
            .delete(&format!("/files/{file_id}"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Returns the contents of the specified file
    pub async fn download_file(&self, file_id: String) -> anyhow::Result<String> {
        let res = self
            .client
            .get(&format!("/files/{file_id}/content"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Answers the specified question using the provided documents and examples.

The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions).
*/
    pub async fn create_answer(
        &self,
        model: String,
        question: String,
        examples: Vec<Vec<String>>,
        examples_context: String,
        documents: Option<Vec<String>>,
        file: Option<String>,
        search_model: Option<String>,
        max_rerank: Option<i64>,
        temperature: Option<f64>,
        logprobs: Option<i64>,
        max_tokens: Option<i64>,
        stop: Option<serde_json::Value>,
        n: Option<i64>,
        logit_bias: Option<serde_json::Value>,
        return_metadata: Option<bool>,
        return_prompt: Option<bool>,
        expand: Option<Vec<serde_json::Value>>,
        user: String,
    ) -> anyhow::Result<CreateAnswerResponse> {
        let res = self
            .client
            .post("/answers")
            .json(
                json!(
                    { "model" : model, "question" : question, "examples" : examples,
                    "examples_context" : examples_context, "documents" : documents,
                    "file" : file, "search_model" : search_model, "max_rerank" :
                    max_rerank, "temperature" : temperature, "logprobs" : logprobs,
                    "max_tokens" : max_tokens, "stop" : stop, "n" : n, "logit_bias" :
                    logit_bias, "return_metadata" : return_metadata, "return_prompt" :
                    return_prompt, "expand" : expand, "user" : user }
                ),
            )
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Classifies the specified `query` using provided examples.

The endpoint first [searches](/docs/api-reference/searches) over the labeled examples
to select the ones most relevant for the particular query. Then, the relevant examples
are combined with the query to construct a prompt to produce the final label via the
[completions](/docs/api-reference/completions) endpoint.

Labeled examples can be provided via an uploaded `file`, or explicitly listed in the
request using the `examples` parameter for quick tests and small scale use cases.
*/
    pub async fn create_classification(
        &self,
        model: String,
        query: String,
        examples: Option<Vec<Vec<String>>>,
        file: Option<String>,
        labels: Option<Vec<String>>,
        search_model: Option<String>,
        temperature: Option<f64>,
        logprobs: Option<i64>,
        max_examples: Option<i64>,
        logit_bias: Option<serde_json::Value>,
        return_prompt: Option<bool>,
        return_metadata: Option<bool>,
        expand: Option<Vec<serde_json::Value>>,
        user: String,
    ) -> anyhow::Result<CreateClassificationResponse> {
        let res = self
            .client
            .post("/classifications")
            .json(
                json!(
                    { "model" : model, "query" : query, "examples" : examples, "file" :
                    file, "labels" : labels, "search_model" : search_model, "temperature"
                    : temperature, "logprobs" : logprobs, "max_examples" : max_examples,
                    "logit_bias" : logit_bias, "return_prompt" : return_prompt,
                    "return_metadata" : return_metadata, "expand" : expand, "user" : user
                    }
                ),
            )
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**List your organization's fine-tuning jobs
*/
    pub async fn list_fine_tunes(&self) -> anyhow::Result<ListFineTunesResponse> {
        let res = self
            .client
            .get("/fine-tunes")
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Creates a job that fine-tunes a specified model from a given dataset.

Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete.

[Learn more about Fine-tuning](/docs/guides/fine-tuning)
*/
    pub async fn create_fine_tune(
        &self,
        training_file: String,
        validation_file: Option<String>,
        model: Option<String>,
        n_epochs: Option<i64>,
        batch_size: Option<i64>,
        learning_rate_multiplier: Option<f64>,
        prompt_loss_weight: Option<f64>,
        compute_classification_metrics: Option<bool>,
        classification_n_classes: Option<i64>,
        classification_positive_class: Option<String>,
        classification_betas: Option<Vec<f64>>,
        suffix: Option<String>,
    ) -> anyhow::Result<FineTune> {
        let res = self
            .client
            .post("/fine-tunes")
            .json(
                json!(
                    { "training_file" : training_file, "validation_file" :
                    validation_file, "model" : model, "n_epochs" : n_epochs, "batch_size"
                    : batch_size, "learning_rate_multiplier" : learning_rate_multiplier,
                    "prompt_loss_weight" : prompt_loss_weight,
                    "compute_classification_metrics" : compute_classification_metrics,
                    "classification_n_classes" : classification_n_classes,
                    "classification_positive_class" : classification_positive_class,
                    "classification_betas" : classification_betas, "suffix" : suffix }
                ),
            )
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Gets info about the fine-tune job.

[Learn more about Fine-tuning](/docs/guides/fine-tuning)
*/
    pub async fn retrieve_fine_tune(
        &self,
        fine_tune_id: String,
    ) -> anyhow::Result<FineTune> {
        let res = self
            .client
            .get(&format!("/fine-tunes/{fine_tune_id}"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Immediately cancel a fine-tune job.
*/
    pub async fn cancel_fine_tune(
        &self,
        fine_tune_id: String,
    ) -> anyhow::Result<FineTune> {
        let res = self
            .client
            .post(&format!("/fine-tunes/{fine_tune_id}/cancel"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Get fine-grained status updates for a fine-tune job.
*/
    pub async fn list_fine_tune_events(
        &self,
        fine_tune_id: String,
        stream: bool,
    ) -> anyhow::Result<ListFineTuneEventsResponse> {
        let res = self
            .client
            .get(&format!("/fine-tunes/{fine_tune_id}/events"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    ///Delete a fine-tuned model. You must have the Owner role in your organization.
    pub async fn delete_model(
        &self,
        model: String,
    ) -> anyhow::Result<DeleteModelResponse> {
        let res = self
            .client
            .delete(&format!("/models/{model}"))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
    /**Creates an embedding vector representing the input text.
*/
    pub async fn create_embedding(
        &self,
        engine_id: String,
        input: serde_json::Value,
        user: String,
    ) -> anyhow::Result<CreateEmbeddingResponse> {
        let res = self
            .client
            .post(&format!("/engines/{engine_id}/embeddings"))
            .json(json!({ "input" : input, "user" : user }))
            .authenticate(&self.authentication)
            .send()
            .await
            .unwrap()
            .error_for_status();
        match res {
            Ok(res) => res.json().await.map_err(|e| anyhow::anyhow!("{:?}", e)),
            Err(res) => {
                let text = res.text().await.map_err(|e| anyhow::anyhow!("{:?}", e));
                Err(anyhow::anyhow!("{:?}", text))
            }
        }
    }
}