AiClientBuilder

Struct AiClientBuilder 

Source
pub struct AiClientBuilder { /* private fields */ }
Expand description

AI client builder with progressive custom configuration

Usage examples:

use ai_lib::{AiClientBuilder, Provider};

// Simplest usage - automatic environment variable detection
let client = AiClientBuilder::new(Provider::Groq).build()?;

// Custom base_url and proxy
let client = AiClientBuilder::new(Provider::Groq)
    .with_base_url("https://custom.groq.com")
    .with_proxy("http://proxy.example.com:8080")
    .build()?;

// Full custom configuration
let client = AiClientBuilder::new(Provider::Groq)
    .with_base_url("https://custom.groq.com")
    .with_proxy("http://proxy.example.com:8080")
    .with_timeout(std::time::Duration::from_secs(60))
    .with_pool_config(32, std::time::Duration::from_secs(90))
    .build()?;

Implementationsยง

Sourceยง

impl AiClientBuilder

Source

pub fn new(provider: Provider) -> Self

Create a new builder instance

ยงArguments
  • provider - The AI model provider to use
ยงReturns
  • Self - Builder instance
Examples found in repository?
examples/quickstart.rs (line 17)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("๐Ÿš€ AI-lib Quickstart Example");
8    println!("============================");
9
10    // ๐ŸŽฏ Simplest usage - create client with one line of code
11    println!("\n๐Ÿ“‹ Simplest usage:");
12    let client = AiClient::new(Provider::Groq)?;
13    println!("โœ… Client created successfully!");
14
15    // ๐Ÿ”ง If you need custom configuration, use builder pattern
16    println!("\n๐Ÿ“‹ Custom configuration:");
17    let client = AiClientBuilder::new(Provider::Groq)
18        .with_base_url("https://custom.groq.com") // Optional: custom server
19        .with_proxy("http://proxy.example.com:8080") // Optional: custom proxy
20        .build()?;
21    println!("โœ… Custom client created successfully!");
22
23    // ๐Ÿ“ Create chat request
24    println!("\n๐Ÿ“‹ Create chat request:");
25    let request = ChatCompletionRequest::new(
26        "llama3-8b-8192".to_string(), // Model name
27        vec![Message {
28            role: Role::User,
29            content: Content::Text("Hello! How are you?".to_string()),
30            function_call: None,
31        }],
32    );
33    println!("โœ… Request created successfully!");
34
35    // ๐ŸŒ Send request (requires GROQ_API_KEY environment variable)
36    println!("\n๐Ÿ“‹ Send request:");
37    println!("   Note: Set GROQ_API_KEY environment variable for actual API calls");
38    println!("   Usage: export GROQ_API_KEY=your_api_key_here");
39
40    // Check if API key is available
41    match std::env::var("GROQ_API_KEY") {
42        Ok(_) => {
43            println!("โœ… GROQ_API_KEY detected, ready to send actual requests");
44            // Uncomment the following code to send actual request
45            // let response = client.chat_completion(request).await?;
46            // println!("๐Ÿค– AI response: {}", response.choices[0].message.content.as_text());
47        }
48        Err(_) => {
49            println!("โ„น๏ธ  GROQ_API_KEY not set, skipping actual request");
50            println!("   This is a demo showing how to build requests");
51        }
52    }
53
54    // ๐ŸŽจ More customization options
55    println!("\n๐Ÿ“‹ More customization options:");
56    let advanced_client = AiClientBuilder::new(Provider::Groq)
57        .with_timeout(std::time::Duration::from_secs(60)) // 60 second timeout
58        .with_pool_config(16, std::time::Duration::from_secs(60)) // Connection pool config
59        .build()?;
60    println!("โœ… Advanced configuration client created successfully!");
61
62    // ๐Ÿ”„ Switch to other providers
63    println!("\n๐Ÿ“‹ Switch to other providers:");
64    let deepseek_client = AiClient::new(Provider::DeepSeek)?;
65    println!("โœ… DeepSeek client created successfully!");
66
67    let ollama_client = AiClient::new(Provider::Ollama)?;
68    println!("โœ… Ollama client created successfully!");
69
70    println!("\n๐ŸŽ‰ Quickstart completed!");
71    println!("\n๐Ÿ’ก Key points:");
72    println!("   1. AiClient::new() - Simplest usage with automatic environment detection");
73    println!("   2. AiClientBuilder - Builder pattern with custom configuration support");
74    println!(
75        "   3. Environment variable priority: Explicit setting > Environment variable > Default"
76    );
77    println!("   4. Support for all mainstream AI providers");
78    println!("   5. Backward compatible, existing code requires no changes");
79
80    Ok(())
81}
More examples
Hide additional examples
examples/builder_pattern.rs (line 15)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    println!("๐Ÿš€ AI Client Builder Pattern Example");
9    println!("===================================");
10
11    // Example 1: Simplest usage - automatic environment variable detection
12    println!("\n๐Ÿ“‹ Example 1: Simplest usage");
13    println!("   Automatically detect GROQ_BASE_URL and AI_PROXY_URL from environment variables");
14
15    let client = AiClientBuilder::new(Provider::Groq).build()?;
16    println!(
17        "โœ… Client created successfully, provider: {:?}",
18        client.current_provider()
19    );
20
21    // Example 2: Custom base_url
22    println!("\n๐Ÿ“‹ Example 2: Custom base_url");
23    println!("   Use custom Groq server address");
24
25    let client = AiClientBuilder::new(Provider::Groq)
26        .with_base_url("https://custom.groq.com")
27        .build()?;
28    println!("โœ… Client created successfully with custom base_url");
29
30    // Example 3: Custom base_url and proxy
31    println!("\n๐Ÿ“‹ Example 3: Custom base_url and proxy");
32    println!("   Use custom server and proxy");
33
34    let client = AiClientBuilder::new(Provider::Groq)
35        .with_base_url("https://custom.groq.com")
36        .with_proxy("http://proxy.example.com:8080")
37        .build()?;
38    println!("โœ… Client created successfully with custom base_url and proxy");
39
40    // Example 4: Full custom configuration
41    println!("\n๐Ÿ“‹ Example 4: Full custom configuration");
42    println!("   Custom timeout, connection pool and other advanced configurations");
43
44    let client = AiClientBuilder::new(Provider::Groq)
45        .with_base_url("https://custom.groq.com")
46        .with_proxy("http://proxy.example.com:8080")
47        .with_timeout(Duration::from_secs(60))
48        .with_pool_config(32, Duration::from_secs(90))
49        .build()?;
50    println!("โœ… Client created successfully with full custom configuration");
51
52    // Example 5: Use convenient builder method
53    println!("\n๐Ÿ“‹ Example 5: Use convenient builder method");
54    println!("   Create builder through AiClient::builder()");
55
56    let client = AiClient::builder(Provider::Groq)
57        .with_base_url("https://custom.groq.com")
58        .with_proxy("http://proxy.example.com:8080")
59        .build()?;
60    println!("โœ… Client created successfully using convenient builder method");
61
62    // Example 6: Environment variable priority demonstration
63    println!("\n๐Ÿ“‹ Example 6: Environment variable priority demonstration");
64    println!("   Set environment variables, then use builder");
65
66    // Set environment variables
67    std::env::set_var("GROQ_BASE_URL", "https://env.groq.com");
68    std::env::set_var("AI_PROXY_URL", "http://env.proxy.com:8080");
69
70    // Don't set any custom configuration, should use environment variables
71    let client = AiClientBuilder::new(Provider::Groq).build()?;
72    println!("โœ… Client created successfully using environment variable configuration");
73
74    // Explicit settings override environment variables
75    let client = AiClientBuilder::new(Provider::Groq)
76        .with_base_url("https://explicit.groq.com")
77        .with_proxy("http://explicit.proxy.com:8080")
78        .build()?;
79    println!(
80        "โœ… Client created successfully, explicit configuration overrides environment variables"
81    );
82
83    // Example 7: Different provider configurations
84    println!("\n๐Ÿ“‹ Example 7: Different provider configurations");
85
86    // Groq
87    let groq_client = AiClientBuilder::new(Provider::Groq)
88        .with_base_url("https://custom.groq.com")
89        .build()?;
90    println!("โœ… Groq client created successfully");
91
92    // DeepSeek
93    let deepseek_client = AiClientBuilder::new(Provider::DeepSeek)
94        .with_base_url("https://custom.deepseek.com")
95        .with_proxy("http://proxy.example.com:8080")
96        .build()?;
97    println!("โœ… DeepSeek client created successfully");
98
99    // Ollama (local deployment)
100    let ollama_client = AiClientBuilder::new(Provider::Ollama)
101        .with_base_url("http://localhost:11434")
102        .build()?;
103    println!("โœ… Ollama client created successfully");
104
105    // Example 8: Error handling
106    println!("\n๐Ÿ“‹ Example 8: Error handling");
107    println!("   Try to set custom configuration for unsupported provider");
108
109    match AiClientBuilder::new(Provider::OpenAI)
110        .with_base_url("https://custom.openai.com")
111        .build()
112    {
113        Ok(_) => println!("โŒ This should not succeed"),
114        Err(e) => println!("โœ… Correctly caught error: {}", e),
115    }
116
117    println!("\n๐ŸŽ‰ All examples completed!");
118    println!("\n๐Ÿ’ก Advantages of builder pattern:");
119    println!("   1. Automatic environment variable detection, reducing configuration code");
120    println!("   2. Support for progressive custom configuration");
121    println!("   3. Method chaining for cleaner code");
122    println!("   4. Backward compatible, existing code requires no changes");
123    println!("   5. Support for advanced configuration (timeout, connection pool, etc.)");
124
125    Ok(())
126}
Source

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

