OpenAIClient

Struct OpenAIClient 

Source
pub struct OpenAIClient {
    pub response_headers: Option<HeaderMap>,
    /* private fields */
}

Fields§

§response_headers: Option<HeaderMap>

Implementations§

Source§

impl OpenAIClient

Source

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
Hide additional examples
examples/openrouter_models.rs (line 7)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
7    let mut client = OpenAIClient::builder()
8        .with_endpoint("https://openrouter.ai/api/v1")
9        .with_api_key(api_key)
10        .build()?;
11
12    let result = client.list_models().await?;
13    let models = result.data;
14
15    for model in models {
16        println!("Model id: {:?}", model.id);
17    }
18
19    Ok(())
20}
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}
Source

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}
Source

pub async fn edit(&mut self, req: EditRequest) -> Result<EditResponse, APIError>

Source

pub async fn image_generation( &mut self, req: ImageGenerationRequest, ) -> Result<ImageGenerationResponse, APIError>

Source

pub async fn image_edit( &mut self, req: ImageEditRequest, ) -> Result<ImageEditResponse, APIError>

Source

pub async fn image_variation( &mut self, req: ImageVariationRequest, ) -> Result<ImageVariationResponse, APIError>

Source

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}
Source

pub async fn file_list(&mut self) -> Result<FileListResponse, APIError>

Source

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}
Source

pub async fn delete_file( &mut self, req: FileDeleteRequest, ) -> Result<FileDeleteResponse, APIError>

Source

pub async fn retrieve_file( &mut self, file_id: String, ) -> Result<FileRetrieveResponse, APIError>

Source

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}
Source

pub async fn chat_completion( &mut self, req: ChatCompletionRequest, ) -> Result<ChatCompletionResponse, APIError>

