pub struct OpenAIClient {
pub response_headers: Option<HeaderMap>,
/* private fields */
}
Fields§
§response_headers: Option<HeaderMap>
Implementations§
Source§impl OpenAIClient
impl OpenAIClient
Sourcepub fn builder() -> OpenAIClientBuilder
pub fn builder() -> OpenAIClientBuilder
Examples found in repository?
examples/audio_translations.rs (line 8)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
8 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
9
10 let req = AudioTranslationRequest::new(
11 "examples/data/problem_cn.mp3".to_string(),
12 WHISPER_1.to_string(),
13 );
14
15 let result = client.audio_translation(req).await?;
16 println!("{:?}", result);
17
18 Ok(())
19}
More examples
examples/embedding.rs (line 9)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
9 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
10
11 let mut req = EmbeddingRequest::new(
12 TEXT_EMBEDDING_3_SMALL.to_string(),
13 vec!["story time".to_string(), "Once upon a time".to_string()],
14 );
15 req.dimensions = Some(10);
16
17 let result = client.embedding(req).await?;
18 println!("{:?}", result.data);
19
20 Ok(())
21}
examples/model.rs (line 7)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
7 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
8
9 let result = client.list_models().await?;
10 let models = result.data;
11
12 for model in models {
13 println!("Model id: {:?}", model.id);
14 }
15
16 let result = client.retrieve_model("gpt-4.1".to_string()).await?;
17 println!("Model id: {:?}", result.id);
18 println!("Model object: {:?}", result.object);
19
20 Ok(())
21}
examples/audio_speech.rs (line 8)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
8 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
9
10 let req = AudioSpeechRequest::new(
11 TTS_1.to_string(),
12 String::from("Money is not the problem, the problem is no money."),
13 audio::VOICE_ALLOY.to_string(),
14 String::from("examples/data/problem.mp3"),
15 );
16
17 let result = client.audio_speech(req).await?;
18 println!("{:?}", result);
19
20 Ok(())
21}
examples/completion.rs (line 8)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
8 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
9
10 let req = CompletionRequest::new(
11 completion::GPT3_TEXT_DAVINCI_003.to_string(),
12 String::from("What is Bitcoin?"),
13 )
14 .max_tokens(3000)
15 .temperature(0.9)
16 .top_p(1.0)
17 .stop(vec![String::from(" Human:"), String::from(" AI:")])
18 .presence_penalty(0.6)
19 .frequency_penalty(0.0);
20
21 let result = client.completion(req).await?;
22 println!("{:}", result.choices[0].text);
23
24 Ok(())
25}
examples/openrouter.rs (line 9)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
9 let mut client = OpenAIClient::builder()
10 .with_endpoint("https://openrouter.ai/api/v1")
11 .with_api_key(api_key)
12 .build()?;
13
14 let req = ChatCompletionRequest::new(
15 GPT4_O_MINI.to_string(),
16 vec![chat_completion::ChatCompletionMessage {
17 role: chat_completion::MessageRole::user,
18 content: chat_completion::Content::Text(String::from("What is bitcoin?")),
19 name: None,
20 tool_calls: None,
21 tool_call_id: None,
22 }],
23 );
24
25 let result = client.chat_completion(req).await?;
26 println!("Content: {:?}", result.choices[0].message.content);
27 println!("Response Headers: {:?}", client.response_headers);
28
29 Ok(())
30}
Sourcepub async fn completion(
&mut self,
req: CompletionRequest,
) -> Result<CompletionResponse, APIError>
pub async fn completion( &mut self, req: CompletionRequest, ) -> Result<CompletionResponse, APIError>
Examples found in repository?
examples/completion.rs (line 21)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
8 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
9
10 let req = CompletionRequest::new(
11 completion::GPT3_TEXT_DAVINCI_003.to_string(),
12 String::from("What is Bitcoin?"),
13 )
14 .max_tokens(3000)
15 .temperature(0.9)
16 .top_p(1.0)
17 .stop(vec![String::from(" Human:"), String::from(" AI:")])
18 .presence_penalty(0.6)
19 .frequency_penalty(0.0);
20
21 let result = client.completion(req).await?;
22 println!("{:}", result.choices[0].text);
23
24 Ok(())
25}
pub async fn edit(&mut self, req: EditRequest) -> Result<EditResponse, APIError>
pub async fn image_generation( &mut self, req: ImageGenerationRequest, ) -> Result<ImageGenerationResponse, APIError>
pub async fn image_edit( &mut self, req: ImageEditRequest, ) -> Result<ImageEditResponse, APIError>
pub async fn image_variation( &mut self, req: ImageVariationRequest, ) -> Result<ImageVariationResponse, APIError>
Sourcepub async fn embedding(
&mut self,
req: EmbeddingRequest,
) -> Result<EmbeddingResponse, APIError>
pub async fn embedding( &mut self, req: EmbeddingRequest, ) -> Result<EmbeddingResponse, APIError>
Examples found in repository?
examples/embedding.rs (line 17)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
9 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
10
11 let mut req = EmbeddingRequest::new(
12 TEXT_EMBEDDING_3_SMALL.to_string(),
13 vec!["story time".to_string(), "Once upon a time".to_string()],
14 );
15 req.dimensions = Some(10);
16
17 let result = client.embedding(req).await?;
18 println!("{:?}", result.data);
19
20 Ok(())
21}
pub async fn file_list(&mut self) -> Result<FileListResponse, APIError>
Sourcepub async fn upload_file(
&mut self,
req: FileUploadRequest,
) -> Result<FileUploadResponse, APIError>
pub async fn upload_file( &mut self, req: FileUploadRequest, ) -> Result<FileUploadResponse, APIError>
Examples found in repository?
examples/batch.rs (line 20)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let req = FileUploadRequest::new(
16 "examples/data/batch_request.json".to_string(),
17 "batch".to_string(),
18 );
19
20 let result = client.upload_file(req).await?;
21 println!("File id: {:?}", result.id);
22
23 let input_file_id = result.id;
24 let req = CreateBatchRequest::new(
25 input_file_id.clone(),
26 "/v1/chat/completions".to_string(),
27 "24h".to_string(),
28 );
29
30 let result = client.create_batch(req).await?;
31 println!("Batch id: {:?}", result.id);
32
33 let batch_id = result.id;
34 let result = client.retrieve_batch(batch_id.to_string()).await?;
35 println!("Batch status: {:?}", result.status);
36
37 // sleep 30 seconds
38 println!("Sleeping for 30 seconds...");
39 tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
40
41 let result = client.retrieve_batch(batch_id.to_string()).await?;
42
43 let file_id = result.output_file_id.unwrap();
44 let result = client.retrieve_file_content(file_id).await?;
45 let s = match str::from_utf8(&result) {
46 Ok(v) => v.to_string(),
47 Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
48 };
49 let json_value: Value = from_str(&s)?;
50 let result_json = to_string_pretty(&json_value)?;
51
52 let output_file_path = "examples/data/batch_result.json";
53 let mut file = File::create(output_file_path)?;
54 file.write_all(result_json.as_bytes())?;
55
56 println!("File writed to {:?}", output_file_path);
57
58 Ok(())
59}
pub async fn delete_file( &mut self, req: FileDeleteRequest, ) -> Result<FileDeleteResponse, APIError>
pub async fn retrieve_file( &mut 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 44)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let req = FileUploadRequest::new(
16 "examples/data/batch_request.json".to_string(),
17 "batch".to_string(),
18 );
19
20 let result = client.upload_file(req).await?;
21 println!("File id: {:?}", result.id);
22
23 let input_file_id = result.id;
24 let req = CreateBatchRequest::new(
25 input_file_id.clone(),
26 "/v1/chat/completions".to_string(),
27 "24h".to_string(),
28 );
29
30 let result = client.create_batch(req).await?;
31 println!("Batch id: {:?}", result.id);
32
33 let batch_id = result.id;
34 let result = client.retrieve_batch(batch_id.to_string()).await?;
35 println!("Batch status: {:?}", result.status);
36
37 // sleep 30 seconds
38 println!("Sleeping for 30 seconds...");
39 tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
40
41 let result = client.retrieve_batch(batch_id.to_string()).await?;
42
43 let file_id = result.output_file_id.unwrap();
44 let result = client.retrieve_file_content(file_id).await?;
45 let s = match str::from_utf8(&result) {
46 Ok(v) => v.to_string(),
47 Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
48 };
49 let json_value: Value = from_str(&s)?;
50 let result_json = to_string_pretty(&json_value)?;
51
52 let output_file_path = "examples/data/batch_result.json";
53 let mut file = File::create(output_file_path)?;
54 file.write_all(result_json.as_bytes())?;
55
56 println!("File writed to {:?}", output_file_path);
57
58 Ok(())
59}
Sourcepub async fn chat_completion(
&mut self,
req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, APIError>
pub async fn chat_completion( &mut self, req: ChatCompletionRequest, ) -> Result<ChatCompletionResponse, APIError>
Examples found in repository?
examples/openrouter.rs (line 25)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
9 let mut client = OpenAIClient::builder()
10 .with_endpoint("https://openrouter.ai/api/v1")
11 .with_api_key(api_key)
12 .build()?;
13
14 let req = ChatCompletionRequest::new(
15 GPT4_O_MINI.to_string(),
16 vec![chat_completion::ChatCompletionMessage {
17 role: chat_completion::MessageRole::user,
18 content: chat_completion::Content::Text(String::from("What is bitcoin?")),
19 name: None,
20 tool_calls: None,
21 tool_call_id: None,
22 }],
23 );
24
25 let result = client.chat_completion(req).await?;
26 println!("Content: {:?}", result.choices[0].message.content);
27 println!("Response Headers: {:?}", client.response_headers);
28
29 Ok(())
30}
More examples
examples/chat_completion.rs (line 22)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
9 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
10
11 let req = ChatCompletionRequest::new(
12 GPT4_O_MINI.to_string(),
13 vec![chat_completion::ChatCompletionMessage {
14 role: chat_completion::MessageRole::user,
15 content: chat_completion::Content::Text(String::from("What is bitcoin?")),
16 name: None,
17 tool_calls: None,
18 tool_call_id: None,
19 }],
20 );
21
22 let result = client.chat_completion(req).await?;
23 println!("Content: {:?}", result.choices[0].message.content);
24
25 // print response headers
26 for (key, value) in client.response_headers.unwrap().iter() {
27 println!("{}: {:?}", key, value);
28 }
29
30 Ok(())
31}
examples/vision.rs (line 37)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
9 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
10
11 let req = ChatCompletionRequest::new(
12 GPT4_O.to_string(),
13 vec![chat_completion::ChatCompletionMessage {
14 role: chat_completion::MessageRole::user,
15 content: chat_completion::Content::ImageUrl(vec![
16 chat_completion::ImageUrl {
17 r#type: chat_completion::ContentType::text,
18 text: Some(String::from("What's in this image?")),
19 image_url: None,
20 },
21 chat_completion::ImageUrl {
22 r#type: chat_completion::ContentType::image_url,
23 text: None,
24 image_url: Some(chat_completion::ImageUrlType {
25 url: String::from(
26 "https://upload.wikimedia.org/wikipedia/commons/5/50/Bitcoin.png",
27 ),
28 }),
29 },
30 ]),
31 name: None,
32 tool_calls: None,
33 tool_call_id: None,
34 }],
35 );
36
37 let result = client.chat_completion(req).await?;
38 println!("{:?}", result.choices[0].message.content);
39
40 Ok(())
41}
examples/function_call.rs (line 61)
19async fn main() -> Result<(), Box<dyn std::error::Error>> {
20 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
21 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
22
23 let mut properties = HashMap::new();
24 properties.insert(
25 "coin".to_string(),
26 Box::new(types::JSONSchemaDefine {
27 schema_type: Some(types::JSONSchemaType::String),
28 description: Some("The cryptocurrency to get the price of".to_string()),
29 ..Default::default()
30 }),
31 );
32
33 let req = ChatCompletionRequest::new(
34 GPT4_O.to_string(),
35 vec![chat_completion::ChatCompletionMessage {
36 role: chat_completion::MessageRole::user,
37 content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
38 name: None,
39 tool_calls: None,
40 tool_call_id: None,
41 }],
42 )
43 .tools(vec![chat_completion::Tool {
44 r#type: chat_completion::ToolType::Function,
45 function: types::Function {
46 name: String::from("get_coin_price"),
47 description: Some(String::from("Get the price of a cryptocurrency")),
48 parameters: types::FunctionParameters {
49 schema_type: types::JSONSchemaType::Object,
50 properties: Some(properties),
51 required: Some(vec![String::from("coin")]),
52 },
53 },
54 }])
55 .tool_choice(chat_completion::ToolChoiceType::Auto);
56
57 // debug request json
58 // let serialized = serde_json::to_string(&req).unwrap();
59 // println!("{}", serialized);
60
61 let result = client.chat_completion(req).await?;
62
63 match result.choices[0].finish_reason {
64 None => {
65 println!("No finish_reason");
66 println!("{:?}", result.choices[0].message.content);
67 }
68 Some(chat_completion::FinishReason::stop) => {
69 println!("Stop");
70 println!("{:?}", result.choices[0].message.content);
71 }
72 Some(chat_completion::FinishReason::length) => {
73 println!("Length");
74 }
75 Some(chat_completion::FinishReason::tool_calls) => {
76 println!("ToolCalls");
77 #[derive(Deserialize, Serialize)]
78 struct Currency {
79 coin: String,
80 }
81 let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
82 for tool_call in tool_calls {
83 let name = tool_call.function.name.clone().unwrap();
84 let arguments = tool_call.function.arguments.clone().unwrap();
85 let c: Currency = serde_json::from_str(&arguments)?;
86 let coin = c.coin;
87 if name == "get_coin_price" {
88 let price = get_coin_price(&coin);
89 println!("{} price: {}", coin, price);
90 }
91 }
92 }
93 Some(chat_completion::FinishReason::content_filter) => {
94 println!("ContentFilter");
95 }
96 Some(chat_completion::FinishReason::null) => {
97 println!("Null");
98 }
99 }
100 Ok(())
101}
examples/function_call_role.rs (line 56)
19async fn main() -> Result<(), Box<dyn std::error::Error>> {
20 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
21 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
22
23 let mut properties = HashMap::new();
24 properties.insert(
25 "coin".to_string(),
26 Box::new(types::JSONSchemaDefine {
27 schema_type: Some(types::JSONSchemaType::String),
28 description: Some("The cryptocurrency to get the price of".to_string()),
29 ..Default::default()
30 }),
31 );
32
33 let req = ChatCompletionRequest::new(
34 GPT4_O.to_string(),
35 vec![chat_completion::ChatCompletionMessage {
36 role: chat_completion::MessageRole::user,
37 content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
38 name: None,
39 tool_calls: None,
40 tool_call_id: None,
41 }],
42 )
43 .tools(vec![chat_completion::Tool {
44 r#type: chat_completion::ToolType::Function,
45 function: types::Function {
46 name: String::from("get_coin_price"),
47 description: Some(String::from("Get the price of a cryptocurrency")),
48 parameters: types::FunctionParameters {
49 schema_type: types::JSONSchemaType::Object,
50 properties: Some(properties),
51 required: Some(vec![String::from("coin")]),
52 },
53 },
54 }]);
55
56 let result = client.chat_completion(req).await?;
57
58 match result.choices[0].finish_reason {
59 None => {
60 println!("No finish_reason");
61 println!("{:?}", result.choices[0].message.content);
62 }
63 Some(chat_completion::FinishReason::stop) => {
64 println!("Stop");
65 println!("{:?}", result.choices[0].message.content);
66 }
67 Some(chat_completion::FinishReason::length) => {
68 println!("Length");
69 }
70 Some(chat_completion::FinishReason::tool_calls) => {
71 println!("ToolCalls");
72 #[derive(Deserialize, Serialize)]
73 struct Currency {
74 coin: String,
75 }
76 let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
77 for tool_call in tool_calls {
78 let function_call = &tool_call.function;
79 let arguments = function_call.arguments.clone().unwrap();
80 let c: Currency = serde_json::from_str(&arguments)?;
81 let coin = c.coin;
82 println!("coin: {}", coin);
83 let price = get_coin_price(&coin);
84 println!("price: {}", price);
85
86 let req = ChatCompletionRequest::new(
87 GPT4_O.to_string(),
88 vec![
89 chat_completion::ChatCompletionMessage {
90 role: chat_completion::MessageRole::user,
91 content: chat_completion::Content::Text(String::from(
92 "What is the price of Ethereum?",
93 )),
94 name: None,
95 tool_calls: None,
96 tool_call_id: None,
97 },
98 chat_completion::ChatCompletionMessage {
99 role: chat_completion::MessageRole::function,
100 content: chat_completion::Content::Text({
101 let price = get_coin_price(&coin);
102 format!("{{\"price\": {}}}", price)
103 }),
104 name: Some(String::from("get_coin_price")),
105 tool_calls: None,
106 tool_call_id: None,
107 },
108 ],
109 );
110
111 let result = client.chat_completion(req).await?;
112 println!("{:?}", result.choices[0].message.content);
113 }
114 }
115 Some(chat_completion::FinishReason::content_filter) => {
116 println!("ContentFilter");
117 }
118 Some(chat_completion::FinishReason::null) => {
119 println!("Null");
120 }
121 }
122 Ok(())
123}
Sourcepub async fn audio_transcription(
&mut self,
req: AudioTranscriptionRequest,
) -> Result<AudioTranscriptionResponse, APIError>
pub async fn audio_transcription( &mut self, req: AudioTranscriptionRequest, ) -> Result<AudioTranscriptionResponse, APIError>
Examples found in repository?
examples/audio_transcriptions.rs (line 19)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
10 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
11
12 let file_path = "examples/data/problem.mp3";
13
14 // Test with file
15 let req = AudioTranscriptionRequest::new(file_path.to_string(), WHISPER_1.to_string());
16
17 let req_json = req.clone().response_format("json".to_string());
18
19 let result = client.audio_transcription(req_json).await?;
20 println!("{:?}", result);
21
22 let req_raw = req.clone().response_format("text".to_string());
23
24 let result = client.audio_transcription_raw(req_raw).await?;
25 println!("{:?}", result);
26
27 // Test with bytes
28 let mut file = File::open(file_path)?;
29 let mut buffer = Vec::new();
30 file.read_to_end(&mut buffer)?;
31
32 let req = AudioTranscriptionRequest::new_bytes(buffer, WHISPER_1.to_string());
33
34 let req_json = req.clone().response_format("json".to_string());
35
36 let result = client.audio_transcription(req_json).await?;
37 println!("{:?}", result);
38
39 Ok(())
40}
Sourcepub async fn audio_transcription_raw(
&mut self,
req: AudioTranscriptionRequest,
) -> Result<Bytes, APIError>
pub async fn audio_transcription_raw( &mut self, req: AudioTranscriptionRequest, ) -> Result<Bytes, APIError>
Examples found in repository?
examples/audio_transcriptions.rs (line 24)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
10 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
11
12 let file_path = "examples/data/problem.mp3";
13
14 // Test with file
15 let req = AudioTranscriptionRequest::new(file_path.to_string(), WHISPER_1.to_string());
16
17 let req_json = req.clone().response_format("json".to_string());
18
19 let result = client.audio_transcription(req_json).await?;
20 println!("{:?}", result);
21
22 let req_raw = req.clone().response_format("text".to_string());
23
24 let result = client.audio_transcription_raw(req_raw).await?;
25 println!("{:?}", result);
26
27 // Test with bytes
28 let mut file = File::open(file_path)?;
29 let mut buffer = Vec::new();
30 file.read_to_end(&mut buffer)?;
31
32 let req = AudioTranscriptionRequest::new_bytes(buffer, WHISPER_1.to_string());
33
34 let req_json = req.clone().response_format("json".to_string());
35
36 let result = client.audio_transcription(req_json).await?;
37 println!("{:?}", result);
38
39 Ok(())
40}
Sourcepub async fn audio_translation(
&mut self,
req: AudioTranslationRequest,
) -> Result<AudioTranslationResponse, APIError>
pub async fn audio_translation( &mut self, req: AudioTranslationRequest, ) -> Result<AudioTranslationResponse, APIError>
Examples found in repository?
examples/audio_translations.rs (line 15)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
8 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
9
10 let req = AudioTranslationRequest::new(
11 "examples/data/problem_cn.mp3".to_string(),
12 WHISPER_1.to_string(),
13 );
14
15 let result = client.audio_translation(req).await?;
16 println!("{:?}", result);
17
18 Ok(())
19}
Sourcepub async fn audio_speech(
&mut self,
req: AudioSpeechRequest,
) -> Result<AudioSpeechResponse, APIError>
pub async fn audio_speech( &mut self, req: AudioSpeechRequest, ) -> Result<AudioSpeechResponse, APIError>
Examples found in repository?
examples/audio_speech.rs (line 17)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
8 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
9
10 let req = AudioSpeechRequest::new(
11 TTS_1.to_string(),
12 String::from("Money is not the problem, the problem is no money."),
13 audio::VOICE_ALLOY.to_string(),
14 String::from("examples/data/problem.mp3"),
15 );
16
17 let result = client.audio_speech(req).await?;
18 println!("{:?}", result);
19
20 Ok(())
21}
pub async fn create_fine_tuning_job( &mut self, req: CreateFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>
pub async fn list_fine_tuning_jobs( &mut self, ) -> Result<FineTuningPagination<FineTuningJobObject>, APIError>
pub async fn list_fine_tuning_job_events( &mut self, req: ListFineTuningJobEventsRequest, ) -> Result<FineTuningPagination<FineTuningJobEvent>, APIError>
pub async fn retrieve_fine_tuning_job( &mut self, req: RetrieveFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>
pub async fn cancel_fine_tuning_job( &mut self, req: CancelFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>
pub async fn create_moderation( &mut self, req: CreateModerationRequest, ) -> Result<CreateModerationResponse, APIError>
Sourcepub async fn create_assistant(
&mut self,
req: AssistantRequest,
) -> Result<AssistantObject, APIError>
pub async fn create_assistant( &mut self, req: AssistantRequest, ) -> Result<AssistantObject, APIError>
Examples found in repository?
examples/assistant.rs (line 26)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let mut tools = HashMap::new();
16 tools.insert("type".to_string(), "code_interpreter".to_string());
17
18 let req = AssistantRequest::new(GPT4_O.to_string());
19 let req = req
20 .clone()
21 .description("this is a test assistant".to_string());
22 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());
23 let req = req.clone().tools(vec![tools]);
24 println!("AssistantRequest: {:?}", req);
25
26 let result = client.create_assistant(req).await?;
27 println!("Create Assistant Result ID: {:?}", result.id);
28
29 let thread_req = CreateThreadRequest::new();
30 let thread_result = client.create_thread(thread_req).await?;
31 println!("Create Thread Result ID: {:?}", thread_result.id.clone());
32
33 let message_req = CreateMessageRequest::new(
34 MessageRole::user,
35 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
36 );
37
38 let message_result = client
39 .create_message(thread_result.id.clone(), message_req)
40 .await?;
41 println!("Create Message Result ID: {:?}", message_result.id.clone());
42
43 let run_req = CreateRunRequest::new(result.id);
44 let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
45 println!("Create Run Result ID: {:?}", run_result.id.clone());
46
47 loop {
48 let run_result = client
49 .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50 .await
51 .unwrap();
52 if run_result.status == "completed" {
53 break;
54 } else {
55 println!("waiting...");
56 std::thread::sleep(std::time::Duration::from_secs(1));
57 }
58 }
59
60 let list_message_result = client
61 .list_messages(thread_result.id.clone())
62 .await
63 .unwrap();
64 for data in list_message_result.data {
65 for content in data.content {
66 println!(
67 "{:?}: {:?} {:?}",
68 data.role, content.text.value, content.text.annotations
69 );
70 }
71 }
72
73 Ok(())
74}
pub async fn retrieve_assistant( &mut self, assistant_id: String, ) -> Result<AssistantObject, APIError>
pub async fn modify_assistant( &mut self, assistant_id: String, req: AssistantRequest, ) -> Result<AssistantObject, APIError>
pub async fn delete_assistant( &mut self, assistant_id: String, ) -> Result<DeletionStatus, APIError>
pub async fn list_assistant( &mut self, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListAssistant, APIError>
pub async fn create_assistant_file( &mut self, assistant_id: String, req: AssistantFileRequest, ) -> Result<AssistantFileObject, APIError>
pub async fn retrieve_assistant_file( &mut self, assistant_id: String, file_id: String, ) -> Result<AssistantFileObject, APIError>
pub async fn delete_assistant_file( &mut self, assistant_id: String, file_id: String, ) -> Result<DeletionStatus, APIError>
pub async fn list_assistant_file( &mut self, assistant_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListAssistantFile, APIError>
Sourcepub async fn create_thread(
&mut self,
req: CreateThreadRequest,
) -> Result<ThreadObject, APIError>
pub async fn create_thread( &mut self, req: CreateThreadRequest, ) -> Result<ThreadObject, APIError>
Examples found in repository?
examples/assistant.rs (line 30)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let mut tools = HashMap::new();
16 tools.insert("type".to_string(), "code_interpreter".to_string());
17
18 let req = AssistantRequest::new(GPT4_O.to_string());
19 let req = req
20 .clone()
21 .description("this is a test assistant".to_string());
22 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());
23 let req = req.clone().tools(vec![tools]);
24 println!("AssistantRequest: {:?}", req);
25
26 let result = client.create_assistant(req).await?;
27 println!("Create Assistant Result ID: {:?}", result.id);
28
29 let thread_req = CreateThreadRequest::new();
30 let thread_result = client.create_thread(thread_req).await?;
31 println!("Create Thread Result ID: {:?}", thread_result.id.clone());
32
33 let message_req = CreateMessageRequest::new(
34 MessageRole::user,
35 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
36 );
37
38 let message_result = client
39 .create_message(thread_result.id.clone(), message_req)
40 .await?;
41 println!("Create Message Result ID: {:?}", message_result.id.clone());
42
43 let run_req = CreateRunRequest::new(result.id);
44 let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
45 println!("Create Run Result ID: {:?}", run_result.id.clone());
46
47 loop {
48 let run_result = client
49 .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50 .await
51 .unwrap();
52 if run_result.status == "completed" {
53 break;
54 } else {
55 println!("waiting...");
56 std::thread::sleep(std::time::Duration::from_secs(1));
57 }
58 }
59
60 let list_message_result = client
61 .list_messages(thread_result.id.clone())
62 .await
63 .unwrap();
64 for data in list_message_result.data {
65 for content in data.content {
66 println!(
67 "{:?}: {:?} {:?}",
68 data.role, content.text.value, content.text.annotations
69 );
70 }
71 }
72
73 Ok(())
74}
pub async fn retrieve_thread( &mut self, thread_id: String, ) -> Result<ThreadObject, APIError>
pub async fn modify_thread( &mut self, thread_id: String, req: ModifyThreadRequest, ) -> Result<ThreadObject, APIError>
pub async fn delete_thread( &mut self, thread_id: String, ) -> Result<DeletionStatus, APIError>
Sourcepub async fn create_message(
&mut self,
thread_id: String,
req: CreateMessageRequest,
) -> Result<MessageObject, APIError>
pub async fn create_message( &mut self, thread_id: String, req: CreateMessageRequest, ) -> Result<MessageObject, APIError>
Examples found in repository?
examples/assistant.rs (line 39)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let mut tools = HashMap::new();
16 tools.insert("type".to_string(), "code_interpreter".to_string());
17
18 let req = AssistantRequest::new(GPT4_O.to_string());
19 let req = req
20 .clone()
21 .description("this is a test assistant".to_string());
22 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());
23 let req = req.clone().tools(vec![tools]);
24 println!("AssistantRequest: {:?}", req);
25
26 let result = client.create_assistant(req).await?;
27 println!("Create Assistant Result ID: {:?}", result.id);
28
29 let thread_req = CreateThreadRequest::new();
30 let thread_result = client.create_thread(thread_req).await?;
31 println!("Create Thread Result ID: {:?}", thread_result.id.clone());
32
33 let message_req = CreateMessageRequest::new(
34 MessageRole::user,
35 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
36 );
37
38 let message_result = client
39 .create_message(thread_result.id.clone(), message_req)
40 .await?;
41 println!("Create Message Result ID: {:?}", message_result.id.clone());
42
43 let run_req = CreateRunRequest::new(result.id);
44 let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
45 println!("Create Run Result ID: {:?}", run_result.id.clone());
46
47 loop {
48 let run_result = client
49 .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50 .await
51 .unwrap();
52 if run_result.status == "completed" {
53 break;
54 } else {
55 println!("waiting...");
56 std::thread::sleep(std::time::Duration::from_secs(1));
57 }
58 }
59
60 let list_message_result = client
61 .list_messages(thread_result.id.clone())
62 .await
63 .unwrap();
64 for data in list_message_result.data {
65 for content in data.content {
66 println!(
67 "{:?}: {:?} {:?}",
68 data.role, content.text.value, content.text.annotations
69 );
70 }
71 }
72
73 Ok(())
74}
pub async fn retrieve_message( &mut self, thread_id: String, message_id: String, ) -> Result<MessageObject, APIError>
pub async fn modify_message( &mut self, thread_id: String, message_id: String, req: ModifyMessageRequest, ) -> Result<MessageObject, APIError>
Sourcepub async fn list_messages(
&mut self,
thread_id: String,
) -> Result<ListMessage, APIError>
pub async fn list_messages( &mut self, thread_id: String, ) -> Result<ListMessage, APIError>
Examples found in repository?
examples/assistant.rs (line 61)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let mut tools = HashMap::new();
16 tools.insert("type".to_string(), "code_interpreter".to_string());
17
18 let req = AssistantRequest::new(GPT4_O.to_string());
19 let req = req
20 .clone()
21 .description("this is a test assistant".to_string());
22 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());
23 let req = req.clone().tools(vec![tools]);
24 println!("AssistantRequest: {:?}", req);
25
26 let result = client.create_assistant(req).await?;
27 println!("Create Assistant Result ID: {:?}", result.id);
28
29 let thread_req = CreateThreadRequest::new();
30 let thread_result = client.create_thread(thread_req).await?;
31 println!("Create Thread Result ID: {:?}", thread_result.id.clone());
32
33 let message_req = CreateMessageRequest::new(
34 MessageRole::user,
35 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
36 );
37
38 let message_result = client
39 .create_message(thread_result.id.clone(), message_req)
40 .await?;
41 println!("Create Message Result ID: {:?}", message_result.id.clone());
42
43 let run_req = CreateRunRequest::new(result.id);
44 let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
45 println!("Create Run Result ID: {:?}", run_result.id.clone());
46
47 loop {
48 let run_result = client
49 .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50 .await
51 .unwrap();
52 if run_result.status == "completed" {
53 break;
54 } else {
55 println!("waiting...");
56 std::thread::sleep(std::time::Duration::from_secs(1));
57 }
58 }
59
60 let list_message_result = client
61 .list_messages(thread_result.id.clone())
62 .await
63 .unwrap();
64 for data in list_message_result.data {
65 for content in data.content {
66 println!(
67 "{:?}: {:?} {:?}",
68 data.role, content.text.value, content.text.annotations
69 );
70 }
71 }
72
73 Ok(())
74}
pub async fn retrieve_message_file( &mut self, thread_id: String, message_id: String, file_id: String, ) -> Result<MessageFileObject, APIError>
pub async fn list_message_file( &mut 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(
&mut self,
thread_id: String,
req: CreateRunRequest,
) -> Result<RunObject, APIError>
pub async fn create_run( &mut self, thread_id: String, req: CreateRunRequest, ) -> Result<RunObject, APIError>
Examples found in repository?
examples/assistant.rs (line 44)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let mut tools = HashMap::new();
16 tools.insert("type".to_string(), "code_interpreter".to_string());
17
18 let req = AssistantRequest::new(GPT4_O.to_string());
19 let req = req
20 .clone()
21 .description("this is a test assistant".to_string());
22 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());
23 let req = req.clone().tools(vec![tools]);
24 println!("AssistantRequest: {:?}", req);
25
26 let result = client.create_assistant(req).await?;
27 println!("Create Assistant Result ID: {:?}", result.id);
28
29 let thread_req = CreateThreadRequest::new();
30 let thread_result = client.create_thread(thread_req).await?;
31 println!("Create Thread Result ID: {:?}", thread_result.id.clone());
32
33 let message_req = CreateMessageRequest::new(
34 MessageRole::user,
35 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
36 );
37
38 let message_result = client
39 .create_message(thread_result.id.clone(), message_req)
40 .await?;
41 println!("Create Message Result ID: {:?}", message_result.id.clone());
42
43 let run_req = CreateRunRequest::new(result.id);
44 let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
45 println!("Create Run Result ID: {:?}", run_result.id.clone());
46
47 loop {
48 let run_result = client
49 .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50 .await
51 .unwrap();
52 if run_result.status == "completed" {
53 break;
54 } else {
55 println!("waiting...");
56 std::thread::sleep(std::time::Duration::from_secs(1));
57 }
58 }
59
60 let list_message_result = client
61 .list_messages(thread_result.id.clone())
62 .await
63 .unwrap();
64 for data in list_message_result.data {
65 for content in data.content {
66 println!(
67 "{:?}: {:?} {:?}",
68 data.role, content.text.value, content.text.annotations
69 );
70 }
71 }
72
73 Ok(())
74}
Sourcepub async fn retrieve_run(
&mut self,
thread_id: String,
run_id: String,
) -> Result<RunObject, APIError>
pub async fn retrieve_run( &mut self, thread_id: String, run_id: String, ) -> Result<RunObject, APIError>
Examples found in repository?
examples/assistant.rs (line 49)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let mut tools = HashMap::new();
16 tools.insert("type".to_string(), "code_interpreter".to_string());
17
18 let req = AssistantRequest::new(GPT4_O.to_string());
19 let req = req
20 .clone()
21 .description("this is a test assistant".to_string());
22 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());
23 let req = req.clone().tools(vec![tools]);
24 println!("AssistantRequest: {:?}", req);
25
26 let result = client.create_assistant(req).await?;
27 println!("Create Assistant Result ID: {:?}", result.id);
28
29 let thread_req = CreateThreadRequest::new();
30 let thread_result = client.create_thread(thread_req).await?;
31 println!("Create Thread Result ID: {:?}", thread_result.id.clone());
32
33 let message_req = CreateMessageRequest::new(
34 MessageRole::user,
35 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
36 );
37
38 let message_result = client
39 .create_message(thread_result.id.clone(), message_req)
40 .await?;
41 println!("Create Message Result ID: {:?}", message_result.id.clone());
42
43 let run_req = CreateRunRequest::new(result.id);
44 let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
45 println!("Create Run Result ID: {:?}", run_result.id.clone());
46
47 loop {
48 let run_result = client
49 .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50 .await
51 .unwrap();
52 if run_result.status == "completed" {
53 break;
54 } else {
55 println!("waiting...");
56 std::thread::sleep(std::time::Duration::from_secs(1));
57 }
58 }
59
60 let list_message_result = client
61 .list_messages(thread_result.id.clone())
62 .await
63 .unwrap();
64 for data in list_message_result.data {
65 for content in data.content {
66 println!(
67 "{:?}: {:?} {:?}",
68 data.role, content.text.value, content.text.annotations
69 );
70 }
71 }
72
73 Ok(())
74}
pub async fn modify_run( &mut self, thread_id: String, run_id: String, req: ModifyRunRequest, ) -> Result<RunObject, APIError>
pub async fn list_run( &mut self, thread_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListRun, APIError>
pub async fn cancel_run( &mut self, thread_id: String, run_id: String, ) -> Result<RunObject, APIError>
pub async fn create_thread_and_run( &mut self, req: CreateThreadAndRunRequest, ) -> Result<RunObject, APIError>
pub async fn retrieve_run_step( &mut self, thread_id: String, run_id: String, step_id: String, ) -> Result<RunStepObject, APIError>
pub async fn list_run_step( &mut 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(
&mut self,
req: CreateBatchRequest,
) -> Result<BatchResponse, APIError>
pub async fn create_batch( &mut self, req: CreateBatchRequest, ) -> Result<BatchResponse, APIError>
Examples found in repository?
examples/batch.rs (line 30)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let req = FileUploadRequest::new(
16 "examples/data/batch_request.json".to_string(),
17 "batch".to_string(),
18 );
19
20 let result = client.upload_file(req).await?;
21 println!("File id: {:?}", result.id);
22
23 let input_file_id = result.id;
24 let req = CreateBatchRequest::new(
25 input_file_id.clone(),
26 "/v1/chat/completions".to_string(),
27 "24h".to_string(),
28 );
29
30 let result = client.create_batch(req).await?;
31 println!("Batch id: {:?}", result.id);
32
33 let batch_id = result.id;
34 let result = client.retrieve_batch(batch_id.to_string()).await?;
35 println!("Batch status: {:?}", result.status);
36
37 // sleep 30 seconds
38 println!("Sleeping for 30 seconds...");
39 tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
40
41 let result = client.retrieve_batch(batch_id.to_string()).await?;
42
43 let file_id = result.output_file_id.unwrap();
44 let result = client.retrieve_file_content(file_id).await?;
45 let s = match str::from_utf8(&result) {
46 Ok(v) => v.to_string(),
47 Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
48 };
49 let json_value: Value = from_str(&s)?;
50 let result_json = to_string_pretty(&json_value)?;
51
52 let output_file_path = "examples/data/batch_result.json";
53 let mut file = File::create(output_file_path)?;
54 file.write_all(result_json.as_bytes())?;
55
56 println!("File writed to {:?}", output_file_path);
57
58 Ok(())
59}
Sourcepub async fn retrieve_batch(
&mut self,
batch_id: String,
) -> Result<BatchResponse, APIError>
pub async fn retrieve_batch( &mut self, batch_id: String, ) -> Result<BatchResponse, APIError>
Examples found in repository?
examples/batch.rs (line 34)
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
13 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
14
15 let req = FileUploadRequest::new(
16 "examples/data/batch_request.json".to_string(),
17 "batch".to_string(),
18 );
19
20 let result = client.upload_file(req).await?;
21 println!("File id: {:?}", result.id);
22
23 let input_file_id = result.id;
24 let req = CreateBatchRequest::new(
25 input_file_id.clone(),
26 "/v1/chat/completions".to_string(),
27 "24h".to_string(),
28 );
29
30 let result = client.create_batch(req).await?;
31 println!("Batch id: {:?}", result.id);
32
33 let batch_id = result.id;
34 let result = client.retrieve_batch(batch_id.to_string()).await?;
35 println!("Batch status: {:?}", result.status);
36
37 // sleep 30 seconds
38 println!("Sleeping for 30 seconds...");
39 tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
40
41 let result = client.retrieve_batch(batch_id.to_string()).await?;
42
43 let file_id = result.output_file_id.unwrap();
44 let result = client.retrieve_file_content(file_id).await?;
45 let s = match str::from_utf8(&result) {
46 Ok(v) => v.to_string(),
47 Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
48 };
49 let json_value: Value = from_str(&s)?;
50 let result_json = to_string_pretty(&json_value)?;
51
52 let output_file_path = "examples/data/batch_result.json";
53 let mut file = File::create(output_file_path)?;
54 file.write_all(result_json.as_bytes())?;
55
56 println!("File writed to {:?}", output_file_path);
57
58 Ok(())
59}
pub async fn cancel_batch( &mut self, batch_id: String, ) -> Result<BatchResponse, APIError>
pub async fn list_batch( &mut self, after: Option<String>, limit: Option<i64>, ) -> Result<ListBatchResponse, APIError>
Sourcepub async fn list_models(&mut self) -> Result<ModelsResponse, APIError>
pub async fn list_models(&mut self) -> Result<ModelsResponse, APIError>
Examples found in repository?
examples/model.rs (line 9)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
7 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
8
9 let result = client.list_models().await?;
10 let models = result.data;
11
12 for model in models {
13 println!("Model id: {:?}", model.id);
14 }
15
16 let result = client.retrieve_model("gpt-4.1".to_string()).await?;
17 println!("Model id: {:?}", result.id);
18 println!("Model object: {:?}", result.object);
19
20 Ok(())
21}
Sourcepub async fn retrieve_model(
&mut self,
model_id: String,
) -> Result<ModelResponse, APIError>
pub async fn retrieve_model( &mut self, model_id: String, ) -> Result<ModelResponse, APIError>
Examples found in repository?
examples/model.rs (line 16)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
7 let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
8
9 let result = client.list_models().await?;
10 let models = result.data;
11
12 for model in models {
13 println!("Model id: {:?}", model.id);
14 }
15
16 let result = client.retrieve_model("gpt-4.1".to_string()).await?;
17 println!("Model id: {:?}", result.id);
18 println!("Model object: {:?}", result.object);
19
20 Ok(())
21}
pub async fn delete_model( &mut self, model_id: String, ) -> Result<DeletionStatus, APIError>
Trait Implementations§
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