embellama 0.10.1

High-performance Rust library for generating text embeddings using llama-cpp
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// Copyright 2025 Embellama Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Core API integration tests for the Embellama server

#![cfg(feature = "server")]

mod server_test_helpers;

use reqwest::StatusCode;
use serial_test::serial;
use server_test_helpers::*;

#[tokio::test]
#[serial]
async fn test_health_endpoint() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .health_check(&server.base_url)
        .await
        .expect("Failed to check health");

    assert_eq!(response.status(), StatusCode::OK);

    let body: serde_json::Value = response.json().await.unwrap();
    assert_eq!(body["status"], "healthy");
    assert!(body["model"].is_string());
    assert!(body["version"].is_string());
}

#[tokio::test]
#[serial]
async fn test_models_endpoint() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .list_models(&server.base_url)
        .await
        .expect("Failed to list models");

    assert_eq!(response.status(), StatusCode::OK);

    let body: serde_json::Value = response.json().await.unwrap();
    assert_eq!(body["object"], "list");
    assert!(body["data"].is_array());
    assert!(!body["data"].as_array().unwrap().is_empty());

    // Check first model
    let first_model = &body["data"][0];
    assert_eq!(first_model["object"], "model");
    assert_eq!(first_model["id"], "test-model");
    assert_eq!(first_model["owned_by"], "embellama");
    // Verify context_size field is present (can be null or a number)
    assert!(
        first_model.get("context_size").is_some(),
        "context_size field should be present"
    );
}

#[tokio::test]
#[serial]
async fn test_single_embedding_short_text() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single("Hello world".to_string()),
            None,
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, 1);

    // Verify it's float format by default
    match &embedding_response.data[0].embedding {
        EmbeddingValue::Float(vec) => {
            assert!(!vec.is_empty());
        }
        EmbeddingValue::Base64(_) => panic!("Expected float embedding format"),
    }
}

#[tokio::test]
#[serial]
async fn test_single_embedding_medium_text() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let medium_text = "This is a medium length text that contains multiple sentences. \
                       It's designed to test how the embedding API handles typical paragraph-sized inputs. \
                       The text should be processed correctly and return valid embeddings.";

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single(medium_text.to_string()),
            None,
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, 1);
}

#[tokio::test]
#[serial]
async fn test_single_embedding_long_text() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let long_text = "Lorem ipsum ".repeat(100); // Create a long text

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single(long_text),
            None,
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, 1);
}

#[tokio::test]
#[serial]
async fn test_single_embedding_special_chars() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let special_text = "Text with special characters: café, naïve, 日本語, emoji 🚀, symbols @#$%";

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single(special_text.to_string()),
            None,
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, 1);
}

#[tokio::test]
#[serial]
async fn test_batch_embeddings_small() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = vec![
        "First text".to_string(),
        "Second text".to_string(),
        "Third text".to_string(),
    ];

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts.clone()),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, texts.len());
}

#[tokio::test]
#[serial]
async fn test_batch_embeddings_medium() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = generate_test_texts(10);

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts.clone()),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, texts.len());
}

#[tokio::test]
#[serial]
async fn test_batch_embeddings_large() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 4)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = generate_test_texts(50);

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts.clone()),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, texts.len());
}

#[tokio::test]
#[serial]
#[ignore = "This test is slow"]
async fn test_batch_embeddings_very_large() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 4)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = generate_test_texts(100);

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts.clone()),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, texts.len());
}

#[tokio::test]
#[serial]
async fn test_batch_embeddings_mixed_lengths() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = vec![
        "Short".to_string(),
        "This is a medium length text with more words".to_string(),
        "This is a much longer text that contains multiple sentences. It's designed to test how the embedding system handles various text lengths in a single batch. We want to ensure consistent processing.".to_string(),
        "Another short one".to_string(),
    ];

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts.clone()),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, texts.len());
}

#[tokio::test]
#[serial]
async fn test_batch_embeddings_duplicate_texts() {
    let model_path = get_test_model_path().expect("Test model not found");
    // Use n_seq_max=1 to ensure duplicate texts produce identical embeddings
    let server = TestServer::spawn_with_config(model_path, 2, Some(1))
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = vec![
        "Duplicate text".to_string(),
        "Unique text".to_string(),
        "Duplicate text".to_string(), // Same as first
        "Another unique".to_string(),
        "Duplicate text".to_string(), // Same as first again
    ];

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts.clone()),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, texts.len());

    // Verify duplicate texts produce same embeddings
    if let EmbeddingValue::Float(emb1) = &embedding_response.data[0].embedding
        && let EmbeddingValue::Float(emb2) = &embedding_response.data[2].embedding
        && let EmbeddingValue::Float(emb3) = &embedding_response.data[4].embedding
    {
        // Check embeddings are identical for duplicate texts
        for i in 0..emb1.len() {
            assert!((emb1[i] - emb2[i]).abs() < 1e-6);
            assert!((emb1[i] - emb3[i]).abs() < 1e-6);
        }
    } else {
        panic!("Expected embeddings in Float format");
    }
}