Set custom base URL

ยงArguments
  • base_url - Custom base URL
ยงReturns
  • Self - Builder instance for method chaining
Examples found in repository?
examples/quickstart.rs (line 18)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("๐Ÿš€ AI-lib Quickstart Example");
8    println!("============================");
9
10    // ๐ŸŽฏ Simplest usage - create client with one line of code
11    println!("\n๐Ÿ“‹ Simplest usage:");
12    let client = AiClient::new(Provider::Groq)?;
13    println!("โœ… Client created successfully!");
14
15    // ๐Ÿ”ง If you need custom configuration, use builder pattern
16    println!("\n๐Ÿ“‹ Custom configuration:");
17    let client = AiClientBuilder::new(Provider::Groq)
18        .with_base_url("https://custom.groq.com") // Optional: custom server
19        .with_proxy("http://proxy.example.com:8080") // Optional: custom proxy
20        .build()?;
21    println!("โœ… Custom client created successfully!");
22
23    // ๐Ÿ“ Create chat request
24    println!("\n๐Ÿ“‹ Create chat request:");
25    let request = ChatCompletionRequest::new(
26        "llama3-8b-8192".to_string(), // Model name
27        vec![Message {
28            role: Role::User,
29            content: Content::Text("Hello! How are you?".to_string()),
30            function_call: None,
31        }],
32    );
33    println!("โœ… Request created successfully!");
34
35    // ๐ŸŒ Send request (requires GROQ_API_KEY environment variable)
36    println!("\n๐Ÿ“‹ Send request:");
37    println!("   Note: Set GROQ_API_KEY environment variable for actual API calls");
38    println!("   Usage: export GROQ_API_KEY=your_api_key_here");
39
40    // Check if API key is available
41    match std::env::var("GROQ_API_KEY") {
42        Ok(_) => {
43            println!("โœ… GROQ_API_KEY detected, ready to send actual requests");
44            // Uncomment the following code to send actual request
45            // let response = client.chat_completion(request).await?;
46            // println!("๐Ÿค– AI response: {}", response.choices[0].message.content.as_text());
47        }
48        Err(_) => {
49            println!("โ„น๏ธ  GROQ_API_KEY not set, skipping actual request");
50            println!("   This is a demo showing how to build requests");
51        }
52    }
53
54    // ๐ŸŽจ More customization options
55    println!("\n๐Ÿ“‹ More customization options:");
56    let advanced_client = AiClientBuilder::new(Provider::Groq)
57        .with_timeout(std::time::Duration::from_secs(60)) // 60 second timeout
58        .with_pool_config(16, std::time::Duration::from_secs(60)) // Connection pool config
59        .build()?;
60    println!("โœ… Advanced configuration client created successfully!");
61
62    // ๐Ÿ”„ Switch to other providers
63    println!("\n๐Ÿ“‹ Switch to other providers:");
64    let deepseek_client = AiClient::new(Provider::DeepSeek)?;
65    println!("โœ… DeepSeek client created successfully!");
66
67    let ollama_client = AiClient::new(Provider::Ollama)?;
68    println!("โœ… Ollama client created successfully!");
69
70    println!("\n๐ŸŽ‰ Quickstart completed!");
71    println!("\n๐Ÿ’ก Key points:");
72    println!("   1. AiClient::new() - Simplest usage with automatic environment detection");
73    println!("   2. AiClientBuilder - Builder pattern with custom configuration support");
74    println!(
75        "   3. Environment variable priority: Explicit setting > Environment variable > Default"
76    );
77    println!("   4. Support for all mainstream AI providers");
78    println!("   5. Backward compatible, existing code requires no changes");
79
80    Ok(())
81}
More examples
Hide additional examples
examples/builder_pattern.rs (line 26)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    println!("๐Ÿš€ AI Client Builder Pattern Example");
9    println!("===================================");
10
11    // Example 1: Simplest usage - automatic environment variable detection
12    println!("\n๐Ÿ“‹ Example 1: Simplest usage");
13    println!("   Automatically detect GROQ_BASE_URL and AI_PROXY_URL from environment variables");
14
15    let client = AiClientBuilder::new(Provider::Groq).build()?;
16    println!(
17        "โœ… Client created successfully, provider: {:?}",
18        client.current_provider()
19    );
20
21    // Example 2: Custom base_url
22    println!("\n๐Ÿ“‹ Example 2: Custom base_url");
23    println!("   Use custom Groq server address");
24
25    let client = AiClientBuilder::new(Provider::Groq)
26        .with_base_url("https://custom.groq.com")
27        .build()?;
28    println!("โœ… Client created successfully with custom base_url");
29
30    // Example 3: Custom base_url and proxy
31    println!("\n๐Ÿ“‹ Example 3: Custom base_url and proxy");
32    println!("   Use custom server and proxy");
33
34    let client = AiClientBuilder::new(Provider::Groq)
35        .with_base_url("https://custom.groq.com")
36        .with_proxy("http://proxy.example.com:8080")
37        .build()?;
38    println!("โœ… Client created successfully with custom base_url and proxy");
39
40    // Example 4: Full custom configuration
41    println!("\n๐Ÿ“‹ Example 4: Full custom configuration");
42    println!("   Custom timeout, connection pool and other advanced configurations");
43
44    let client = AiClientBuilder::new(Provider::Groq)
45        .with_base_url("https://custom.groq.com")
46        .with_proxy("http://proxy.example.com:8080")
47        .with_timeout(Duration::from_secs(60))
48        .with_pool_config(32, Duration::from_secs(90))
49        .build()?;
50    println!("โœ… Client created successfully with full custom configuration");
51
52    // Example 5: Use convenient builder method
53    println!("\n๐Ÿ“‹ Example 5: Use convenient builder method");
54    println!("   Create builder through AiClient::builder()");
55
56    let client = AiClient::builder(Provider::Groq)
57        .with_base_url("https://custom.groq.com")
58        .with_proxy("http://proxy.example.com:8080")
59        .build()?;
60    println!("โœ… Client created successfully using convenient builder method");
61
62    // Example 6: Environment variable priority demonstration
63    println!("\n๐Ÿ“‹ Example 6: Environment variable priority demonstration");
64    println!("   Set environment variables, then use builder");
65
66    // Set environment variables
67    std::env::set_var("GROQ_BASE_URL", "https://env.groq.com");
68    std::env::set_var("AI_PROXY_URL", "http://env.proxy.com:8080");
69
70    // Don't set any custom configuration, should use environment variables
71    let client = AiClientBuilder::new(Provider::Groq).build()?;
72    println!("โœ… Client created successfully using environment variable configuration");
73
74    // Explicit settings override environment variables
75    let client = AiClientBuilder::new(Provider::Groq)
76        .with_base_url("https://explicit.groq.com")
77        .with_proxy("http://explicit.proxy.com:8080")
78        .build()?;
79    println!(
80        "โœ… Client created successfully, explicit configuration overrides environment variables"
81    );
82
83    // Example 7: Different provider configurations
84    println!("\n๐Ÿ“‹ Example 7: Different provider configurations");
85
86    // Groq
87    let groq_client = AiClientBuilder::new(Provider::Groq)
88        .with_base_url("https://custom.groq.com")
89        .build()?;
90    println!("โœ… Groq client created successfully");
91
92    // DeepSeek
93    let deepseek_client = AiClientBuilder::new(Provider::DeepSeek)
94        .with_base_url("https://custom.deepseek.com")
95        .with_proxy("http://proxy.example.com:8080")
96        .build()?;
97    println!("โœ… DeepSeek client created successfully");
98
99    // Ollama (local deployment)
100    let ollama_client = AiClientBuilder::new(Provider::Ollama)
101        .with_base_url("http://localhost:11434")
102        .build()?;
103    println!("โœ… Ollama client created successfully");
104
105    // Example 8: Error handling
106    println!("\n๐Ÿ“‹ Example 8: Error handling");
107    println!("   Try to set custom configuration for unsupported provider");
108
109    match AiClientBuilder::new(Provider::OpenAI)
110        .with_base_url("https://custom.openai.com")
111        .build()
112    {
113        Ok(_) => println!("โŒ This should not succeed"),
114        Err(e) => println!("โœ… Correctly caught error: {}", e),
115    }
116
117    println!("\n๐ŸŽ‰ All examples completed!");
118    println!("\n๐Ÿ’ก Advantages of builder pattern:");
119    println!("   1. Automatic environment variable detection, reducing configuration code");
120    println!("   2. Support for progressive custom configuration");
121    println!("   3. Method chaining for cleaner code");
122    println!("   4. Backward compatible, existing code requires no changes");
123    println!("   5. Support for advanced configuration (timeout, connection pool, etc.)");
124
125    Ok(())
126}
Source