Examples found in repository?
examples/openrouter.rs (line 26)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
10    let mut client = OpenAIClient::builder()
11        .with_endpoint("https://openrouter.ai/api/v1")
12        .with_api_key(api_key)
13        .build()?;
14
15    let req = ChatCompletionRequest::new(
16        GPT4_O_MINI.to_string(),
17        vec![chat_completion::ChatCompletionMessage {
18            role: chat_completion::MessageRole::user,
19            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
20            name: None,
21            tool_calls: None,
22            tool_call_id: None,
23        }],
24    );
25
26    let result = client.chat_completion(req).await?;
27    println!("Content: {:?}", result.choices[0].message.content);
28    println!("Response Headers: {:?}", client.response_headers);
29
30    Ok(())
31}
More examples
Hide additional examples
examples/chat_completion.rs (line 23)
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 req = ChatCompletionRequest::new(
13        GPT4_O_MINI.to_string(),
14        vec![chat_completion::ChatCompletionMessage {
15            role: chat_completion::MessageRole::user,
16            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
17            name: None,
18            tool_calls: None,
19            tool_call_id: None,
20        }],
21    );
22
23    let result = client.chat_completion(req).await?;
24    println!("Content: {:?}", result.choices[0].message.content);
25
26    // print response headers
27    for (key, value) in client.response_headers.unwrap().iter() {
28        println!("{}: {:?}", key, value);
29    }
30
31    Ok(())
32}
examples/vision.rs (line 38)
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 req = ChatCompletionRequest::new(
13        GPT4_O.to_string(),
14        vec![chat_completion::ChatCompletionMessage {
15            role: chat_completion::MessageRole::user,
16            content: chat_completion::Content::ImageUrl(vec![
17                chat_completion::ImageUrl {
18                    r#type: chat_completion::ContentType::text,
19                    text: Some(String::from("What's in this image?")),
20                    image_url: None,
21                },
22                chat_completion::ImageUrl {
23                    r#type: chat_completion::ContentType::image_url,
24                    text: None,
25                    image_url: Some(chat_completion::ImageUrlType {
26                        url: String::from(
27                            "https://upload.wikimedia.org/wikipedia/commons/5/50/Bitcoin.png",
28                        ),
29                    }),
30                },
31            ]),
32            name: None,
33            tool_calls: None,
34            tool_call_id: None,
35        }],
36    );
37
38    let result = client.chat_completion(req).await?;
39    println!("{:?}", result.choices[0].message.content);
40
41    Ok(())
42}
examples/openrouter_reasoning.rs (line 37)
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    // Example 1: Using reasoning with effort
15    let mut req = ChatCompletionRequest::new(
16        "x-ai/grok-3-mini".to_string(), // Grok model that supports reasoning
17        vec![chat_completion::ChatCompletionMessage {
18            role: chat_completion::MessageRole::user,
19            content: chat_completion::Content::Text(String::from(
20                "Explain quantum computing in simple terms.",
21            )),
22            name: None,
23            tool_calls: None,
24            tool_call_id: None,
25        }],
26    );
27
28    // Set reasoning with high effort
29    req.reasoning = Some(Reasoning {
30        mode: Some(ReasoningMode::Effort {
31            effort: ReasoningEffort::High,
32        }),
33        exclude: Some(false), // Include reasoning in response
34        enabled: None,
35    });
36
37    let result = client.chat_completion(req).await?;
38    println!("Content: {:?}", result.choices[0].message.content);
39
40    // Example 2: Using reasoning with max_tokens
41    let mut req2 = ChatCompletionRequest::new(
42        "anthropic/claude-4-sonnet".to_string(), // Claude model that supports max_tokens
43        vec![chat_completion::ChatCompletionMessage {
44            role: chat_completion::MessageRole::user,
45            content: chat_completion::Content::Text(String::from(
46                "What's the most efficient sorting algorithm?",
47            )),
48            name: None,
49            tool_calls: None,
50            tool_call_id: None,
51        }],
52    );
53
54    // Set reasoning with max_tokens
55    req2.reasoning = Some(Reasoning {
56        mode: Some(ReasoningMode::MaxTokens { max_tokens: 2000 }),
57        exclude: None,
58        enabled: None,
59    });
60
61    let result2 = client.chat_completion(req2).await?;
62    println!("Content: {:?}", result2.choices[0].message.content);
63
64    Ok(())
65}
examples/function_call.rs (line 66)
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25    let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
26    let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
27
28    let mut properties = HashMap::new();
29    properties.insert(
30        "coin".to_string(),
31        Box::new(types::JSONSchemaDefine {
32            schema_type: Some(types::JSONSchemaType::String),
33            description: Some("The cryptocurrency to get the price of".to_string()),
34            ..Default::default()
35        }),
36    );
37
38    let req = ChatCompletionRequest::new(
39        GPT4_O.to_string(),
40        vec![ChatCompletionMessage {
41            role: MessageRole::user,
42            content: Content::Text(String::from("What is the price of Ethereum?")),
43            name: None,
44            tool_calls: None,
45            tool_call_id: None,
46        }],
47    )
48    .tools(vec![Tool {
49        r#type: ToolType::Function,
50        function: types::Function {
51            name: String::from("get_coin_price"),
52            description: Some(String::from("Get the price of a cryptocurrency")),
53            parameters: types::FunctionParameters {
54                schema_type: types::JSONSchemaType::Object,
55                properties: Some(properties),
56                required: Some(vec![String::from("coin")]),
57            },
58        },
59    }])
60    .tool_choice(ToolChoiceType::Auto);
61
62    // debug request json
63    // let serialized = serde_json::to_string(&req).unwrap();
64    // println!("{}", serialized);
65
66    let result = client.chat_completion(req).await?;
67
68    match result.choices[0].finish_reason {
69        None => {
70            println!("No finish_reason");
71            println!("{:?}", result.choices[0].message.content);
72        }
73        Some(FinishReason::stop) => {
74            println!("Stop");
75            println!("{:?}", result.choices[0].message.content);
76        }
77        Some(FinishReason::length) => {
78            println!("Length");
79        }
80        Some(FinishReason::tool_calls) => {
81            println!("ToolCalls");
82            #[derive(Deserialize, Serialize)]
83            struct Currency {
84                coin: String,
85            }
86            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
87            for tool_call in tool_calls {
88                let name = tool_call.function.name.clone().unwrap();
89                let arguments = tool_call.function.arguments.clone().unwrap();
90                let c: Currency = serde_json::from_str(&arguments)?;
91                let coin = c.coin;
92                if name == "get_coin_price" {
93                    let price = get_coin_price(&coin);
94                    println!("{coin} price: {price}");
95                }
96            }
97        }
98        Some(FinishReason::content_filter) => {
99            println!("ContentFilter");
100        }
101        Some(FinishReason::null) => {
102            println!("Null");
103        }
104    }
105    Ok(())
106}
examples/function_call_role.rs (line 57)
20async fn main() -> Result<(), Box<dyn std::error::Error>> {
21    let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
22    let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
23
24    let mut properties = HashMap::new();
25    properties.insert(
26        "coin".to_string(),
27        Box::new(types::JSONSchemaDefine {
28            schema_type: Some(types::JSONSchemaType::String),
29            description: Some("The cryptocurrency to get the price of".to_string()),
30            ..Default::default()
31        }),
32    );
33
34    let req = ChatCompletionRequest::new(
35        GPT4_O.to_string(),
36        vec![chat_completion::ChatCompletionMessage {
37            role: chat_completion::MessageRole::user,
38            content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
39            name: None,
40            tool_calls: None,
41            tool_call_id: None,
42        }],
43    )
44    .tools(vec![chat_completion::Tool {
45        r#type: chat_completion::ToolType::Function,
46        function: types::Function {
47            name: String::from("get_coin_price"),
48            description: Some(String::from("Get the price of a cryptocurrency")),
49            parameters: types::FunctionParameters {
50                schema_type: types::JSONSchemaType::Object,
51                properties: Some(properties),
52                required: Some(vec![String::from("coin")]),
53            },
54        },
55    }]);
56
57    let result = client.chat_completion(req).await?;
58
59    match result.choices[0].finish_reason {
60        None => {
61            println!("No finish_reason");
62            println!("{:?}", result.choices[0].message.content);
63        }
64        Some(chat_completion::FinishReason::stop) => {
65            println!("Stop");
66            println!("{:?}", result.choices[0].message.content);
67        }
68        Some(chat_completion::FinishReason::length) => {
69            println!("Length");
70        }
71        Some(chat_completion::FinishReason::tool_calls) => {
72            println!("ToolCalls");
73            #[derive(Deserialize, Serialize)]
74            struct Currency {
75                coin: String,
76            }
77            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
78            for tool_call in tool_calls {
79                let function_call = &tool_call.function;
80                let arguments = function_call.arguments.clone().unwrap();
81                let c: Currency = serde_json::from_str(&arguments)?;
82                let coin = c.coin;
83                println!("coin: {coin}");
84                let price = get_coin_price(&coin);
85                println!("price: {price}");
86
87                let req = ChatCompletionRequest::new(
88                    GPT4_O.to_string(),
89                    vec![
90                        chat_completion::ChatCompletionMessage {
91                            role: chat_completion::MessageRole::user,
92                            content: chat_completion::Content::Text(String::from(
93                                "What is the price of Ethereum?",
94                            )),
95                            name: None,
96                            tool_calls: None,
97                            tool_call_id: None,
98                        },
99                        chat_completion::ChatCompletionMessage {
100                            role: chat_completion::MessageRole::function,
101                            content: chat_completion::Content::Text({
102                                let price = get_coin_price(&coin);
103                                format!("{{\"price\": {price}}}")
104                            }),
105                            name: Some(String::from("get_coin_price")),
106                            tool_calls: None,
107                            tool_call_id: None,
108                        },
109                    ],
110                );
111
112                let result = client.chat_completion(req).await?;
113                println!("{:?}", result.choices[0].message.content);
114            }
115        }
116        Some(chat_completion::FinishReason::content_filter) => {
117            println!("ContentFilter");
118        }
119        Some(chat_completion::FinishReason::null) => {
120            println!("Null");
121        }
122    }
123    Ok(())
124}
Source

