openai_api_rs::v1::api

Struct OpenAIClient

Source
pub struct OpenAIClient {
    pub api_endpoint: String,
    pub api_key: String,
    pub organization: Option<String>,
    pub proxy: Option<String>,
    pub timeout: Option<u64>,
}

Fields§

§api_endpoint: String§api_key: String§organization: Option<String>§proxy: Option<String>§timeout: Option<u64>

Implementations§

Source§

impl OpenAIClient

Source

pub fn new(api_key: String) -> Self

Examples found in repository?
examples/audio_translations.rs (line 7)
6
7
8
9
10
11
12
13
14
15
16
17
18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = AudioTranslationRequest::new(
        "examples/data/problem_cn.mp3".to_string(),
        WHISPER_1.to_string(),
    );

    let result = client.audio_translation(req).await?;
    println!("{:?}", result);

    Ok(())
}
More examples
Hide additional examples
examples/audio_transcriptions.rs (line 7)
6
7
8
9
10
11
12
13
14
15
16
17
18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = AudioTranscriptionRequest::new(
        "examples/data/problem.mp3".to_string(),
        WHISPER_1.to_string(),
    );

    let result = client.audio_transcription(req).await?;
    println!("{:?}", result);

    Ok(())
}
examples/embedding.rs (line 8)
7
8
9
10
11
12
13
14
15
16
17
18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut req =
        EmbeddingRequest::new(TEXT_EMBEDDING_3_SMALL.to_string(), "story time".to_string());
    req.dimensions = Some(10);

    let result = client.embedding(req).await?;
    println!("{:?}", result.data);

    Ok(())
}
examples/audio_speech.rs (line 7)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = AudioSpeechRequest::new(
        TTS_1.to_string(),
        String::from("Money is not the problem, the problem is no money."),
        audio::VOICE_ALLOY.to_string(),
        String::from("examples/data/problem.mp3"),
    );

    let result = client.audio_speech(req).await?;
    println!("{:?}", result);

    Ok(())
}
examples/completion.rs (line 7)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = CompletionRequest::new(
        completion::GPT3_TEXT_DAVINCI_003.to_string(),
        String::from("What is Bitcoin?"),
    )
    .max_tokens(3000)
    .temperature(0.9)
    .top_p(1.0)
    .stop(vec![String::from(" Human:"), String::from(" AI:")])
    .presence_penalty(0.6)
    .frequency_penalty(0.0);

    let result = client.completion(req).await?;
    println!("{:}", result.choices[0].text);

    Ok(())
}
examples/chat_completion.rs (line 8)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = ChatCompletionRequest::new(
        GPT4_O_MINI.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    );

    let result = client.chat_completion(req).await?;
    println!("Content: {:?}", result.choices[0].message.content);
    println!("Response Headers: {:?}", result.headers);

    Ok(())
}
Source

pub fn new_with_endpoint(api_endpoint: String, api_key: String) -> Self

Source

pub fn new_with_organization(api_key: String, organization: String) -> Self

Source

pub fn new_with_proxy(api_key: String, proxy: String) -> Self

Source

pub fn new_with_timeout(api_key: String, timeout: u64) -> Self

Source

pub async fn completion( &self, req: CompletionRequest, ) -> Result<CompletionResponse, APIError>

Examples found in repository?
examples/completion.rs (line 20)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = CompletionRequest::new(
        completion::GPT3_TEXT_DAVINCI_003.to_string(),
        String::from("What is Bitcoin?"),
    )
    .max_tokens(3000)
    .temperature(0.9)
    .top_p(1.0)
    .stop(vec![String::from(" Human:"), String::from(" AI:")])
    .presence_penalty(0.6)
    .frequency_penalty(0.0);

    let result = client.completion(req).await?;
    println!("{:}", result.choices[0].text);

    Ok(())
}
Source

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

Source

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

Source

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

Source

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

Source

pub async fn embedding( &self, req: EmbeddingRequest, ) -> Result<EmbeddingResponse, APIError>