pub fn with_proxy(self, proxy_url: &str) -> Self

Set custom proxy URL

ยงArguments
  • proxy_url - Custom proxy URL
ยงReturns
  • Self - Builder instance for method chaining
Examples found in repository?
examples/quickstart.rs (line 19)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("๐Ÿš€ AI-lib Quickstart Example");
8    println!("============================");
9
10    // ๐ŸŽฏ Simplest usage - create client with one line of code
11    println!("\n๐Ÿ“‹ Simplest usage:");
12    let client = AiClient::new(Provider::Groq)?;
13    println!("โœ… Client created successfully!");
14
15    // ๐Ÿ”ง If you need custom configuration, use builder pattern
16    println!("\n๐Ÿ“‹ Custom configuration:");
17    let client = AiClientBuilder::new(Provider::Groq)
18        .with_base_url("https://custom.groq.com") // Optional: custom server
19        .with_proxy("http://proxy.example.com:8080") // Optional: custom proxy
20        .build()?;
21    println!("โœ… Custom client created successfully!");
22
23    // ๐Ÿ“ Create chat request
24    println!("\n๐Ÿ“‹ Create chat request:");
25    let request = ChatCompletionRequest::new(
26        "llama3-8b-8192".to_string(), // Model name
27        vec![Message {
28            role: Role::User,
29            content: Content::Text("Hello! How are you?".to_string()),
30            function_call: None,
31        }],
32    );
33    println!("โœ… Request created successfully!");
34
35    // ๐ŸŒ Send request (requires GROQ_API_KEY environment variable)
36    println!("\n๐Ÿ“‹ Send request:");
37    println!("   Note: Set GROQ_API_KEY environment variable for actual API calls");
38    println!("   Usage: export GROQ_API_KEY=your_api_key_here");
39
40    // Check if API key is available
41    match std::env::var("GROQ_API_KEY") {
42        Ok(_) => {
43            println!("โœ… GROQ_API_KEY detected, ready to send actual requests");
44            // Uncomment the following code to send actual request
45            // let response = client.chat_completion(request).await?;
46            // println!("๐Ÿค– AI response: {}", response.choices[0].message.content.as_text());
47        }
48        Err(_) => {
49            println!("โ„น๏ธ  GROQ_API_KEY not set, skipping actual request");
50            println!("   This is a demo showing how to build requests");
51        }
52    }
53
54    // ๐ŸŽจ More customization options
55    println!("\n๐Ÿ“‹ More customization options:");
56    let advanced_client = AiClientBuilder::new(Provider::Groq)
57        .with_timeout(std::time::Duration::from_secs(60)) // 60 second timeout
58        .with_pool_config(16, std::time::Duration::from_secs(60)) // Connection pool config
59        .build()?;
60    println!("โœ… Advanced configuration client created successfully!");
61
62    // ๐Ÿ”„ Switch to other providers
63    println!("\n๐Ÿ“‹ Switch to other providers:");
64    let deepseek_client = AiClient::new(Provider::DeepSeek)?;
65    println!("โœ… DeepSeek client created successfully!");
66
67    let ollama_client = AiClient::new(Provider::Ollama)?;
68    println!("โœ… Ollama client created successfully!");
69
70    println!("\n๐ŸŽ‰ Quickstart completed!");
71    println!("\n๐Ÿ’ก Key points:");
72    println!("   1. AiClient::new() - Simplest usage with automatic environment detection");
73    println!("   2. AiClientBuilder - Builder pattern with custom configuration support");
74    println!(
75        "   3. Environment variable priority: Explicit setting > Environment variable > Default"
76    );
77    println!("   4. Support for all mainstream AI providers");
78    println!("   5. Backward compatible, existing code requires no changes");
79
80    Ok(())
81}
More examples
Hide additional examples
examples/builder_pattern.rs (line 36)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    println!("๐Ÿš€ AI Client Builder Pattern Example");
9    println!("===================================");
10
11    // Example 1: Simplest usage - automatic environment variable detection
12    println!("\n๐Ÿ“‹ Example 1: Simplest usage");
13    println!("   Automatically detect GROQ_BASE_URL and AI_PROXY_URL from environment variables");
14
15    let client = AiClientBuilder::new(Provider::Groq).build()?;
16    println!(
17        "โœ… Client created successfully, provider: {:?}",
18        client.current_provider()
19    );
20
21    // Example 2: Custom base_url
22    println!("\n๐Ÿ“‹ Example 2: Custom base_url");
23    println!("   Use custom Groq server address");
24
25    let client = AiClientBuilder::new(Provider::Groq)
26        .with_base_url("https://custom.groq.com")
27        .build()?;
28    println!("โœ… Client created successfully with custom base_url");
29
30    // Example 3: Custom base_url and proxy
31    println!("\n๐Ÿ“‹ Example 3: Custom base_url and proxy");
32    println!("   Use custom server and proxy");
33
34    let client = AiClientBuilder::new(Provider::Groq)
35        .with_base_url("https://custom.groq.com")
36        .with_proxy("http://proxy.example.com:8080")
37        .build()?;
38    println!("โœ… Client created successfully with custom base_url and proxy");
39
40    // Example 4: Full custom configuration
41    println!("\n๐Ÿ“‹ Example 4: Full custom configuration");
42    println!("   Custom timeout, connection pool and other advanced configurations");
43
44    let client = AiClientBuilder::new(Provider::Groq)
45        .with_base_url("https://custom.groq.com")
46        .with_proxy("http://proxy.example.com:8080")
47        .with_timeout(Duration::from_secs(60))
48        .with_pool_config(32, Duration::from_secs(90))
49        .build()?;
50    println!("โœ… Client created successfully with full custom configuration");
51
52    // Example 5: Use convenient builder method
53    println!("\n๐Ÿ“‹ Example 5: Use convenient builder method");
54    println!("   Create builder through AiClient::builder()");
55
56    let client = AiClient::builder(Provider::Groq)
57        .with_base_url("https://custom.groq.com")
58        .with_proxy("http://proxy.example.com:8080")
59        .build()?;
60    println!("โœ… Client created successfully using convenient builder method");
61
62    // Example 6: Environment variable priority demonstration
63    println!("\n๐Ÿ“‹ Example 6: Environment variable priority demonstration");
64    println!("   Set environment variables, then use builder");
65
66    // Set environment variables
67    std::env::set_var("GROQ_BASE_URL", "https://env.groq.com");
68    std::env::set_var("AI_PROXY_URL", "http://env.proxy.com:8080");
69
70    // Don't set any custom configuration, should use environment variables
71    let client = AiClientBuilder::new(Provider::Groq).build()?;
72    println!("โœ… Client created successfully using environment variable configuration");
73
74    // Explicit settings override environment variables
75    let client = AiClientBuilder::new(Provider::Groq)
76        .with_base_url("https://explicit.groq.com")
77        .with_proxy("http://explicit.proxy.com:8080")
78        .build()?;
79    println!(
80        "โœ… Client created successfully, explicit configuration overrides environment variables"
81    );
82
83    // Example 7: Different provider configurations
84    println!("\n๐Ÿ“‹ Example 7: Different provider configurations");
85
86    // Groq
87    let groq_client = AiClientBuilder::new(Provider::Groq)
88        .with_base_url("https://custom.groq.com")
89        .build()?;
90    println!("โœ… Groq client created successfully");
91
92    // DeepSeek
93    let deepseek_client = AiClientBuilder::new(Provider::DeepSeek)
94        .with_base_url("https://custom.deepseek.com")
95        .with_proxy("http://proxy.example.com:8080")
96        .build()?;
97    println!("โœ… DeepSeek client created successfully");
98
99    // Ollama (local deployment)
100    let ollama_client = AiClientBuilder::new(Provider::Ollama)
101        .with_base_url("http://localhost:11434")
102        .build()?;
103    println!("โœ… Ollama client created successfully");
104
105    // Example 8: Error handling
106    println!("\n๐Ÿ“‹ Example 8: Error handling");
107    println!("   Try to set custom configuration for unsupported provider");
108
109    match AiClientBuilder::new(Provider::OpenAI)
110        .with_base_url("https://custom.openai.com")
111        .build()
112    {
113        Ok(_) => println!("โŒ This should not succeed"),
114        Err(e) => println!("โœ… Correctly caught error: {}", e),
115    }
116
117    println!("\n๐ŸŽ‰ All examples completed!");
118    println!("\n๐Ÿ’ก Advantages of builder pattern:");
119    println!("   1. Automatic environment variable detection, reducing configuration code");
120    println!("   2. Support for progressive custom configuration");
121    println!("   3. Method chaining for cleaner code");
122    println!("   4. Backward compatible, existing code requires no changes");
123    println!("   5. Support for advanced configuration (timeout, connection pool, etc.)");
124
125    Ok(())
126}
Source

