Struct openai_api_rs::v1::api::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 file_upload( &self, req: FileUploadRequest, ) -> Result<FileUploadResponse, APIError>

source

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

source

pub async fn file_retrieve( &self, req: FileRetrieveRequest, ) -> Result<FileRetrieveResponse, APIError>

source

pub async fn file_retrieve_content( &self, req: FileRetrieveContentRequest, ) -> Result<FileRetrieveContentResponse, APIError>

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_VISION_PREVIEW.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 59)
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::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: chat_completion::Function {
            name: String::from("get_coin_price"),
            description: Some(String::from("Get the price of a cryptocurrency")),
            parameters: chat_completion::FunctionParameters {
                schema_type: chat_completion::JSONSchemaType::Object,
                properties: Some(properties),
                required: Some(vec![String::from("coin")]),
            },
        },
    }])
    .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 54)
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::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: chat_completion::Function {
            name: String::from("get_coin_price"),
            description: Some(String::from("Get the price of a cryptocurrency")),
            parameters: chat_completion::FunctionParameters {
                schema_type: chat_completion::JSONSchemaType::Object,
                properties: Some(properties),
                required: Some(vec![String::from("coin")]),
            },
        },
    }]);

    let result = client.chat_completion(req).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>

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, U> TryFrom<U> for T
where U: Into<T>,

§

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>,

§

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