Struct openai_api_rs::v1::api::Client
source · pub struct Client {
pub api_endpoint: String,
pub api_key: String,
pub organization: Option<String>,
}
Fields§
§api_endpoint: String
§api_key: String
§organization: Option<String>
Implementations§
source§impl Client
impl Client
sourcepub fn new(api_key: String) -> Self
pub fn new(api_key: String) -> Self
Examples found in repository?
examples/embedding.rs (line 6)
5 6 7 8 9 10 11 12 13 14 15 16 17
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = EmbeddingRequest::new(
"text-embedding-ada-002".to_string(),
"story time".to_string(),
);
let result = client.embedding(req)?;
println!("{:?}", result.data);
Ok(())
}
More examples
examples/completion.rs (line 6)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = CompletionRequest::new(
completion::GPT3_TEXT_DAVINCI_003.to_string(),
String::from("What is Bitcoin?"),
)
.max_tokens(3000)
.temperature(0.9)
.top_p(1.0)
.stop(vec![String::from(" Human:"), String::from(" AI:")])
.presence_penalty(0.6)
.frequency_penalty(0.0);
let result = client.completion(req)?;
println!("{:}", result.choices[0].text);
Ok(())
}
examples/chat_completion.rs (line 6)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
chat_completion::GPT4.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is Bitcoin?"),
name: None,
function_call: None,
}],
);
let result = client.chat_completion(req)?;
println!("{:?}", result.choices[0].message.content);
Ok(())
}
examples/function_call.rs (line 17)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
"coin".to_string(),
Box::new(chat_completion::JSONSchemaDefine {
schema_type: Some(chat_completion::JSONSchemaType::String),
description: Some("The cryptocurrency to get the price of".to_string()),
enum_values: None,
properties: None,
required: None,
items: None,
}),
);
let req = ChatCompletionRequest::new(
chat_completion::GPT3_5_TURBO_0613.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is the price of Ethereum?"),
name: None,
function_call: None,
}],
)
.functions(vec![chat_completion::Function {
name: String::from("get_coin_price"),
description: Some(String::from("Get the price of a cryptocurrency")),
parameters: chat_completion::FunctionParameters {
schema_type: chat_completion::JSONSchemaType::Object,
properties: Some(properties),
required: Some(vec![String::from("coin")]),
},
}])
.function_call(FunctionCallType::Auto);
// debug reuqest json
// let serialized = serde_json::to_string(&req).unwrap();
// println!("{}", serialized);
let result = client.chat_completion(req)?;
match result.choices[0].finish_reason {
chat_completion::FinishReason::stop => {
println!("Stop");
println!("{:?}", result.choices[0].message.content);
}
chat_completion::FinishReason::length => {
println!("Length");
}
chat_completion::FinishReason::function_call => {
println!("FunctionCall");
#[derive(Serialize, Deserialize)]
struct Currency {
coin: String,
}
let function_call = result.choices[0].message.function_call.as_ref().unwrap();
let name = function_call.name.clone().unwrap();
let arguments = function_call.arguments.clone().unwrap();
let c: Currency = serde_json::from_str(&arguments)?;
let coin = c.coin;
if name == "get_coin_price" {
let price = get_coin_price(&coin);
println!("{} price: {}", coin, price);
}
}
chat_completion::FinishReason::content_filter => {
println!("ContentFilter");
}
chat_completion::FinishReason::null => {
println!("Null");
}
}
Ok(())
}
examples/function_call_role.rs (line 17)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
"coin".to_string(),
Box::new(chat_completion::JSONSchemaDefine {
schema_type: Some(chat_completion::JSONSchemaType::String),
description: Some("The cryptocurrency to get the price of".to_string()),
enum_values: None,
properties: None,
required: None,
items: None,
}),
);
let req = ChatCompletionRequest::new(
chat_completion::GPT3_5_TURBO_0613.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is the price of Ethereum?"),
name: None,
function_call: None,
}],
)
.functions(vec![chat_completion::Function {
name: String::from("get_coin_price"),
description: Some(String::from("Get the price of a cryptocurrency")),
parameters: chat_completion::FunctionParameters {
schema_type: chat_completion::JSONSchemaType::Object,
properties: Some(properties),
required: Some(vec![String::from("coin")]),
},
}]);
let result = client.chat_completion(req)?;
match result.choices[0].finish_reason {
chat_completion::FinishReason::stop => {
println!("Stop");
println!("{:?}", result.choices[0].message.content);
}
chat_completion::FinishReason::length => {
println!("Length");
}
chat_completion::FinishReason::function_call => {
println!("FunctionCall");
#[derive(Serialize, Deserialize)]
struct Currency {
coin: String,
}
let function_call = result.choices[0].message.function_call.as_ref().unwrap();
let arguments = function_call.arguments.clone().unwrap();
let c: Currency = serde_json::from_str(&arguments)?;
let coin = c.coin;
let req = ChatCompletionRequest::new(
chat_completion::GPT3_5_TURBO_0613.to_string(),
vec![
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is the price of Ethereum?"),
name: None,
function_call: None,
},
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::function,
content: {
let price = get_coin_price(&coin);
format!("{{\"price\": {}}}", price)
},
name: Some(String::from("get_coin_price")),
function_call: None,
},
],
);
let result = client.chat_completion(req)?;
println!("{:?}", result.choices[0].message.content);
}
chat_completion::FinishReason::content_filter => {
println!("ContentFilter");
}
chat_completion::FinishReason::null => {
println!("Null");
}
}
Ok(())
}
pub fn new_with_endpoint(api_endpoint: String, api_key: String) -> Self
pub fn new_with_organization(api_key: String, organization: String) -> Self
pub fn build_request(&self, request: Request) -> Request
pub fn post<T: Serialize>( &self, path: &str, params: &T ) -> Result<Response, APIError>
pub fn get(&self, path: &str) -> Result<Response, APIError>
pub fn delete(&self, path: &str) -> Result<Response, APIError>
sourcepub fn completion(
&self,
req: CompletionRequest
) -> Result<CompletionResponse, APIError>
pub fn completion( &self, req: CompletionRequest ) -> Result<CompletionResponse, APIError>
Examples found in repository?
examples/completion.rs (line 19)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = CompletionRequest::new(
completion::GPT3_TEXT_DAVINCI_003.to_string(),
String::from("What is Bitcoin?"),
)
.max_tokens(3000)
.temperature(0.9)
.top_p(1.0)
.stop(vec![String::from(" Human:"), String::from(" AI:")])
.presence_penalty(0.6)
.frequency_penalty(0.0);
let result = client.completion(req)?;
println!("{:}", result.choices[0].text);
Ok(())
}
pub fn edit(&self, req: EditRequest) -> Result<EditResponse, APIError>
pub fn image_generation( &self, req: ImageGenerationRequest ) -> Result<ImageGenerationResponse, APIError>
pub fn image_edit( &self, req: ImageEditRequest ) -> Result<ImageEditResponse, APIError>
pub fn image_variation( &self, req: ImageVariationRequest ) -> Result<ImageVariationResponse, APIError>
sourcepub fn embedding(
&self,
req: EmbeddingRequest
) -> Result<EmbeddingResponse, APIError>
pub fn embedding( &self, req: EmbeddingRequest ) -> Result<EmbeddingResponse, APIError>
Examples found in repository?
examples/embedding.rs (line 13)
5 6 7 8 9 10 11 12 13 14 15 16 17
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = EmbeddingRequest::new(
"text-embedding-ada-002".to_string(),
"story time".to_string(),
);
let result = client.embedding(req)?;
println!("{:?}", result.data);
Ok(())
}
pub fn file_list(&self) -> Result<FileListResponse, APIError>
pub fn file_upload( &self, req: FileUploadRequest ) -> Result<FileUploadResponse, APIError>
pub fn file_delete( &self, req: FileDeleteRequest ) -> Result<FileDeleteResponse, APIError>
pub fn file_retrieve( &self, req: FileRetrieveRequest ) -> Result<FileRetrieveResponse, APIError>
pub fn file_retrieve_content( &self, req: FileRetrieveContentRequest ) -> Result<FileRetrieveContentResponse, APIError>
sourcepub fn chat_completion(
&self,
req: ChatCompletionRequest
) -> Result<ChatCompletionResponse, APIError>
pub fn chat_completion( &self, req: ChatCompletionRequest ) -> Result<ChatCompletionResponse, APIError>
Examples found in repository?
examples/chat_completion.rs (line 18)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
chat_completion::GPT4.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is Bitcoin?"),
name: None,
function_call: None,
}],
);
let result = client.chat_completion(req)?;
println!("{:?}", result.choices[0].message.content);
Ok(())
}
More examples
examples/function_call.rs (line 56)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
"coin".to_string(),
Box::new(chat_completion::JSONSchemaDefine {
schema_type: Some(chat_completion::JSONSchemaType::String),
description: Some("The cryptocurrency to get the price of".to_string()),
enum_values: None,
properties: None,
required: None,
items: None,
}),
);
let req = ChatCompletionRequest::new(
chat_completion::GPT3_5_TURBO_0613.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is the price of Ethereum?"),
name: None,
function_call: None,
}],
)
.functions(vec![chat_completion::Function {
name: String::from("get_coin_price"),
description: Some(String::from("Get the price of a cryptocurrency")),
parameters: chat_completion::FunctionParameters {
schema_type: chat_completion::JSONSchemaType::Object,
properties: Some(properties),
required: Some(vec![String::from("coin")]),
},
}])
.function_call(FunctionCallType::Auto);
// debug reuqest json
// let serialized = serde_json::to_string(&req).unwrap();
// println!("{}", serialized);
let result = client.chat_completion(req)?;
match result.choices[0].finish_reason {
chat_completion::FinishReason::stop => {
println!("Stop");
println!("{:?}", result.choices[0].message.content);
}
chat_completion::FinishReason::length => {
println!("Length");
}
chat_completion::FinishReason::function_call => {
println!("FunctionCall");
#[derive(Serialize, Deserialize)]
struct Currency {
coin: String,
}
let function_call = result.choices[0].message.function_call.as_ref().unwrap();
let name = function_call.name.clone().unwrap();
let arguments = function_call.arguments.clone().unwrap();
let c: Currency = serde_json::from_str(&arguments)?;
let coin = c.coin;
if name == "get_coin_price" {
let price = get_coin_price(&coin);
println!("{} price: {}", coin, price);
}
}
chat_completion::FinishReason::content_filter => {
println!("ContentFilter");
}
chat_completion::FinishReason::null => {
println!("Null");
}
}
Ok(())
}
examples/function_call_role.rs (line 51)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
"coin".to_string(),
Box::new(chat_completion::JSONSchemaDefine {
schema_type: Some(chat_completion::JSONSchemaType::String),
description: Some("The cryptocurrency to get the price of".to_string()),
enum_values: None,
properties: None,
required: None,
items: None,
}),
);
let req = ChatCompletionRequest::new(
chat_completion::GPT3_5_TURBO_0613.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is the price of Ethereum?"),
name: None,
function_call: None,
}],
)
.functions(vec![chat_completion::Function {
name: String::from("get_coin_price"),
description: Some(String::from("Get the price of a cryptocurrency")),
parameters: chat_completion::FunctionParameters {
schema_type: chat_completion::JSONSchemaType::Object,
properties: Some(properties),
required: Some(vec![String::from("coin")]),
},
}]);
let result = client.chat_completion(req)?;
match result.choices[0].finish_reason {
chat_completion::FinishReason::stop => {
println!("Stop");
println!("{:?}", result.choices[0].message.content);
}
chat_completion::FinishReason::length => {
println!("Length");
}
chat_completion::FinishReason::function_call => {
println!("FunctionCall");
#[derive(Serialize, Deserialize)]
struct Currency {
coin: String,
}
let function_call = result.choices[0].message.function_call.as_ref().unwrap();
let arguments = function_call.arguments.clone().unwrap();
let c: Currency = serde_json::from_str(&arguments)?;
let coin = c.coin;
let req = ChatCompletionRequest::new(
chat_completion::GPT3_5_TURBO_0613.to_string(),
vec![
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: String::from("What is the price of Ethereum?"),
name: None,
function_call: None,
},
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::function,
content: {
let price = get_coin_price(&coin);
format!("{{\"price\": {}}}", price)
},
name: Some(String::from("get_coin_price")),
function_call: None,
},
],
);
let result = client.chat_completion(req)?;
println!("{:?}", result.choices[0].message.content);
}
chat_completion::FinishReason::content_filter => {
println!("ContentFilter");
}
chat_completion::FinishReason::null => {
println!("Null");
}
}
Ok(())
}
pub fn audio_transcription( &self, req: AudioTranscriptionRequest ) -> Result<AudioTranscriptionResponse, APIError>
pub fn audio_translation( &self, req: AudioTranslationRequest ) -> Result<AudioTranslationResponse, APIError>
pub fn create_fine_tune( &self, req: CreateFineTuneRequest ) -> Result<CreateFineTuneResponse, APIError>
pub fn list_fine_tune(&self) -> Result<ListFineTuneResponse, APIError>
pub fn retrieve_fine_tune( &self, req: RetrieveFineTuneRequest ) -> Result<RetrieveFineTuneResponse, APIError>
pub fn cancel_fine_tune( &self, req: CancelFineTuneRequest ) -> Result<CancelFineTuneResponse, APIError>
pub fn list_fine_tune_events( &self, req: ListFineTuneEventsRequest ) -> Result<ListFineTuneEventsResponse, APIError>
pub fn delete_fine_tune( &self, req: DeleteFineTuneModelRequest ) -> Result<DeleteFineTuneModelResponse, APIError>
pub fn create_moderation( &self, req: CreateModerationRequest ) -> Result<CreateModerationResponse, APIError>
Auto Trait Implementations§
impl RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl UnwindSafe for Client
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more