#[tokio::test]
#[serial]
async fn test_encoding_format_float() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single("Test text".to_string()),
            Some("float"),
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, 1);

    // Verify it's float format
    match &embedding_response.data[0].embedding {
        EmbeddingValue::Float(_) => {}
        EmbeddingValue::Base64(_) => panic!("Expected float embedding format"),
    }
}

#[tokio::test]
#[serial]
async fn test_encoding_format_base64() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single("Test text".to_string()),
            Some("base64"),
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();
    validate_embedding_response(&embedding_response, 1);

    // Verify it's base64 format
    match &embedding_response.data[0].embedding {
        EmbeddingValue::Base64(_) => {}
        EmbeddingValue::Float(_) => panic!("Expected base64 embedding format"),
    }
}

#[tokio::test]
#[serial]
async fn test_error_empty_input() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single(String::new()),
            None,
        )
        .await
        .expect("Failed to send request");

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let error: ErrorResponse = response.json().await.unwrap();
    assert!(error.error.message.contains("empty"));
}

#[tokio::test]
#[serial]
async fn test_error_empty_batch() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(vec![]),
            None,
        )
        .await
        .expect("Failed to send request");

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let error: ErrorResponse = response.json().await.unwrap();
    assert!(error.error.message.contains("empty"));
}

#[tokio::test]
#[serial]
async fn test_error_invalid_encoding_format() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single("Test".to_string()),
            Some("invalid_format"),
        )
        .await
        .expect("Failed to send request");

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let error: ErrorResponse = response.json().await.unwrap();
    assert!(error.error.message.contains("encoding_format"));
}

#[tokio::test]
#[serial]
async fn test_error_missing_model_field() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    // Send request without model field
    let response = client
        .client
        .post(format!("{}/v1/embeddings", server.base_url))
        .json(&serde_json::json!({
            "input": "Test text"
        }))
        .send()
        .await
        .expect("Failed to send request");

    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
#[serial]
async fn test_error_missing_input_field() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    // Send request without input field
    let response = client
        .client
        .post(format!("{}/v1/embeddings", server.base_url))
        .json(&serde_json::json!({
            "model": "test-model"
        }))
        .send()
        .await
        .expect("Failed to send request");

    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
#[serial]
async fn test_error_invalid_json() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .client
        .post(format!("{}/v1/embeddings", server.base_url))
        .header("Content-Type", "application/json")
        .body("{ invalid json }")
        .send()
        .await
        .expect("Failed to send request");

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
#[serial]
async fn test_usage_metrics_single() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Single("Test text for usage metrics".to_string()),
            None,
        )
        .await
        .expect("Failed to create embedding");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();

    // Verify usage metrics are present and reasonable
    assert!(embedding_response.usage.prompt_tokens > 0);
    assert!(embedding_response.usage.total_tokens > 0);
    assert_eq!(
        embedding_response.usage.prompt_tokens,
        embedding_response.usage.total_tokens
    );
}

#[tokio::test]
#[serial]
async fn test_usage_metrics_batch() {
    let model_path = get_test_model_path().expect("Test model not found");
    let server = TestServer::spawn(model_path, 2)
        .await
        .expect("Failed to spawn server");
    let client = TestClient::new();

    let texts = vec![
        "First text".to_string(),
        "Second text with more words".to_string(),
        "Third text that is even longer than the second one".to_string(),
    ];

    let response = client
        .embedding_request(
            &server.base_url,
            "test-model",
            EmbeddingInput::Batch(texts),
            None,
        )
        .await
        .expect("Failed to create embeddings");

    assert_eq!(response.status(), StatusCode::OK);

    let embedding_response: EmbeddingResponse = response.json().await.unwrap();

    // Verify usage metrics increase with more text
    assert!(embedding_response.usage.prompt_tokens > 3); // More than number of texts
    assert!(embedding_response.usage.total_tokens > 3);
}