pub async fn chat_completion_stream( &mut self, req: ChatCompletionStreamRequest, ) -> Result<impl Stream<Item = ChatCompletionStreamResponse>, APIError>

Examples found in repository?
examples/chat_completion_stream.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 req = ChatCompletionStreamRequest::new(
16        GPT4_O_MINI.to_string(),
17        vec![chat_completion::ChatCompletionMessage {
18            role: chat_completion::MessageRole::user,
19            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
20            name: None,
21            tool_calls: None,
22            tool_call_id: None,
23        }],
24    );
25
26    let mut result = client.chat_completion_stream(req).await?;
27    while let Some(response) = result.next().await {
28        match response.clone() {
29            ChatCompletionStreamResponse::ToolCall(toolcalls) => {
30                println!("Tool Call: {:?}", toolcalls);
31            }
32            ChatCompletionStreamResponse::Content(content) => {
33                println!("Content: {:?}", content);
34            }
35            ChatCompletionStreamResponse::Done => {
36                println!("Done");
37            }
38        }
39    }
40
41    Ok(())
42}
Source

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}
Source

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}
Source

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}
Source

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}
Source

pub async fn create_fine_tuning_job( &mut self, req: CreateFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>

Source

pub async fn list_fine_tuning_jobs( &mut self, ) -> Result<FineTuningPagination<FineTuningJobObject>, APIError>

Source

pub async fn list_fine_tuning_job_events( &mut self, req: ListFineTuningJobEventsRequest, ) -> Result<FineTuningPagination<FineTuningJobEvent>, APIError>

Source

pub async fn retrieve_fine_tuning_job( &mut self, req: RetrieveFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>

Source

pub async fn cancel_fine_tuning_job( &mut self, req: CancelFineTuningJobRequest, ) -> Result<FineTuningJobObject, APIError>

Source

pub async fn create_moderation( &mut self, req: CreateModerationRequest, ) -> Result<CreateModerationResponse, APIError>

Source

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}
Source

pub async fn retrieve_assistant( &mut self, assistant_id: String, ) -> Result<AssistantObject, APIError>

Source

pub async fn modify_assistant( &mut self, assistant_id: String, req: AssistantRequest, ) -> Result<AssistantObject, APIError>

Source

pub async fn delete_assistant( &mut self, assistant_id: String, ) -> Result<DeletionStatus, APIError>

Source

pub async fn list_assistant( &mut self, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListAssistant, APIError>

Source

pub async fn create_assistant_file( &mut self, assistant_id: String, req: AssistantFileRequest, ) -> Result<AssistantFileObject, APIError>

Source

pub async fn retrieve_assistant_file( &mut self, assistant_id: String, file_id: String, ) -> Result<AssistantFileObject, APIError>

Source

pub async fn delete_assistant_file( &mut self, assistant_id: String, file_id: String, ) -> Result<DeletionStatus, APIError>

Source

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>

Source

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}
Source

pub async fn retrieve_thread( &mut self, thread_id: String, ) -> Result<ThreadObject, APIError>

Source

pub async fn modify_thread( &mut self, thread_id: String, req: ModifyThreadRequest, ) -> Result<ThreadObject, APIError>

Source

pub async fn delete_thread( &mut self, thread_id: String, ) -> Result<DeletionStatus, APIError>

Source

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}
Source

