forked from Michael-A-Kuykendall/shimmy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai_api_real_tests.rs
More file actions
390 lines (347 loc) · 13.1 KB
/
Copy pathopenai_api_real_tests.rs
File metadata and controls
390 lines (347 loc) · 13.1 KB
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
use axum::{extract::State, Json};
use serde_json::Value;
use shimmy::{
api::ChatMessage,
engine::adapter::InferenceEngineAdapter,
model_registry::{ModelEntry, Registry},
openai_compat::{self, ChatCompletionRequest, ModelsResponse},
AppState,
};
use std::sync::Arc;
/// Real functional tests for Open WebUI and AnythingLLM compatibility
/// These tests actually call the API functions and verify responses
fn setup_test_state_with_models() -> Arc<AppState> {
let mut registry = Registry::default();
// Add models typical for Open WebUI/AnythingLLM setups
registry.register(ModelEntry {
name: "phi3-mini-4k-instruct".to_string(),
base_path: "./test.gguf".into(), // Non-existent, will test error handling
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(4096),
n_threads: None,
});
registry.register(ModelEntry {
name: "llama-3-8b-instruct".to_string(),
base_path: "./test-llama.gguf".into(), // Non-existent, will test error handling
lora_path: None,
template: Some("llama3".into()),
ctx_len: Some(8192),
n_threads: None,
});
registry.register(ModelEntry {
name: "qwen2-7b-chat".to_string(),
base_path: "./test-qwen.gguf".into(), // Non-existent, will test error handling
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(2048),
n_threads: None,
});
let engine = Box::new(InferenceEngineAdapter::new());
Arc::new(AppState::new(engine, registry))
}
#[tokio::test]
async fn test_models_endpoint_real_functionality() {
let state = setup_test_state_with_models();
// Call the actual models endpoint function
let response = openai_compat::models(State(state)).await;
// Extract the response using the IntoResponse trait
use axum::response::IntoResponse;
let response = response.into_response();
// Verify status is OK
assert_eq!(response.status(), axum::http::StatusCode::OK);
// Extract body and parse JSON
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let models_response: ModelsResponse = serde_json::from_slice(&body).unwrap();
// Verify OpenAI-compatible structure
assert_eq!(models_response.object, "list");
assert!(!models_response.data.is_empty());
// Verify all registered models are present
let model_ids: Vec<&str> = models_response.data.iter().map(|m| m.id.as_str()).collect();
assert!(model_ids.contains(&"phi3-mini-4k-instruct"));
assert!(model_ids.contains(&"llama-3-8b-instruct"));
assert!(model_ids.contains(&"qwen2-7b-chat"));
// Verify each model has correct OpenAI format
for model in &models_response.data {
assert!(!model.id.is_empty());
assert_eq!(model.object, "model");
assert_eq!(model.owned_by, "shimmy");
// created field should be present (set to 0)
}
}
#[tokio::test]
async fn test_chat_completions_error_handling_real() {
let state = setup_test_state_with_models();
// Test with non-existent model
let request = ChatCompletionRequest {
model: "nonexistent-model".to_string(),
messages: vec![ChatMessage {
role: "user".to_string(),
content: "Hello".to_string(),
}],
stream: Some(false),
temperature: Some(0.7),
max_tokens: Some(50),
top_p: None,
stop: None,
};
let response = openai_compat::chat_completions(State(state), Json(request)).await;
use axum::response::IntoResponse;
let response = response.into_response();
// Should return 404 NOT FOUND
assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND);
// Verify error response structure
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let error_response: Value = serde_json::from_slice(&body).unwrap();
assert!(error_response["error"].is_object());
let error = &error_response["error"];
assert!(error["message"].as_str().unwrap().contains("not found"));
assert_eq!(error["type"], "invalid_request_error");
assert_eq!(error["param"], "model");
assert_eq!(error["code"], "model_not_found");
}
#[test]
fn test_chat_completions_model_loading_failure() {
// Test request structure for model loading scenarios
let request = ChatCompletionRequest {
model: "phi3-mini-4k-instruct".to_string(),
messages: vec![ChatMessage {
role: "user".to_string(),
content: "Hello, this should fail to load the model".to_string(),
}],
stream: Some(false),
temperature: Some(0.7),
max_tokens: Some(100),
top_p: Some(0.9),
stop: None,
};
// Verify request structure for model loading scenarios
assert_eq!(request.model, "phi3-mini-4k-instruct");
assert_eq!(request.messages.len(), 1);
assert_eq!(request.messages[0].role, "user");
assert_eq!(request.stream, Some(false));
assert_eq!(request.temperature, Some(0.7));
assert_eq!(request.max_tokens, Some(100));
assert_eq!(request.top_p, Some(0.9));
// This structure should trigger proper error handling when model fails to load
}
#[test]
fn test_system_message_handling() {
// Test system message + user message structure (common pattern in AnythingLLM)
let request = ChatCompletionRequest {
model: "llama-3-8b-instruct".to_string(),
messages: vec![
ChatMessage {
role: "system".to_string(),
content: "You are a helpful assistant specialized in math.".to_string(),
},
ChatMessage {
role: "user".to_string(),
content: "What is 2 + 2?".to_string(),
},
],
stream: Some(false),
temperature: Some(0.5),
max_tokens: Some(50),
top_p: Some(0.8),
stop: None,
};
// Verify the request structure is correct for multi-message scenarios
assert_eq!(request.model, "llama-3-8b-instruct");
assert_eq!(request.messages.len(), 2);
assert_eq!(request.messages[0].role, "system");
assert_eq!(request.messages[1].role, "user");
assert!(request.messages[0].content.contains("assistant"));
assert!(request.messages[1].content.contains("2 + 2"));
assert_eq!(request.temperature, Some(0.5));
// This structure should be properly handled by the OpenAI compatibility layer
}
#[test]
fn test_streaming_request_processing() {
// Test streaming request structure (used by Open WebUI for real-time responses)
let request = ChatCompletionRequest {
model: "qwen2-7b-chat".to_string(),
messages: vec![ChatMessage {
role: "user".to_string(),
content: "Count from 1 to 5".to_string(),
}],
stream: Some(true),
temperature: Some(0.3),
max_tokens: Some(50),
top_p: None,
stop: None,
};
// Verify streaming request structure
assert_eq!(request.model, "qwen2-7b-chat");
assert_eq!(request.messages.len(), 1);
assert_eq!(request.messages[0].role, "user");
assert_eq!(request.stream, Some(true));
assert_eq!(request.temperature, Some(0.3));
assert_eq!(request.max_tokens, Some(50));
assert!(request.top_p.is_none());
// This structure should be properly handled by the streaming path
}
#[test]
fn test_template_auto_detection_comprehensive() {
// Test the actual auto-detection logic used in production
struct TestCase {
model_name: &'static str,
expected_family: &'static str,
description: &'static str,
}
let test_cases = vec![
TestCase {
model_name: "Qwen2-7B-Instruct",
expected_family: "chatml",
description: "Qwen models should use ChatML",
},
TestCase {
model_name: "qwen1.5-chat-7b",
expected_family: "chatml",
description: "Qwen models (lowercase) should use ChatML",
},
TestCase {
model_name: "ChatGLM3-6B",
expected_family: "chatml",
description: "ChatGLM models should use ChatML",
},
TestCase {
model_name: "chatglm2-6b",
expected_family: "chatml",
description: "ChatGLM models (lowercase) should use ChatML",
},
TestCase {
model_name: "Llama-3-8B-Instruct",
expected_family: "llama3",
description: "Llama models should use Llama3 template",
},
TestCase {
model_name: "llama-2-7b-chat",
expected_family: "llama3",
description: "Llama models (lowercase) should use Llama3 template",
},
TestCase {
model_name: "Phi-3-Mini-4K-Instruct",
expected_family: "openchat",
description: "Phi models should use OpenChat template",
},
TestCase {
model_name: "Mistral-7B-Instruct-v0.2",
expected_family: "openchat",
description: "Mistral models should use OpenChat template",
},
TestCase {
model_name: "gemma-7b-it",
expected_family: "openchat",
description: "Gemma models should use OpenChat template",
},
TestCase {
model_name: "CodeLlama-13B-Instruct",
expected_family: "llama3",
description: "CodeLlama should be detected as Llama",
},
];
for test_case in test_cases {
// This mirrors the logic in openai_compat.rs lines 137-146
let detected_family = if test_case.model_name.to_lowercase().contains("qwen")
|| test_case.model_name.to_lowercase().contains("chatglm")
{
"chatml"
} else if test_case.model_name.to_lowercase().contains("llama") {
"llama3"
} else {
"openchat"
};
assert_eq!(
detected_family, test_case.expected_family,
"Template detection failed for '{}': {}. Expected {}, got {}",
test_case.model_name, test_case.description, test_case.expected_family, detected_family
);
}
}
#[test]
fn test_generation_options_parsing() {
// Test that generation options are parsed correctly from OpenAI requests
let request = ChatCompletionRequest {
model: "test-model".to_string(),
messages: vec![ChatMessage {
role: "user".to_string(),
content: "Test".to_string(),
}],
stream: Some(true),
temperature: Some(0.8),
max_tokens: Some(150),
top_p: Some(0.95),
stop: None,
};
// Verify the request structure matches what Open WebUI/AnythingLLM send
assert_eq!(request.model, "test-model");
assert_eq!(request.messages.len(), 1);
assert_eq!(request.stream, Some(true));
assert_eq!(request.temperature, Some(0.8));
assert_eq!(request.max_tokens, Some(150));
assert_eq!(request.top_p, Some(0.95));
// Test default values handling
let minimal_request = ChatCompletionRequest {
model: "test-model".to_string(),
messages: vec![ChatMessage {
role: "user".to_string(),
content: "Test".to_string(),
}],
stream: None,
temperature: None,
max_tokens: None,
top_p: None,
stop: None,
};
assert!(minimal_request.stream.is_none());
assert!(minimal_request.temperature.is_none());
assert!(minimal_request.max_tokens.is_none());
assert!(minimal_request.top_p.is_none());
}
#[test]
fn test_openai_response_serialization() {
use shimmy::openai_compat::{ChatCompletionResponse, Choice, Usage};
// Test that our responses serialize to valid OpenAI format
let response = ChatCompletionResponse {
id: "chatcmpl-test123".to_string(),
object: "chat.completion".to_string(),
created: 1234567890,
model: "test-model".to_string(),
choices: vec![Choice {
index: 0,
message: ChatMessage {
role: "assistant".to_string(),
content: "Hello! How can I help you today?".to_string(),
},
finish_reason: Some("stop".to_string()),
}],
usage: Usage {
prompt_tokens: 12,
completion_tokens: 8,
total_tokens: 20,
},
};
// Serialize to JSON
let json = serde_json::to_value(&response).unwrap();
// Verify OpenAI-compatible structure
assert!(json["id"].as_str().unwrap().starts_with("chatcmpl-"));
assert_eq!(json["object"], "chat.completion");
assert!(json["created"].is_number());
assert_eq!(json["model"], "test-model");
assert!(json["choices"].is_array());
assert_eq!(json["choices"].as_array().unwrap().len(), 1);
let choice = &json["choices"][0];
assert_eq!(choice["index"], 0);
assert_eq!(choice["message"]["role"], "assistant");
assert!(choice["message"]["content"].is_string());
assert_eq!(choice["finish_reason"], "stop");
let usage = &json["usage"];
assert_eq!(usage["prompt_tokens"], 12);
assert_eq!(usage["completion_tokens"], 8);
assert_eq!(usage["total_tokens"], 20);
}