Struct Client

Source
pub struct Client {
    pub endpoint: String,
    pub api_key: String,
    pub client: Client,
}
Expand description

The Client struct for interacting with the OpenAI API.

Fields§

§endpoint: String

API endpoint URL.

§api_key: String

API key for authentication.

§client: Client

Reqwest client for making HTTP requests.

Implementations§

Source§

impl Client

Source

pub fn from_env() -> Result<Self, APIError>

Creates a new Client instance from environment variables.

Examples found in repository?
examples/chat_completion.rs (line 5)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let client = Client::from_env().unwrap();
6    let req = "What is bitcoin?".into();
7    let result = client.chat_completion(req).await?;
8
9    println!("Content: {:?}", result.get_choice());
10    println!("Response Headers: {:?}", result.headers);
11
12    Ok(())
13}
More examples
Hide additional examples
examples/embedding.rs (line 9)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let client = Client::from_env().unwrap();
10
11    let mut req = EmbeddingRequest::new(
12        Model::Embedding(EmbeddingsModels::TextEmbeddingAda002),
13        "story 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/text_to_speech.rs (line 6)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    let client = Client::from_env().unwrap();
7
8    let req = AudioSpeechRequest::new(
9        TTS_1.to_string(),
10        String::from("Money is not problem, Problem is no money"),
11        audio::VOICE_ALLOY.to_string(),
12        String::from("problem.mp3"),
13    );
14
15    let result = client.audio_speech(req).await?;
16    println!("{:?}", result);
17
18    Ok(())
19}
examples/completion.rs (line 9)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let client = Client::from_env().unwrap();
10
11    let req = CompletionRequest::new(
12        Model::GPT3(GPT3::GPT35Turbo),
13        String::from("What is Bitcoin?"),
14    )
15    .max_tokens(3000)
16    .temperature(0.9)
17    .top_p(1.0)
18    .stop(vec![String::from(" Human:"), String::from(" AI:")])
19    .presence_penalty(0.6)
20    .frequency_penalty(0.0);
21
22    let result = client.completion(req).await?;
23    println!("{:}", result.choices[0].text);
24
25    Ok(())
26}
examples/vision.rs (line 10)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let client = Client::from_env().unwrap();
11
12    let req = ChatCompletionRequest::new_multi(
13        Model::GPT4(GPT4::GPT40125Preview),
14        vec![chat_completion::ChatCompletionMessage {
15            role: 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        }],
34    );
35
36    let result = client.chat_completion(req).await?;
37    println!("{:?}", result.choices[0].message.content);
38
39    Ok(())
40}
examples/assistant.rs (line 14)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

pub fn new(api_key: String) -> Result<Self, APIError>

Creates a new Client instance with the given API key.

Source

pub async fn post<T: Serialize>( &self, path: &str, params: &T, ) -> Result<Response, APIError>

Sends a POST request with the given path and parameters.

Source

pub async fn get(&self, path: &str) -> Result<Response, APIError>

Sends a GET request to the given path.

Source

pub async fn delete(&self, path: &str) -> Result<Response, APIError>

Sends a DELETE request to the given path.

Source

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

Sends a completion request and returns the response.

Examples found in repository?
examples/completion.rs (line 22)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let client = Client::from_env().unwrap();
10
11    let req = CompletionRequest::new(
12        Model::GPT3(GPT3::GPT35Turbo),
13        String::from("What is Bitcoin?"),
14    )
15    .max_tokens(3000)
16    .temperature(0.9)
17    .top_p(1.0)
18    .stop(vec![String::from(" Human:"), String::from(" AI:")])
19    .presence_penalty(0.6)
20    .frequency_penalty(0.0);
21
22    let result = client.completion(req).await?;
23    println!("{:}", result.choices[0].text);
24
25    Ok(())
26}
Source

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

Sends an edit request and returns the response.

Source

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

Sends an image generation request and returns the response.