Examples found in repository?
examples/embedding.rs (line 14)
7
8
9
10
11
12
13
14
15
16
17
18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut req =
        EmbeddingRequest::new(TEXT_EMBEDDING_3_SMALL.to_string(), "story time".to_string());
    req.dimensions = Some(10);

    let result = client.embedding(req).await?;
    println!("{:?}", result.data);

    Ok(())
}
Source

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

Source

pub async fn upload_file( &self, req: FileUploadRequest, ) -> Result<FileUploadResponse, APIError>

Examples found in repository?
examples/batch.rs (line 19)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = FileUploadRequest::new(
        "examples/data/batch_request.json".to_string(),
        "batch".to_string(),
    );

    let result = client.upload_file(req).await?;
    println!("File id: {:?}", result.id);

    let input_file_id = result.id;
    let req = CreateBatchRequest::new(
        input_file_id.clone(),
        "/v1/chat/completions".to_string(),
        "24h".to_string(),
    );

    let result = client.create_batch(req).await?;
    println!("Batch id: {:?}", result.id);

    let batch_id = result.id;
    let result = client.retrieve_batch(batch_id.to_string()).await?;
    println!("Batch status: {:?}", result.status);

    // sleep 30 seconds
    println!("Sleeping for 30 seconds...");
    tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;

    let result = client.retrieve_batch(batch_id.to_string()).await?;

    let file_id = result.output_file_id.unwrap();
    let result = client.retrieve_file_content(file_id).await?;
    let s = match str::from_utf8(&result) {
        Ok(v) => v.to_string(),
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };
    let json_value: Value = from_str(&s)?;
    let result_json = to_string_pretty(&json_value)?;

    let output_file_path = "examples/data/batch_result.json";
    let mut file = File::create(output_file_path)?;
    file.write_all(result_json.as_bytes())?;

    println!("File writed to {:?}", output_file_path);

    Ok(())
}
Source

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

Source

pub async fn retrieve_file( &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 43)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = FileUploadRequest::new(
        "examples/data/batch_request.json".to_string(),
        "batch".to_string(),
    );

    let result = client.upload_file(req).await?;
    println!("File id: {:?}", result.id);

    let input_file_id = result.id;
    let req = CreateBatchRequest::new(
        input_file_id.clone(),
        "/v1/chat/completions".to_string(),
        "24h".to_string(),
    );

    let result = client.create_batch(req).await?;
    println!("Batch id: {:?}", result.id);

    let batch_id = result.id;
    let result = client.retrieve_batch(batch_id.to_string()).await?;
    println!("Batch status: {:?}", result.status);

    // sleep 30 seconds
    println!("Sleeping for 30 seconds...");
    tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;

    let result = client.retrieve_batch(batch_id.to_string()).await?;

    let file_id = result.output_file_id.unwrap();
    let result = client.retrieve_file_content(file_id).await?;
    let s = match str::from_utf8(&result) {
        Ok(v) => v.to_string(),
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };
    let json_value: Value = from_str(&s)?;
    let result_json = to_string_pretty(&json_value)?;

    let output_file_path = "examples/data/batch_result.json";
    let mut file = File::create(output_file_path)?;
    file.write_all(result_json.as_bytes())?;

    println!("File writed to {:?}", output_file_path);

    Ok(())
}
Source

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

