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(Some("http://proxy.example.com:8080"))
.build()?;
// Full custom configuration
let client = AiClientBuilder::new(Provider::Groq)
.with_base_url("https://custom.groq.com")
.with_proxy(Some("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
impl AiClientBuilder
Sourcepub fn new(provider: Provider) -> Self
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/proxy_config_test.rs (line 9)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
examples/proxy_behavior_test.rs (line 18)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 println!("Testing proxy configuration behavior in detail...\n");
7
8 // Test 1: Check current environment
9 println!("1. Current environment:");
10 match env::var("AI_PROXY_URL") {
11 Ok(url) => println!(" AI_PROXY_URL is set to: {}", url),
12 Err(_) => println!(" AI_PROXY_URL is not set"),
13 }
14 println!();
15
16 // Test 2: Default behavior - should not read environment variable
17 println!("2. Default behavior test:");
18 let _client = AiClientBuilder::new(Provider::Groq).build()?;
19 println!(" ✓ Client created with default settings");
20 println!(" ✓ No automatic proxy configuration from environment");
21 println!();
22
23 // Test 3: Explicit no-proxy setting
24 println!("3. Explicit no-proxy test:");
25 let _client = AiClientBuilder::new(Provider::Groq)
26 .without_proxy()
27 .build()?;
28 println!(" ✓ Client created with explicit no-proxy setting");
29 println!(" ✓ This ensures no proxy is used regardless of environment");
30 println!();
31
32 // Test 4: Use environment variable explicitly
33 println!("4. Environment variable proxy test:");
34 let _client = AiClientBuilder::new(Provider::Groq)
35 .with_proxy(None)
36 .build()?;
37 println!(" ✓ Client created with environment variable proxy (if available)");
38 println!(" ✓ This is the only way to use AI_PROXY_URL now");
39 println!();
40
41 // Test 5: Custom proxy URL
42 println!("5. Custom proxy URL test:");
43 let _client = AiClientBuilder::new(Provider::Groq)
44 .with_proxy(Some("http://custom.proxy.com:8080"))
45 .build()?;
46 println!(" ✓ Client created with custom proxy: http://custom.proxy.com:8080");
47 println!(" ✓ Environment variable is ignored when custom URL is provided");
48 println!();
49
50 // Test 6: Verify the new behavior
51 println!("6. Behavior verification:");
52 println!(" ✓ Before: HttpTransport::new() always read AI_PROXY_URL");
53 println!(" ✓ After: HttpTransport::new_without_proxy() used by default");
54 println!(" ✓ Before: with_proxy() required string parameter");
55 println!(" ✓ After: with_proxy(Option<&str>) supports both modes");
56 println!(" ✓ New: without_proxy() explicitly disables proxy");
57 println!();
58
59 println!("All tests passed! 🎉");
60 println!("\nSummary of changes:");
61 println!("- Default behavior no longer automatically reads AI_PROXY_URL");
62 println!("- Users must explicitly choose proxy behavior:");
63 println!(" * .build() - No proxy, no env var reading");
64 println!(" * .without_proxy() - Explicitly no proxy");
65 println!(" * .with_proxy(None) - Use AI_PROXY_URL environment variable");
66 println!(" * .with_proxy(Some(url)) - Use specific proxy URL");
67 println!("\nThis prevents the issue where clearing environment variables");
68 println!("still resulted in proxy usage due to automatic detection.");
69
70 Ok(())
71}
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(Some("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}
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(Some("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(Some("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(Some("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(Some("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(Some("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}
Sourcepub fn with_base_url(self, base_url: &str) -> Self
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/proxy_config_test.rs (line 37)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
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(Some("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}
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(Some("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(Some("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(Some("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(Some("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(Some("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}
Sourcepub fn with_proxy(self, proxy_url: Option<&str>) -> Self
pub fn with_proxy(self, proxy_url: Option<&str>) -> Self
Set custom proxy URL
§Arguments
proxy_url
- Custom proxy URL, or None to use AI_PROXY_URL environment variable
§Returns
Self
- Builder instance for method chaining
§Examples
use ai_lib::{AiClientBuilder, Provider};
// Use specific proxy URL
let client = AiClientBuilder::new(Provider::Groq)
.with_proxy(Some("http://proxy.example.com:8080"))
.build()?;
// Use AI_PROXY_URL environment variable
let client = AiClientBuilder::new(Provider::Groq)
.with_proxy(None)
.build()?;
Examples found in repository?
examples/proxy_config_test.rs (line 23)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
examples/proxy_behavior_test.rs (line 35)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 println!("Testing proxy configuration behavior in detail...\n");
7
8 // Test 1: Check current environment
9 println!("1. Current environment:");
10 match env::var("AI_PROXY_URL") {
11 Ok(url) => println!(" AI_PROXY_URL is set to: {}", url),
12 Err(_) => println!(" AI_PROXY_URL is not set"),
13 }
14 println!();
15
16 // Test 2: Default behavior - should not read environment variable
17 println!("2. Default behavior test:");
18 let _client = AiClientBuilder::new(Provider::Groq).build()?;
19 println!(" ✓ Client created with default settings");
20 println!(" ✓ No automatic proxy configuration from environment");
21 println!();
22
23 // Test 3: Explicit no-proxy setting
24 println!("3. Explicit no-proxy test:");
25 let _client = AiClientBuilder::new(Provider::Groq)
26 .without_proxy()
27 .build()?;
28 println!(" ✓ Client created with explicit no-proxy setting");
29 println!(" ✓ This ensures no proxy is used regardless of environment");
30 println!();
31
32 // Test 4: Use environment variable explicitly
33 println!("4. Environment variable proxy test:");
34 let _client = AiClientBuilder::new(Provider::Groq)
35 .with_proxy(None)
36 .build()?;
37 println!(" ✓ Client created with environment variable proxy (if available)");
38 println!(" ✓ This is the only way to use AI_PROXY_URL now");
39 println!();
40
41 // Test 5: Custom proxy URL
42 println!("5. Custom proxy URL test:");
43 let _client = AiClientBuilder::new(Provider::Groq)
44 .with_proxy(Some("http://custom.proxy.com:8080"))
45 .build()?;
46 println!(" ✓ Client created with custom proxy: http://custom.proxy.com:8080");
47 println!(" ✓ Environment variable is ignored when custom URL is provided");
48 println!();
49
50 // Test 6: Verify the new behavior
51 println!("6. Behavior verification:");
52 println!(" ✓ Before: HttpTransport::new() always read AI_PROXY_URL");
53 println!(" ✓ After: HttpTransport::new_without_proxy() used by default");
54 println!(" ✓ Before: with_proxy() required string parameter");
55 println!(" ✓ After: with_proxy(Option<&str>) supports both modes");
56 println!(" ✓ New: without_proxy() explicitly disables proxy");
57 println!();
58
59 println!("All tests passed! 🎉");
60 println!("\nSummary of changes:");
61 println!("- Default behavior no longer automatically reads AI_PROXY_URL");
62 println!("- Users must explicitly choose proxy behavior:");
63 println!(" * .build() - No proxy, no env var reading");
64 println!(" * .without_proxy() - Explicitly no proxy");
65 println!(" * .with_proxy(None) - Use AI_PROXY_URL environment variable");
66 println!(" * .with_proxy(Some(url)) - Use specific proxy URL");
67 println!("\nThis prevents the issue where clearing environment variables");
68 println!("still resulted in proxy usage due to automatic detection.");
69
70 Ok(())
71}
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(Some("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}
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(Some("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(Some("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(Some("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(Some("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(Some("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}
Sourcepub fn without_proxy(self) -> Self
pub fn without_proxy(self) -> Self
Explicitly disable proxy usage
This method ensures that no proxy will be used, regardless of environment variables.
§Returns
Self
- Builder instance for method chaining
§Example
use ai_lib::{AiClientBuilder, Provider};
let client = AiClientBuilder::new(Provider::Groq)
.build()?;
Examples found in repository?
examples/proxy_config_test.rs (line 16)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
examples/proxy_behavior_test.rs (line 26)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 println!("Testing proxy configuration behavior in detail...\n");
7
8 // Test 1: Check current environment
9 println!("1. Current environment:");
10 match env::var("AI_PROXY_URL") {
11 Ok(url) => println!(" AI_PROXY_URL is set to: {}", url),
12 Err(_) => println!(" AI_PROXY_URL is not set"),
13 }
14 println!();
15
16 // Test 2: Default behavior - should not read environment variable
17 println!("2. Default behavior test:");
18 let _client = AiClientBuilder::new(Provider::Groq).build()?;
19 println!(" ✓ Client created with default settings");
20 println!(" ✓ No automatic proxy configuration from environment");
21 println!();
22
23 // Test 3: Explicit no-proxy setting
24 println!("3. Explicit no-proxy test:");
25 let _client = AiClientBuilder::new(Provider::Groq)
26 .without_proxy()
27 .build()?;
28 println!(" ✓ Client created with explicit no-proxy setting");
29 println!(" ✓ This ensures no proxy is used regardless of environment");
30 println!();
31
32 // Test 4: Use environment variable explicitly
33 println!("4. Environment variable proxy test:");
34 let _client = AiClientBuilder::new(Provider::Groq)
35 .with_proxy(None)
36 .build()?;
37 println!(" ✓ Client created with environment variable proxy (if available)");
38 println!(" ✓ This is the only way to use AI_PROXY_URL now");
39 println!();
40
41 // Test 5: Custom proxy URL
42 println!("5. Custom proxy URL test:");
43 let _client = AiClientBuilder::new(Provider::Groq)
44 .with_proxy(Some("http://custom.proxy.com:8080"))
45 .build()?;
46 println!(" ✓ Client created with custom proxy: http://custom.proxy.com:8080");
47 println!(" ✓ Environment variable is ignored when custom URL is provided");
48 println!();
49
50 // Test 6: Verify the new behavior
51 println!("6. Behavior verification:");
52 println!(" ✓ Before: HttpTransport::new() always read AI_PROXY_URL");
53 println!(" ✓ After: HttpTransport::new_without_proxy() used by default");
54 println!(" ✓ Before: with_proxy() required string parameter");
55 println!(" ✓ After: with_proxy(Option<&str>) supports both modes");
56 println!(" ✓ New: without_proxy() explicitly disables proxy");
57 println!();
58
59 println!("All tests passed! 🎉");
60 println!("\nSummary of changes:");
61 println!("- Default behavior no longer automatically reads AI_PROXY_URL");
62 println!("- Users must explicitly choose proxy behavior:");
63 println!(" * .build() - No proxy, no env var reading");
64 println!(" * .without_proxy() - Explicitly no proxy");
65 println!(" * .with_proxy(None) - Use AI_PROXY_URL environment variable");
66 println!(" * .with_proxy(Some(url)) - Use specific proxy URL");
67 println!("\nThis prevents the issue where clearing environment variables");
68 println!("still resulted in proxy usage due to automatic detection.");
69
70 Ok(())
71}
Sourcepub fn with_timeout(self, timeout: Duration) -> Self
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/proxy_config_test.rs (line 39)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
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(Some("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}
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(Some("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(Some("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(Some("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(Some("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(Some("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}
Sourcepub fn with_pool_config(self, max_idle: usize, idle_timeout: Duration) -> Self
pub fn with_pool_config(self, max_idle: usize, idle_timeout: Duration) -> Self
Set connection pool configuration
§Arguments
max_idle
- Maximum idle connections per hostidle_timeout
- Idle connection timeout duration
§Returns
Self
- Builder instance for method chaining
Examples found in repository?
examples/proxy_config_test.rs (line 40)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
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(Some("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}
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(Some("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(Some("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(Some("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(Some("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(Some("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}
Sourcepub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self
pub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self
Sourcepub fn build(self) -> Result<AiClient, AiLibError>
pub fn build(self) -> Result<AiClient, AiLibError>
Build AiClient instance
The build process applies configuration in the following priority order:
- Explicitly set configuration (via with_* methods)
- Environment variable configuration
- Default configuration
§Returns
Result<AiClient, AiLibError>
- Returns client instance on success, error on failure
Examples found in repository?
examples/proxy_config_test.rs (line 9)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 println!("Testing different proxy configuration modes...\n");
6
7 // Test 1: Default behavior - no proxy, no environment variable reading
8 println!("1. Default behavior (no proxy, no env var reading):");
9 let client = AiClientBuilder::new(Provider::Groq).build()?;
10 println!(" ✓ Client created successfully without proxy");
11 println!(" ✓ No AI_PROXY_URL environment variable was read\n");
12
13 // Test 2: Explicitly disable proxy
14 println!("2. Explicitly disable proxy:");
15 let client = AiClientBuilder::new(Provider::Groq)
16 .without_proxy()
17 .build()?;
18 println!(" ✓ Client created successfully with explicit no-proxy setting\n");
19
20 // Test 3: Use specific proxy URL
21 println!("3. Use specific proxy URL:");
22 let client = AiClientBuilder::new(Provider::Groq)
23 .with_proxy(Some("http://custom.proxy.com:8080"))
24 .build()?;
25 println!(" ✓ Client created successfully with custom proxy: http://custom.proxy.com:8080\n");
26
27 // Test 4: Use environment variable (if set)
28 println!("4. Use AI_PROXY_URL environment variable:");
29 let client = AiClientBuilder::new(Provider::Groq)
30 .with_proxy(None)
31 .build()?;
32 println!(" ✓ Client created successfully with environment variable proxy (if set)\n");
33
34 // Test 5: Full custom configuration
35 println!("5. Full custom configuration:");
36 let client = AiClientBuilder::new(Provider::Groq)
37 .with_base_url("https://custom.groq.com")
38 .with_proxy(Some("http://custom.proxy.com:8080"))
39 .with_timeout(std::time::Duration::from_secs(60))
40 .with_pool_config(32, std::time::Duration::from_secs(90))
41 .build()?;
42 println!(" ✓ Client created successfully with full custom configuration\n");
43
44 println!("All proxy configuration tests passed! 🎉");
45 println!("\nKey improvements:");
46 println!("- Default behavior no longer reads AI_PROXY_URL automatically");
47 println!("- with_proxy(None) reads AI_PROXY_URL when needed");
48 println!("- without_proxy() explicitly disables proxy usage");
49 println!("- with_proxy(Some(url)) uses specific proxy URL");
50
51 Ok(())
52}
More examples
examples/proxy_behavior_test.rs (line 18)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 println!("Testing proxy configuration behavior in detail...\n");
7
8 // Test 1: Check current environment
9 println!("1. Current environment:");
10 match env::var("AI_PROXY_URL") {
11 Ok(url) => println!(" AI_PROXY_URL is set to: {}", url),
12 Err(_) => println!(" AI_PROXY_URL is not set"),
13 }
14 println!();
15
16 // Test 2: Default behavior - should not read environment variable
17 println!("2. Default behavior test:");
18 let _client = AiClientBuilder::new(Provider::Groq).build()?;
19 println!(" ✓ Client created with default settings");
20 println!(" ✓ No automatic proxy configuration from environment");
21 println!();
22
23 // Test 3: Explicit no-proxy setting
24 println!("3. Explicit no-proxy test:");
25 let _client = AiClientBuilder::new(Provider::Groq)
26 .without_proxy()
27 .build()?;
28 println!(" ✓ Client created with explicit no-proxy setting");
29 println!(" ✓ This ensures no proxy is used regardless of environment");
30 println!();
31
32 // Test 4: Use environment variable explicitly
33 println!("4. Environment variable proxy test:");
34 let _client = AiClientBuilder::new(Provider::Groq)
35 .with_proxy(None)
36 .build()?;
37 println!(" ✓ Client created with environment variable proxy (if available)");
38 println!(" ✓ This is the only way to use AI_PROXY_URL now");
39 println!();
40
41 // Test 5: Custom proxy URL
42 println!("5. Custom proxy URL test:");
43 let _client = AiClientBuilder::new(Provider::Groq)
44 .with_proxy(Some("http://custom.proxy.com:8080"))
45 .build()?;
46 println!(" ✓ Client created with custom proxy: http://custom.proxy.com:8080");
47 println!(" ✓ Environment variable is ignored when custom URL is provided");
48 println!();
49
50 // Test 6: Verify the new behavior
51 println!("6. Behavior verification:");
52 println!(" ✓ Before: HttpTransport::new() always read AI_PROXY_URL");
53 println!(" ✓ After: HttpTransport::new_without_proxy() used by default");
54 println!(" ✓ Before: with_proxy() required string parameter");
55 println!(" ✓ After: with_proxy(Option<&str>) supports both modes");
56 println!(" ✓ New: without_proxy() explicitly disables proxy");
57 println!();
58
59 println!("All tests passed! 🎉");
60 println!("\nSummary of changes:");
61 println!("- Default behavior no longer automatically reads AI_PROXY_URL");
62 println!("- Users must explicitly choose proxy behavior:");
63 println!(" * .build() - No proxy, no env var reading");
64 println!(" * .without_proxy() - Explicitly no proxy");
65 println!(" * .with_proxy(None) - Use AI_PROXY_URL environment variable");
66 println!(" * .with_proxy(Some(url)) - Use specific proxy URL");
67 println!("\nThis prevents the issue where clearing environment variables");
68 println!("still resulted in proxy usage due to automatic detection.");
69
70 Ok(())
71}
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(Some("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}
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(Some("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(Some("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(Some("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(Some("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(Some("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§
impl Freeze for AiClientBuilder
impl !RefUnwindSafe for AiClientBuilder
impl Send for AiClientBuilder
impl Sync for AiClientBuilder
impl Unpin for AiClientBuilder
impl !UnwindSafe for AiClientBuilder
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more