pub fn with_timeout(self, timeout: Duration) -> Self

Set custom timeout duration

ยงArguments
  • timeout - Custom timeout duration
ยงReturns
  • Self - Builder instance for method chaining
Examples found in repository?
examples/quickstart.rs (line 57)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("๐Ÿš€ AI-lib Quickstart Example");
8    println!("============================");
9
10    // ๐ŸŽฏ Simplest usage - create client with one line of code
11    println!("\n๐Ÿ“‹ Simplest usage:");
12    let client = AiClient::new(Provider::Groq)?;
13    println!("โœ… Client created successfully!");
14
15    // ๐Ÿ”ง If you need custom configuration, use builder pattern
16    println!("\n๐Ÿ“‹ Custom configuration:");
17    let client = AiClientBuilder::new(Provider::Groq)
18        .with_base_url("https://custom.groq.com") // Optional: custom server
19        .with_proxy("http://proxy.example.com:8080") // Optional: custom proxy
20        .build()?;
21    println!("โœ… Custom client created successfully!");
22
23    // ๐Ÿ“ Create chat request
24    println!("\n๐Ÿ“‹ Create chat request:");
25    let request = ChatCompletionRequest::new(
26        "llama3-8b-8192".to_string(), // Model name
27        vec![Message {
28            role: Role::User,
29            content: Content::Text("Hello! How are you?".to_string()),
30            function_call: None,
31        }],
32    );
33    println!("โœ… Request created successfully!");
34
35    // ๐ŸŒ Send request (requires GROQ_API_KEY environment variable)
36    println!("\n๐Ÿ“‹ Send request:");
37    println!("   Note: Set GROQ_API_KEY environment variable for actual API calls");
38    println!("   Usage: export GROQ_API_KEY=your_api_key_here");
39
40    // Check if API key is available
41    match std::env::var("GROQ_API_KEY") {
42        Ok(_) => {
43            println!("โœ… GROQ_API_KEY detected, ready to send actual requests");
44            // Uncomment the following code to send actual request
45            // let response = client.chat_completion(request).await?;
46            // println!("๐Ÿค– AI response: {}", response.choices[0].message.content.as_text());
47        }
48        Err(_) => {
49            println!("โ„น๏ธ  GROQ_API_KEY not set, skipping actual request");
50            println!("   This is a demo showing how to build requests");
51        }
52    }
53
54    // ๐ŸŽจ More customization options
55    println!("\n๐Ÿ“‹ More customization options:");
56    let advanced_client = AiClientBuilder::new(Provider::Groq)
57        .with_timeout(std::time::Duration::from_secs(60)) // 60 second timeout
58        .with_pool_config(16, std::time::Duration::from_secs(60)) // Connection pool config
59        .build()?;
60    println!("โœ… Advanced configuration client created successfully!");
61
62    // ๐Ÿ”„ Switch to other providers
63    println!("\n๐Ÿ“‹ Switch to other providers:");
64    let deepseek_client = AiClient::new(Provider::DeepSeek)?;
65    println!("โœ… DeepSeek client created successfully!");
66
67    let ollama_client = AiClient::new(Provider::Ollama)?;
68    println!("โœ… Ollama client created successfully!");
69
70    println!("\n๐ŸŽ‰ Quickstart completed!");
71    println!("\n๐Ÿ’ก Key points:");
72    println!("   1. AiClient::new() - Simplest usage with automatic environment detection");
73    println!("   2. AiClientBuilder - Builder pattern with custom configuration support");
74    println!(
75        "   3. Environment variable priority: Explicit setting > Environment variable > Default"
76    );
77    println!("   4. Support for all mainstream AI providers");
78    println!("   5. Backward compatible, existing code requires no changes");
79
80    Ok(())
81}
More examples
Hide additional examples
examples/builder_pattern.rs (line 47)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    println!("๐Ÿš€ AI Client Builder Pattern Example");
9    println!("===================================");
10
11    // Example 1: Simplest usage - automatic environment variable detection
12    println!("\n๐Ÿ“‹ Example 1: Simplest usage");
13    println!("   Automatically detect GROQ_BASE_URL and AI_PROXY_URL from environment variables");
14
15    let client = AiClientBuilder::new(Provider::Groq).build()?;
16    println!(
17        "โœ… Client created successfully, provider: {:?}",
18        client.current_provider()
19    );
20
21    // Example 2: Custom base_url
22    println!("\n๐Ÿ“‹ Example 2: Custom base_url");
23    println!("   Use custom Groq server address");
24
25    let client = AiClientBuilder::new(Provider::Groq)
26        .with_base_url("https://custom.groq.com")
27        .build()?;
28    println!("โœ… Client created successfully with custom base_url");
29
30    // Example 3: Custom base_url and proxy
31    println!("\n๐Ÿ“‹ Example 3: Custom base_url and proxy");
32    println!("   Use custom server and proxy");
33
34    let client = AiClientBuilder::new(Provider::Groq)
35        .with_base_url("https://custom.groq.com")
36        .with_proxy("http://proxy.example.com:8080")
37        .build()?;
38    println!("โœ… Client created successfully with custom base_url and proxy");
39
40    // Example 4: Full custom configuration
41    println!("\n๐Ÿ“‹ Example 4: Full custom configuration");
42    println!("   Custom timeout, connection pool and other advanced configurations");
43
44    let client = AiClientBuilder::new(Provider::Groq)
45        .with_base_url("https://custom.groq.com")
46        .with_proxy("http://proxy.example.com:8080")
47        .with_timeout(Duration::from_secs(60))
48        .with_pool_config(32, Duration::from_secs(90))
49        .build()?;
50    println!("โœ… Client created successfully with full custom configuration");
51
52    // Example 5: Use convenient builder method
53    println!("\n๐Ÿ“‹ Example 5: Use convenient builder method");
54    println!("   Create builder through AiClient::builder()");
55
56    let client = AiClient::builder(Provider::Groq)
57        .with_base_url("https://custom.groq.com")
58        .with_proxy("http://proxy.example.com:8080")
59        .build()?;
60    println!("โœ… Client created successfully using convenient builder method");
61
62    // Example 6: Environment variable priority demonstration
63    println!("\n๐Ÿ“‹ Example 6: Environment variable priority demonstration");
64    println!("   Set environment variables, then use builder");
65
66    // Set environment variables
67    std::env::set_var("GROQ_BASE_URL", "https://env.groq.com");
68    std::env::set_var("AI_PROXY_URL", "http://env.proxy.com:8080");
69
70    // Don't set any custom configuration, should use environment variables
71    let client = AiClientBuilder::new(Provider::Groq).build()?;
72    println!("โœ… Client created successfully using environment variable configuration");
73
74    // Explicit settings override environment variables
75    let client = AiClientBuilder::new(Provider::Groq)
76        .with_base_url("https://explicit.groq.com")
77        .with_proxy("http://explicit.proxy.com:8080")
78        .build()?;
79    println!(
80        "โœ… Client created successfully, explicit configuration overrides environment variables"
81    );
82
83    // Example 7: Different provider configurations
84    println!("\n๐Ÿ“‹ Example 7: Different provider configurations");
85
86    // Groq
87    let groq_client = AiClientBuilder::new(Provider::Groq)
88        .with_base_url("https://custom.groq.com")
89        .build()?;
90    println!("โœ… Groq client created successfully");
91
92    // DeepSeek
93    let deepseek_client = AiClientBuilder::new(Provider::DeepSeek)
94        .with_base_url("https://custom.deepseek.com")
95        .with_proxy("http://proxy.example.com:8080")
96        .build()?;
97    println!("โœ… DeepSeek client created successfully");
98
99    // Ollama (local deployment)
100    let ollama_client = AiClientBuilder::new(Provider::Ollama)
101        .with_base_url("http://localhost:11434")
102        .build()?;
103    println!("โœ… Ollama client created successfully");
104
105    // Example 8: Error handling
106    println!("\n๐Ÿ“‹ Example 8: Error handling");
107    println!("   Try to set custom configuration for unsupported provider");
108
109    match AiClientBuilder::new(Provider::OpenAI)
110        .with_base_url("https://custom.openai.com")
111        .build()
112    {
113        Ok(_) => println!("โŒ This should not succeed"),
114        Err(e) => println!("โœ… Correctly caught error: {}", e),
115    }
116
117    println!("\n๐ŸŽ‰ All examples completed!");
118    println!("\n๐Ÿ’ก Advantages of builder pattern:");
119    println!("   1. Automatic environment variable detection, reducing configuration code");
120    println!("   2. Support for progressive custom configuration");
121    println!("   3. Method chaining for cleaner code");
122    println!("   4. Backward compatible, existing code requires no changes");
123    println!("   5. Support for advanced configuration (timeout, connection pool, etc.)");
124
125    Ok(())
126}
Source