Examples found in repository?
examples/chat_completion.rs (line 21)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = ChatCompletionRequest::new(
        GPT4_O_MINI.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    );

    let result = client.chat_completion(req).await?;
    println!("Content: {:?}", result.choices[0].message.content);
    println!("Response Headers: {:?}", result.headers);

    Ok(())
}
More examples
Hide additional examples
examples/vision.rs (line 36)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = ChatCompletionRequest::new(
        GPT4_O.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::ImageUrl(vec![
                chat_completion::ImageUrl {
                    r#type: chat_completion::ContentType::text,
                    text: Some(String::from("What's in this image?")),
                    image_url: None,
                },
                chat_completion::ImageUrl {
                    r#type: chat_completion::ContentType::image_url,
                    text: None,
                    image_url: Some(chat_completion::ImageUrlType {
                        url: String::from(
                            "https://upload.wikimedia.org/wikipedia/commons/5/50/Bitcoin.png",
                        ),
                    }),
                },
            ]),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    );

    let result = client.chat_completion(req).await?;
    println!("{:?}", result.choices[0].message.content);

    Ok(())
}
examples/function_call.rs (line 60)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(types::JSONSchemaDefine {
            schema_type: Some(types::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            ..Default::default()
        }),
    );

    let req = ChatCompletionRequest::new(
        GPT4_O.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    )
    .tools(vec![chat_completion::Tool {
        r#type: chat_completion::ToolType::Function,
        function: types::Function {
            name: String::from("get_coin_price"),
            description: Some(String::from("Get the price of a cryptocurrency")),
            parameters: types::FunctionParameters {
                schema_type: types::JSONSchemaType::Object,
                properties: Some(properties),
                required: Some(vec![String::from("coin")]),
            },
        },
    }])
    .tool_choice(chat_completion::ToolChoiceType::Auto);

    // debug request json
    // let serialized = serde_json::to_string(&req).unwrap();
    // println!("{}", serialized);

    let result = client.chat_completion(req).await?;

    match result.choices[0].finish_reason {
        None => {
            println!("No finish_reason");
            println!("{:?}", result.choices[0].message.content);
        }
        Some(chat_completion::FinishReason::stop) => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        Some(chat_completion::FinishReason::length) => {
            println!("Length");
        }
        Some(chat_completion::FinishReason::tool_calls) => {
            println!("ToolCalls");
            #[derive(Deserialize, Serialize)]
            struct Currency {
                coin: String,
            }
            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
            for tool_call in tool_calls {
                let name = tool_call.function.name.clone().unwrap();
                let arguments = tool_call.function.arguments.clone().unwrap();
                let c: Currency = serde_json::from_str(&arguments)?;
                let coin = c.coin;
                if name == "get_coin_price" {
                    let price = get_coin_price(&coin);
                    println!("{} price: {}", coin, price);
                }
            }
        }
        Some(chat_completion::FinishReason::content_filter) => {
            println!("ContentFilter");
        }
        Some(chat_completion::FinishReason::null) => {
            println!("Null");
        }
    }
    Ok(())
}
examples/function_call_role.rs (line 55)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(types::JSONSchemaDefine {
            schema_type: Some(types::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            ..Default::default()
        }),
    );

    let req = ChatCompletionRequest::new(
        GPT4_O.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    )
    .tools(vec![chat_completion::Tool {
        r#type: chat_completion::ToolType::Function,
        function: types::Function {
            name: String::from("get_coin_price"),
            description: Some(String::from("Get the price of a cryptocurrency")),
            parameters: types::FunctionParameters {
                schema_type: types::JSONSchemaType::Object,
                properties: Some(properties),
                required: Some(vec![String::from("coin")]),
            },
        },
    }]);

    let result = client.chat_completion(req).await?;

    match result.choices[0].finish_reason {
        None => {
            println!("No finish_reason");
            println!("{:?}", result.choices[0].message.content);
        }
        Some(chat_completion::FinishReason::stop) => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        Some(chat_completion::FinishReason::length) => {
            println!("Length");
        }
        Some(chat_completion::FinishReason::tool_calls) => {
            println!("ToolCalls");
            #[derive(Deserialize, Serialize)]
            struct Currency {
                coin: String,
            }
            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
            for tool_call in tool_calls {
                let function_call = &tool_call.function;
                let arguments = function_call.arguments.clone().unwrap();
                let c: Currency = serde_json::from_str(&arguments)?;
                let coin = c.coin;
                println!("coin: {}", coin);
                let price = get_coin_price(&coin);
                println!("price: {}", price);

                let req = ChatCompletionRequest::new(
                    GPT4_O.to_string(),
                    vec![
                        chat_completion::ChatCompletionMessage {
                            role: chat_completion::MessageRole::user,
                            content: chat_completion::Content::Text(String::from(
                                "What is the price of Ethereum?",
                            )),
                            name: None,
                            tool_calls: None,
                            tool_call_id: None,
                        },
                        chat_completion::ChatCompletionMessage {
                            role: chat_completion::MessageRole::function,
                            content: chat_completion::Content::Text({
                                let price = get_coin_price(&coin);
                                format!("{{\"price\": {}}}", price)
                            }),
                            name: Some(String::from("get_coin_price")),
                            tool_calls: None,
                            tool_call_id: None,
                        },
                    ],
                );

                let result = client.chat_completion(req).await?;
                println!("{:?}", result.choices[0].message.content);
            }
        }
        Some(chat_completion::FinishReason::content_filter) => {
            println!("ContentFilter");
        }
        Some(chat_completion::FinishReason::null) => {
            println!("Null");
        }
    }
    Ok(())
}
Source

