multi-llm 1.0.0

Unified multi-provider LLM client with support for OpenAI, Anthropic, Ollama, and LMStudio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Unit Tests for OpenAI-Compatible HTTP Client
//!
//! UNIT UNDER TEST: OpenAICompatibleClient and HTTP utilities
//!
//! BUSINESS RESPONSIBILITY:
//!   - Execute HTTP requests with retry logic
//!   - Handle authentication headers
//!   - Parse success and error responses
//!   - Handle rate limiting (429) with retry-after
//!   - Handle authentication failures (401)
//!   - Handle network errors with appropriate error types
//!
//! TEST COVERAGE:
//!   - Successful HTTP requests and response parsing
//!   - Authentication header building
//!   - Error response handling (401, 429, generic errors)
//!   - Retry logic with exponential backoff
//!   - Network failure handling
//!   - Invalid response body handling

use multi_llm::error::LlmError;
use multi_llm::providers::openai_shared::http::OpenAICompatibleClient;
use multi_llm::providers::openai_shared::types::{
    OpenAIChoice, OpenAIRequest, OpenAIResponse, OpenAIResponseMessage, OpenAIUsage,
};
use multi_llm::RetryPolicy;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ============================================================================
// Helper Functions
// ============================================================================

fn create_test_request() -> OpenAIRequest {
    OpenAIRequest {
        model: "gpt-4".to_string(),
        messages: vec![],
        temperature: Some(0.7),
        max_tokens: Some(100),
        top_p: Some(1.0),
        presence_penalty: None,
        stream: None,
        response_format: None,
        tools: None,
        tool_choice: None,
    }
}

fn create_success_response() -> OpenAIResponse {
    OpenAIResponse {
        choices: vec![OpenAIChoice {
            message: OpenAIResponseMessage {
                role: "assistant".to_string(),
                content: "Hello!".to_string(),
                tool_calls: None,
            },
            finish_reason: Some("stop".to_string()),
        }],
        usage: Some(OpenAIUsage {
            prompt_tokens: 10,
            completion_tokens: 5,
            total_tokens: 15,
        }),
    }
}

// ============================================================================
// HTTP Client Tests
// ============================================================================

#[tokio::test]
async fn test_execute_chat_request_success() {
    // Test successful HTTP request execution
    // Verifies that client can make requests and parse successful responses

    let mock_server = MockServer::start().await;
    let response = create_success_response();

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&response))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_ok(), "Request should succeed");
    let response_data = result.unwrap();
    assert_eq!(response_data.choices[0].message.content, "Hello!");
    assert!(response_data.usage.is_some(), "Should have usage data");
}

#[tokio::test]
async fn test_build_auth_headers() {
    // Test authentication header construction
    // Verifies that API key is properly formatted as Bearer token

    let headers = OpenAICompatibleClient::build_auth_headers("test-api-key");

    assert!(headers.is_ok(), "Should build headers successfully");
    let headers = headers.unwrap();

    assert!(headers.contains_key("authorization"));
    assert!(headers.contains_key("content-type"));

    let auth_value = headers.get("authorization").unwrap().to_str().unwrap();
    assert_eq!(auth_value, "Bearer test-api-key");
}

