### Running the Function Call Example Source: https://docs.rs/openai-api-rs/latest/src/function_call_role/function_call_role.rs.html This command executes the function call example using Cargo. Ensure your OPENAI_API_KEY is set. ```bash OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example function_call_role ``` -------------------------------- ### Create Run Request Example Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/run/struct.CreateRunRequest.html This example demonstrates how to create a `CreateRunRequest` and use it to initiate a run for an assistant. It is part of a larger workflow involving assistant creation, thread creation, and message posting. ```rust 11async fn main() -> Result<(), Box> { 12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); 13 let client = OpenAIClient::builder().with_api_key(api_key).build()?; 14 15 let mut tools = HashMap::new(); 16 tools.insert("type".to_string(), "code_interpreter".to_string()); 17 18 let req = AssistantRequest::new(GPT4_O.to_string()); 19 let req = req 20 .clone() 21 .description("this is a test assistant".to_string()); 22 let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string()); 23 let req = req.clone().tools(vec![tools]); 24 println!("AssistantRequest: {:?}", req); 25 26 let result = client.create_assistant(req).await?; 27 println!("Create Assistant Result ID: {:?}", result.inner.id); 28 29 let thread_req = CreateThreadRequest::new(); 30 let thread_result = client.create_thread(thread_req).await?; 31 println!( 32 "Create Thread Result ID: {:?}", 33 thread_result.inner.id.clone() 34 ); 35 36 let message_req = CreateMessageRequest::new( 37 MessageRole::user, 38 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(), 39 ); 40 41 let message_result = client 42 .create_message(thread_result.inner.id.clone(), message_req) 43 .await?; 44 println!( 45 "Create Message Result ID: {:?}", 46 message_result.inner.id.clone() 47 ); 48 49 let run_req = CreateRunRequest::new(result.inner.id); 50 let run_result = client 51 .create_run(thread_result.inner.id.clone(), run_req) 52 .await?; 53 println!("Create Run Result ID: {:?}", run_result.inner.id.clone()); 54 55 loop { 56 let run_result = client 57 .retrieve_run(thread_result.inner.id.clone(), run_result.inner.id.clone()) 58 .await 59 .unwrap(); 60 if run_result.inner.status == "completed" { 61 break; 62 } else { 63 println!("waiting..."); 64 std::thread::sleep(std::time::Duration::from_secs(1)); 65 } 66 } 67 68 let list_message_result = client 69 .list_messages(thread_result.inner.id.clone()) 70 .await 71 .unwrap(); 72 for data in list_message_result.inner.data { 73 for content in data.content { 74 println!( 75 "{:} {:?} {:?}", 76 data.role, content.text.value, content.text.annotations 77 ); 78 } 79 } 80 81 Ok(()) 82} ``` -------------------------------- ### Rust Batch API Example Source: https://docs.rs/openai-api-rs/latest/src/batch/batch.rs.html This example requires the OPENAI_API_KEY environment variable to be set. It demonstrates uploading a file, creating a batch job, retrieving its status, and saving the output. ```rust use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::batch::CreateBatchRequest; use openai_api_rs::v1::file::FileUploadRequest; use serde_json::{from_str, to_string_pretty, Value}; use std::env; use std::fs::File; use std::io::Write; use std::str; #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; let req = FileUploadRequest::new( "examples/data/batch_request.json".to_string(), "batch".to_string(), ); let result = client.upload_file(req).await?; let input_file_id = result.inner.id; println!("File id: {:?}", input_file_id); let req = CreateBatchRequest::new( input_file_id.clone(), "/v1/chat/completions".to_string(), "24h".to_string(), ); let result = client.create_batch(req).await?; let batch_id = result.inner.id; println!("Batch id: {:?}", batch_id); let result = client.retrieve_batch(batch_id.to_string()).await?; println!("Batch status: {:?}", result.inner.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.inner.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(()) } // OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example batch ``` -------------------------------- ### Example Usage of a Function Source: https://docs.rs/openai-api-rs/latest/scrape-examples-help.html An example demonstrating how to call a documented function from another crate. This code would be scraped and included in the documentation of `a_func`. ```Rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Rust Function Call Example Source: https://docs.rs/openai-api-rs/latest/src/function_call/function_call.rs.html This example demonstrates how to use the function calling feature to interact with a local Rust function. It requires setting the OPENAI_API_KEY environment variable and uses the GPT-4o model. The code defines a tool for getting cryptocurrency prices and handles the response to call the `get_coin_price` function. ```Rust use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::chat_completion::{ chat_completion::ChatCompletionRequest, ChatCompletionMessage, }; use openai_api_rs::v1::chat_completion::{ Content, FinishReason, MessageRole, Tool, ToolChoiceType, ToolType, }; use openai_api_rs::v1::common::GPT4_O; use openai_api_rs::v1::types; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::{env, vec}; fn get_coin_price(coin: &str) -> f64 { let coin = coin.to_lowercase(); match coin.as_str() { "btc" | "bitcoin" => 10000.0, "eth" | "ethereum" => 1000.0, _ => 0.0, } } #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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![ChatCompletionMessage { role: MessageRole::user, content: Content::Text(String::from("What is the price of Ethereum?")), name: None, tool_calls: None, tool_call_id: None, }], ) .tools(vec![Tool { r#type: 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(ToolChoiceType::Auto); // debug request json // let serialized = serde_json::to_string(&req).unwrap(); // println!("{}", serialized); let result = client.chat_completion(req).await?; match result.inner.choices[0].finish_reason { None => { println!("No finish_reason"); println!("{:?}", result.inner.choices[0].message.content); } Some(FinishReason::stop) => { println!("Stop"); println!("{:?}", result.inner.choices[0].message.content); } Some(FinishReason::length) => { println!("Length"); } Some(FinishReason::tool_calls) => { println!("ToolCalls"); #[derive(Deserialize, Serialize)] struct Currency { coin: String, } let tool_calls = result.inner.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!("{coin} price: {price}"); } } } Some(FinishReason::content_filter) => { println!("ContentFilter"); } Some(FinishReason::null) => { println!("Null"); } } Ok(()) } // OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example function_call ``` -------------------------------- ### Example: Creating a Message Request Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/message/struct.CreateMessageRequest.html Demonstrates how to create a new message request using the `CreateMessageRequest::new` constructor within an assistant workflow. This example is part of a larger interaction involving creating assistants, threads, and runs. ```rust 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.inner.id.clone(), message_req) .await?; ``` -------------------------------- ### OpenAIClientBuilder Initialization Source: https://docs.rs/openai-api-rs/latest/src/openai_api_rs/v1/api.rs.html Demonstrates how to create a new instance of the OpenAIClientBuilder. This is the starting point for configuring your API client. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### Text Completion Example Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClient.html Demonstrates how to perform text completion using the OpenAI API. It shows client initialization, request construction with parameters like max_tokens and temperature, and processing the completion result. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.choices[0].text); Ok(()) } ``` -------------------------------- ### Full Assistant API Workflow Example Source: https://docs.rs/openai-api-rs/latest/src/assistant/assistant.rs.html This Rust code demonstrates the complete lifecycle of interacting with the OpenAI Assistant API, from creating an assistant and thread to sending messages, running the assistant, and retrieving the output. Ensure the OPENAI_API_KEY environment variable is set. ```rust use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::assistant::AssistantRequest; use openai_api_rs::v1::common::GPT4_O; use openai_api_rs::v1::message::{CreateMessageRequest, MessageRole}; use openai_api_rs::v1::run::CreateRunRequest; use openai_api_rs::v1::thread::CreateThreadRequest; use std::collections::HashMap; use std::env; #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.id); let thread_req = CreateThreadRequest::new(); let thread_result = client.create_thread(thread_req).await?; println!( "Create Thread Result ID: {:?}", thread_result.inner.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.inner.id.clone(), message_req) .await?; println!( "Create Message Result ID: {:?}", message_result.inner.id.clone() ); let run_req = CreateRunRequest::new(result.inner.id); let run_result = client .create_run(thread_result.inner.id.clone(), run_req) .await?; println!("Create Run Result ID: {:?}", run_result.inner.id.clone()); loop { let run_result = client .retrieve_run(thread_result.inner.id.clone(), run_result.inner.id.clone()) .await .unwrap(); if run_result.inner.status == "completed" { break; } else { println!("waiting..."); std::thread::sleep(std::time::Duration::from_secs(1)); } } let list_message_result = client .list_messages(thread_result.inner.id.clone()) .await .unwrap(); for data in list_message_result.inner.data { for content in data.content { println!( "{:} {:?} {:?}", data.role, content.text.value, content.text.annotations ); } } Ok(()) } // OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example assistant ``` -------------------------------- ### create_thread_and_run Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClient.html Convenience method to create a thread and immediately run it with the specified assistant. This simplifies the process of starting a new conversation and getting an initial response. ```APIDOC ## create_thread_and_run ### Description Convenience method to create a thread and immediately run it with the specified assistant. This simplifies the process of starting a new conversation and getting an initial response. ### Method POST ### Endpoint /v1/threads/runs ### Parameters #### Request Body - **req** (CreateThreadAndRunRequest) - Required - The request object containing details for creating the thread and initiating the run. ``` -------------------------------- ### Rust OpenAI Completion Example Source: https://docs.rs/openai-api-rs/latest/src/completion/completion.rs.html This Rust code snippet demonstrates how to perform a text completion using the OpenAI API. It requires the OPENAI_API_KEY environment variable to be set. The example configures parameters like model, max_tokens, temperature, and stop sequences. ```rust use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::completion::{self, CompletionRequest}; use std::env; #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.choices[0].text); Ok(()) } // OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example completion ``` -------------------------------- ### Build OpenAI Client with API Key Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClientBuilder.html Demonstrates how to build an OpenAI client using an API key. This is a common setup for authenticating with the OpenAI API. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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(()) } ``` -------------------------------- ### List Files API Method Source: https://docs.rs/openai-api-rs/latest/src/openai_api_rs/v1/api.rs.html Handles GET requests to list all files associated with the account. ```Rust pub async fn file_list(&self) -> Result, APIError> { self.get("files").await } ``` -------------------------------- ### Creating and Uploading a File Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/file/struct.FileUploadRequest.html Demonstrates how to create a FileUploadRequest and use it with the OpenAIClient to upload a file. This example requires the OPENAI_API_KEY environment variable to be set. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; let req = FileUploadRequest::new( "examples/data/batch_request.json".to_string(), "batch".to_string(), ); let result = client.upload_file(req).await?; let input_file_id = result.inner.id; println!("File id: {:?}", input_file_id); let req = CreateBatchRequest::new( input_file_id.clone(), "/v1/chat/completions".to_string(), "24h".to_string(), ); let result = client.create_batch(req).await?; let batch_id = result.inner.id; println!("Batch id: {:?}", batch_id); let result = client.retrieve_batch(batch_id.to_string()).await?; println!("Batch status: {:?}", result.inner.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.inner.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(()) } ``` -------------------------------- ### Example Usage of CreateBatchRequest Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/batch/struct.CreateBatchRequest.html Demonstrates how to create a FileUploadRequest, upload a file, and then use the resulting file ID to create a batch request using CreateBatchRequest::new. ```rust let req = CreateBatchRequest::new( input_file_id.clone(), "/v1/chat/completions".to_string(), "24h".to_string(), ); ``` -------------------------------- ### Create Response with OpenAI API Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClient.html This example shows how to create a response using the OpenAI API, specifying a model, input, and custom parameters like temperature. It prints the response ID, status, and output. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; let mut req = CreateResponseRequest::new(); req.model = Some(GPT4_1_MINI.to_string()); req.input = Some(json!( "Tell me a three sentence bedtime story about a unicorn." )); req.extra.insert("temperature".to_string(), json!(0.7)); let resp = client.create_response(req).await?; println!( "response id: {} status: ?:", resp.inner.id, resp.inner.status ); println!("response output: {:?}", resp.inner.output); Ok(()) } ``` -------------------------------- ### Rust OpenAI API Function Call Example Source: https://docs.rs/openai-api-rs/latest/src/function_call_role/function_call_role.rs.html This Rust code demonstrates a full example of using the OpenAI API for chat completions with function calling. It includes setting up the API client, defining a user request, specifying a tool (function) with its parameters, making the initial API call, processing the tool call response, executing the local function, and then making a second API call with the function's result. ```rust use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::chat_completion::chat_completion::ChatCompletionRequest; use openai_api_rs::v1::chat_completion::{self}; use openai_api_rs::v1::common::GPT4_O; use openai_api_rs::v1::types; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::{env, vec}; fn get_coin_price(coin: &str) -> f64 { let coin = coin.to_lowercase(); match coin.as_str() { "btc" | "bitcoin" => 10000.0, "eth" | "ethereum" => 1000.0, _ => 0.0, } } #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.choices[0].finish_reason { None => { println!("No finish_reason"); println!("{:?}", result.inner.choices[0].message.content); } Some(chat_completion::FinishReason::stop) => { println!("Stop"); println!("{:?}", result.inner.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.inner.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.inner.choices[0].message.content); } } Some(chat_completion::FinishReason::content_filter) => { // Content filter triggered } } Ok(()) } ``` -------------------------------- ### TryFrom Implementation Example Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/fine_tuning/struct.FineTuningPagination.html Demonstrates the TryFrom trait implementation, which allows attempting to convert one type into another. ```rust impl TryFrom for T where U: Into, { type Error = Infallible; fn try_from(value: U) -> Result>::Error> { Ok(value.into()) } } ``` -------------------------------- ### OpenRouter Chat Completion Example Source: https://docs.rs/openai-api-rs/latest/src/openrouter/openrouter.rs.html This snippet shows how to initialize the OpenAIClient for OpenRouter, create a chat completion request, and process the response. Ensure the OPENROUTER_API_KEY environment variable is set before running. ```rust use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::chat_completion::chat_completion::ChatCompletionRequest; use openai_api_rs::v1::chat_completion::{self}; use openai_api_rs::v1::common::GPT4_O_MINI; use std::env; #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder() .with_endpoint("https://openrouter.ai/api/v1") .with_api_key(api_key) .build()?; 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.inner.choices[0].message.content); println!("Response Headers: {:?}", result.headers); Ok(()) } // OPENROUTER_API_KEY=xxxx cargo run --package openai-api-rs --example openrouter ``` -------------------------------- ### Chat Completion with Reasoning Configuration Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClientBuilder.html Shows how to configure and send a chat completion request with specific reasoning parameters, including effort and summary verbosity. This example uses a Grok model that supports reasoning. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder() .with_endpoint("https://openrouter.ai/api/v1") .with_api_key(api_key) .build()?; // Example 1: OpenRouter reasoning uses the reasoning object. let mut req = ChatCompletionRequest::new( "x-ai/grok-3-mini".to_string(), // Grok model that supports reasoning vec![chat_completion::ChatCompletionMessage { role: chat_completion::MessageRole::user, content: chat_completion::Content::Text(String::from( "Explain quantum computing in simple terms." )), name: None, tool_calls: None, tool_call_id: None, }], ); req.reasoning = Some(Reasoning { effort: Some(ReasoningEffort::High), summary: Some(ReasoningSummary::Detailed), }); let result = client.chat_completion(req).await?; println!("Content: {:?}", result.inner.choices[0].message.content); println!( "Reasoning: {:?}", result.inner.choices[0].message.reasoning_content ); // Example 2: Another reasoning configuration with a different summary verbosity. let mut req2 = ChatCompletionRequest::new( "anthropic/claude-opus-4.6".to_string(), // Claude model that supports max_tokens vec![chat_completion::ChatCompletionMessage { role: chat_completion::MessageRole::user, content: chat_completion::Content::Text(String::from( "What's the most efficient sorting algorithm?" )), name: None, tool_calls: None, tool_call_id: None, }], ); req2.reasoning = Some(Reasoning { effort: Some(ReasoningEffort::Minimal), summary: Some(ReasoningSummary::Concise), }); let result2 = client.chat_completion(req2).await?; println!("Content: {:?}", result2.inner.choices[0].message.content); println!( "Reasoning: {:?}", result2.inner.choices[0].message.reasoning_content ); Ok(()) } ``` -------------------------------- ### TryInto Implementation Example Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/fine_tuning/struct.FineTuningPagination.html Demonstrates the TryInto trait implementation, which allows attempting to convert a type into another type that supports TryFrom. ```rust impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error> { U::try_from(self) } } ``` -------------------------------- ### Stream Chat Completions in Rust Source: https://docs.rs/openai-api-rs/latest/src/chat_completion_stream/chat_completion_stream.rs.html This example shows how to stream chat completions from the OpenAI API using the openai-api-rs library. Ensure you have the OPENAI_API_KEY environment variable set. ```rust use futures_util::StreamExt; use openai_api_rs::v1::api::OpenAIClient; use openai_api_rs::v1::chat_completion::chat_completion_stream::{ ChatCompletionStreamRequest, ChatCompletionStreamResponse, }; use openai_api_rs::v1::chat_completion::{self}; use openai_api_rs::v1::common::GPT4_O_MINI; use std::env; #[tokio::main] async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; let req = ChatCompletionStreamRequest::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 mut result = client.chat_completion_stream(req).await?; while let Some(response) = result.next().await { match response.clone() { ChatCompletionStreamResponse::ToolCall(toolcalls) => { println!("Tool Call: {:?}", toolcalls); } ChatCompletionStreamResponse::Reasoning(reasoning) => { println!("Reasoning: {:?}", reasoning); } ChatCompletionStreamResponse::Content(content) => { println!("Content: {:?}", content); } ChatCompletionStreamResponse::Done => { println!("Done"); } } } Ok(()) } // OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example chat_completion_stream ``` -------------------------------- ### Example Usage of CreateThreadRequest Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/thread/struct.CreateThreadRequest.html Demonstrates how to create a new thread using the CreateThreadRequest struct and the OpenAIClient in a Rust application. ```rust 11async fn main() -> Result<(), Box> { 12 let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); 13 let client = OpenAIClient::builder().with_api_key(api_key).build()?; 14 15 let mut tools = HashMap::new(); 16 tools.insert("type".to_string(), "code_interpreter".to_string()); 17 18 let req = AssistantRequest::new(GPT4_O.to_string()); 19 let req = req 20 .clone() 21 .description("this is a test assistant".to_string()); 22 let req = req.clone().instructions("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string()); 23 let req = req.clone().tools(vec![tools]); 24 println!("AssistantRequest: {:?}", req); 25 26 let result = client.create_assistant(req).await?; 27 println!("Create Assistant Result ID: {:?}", result.inner.id); 28 29 let thread_req = CreateThreadRequest::new(); 30 let thread_result = client.create_thread(thread_req).await?; 31 println!( 32 "Create Thread Result ID: {:?}", 33 thread_result.inner.id.clone() 34 ); 35 36 let message_req = CreateMessageRequest::new( 37 MessageRole::user, 38 "`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(), 39 ); 40 41 let message_result = client 42 .create_message(thread_result.inner.id.clone(), message_req) 43 .await?; 44 println!( 45 "Create Message Result ID: {:?}", 46 message_result.inner.id.clone() 47 ); 48 49 let run_req = CreateRunRequest::new(result.inner.id); 50 let run_result = client 51 .create_run(thread_result.inner.id.clone(), run_req) 52 .await?; 53 println!("Create Run Result ID: {:?}", run_result.inner.id.clone()); 54 55 loop { 56 let run_result = client 57 .retrieve_run(thread_result.inner.id.clone(), run_result.inner.id.clone()) 58 .await 59 .unwrap(); 60 if run_result.inner.status == "completed" { 61 break; 62 } else { 63 println!("waiting..."); 64 std::thread::sleep(std::time::Duration::from_secs(1)); 65 } 66 } 67 68 let list_message_result = client 69 .list_messages(thread_result.inner.id.clone()) 70 .await 71 .unwrap(); 72 for data in list_message_result.inner.data { 73 for content in data.content { 74 println!( 75 "{:<5}: {:?} {:?}", 76 data.role, content.text.value, content.text.annotations 77 ); 78 } 79 } 80 81 Ok(()) 82} ``` -------------------------------- ### Basic Chat Completion with OpenAIClient Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClient.html Performs a basic chat completion request using the OpenAIClient. This example demonstrates setting the API key and sending a simple text-based user message. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; let mut req = ChatCompletionRequest::new( GPT5_4.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, }], ); req.reasoning_effort = Some(chat_completion::ReasoningEffort::High); let result = client.chat_completion(req).await?; println!("Content: {:?}", result.inner.choices[0].message.content); // print response headers for (key, value) in result.headers.iter() { println!(ירתkey, value); } Ok(()) } ``` -------------------------------- ### Chat Completion Request Structure Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/chat_completion/chat_completion/struct.ChatCompletionRequest.html This example demonstrates the basic structure of a chat completion request, including specifying the model and user messages. It omits the tool definitions and tool choice for simplicity. ```Rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.choices[0].finish_reason { None => { println!("No finish_reason"); ``` -------------------------------- ### GET Raw Response Source: https://docs.rs/openai-api-rs/latest/src/openai_api_rs/v1/api.rs.html Sends a GET request to a specified path and returns the raw response body as `Bytes`. ```APIDOC ## GET Raw ### Description Sends a GET request to a specified path and returns the raw response body as `Bytes`. ### Method GET ### Endpoint /{path} ### Parameters #### Path Parameters - **path** (string) - Required - The API endpoint path. ### Response #### Success Response (200) - **Bytes** - The raw response body as a byte vector. #### Error Response - **APIError** - Represents potential errors during the API call, such as network issues. ``` -------------------------------- ### GET Request Source: https://docs.rs/openai-api-rs/latest/src/openai_api_rs/v1/api.rs.html Sends a GET request to a specified path. This method is generic and can deserialize the response into any type `T` that implements `DeserializeOwned`. ```APIDOC ## GET ### Description Sends a GET request to a specified path. This method is generic and can deserialize the response into any type `T` that implements `DeserializeOwned`. ### Method GET ### Endpoint /{path} ### Parameters #### Path Parameters - **path** (string) - Required - The API endpoint path. ### Response #### Success Response (200) - **CallResponse** - Contains the response headers and the deserialized response body of type `T`. #### Error Response - **APIError** - Represents potential errors during the API call, such as network issues or JSON parsing failures. ``` -------------------------------- ### GET Request to OpenAI API Source: https://docs.rs/openai-api-rs/latest/src/openai_api_rs/v1/api.rs.html Sends a GET request to the specified path and deserializes the response into a `CallResponse`. Handles potential API errors. ```rust async fn get( &self, path: &str, ) -> Result, APIError> { let request = self.build_request(Method::GET, path).await; let response = request.send().await?; self.handle_response(response).await } ``` -------------------------------- ### Create and Configure Assistant Request Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/assistant/struct.AssistantRequest.html Demonstrates how to create a new AssistantRequest, set its description and instructions, and add tools. This is typically used when initializing an assistant via the OpenAI API. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.id); let thread_req = CreateThreadRequest::new(); let thread_result = client.create_thread(thread_req).await?; println!( "Create Thread Result ID: {:?}", thread_result.inner.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.inner.id.clone(), message_req) .await?; println!( "Create Message Result ID: {:?}", message_result.inner.id.clone() ); let run_req = CreateRunRequest::new(result.inner.id); let run_result = client .create_run(thread_result.inner.id.clone(), run_req) .await?; println!("Create Run Result ID: {:?}", run_result.inner.id.clone()); loop { let run_result = client .retrieve_run(thread_result.inner.id.clone(), run_result.inner.id.clone()) .await .unwrap(); if run_result.inner.status == "completed" { break; } else { println!("waiting..."); std::thread::sleep(std::time::Duration::from_secs(1)); } } let list_message_result = client .list_messages(thread_result.inner.id.clone()) .await .unwrap(); for data in list_message_result.inner.data { for content in data.content { println!( "{:<5}: {:?} {:?}", data.role, content.text.value, content.text.annotations ); } } Ok(()) } ``` -------------------------------- ### Build OpenAI Client for Text Completion Source: https://docs.rs/openai-api-rs/latest/openai_api_rs/v1/api/struct.OpenAIClientBuilder.html Demonstrates creating an OpenAI client with an API key and configuring a completion request with various parameters like max tokens, temperature, and stop sequences. ```rust async fn main() -> Result<(), Box> { let api_key = env::var("OPENAI_API_KEY").unwrap().to_string(); let client = OpenAIClient::builder().with_api_key(api_key).build()?; 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.inner.choices[0].text); Ok(()) } ``` -------------------------------- ### Initialize RealtimeClient Source: https://docs.rs/openai-api-rs/latest/src/openai_api_rs/realtime/api.rs.html Creates a new RealtimeClient instance. It uses the WSS_URL environment variable if set, otherwise defaults to a predefined URL. Requires an API key and model name. ```rust pub fn new(api_key: String, model: String) -> Self { let wss_url = std::env::var("WSS_URL").unwrap_or_else(|_| WSS_URL.to_owned()); Self::new_with_endpoint(wss_url, api_key, model) } ``` ```rust pub fn new_with_endpoint(wss_url: String, api_key: String, model: String) -> Self { Self { wss_url, api_key, model, } } ```