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
pub mod models;
use std::{error::Error, sync::Arc};
use awc::Client;
use rustls::{ClientConfig, OwnedTrustAnchor, RootCertStore};
use self::models::{
audio::{TextResponse, TranscriptionParameters, TranslationParameters},
chat::{ChatParameters, ChatResponse},
completions::{CompletionParameters, CompletionResponse},
edits::{EditParameters, EditResponse},
embeddings::{EmbeddingParameters, EmbeddingResponse},
files::{DeleteResponse, FileData, FileList, FileUpload},
images::{ImageCreateParameters, ImageEditParameters, ImageResponse, ImageVariationParameters},
list_models::{Model, ModelList},
};
pub struct OpenAI {
pub token: String,
pub oia_org: String,
https_client: Client,
}
impl OpenAI {
/// The function creates a new instance of the OpenAI struct with the provided token and
/// organization, along with an HTTPS client.
///
/// Arguments:
///
/// * `token`: The `token` parameter is a string that represents the authentication token used to
/// access the OpenAI API. This token is typically provided by OpenAI when you sign up for their
/// services.
/// * `oia_org`: The `oia_org` parameter represents the OpenAI organization ID. It is used to
/// identify the organization associated with the API token being used.
///
/// Returns:
///
/// The `new` function returns an instance of the `OpenAI` struct.
pub fn new(token: String, oia_org: String) -> Self {
let https_client = Client::builder()
.connector(awc::Connector::new().rustls(Arc::new(Self::rustls_config())))
.finish();
OpenAI {
token,
oia_org,
https_client,
}
}
fn rustls_config() -> ClientConfig {
let mut root_store = RootCertStore::empty();
root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_store)
.with_no_client_auth()
}
/// The function `list_models` sends a GET request to the OpenAI API to retrieve a list of models
/// and returns the parsed response as a `ModelList` object.
///
/// Returns:
///
/// a Result object with the type ModelList.
pub async fn list_models(self) -> Result<ModelList, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/models");
let result = client
.get(url)
.bearer_auth(self.token)
.send()
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<ModelList>(&result).expect("Failed to parse model list"))
}
/// The function retrieves a model from the OpenAI API using an HTTPS client and returns the parsed
/// model response.
///
/// Arguments:
///
/// * `model`: The `model` parameter is a `String` that represents the name of the model you want to
/// retrieve. It is used to construct the URL for the API request.
///
/// Returns:
///
/// a Result object with the type Model as the Ok variant and Box<dyn Error> as the Err variant.
pub async fn retrive_model(self, model: String) -> Result<Model, Box<dyn Error>> {
let client = self.https_client;
let url = format!("https://api.openai.com/v1/models/{}", model);
let result = client
.get(url)
.bearer_auth(self.token)
.send()
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<Model>(&result).expect("Failed to parse model response"))
}
/// The function `create_chat_completions` sends a POST request to the OpenAI API to generate chat completions
/// based on the given parameters.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_chat_completions` function is of type
/// `ChatParameters`. It is an input parameter that contains the information required to
/// generate chat completions using the OpenAI API.
///
/// Returns:
///
/// a `Result` with a `ChatResponse` on success or a `Box<dyn Error>` on failure.
pub async fn create_chat_completions(
self,
parameters: ChatParameters,
) -> Result<ChatResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/chat/completions");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<ChatResponse>(&result).expect("Failed to parse chat response"))
}
/// The function `create_completions` sends a POST request to the OpenAI API to generate completions
/// based on the given parameters.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_completions` function is of type
/// `CompletionParameters`. It is an input parameter that contains the information required to
/// generate completions using the OpenAI API.
///
/// Returns:
///
/// a `Result` with a `CompletionResponse` on success or a `Box<dyn Error>` on failure.
pub async fn create_completions(
self,
parameters: CompletionParameters,
) -> Result<CompletionResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/completions");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<CompletionResponse>(&result)
.expect("Failed to parse completion response"))
}
/// The function `create_edit` sends a POST request to the OpenAI API to create or edit a completion
/// and returns the response.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_edit` function is of type
/// `EditParameters`. It is an input parameter that contains the necessary information for creating
/// an edit. The specific fields and their meanings depend on the implementation of the
/// `EditParameters` struct. You would need to refer to the definition
///
/// Returns:
///
/// a `Result` with the type `EditResponse` on success or a `Box<dyn Error>` on failure.
pub async fn create_edit(
self,
parameters: EditParameters,
) -> Result<EditResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/completions");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<EditResponse>(&result).expect("Failed to parse edit response"))
}
/// The `create_image` function sends a POST request to the OpenAI API to generate an image based on
/// the provided parameters.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_image` function is of type
/// `ImageCreateParameters`. It is an input parameter that contains the necessary information for
/// generating an image.
///
/// Returns:
///
/// The function `create_image` returns a `Result` enum with the success case containing an
/// `ImageResponse` and the error case containing a `Box<dyn Error>`.
pub async fn create_image(
self,
parameters: ImageCreateParameters,
) -> Result<ImageResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/images/generations");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<ImageResponse>(&result)
.expect("Failed to parse image response"))
}
/// The function `create_image_edit` sends a POST request to the OpenAI API to create an image edit,
/// using the provided parameters, and returns the resulting image response.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_image_edit` function is of type
/// `ImageEditParameters`. It is an input parameter that contains the necessary information for
/// creating an image edit.
///
/// Returns:
///
/// a Result type with the success variant containing an ImageResponse or the error variant
/// containing a Box<dyn Error>.
pub async fn create_image_edit(
self,
parameters: ImageEditParameters,
) -> Result<ImageResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/images/edits");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<ImageResponse>(&result)
.expect("Failed to parse image response"))
}
/// The function `create_image_variations` sends a POST request to the OpenAI API to create image
/// variations based on the provided parameters.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_image_variations` function is of type
/// `ImageVariationParameters`. It is an input parameter that contains the necessary information for
/// creating image variations.
///
/// Returns:
///
/// a Result object with the type ImageResponse.
pub async fn create_image_variations(
self,
parameters: ImageVariationParameters,
) -> Result<ImageResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/images/variations");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<ImageResponse>(&result)
.expect("Failed to parse image response"))
}
/// The function `create_embedding` sends a POST request to the OpenAI API to create an embedding,
/// using the provided parameters, and returns the resulting embedding response.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_embedding` function is of type
/// `EmbeddingParameters`. It is an input parameter that contains the necessary information for
/// creating an embedding.
///
/// Returns:
///
/// a Result type with the success variant containing an EmbeddingResponse or the error variant
/// containing a Box<dyn Error>.
pub async fn create_embedding(
self,
parameters: EmbeddingParameters,
) -> Result<EmbeddingResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/embeddings");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<EmbeddingResponse>(&result)
.expect("Failed to parse embedding response"))
}
/// The function `create_transcription` sends a POST request to the OpenAI API to create a transcription,
/// using the provided parameters, and returns the resulting transcription response.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_transcription` function is of type
/// `TranscriptionParameters`. It is an input parameter that contains the necessary information for
/// creating a transcription.
///
/// Returns:
///
/// a Result type with the success variant containing a TextResponse or the error variant
/// containing a Box<dyn Error>.
pub async fn create_transcription(
self,
parameters: TranscriptionParameters,
) -> Result<TextResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/audio/transcriptions");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<TextResponse>(&result).expect("Failed to parse text response"))
}
/// The function `create_translation` sends a POST request to the OpenAI API to create a translation,
/// using the provided parameters, and returns the resulting translation response.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `create_translation` function is of type
/// `TranslationParameters`. It is an input parameter that contains the necessary information for
/// creating a translation.
///
/// Returns:
///
/// a Result type with the success variant containing a TextResponse or the error variant
/// containing a Box<dyn Error>.
pub async fn create_translation(
self,
parameters: TranslationParameters,
) -> Result<TextResponse, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/audio/translations");
let result = client
.post(url)
.insert_header(("Content-Type", "application/json"))
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<TextResponse>(&result).expect("Failed to parse text response"))
}
/// The function `list_files` makes an asynchronous HTTP GET request to the OpenAI API to retrieve a
/// list of files and returns the parsed result.
///
/// Returns:
///
/// The function `list_files` returns a `Result` containing either a `FileList` or a boxed dynamic
/// error (`Box<dyn Error>`).
pub async fn list_files(self) -> Result<FileList, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/files");
let result = client
.get(url)
.bearer_auth(self.token)
.send()
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<FileList>(&result).expect("Failed to parse file list"))
}
/// The `upload_files` function in Rust uploads files to the OpenAI API and returns the file data.
///
/// Arguments:
///
/// * `parameters`: The `parameters` parameter in the `upload_files` function is of type
/// `FileUpload`. It represents the data that needs to be uploaded to the server. The `FileUpload`
/// struct should contain the necessary information for the file upload, such as the file content,
/// file name, and file type
///
/// Returns:
///
/// The function `upload_files` returns a `Result` containing either a `FileData` object or an error
/// (`Box<dyn Error>`).
pub async fn upload_files(self, parameters: FileUpload) -> Result<FileData, Box<dyn Error>> {
let client = self.https_client;
let url = String::from("https://api.openai.com/v1/files");
let result = client
.post(url)
.bearer_auth(self.token)
.send_json(¶meters)
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<FileData>(&result).expect("Failed to parse file data"))
}
/// The function `delete_file` is an asynchronous function in Rust that sends a DELETE request to the
/// OpenAI API to delete a file.
///
/// Arguments:
///
/// * `file_id`: The `file_id` parameter is a string that represents the unique identifier of the
/// file you want to delete. It is used to construct the URL for the DELETE request to the OpenAI
/// API.
///
/// Returns:
///
/// The function `delete_file` returns a `Result` containing either a `DeleteResponse` or a boxed
/// dynamic error (`Box<dyn Error>`).
pub async fn delete_file(self, file_id: String) -> Result<DeleteResponse, Box<dyn Error>> {
let client = self.https_client;
let url = format!("https://api.openai.com/v1/files/{}", file_id);
let result = client
.delete(url)
.bearer_auth(self.token)
.send()
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<DeleteResponse>(&result)
.expect("Failed to parse delete response"))
}
/// The `retrieve_file` function retrieves file data from the OpenAI API using the provided file ID.
///
/// Arguments:
///
/// * `file_id`: The `file_id` parameter is a unique identifier for the file you want to retrieve.
/// It is used to construct the URL for the API request to retrieve the file data.
///
/// Returns:
///
/// The function `retrieve_file` returns a `Result` containing either a `FileData` object or an
/// error (`Box<dyn Error>`).
pub async fn retrieve_file(self, file_id: String) -> Result<FileData, Box<dyn Error>> {
let client = self.https_client;
let url = format!("https://api.openai.com/v1/files/{}", file_id);
let result = client
.get(url)
.bearer_auth(self.token)
.send()
.await
.unwrap()
.body()
.await
.unwrap();
Ok(serde_json::from_slice::<FileData>(&result).expect("Failed to parse file data"))
}
/// The function `retrieve_file_content` retrieves the content of a file from the OpenAI API using a
/// provided file ID.
///
/// Arguments:
///
/// * `file_id`: The `file_id` parameter is a unique identifier for the file you want to retrieve
/// the content of. It is used to construct the URL for the API request to fetch the file content.
///
/// Returns:
///
/// The function `retrieve_file_content` returns a `Result` containing a `String` representing the
/// content of the file with the given `file_id`. The `Ok` variant of the `Result` contains the file
/// content as a `String`, while the `Err` variant contains a boxed dynamic error (`Box<dyn
/// Error>`).
pub async fn retrieve_file_content(self, file_id: String) -> Result<String, Box<dyn Error>> {
let client = self.https_client;
let url = format!("https://api.openai.com/v1/files/{}/content", file_id);
let result = client
.get(url)
.bearer_auth(self.token)
.send()
.await
.unwrap()
.body()
.await
.unwrap();
Ok(String::from_utf8(result.to_vec()).expect("Failed to parse file content"))
}
}