#[tokio::test]
async fn test_build_auth_headers_invalid_key() {
    // Test that invalid API key format is rejected
    // Verifies error handling for malformed authentication credentials

    let result = OpenAICompatibleClient::build_auth_headers("invalid\nkey");

    assert!(result.is_err(), "Should reject invalid API key");
    match result.unwrap_err() {
        LlmError::ConfigurationError { .. } => {} // Expected
        other => panic!("Expected ConfigurationError, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_handle_401_error_response() {
    // Test authentication failure (401) error handling
    // Verifies that 401 responses are converted to authentication errors

    let mock_server = MockServer::start().await;
    let error_body = serde_json::json!({
        "error": {
            "message": "Invalid API key",
            "code": "invalid_api_key",
            "type": "authentication_error"
        }
    });

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(401).set_body_json(&error_body))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("invalid-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err(), "Should fail with authentication error");
    match result.unwrap_err() {
        LlmError::AuthenticationFailed { .. } => {} // Expected
        other => panic!("Expected AuthenticationFailed error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_handle_429_rate_limit_error() {
    // Test rate limit (429) error handling
    // Verifies that 429 responses are converted to rate limit errors with retry_after

    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(
            ResponseTemplate::new(429)
                .insert_header("retry-after", "60")
                .set_body_json(serde_json::json!({
                    "error": {
                        "message": "Rate limit exceeded",
                        "type": "rate_limit_error"
                    }
                })),
        )
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err(), "Should fail with rate limit error");
    match result.unwrap_err() {
        LlmError::RateLimitExceeded {
            retry_after_seconds,
        } => {
            assert_eq!(retry_after_seconds, 60, "Should parse retry-after header");
        }
        other => panic!("Expected RateLimitExceeded error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_handle_429_without_retry_after_header() {
    // Test rate limit error when retry-after header is missing
    // Verifies default retry_after value is used

    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(429).set_body_json(serde_json::json!({
            "error": {
                "message": "Rate limit exceeded"
            }
        })))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err(), "Should fail with rate limit error");
    match result.unwrap_err() {
        LlmError::RateLimitExceeded {
            retry_after_seconds,
        } => {
            assert_eq!(retry_after_seconds, 60, "Should use default 60 seconds");
        }
        other => panic!("Expected RateLimitExceeded error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_handle_generic_error_response() {
    // Test generic API error handling (non-401, non-429)
    // Verifies that other error status codes are converted to RequestFailed errors

    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
            "error": {
                "message": "Internal server error"
            }
        })))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err(), "Should fail with generic error");
    match result.unwrap_err() {
        LlmError::RequestFailed { .. } => {} // Expected
        other => panic!("Expected RequestFailed error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_parse_invalid_json_response() {
    // Test handling of malformed JSON in response body
    // Verifies that invalid JSON is converted to ResponseParsing error

    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_string("invalid json"))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err(), "Should fail with parsing error");
    match result.unwrap_err() {
        LlmError::ResponseParsingError { .. } => {} // Expected
        other => panic!("Expected ResponseParsingError, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_custom_retry_policy() {
    // Test that client can be configured with custom retry policy
    // Verifies retry policy configuration without actual retries

    let retry_policy = RetryPolicy {
        max_attempts: 5,
        initial_delay: std::time::Duration::from_millis(500),
        max_delay: std::time::Duration::from_millis(5000),
        backoff_multiplier: 2.0,
        total_timeout: std::time::Duration::from_secs(60),
        request_timeout: std::time::Duration::from_secs(30),
    };

    let client = OpenAICompatibleClient::with_retry_policy(retry_policy.clone());

    // Set and restore policy to verify the API works
    client.set_retry_policy(retry_policy.clone()).await;
    client.restore_default_retry_policy(&retry_policy).await;

    // If we got here without panic, the API works correctly
}

#[tokio::test]
async fn test_network_failure_handling() {
    // Test handling of network connection failures
    // Verifies that connection errors are converted to RequestFailed errors

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();

    // Use invalid URL to trigger connection failure
    let url = "http://localhost:1/invalid";

    let result = client.execute_chat_request(url, &headers, &request).await;

    assert!(result.is_err(), "Should fail with network error");
    match result.unwrap_err() {
        LlmError::RequestFailed { .. } => {} // Expected
        other => panic!("Expected RequestFailed error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_auth_header_with_content_type() {
    // Test that both Authorization and Content-Type headers are set
    // Verifies complete header configuration

    let headers = OpenAICompatibleClient::build_auth_headers("key").unwrap();

    assert!(
        headers.contains_key("authorization"),
        "Should have authorization header"
    );
    assert!(
        headers.contains_key("content-type"),
        "Should have content-type header"
    );

    let content_type = headers.get("content-type").unwrap().to_str().unwrap();
    assert_eq!(
        content_type, "application/json",
        "Content-Type should be application/json"
    );
}

#[tokio::test]
async fn test_401_error_with_auth_code() {
    // Test 401 error with authentication code in response
    // Verifies detailed error parsing for auth failures

    let mock_server = MockServer::start().await;
    let error_body = serde_json::json!({
        "error": {
            "message": "Authentication failed",
            "code": "invalid_api_key",
            "type": "authentication_error"
        }
    });

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(401).set_body_json(&error_body))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        LlmError::AuthenticationFailed { message } => {
            assert!(
                message.contains("Invalid API key") || message.contains("authentication"),
                "Error message should indicate authentication issue"
            );
        }
        other => panic!("Expected AuthenticationFailed error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_401_error_without_specific_code() {
    // Test 401 error without specific error code in response
    // Verifies fallback authentication error handling

    let mock_server = MockServer::start().await;
    let error_body = serde_json::json!({
        "error": {
            "message": "Unauthorized"
        }
    });

    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(401).set_body_json(&error_body))
        .mount(&mock_server)
        .await;

    let client = OpenAICompatibleClient::new();
    let headers = OpenAICompatibleClient::build_auth_headers("test-key").unwrap();
    let request = create_test_request();
    let url = format!("{}/v1/chat/completions", mock_server.uri());

    let result = client.execute_chat_request(&url, &headers, &request).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        LlmError::AuthenticationFailed { .. } => {} // Expected
        other => panic!("Expected AuthenticationFailed error, got: {:?}", other),
    }
}