pub async fn audio_transcription( &self, req: AudioTranscriptionRequest, ) -> Result<AudioTranscriptionResponse, APIError>

Examples found in repository?
examples/audio_transcriptions.rs (line 14)
6
7
8
9
10
11
12
13
14
15
16
17
18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = AudioTranscriptionRequest::new(
        "examples/data/problem.mp3".to_string(),
        WHISPER_1.to_string(),
    );

    let result = client.audio_transcription(req).await?;
    println!("{:?}", result);

    Ok(())
}
Source

pub async fn audio_translation( &self, req: AudioTranslationRequest, ) -> Result<AudioTranslationResponse, APIError>

Examples found in repository?
examples/audio_translations.rs (line 14)
6
7
8
9
10
11
12
13
14
15
16
17
18
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = AudioTranslationRequest::new(
        "examples/data/problem_cn.mp3".to_string(),
        WHISPER_1.to_string(),
    );

    let result = client.audio_translation(req).await?;
    println!("{:?}", result);

    Ok(())
}
Source

pub async fn audio_speech( &self, req: AudioSpeechRequest, ) -> Result<AudioSpeechResponse, APIError>

Examples found in repository?
examples/audio_speech.rs (line 16)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = AudioSpeechRequest::new(
        TTS_1.to_string(),
        String::from("Money is not the problem, the problem is no money."),
        audio::VOICE_ALLOY.to_string(),
        String::from("examples/data/problem.mp3"),
    );

    let result = client.audio_speech(req).await?;
    println!("{:?}", result);

    Ok(())
}
Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

pub async fn create_assistant( &self, req: AssistantRequest, ) -> Result<AssistantObject, APIError>

