kreuzberg 4.7.3

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 91+ formats and 248 programming languages via tree-sitter code intelligence with async/sync APIs.
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
//! Integration tests for the /embed API endpoint.

#![cfg(all(feature = "api", feature = "embeddings"))]

use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use serde_json::json;
use tower::ServiceExt;

use kreuzberg::{
    ExtractionConfig,
    api::{EmbedResponse, create_router},
};

/// Test embed endpoint with valid texts.
#[tokio::test]
async fn test_embed_valid_texts() {
    let app = create_router(ExtractionConfig::default());

    let request_body = json!({
        "texts": ["Hello world", "Second text"]
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response: EmbedResponse = serde_json::from_slice(&body).expect("Failed to deserialize");

    assert_eq!(embed_response.count, 2);
    assert_eq!(embed_response.embeddings.len(), 2);
    assert!(embed_response.dimensions > 0);
    assert!(!embed_response.model.is_empty());

    // Verify embeddings have correct dimensions
    for embedding in &embed_response.embeddings {
        assert_eq!(embedding.len(), embed_response.dimensions);
    }
}

/// Test embed endpoint with empty texts array returns 400.
#[tokio::test]
async fn test_embed_empty_texts() {
    let app = create_router(ExtractionConfig::default());

    let request_body = json!({
        "texts": []
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

/// Test embed endpoint with custom embedding configuration.
#[tokio::test]
#[cfg_attr(target_arch = "aarch64", ignore = "ONNX Runtime model loading unstable on ARM")]
async fn test_embed_with_custom_config() {
    let app = create_router(ExtractionConfig::default());

    let request_body = json!({
        "texts": ["Test embedding with custom config"],
        "config": {
            "model": {
                "type": "preset",
                "name": "fast"
            },
            "batch_size": 32
        }
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response: EmbedResponse = serde_json::from_slice(&body).expect("Failed to deserialize");

    assert_eq!(embed_response.count, 1);
    assert_eq!(embed_response.embeddings.len(), 1);
    assert_eq!(embed_response.model, "fast");
}

/// Test embed endpoint with single text.
#[tokio::test]
#[cfg_attr(target_arch = "aarch64", ignore = "ONNX Runtime model loading unstable on ARM")]
async fn test_embed_single_text() {
    let app = create_router(ExtractionConfig::default());

    let request_body = json!({
        "texts": ["Single text for embedding"]
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response: EmbedResponse = serde_json::from_slice(&body).expect("Failed to deserialize");

    assert_eq!(embed_response.count, 1);
    assert_eq!(embed_response.embeddings.len(), 1);
}

/// Test embed endpoint with multiple texts (batch).
#[tokio::test]
async fn test_embed_batch() {
    let app = create_router(ExtractionConfig::default());

    let texts: Vec<String> = (0..10).map(|i| format!("Test text number {}", i)).collect();

    let request_body = json!({
        "texts": texts
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response: EmbedResponse = serde_json::from_slice(&body).expect("Failed to deserialize");

    assert_eq!(embed_response.count, 10);
    assert_eq!(embed_response.embeddings.len(), 10);

    // Verify all embeddings have the same dimensions
    let first_dim = embed_response.embeddings[0].len();
    for embedding in &embed_response.embeddings {
        assert_eq!(embedding.len(), first_dim);
    }
}

/// Test embed endpoint with long text.
#[tokio::test]
#[cfg_attr(target_arch = "aarch64", ignore = "ONNX Runtime model loading unstable on ARM")]
async fn test_embed_long_text() {
    let app = create_router(ExtractionConfig::default());

    let long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ".repeat(100);

    let request_body = json!({
        "texts": [long_text]
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response: EmbedResponse = serde_json::from_slice(&body).expect("Failed to deserialize");

    assert_eq!(embed_response.count, 1);
    assert_eq!(embed_response.embeddings.len(), 1);
}

/// Test embed endpoint with malformed JSON returns 400.
#[tokio::test]
async fn test_embed_malformed_json() {
    let app = create_router(ExtractionConfig::default());

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from("{invalid json}"))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

/// Test embed endpoint rejects JSON array at root level.
#[tokio::test]
async fn test_embed_rejects_json_array() {
    let app = create_router(ExtractionConfig::default());

    // Send a JSON array instead of object
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(r#"[["text1"], {"texts": ["text2"]}]"#))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

    // Should reject with 400 or 422, NOT 200
    assert!(
        response.status() == StatusCode::BAD_REQUEST || response.status() == StatusCode::UNPROCESSABLE_ENTITY,
        "Expected 400 or 422, got {}",
        response.status()
    );
}

/// Test embed endpoint rejects simple JSON array with strings.
#[tokio::test]
async fn test_embed_rejects_simple_json_array() {
    let app = create_router(ExtractionConfig::default());

    // Send a simple string array instead of object with texts field
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(r#"["text1", "text2", "text3"]"#))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    // Check that error response contains helpful message
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("Failed to read response body");
    let error_response: serde_json::Value = serde_json::from_slice(&body).expect("Failed to parse error response");

    assert!(
        error_response["message"]
            .as_str()
            .map(|msg| msg.contains("array") || msg.contains("object"))
            .unwrap_or(false)
    );
}

/// Test embed endpoint preserves embedding vector values across calls.
#[tokio::test]
#[cfg_attr(target_arch = "aarch64", ignore = "ONNX Runtime model loading unstable on ARM")]
async fn test_embed_deterministic() {
    let app = create_router(ExtractionConfig::default());

    let request_body = json!({
        "texts": ["Deterministic test"]
    });

    // First call
    let response1 = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body1 = axum::body::to_bytes(response1.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response1: EmbedResponse = serde_json::from_slice(&body1).expect("Failed to deserialize");

    // Second call with same text
    let response2 = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_body).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body2 = axum::body::to_bytes(response2.into_body(), usize::MAX)
        .await
        .expect("Failed to convert to bytes");
    let embed_response2: EmbedResponse = serde_json::from_slice(&body2).expect("Failed to deserialize");

    // Compare embeddings - they should be identical
    assert_eq!(embed_response1.embeddings.len(), embed_response2.embeddings.len());
    assert_eq!(embed_response1.embeddings[0], embed_response2.embeddings[0]);
}

/// Test embed endpoint with different embedding presets.
#[tokio::test]
#[cfg_attr(target_arch = "aarch64", ignore = "ONNX Runtime model loading unstable on ARM")]
async fn test_embed_different_presets() {
    let app = create_router(ExtractionConfig::default());

    // Test with "fast" preset
    let request_fast = json!({
        "texts": ["Test text"],
        "config": {
            "model": {
                "type": "preset",
                "name": "fast"
            }
        }
    });

    let response_fast = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_fast).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body_fast = axum::body::to_bytes(response_fast.into_body(), usize::MAX)
        .await
        .expect("Operation failed");
    let embed_fast: EmbedResponse = serde_json::from_slice(&body_fast).expect("Failed to deserialize");

    // Test with "balanced" preset
    let request_balanced = json!({
        "texts": ["Test text"],
        "config": {
            "model": {
                "type": "preset",
                "name": "balanced"
            }
        }
    });

    let response_balanced = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/embed")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request_balanced).expect("Operation failed"),
                ))
                .expect("Operation failed"),
        )
        .await
        .expect("Operation failed");

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

    let body_balanced = axum::body::to_bytes(response_balanced.into_body(), usize::MAX)
        .await
        .expect("Operation failed");
    let embed_balanced: EmbedResponse = serde_json::from_slice(&body_balanced).expect("Failed to deserialize");

    // Different presets should have different dimensions
    assert_ne!(embed_fast.dimensions, embed_balanced.dimensions);
    assert_eq!(embed_fast.model, "fast");
    assert_eq!(embed_balanced.model, "balanced");
}