pub struct HttpTransport { /* private fields */ }
Expand description
基于reqwest的HTTP传输实现,封装所有HTTP细节
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
Examples found in repository?
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 println!("🔍 OpenAI传输层调试");
8 println!("===================");
9
10 let api_key = match std::env::var("OPENAI_API_KEY") {
11 Ok(key) => key,
12 Err(_) => {
13 println!("❌ 未设置OPENAI_API_KEY");
14 return Ok(());
15 }
16 };
17
18 // 使用我们的HttpTransport
19 let transport = HttpTransport::new();
20
21 // 测试GET请求 (模型列表) - 我们知道这个工作
22 println!("\n📋 测试GET请求 (模型列表):");
23 let mut headers = HashMap::new();
24 headers.insert("Authorization".to_string(), format!("Bearer {}", api_key));
25
26 match transport
27 .get::<serde_json::Value>("https://api.openai.com/v1/models", Some(headers))
28 .await
29 {
30 Ok(response) => {
31 let model_count = response["data"]
32 .as_array()
33 .map(|arr| arr.len())
34 .unwrap_or(0);
35 println!("✅ GET请求成功,获取到 {} 个模型", model_count);
36 }
37 Err(e) => {
38 println!("❌ GET请求失败: {}", e);
39 }
40 }
41
42 // 测试POST请求 (聊天完成) - 这个有问题
43 println!("\n💬 测试POST请求 (聊天完成):");
44 let mut headers = HashMap::new();
45 headers.insert("Authorization".to_string(), format!("Bearer {}", api_key));
46
47 let request_body = json!({
48 "model": "gpt-3.5-turbo",
49 "messages": [
50 {
51 "role": "user",
52 "content": "Say 'test' in one word."
53 }
54 ],
55 "max_tokens": 5
56 });
57
58 println!("请求体: {}", serde_json::to_string_pretty(&request_body)?);
59
60 match transport
61 .post::<serde_json::Value, serde_json::Value>(
62 "https://api.openai.com/v1/chat/completions",
63 Some(headers),
64 &request_body,
65 )
66 .await
67 {
68 Ok(response) => {
69 println!("✅ POST请求成功!");
70 println!("响应: {}", serde_json::to_string_pretty(&response)?);
71 }
72 Err(e) => {
73 println!("❌ POST请求失败: {}", e);
74
75 // 分析错误类型
76 let error_str = e.to_string();
77 if error_str.contains("you must provide a model parameter") {
78 println!("🔍 这个错误很奇怪,因为我们确实提供了model参数");
79 println!(" 可能的原因:");
80 println!(" 1. 代理服务器修改了请求体");
81 println!(" 2. Content-Type头部问题");
82 println!(" 3. JSON序列化问题");
83 }
84 }
85 }
86
87 println!("\n💡 调试结论:");
88 println!(" • GET请求工作正常 → 认证和网络连接OK");
89 println!(" • POST请求失败 → 可能是代理或请求格式问题");
90 println!(" • 建议检查代理服务器的POST请求处理");
91
92 Ok(())
93}
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_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