pub struct HttpTransport { /* private fields */ }
Expand description
Reqwest-based HTTP transport implementation, encapsulating all HTTP details
HTTP transport implementation based on reqwest, encapsulating all HTTP details
This is the concrete implementation of the HttpClient trait, encapsulating all HTTP details
Implementations§
Source§impl HttpTransport
impl HttpTransport
Sourcepub fn new() -> Self
pub fn new() -> Self
Create new HTTP transport instance
Automatically detects AI_PROXY_URL environment variable for proxy configuration
Note: This method will always check for AI_PROXY_URL environment variable.
If you want to avoid automatic proxy detection, use new_without_proxy()
instead.
Examples found in repository?
7async fn main() -> Result<(), Box<dyn std::error::Error>> {
8 println!("🔍 OpenAI Transport Layer Debugging");
9 println!("==================================");
10
11 let api_key = match std::env::var("OPENAI_API_KEY") {
12 Ok(key) => key,
13 Err(_) => {
14 println!("❌ OPENAI_API_KEY not set");
15 return Ok(());
16 }
17 };
18
19 // Use our HttpTransport
20 let transport = HttpTransport::new();
21
22 // Test GET request (model list) - we know this works
23 println!("\n📋 Test GET request (model list):");
24 let mut headers = HashMap::new();
25 headers.insert("Authorization".to_string(), format!("Bearer {}", api_key));
26
27 match transport
28 .get::<serde_json::Value>("https://api.openai.com/v1/models", Some(headers))
29 .await
30 {
31 Ok(response) => {
32 let model_count = response["data"]
33 .as_array()
34 .map(|arr| arr.len())
35 .unwrap_or(0);
36 println!("✅ GET request successful, got {} models", model_count);
37 }
38 Err(e) => {
39 println!("❌ GET request failed: {}", e);
40 }
41 }
42
43 // Test POST request (chat completion) - this has issues
44 println!("\n💬 Test POST request (chat completion):");
45 let mut headers = HashMap::new();
46 headers.insert("Authorization".to_string(), format!("Bearer {}", api_key));
47
48 let request_body = json!({
49 "model": "gpt-3.5-turbo",
50 "messages": [
51 {
52 "role": "user",
53 "content": "Say 'test' in one word."
54 }
55 ],
56 "max_tokens": 5
57 });
58
59 println!(
60 "Request body: {}",
61 serde_json::to_string_pretty(&request_body)?
62 );
63
64 match transport
65 .post::<serde_json::Value, serde_json::Value>(
66 "https://api.openai.com/v1/chat/completions",
67 Some(headers),
68 &request_body,
69 )
70 .await
71 {
72 Ok(response) => {
73 println!("✅ POST request successful!");
74 println!("Response: {}", serde_json::to_string_pretty(&response)?);
75 }
76 Err(e) => {
77 println!("❌ POST request failed: {}", e);
78
79 // Analyze error type
80 let error_str = e.to_string();
81 if error_str.contains("you must provide a model parameter") {
82 println!("🔍 This error is strange because we did provide the model parameter");
83 println!(" Possible reasons:");
84 println!(" 1. Proxy server modified the request body");
85 println!(" 2. Content-Type header issue");
86 println!(" 3. JSON serialization issue");
87 }
88 }
89 }
90
91 println!("\n💡 Debug Conclusion:");
92 println!(" • GET request works → authentication and network connection OK");
93 println!(" • POST request fails → may be proxy or request format issue");
94 println!(" • Recommend checking proxy server's POST request handling");
95
96 Ok(())
97}
Sourcepub fn new_without_proxy() -> Self
pub fn new_without_proxy() -> Self
Create new HTTP transport instance without automatic proxy detection
This method creates a transport instance without checking AI_PROXY_URL environment variable. Use this when you want explicit control over proxy configuration.
Sourcepub fn with_timeout(timeout: Duration) -> Self
pub fn with_timeout(timeout: Duration) -> Self
Create HTTP transport instance with timeout
Automatically detects AI_PROXY_URL environment variable for proxy configuration
Sourcepub fn with_timeout_without_proxy(timeout: Duration) -> Self
pub fn with_timeout_without_proxy(timeout: Duration) -> Self
Create HTTP transport instance with timeout without automatic proxy detection
This method creates a transport instance with timeout but without checking AI_PROXY_URL environment variable.
Sourcepub fn with_client(client: Client, timeout: Duration) -> Self
pub fn with_client(client: Client, timeout: Duration) -> Self
Create an instance from an existing reqwest::Client (injected)
Examples found in repository?
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8 // Build a reqwest client with custom pool settings
9 let reqwest_client = Client::builder()
10 .pool_max_idle_per_host(32)
11 .pool_idle_timeout(Duration::from_secs(90))
12 .timeout(Duration::from_secs(30))
13 .build()?;
14
15 // Wrap into library transport and inject
16 let transport = HttpTransport::with_client(reqwest_client, Duration::from_secs(30));
17
18 let config = ProviderConfigs::groq();
19 let _adapter = GenericAdapter::with_transport(config, transport)?;
20
21 println!("Created generic adapter with custom transport");
22 Ok(())
23}
Sourcepub fn with_reqwest_client(client: Client, timeout: Duration) -> Self
pub fn with_reqwest_client(client: Client, timeout: Duration) -> Self
Convenience alias that makes the intent explicit: create from a pre-built reqwest::Client.
This is a small, descriptive wrapper around with_client
that callers may find more
discoverable when constructing transports from an external reqwest::Client
.
Sourcepub fn new_with_config(
config: HttpTransportConfig,
) -> Result<Self, TransportError>
pub fn new_with_config( config: HttpTransportConfig, ) -> Result<Self, TransportError>
Create instance using HttpTransportConfig
Examples found in repository?
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7 let cfg = HttpTransportConfig {
8 timeout: Duration::from_secs(30),
9 proxy: None,
10 pool_max_idle_per_host: Some(16),
11 pool_idle_timeout: Some(Duration::from_secs(60)),
12 };
13
14 let transport = HttpTransport::new_with_config(cfg)?;
15 let provider_cfg = ProviderConfigs::groq();
16 let _adapter = GenericAdapter::with_transport(provider_cfg, transport)?;
17
18 println!("Created adapter using HttpTransportConfig");
19 Ok(())
20}
Sourcepub fn with_proxy(
timeout: Duration,
proxy_url: Option<&str>,
) -> Result<Self, TransportError>
pub fn with_proxy( timeout: Duration, proxy_url: Option<&str>, ) -> Result<Self, TransportError>
Create HTTP transport instance with custom proxy
Source§impl HttpTransport
impl HttpTransport
Sourcepub fn boxed(self) -> DynHttpTransportRef
pub fn boxed(self) -> DynHttpTransportRef
Produce an Arc-wrapped object-safe transport reference