Gpt5Client

Struct Gpt5Client 

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

Main client for interacting with the GPT-5 API

The Gpt5Client handles authentication, request building, and response parsing for the OpenAI GPT-5 API. It supports both simple and advanced usage patterns.

§Examples

§Simple Usage

use gpt5::{Gpt5Client, Gpt5Model};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Gpt5Client::new("your-api-key".to_string());
    let response = client.simple(Gpt5Model::Gpt5Nano, "Hello!").await?;
    println!("{}", response);
    Ok(())
}

§Advanced Usage with Custom Base URL

use gpt5::Gpt5Client;

let client = Gpt5Client::new("your-api-key".to_string())
    .with_base_url("https://custom-api.example.com".to_string());

Fields§

§client: Client§api_key: String§base_url: String

Implementations§

Source§

impl Gpt5Client

Source

pub fn new(api_key: String) -> Self

Create a new GPT-5 client with the specified API key

§Arguments
  • api_key - Your OpenAI API key
§Examples
use gpt5::Gpt5Client;

let client = Gpt5Client::new("sk-...".to_string());
Examples found in repository?
examples/quick_start.rs (line 11)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // 1. Create client
11    let client = Gpt5Client::new("your-api-key-here".to_string());
12
13    // 2. Ask a question
14    let response = client.simple(Gpt5Model::Gpt5Nano, "Hello, world!").await?;
15
16    // 3. Print response
17    println!("{}", response);
18
19    Ok(())
20}
More examples
Hide additional examples
examples/simple_chat.rs (line 14)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let api_key =
12        std::env::var("OPENAI_API_KEY").expect("Please set OPENAI_API_KEY environment variable");
13
14    let client = Gpt5Client::new(api_key);
15
16    println!("🤖 GPT-5 Chat Bot");
17    println!("Type 'quit' or 'exit' to end the conversation\n");
18
19    loop {
20        print!("You: ");
21        io::stdout().flush()?;
22
23        let mut input = String::new();
24        io::stdin().read_line(&mut input)?;
25        let input = input.trim();
26
27        if input == "quit" || input == "exit" {
28            println!("Goodbye! 👋");
29            break;
30        }
31
32        if input.is_empty() {
33            continue;
34        }
35
36        println!("🤖 Thinking...");
37
38        match client.simple(Gpt5Model::Gpt5Nano, input).await {
39            Ok(response) => {
40                println!("Bot: {}\n", response);
41            }
42            Err(e) => {
43                println!("❌ Error: {}\n", e);
44            }
45        }
46    }
47
48    Ok(())
49}
examples/basic_usage.rs (line 14)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // Initialize the client with your API key
11    let api_key =
12        std::env::var("OPENAI_API_KEY").expect("Please set OPENAI_API_KEY environment variable");
13
14    let client = Gpt5Client::new(api_key);
15
16    // Simple text generation
17    println!("🤖 Asking GPT-5 Nano a simple question...");
18    let response = client
19        .simple(Gpt5Model::Gpt5Nano, "What is the capital of France?")
20        .await?;
21
22    println!("Response: {}", response);
23
24    // Try different models
25    println!("\n🤖 Asking GPT-5 Mini...");
26    let response = client
27        .simple(
28            Gpt5Model::Gpt5Mini,
29            "Explain quantum computing in simple terms",
30        )
31        .await?;
32
33    println!("Response: {}", response);
34
35    // Try the main GPT-5 model
36    println!("\n🤖 Asking GPT-5 (main model)...");
37    let response = client
38        .simple(Gpt5Model::Gpt5, "Write a short poem about coding")
39        .await?;
40
41    println!("Response: {}", response);
42
43    Ok(())
44}
examples/error_handling.rs (line 12)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // Test with invalid API key
11    println!("🔑 Testing with invalid API key...");
12    let invalid_client = Gpt5Client::new("invalid-key".to_string());
13
14    match invalid_client.simple(Gpt5Model::Gpt5Nano, "Hello").await {
15        Ok(response) => println!("Unexpected success: {}", response),
16        Err(e) => {
17            println!("❌ Expected error: {}", e);
18            // Check error type by string content
19            let error_str = e.to_string();
20            if error_str.contains("401") || error_str.contains("Unauthorized") {
21                println!("   Error type: Authentication error");
22            } else if error_str.contains("timeout") {
23                println!("   Error type: Timeout error");
24            } else if error_str.contains("network") {
25                println!("   Error type: Network error");
26            } else {
27                println!("   Error type: Other error");
28            }
29        }
30    }
31
32    // Test with valid API key (if available)
33    if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
34        println!("\n✅ Testing with valid API key...");
35        let client = Gpt5Client::new(api_key);
36
37        // Test empty input
38        println!("📝 Testing empty input...");
39        match client.simple(Gpt5Model::Gpt5Nano, "").await {
40            Ok(response) => println!("Response: {}", response),
41            Err(e) => println!("❌ Error with empty input: {}", e),
42        }
43
44        // Test very long input
45        println!("\n📝 Testing very long input...");
46        let long_input = "Hello ".repeat(10000); // Very long string
47        match client.simple(Gpt5Model::Gpt5Nano, &long_input).await {
48            Ok(response) => println!("Response length: {} chars", response.len()),
49            Err(e) => println!("❌ Error with long input: {}", e),
50        }
51
52        // Test normal usage
53        println!("\n✅ Testing normal usage...");
54        match client
55            .simple(Gpt5Model::Gpt5Nano, "Say hello in 3 different languages")
56            .await
57        {
58            Ok(response) => println!("✅ Success: {}", response),
59            Err(e) => println!("❌ Unexpected error: {}", e),
60        }
61    } else {
62        println!("⚠️  OPENAI_API_KEY not set, skipping valid key tests");
63    }
64
65    // Demonstrate error type checking
66    println!("\n🔍 Error type checking example...");
67    let client = Gpt5Client::new("test-key".to_string());
68
69    match client.simple(Gpt5Model::Gpt5Nano, "test").await {
70        Ok(_) => println!("Unexpected success"),
71        Err(e) => {
72            // Check if it's a network error
73            if e.to_string().contains("401") || e.to_string().contains("Unauthorized") {
74                println!("🔐 Authentication error detected");
75            } else if e.to_string().contains("timeout") {
76                println!("⏰ Timeout error detected");
77            } else if e.to_string().contains("network") {
78                println!("🌐 Network error detected");
79            } else {
80                println!("❓ Other error: {}", e);
81            }
82        }
83    }
84
85    Ok(())
86}
examples/function_calling.rs (line 14)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let api_key =
12        std::env::var("OPENAI_API_KEY").expect("Please set OPENAI_API_KEY environment variable");
13
14    let client = Gpt5Client::new(api_key);
15
16    // Define a simple calculator tool
17    let calculator_tool = Tool {
18        tool_type: "function".to_string(),
19        name: "calculate".to_string(),
20        description: "Perform basic arithmetic calculations".to_string(),
21        parameters: json!({
22            "type": "object",
23            "properties": {
24                "expression": {
25                    "type": "string",
26                    "description": "Mathematical expression to evaluate (e.g., '2 + 2', '10 * 5')"
27                }
28            },
29            "required": ["expression"]
30        }),
31    };
32
33    // Define a weather tool (mock)
34    let weather_tool = Tool {
35        tool_type: "function".to_string(),
36        name: "get_weather".to_string(),
37        description: "Get current weather information for a city".to_string(),
38        parameters: json!({
39            "type": "object",
40            "properties": {
41                "city": {
42                    "type": "string",
43                    "description": "The city name to get weather for"
44                }
45            },
46            "required": ["city"]
47        }),
48    };
49
50    println!("🧮 Testing calculator function...");
51
52    // Build a request with tools
53    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
54        .input("What is 15 * 8 + 42?")
55        .instructions("Use the calculator tool to solve this math problem")
56        .tools(vec![calculator_tool])
57        .tool_choice("auto")
58        .verbosity(VerbosityLevel::Medium)
59        .reasoning_effort(ReasoningEffort::Low)
60        .max_output_tokens(200)
61        .build();
62
63    // Send the request
64    let response = client.request(request).await?;
65
66    // Check for function calls
67    let function_calls = response.function_calls();
68    if !function_calls.is_empty() {
69        println!("🔧 Function calls made: {}", function_calls.len());
70        for call in function_calls {
71            println!("  Function: {}", call.name.as_deref().unwrap_or("unknown"));
72            println!("  Arguments: {}", call.arguments.as_deref().unwrap_or("{}"));
73        }
74    }
75
76    // Get text response
77    if let Some(text) = response.text() {
78        println!("🤖 Response: {}", text);
79    }
80
81    println!("\n🌤️ Testing weather function...");
82
83    // Test weather tool
84    let weather_request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
85        .input("What's the weather like in Tokyo?")
86        .instructions("Use the weather tool to get current conditions")
87        .tools(vec![weather_tool])
88        .tool_choice("auto")
89        .verbosity(VerbosityLevel::Low)
90        .reasoning_effort(ReasoningEffort::Low)
91        .max_output_tokens(150)
92        .build();
93
94    let weather_response = client.request(weather_request).await?;
95
96    let weather_calls = weather_response.function_calls();
97    if !weather_calls.is_empty() {
98        println!("🔧 Weather function calls made: {}", weather_calls.len());
99        for call in weather_calls {
100            println!("  Function: {}", call.name.as_deref().unwrap_or("unknown"));
101            println!("  Arguments: {}", call.arguments.as_deref().unwrap_or("{}"));
102        }
103    }
104
105    if let Some(text) = weather_response.text() {
106        println!("🤖 Response: {}", text);
107    }
108
109    Ok(())
110}
Source

