openai/
lib.rs

1//! [`OpenAiClient`](struct.OpenAiClient.html) is the main entry point for this library.
2//!
3//! Library created with [`libninja`](https://www.libninja.com).
4#![allow(non_camel_case_types)]
5#![allow(unused)]
6pub mod model;
7pub mod request;
8use crate::model::*;
9pub struct OpenAiClient {
10    pub client: httpclient::Client,
11    authentication: OpenAiAuthentication,
12}
13impl OpenAiClient {
14    pub fn from_env() -> Self {
15        Self {
16            client: httpclient::Client::new().base_url("https://api.openai.com/v1"),
17            authentication: OpenAiAuthentication::from_env(),
18        }
19    }
20}
21impl OpenAiClient {
22    pub fn new(url: &str, authentication: OpenAiAuthentication) -> Self {
23        let client = httpclient::Client::new().base_url(url);
24        Self { client, authentication }
25    }
26    pub fn with_authentication(mut self, authentication: OpenAiAuthentication) -> Self {
27        self.authentication = authentication;
28        self
29    }
30    pub(crate) fn authenticate<'a>(
31        &self,
32        mut r: httpclient::RequestBuilder<'a>,
33    ) -> httpclient::RequestBuilder<'a> {
34        match &self.authentication {
35            OpenAiAuthentication::Bearer { bearer } => {
36                r = r.bearer_auth(bearer);
37            }
38        }
39        r
40    }
41    pub fn with_middleware<M: httpclient::Middleware + 'static>(
42        mut self,
43        middleware: M,
44    ) -> Self {
45        self.client = self.client.with_middleware(middleware);
46        self
47    }
48    ///Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability.
49    pub fn list_engines(&self) -> request::ListEnginesRequest {
50        request::ListEnginesRequest {
51            http_client: &self,
52        }
53    }
54    ///Retrieves a model instance, providing basic information about it such as the owner and availability.
55    pub fn retrieve_engine(&self, engine_id: &str) -> request::RetrieveEngineRequest {
56        request::RetrieveEngineRequest {
57            http_client: &self,
58            engine_id: engine_id.to_owned(),
59        }
60    }
61    ///Creates a completion for the provided prompt and parameters
62    pub fn create_completion(&self, model: &str) -> request::CreateCompletionRequest {
63        request::CreateCompletionRequest {
64            http_client: &self,
65            best_of: None,
66            echo: None,
67            frequency_penalty: None,
68            logit_bias: None,
69            logprobs: None,
70            max_tokens: None,
71            model: model.to_owned(),
72            n: None,
73            presence_penalty: None,
74            prompt: None,
75            stop: None,
76            stream: None,
77            suffix: None,
78            temperature: None,
79            top_p: None,
80            user: None,
81        }
82    }
83    ///Creates a completion for the chat message
84    pub fn create_chat_completion(
85        &self,
86        messages: Vec<ChatCompletionRequestMessage>,
87        model: &str,
88    ) -> request::CreateChatCompletionRequest {
89        request::CreateChatCompletionRequest {
90            http_client: &self,
91            frequency_penalty: None,
92            logit_bias: None,
93            max_tokens: None,
94            messages,
95            model: model.to_owned(),
96            n: None,
97            presence_penalty: None,
98            stop: None,
99            stream: None,
100            temperature: None,
101            top_p: None,
102            user: None,
103        }
104    }
105    ///Creates a new edit for the provided input, instruction, and parameters.
106    pub fn create_edit(
107        &self,
108        instruction: &str,
109        model: &str,
110    ) -> request::CreateEditRequest {
111        request::CreateEditRequest {
112            http_client: &self,
113            input: None,
114            instruction: instruction.to_owned(),
115            model: model.to_owned(),
116            n: None,
117            temperature: None,
118            top_p: None,
119        }
120    }
121    ///Creates an image given a prompt.
122    pub fn create_image(&self, prompt: &str) -> request::CreateImageRequest {
123        request::CreateImageRequest {
124            http_client: &self,
125            n: None,
126            prompt: prompt.to_owned(),
127            response_format: None,
128            size: None,
129            user: None,
130        }
131    }
132    ///Creates an edited or extended image given an original image and a prompt.
133    pub fn create_image_edit(&self) -> request::CreateImageEditRequest {
134        request::CreateImageEditRequest {
135            http_client: &self,
136        }
137    }
138    ///Creates a variation of a given image.
139    pub fn create_image_variation(&self) -> request::CreateImageVariationRequest {
140        request::CreateImageVariationRequest {
141            http_client: &self,
142        }
143    }
144    ///Creates an embedding vector representing the input text.
145    pub fn create_embedding(
146        &self,
147        input: serde_json::Value,
148        model: &str,
149    ) -> request::CreateEmbeddingRequest {
150        request::CreateEmbeddingRequest {
151            http_client: &self,
152            input,
153            model: model.to_owned(),
154            user: None,
155        }
156    }
157    ///Transcribes audio into the input language.
158    pub fn create_transcription(&self) -> request::CreateTranscriptionRequest {
159        request::CreateTranscriptionRequest {
160            http_client: &self,
161        }
162    }
163    ///Translates audio into into English.
164    pub fn create_translation(&self) -> request::CreateTranslationRequest {
165        request::CreateTranslationRequest {
166            http_client: &self,
167        }
168    }
169    /**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.
170
171To 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.
172
173The 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.
174*/
175    pub fn create_search(
176        &self,
177        engine_id: &str,
178        query: &str,
179    ) -> request::CreateSearchRequest {
180        request::CreateSearchRequest {
181            http_client: &self,
182            documents: None,
183            engine_id: engine_id.to_owned(),
184            file: None,
185            max_rerank: None,
186            query: query.to_owned(),
187            return_metadata: None,
188            user: None,
189        }
190    }
191    ///Returns a list of files that belong to the user's organization.
192    pub fn list_files(&self) -> request::ListFilesRequest {
193        request::ListFilesRequest {
194            http_client: &self,
195        }
196    }
197    /**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.
198*/
199    pub fn create_file(&self) -> request::CreateFileRequest {
200        request::CreateFileRequest {
201            http_client: &self,
202        }
203    }
204    ///Returns information about a specific file.
205    pub fn retrieve_file(&self, file_id: &str) -> request::RetrieveFileRequest {
206        request::RetrieveFileRequest {
207            http_client: &self,
208            file_id: file_id.to_owned(),
209        }
210    }
211    ///Delete a file.
212    pub fn delete_file(&self, file_id: &str) -> request::DeleteFileRequest {
213        request::DeleteFileRequest {
214            http_client: &self,
215            file_id: file_id.to_owned(),
216        }
217    }
218    ///Returns the contents of the specified file
219    pub fn download_file(&self, file_id: &str) -> request::DownloadFileRequest {
220        request::DownloadFileRequest {
221            http_client: &self,
222            file_id: file_id.to_owned(),
223        }
224    }
225    /**Answers the specified question using the provided documents and examples.
226
227The 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).
228*/
229    pub fn create_answer(
230        &self,
231        args: request::CreateAnswerRequired,
232    ) -> request::CreateAnswerRequest {
233        request::CreateAnswerRequest {
234            http_client: &self,
235            documents: None,
236            examples: args.examples
237                .into_iter()
238                .map(|&x| x
239                    .into_iter()
240                    .map(|&x| x.to_owned())
241                    .collect()
242                )
243                .collect(),
244            examples_context: args.examples_context.to_owned(),
245            expand: None,
246            file: None,
247            logit_bias: None,
248            logprobs: None,
249            max_rerank: None,
250            max_tokens: None,
251            model: args.model.to_owned(),
252            n: None,
253            question: args.question.to_owned(),
254            return_metadata: None,
255            return_prompt: None,
256            search_model: None,
257            stop: None,
258            temperature: None,
259            user: None,
260        }
261    }
262    /**Classifies the specified `query` using provided examples.
263
264The endpoint first [searches](/docs/api-reference/searches) over the labeled examples
265to select the ones most relevant for the particular query. Then, the relevant examples
266are combined with the query to construct a prompt to produce the final label via the
267[completions](/docs/api-reference/completions) endpoint.
268
269Labeled examples can be provided via an uploaded `file`, or explicitly listed in the
270request using the `examples` parameter for quick tests and small scale use cases.
271*/
272    pub fn create_classification(
273        &self,
274        model: &str,
275        query: &str,
276    ) -> request::CreateClassificationRequest {
277        request::CreateClassificationRequest {
278            http_client: &self,
279            examples: None,
280            expand: None,
281            file: None,
282            labels: None,
283            logit_bias: None,
284            logprobs: None,
285            max_examples: None,
286            model: model.to_owned(),
287            query: query.to_owned(),
288            return_metadata: None,
289            return_prompt: None,
290            search_model: None,
291            temperature: None,
292            user: None,
293        }
294    }
295    /**List your organization's fine-tuning jobs
296*/
297    pub fn list_fine_tunes(&self) -> request::ListFineTunesRequest {
298        request::ListFineTunesRequest {
299            http_client: &self,
300        }
301    }
302    /**Creates a job that fine-tunes a specified model from a given dataset.
303
304Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete.
305
306[Learn more about Fine-tuning](/docs/guides/fine-tuning)
307*/
308    pub fn create_fine_tune(
309        &self,
310        training_file: &str,
311    ) -> request::CreateFineTuneRequest {
312        request::CreateFineTuneRequest {
313            http_client: &self,
314            batch_size: None,
315            classification_betas: None,
316            classification_n_classes: None,
317            classification_positive_class: None,
318            compute_classification_metrics: None,
319            learning_rate_multiplier: None,
320            model: None,
321            n_epochs: None,
322            prompt_loss_weight: None,
323            suffix: None,
324            training_file: training_file.to_owned(),
325            validation_file: None,
326        }
327    }
328    /**Gets info about the fine-tune job.
329
330[Learn more about Fine-tuning](/docs/guides/fine-tuning)
331*/
332    pub fn retrieve_fine_tune(
333        &self,
334        fine_tune_id: &str,
335    ) -> request::RetrieveFineTuneRequest {
336        request::RetrieveFineTuneRequest {
337            http_client: &self,
338            fine_tune_id: fine_tune_id.to_owned(),
339        }
340    }
341    /**Immediately cancel a fine-tune job.
342*/
343    pub fn cancel_fine_tune(
344        &self,
345        fine_tune_id: &str,
346    ) -> request::CancelFineTuneRequest {
347        request::CancelFineTuneRequest {
348            http_client: &self,
349            fine_tune_id: fine_tune_id.to_owned(),
350        }
351    }
352    /**Get fine-grained status updates for a fine-tune job.
353*/
354    pub fn list_fine_tune_events(
355        &self,
356        fine_tune_id: &str,
357    ) -> request::ListFineTuneEventsRequest {
358        request::ListFineTuneEventsRequest {
359            http_client: &self,
360            fine_tune_id: fine_tune_id.to_owned(),
361            stream: None,
362        }
363    }
364    ///Lists the currently available models, and provides basic information about each one such as the owner and availability.
365    pub fn list_models(&self) -> request::ListModelsRequest {
366        request::ListModelsRequest {
367            http_client: &self,
368        }
369    }
370    ///Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
371    pub fn retrieve_model(&self, model: &str) -> request::RetrieveModelRequest {
372        request::RetrieveModelRequest {
373            http_client: &self,
374            model: model.to_owned(),
375        }
376    }
377    ///Delete a fine-tuned model. You must have the Owner role in your organization.
378    pub fn delete_model(&self, model: &str) -> request::DeleteModelRequest {
379        request::DeleteModelRequest {
380            http_client: &self,
381            model: model.to_owned(),
382        }
383    }
384    ///Classifies if text violates OpenAI's Content Policy
385    pub fn create_moderation(
386        &self,
387        input: serde_json::Value,
388    ) -> request::CreateModerationRequest {
389        request::CreateModerationRequest {
390            http_client: &self,
391            input,
392            model: None,
393        }
394    }
395}
396pub enum OpenAiAuthentication {
397    Bearer { bearer: String },
398}
399impl OpenAiAuthentication {
400    pub fn from_env() -> Self {
401        Self::Bearer {
402            bearer: std::env::var("OPENAI_API_KEY")
403                .expect("Environment variable OPENAI_API_KEY is not set."),
404        }
405    }
406}