pub async fn retrieve_message( &mut self, thread_id: String, message_id: String, ) -> Result<MessageObject, APIError>

Source

pub async fn modify_message( &mut self, thread_id: String, message_id: String, req: ModifyMessageRequest, ) -> Result<MessageObject, APIError>

Source

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}
Source

pub async fn retrieve_message_file( &mut self, thread_id: String, message_id: String, file_id: String, ) -> Result<MessageFileObject, APIError>

Source

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>

Source

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}
Source

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}
Source

pub async fn modify_run( &mut self, thread_id: String, run_id: String, req: ModifyRunRequest, ) -> Result<RunObject, APIError>

Source

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>

Source

pub async fn cancel_run( &mut self, thread_id: String, run_id: String, ) -> Result<RunObject, APIError>

Source

pub async fn create_thread_and_run( &mut self, req: CreateThreadAndRunRequest, ) -> Result<RunObject, APIError>

Source

pub async fn retrieve_run_step( &mut self, thread_id: String, run_id: String, step_id: String, ) -> Result<RunStepObject, APIError>

Source

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>

Source

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}
Source

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}
Source

pub async fn cancel_batch( &mut self, batch_id: String, ) -> Result<BatchResponse, APIError>

Source

pub async fn list_batch( &mut self, after: Option<String>, limit: Option<i64>, ) -> Result<ListBatchResponse, APIError>

Source

pub async fn list_models(&mut self) -> Result<ModelsResponse, APIError>

Examples found in repository?
examples/openrouter_models.rs (line 12)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
7    let mut client = OpenAIClient::builder()
8        .with_endpoint("https://openrouter.ai/api/v1")
9        .with_api_key(api_key)
10        .build()?;
11
12    let result = client.list_models().await?;
13    let models = result.data;
14
15    for model in models {
16        println!("Model id: {:?}", model.id);
17    }
18
19    Ok(())
20}
More examples
Hide additional examples
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}
Source

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}
Source

pub async fn delete_model( &mut self, model_id: String, ) -> Result<DeletionStatus, APIError>

Trait Implementations§

Source§

impl Debug for OpenAIClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,