Source

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

Sends an image edit request and returns the response.

Source

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

Sends an image variation request and returns the response.

Source

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

Sends an embedding request and returns the response.

Examples found in repository?
examples/embedding.rs (line 17)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let client = Client::from_env().unwrap();
10
11    let mut req = EmbeddingRequest::new(
12        Model::Embedding(EmbeddingsModels::TextEmbeddingAda002),
13        "story 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(&self) -> Result<FileListResponse, APIError>

Retrieves a list of files.

Source

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

Uploads a file and returns the response.

Source

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

Deletes a file and returns the response.

Source

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

Retrieves a file’s metadata and returns the response.

Source

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

Retrieves the content of a file and returns the response.

Source

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

Sends a chat completion request and returns the response.

Examples found in repository?
examples/chat_completion.rs (line 7)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let client = Client::from_env().unwrap();
6    let req = "What is bitcoin?".into();
7    let result = client.chat_completion(req).await?;
8
9    println!("Content: {:?}", result.get_choice());
10    println!("Response Headers: {:?}", result.headers);
11
12    Ok(())
13}
More examples
Hide additional examples
examples/vision.rs (line 36)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let client = Client::from_env().unwrap();
11
12    let req = ChatCompletionRequest::new_multi(
13        Model::GPT4(GPT4::GPT40125Preview),
14        vec![chat_completion::ChatCompletionMessage {
15            role: 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        }],
34    );
35
36    let result = client.chat_completion(req).await?;
37    println!("{:?}", result.choices[0].message.content);
38
39    Ok(())
40}
examples/function_call.rs (line 58)
23async fn main() -> Result<(), Box<dyn std::error::Error>> {
24    let client = Client::from_env().unwrap();
25
26    let mut properties = HashMap::new();
27    properties.insert(
28        "coin".to_string(),
29        Box::new(JSONSchemaDefine {
30            schema_type: Some(JSONSchemaType::String),
31            description: Some("The cryptocurrency to get the price of".to_string()),
32            ..Default::default()
33        }),
34    );
35
36    let req = ChatCompletionRequest::new_multi(
37        Model::GPT3(GPT3::GPT35Turbo),
38        vec![ChatCompletionMessage {
39            role: MessageRole::User,
40            content: Content::Text(String::from("What is the price of Ethereum?")),
41            name: None,
42        }],
43    )
44    .tools(vec![Tool {
45        r#type: ToolType::Function,
46        function: Function {
47            name: String::from("get_coin_price"),
48            description: Some(String::from("Get the price of a cryptocurrency")),
49            parameters: FunctionParameters {
50                schema_type: JSONSchemaType::Object,
51                properties: Some(properties),
52                required: Some(vec![String::from("coin")]),
53            },
54        },
55    }])
56    .tool_choice(ToolChoiceType::Auto);
57
58    let result = client.chat_completion(req).await?;
59
60    match result.choices[0].finish_reason {
61        None => {
62            println!("No finish_reason");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(FinishReason::stop) => {
66            println!("Stop");
67            println!("{:?}", result.choices[0].message.content);
68        }
69        Some(FinishReason::length) => {
70            println!("Length");
71        }
72        Some(FinishReason::tool_calls) => {
73            println!("ToolCalls");
74            #[derive(Deserialize, Serialize)]
75            struct Currency {
76                coin: String,
77            }
78            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
79            for tool_call in tool_calls {
80                let name = tool_call.function.name.clone().unwrap();
81                let arguments = tool_call.function.arguments.clone().unwrap();
82                let c: Currency = serde_json::from_str(&arguments)?;
83                let coin = c.coin;
84                if name == "get_coin_price" {
85                    let price = get_coin_price(&coin);
86                    println!("{} price: {}", coin, price);
87                }
88            }
89        }
90        Some(FinishReason::content_filter) => {
91            println!("ContentFilter");
92        }
93        Some(FinishReason::null) => {
94            println!("Null");
95        }
96    }
97    Ok(())
98}
examples/function_call_role.rs (line 54)
20async fn main() -> Result<(), Box<dyn std::error::Error>> {
21    let client = Client::from_env().unwrap();
22
23    let mut properties = HashMap::new();
24    properties.insert(
25        "coin".to_string(),
26        Box::new(chat_completion::JSONSchemaDefine {
27            schema_type: Some(chat_completion::JSONSchemaType::String),
28            description: Some("The cryptocurrency to get the price of".to_string()),
29            ..Default::default()
30        }),
31    );
32
33    let req = ChatCompletionRequest::new_multi(
34        Model::GPT3(GPT3::GPT35Turbo),
35        vec![chat_completion::ChatCompletionMessage {
36            role: MessageRole::User,
37            content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
38            name: None,
39        }],
40    )
41    .tools(vec![chat_completion::Tool {
42        r#type: chat_completion::ToolType::Function,
43        function: chat_completion::Function {
44            name: String::from("get_coin_price"),
45            description: Some(String::from("Get the price of a cryptocurrency")),
46            parameters: chat_completion::FunctionParameters {
47                schema_type: chat_completion::JSONSchemaType::Object,
48                properties: Some(properties),
49                required: Some(vec![String::from("coin")]),
50            },
51        },
52    }]);
53
54    let result = client.chat_completion(req).await?;
55
56    match result.choices[0].finish_reason {
57        None => {
58            println!("No finish_reason");
59            println!("{:?}", result.choices[0].message.content);
60        }
61        Some(chat_completion::FinishReason::stop) => {
62            println!("Stop");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(chat_completion::FinishReason::length) => {
66            println!("Length");
67        }
68        Some(chat_completion::FinishReason::tool_calls) => {
69            println!("ToolCalls");
70            #[derive(Deserialize, Serialize)]
71            struct Currency {
72                coin: String,
73            }
74            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
75            for tool_call in tool_calls {
76                let function_call = &tool_call.function;
77                let arguments = function_call.arguments.clone().unwrap();
78                let c: Currency = serde_json::from_str(&arguments)?;
79                let coin = c.coin;
80                println!("coin: {}", coin);
81                let price = get_coin_price(&coin);
82                println!("price: {}", price);
83
84                let req = ChatCompletionRequest::new_multi(
85                    Model::GPT3(GPT3::GPT35Turbo),
86                    vec![
87                        chat_completion::ChatCompletionMessage {
88                            role: MessageRole::User,
89                            content: chat_completion::Content::Text(String::from(
90                                "What is the price of Ethereum?",
91                            )),
92                            name: None,
93                        },
94                        chat_completion::ChatCompletionMessage {
95                            role: MessageRole::Function,
96                            content: chat_completion::Content::Text({
97                                let price = get_coin_price(&coin);
98                                format!("{{\"price\": {}}}", price)
99                            }),
100                            name: Some(String::from("get_coin_price")),
101                        },
102                    ],
103                );
104
105                let result = client.chat_completion(req).await?;
106                println!("{:?}", result.choices[0].message.content);
107            }
108        }
109        Some(chat_completion::FinishReason::content_filter) => {
110            println!("ContentFilter");
111        }
112        Some(chat_completion::FinishReason::null) => {
113            println!("Null");
114        }
115    }
116    Ok(())
117}
Source

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

Sends an audio transcription request and returns the response.

Source

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

Sends an audio translation request and returns the response.

Source

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

Sends an audio speech request, saves the response to a file, and returns the response.

Examples found in repository?
examples/text_to_speech.rs (line 15)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    let client = Client::from_env().unwrap();
7
8    let req = AudioSpeechRequest::new(
9        TTS_1.to_string(),
10        String::from("Money is not problem, Problem is no money"),
11        audio::VOICE_ALLOY.to_string(),
12        String::from("problem.mp3"),
13    );
14
15    let result = client.audio_speech(req).await?;
16    println!("{:?}", result);
17
18    Ok(())
19}
Source

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

Creates a fine-tuning job and returns the response.

Source

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

Lists fine-tuning jobs and returns the response.

Source

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

Lists fine-tuning job events and returns the response.

Source

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

Retrieves a fine-tuning job and returns the response.

Source

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

Cancels a fine-tuning job and returns the response.

Source

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

Creates a moderation request and returns the response.

Source

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

Creates an assistant and returns the response.

Examples found in repository?
examples/assistant.rs (line 27)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

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

Retrieves an assistant and returns the response.

Source

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

Modifies an assistant and returns the response.

Source

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

Deletes an assistant and returns the response.

Source

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

Lists assistants and returns the response.

Source

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

Creates an assistant file and returns the response.

Source

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

Retrieves an assistant file and returns the response.

Source

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

Deletes an assistant file and returns the response.

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>

Lists assistant files and returns the response.

Source

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

Creates a thread and returns the response.

Examples found in repository?
examples/assistant.rs (line 31)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

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

Retrieves a thread and returns the response.

Source

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

Modifies a thread and returns the response.

Source

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

Deletes a thread and returns the response.

Source

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

Creates a message in a thread and returns the response.

Examples found in repository?
examples/assistant.rs (line 40)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

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

Retrieves a message in a thread and returns the response.

Source

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

Modifies a message in a thread and returns the response.

Source

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

Lists messages in a thread and returns the response.

Examples found in repository?
examples/assistant.rs (line 59)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

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

Retrieves a file associated with a message and returns the response.

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>

Lists files associated with a message and returns the response.

Source

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

Creates a run in a thread and returns the response.

Examples found in repository?
examples/assistant.rs (line 45)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

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

Retrieves a run in a thread and returns the response.

Examples found in repository?
examples/assistant.rs (line 49)
13async fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let client = Client::from_env().unwrap();
15
16    let mut tools = HashMap::new();
17    tools.insert("type".to_string(), "code_interpreter".to_string());
18
19    let req = AssistantRequest::new(Model::GPT4(GPT4::GPT40125Preview));
20    let req = req
21        .clone()
22        .description("this is a test assistant".to_string());
23    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());
24    let req = req.clone().tools(vec![tools]);
25    println!("{:?}", req);
26
27    let result = client.create_assistant(req).await?;
28    println!("{:?}", result.id);
29
30    let thread_req = CreateThreadRequest::new();
31    let thread_result = client.create_thread(thread_req).await?;
32    println!("{:?}", thread_result.id.clone());
33
34    let message_req = CreateMessageRequest::new(
35        MessageRole::User,
36        "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
37    );
38
39    let message_result = client
40        .create_message(thread_result.id.clone(), message_req)
41        .await?;
42    println!("{:?}", message_result.id.clone());
43
44    let run_req = CreateRunRequest::new(result.id);
45    let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
46
47    loop {
48        let run_result = client
49            .retrieve_run(thread_result.id.clone(), run_result.id.clone())
50            .await?;
51        if run_result.status == "completed" {
52            break;
53        } else {
54            println!("waiting...");
55            std::thread::sleep(std::time::Duration::from_secs(1));
56        }
57    }
58
59    let list_message_result = client.list_messages(thread_result.id.clone()).await?;
60    for data in list_message_result.data {
61        for content in data.content {
62            println!(
63                "{:?}: {:?} {:?}",
64                data.role, content.text.value, content.text.annotations
65            );
66        }
67    }
68
69    Ok(())
70}
Source

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

Modifies a run in a thread and returns the response.

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>

Lists runs in a thread and returns the response.

Source

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

Cancels a run in a thread and returns the response.

Source

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

Creates a thread and a run and returns the response.

Source

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

Retrieves a step in a run and returns the response.

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>

Lists steps in a run and returns the response.

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

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

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