pub fn with_base_url(self, base_url: String) -> Self

Set a custom base URL for the API

§Arguments
  • base_url - Custom base URL for the API
§Examples
use gpt5::Gpt5Client;

let client = Gpt5Client::new("sk-...".to_string())
    .with_base_url("https://custom-api.example.com".to_string());
Source

pub async fn request(&self, req: Gpt5Request) -> Result<Gpt5Response>

Send a request to the GPT-5 API

§Arguments
  • req - The GPT-5 request to send
§Returns
  • Result<Gpt5Response, anyhow::Error> - The response or an error
§Examples
use gpt5::{Gpt5Client, Gpt5RequestBuilder, Gpt5Model};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Gpt5Client::new("sk-...".to_string());
    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
        .input("Hello!")
        .build();
     
    let response = client.request(request).await?;
    println!("{:?}", response);
    Ok(())
}
Examples found in repository?
examples/function_calling.rs (line 64)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let api_key =
12        std::env::var("OPENAI_API_KEY").expect("Please set OPENAI_API_KEY environment variable");
13
14    let client = Gpt5Client::new(api_key);
15
16    // Define a simple calculator tool
17    let calculator_tool = Tool {
18        tool_type: "function".to_string(),
19        name: "calculate".to_string(),
20        description: "Perform basic arithmetic calculations".to_string(),
21        parameters: json!({
22            "type": "object",
23            "properties": {
24                "expression": {
25                    "type": "string",
26                    "description": "Mathematical expression to evaluate (e.g., '2 + 2', '10 * 5')"
27                }
28            },
29            "required": ["expression"]
30        }),
31    };
32
33    // Define a weather tool (mock)
34    let weather_tool = Tool {
35        tool_type: "function".to_string(),
36        name: "get_weather".to_string(),
37        description: "Get current weather information for a city".to_string(),
38        parameters: json!({
39            "type": "object",
40            "properties": {
41                "city": {
42                    "type": "string",
43                    "description": "The city name to get weather for"
44                }
45            },
46            "required": ["city"]
47        }),
48    };
49
50    println!("🧮 Testing calculator function...");
51
52    // Build a request with tools
53    let request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
54        .input("What is 15 * 8 + 42?")
55        .instructions("Use the calculator tool to solve this math problem")
56        .tools(vec![calculator_tool])
57        .tool_choice("auto")
58        .verbosity(VerbosityLevel::Medium)
59        .reasoning_effort(ReasoningEffort::Low)
60        .max_output_tokens(200)
61        .build();
62
63    // Send the request
64    let response = client.request(request).await?;
65
66    // Check for function calls
67    let function_calls = response.function_calls();
68    if !function_calls.is_empty() {
69        println!("🔧 Function calls made: {}", function_calls.len());
70        for call in function_calls {
71            println!("  Function: {}", call.name.as_deref().unwrap_or("unknown"));
72            println!("  Arguments: {}", call.arguments.as_deref().unwrap_or("{}"));
73        }
74    }
75
76    // Get text response
77    if let Some(text) = response.text() {
78        println!("🤖 Response: {}", text);
79    }
80
81    println!("\n🌤️ Testing weather function...");
82
83    // Test weather tool
84    let weather_request = Gpt5RequestBuilder::new(Gpt5Model::Gpt5Nano)
85        .input("What's the weather like in Tokyo?")
86        .instructions("Use the weather tool to get current conditions")
87        .tools(vec![weather_tool])
88        .tool_choice("auto")
89        .verbosity(VerbosityLevel::Low)
90        .reasoning_effort(ReasoningEffort::Low)
91        .max_output_tokens(150)
92        .build();
93
94    let weather_response = client.request(weather_request).await?;
95
96    let weather_calls = weather_response.function_calls();
97    if !weather_calls.is_empty() {
98        println!("🔧 Weather function calls made: {}", weather_calls.len());
99        for call in weather_calls {
100            println!("  Function: {}", call.name.as_deref().unwrap_or("unknown"));
101            println!("  Arguments: {}", call.arguments.as_deref().unwrap_or("{}"));
102        }
103    }
104
105    if let Some(text) = weather_response.text() {
106        println!("🤖 Response: {}", text);
107    }
108
109    Ok(())
110}
Source