pub fn with_pool_config(self, max_idle: usize, idle_timeout: Duration) -> Self

Set connection pool configuration

ยงArguments
  • max_idle - Maximum idle connections per host
  • idle_timeout - Idle connection timeout duration
ยงReturns
  • Self - Builder instance for method chaining
Examples found in repository?
examples/quickstart.rs (line 58)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("๐Ÿš€ AI-lib Quickstart Example");
8    println!("============================");
9
10    // ๐ŸŽฏ Simplest usage - create client with one line of code
11    println!("\n๐Ÿ“‹ Simplest usage:");
12    let client = AiClient::new(Provider::Groq)?;
13    println!("โœ… Client created successfully!");
14
15    // ๐Ÿ”ง If you need custom configuration, use builder pattern
16    println!("\n๐Ÿ“‹ Custom configuration:");
17    let client = AiClientBuilder::new(Provider::Groq)
18        .with_base_url("https://custom.groq.com") // Optional: custom server
19        .with_proxy("http://proxy.example.com:8080") // Optional: custom proxy
20        .build()?;
21    println!("โœ… Custom client created successfully!");
22
23    // ๐Ÿ“ Create chat request
24    println!("\n๐Ÿ“‹ Create chat request:");
25    let request = ChatCompletionRequest::new(
26        "llama3-8b-8192".to_string(), // Model name
27        vec![Message {
28            role: Role::User,
29            content: Content::Text("Hello! How are you?".to_string()),
30            function_call: None,
31        }],
32    );
33    println!("โœ… Request created successfully!");
34
35    // ๐ŸŒ Send request (requires GROQ_API_KEY environment variable)
36    println!("\n๐Ÿ“‹ Send request:");
37    println!("   Note: Set GROQ_API_KEY environment variable for actual API calls");
38    println!("   Usage: export GROQ_API_KEY=your_api_key_here");
39
40    // Check if API key is available
41    match std::env::var("GROQ_API_KEY") {
42        Ok(_) => {
43            println!("โœ… GROQ_API_KEY detected, ready to send actual requests");
44            // Uncomment the following code to send actual request
45            // let response = client.chat_completion(request).await?;
46            // println!("๐Ÿค– AI response: {}", response.choices[0].message.content.as_text());
47        }
48        Err(_) => {
49            println!("โ„น๏ธ  GROQ_API_KEY not set, skipping actual request");
50            println!("   This is a demo showing how to build requests");
51        }
52    }
53
54    // ๐ŸŽจ More customization options
55    println!("\n๐Ÿ“‹ More customization options:");
56    let advanced_client = AiClientBuilder::new(Provider::Groq)
57        .with_timeout(std::time::Duration::from_secs(60)) // 60 second timeout
58        .with_pool_config(16, std::time::Duration::from_secs(60)) // Connection pool config
59        .build()?;
60    println!("โœ… Advanced configuration client created successfully!");
61
62    // ๐Ÿ”„ Switch to other providers
63    println!("\n๐Ÿ“‹ Switch to other providers:");
64    let deepseek_client = AiClient::new(Provider::DeepSeek)?;
65    println!("โœ… DeepSeek client created successfully!");
66
67    let ollama_client = AiClient::new(Provider::Ollama)?;
68    println!("โœ… Ollama client created successfully!");
69
70    println!("\n๐ŸŽ‰ Quickstart completed!");
71    println!("\n๐Ÿ’ก Key points:");
72    println!("   1. AiClient::new() - Simplest usage with automatic environment detection");
73    println!("   2. AiClientBuilder - Builder pattern with custom configuration support");
74    println!(
75        "   3. Environment variable priority: Explicit setting > Environment variable > Default"
76    );
77    println!("   4. Support for all mainstream AI providers");
78    println!("   5. Backward compatible, existing code requires no changes");
79
80    Ok(())
81}
More examples
Hide additional examples
examples/builder_pattern.rs (line 48)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    println!("๐Ÿš€ AI Client Builder Pattern Example");
9    println!("===================================");
10
11    // Example 1: Simplest usage - automatic environment variable detection
12    println!("\n๐Ÿ“‹ Example 1: Simplest usage");
13    println!("   Automatically detect GROQ_BASE_URL and AI_PROXY_URL from environment variables");
14
15    let client = AiClientBuilder::new(Provider::Groq).build()?;
16    println!(
17        "โœ… Client created successfully, provider: {:?}",
18        client.current_provider()
19    );
20
21    // Example 2: Custom base_url
22    println!("\n๐Ÿ“‹ Example 2: Custom base_url");
23    println!("   Use custom Groq server address");
24
25    let client = AiClientBuilder::new(Provider::Groq)
26        .with_base_url("https://custom.groq.com")
27        .build()?;
28    println!("โœ… Client created successfully with custom base_url");
29
30    // Example 3: Custom base_url and proxy
31    println!("\n๐Ÿ“‹ Example 3: Custom base_url and proxy");
32    println!("   Use custom server and proxy");
33
34    let client = AiClientBuilder::new(Provider::Groq)
35        .with_base_url("https://custom.groq.com")
36        .with_proxy("http://proxy.example.com:8080")
37        .build()?;
38    println!("โœ… Client created successfully with custom base_url and proxy");
39
40    // Example 4: Full custom configuration
41    println!("\n๐Ÿ“‹ Example 4: Full custom configuration");
42    println!("   Custom timeout, connection pool and other advanced configurations");
43
44    let client = AiClientBuilder::new(Provider::Groq)
45        .with_base_url("https://custom.groq.com")
46        .with_proxy("http://proxy.example.com:8080")
47        .with_timeout(Duration::from_secs(60))
48        .with_pool_config(32, Duration::from_secs(90))
49        .build()?;
50    println!("โœ… Client created successfully with full custom configuration");
51
52    // Example 5: Use convenient builder method
53    println!("\n๐Ÿ“‹ Example 5: Use convenient builder method");
54    println!("   Create builder through AiClient::builder()");
55
56    let client = AiClient::builder(Provider::Groq)
57        .with_base_url("https://custom.groq.com")
58        .with_proxy("http://proxy.example.com:8080")
59        .build()?;
60    println!("โœ… Client created successfully using convenient builder method");
61
62    // Example 6: Environment variable priority demonstration
63    println!("\n๐Ÿ“‹ Example 6: Environment variable priority demonstration");
64    println!("   Set environment variables, then use builder");
65
66    // Set environment variables
67    std::env::set_var("GROQ_BASE_URL", "https://env.groq.com");
68    std::env::set_var("AI_PROXY_URL", "http://env.proxy.com:8080");
69
70    // Don't set any custom configuration, should use environment variables
71    let client = AiClientBuilder::new(Provider::Groq).build()?;
72    println!("โœ… Client created successfully using environment variable configuration");
73
74    // Explicit settings override environment variables
75    let client = AiClientBuilder::new(Provider::Groq)
76        .with_base_url("https://explicit.groq.com")
77        .with_proxy("http://explicit.proxy.com:8080")
78        .build()?;
79    println!(
80        "โœ… Client created successfully, explicit configuration overrides environment variables"
81    );
82
83    // Example 7: Different provider configurations
84    println!("\n๐Ÿ“‹ Example 7: Different provider configurations");
85
86    // Groq
87    let groq_client = AiClientBuilder::new(Provider::Groq)
88        .with_base_url("https://custom.groq.com")
89        .build()?;
90    println!("โœ… Groq client created successfully");
91
92    // DeepSeek
93    let deepseek_client = AiClientBuilder::new(Provider::DeepSeek)
94        .with_base_url("https://custom.deepseek.com")
95        .with_proxy("http://proxy.example.com:8080")
96        .build()?;
97    println!("โœ… DeepSeek client created successfully");
98
99    // Ollama (local deployment)
100    let ollama_client = AiClientBuilder::new(Provider::Ollama)
101        .with_base_url("http://localhost:11434")
102        .build()?;
103    println!("โœ… Ollama client created successfully");
104
105    // Example 8: Error handling
106    println!("\n๐Ÿ“‹ Example 8: Error handling");
107    println!("   Try to set custom configuration for unsupported provider");
108
109    match AiClientBuilder::new(Provider::OpenAI)
110        .with_base_url("https://custom.openai.com")
111        .build()
112    {
113        Ok(_) => println!("โŒ This should not succeed"),
114        Err(e) => println!("โœ… Correctly caught error: {}", e),
115    }
116
117    println!("\n๐ŸŽ‰ All examples completed!");
118    println!("\n๐Ÿ’ก Advantages of builder pattern:");
119    println!("   1. Automatic environment variable detection, reducing configuration code");
120    println!("   2. Support for progressive custom configuration");
121    println!("   3. Method chaining for cleaner code");
122    println!("   4. Backward compatible, existing code requires no changes");
123    println!("   5. Support for advanced configuration (timeout, connection pool, etc.)");
124
125    Ok(())
126}
Source

