pub struct OpenAIClient {
pub api_endpoint: String,
pub api_key: String,
pub organization: Option<String>,
pub proxy: Option<String>,
pub timeout: Option<u64>,
}
Fields§
§api_endpoint: String
§api_key: String
§organization: Option<String>
§proxy: Option<String>
§timeout: Option<u64>
Implementations§
Source§impl OpenAIClient
impl OpenAIClient
Sourcepub fn new(api_key: String) -> Self
pub fn new(api_key: String) -> Self
Examples found in repository?
examples/audio_translations.rs (line 7)
6 7 8 9 10 11 12 13 14 15 16 17 18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioTranslationRequest::new(
"examples/data/problem_cn.mp3".to_string(),
WHISPER_1.to_string(),
);
let result = client.audio_translation(req).await?;
println!("{:?}", result);
Ok(())
}
More examples
examples/audio_transcriptions.rs (line 7)
6 7 8 9 10 11 12 13 14 15 16 17 18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioTranscriptionRequest::new(
"examples/data/problem.mp3".to_string(),
WHISPER_1.to_string(),
);
let result = client.audio_transcription(req).await?;
println!("{:?}", result);
Ok(())
}
examples/embedding.rs (line 8)
7 8 9 10 11 12 13 14 15 16 17 18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut req =
EmbeddingRequest::new(TEXT_EMBEDDING_3_SMALL.to_string(), "story time".to_string());
req.dimensions = Some(10);
let result = client.embedding(req).await?;
println!("{:?}", result.data);
Ok(())
}
examples/audio_speech.rs (line 7)
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioSpeechRequest::new(
TTS_1.to_string(),
String::from("Money is not the problem, the problem is no money."),
audio::VOICE_ALLOY.to_string(),
String::from("examples/data/problem.mp3"),
);
let result = client.audio_speech(req).await?;
println!("{:?}", result);
Ok(())
}
examples/completion.rs (line 7)
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::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).await?;
println!("{:}", result.choices[0].text);
Ok(())
}
examples/chat_completion.rs (line 8)
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
GPT4_O_MINI.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from("What is bitcoin?")),
name: None,
tool_calls: None,
tool_call_id: None,
}],
);
let result = client.chat_completion(req).await?;
println!("Content: {:?}", result.choices[0].message.content);
println!("Response Headers: {:?}", result.headers);
Ok(())
}
Additional examples can be found in:
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 new_with_proxy(api_key: String, proxy: String) -> Self
pub fn new_with_timeout(api_key: String, timeout: u64) -> Self
Sourcepub async fn completion(
&self,
req: CompletionRequest,
) -> Result<CompletionResponse, APIError>
pub async fn completion( &self, req: CompletionRequest, ) -> Result<CompletionResponse, APIError>
Examples found in repository?
examples/completion.rs (line 20)
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::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).await?;
println!("{:}", result.choices[0].text);
Ok(())
}
pub async fn edit(&self, req: EditRequest) -> Result<EditResponse, APIError>
pub async fn image_generation( &self, req: ImageGenerationRequest, ) -> Result<ImageGenerationResponse, APIError>
pub async fn image_edit( &self, req: ImageEditRequest, ) -> Result<ImageEditResponse, APIError>
pub async fn image_variation( &self, req: ImageVariationRequest, ) -> Result<ImageVariationResponse, APIError>
Sourcepub async fn embedding(
&self,
req: EmbeddingRequest,
) -> Result<EmbeddingResponse, APIError>
pub async fn embedding( &self, req: EmbeddingRequest, ) -> Result<EmbeddingResponse, APIError>
Examples found in repository?
examples/embedding.rs (line 14)
7 8 9 10 11 12 13 14 15 16 17 18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut req =
EmbeddingRequest::new(TEXT_EMBEDDING_3_SMALL.to_string(), "story time".to_string());
req.dimensions = Some(10);
let result = client.embedding(req).await?;
println!("{:?}", result.data);
Ok(())
}
pub async fn file_list(&self) -> Result<FileListResponse, APIError>
Sourcepub async fn upload_file(
&self,
req: FileUploadRequest,
) -> Result<FileUploadResponse, APIError>
pub async fn upload_file( &self, req: FileUploadRequest, ) -> Result<FileUploadResponse, APIError>
Examples found in repository?
examples/batch.rs (line 19)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = FileUploadRequest::new(
"examples/data/batch_request.json".to_string(),
"batch".to_string(),
);
let result = client.upload_file(req).await?;
println!("File id: {:?}", result.id);
let input_file_id = result.id;
let req = CreateBatchRequest::new(
input_file_id.clone(),
"/v1/chat/completions".to_string(),
"24h".to_string(),
);
let result = client.create_batch(req).await?;
println!("Batch id: {:?}", result.id);
let batch_id = result.id;
let result = client.retrieve_batch(batch_id.to_string()).await?;
println!("Batch status: {:?}", result.status);
// sleep 30 seconds
println!("Sleeping for 30 seconds...");
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
let result = client.retrieve_batch(batch_id.to_string()).await?;
let file_id = result.output_file_id.unwrap();
let result = client.retrieve_file_content(file_id).await?;
let s = match str::from_utf8(&result) {
Ok(v) => v.to_string(),
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
let json_value: Value = from_str(&s)?;
let result_json = to_string_pretty(&json_value)?;
let output_file_path = "examples/data/batch_result.json";
let mut file = File::create(output_file_path)?;
file.write_all(result_json.as_bytes())?;
println!("File writed to {:?}", output_file_path);
Ok(())
}
pub async fn delete_file( &self, req: FileDeleteRequest, ) -> Result<FileDeleteResponse, APIError>
pub async fn retrieve_file( &self, file_id: String, ) -> Result<FileRetrieveResponse, APIError>
Sourcepub async fn retrieve_file_content(
&self,
file_id: String,
) -> Result<Bytes, APIError>
pub async fn retrieve_file_content( &self, file_id: String, ) -> Result<Bytes, APIError>
Examples found in repository?
examples/batch.rs (line 43)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = FileUploadRequest::new(
"examples/data/batch_request.json".to_string(),
"batch".to_string(),
);
let result = client.upload_file(req).await?;
println!("File id: {:?}", result.id);
let input_file_id = result.id;
let req = CreateBatchRequest::new(
input_file_id.clone(),
"/v1/chat/completions".to_string(),
"24h".to_string(),
);
let result = client.create_batch(req).await?;
println!("Batch id: {:?}", result.id);
let batch_id = result.id;
let result = client.retrieve_batch(batch_id.to_string()).await?;
println!("Batch status: {:?}", result.status);
// sleep 30 seconds
println!("Sleeping for 30 seconds...");
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
let result = client.retrieve_batch(batch_id.to_string()).await?;
let file_id = result.output_file_id.unwrap();
let result = client.retrieve_file_content(file_id).await?;
let s = match str::from_utf8(&result) {
Ok(v) => v.to_string(),
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
let json_value: Value = from_str(&s)?;
let result_json = to_string_pretty(&json_value)?;
let output_file_path = "examples/data/batch_result.json";
let mut file = File::create(output_file_path)?;
file.write_all(result_json.as_bytes())?;
println!("File writed to {:?}", output_file_path);
Ok(())
}
Sourcepub async fn chat_completion(
&self,
req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, APIError>
pub async fn chat_completion( &self, req: ChatCompletionRequest, ) -> Result<ChatCompletionResponse, APIError>
Examples found in repository?
examples/chat_completion.rs (line 21)
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
GPT4_O_MINI.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from("What is bitcoin?")),
name: None,
tool_calls: None,
tool_call_id: None,
}],
);
let result = client.chat_completion(req).await?;
println!("Content: {:?}", result.choices[0].message.content);
println!("Response Headers: {:?}", result.headers);
Ok(())
}
More examples
examples/vision.rs (line 36)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
GPT4_O.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::ImageUrl(vec![
chat_completion::ImageUrl {
r#type: chat_completion::ContentType::text,
text: Some(String::from("What's in this image?")),
image_url: None,
},
chat_completion::ImageUrl {
r#type: chat_completion::ContentType::image_url,
text: None,
image_url: Some(chat_completion::ImageUrlType {
url: String::from(
"https://upload.wikimedia.org/wikipedia/commons/5/50/Bitcoin.png",
),
}),
},
]),
name: None,
tool_calls: None,
tool_call_id: None,
}],
);
let result = client.chat_completion(req).await?;
println!("{:?}", result.choices[0].message.content);
Ok(())
}
examples/function_call.rs (line 60)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
"coin".to_string(),
Box::new(types::JSONSchemaDefine {
schema_type: Some(types::JSONSchemaType::String),
description: Some("The cryptocurrency to get the price of".to_string()),
..Default::default()
}),
);
let req = ChatCompletionRequest::new(
GPT4_O.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
name: None,
tool_calls: None,
tool_call_id: None,
}],
)
.tools(vec![chat_completion::Tool {
r#type: chat_completion::ToolType::Function,
function: types::Function {
name: String::from("get_coin_price"),
description: Some(String::from("Get the price of a cryptocurrency")),
parameters: types::FunctionParameters {
schema_type: types::JSONSchemaType::Object,
properties: Some(properties),
required: Some(vec![String::from("coin")]),
},
},
}])
.tool_choice(chat_completion::ToolChoiceType::Auto);
// debug request json
// let serialized = serde_json::to_string(&req).unwrap();
// println!("{}", serialized);
let result = client.chat_completion(req).await?;
match result.choices[0].finish_reason {
None => {
println!("No finish_reason");
println!("{:?}", result.choices[0].message.content);
}
Some(chat_completion::FinishReason::stop) => {
println!("Stop");
println!("{:?}", result.choices[0].message.content);
}
Some(chat_completion::FinishReason::length) => {
println!("Length");
}
Some(chat_completion::FinishReason::tool_calls) => {
println!("ToolCalls");
#[derive(Deserialize, Serialize)]
struct Currency {
coin: String,
}
let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
for tool_call in tool_calls {
let name = tool_call.function.name.clone().unwrap();
let arguments = tool_call.function.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);
}
}
}
Some(chat_completion::FinishReason::content_filter) => {
println!("ContentFilter");
}
Some(chat_completion::FinishReason::null) => {
println!("Null");
}
}
Ok(())
}
examples/function_call_role.rs (line 55)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
"coin".to_string(),
Box::new(types::JSONSchemaDefine {
schema_type: Some(types::JSONSchemaType::String),
description: Some("The cryptocurrency to get the price of".to_string()),
..Default::default()
}),
);
let req = ChatCompletionRequest::new(
GPT4_O.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
name: None,
tool_calls: None,
tool_call_id: None,
}],
)
.tools(vec![chat_completion::Tool {
r#type: chat_completion::ToolType::Function,
function: types::Function {
name: String::from("get_coin_price"),
description: Some(String::from("Get the price of a cryptocurrency")),
parameters: types::FunctionParameters {
schema_type: types::JSONSchemaType::Object,
properties: Some(properties),
required: Some(vec![String::from("coin")]),
},
},
}]);
let result = client.chat_completion(req).await?;
match result.choices[0].finish_reason {
None => {
println!("No finish_reason");
println!("{:?}", result.choices[0].message.content);
}
Some(chat_completion::FinishReason::stop) => {
println!("Stop");
println!("{:?}", result.choices[0].message.content);
}
Some(chat_completion::FinishReason::length) => {
println!("Length");
}
Some(chat_completion::FinishReason::tool_calls) => {
println!("ToolCalls");
#[derive(Deserialize, Serialize)]
struct Currency {
coin: String,
}
let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
for tool_call in tool_calls {
let function_call = &tool_call.function;
let arguments = function_call.arguments.clone().unwrap();
let c: Currency = serde_json::from_str(&arguments)?;
let coin = c.coin;
println!("coin: {}", coin);
let price = get_coin_price(&coin);
println!("price: {}", price);
let req = ChatCompletionRequest::new(
GPT4_O.to_string(),
vec![
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from(
"What is the price of Ethereum?",
)),
name: None,
tool_calls: None,
tool_call_id: None,
},
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::function,
content: chat_completion::Content::Text({
let price = get_coin_price(&coin);
format!("{{\"price\": {}}}", price)
}),
name: Some(String::from("get_coin_price")),
tool_calls: None,
tool_call_id: None,
},
],
);
let result = client.chat_completion(req).await?;
println!("{:?}", result.choices[0].message.content);
}
}
Some(chat_completion::FinishReason::content_filter) => {
println!("ContentFilter");
}
Some(chat_completion::FinishReason::null) => {
println!("Null");
}
}
Ok(())
}
Sourcepub async fn audio_transcription(
&self,
req: AudioTranscriptionRequest,
) -> Result<AudioTranscriptionResponse, APIError>
pub async fn audio_transcription( &self, req: AudioTranscriptionRequest, ) -> Result<AudioTranscriptionResponse, APIError>
Examples found in repository?
examples/audio_transcriptions.rs (line 14)
6 7 8 9 10 11 12 13 14 15 16 17 18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioTranscriptionRequest::new(
"examples/data/problem.mp3".to_string(),
WHISPER_1.to_string(),
);
let result = client.audio_transcription(req).await?;
println!("{:?}", result);
Ok(())
}
Sourcepub async fn audio_translation(
&self,
req: AudioTranslationRequest,
) -> Result<AudioTranslationResponse, APIError>
pub async fn audio_translation( &self, req: AudioTranslationRequest, ) -> Result<AudioTranslationResponse, APIError>
Examples found in repository?
examples/audio_translations.rs (line 14)
6 7 8 9 10 11 12 13 14 15 16 17 18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioTranslationRequest::new(
"examples/data/problem_cn.mp3".to_string(),
WHISPER_1.to_string(),
);
let result = client.audio_translation(req).await?;
println!("{:?}", result);
Ok(())
}
Sourcepub async fn audio_speech(
&self,
req: AudioSpeechRequest,
) -> Result<AudioSpeechResponse, APIError>
pub async fn audio_speech( &self, req: AudioSpeechRequest, ) -> Result<AudioSpeechResponse, APIError>
Examples found in repository?
examples/audio_speech.rs (line 16)
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioSpeechRequest::new(
TTS_1.to_string(),
String::from("Money is not the problem, the problem is no money."),
audio::VOICE_ALLOY.to_string(),
String::from("examples/data/problem.mp3"),
);
let result = client.audio_speech(req).await?;
println!("{:?}", result);
Ok(())
}
pub async fn create_fine_tuning_job( &self, req: CreateFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>
pub async fn list_fine_tuning_jobs( &self, ) -> Result<FineTuningPagination<FineTuningJobObject>, APIError>
pub async fn list_fine_tuning_job_events( &self, req: ListFineTuningJobEventsRequest, ) -> Result<FineTuningPagination<FineTuningJobEvent>, APIError>
pub async fn retrieve_fine_tuning_job( &self, req: RetrieveFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>
pub async fn cancel_fine_tuning_job( &self, req: CancelFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>
pub async fn create_moderation( &self, req: CreateModerationRequest, ) -> Result<CreateModerationResponse, APIError>
Sourcepub async fn create_assistant(
&self,
req: AssistantRequest,
) -> Result<AssistantObject, APIError>
pub async fn create_assistant( &self, req: AssistantRequest, ) -> Result<AssistantObject, APIError>
Examples found in repository?
examples/assistant.rs (line 25)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
let req = AssistantRequest::new(GPT4_O.to_string());
let req = req
.clone()
.description("this is a test assistant".to_string());
let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
MessageRole::user,
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
} else {
println!("waiting...");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(
"{:?}: {:?} {:?}",
data.role, content.text.value, content.text.annotations
);
}
}
Ok(())
}
pub async fn retrieve_assistant( &self, assistant_id: String, ) -> Result<AssistantObject, APIError>
pub async fn modify_assistant( &self, assistant_id: String, req: AssistantRequest, ) -> Result<AssistantObject, APIError>
pub async fn delete_assistant( &self, assistant_id: String, ) -> Result<DeletionStatus, APIError>
pub async fn list_assistant( &self, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListAssistant, APIError>
pub async fn create_assistant_file( &self, assistant_id: String, req: AssistantFileRequest, ) -> Result<AssistantFileObject, APIError>
pub async fn retrieve_assistant_file( &self, assistant_id: String, file_id: String, ) -> Result<AssistantFileObject, APIError>
pub async fn delete_assistant_file( &self, assistant_id: String, file_id: String, ) -> Result<DeletionStatus, APIError>
pub async fn list_assistant_file( &self, assistant_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListAssistantFile, APIError>
Sourcepub async fn create_thread(
&self,
req: CreateThreadRequest,
) -> Result<ThreadObject, APIError>
pub async fn create_thread( &self, req: CreateThreadRequest, ) -> Result<ThreadObject, APIError>
Examples found in repository?
examples/assistant.rs (line 29)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
let req = AssistantRequest::new(GPT4_O.to_string());
let req = req
.clone()
.description("this is a test assistant".to_string());
let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
MessageRole::user,
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
} else {
println!("waiting...");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(
"{:?}: {:?} {:?}",
data.role, content.text.value, content.text.annotations
);
}
}
Ok(())
}
pub async fn retrieve_thread( &self, thread_id: String, ) -> Result<ThreadObject, APIError>
pub async fn modify_thread( &self, thread_id: String, req: ModifyThreadRequest, ) -> Result<ThreadObject, APIError>
pub async fn delete_thread( &self, thread_id: String, ) -> Result<DeletionStatus, APIError>
Sourcepub async fn create_message(
&self,
thread_id: String,
req: CreateMessageRequest,
) -> Result<MessageObject, APIError>
pub async fn create_message( &self, thread_id: String, req: CreateMessageRequest, ) -> Result<MessageObject, APIError>
Examples found in repository?
examples/assistant.rs (line 38)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
let req = AssistantRequest::new(GPT4_O.to_string());
let req = req
.clone()
.description("this is a test assistant".to_string());
let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
MessageRole::user,
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
} else {
println!("waiting...");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(
"{:?}: {:?} {:?}",
data.role, content.text.value, content.text.annotations
);
}
}
Ok(())
}
pub async fn retrieve_message( &self, thread_id: String, message_id: String, ) -> Result<MessageObject, APIError>
pub async fn modify_message( &self, thread_id: String, message_id: String, req: ModifyMessageRequest, ) -> Result<MessageObject, APIError>
Sourcepub async fn list_messages(
&self,
thread_id: String,
) -> Result<ListMessage, APIError>
pub async fn list_messages( &self, thread_id: String, ) -> Result<ListMessage, APIError>
Examples found in repository?
examples/assistant.rs (line 60)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
let req = AssistantRequest::new(GPT4_O.to_string());
let req = req
.clone()
.description("this is a test assistant".to_string());
let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
MessageRole::user,
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
} else {
println!("waiting...");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(
"{:?}: {:?} {:?}",
data.role, content.text.value, content.text.annotations
);
}
}
Ok(())
}
pub async fn retrieve_message_file( &self, thread_id: String, message_id: String, file_id: String, ) -> Result<MessageFileObject, APIError>
pub async fn list_message_file( &self, thread_id: String, message_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListMessageFile, APIError>
Sourcepub async fn create_run(
&self,
thread_id: String,
req: CreateRunRequest,
) -> Result<RunObject, APIError>
pub async fn create_run( &self, thread_id: String, req: CreateRunRequest, ) -> Result<RunObject, APIError>
Examples found in repository?
examples/assistant.rs (line 43)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
let req = AssistantRequest::new(GPT4_O.to_string());
let req = req
.clone()
.description("this is a test assistant".to_string());
let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
MessageRole::user,
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
} else {
println!("waiting...");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(
"{:?}: {:?} {:?}",
data.role, content.text.value, content.text.annotations
);
}
}
Ok(())
}
Sourcepub async fn retrieve_run(
&self,
thread_id: String,
run_id: String,
) -> Result<RunObject, APIError>
pub async fn retrieve_run( &self, thread_id: String, run_id: String, ) -> Result<RunObject, APIError>
Examples found in repository?
examples/assistant.rs (line 48)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
let req = AssistantRequest::new(GPT4_O.to_string());
let req = req
.clone()
.description("this is a test assistant".to_string());
let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
MessageRole::user,
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
} else {
println!("waiting...");
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(
"{:?}: {:?} {:?}",
data.role, content.text.value, content.text.annotations
);
}
}
Ok(())
}
pub async fn modify_run( &self, thread_id: String, run_id: String, req: ModifyRunRequest, ) -> Result<RunObject, APIError>
pub async fn list_run( &self, thread_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListRun, APIError>
pub async fn cancel_run( &self, thread_id: String, run_id: String, ) -> Result<RunObject, APIError>
pub async fn create_thread_and_run( &self, req: CreateThreadAndRunRequest, ) -> Result<RunObject, APIError>
pub async fn retrieve_run_step( &self, thread_id: String, run_id: String, step_id: String, ) -> Result<RunStepObject, APIError>
pub async fn list_run_step( &self, thread_id: String, run_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListRunStep, APIError>
Sourcepub async fn create_batch(
&self,
req: CreateBatchRequest,
) -> Result<BatchResponse, APIError>
pub async fn create_batch( &self, req: CreateBatchRequest, ) -> Result<BatchResponse, APIError>
Examples found in repository?
examples/batch.rs (line 29)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = FileUploadRequest::new(
"examples/data/batch_request.json".to_string(),
"batch".to_string(),
);
let result = client.upload_file(req).await?;
println!("File id: {:?}", result.id);
let input_file_id = result.id;
let req = CreateBatchRequest::new(
input_file_id.clone(),
"/v1/chat/completions".to_string(),
"24h".to_string(),
);
let result = client.create_batch(req).await?;
println!("Batch id: {:?}", result.id);
let batch_id = result.id;
let result = client.retrieve_batch(batch_id.to_string()).await?;
println!("Batch status: {:?}", result.status);
// sleep 30 seconds
println!("Sleeping for 30 seconds...");
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
let result = client.retrieve_batch(batch_id.to_string()).await?;
let file_id = result.output_file_id.unwrap();
let result = client.retrieve_file_content(file_id).await?;
let s = match str::from_utf8(&result) {
Ok(v) => v.to_string(),
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
let json_value: Value = from_str(&s)?;
let result_json = to_string_pretty(&json_value)?;
let output_file_path = "examples/data/batch_result.json";
let mut file = File::create(output_file_path)?;
file.write_all(result_json.as_bytes())?;
println!("File writed to {:?}", output_file_path);
Ok(())
}
Sourcepub async fn retrieve_batch(
&self,
batch_id: String,
) -> Result<BatchResponse, APIError>
pub async fn retrieve_batch( &self, batch_id: String, ) -> Result<BatchResponse, APIError>
Examples found in repository?
examples/batch.rs (line 33)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = FileUploadRequest::new(
"examples/data/batch_request.json".to_string(),
"batch".to_string(),
);
let result = client.upload_file(req).await?;
println!("File id: {:?}", result.id);
let input_file_id = result.id;
let req = CreateBatchRequest::new(
input_file_id.clone(),
"/v1/chat/completions".to_string(),
"24h".to_string(),
);
let result = client.create_batch(req).await?;
println!("Batch id: {:?}", result.id);
let batch_id = result.id;
let result = client.retrieve_batch(batch_id.to_string()).await?;
println!("Batch status: {:?}", result.status);
// sleep 30 seconds
println!("Sleeping for 30 seconds...");
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
let result = client.retrieve_batch(batch_id.to_string()).await?;
let file_id = result.output_file_id.unwrap();
let result = client.retrieve_file_content(file_id).await?;
let s = match str::from_utf8(&result) {
Ok(v) => v.to_string(),
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
let json_value: Value = from_str(&s)?;
let result_json = to_string_pretty(&json_value)?;
let output_file_path = "examples/data/batch_result.json";
let mut file = File::create(output_file_path)?;
file.write_all(result_json.as_bytes())?;
println!("File writed to {:?}", output_file_path);
Ok(())
}
pub async fn cancel_batch( &self, batch_id: String, ) -> Result<BatchResponse, APIError>
pub async fn list_batch( &self, after: Option<String>, limit: Option<i64>, ) -> Result<ListBatchResponse, APIError>
Auto Trait Implementations§
impl Freeze for OpenAIClient
impl RefUnwindSafe for OpenAIClient
impl Send for OpenAIClient
impl Sync for OpenAIClient
impl Unpin for OpenAIClient
impl UnwindSafe for OpenAIClient
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
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more