pub async fn simple(&self, model: Gpt5Model, prompt: &str) -> Result<String>

Send a simple request and get text response

§Arguments
  • model - The GPT-5 model to use
  • prompt - The input prompt
§Returns
  • Result<String, anyhow::Error> - The text response or an error
§Examples
use gpt5::{Gpt5Client, Gpt5Model};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Gpt5Client::new("sk-...".to_string());
    let response = client.simple(Gpt5Model::Gpt5Nano, "Hello!").await?;
    println!("{}", response);
    Ok(())
}
Examples found in repository?
examples/quick_start.rs (line 14)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // 1. Create client
11    let client = Gpt5Client::new("your-api-key-here".to_string());
12
13    // 2. Ask a question
14    let response = client.simple(Gpt5Model::Gpt5Nano, "Hello, world!").await?;
15
16    // 3. Print response
17    println!("{}", response);
18
19    Ok(())
20}
More examples
Hide additional examples
examples/simple_chat.rs (line 38)
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let api_key =
12        std::env::var("OPENAI_API_KEY").expect("Please set OPENAI_API_KEY environment variable");
13
14    let client = Gpt5Client::new(api_key);
15
16    println!("🤖 GPT-5 Chat Bot");
17    println!("Type 'quit' or 'exit' to end the conversation\n");
18
19    loop {
20        print!("You: ");
21        io::stdout().flush()?;
22
23        let mut input = String::new();
24        io::stdin().read_line(&mut input)?;
25        let input = input.trim();
26
27        if input == "quit" || input == "exit" {
28            println!("Goodbye! 👋");
29            break;
30        }
31
32        if input.is_empty() {
33            continue;
34        }
35
36        println!("🤖 Thinking...");
37
38        match client.simple(Gpt5Model::Gpt5Nano, input).await {
39            Ok(response) => {
40                println!("Bot: {}\n", response);
41            }
42            Err(e) => {
43                println!("❌ Error: {}\n", e);
44            }
45        }
46    }
47
48    Ok(())
49}
examples/basic_usage.rs (line 19)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // Initialize the client with your API key
11    let api_key =
12        std::env::var("OPENAI_API_KEY").expect("Please set OPENAI_API_KEY environment variable");
13
14    let client = Gpt5Client::new(api_key);
15
16    // Simple text generation
17    println!("🤖 Asking GPT-5 Nano a simple question...");
18    let response = client
19        .simple(Gpt5Model::Gpt5Nano, "What is the capital of France?")
20        .await?;
21
22    println!("Response: {}", response);
23
24    // Try different models
25    println!("\n🤖 Asking GPT-5 Mini...");
26    let response = client
27        .simple(
28            Gpt5Model::Gpt5Mini,
29            "Explain quantum computing in simple terms",
30        )
31        .await?;
32
33    println!("Response: {}", response);
34
35    // Try the main GPT-5 model
36    println!("\n🤖 Asking GPT-5 (main model)...");
37    let response = client
38        .simple(Gpt5Model::Gpt5, "Write a short poem about coding")
39        .await?;
40
41    println!("Response: {}", response);
42
43    Ok(())
44}
examples/error_handling.rs (line 14)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // Test with invalid API key
11    println!("🔑 Testing with invalid API key...");
12    let invalid_client = Gpt5Client::new("invalid-key".to_string());
13
14    match invalid_client.simple(Gpt5Model::Gpt5Nano, "Hello").await {
15        Ok(response) => println!("Unexpected success: {}", response),
16        Err(e) => {
17            println!("❌ Expected error: {}", e);
18            // Check error type by string content
19            let error_str = e.to_string();
20            if error_str.contains("401") || error_str.contains("Unauthorized") {
21                println!("   Error type: Authentication error");
22            } else if error_str.contains("timeout") {
23                println!("   Error type: Timeout error");
24            } else if error_str.contains("network") {
25                println!("   Error type: Network error");
26            } else {
27                println!("   Error type: Other error");
28            }
29        }
30    }
31
32    // Test with valid API key (if available)
33    if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
34        println!("\n✅ Testing with valid API key...");
35        let client = Gpt5Client::new(api_key);
36
37        // Test empty input
38        println!("📝 Testing empty input...");
39        match client.simple(Gpt5Model::Gpt5Nano, "").await {
40            Ok(response) => println!("Response: {}", response),
41            Err(e) => println!("❌ Error with empty input: {}", e),
42        }
43
44        // Test very long input
45        println!("\n📝 Testing very long input...");
46        let long_input = "Hello ".repeat(10000); // Very long string
47        match client.simple(Gpt5Model::Gpt5Nano, &long_input).await {
48            Ok(response) => println!("Response length: {} chars", response.len()),
49            Err(e) => println!("❌ Error with long input: {}", e),
50        }
51
52        // Test normal usage
53        println!("\n✅ Testing normal usage...");
54        match client
55            .simple(Gpt5Model::Gpt5Nano, "Say hello in 3 different languages")
56            .await
57        {
58            Ok(response) => println!("✅ Success: {}", response),
59            Err(e) => println!("❌ Unexpected error: {}", e),
60        }
61    } else {
62        println!("⚠️  OPENAI_API_KEY not set, skipping valid key tests");
63    }
64
65    // Demonstrate error type checking
66    println!("\n🔍 Error type checking example...");
67    let client = Gpt5Client::new("test-key".to_string());
68
69    match client.simple(Gpt5Model::Gpt5Nano, "test").await {
70        Ok(_) => println!("Unexpected success"),
71        Err(e) => {
72            // Check if it's a network error
73            if e.to_string().contains("401") || e.to_string().contains("Unauthorized") {
74                println!("🔐 Authentication error detected");
75            } else if e.to_string().contains("timeout") {
76                println!("⏰ Timeout error detected");
77            } else if e.to_string().contains("network") {
78                println!("🌐 Network error detected");
79            } else {
80                println!("❓ Other error: {}", e);
81            }
82        }
83    }
84
85    Ok(())
86}

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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,