pub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self

Set custom metrics implementation

ยงArguments
  • metrics - Custom metrics implementation
ยงReturns
  • Self - Builder instance for method chaining
Source

pub fn build(self) -> Result<AiClient, AiLibError>

Build AiClient instance

The build process applies configuration in the following priority order:

  1. Explicitly set configuration (via with_* methods)
  2. Environment variable configuration
  3. Default configuration
ยงReturns
  • Result<AiClient, AiLibError> - Returns client instance on success, error on failure
Examples found in repository?
examples/quickstart.rs (line 20)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("๐Ÿš€ AI-lib Quickstart Example");
8    println!("============================");
9
10    // ๐ŸŽฏ Simplest usage - create client with one line of code
11    println!("\n๐Ÿ“‹ Simplest usage:");
12    let client = AiClient::new(Provider::Groq)?;
13    println!("โœ… Client created successfully!");
14
15    // ๐Ÿ”ง If you need custom configuration, use builder pattern
16    println!("\n๐Ÿ“‹ Custom configuration:");
17    let client = AiClientBuilder::new(Provider::Groq)
18        .with_base_url("https://custom.groq.com") // Optional: custom server
19        .with_proxy("http://proxy.example.com:8080") // Optional: custom proxy
20        .build()?;
21    println!("โœ… Custom client created successfully!");
22
23    // ๐Ÿ“ Create chat request
24    println!("\n๐Ÿ“‹ Create chat request:");
25    let request = ChatCompletionRequest::new(
26        "llama3-8b-8192".to_string(), // Model name
27        vec![Message {
28            role: Role::User,
29            content: Content::Text("Hello! How are you?".to_string()),
30            function_call: None,
31        }],
32    );
33    println!("โœ… Request created successfully!");
34
35    // ๐ŸŒ Send request (requires GROQ_API_KEY environment variable)
36    println!("\n๐Ÿ“‹ Send request:");
37    println!("   Note: Set GROQ_API_KEY environment variable for actual API calls");
38    println!("   Usage: export GROQ_API_KEY=your_api_key_here");
39
40    // Check if API key is available
41    match std::env::var("GROQ_API_KEY") {
42        Ok(_) => {
43            println!("โœ… GROQ_API_KEY detected, ready to send actual requests");
44            // Uncomment the following code to send actual request
45            // let response = client.chat_completion(request).await?;
46            // println!("๐Ÿค– AI response: {}", response.choices[0].message.content.as_text());
47        }
48        Err(_) => {
49            println!("โ„น๏ธ  GROQ_API_KEY not set, skipping actual request");
50            println!("   This is a demo showing how to build requests");
51        }
52    }
53
54    // ๐ŸŽจ More customization options
55    println!("\n๐Ÿ“‹ More customization options:");
56    let advanced_client = AiClientBuilder::new(Provider::Groq)
57        .with_timeout(std::time::Duration::from_secs(60)) // 60 second timeout
58        .with_pool_config(16, std::time::Duration::from_secs(60)) // Connection pool config
59        .build()?;
60    println!("โœ… Advanced configuration client created successfully!");
61
62    // ๐Ÿ”„ Switch to other providers
63    println!("\n๐Ÿ“‹ Switch to other providers:");
64    let deepseek_client = AiClient::new(Provider::DeepSeek)?;
65    println!("โœ… DeepSeek client created successfully!");
66
67    let ollama_client = AiClient::new(Provider::Ollama)?;
68    println!("โœ… Ollama client created successfully!");
69
70    println!("\n๐ŸŽ‰ Quickstart completed!");
71    println!("\n๐Ÿ’ก Key points:");
72    println!("   1. AiClient::new() - Simplest usage with automatic environment detection");
73    println!("   2. AiClientBuilder - Builder pattern with custom configuration support");
74    println!(
75        "   3. Environment variable priority: Explicit setting > Environment variable > Default"
76    );
77    println!("   4. Support for all mainstream AI providers");
78    println!("   5. Backward compatible, existing code requires no changes");
79
80    Ok(())
81}
More examples
Hide additional examples
examples/builder_pattern.rs (line 15)
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8    println!("๐Ÿš€ AI Client Builder Pattern Example");
9    println!("===================================");
10
11    // Example 1: Simplest usage - automatic environment variable detection
12    println!("\n๐Ÿ“‹ Example 1: Simplest usage");
13    println!("   Automatically detect GROQ_BASE_URL and AI_PROXY_URL from environment variables");
14
15    let client = AiClientBuilder::new(Provider::Groq).build()?;
16    println!(
17        "โœ… Client created successfully, provider: {:?}",
18        client.current_provider()
19    );
20
21    // Example 2: Custom base_url
22    println!("\n๐Ÿ“‹ Example 2: Custom base_url");
23    println!("   Use custom Groq server address");
24
25    let client = AiClientBuilder::new(Provider::Groq)
26        .with_base_url("https://custom.groq.com")
27        .build()?;
28    println!("โœ… Client created successfully with custom base_url");
29
30    // Example 3: Custom base_url and proxy
31    println!("\n๐Ÿ“‹ Example 3: Custom base_url and proxy");
32    println!("   Use custom server and proxy");
33
34    let client = AiClientBuilder::new(Provider::Groq)
35        .with_base_url("https://custom.groq.com")
36        .with_proxy("http://proxy.example.com:8080")
37        .build()?;
38    println!("โœ… Client created successfully with custom base_url and proxy");
39
40    // Example 4: Full custom configuration
41    println!("\n๐Ÿ“‹ Example 4: Full custom configuration");
42    println!("   Custom timeout, connection pool and other advanced configurations");
43
44    let client = AiClientBuilder::new(Provider::Groq)
45        .with_base_url("https://custom.groq.com")
46        .with_proxy("http://proxy.example.com:8080")
47        .with_timeout(Duration::from_secs(60))
48        .with_pool_config(32, Duration::from_secs(90))
49        .build()?;
50    println!("โœ… Client created successfully with full custom configuration");
51
52    // Example 5: Use convenient builder method
53    println!("\n๐Ÿ“‹ Example 5: Use convenient builder method");
54    println!("   Create builder through AiClient::builder()");
55
56    let client = AiClient::builder(Provider::Groq)
57        .with_base_url("https://custom.groq.com")
58        .with_proxy("http://proxy.example.com:8080")
59        .build()?;
60    println!("โœ… Client created successfully using convenient builder method");
61
62    // Example 6: Environment variable priority demonstration
63    println!("\n๐Ÿ“‹ Example 6: Environment variable priority demonstration");
64    println!("   Set environment variables, then use builder");
65
66    // Set environment variables
67    std::env::set_var("GROQ_BASE_URL", "https://env.groq.com");
68    std::env::set_var("AI_PROXY_URL", "http://env.proxy.com:8080");
69
70    // Don't set any custom configuration, should use environment variables
71    let client = AiClientBuilder::new(Provider::Groq).build()?;
72    println!("โœ… Client created successfully using environment variable configuration");
73
74    // Explicit settings override environment variables
75    let client = AiClientBuilder::new(Provider::Groq)
76        .with_base_url("https://explicit.groq.com")
77        .with_proxy("http://explicit.proxy.com:8080")
78        .build()?;
79    println!(
80        "โœ… Client created successfully, explicit configuration overrides environment variables"
81    );
82
83    // Example 7: Different provider configurations
84    println!("\n๐Ÿ“‹ Example 7: Different provider configurations");
85
86    // Groq
87    let groq_client = AiClientBuilder::new(Provider::Groq)
88        .with_base_url("https://custom.groq.com")
89        .build()?;
90    println!("โœ… Groq client created successfully");
91
92    // DeepSeek
93    let deepseek_client = AiClientBuilder::new(Provider::DeepSeek)
94        .with_base_url("https://custom.deepseek.com")
95        .with_proxy("http://proxy.example.com:8080")
96        .build()?;
97    println!("โœ… DeepSeek client created successfully");
98
99    // Ollama (local deployment)
100    let ollama_client = AiClientBuilder::new(Provider::Ollama)
101        .with_base_url("http://localhost:11434")
102        .build()?;
103    println!("โœ… Ollama client created successfully");
104
105    // Example 8: Error handling
106    println!("\n๐Ÿ“‹ Example 8: Error handling");
107    println!("   Try to set custom configuration for unsupported provider");
108
109    match AiClientBuilder::new(Provider::OpenAI)
110        .with_base_url("https://custom.openai.com")
111        .build()
112    {
113        Ok(_) => println!("โŒ This should not succeed"),
114        Err(e) => println!("โœ… Correctly caught error: {}", e),
115    }
116
117    println!("\n๐ŸŽ‰ All examples completed!");
118    println!("\n๐Ÿ’ก Advantages of builder pattern:");
119    println!("   1. Automatic environment variable detection, reducing configuration code");
120    println!("   2. Support for progressive custom configuration");
121    println!("   3. Method chaining for cleaner code");
122    println!("   4. Backward compatible, existing code requires no changes");
123    println!("   5. Support for advanced configuration (timeout, connection pool, etc.)");
124
125    Ok(())
126}

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Sourceยง

fn vzip(self) -> V

Sourceยง

impl<T> WithSubscriber for T

Sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Sourceยง

impl<T> ErasedDestructor for T
where T: 'static,