├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples ├── chatloop.rs └── story.rs └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | push: 4 | branches: 5 | - main 6 | 7 | name: CI 8 | 9 | jobs: 10 | check: 11 | name: Check 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions-rs/toolchain@v1 16 | with: 17 | profile: minimal 18 | toolchain: stable 19 | override: true 20 | - uses: actions-rs/cargo@v1 21 | with: 22 | command: check 23 | - uses: actions-rs/cargo@v1 24 | with: 25 | command: check 26 | args: --features=sync --no-default-features 27 | - uses: actions-rs/cargo@v1 28 | with: 29 | command: check 30 | args: --features=async --no-default-features 31 | 32 | test: 33 | name: Test Suite 34 | runs-on: ubuntu-latest 35 | steps: 36 | - uses: actions/checkout@v2 37 | - uses: actions-rs/toolchain@v1 38 | with: 39 | profile: minimal 40 | toolchain: stable 41 | override: true 42 | - uses: actions-rs/cargo@v1 43 | with: 44 | command: test 45 | args: unit 46 | 47 | fmt: 48 | name: Rustfmt 49 | runs-on: ubuntu-latest 50 | steps: 51 | - uses: actions/checkout@v2 52 | - uses: actions-rs/toolchain@v1 53 | with: 54 | profile: minimal 55 | toolchain: stable 56 | override: true 57 | - run: rustup component add rustfmt 58 | - uses: actions-rs/cargo@v1 59 | with: 60 | command: fmt 61 | args: --all -- --check 62 | 63 | clippy: 64 | name: Clippy 65 | runs-on: ubuntu-latest 66 | steps: 67 | - uses: actions/checkout@v2 68 | - uses: actions-rs/toolchain@v1 69 | with: 70 | profile: minimal 71 | toolchain: stable 72 | override: true 73 | - run: rustup component add clippy 74 | - uses: actions-rs/cargo@v1 75 | with: 76 | command: clippy 77 | args: -- -D warnings 78 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # will have compiled files and executables 2 | /target/ 3 | 4 | Cargo.lock 5 | 6 | # These are backup files generated by rustfmt 7 | **/*.rs.bk 8 | .vscode/ 9 | Notes.md 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "openai-api" 3 | version = "0.1.5-alpha.0" 4 | authors = ["Josh Kuhn "] 5 | license-file = "LICENSE" 6 | edition = "2018" 7 | description = "OpenAI API library for rust" 8 | homepage = "https://github.com/deontologician/openai-api-rust/" 9 | repository = "https://github.com/deontologician/openai-api-rust/" 10 | keywords = ["openai", "gpt3"] 11 | categories = ["api-bindings", "asynchronous"] 12 | 13 | [build] 14 | rustdocflags = ["--all-features"] 15 | 16 | [features] 17 | default = ["sync", "async"] 18 | sync = ["ureq"] 19 | async = ["surf/hyper-client"] 20 | 21 | [dependencies] 22 | thiserror = "^1.0.22" 23 | serde = { version = "^1.0.117", features = ["derive"] } 24 | derive_builder = "^0.9.0" 25 | log = "^0.4.11" 26 | 27 | # Used by sync feature 28 | ureq = { version = "^1.5.4", optional=true, features = ["json", "tls"] } 29 | serde_json = { version="^1.0"} 30 | # Used by async feature 31 | surf = { version = "^2.1.0", optional=true, default-features=false} 32 | 33 | [dev-dependencies] 34 | mockito = "0.28.0" 35 | maplit = "1.0.2" 36 | tokio = { version = "^0.2.5", features = ["full"]} 37 | env_logger = "0.8.2" 38 | serde_json = "^1.0" 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # openai-api-rust 2 | ![docs](https://docs.rs/openai-api/badge.svg) 3 | [![Crates.io](https://img.shields.io/crates/v/openai-api.svg)](https://crates.io/crates/openai-api) 4 | ![build](https://github.com/deontologician/openai-api-rust/workflows/Continuous%20Integration/badge.svg) 5 | 6 | A simple rust client for OpenAI API. 7 | 8 | Has a few conveniences, but is mostly at the level of the API itself. 9 | 10 | # Installation 11 | 12 | ``` 13 | $ cargo add openai-api 14 | ``` 15 | 16 | # Quickstart 17 | 18 | ```rust 19 | #[tokio::main] 20 | async fn main() -> Result<(), Box> { 21 | let api_token = std::env::var("OPENAI_SK")?; 22 | let client = openai_api::Client::new(&api_token); 23 | let prompt = String::from("Once upon a time,"); 24 | println!( 25 | "{}{}", 26 | prompt, 27 | client.complete(prompt.as_str()).await? 28 | ); 29 | Ok(()) 30 | } 31 | ``` 32 | # Basic Usage 33 | 34 | ## Creating a completion 35 | 36 | For simple demos and debugging, you can do a completion and use the `Display` instance of a `Completion` object to convert it to a string: 37 | 38 | ```rust 39 | let response = client.complete_prompt("Once upon a time").await?; 40 | println!("{}", response); 41 | ``` 42 | 43 | To configure the prompt more explicitly, you can use the `CompletionArgs` builder: 44 | 45 | ```rust 46 | let args = openai_api::api::CompletionArgs::builder() 47 | .prompt("Once upon a time,") 48 | .engine("text-davinci-003") 49 | .max_tokens(20) 50 | .temperature(0.7) 51 | .top_p(0.9) 52 | .stop(vec!["\n".into()]); 53 | let completion = client.complete_prompt(args).await?; 54 | println!("Response: {}", response.choices[0].text); 55 | println!("Model used: {}", response.model); 56 | ``` 57 | 58 | See [examples/](./examples) 59 | -------------------------------------------------------------------------------- /examples/chatloop.rs: -------------------------------------------------------------------------------- 1 | use openai_api::{api::CompletionArgs, Client}; 2 | 3 | const START_PROMPT: &str = " 4 | The following is a conversation with an AI assistant. 5 | The assistant is helpful, creative, clever, and very friendly. 6 | Human: Hello, who are you? 7 | AI: I am an AI. How can I help you today?"; 8 | #[tokio::main] 9 | async fn main() -> Result<(), Box> { 10 | let api_token = std::env::var("OPENAI_SK")?; 11 | let client = Client::new(&api_token); 12 | let mut context = String::from(START_PROMPT); 13 | let args = CompletionArgs::builder() 14 | .engine("davinci") 15 | .max_tokens(45) 16 | .stop(vec!["\n".into()]) 17 | .top_p(0.5) 18 | .temperature(0.9) 19 | .frequency_penalty(0.5); 20 | println!("\x1b[1;36m{}\x1b[1;0m", context.split('\n').last().unwrap()); 21 | loop { 22 | context.push_str("\nHuman: "); 23 | if let Err(e) = std::io::stdin().read_line(&mut context) { 24 | eprintln!("Error: {}", e); 25 | break; 26 | } 27 | context.push_str("\nAI: "); 28 | match client 29 | .complete_prompt(args.prompt(context.as_str()).build()?) 30 | .await 31 | { 32 | Ok(completion) => { 33 | println!("\x1b[1;36m{}\x1b[1;0m", completion); 34 | context.push_str(&completion.choices[0].text); 35 | } 36 | Err(e) => { 37 | eprintln!("Error: {}", e); 38 | break; 39 | } 40 | } 41 | } 42 | println!("Full conversation:\n{}", context); 43 | Ok(()) 44 | } 45 | -------------------------------------------------------------------------------- /examples/story.rs: -------------------------------------------------------------------------------- 1 | ///! Example that prints out a story from a prompt. Used in the readme. 2 | use openai_api::Client; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | let api_token = std::env::var("OPENAI_SK").unwrap(); 7 | let client = Client::new(&api_token); 8 | let prompt = String::from("Once upon a time,"); 9 | println!( 10 | "{}{}", 11 | prompt, 12 | client.complete_prompt(prompt.as_str()).await.unwrap() 13 | ); 14 | } 15 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /// `OpenAI` API client library 2 | #[macro_use] 3 | extern crate derive_builder; 4 | 5 | use thiserror::Error; 6 | 7 | type Result = std::result::Result; 8 | 9 | #[allow(clippy::default_trait_access)] 10 | pub mod api { 11 | //! Data types corresponding to requests and responses from the API 12 | use std::{collections::HashMap, convert::TryFrom, fmt::Display}; 13 | 14 | use serde::{Deserialize, Serialize}; 15 | 16 | /// Container type. Used in the api, but not useful for clients of this library 17 | #[derive(Deserialize, Debug)] 18 | pub(crate) struct Container { 19 | /// Items in the page's results 20 | pub data: Vec, 21 | } 22 | 23 | /// Detailed information on a particular engine. 24 | #[derive(Deserialize, Debug, Eq, PartialEq, Clone)] 25 | pub struct EngineInfo { 26 | /// The name of the engine, e.g. `"davinci"` or `"ada"` 27 | pub id: String, 28 | /// The owner of the model. Usually (always?) `"openai"` 29 | pub owner: String, 30 | /// Whether the model is ready for use. Usually (always?) `true` 31 | pub ready: bool, 32 | } 33 | 34 | /// Options for the query completion 35 | #[derive(Serialize, Debug, Builder, Clone)] 36 | #[builder(pattern = "immutable")] 37 | pub struct CompletionArgs { 38 | /// The id of the engine to use for this request 39 | /// 40 | /// # Example 41 | /// ``` 42 | /// # use openai_api::api::CompletionArgs; 43 | /// CompletionArgs::builder().engine("davinci"); 44 | /// ``` 45 | #[builder(setter(into), default = "\"davinci\".into()")] 46 | #[serde(skip_serializing)] 47 | pub(super) engine: String, 48 | /// The prompt to complete from. 49 | /// 50 | /// Defaults to `"<|endoftext|>"` which is a special token seen during training. 51 | /// 52 | /// # Example 53 | /// ``` 54 | /// # use openai_api::api::CompletionArgs; 55 | /// CompletionArgs::builder().prompt("Once upon a time..."); 56 | /// ``` 57 | #[builder(setter(into), default = "\"<|endoftext|>\".into()")] 58 | prompt: String, 59 | /// Maximum number of tokens to complete. 60 | /// 61 | /// Defaults to 16 62 | /// # Example 63 | /// ``` 64 | /// # use openai_api::api::CompletionArgs; 65 | /// CompletionArgs::builder().max_tokens(64); 66 | /// ``` 67 | #[builder(default = "16")] 68 | max_tokens: u64, 69 | /// What sampling temperature to use. 70 | /// 71 | /// Default is `1.0` 72 | /// 73 | /// Higher values means the model will take more risks. 74 | /// Try 0.9 for more creative applications, and 0 (argmax sampling) 75 | /// for ones with a well-defined answer. 76 | /// 77 | /// OpenAI recommends altering this or top_p but not both. 78 | /// 79 | /// # Example 80 | /// ``` 81 | /// # use openai_api::api::{CompletionArgs, CompletionArgsBuilder}; 82 | /// # use std::convert::{TryInto, TryFrom}; 83 | /// # fn main() -> Result<(), String> { 84 | /// let builder = CompletionArgs::builder().temperature(0.7); 85 | /// let args: CompletionArgs = builder.try_into()?; 86 | /// # Ok::<(), String>(()) 87 | /// # } 88 | /// ``` 89 | #[builder(default = "1.0")] 90 | temperature: f64, 91 | #[builder(default = "1.0")] 92 | top_p: f64, 93 | #[builder(default = "1")] 94 | n: u64, 95 | #[builder(setter(strip_option), default)] 96 | logprobs: Option, 97 | #[builder(default = "false")] 98 | echo: bool, 99 | #[builder(setter(strip_option), default)] 100 | stop: Option>, 101 | #[builder(default = "0.0")] 102 | presence_penalty: f64, 103 | #[builder(default = "0.0")] 104 | frequency_penalty: f64, 105 | #[builder(default)] 106 | logit_bias: HashMap, 107 | } 108 | 109 | // TODO: add validators for the different arguments 110 | 111 | impl From<&str> for CompletionArgs { 112 | fn from(prompt_string: &str) -> Self { 113 | Self { 114 | prompt: prompt_string.into(), 115 | ..CompletionArgsBuilder::default() 116 | .build() 117 | .expect("default should build") 118 | } 119 | } 120 | } 121 | 122 | impl CompletionArgs { 123 | /// Build a `CompletionArgs` from the defaults 124 | #[must_use] 125 | pub fn builder() -> CompletionArgsBuilder { 126 | CompletionArgsBuilder::default() 127 | } 128 | } 129 | 130 | impl TryFrom for CompletionArgs { 131 | type Error = String; 132 | 133 | fn try_from(builder: CompletionArgsBuilder) -> Result { 134 | builder.build() 135 | } 136 | } 137 | 138 | /// Represents a non-streamed completion response 139 | #[derive(Deserialize, Debug, Clone)] 140 | pub struct Completion { 141 | /// Completion unique identifier 142 | pub id: String, 143 | /// Unix timestamp when the completion was generated 144 | pub created: u64, 145 | /// Exact model type and version used for the completion 146 | pub model: String, 147 | /// List of completions generated by the model 148 | pub choices: Vec, 149 | } 150 | 151 | impl std::fmt::Display for Completion { 152 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 153 | write!(f, "{}", self.choices[0]) 154 | } 155 | } 156 | 157 | /// A single completion result 158 | #[derive(Deserialize, Debug, Clone)] 159 | pub struct Choice { 160 | /// The text of the completion. Will contain the prompt if echo is True. 161 | pub text: String, 162 | /// Offset in the result where the completion began. Useful if using echo. 163 | pub index: u64, 164 | /// If requested, the log probabilities of the completion tokens 165 | pub logprobs: Option, 166 | /// Why the completion ended when it did 167 | pub finish_reason: String, 168 | } 169 | 170 | impl std::fmt::Display for Choice { 171 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 172 | self.text.fmt(f) 173 | } 174 | } 175 | 176 | /// Represents a logprobs subdocument 177 | #[derive(Deserialize, Debug, Clone)] 178 | pub struct LogProbs { 179 | pub tokens: Vec, 180 | pub token_logprobs: Vec>, 181 | pub top_logprobs: Vec>>, 182 | pub text_offset: Vec, 183 | } 184 | 185 | /// Error response object from the server 186 | #[derive(Deserialize, Debug, Eq, PartialEq, Clone)] 187 | pub struct ErrorMessage { 188 | pub message: String, 189 | #[serde(rename = "type")] 190 | pub error_type: String, 191 | } 192 | 193 | impl Display for ErrorMessage { 194 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 195 | self.message.fmt(f) 196 | } 197 | } 198 | 199 | /// API-level wrapper used in deserialization 200 | #[derive(Deserialize, Debug)] 201 | pub(crate) struct ErrorWrapper { 202 | pub error: ErrorMessage, 203 | } 204 | } 205 | 206 | /// This library's main `Error` type. 207 | #[derive(Error, Debug)] 208 | pub enum Error { 209 | /// An error returned by the API itself 210 | #[error("API returned an Error: {}", .0.message)] 211 | Api(api::ErrorMessage), 212 | /// An error the client discovers before talking to the API 213 | #[error("Bad arguments: {0}")] 214 | BadArguments(String), 215 | /// Network / protocol related errors 216 | #[cfg(feature = "async")] 217 | #[error("Error at the protocol level: {0}")] 218 | AsyncProtocol(surf::Error), 219 | #[cfg(feature = "sync")] 220 | #[error("Error at the protocol level, sync client")] 221 | SyncProtocol(ureq::Error), 222 | } 223 | 224 | impl From for Error { 225 | fn from(e: api::ErrorMessage) -> Self { 226 | Error::Api(e) 227 | } 228 | } 229 | 230 | impl From for Error { 231 | fn from(e: String) -> Self { 232 | Error::BadArguments(e) 233 | } 234 | } 235 | 236 | #[cfg(feature = "async")] 237 | impl From for Error { 238 | fn from(e: surf::Error) -> Self { 239 | Error::AsyncProtocol(e) 240 | } 241 | } 242 | 243 | #[cfg(feature = "sync")] 244 | impl From for Error { 245 | fn from(e: ureq::Error) -> Self { 246 | Error::SyncProtocol(e) 247 | } 248 | } 249 | 250 | /// Authentication middleware 251 | #[cfg(feature = "async")] 252 | struct BearerToken { 253 | token: String, 254 | } 255 | 256 | #[cfg(feature = "async")] 257 | impl std::fmt::Debug for BearerToken { 258 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 259 | // Get the first few characters to help debug, but not accidentally log key 260 | write!( 261 | f, 262 | r#"Bearer {{ token: "{}" }}"#, 263 | self.token.get(0..8).ok_or(std::fmt::Error)? 264 | ) 265 | } 266 | } 267 | 268 | #[cfg(feature = "async")] 269 | impl BearerToken { 270 | fn new(token: &str) -> Self { 271 | Self { 272 | token: String::from(token), 273 | } 274 | } 275 | } 276 | 277 | #[cfg(feature = "async")] 278 | #[surf::utils::async_trait] 279 | impl surf::middleware::Middleware for BearerToken { 280 | async fn handle( 281 | &self, 282 | mut req: surf::Request, 283 | client: surf::Client, 284 | next: surf::middleware::Next<'_>, 285 | ) -> surf::Result { 286 | log::debug!("Request: {:?}", req); 287 | req.insert_header("Authorization", format!("Bearer {}", self.token)); 288 | let response: surf::Response = next.run(req, client).await?; 289 | log::debug!("Response: {:?}", response); 290 | Ok(response) 291 | } 292 | } 293 | 294 | #[cfg(feature = "async")] 295 | fn async_client(token: &str, base_url: &str) -> surf::Client { 296 | let mut async_client = surf::client(); 297 | async_client.set_base_url(surf::Url::parse(base_url).expect("Static string should parse")); 298 | async_client.with(BearerToken::new(token)) 299 | } 300 | 301 | #[cfg(feature = "sync")] 302 | fn sync_client(token: &str) -> ureq::Agent { 303 | ureq::agent().auth_kind("Bearer", token).build() 304 | } 305 | 306 | /// Client object. Must be constructed to talk to the API. 307 | #[derive(Debug, Clone)] 308 | pub struct Client { 309 | #[cfg(feature = "async")] 310 | async_client: surf::Client, 311 | #[cfg(feature = "sync")] 312 | sync_client: ureq::Agent, 313 | #[cfg(feature = "sync")] 314 | base_url: String, 315 | } 316 | 317 | impl Client { 318 | // Creates a new `Client` given an api token 319 | #[must_use] 320 | pub fn new(token: &str) -> Self { 321 | let base_url: String = "https://api.openai.com/v1/".into(); 322 | Self { 323 | #[cfg(feature = "async")] 324 | async_client: async_client(token, &base_url), 325 | #[cfg(feature = "sync")] 326 | sync_client: sync_client(token), 327 | #[cfg(feature = "sync")] 328 | base_url, 329 | } 330 | } 331 | 332 | // Allow setting the api root in the tests 333 | #[cfg(test)] 334 | fn set_api_root(mut self, base_url: &str) -> Self { 335 | #[cfg(feature = "async")] 336 | { 337 | self.async_client.set_base_url( 338 | surf::Url::parse(base_url).expect("static URL expected to parse correctly"), 339 | ); 340 | } 341 | #[cfg(feature = "sync")] 342 | { 343 | self.base_url = String::from(base_url); 344 | } 345 | self 346 | } 347 | 348 | /// Private helper for making gets 349 | #[cfg(feature = "async")] 350 | async fn get(&self, endpoint: &str) -> Result 351 | where 352 | T: serde::de::DeserializeOwned, 353 | { 354 | let mut response = self.async_client.get(endpoint).await?; 355 | if let surf::StatusCode::Ok = response.status() { 356 | Ok(response.body_json::().await?) 357 | } else { 358 | let err = response.body_json::().await?.error; 359 | Err(Error::Api(err)) 360 | } 361 | } 362 | 363 | #[cfg(feature = "sync")] 364 | fn get_sync(&self, endpoint: &str) -> Result 365 | where 366 | T: serde::de::DeserializeOwned, 367 | { 368 | let response = dbg!(self 369 | .sync_client 370 | .get(&format!("{}{}", self.base_url, endpoint))) 371 | .call(); 372 | if let 200 = response.status() { 373 | Ok(response 374 | .into_json_deserialize() 375 | .expect("Bug: client couldn't deserialize api response")) 376 | } else { 377 | let err = response 378 | .into_json_deserialize::() 379 | .expect("Bug: client couldn't deserialize api error response") 380 | .error; 381 | Err(Error::Api(err)) 382 | } 383 | } 384 | 385 | /// Lists the currently available engines. 386 | /// 387 | /// Provides basic information about each one such as the owner and availability. 388 | /// 389 | /// # Errors 390 | /// - `Error::APIError` if the server returns an error 391 | #[cfg(feature = "async")] 392 | pub async fn engines(&self) -> Result> { 393 | self.get("engines").await.map(|r: api::Container<_>| r.data) 394 | } 395 | 396 | /// Lists the currently available engines. 397 | /// 398 | /// Provides basic information about each one such as the owner and availability. 399 | /// 400 | /// # Errors 401 | /// - `Error::APIError` if the server returns an error 402 | #[cfg(feature = "sync")] 403 | pub fn engines_sync(&self) -> Result> { 404 | self.get_sync("engines").map(|r: api::Container<_>| r.data) 405 | } 406 | 407 | /// Retrieves an engine instance 408 | /// 409 | /// Provides basic information about the engine such as the owner and availability. 410 | /// 411 | /// # Errors 412 | /// - `Error::APIError` if the server returns an error 413 | #[cfg(feature = "async")] 414 | pub async fn engine(&self, engine: &str) -> Result { 415 | self.get(&format!("engines/{}", engine)).await 416 | } 417 | 418 | #[cfg(feature = "sync")] 419 | pub fn engine_sync(&self, engine: &str) -> Result { 420 | self.get_sync(&format!("engines/{}", engine)) 421 | } 422 | 423 | // Private helper to generate post requests. Needs to be a bit more flexible than 424 | // get because it should support SSE eventually 425 | #[cfg(feature = "async")] 426 | async fn post(&self, endpoint: &str, body: B) -> Result 427 | where 428 | B: serde::ser::Serialize, 429 | R: serde::de::DeserializeOwned, 430 | { 431 | let mut response = self 432 | .async_client 433 | .post(endpoint) 434 | .body(surf::Body::from_json(&body)?) 435 | .await?; 436 | match response.status() { 437 | surf::StatusCode::Ok => Ok(response.body_json::().await?), 438 | _ => Err(Error::Api( 439 | response 440 | .body_json::() 441 | .await 442 | .expect("The API has returned something funky") 443 | .error, 444 | )), 445 | } 446 | } 447 | 448 | #[cfg(feature = "sync")] 449 | fn post_sync(&self, endpoint: &str, body: B) -> Result 450 | where 451 | B: serde::ser::Serialize, 452 | R: serde::de::DeserializeOwned, 453 | { 454 | let response = self 455 | .sync_client 456 | .post(&format!("{}{}", self.base_url, endpoint)) 457 | .send_json( 458 | serde_json::to_value(body).expect("Bug: client couldn't serialize its own type"), 459 | ); 460 | match response.status() { 461 | 200 => Ok(response 462 | .into_json_deserialize() 463 | .expect("Bug: client couldn't deserialize api response")), 464 | _ => Err(Error::Api( 465 | response 466 | .into_json_deserialize::() 467 | .expect("Bug: client couldn't deserialize api error response") 468 | .error, 469 | )), 470 | } 471 | } 472 | 473 | /// Get predicted completion of the prompt 474 | /// 475 | /// # Errors 476 | /// - `Error::APIError` if the api returns an error 477 | #[cfg(feature = "async")] 478 | pub async fn complete_prompt( 479 | &self, 480 | prompt: impl Into, 481 | ) -> Result { 482 | let args = prompt.into(); 483 | Ok(self 484 | .post(&format!("engines/{}/completions", args.engine), args) 485 | .await?) 486 | } 487 | 488 | /// Get predicted completion of the prompt synchronously 489 | /// 490 | /// # Error 491 | /// - `Error::APIError` if the api returns an error 492 | #[cfg(feature = "sync")] 493 | pub fn complete_prompt_sync( 494 | &self, 495 | prompt: impl Into, 496 | ) -> Result { 497 | let args = prompt.into(); 498 | self.post_sync(&format!("engines/{}/completions", args.engine), args) 499 | } 500 | } 501 | 502 | // TODO: add a macro to de-boilerplate the sync and async tests 503 | 504 | #[allow(unused_macros)] 505 | macro_rules! async_test { 506 | ($test_name: ident, $test_body: block) => { 507 | #[cfg(feature = "async")] 508 | #[tokio::test] 509 | async fn $test_name() -> crate::Result<()> { 510 | $test_body; 511 | Ok(()) 512 | } 513 | }; 514 | } 515 | 516 | #[allow(unused_macros)] 517 | macro_rules! sync_test { 518 | ($test_name: ident, $test_body: expr) => { 519 | #[cfg(feature = "sync")] 520 | #[test] 521 | fn $test_name() -> crate::Result<()> { 522 | $test_body; 523 | Ok(()) 524 | } 525 | }; 526 | } 527 | 528 | #[cfg(test)] 529 | mod unit { 530 | 531 | use mockito::Mock; 532 | 533 | use crate::{ 534 | api::{self, Completion, CompletionArgs, EngineInfo}, 535 | Client, Error, 536 | }; 537 | 538 | fn mocked_client() -> Client { 539 | let _ = env_logger::builder().is_test(true).try_init(); 540 | Client::new("bogus").set_api_root(&format!("{}/", mockito::server_url())) 541 | } 542 | 543 | #[test] 544 | fn can_create_client() { 545 | let _c = mocked_client(); 546 | } 547 | 548 | #[test] 549 | fn parse_engine_info() -> Result<(), Box> { 550 | let example = r#"{ 551 | "id": "ada", 552 | "object": "engine", 553 | "owner": "openai", 554 | "ready": true 555 | }"#; 556 | let ei: api::EngineInfo = serde_json::from_str(example)?; 557 | assert_eq!( 558 | ei, 559 | api::EngineInfo { 560 | id: "ada".into(), 561 | owner: "openai".into(), 562 | ready: true, 563 | } 564 | ); 565 | Ok(()) 566 | } 567 | 568 | fn mock_engines() -> (Mock, Vec) { 569 | let mock = mockito::mock("GET", "/engines") 570 | .with_status(200) 571 | .with_header("content-type", "application/json") 572 | .with_body( 573 | r#"{ 574 | "object": "list", 575 | "data": [ 576 | { 577 | "id": "ada", 578 | "object": "engine", 579 | "owner": "openai", 580 | "ready": true 581 | }, 582 | { 583 | "id": "babbage", 584 | "object": "engine", 585 | "owner": "openai", 586 | "ready": true 587 | }, 588 | { 589 | "id": "experimental-engine-v7", 590 | "object": "engine", 591 | "owner": "openai", 592 | "ready": false 593 | }, 594 | { 595 | "id": "curie", 596 | "object": "engine", 597 | "owner": "openai", 598 | "ready": true 599 | }, 600 | { 601 | "id": "davinci", 602 | "object": "engine", 603 | "owner": "openai", 604 | "ready": true 605 | }, 606 | { 607 | "id": "content-filter-alpha-c4", 608 | "object": "engine", 609 | "owner": "openai", 610 | "ready": true 611 | } 612 | ] 613 | }"#, 614 | ) 615 | .create(); 616 | 617 | let expected = vec![ 618 | EngineInfo { 619 | id: "ada".into(), 620 | owner: "openai".into(), 621 | ready: true, 622 | }, 623 | EngineInfo { 624 | id: "babbage".into(), 625 | owner: "openai".into(), 626 | ready: true, 627 | }, 628 | EngineInfo { 629 | id: "experimental-engine-v7".into(), 630 | owner: "openai".into(), 631 | ready: false, 632 | }, 633 | EngineInfo { 634 | id: "curie".into(), 635 | owner: "openai".into(), 636 | ready: true, 637 | }, 638 | EngineInfo { 639 | id: "davinci".into(), 640 | owner: "openai".into(), 641 | ready: true, 642 | }, 643 | EngineInfo { 644 | id: "content-filter-alpha-c4".into(), 645 | owner: "openai".into(), 646 | ready: true, 647 | }, 648 | ]; 649 | (mock, expected) 650 | } 651 | 652 | async_test!(parse_engines_async, { 653 | let (_m, expected) = mock_engines(); 654 | let response = mocked_client().engines().await?; 655 | assert_eq!(response, expected); 656 | }); 657 | 658 | sync_test!(parse_engines_sync, { 659 | let (_m, expected) = mock_engines(); 660 | let response = mocked_client().engines_sync()?; 661 | assert_eq!(response, expected); 662 | }); 663 | 664 | fn mock_engine() -> (Mock, api::ErrorMessage) { 665 | let mock = mockito::mock("GET", "/engines/davinci") 666 | .with_status(404) 667 | .with_header("content-type", "application/json") 668 | .with_body( 669 | r#"{ 670 | "error": { 671 | "code": null, 672 | "message": "Some kind of error happened", 673 | "type": "some_error_type" 674 | } 675 | }"#, 676 | ) 677 | .create(); 678 | let expected = api::ErrorMessage { 679 | message: "Some kind of error happened".into(), 680 | error_type: "some_error_type".into(), 681 | }; 682 | (mock, expected) 683 | } 684 | 685 | async_test!(engine_error_response_async, { 686 | let (_m, expected) = mock_engine(); 687 | let response = mocked_client().engine("davinci").await; 688 | if let Result::Err(Error::Api(msg)) = response { 689 | assert_eq!(expected, msg); 690 | } 691 | }); 692 | 693 | sync_test!(engine_error_response_sync, { 694 | let (_m, expected) = mock_engine(); 695 | let response = mocked_client().engine_sync("davinci"); 696 | if let Result::Err(Error::Api(msg)) = response { 697 | assert_eq!(expected, msg); 698 | } 699 | }); 700 | fn mock_completion() -> crate::Result<(Mock, CompletionArgs, Completion)> { 701 | let mock = mockito::mock("POST", "/engines/davinci/completions") 702 | .with_status(200) 703 | .with_header("content-type", "application/json") 704 | .with_body( 705 | r#"{ 706 | "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", 707 | "object": "text_completion", 708 | "created": 1589478378, 709 | "model": "davinci:2020-05-03", 710 | "choices": [ 711 | { 712 | "text": " there was a girl who", 713 | "index": 0, 714 | "logprobs": null, 715 | "finish_reason": "length" 716 | } 717 | ] 718 | }"#, 719 | ) 720 | .expect(1) 721 | .create(); 722 | let args = api::CompletionArgs::builder() 723 | .engine("davinci") 724 | .prompt("Once upon a time") 725 | .max_tokens(5) 726 | .temperature(1.0) 727 | .top_p(1.0) 728 | .n(1) 729 | .stop(vec!["\n".into()]) 730 | .build()?; 731 | let expected = api::Completion { 732 | id: "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7".into(), 733 | created: 1589478378, 734 | model: "davinci:2020-05-03".into(), 735 | choices: vec![api::Choice { 736 | text: " there was a girl who".into(), 737 | index: 0, 738 | logprobs: None, 739 | finish_reason: "length".into(), 740 | }], 741 | }; 742 | Ok((mock, args, expected)) 743 | } 744 | 745 | // Defines boilerplate here. The Completion can't derive Eq since it contains 746 | // floats in various places. 747 | fn assert_completion_equal(a: Completion, b: Completion) { 748 | assert_eq!(a.model, b.model); 749 | assert_eq!(a.id, b.id); 750 | assert_eq!(a.created, b.created); 751 | let (a_choice, b_choice) = (&a.choices[0], &b.choices[0]); 752 | assert_eq!(a_choice.text, b_choice.text); 753 | assert_eq!(a_choice.index, b_choice.index); 754 | assert!(a_choice.logprobs.is_none()); 755 | assert_eq!(a_choice.finish_reason, b_choice.finish_reason); 756 | } 757 | 758 | async_test!(completion_args_async, { 759 | let (m, args, expected) = mock_completion()?; 760 | let response = mocked_client().complete_prompt(args).await?; 761 | assert_completion_equal(response, expected); 762 | m.assert(); 763 | }); 764 | 765 | sync_test!(completion_args_sync, { 766 | let (m, args, expected) = mock_completion()?; 767 | let response = mocked_client().complete_prompt_sync(args)?; 768 | assert_completion_equal(response, expected); 769 | m.assert(); 770 | }); 771 | } 772 | 773 | #[cfg(test)] 774 | mod integration { 775 | use crate::{ 776 | api::{self, Completion}, 777 | Client, 778 | }; 779 | /// Used by tests to get a client to the actual api 780 | fn get_client() -> Client { 781 | let _ = env_logger::builder().is_test(true).try_init(); 782 | let sk = std::env::var("OPENAI_SK").expect( 783 | "To run integration tests, you must put set the OPENAI_SK env var to your api token", 784 | ); 785 | Client::new(&sk) 786 | } 787 | 788 | async_test!(can_get_engines_async, { 789 | let client = get_client(); 790 | client.engines().await? 791 | }); 792 | 793 | sync_test!(can_get_engines_sync, { 794 | let client = get_client(); 795 | let engines = client 796 | .engines_sync()? 797 | .into_iter() 798 | .map(|ei| ei.id) 799 | .collect::>(); 800 | assert!(engines.contains(&"ada".into())); 801 | assert!(engines.contains(&"babbage".into())); 802 | assert!(engines.contains(&"curie".into())); 803 | assert!(engines.contains(&"davinci".into())); 804 | }); 805 | 806 | fn assert_engine_correct(engine_id: &str, info: api::EngineInfo) { 807 | assert_eq!(info.id, engine_id); 808 | assert!(info.ready); 809 | assert_eq!(info.owner, "openai"); 810 | } 811 | async_test!(can_get_engine_async, { 812 | let client = get_client(); 813 | assert_engine_correct("ada", client.engine("ada").await?); 814 | }); 815 | 816 | sync_test!(can_get_engine_sync, { 817 | let client = get_client(); 818 | assert_engine_correct("ada", client.engine_sync("ada")?); 819 | }); 820 | 821 | async_test!(complete_string_async, { 822 | let client = get_client(); 823 | client.complete_prompt("Hey there").await?; 824 | }); 825 | 826 | sync_test!(complete_string_sync, { 827 | let client = get_client(); 828 | client.complete_prompt_sync("Hey there")?; 829 | }); 830 | 831 | fn create_args() -> api::CompletionArgs { 832 | api::CompletionArgsBuilder::default() 833 | .prompt("Once upon a time,") 834 | .max_tokens(10) 835 | .temperature(0.5) 836 | .top_p(0.5) 837 | .n(1) 838 | .logprobs(3) 839 | .echo(false) 840 | .stop(vec!["\n".into()]) 841 | .presence_penalty(0.5) 842 | .frequency_penalty(0.5) 843 | .logit_bias(maplit::hashmap! { 844 | "1".into() => 1.0, 845 | "23".into() => 0.0, 846 | }) 847 | .build() 848 | .expect("Bug: build should succeed") 849 | } 850 | async_test!(complete_explicit_params_async, { 851 | let client = get_client(); 852 | let args = create_args(); 853 | client.complete_prompt(args).await?; 854 | }); 855 | 856 | sync_test!(complete_explicit_params_sync, { 857 | let client = get_client(); 858 | let args = create_args(); 859 | client.complete_prompt_sync(args)? 860 | }); 861 | 862 | fn stop_condition_args() -> api::CompletionArgs { 863 | api::CompletionArgs::builder() 864 | .prompt( 865 | r#" 866 | Q: Please type `#` now 867 | A:"#, 868 | ) 869 | // turn temp & top_p way down to prevent test flakiness 870 | .temperature(0.0) 871 | .top_p(0.0) 872 | .max_tokens(100) 873 | .stop(vec!["#".into(), "\n".into()]) 874 | .build() 875 | .expect("Bug: build should succeed") 876 | } 877 | 878 | fn assert_completion_finish_reason(completion: Completion) { 879 | assert_eq!(completion.choices[0].finish_reason, "stop",); 880 | } 881 | 882 | async_test!(complete_stop_condition_async, { 883 | let client = get_client(); 884 | let args = stop_condition_args(); 885 | assert_completion_finish_reason(client.complete_prompt(args).await?); 886 | }); 887 | 888 | sync_test!(complete_stop_condition_sync, { 889 | let client = get_client(); 890 | let args = stop_condition_args(); 891 | assert_completion_finish_reason(client.complete_prompt_sync(args)?); 892 | }); 893 | } 894 | --------------------------------------------------------------------------------