Examples found in repository?
examples/assistant.rs (line 25)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut tools = HashMap::new();
    tools.insert("type".to_string(), "code_interpreter".to_string());

    let req = AssistantRequest::new(GPT4_O.to_string());
    let req = req
        .clone()
        .description("this is a test assistant".to_string());
    let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
    let req = req.clone().tools(vec![tools]);
    println!("AssistantRequest: {:?}", req);

    let result = client.create_assistant(req).await?;
    println!("Create Assistant Result ID: {:?}", result.id);

    let thread_req = CreateThreadRequest::new();
    let thread_result = client.create_thread(thread_req).await?;
    println!("Create Thread Result ID: {:?}", thread_result.id.clone());

    let message_req = CreateMessageRequest::new(
        MessageRole::user,
        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
    );

    let message_result = client
        .create_message(thread_result.id.clone(), message_req)
        .await?;
    println!("Create Message Result ID: {:?}", message_result.id.clone());

    let run_req = CreateRunRequest::new(result.id);
    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
    println!("Create Run Result ID: {:?}", run_result.id.clone());

    loop {
        let run_result = client
            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
            .await
            .unwrap();
        if run_result.status == "completed" {
            break;
        } else {
            println!("waiting...");
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    let list_message_result = client
        .list_messages(thread_result.id.clone())
        .await
        .unwrap();
    for data in list_message_result.data {
        for content in data.content {
            println!(
                "{:?}: {:?} {:?}",
                data.role, content.text.value, content.text.annotations
            );
        }
    }

    Ok(())
}
Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

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

Source

pub async fn list_assistant_file( &self, assistant_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListAssistantFile, APIError>

Source

pub async fn create_thread( &self, req: CreateThreadRequest, ) -> Result<ThreadObject, APIError>

Examples found in repository?
examples/assistant.rs (line 29)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut tools = HashMap::new();
    tools.insert("type".to_string(), "code_interpreter".to_string());

    let req = AssistantRequest::new(GPT4_O.to_string());
    let req = req
        .clone()
        .description("this is a test assistant".to_string());
    let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
    let req = req.clone().tools(vec![tools]);
    println!("AssistantRequest: {:?}", req);

    let result = client.create_assistant(req).await?;
    println!("Create Assistant Result ID: {:?}", result.id);

    let thread_req = CreateThreadRequest::new();
    let thread_result = client.create_thread(thread_req).await?;
    println!("Create Thread Result ID: {:?}", thread_result.id.clone());

    let message_req = CreateMessageRequest::new(
        MessageRole::user,
        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
    );

    let message_result = client
        .create_message(thread_result.id.clone(), message_req)
        .await?;
    println!("Create Message Result ID: {:?}", message_result.id.clone());

    let run_req = CreateRunRequest::new(result.id);
    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
    println!("Create Run Result ID: {:?}", run_result.id.clone());

    loop {
        let run_result = client
            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
            .await
            .unwrap();
        if run_result.status == "completed" {
            break;
        } else {
            println!("waiting...");
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    let list_message_result = client
        .list_messages(thread_result.id.clone())
        .await
        .unwrap();
    for data in list_message_result.data {
        for content in data.content {
            println!(
                "{:?}: {:?} {:?}",
                data.role, content.text.value, content.text.annotations
            );
        }
    }

    Ok(())
}
Source

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

Source

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

Source

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

Source

pub async fn create_message( &self, thread_id: String, req: CreateMessageRequest, ) -> Result<MessageObject, APIError>

Examples found in repository?
examples/assistant.rs (line 38)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut tools = HashMap::new();
    tools.insert("type".to_string(), "code_interpreter".to_string());

    let req = AssistantRequest::new(GPT4_O.to_string());
    let req = req
        .clone()
        .description("this is a test assistant".to_string());
    let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
    let req = req.clone().tools(vec![tools]);
    println!("AssistantRequest: {:?}", req);

    let result = client.create_assistant(req).await?;
    println!("Create Assistant Result ID: {:?}", result.id);

    let thread_req = CreateThreadRequest::new();
    let thread_result = client.create_thread(thread_req).await?;
    println!("Create Thread Result ID: {:?}", thread_result.id.clone());

    let message_req = CreateMessageRequest::new(
        MessageRole::user,
        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
    );

    let message_result = client
        .create_message(thread_result.id.clone(), message_req)
        .await?;
    println!("Create Message Result ID: {:?}", message_result.id.clone());

    let run_req = CreateRunRequest::new(result.id);
    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
    println!("Create Run Result ID: {:?}", run_result.id.clone());

    loop {
        let run_result = client
            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
            .await
            .unwrap();
        if run_result.status == "completed" {
            break;
        } else {
            println!("waiting...");
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    let list_message_result = client
        .list_messages(thread_result.id.clone())
        .await
        .unwrap();
    for data in list_message_result.data {
        for content in data.content {
            println!(
                "{:?}: {:?} {:?}",
                data.role, content.text.value, content.text.annotations
            );
        }
    }

    Ok(())
}
Source

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

Source

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

Source

pub async fn list_messages( &self, thread_id: String, ) -> Result<ListMessage, APIError>

Examples found in repository?
examples/assistant.rs (line 60)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut tools = HashMap::new();
    tools.insert("type".to_string(), "code_interpreter".to_string());

    let req = AssistantRequest::new(GPT4_O.to_string());
    let req = req
        .clone()
        .description("this is a test assistant".to_string());
    let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
    let req = req.clone().tools(vec![tools]);
    println!("AssistantRequest: {:?}", req);

    let result = client.create_assistant(req).await?;
    println!("Create Assistant Result ID: {:?}", result.id);

    let thread_req = CreateThreadRequest::new();
    let thread_result = client.create_thread(thread_req).await?;
    println!("Create Thread Result ID: {:?}", thread_result.id.clone());

    let message_req = CreateMessageRequest::new(
        MessageRole::user,
        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
    );

    let message_result = client
        .create_message(thread_result.id.clone(), message_req)
        .await?;
    println!("Create Message Result ID: {:?}", message_result.id.clone());

    let run_req = CreateRunRequest::new(result.id);
    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
    println!("Create Run Result ID: {:?}", run_result.id.clone());

    loop {
        let run_result = client
            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
            .await
            .unwrap();
        if run_result.status == "completed" {
            break;
        } else {
            println!("waiting...");
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    let list_message_result = client
        .list_messages(thread_result.id.clone())
        .await
        .unwrap();
    for data in list_message_result.data {
        for content in data.content {
            println!(
                "{:?}: {:?} {:?}",
                data.role, content.text.value, content.text.annotations
            );
        }
    }

    Ok(())
}
Source

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

Source

pub async fn list_message_file( &self, thread_id: String, message_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListMessageFile, APIError>

Source

pub async fn create_run( &self, thread_id: String, req: CreateRunRequest, ) -> Result<RunObject, APIError>

Examples found in repository?
examples/assistant.rs (line 43)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut tools = HashMap::new();
    tools.insert("type".to_string(), "code_interpreter".to_string());

    let req = AssistantRequest::new(GPT4_O.to_string());
    let req = req
        .clone()
        .description("this is a test assistant".to_string());
    let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
    let req = req.clone().tools(vec![tools]);
    println!("AssistantRequest: {:?}", req);

    let result = client.create_assistant(req).await?;
    println!("Create Assistant Result ID: {:?}", result.id);

    let thread_req = CreateThreadRequest::new();
    let thread_result = client.create_thread(thread_req).await?;
    println!("Create Thread Result ID: {:?}", thread_result.id.clone());

    let message_req = CreateMessageRequest::new(
        MessageRole::user,
        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
    );

    let message_result = client
        .create_message(thread_result.id.clone(), message_req)
        .await?;
    println!("Create Message Result ID: {:?}", message_result.id.clone());

    let run_req = CreateRunRequest::new(result.id);
    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
    println!("Create Run Result ID: {:?}", run_result.id.clone());

    loop {
        let run_result = client
            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
            .await
            .unwrap();
        if run_result.status == "completed" {
            break;
        } else {
            println!("waiting...");
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    let list_message_result = client
        .list_messages(thread_result.id.clone())
        .await
        .unwrap();
    for data in list_message_result.data {
        for content in data.content {
            println!(
                "{:?}: {:?} {:?}",
                data.role, content.text.value, content.text.annotations
            );
        }
    }

    Ok(())
}
Source

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

Examples found in repository?
examples/assistant.rs (line 48)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut tools = HashMap::new();
    tools.insert("type".to_string(), "code_interpreter".to_string());

    let req = AssistantRequest::new(GPT4_O.to_string());
    let req = req
        .clone()
        .description("this is a test assistant".to_string());
    let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string());
    let req = req.clone().tools(vec![tools]);
    println!("AssistantRequest: {:?}", req);

    let result = client.create_assistant(req).await?;
    println!("Create Assistant Result ID: {:?}", result.id);

    let thread_req = CreateThreadRequest::new();
    let thread_result = client.create_thread(thread_req).await?;
    println!("Create Thread Result ID: {:?}", thread_result.id.clone());

    let message_req = CreateMessageRequest::new(
        MessageRole::user,
        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
    );

    let message_result = client
        .create_message(thread_result.id.clone(), message_req)
        .await?;
    println!("Create Message Result ID: {:?}", message_result.id.clone());

    let run_req = CreateRunRequest::new(result.id);
    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
    println!("Create Run Result ID: {:?}", run_result.id.clone());

    loop {
        let run_result = client
            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
            .await
            .unwrap();
        if run_result.status == "completed" {
            break;
        } else {
            println!("waiting...");
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    let list_message_result = client
        .list_messages(thread_result.id.clone())
        .await
        .unwrap();
    for data in list_message_result.data {
        for content in data.content {
            println!(
                "{:?}: {:?} {:?}",
                data.role, content.text.value, content.text.annotations
            );
        }
    }

    Ok(())
}
Source

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

Source

pub async fn list_run( &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( &self, thread_id: String, run_id: String, ) -> Result<RunObject, APIError>

Source

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

Source

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

Source

pub async fn list_run_step( &self, thread_id: String, run_id: String, limit: Option<i64>, order: Option<String>, after: Option<String>, before: Option<String>, ) -> Result<ListRunStep, APIError>

Source

pub async fn create_batch( &self, req: CreateBatchRequest, ) -> Result<BatchResponse, APIError>

Examples found in repository?
examples/batch.rs (line 29)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = FileUploadRequest::new(
        "examples/data/batch_request.json".to_string(),
        "batch".to_string(),
    );

    let result = client.upload_file(req).await?;
    println!("File id: {:?}", result.id);

    let input_file_id = result.id;
    let req = CreateBatchRequest::new(
        input_file_id.clone(),
        "/v1/chat/completions".to_string(),
        "24h".to_string(),
    );

    let result = client.create_batch(req).await?;
    println!("Batch id: {:?}", result.id);

    let batch_id = result.id;
    let result = client.retrieve_batch(batch_id.to_string()).await?;
    println!("Batch status: {:?}", result.status);

    // sleep 30 seconds
    println!("Sleeping for 30 seconds...");
    tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;

    let result = client.retrieve_batch(batch_id.to_string()).await?;

    let file_id = result.output_file_id.unwrap();
    let result = client.retrieve_file_content(file_id).await?;
    let s = match str::from_utf8(&result) {
        Ok(v) => v.to_string(),
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };
    let json_value: Value = from_str(&s)?;
    let result_json = to_string_pretty(&json_value)?;

    let output_file_path = "examples/data/batch_result.json";
    let mut file = File::create(output_file_path)?;
    file.write_all(result_json.as_bytes())?;

    println!("File writed to {:?}", output_file_path);

    Ok(())
}
Source

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

Examples found in repository?
examples/batch.rs (line 33)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = FileUploadRequest::new(
        "examples/data/batch_request.json".to_string(),
        "batch".to_string(),
    );

    let result = client.upload_file(req).await?;
    println!("File id: {:?}", result.id);

    let input_file_id = result.id;
    let req = CreateBatchRequest::new(
        input_file_id.clone(),
        "/v1/chat/completions".to_string(),
        "24h".to_string(),
    );

    let result = client.create_batch(req).await?;
    println!("Batch id: {:?}", result.id);

    let batch_id = result.id;
    let result = client.retrieve_batch(batch_id.to_string()).await?;
    println!("Batch status: {:?}", result.status);

    // sleep 30 seconds
    println!("Sleeping for 30 seconds...");
    tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;

    let result = client.retrieve_batch(batch_id.to_string()).await?;

    let file_id = result.output_file_id.unwrap();
    let result = client.retrieve_file_content(file_id).await?;
    let s = match str::from_utf8(&result) {
        Ok(v) => v.to_string(),
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };
    let json_value: Value = from_str(&s)?;
    let result_json = to_string_pretty(&json_value)?;

    let output_file_path = "examples/data/batch_result.json";
    let mut file = File::create(output_file_path)?;
    file.write_all(result_json.as_bytes())?;

    println!("File writed to {:?}", output_file_path);

    Ok(())
}
Source

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

Source

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

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