lean-embed 0.1.0

Lean, provider-agnostic text-embeddings client for OpenAI, Gemini, Voyage, and Ollama, on rustls + ring (no OpenSSL, no aws-lc).
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
use serde_json::json;
use wiremock::matchers::{body_partial_json, header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use super::*;

// Wire (de)serialization is unit-tested inside each `providers::*` module. These
// integration tests drive the public `Client` API against an offline mock.

// ---- Builder / config ----------------------------------------------------

#[test]
fn base_url_defaults_per_provider() {
    let ollama = Client::builder(Provider::Ollama, "m").build().unwrap();
    assert_eq!(ollama.base_url, "http://localhost:11434");
    let voyage = Client::builder(Provider::Voyage, "m")
        .api_key("k")
        .build()
        .unwrap();
    assert_eq!(voyage.base_url, "https://api.voyageai.com/v1");
}

#[test]
fn base_url_override_is_trimmed() {
    let c = Client::builder(Provider::Ollama, "m")
        .base_url("http://host:1234/")
        .build()
        .unwrap();
    assert_eq!(c.base_url, "http://host:1234");
    // Blank override falls back to the default.
    let c2 = Client::builder(Provider::Ollama, "m")
        .base_url("   ")
        .build()
        .unwrap();
    assert_eq!(c2.base_url, "http://localhost:11434");
}

#[test]
fn ollama_needs_no_key() {
    let c = Client::builder(Provider::Ollama, "m").build().unwrap();
    assert!(c.api_key.is_none());
    assert_eq!(c.provider(), Provider::Ollama);
}

#[test]
fn voyage_key_from_builder_wins() {
    let c = Client::builder(Provider::Voyage, "m")
        .api_key("explicit")
        .build()
        .unwrap();
    assert_eq!(c.api_key.as_deref(), Some("explicit"));
}

#[test]
fn voyage_without_key_errors_when_env_unset() {
    // Only meaningful when the ambient environment has no key; skip otherwise
    // so the suite stays deterministic without mutating process env.
    if std::env::var(VOYAGE_API_KEY_ENV).is_ok() {
        return;
    }
    let err = Client::builder(Provider::Voyage, "m").build().unwrap_err();
    assert!(matches!(err, Error::MissingApiKey { .. }));
}

// ---- HTTP round-trip (offline mock) --------------------------------------

#[tokio::test]
async fn ollama_round_trip_returns_vectors() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/embed"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"embeddings": [[0.1, 0.2], [0.3, 0.4]]})),
        )
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Ollama, "nomic-embed-text")
        .base_url(server.uri())
        .build()
        .unwrap();
    let v = client
        .embed(&["a".into(), "b".into()], EmbedKind::Document)
        .await
        .unwrap();
    assert_eq!(v, vec![vec![0.1, 0.2], vec![0.3, 0.4]]);
}

#[tokio::test]
async fn voyage_round_trip_sorts_and_sends_dim_and_type() {
    let server = MockServer::start().await;
    // The mock only matches if the body carried the query input_type and the
    // pinned dimension - so a match proves the wire fields were sent.
    Mock::given(method("POST"))
        .and(path("/embeddings"))
        .and(body_partial_json(
            json!({"input_type": "query", "output_dimension": 2}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [
                {"embedding": [9.0, 9.0], "index": 1},
                {"embedding": [1.0, 1.0], "index": 0}
            ]
        })))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Voyage, "voyage-3.5-lite")
        .api_key("k")
        .base_url(server.uri())
        .output_dimension(2)
        .build()
        .unwrap();
    let v = client
        .embed(&["x".into(), "y".into()], EmbedKind::Query)
        .await
        .unwrap();
    // Sorted back into input order despite the out-of-order response.
    assert_eq!(v, vec![vec![1.0, 1.0], vec![9.0, 9.0]]);
}

#[tokio::test]
async fn non_success_status_becomes_api_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/embed"))
        .respond_with(ResponseTemplate::new(503).set_body_string("model loading"))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Ollama, "m")
        .base_url(server.uri())
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into()], EmbedKind::Document)
        .await
        .unwrap_err();
    match err {
        Error::Api {
            provider,
            status,
            body,
        } => {
            assert_eq!(provider, "ollama");
            assert_eq!(status, 503);
            assert!(body.contains("model loading"));
        }
        other => panic!("expected Api error, got {other:?}"),
    }
}

#[tokio::test]
async fn pinned_dimension_mismatch_is_caught() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/embed"))
        // Returns width 2 while the client pinned 1024.
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"embeddings": [[0.1, 0.2]]})))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Ollama, "m")
        .base_url(server.uri())
        .output_dimension(1024)
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into()], EmbedKind::Document)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        Error::DimMismatch {
            got: 2,
            expected: 1024,
            ..
        }
    ));
}

#[tokio::test]
async fn count_mismatch_is_caught() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/embed"))
        // One vector for two inputs.
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"embeddings": [[0.1]]})))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Ollama, "m")
        .base_url(server.uri())
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into(), "b".into()], EmbedKind::Document)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        Error::CountMismatch {
            got: 1,
            expected: 2,
            ..
        }
    ));
}

#[tokio::test]
async fn empty_input_short_circuits_without_a_request() {
    // No mock mounted: if embed hit the network this would error.
    let server = MockServer::start().await;
    let client = Client::builder(Provider::Ollama, "m")
        .base_url(server.uri())
        .build()
        .unwrap();
    let v = client.embed(&[], EmbedKind::Document).await.unwrap();
    assert!(v.is_empty());
}

#[tokio::test]
async fn max_batch_splits_requests_and_preserves_order() {
    let server = MockServer::start().await;
    // Each single-input request returns one vector; expect exactly 3 calls for
    // 3 inputs at max_batch(1).
    Mock::given(method("POST"))
        .and(path("/api/embed"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"embeddings": [[7.0]]})))
        .expect(3)
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Ollama, "m")
        .base_url(server.uri())
        .max_batch(1)
        .build()
        .unwrap();
    let v = client
        .embed(&["a".into(), "b".into(), "c".into()], EmbedKind::Document)
        .await
        .unwrap();
    assert_eq!(v, vec![vec![7.0], vec![7.0], vec![7.0]]);
    // `.expect(3)` is verified on drop of the server.
}

#[tokio::test]
async fn malformed_json_becomes_decode_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/embed"))
        .respond_with(ResponseTemplate::new(200).set_body_string("definitely not json"))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Ollama, "m")
        .base_url(server.uri())
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into()], EmbedKind::Document)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        Error::Decode {
            provider: "ollama",
            ..
        }
    ));
}

#[tokio::test]
async fn voyage_malformed_json_becomes_decode_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/embeddings"))
        .respond_with(ResponseTemplate::new(200).set_body_string("{ nope"))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Voyage, "m")
        .api_key("k")
        .base_url(server.uri())
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into()], EmbedKind::Query)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        Error::Decode {
            provider: "voyage",
            ..
        }
    ));
}

#[tokio::test]
async fn unreachable_endpoint_becomes_request_error() {
    // Port 1 refuses immediately; a tight timeout also exercises the builder.
    let client = Client::builder(Provider::Ollama, "m")
        .base_url("http://127.0.0.1:1")
        .timeout(std::time::Duration::from_secs(5))
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into()], EmbedKind::Document)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        Error::Request {
            provider: "ollama",
            ..
        }
    ));
}

#[tokio::test]
async fn voyage_unreachable_endpoint_becomes_request_error() {
    let client = Client::builder(Provider::Voyage, "m")
        .api_key("k")
        .base_url("http://127.0.0.1:1")
        .build()
        .unwrap();
    let err = client
        .embed(&["a".into()], EmbedKind::Query)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        Error::Request {
            provider: "voyage",
            ..
        }
    ));
}

/// The `Display` strings that thiserror derives, exercised for the variants a
/// caller is most likely to surface to a user.
#[test]
fn error_display_strings() {
    let api = Error::Api {
        provider: "voyage",
        status: 429,
        body: "rate limited".into(),
    };
    assert_eq!(api.to_string(), "voyage returned HTTP 429: rate limited");

    let dim = Error::DimMismatch {
        provider: "voyage",
        got: 512,
        expected: 1024,
    };
    assert_eq!(
        dim.to_string(),
        "voyage returned dimension 512 (expected 1024)"
    );

    let missing = Error::MissingApiKey {
        provider: "voyage",
        env: VOYAGE_API_KEY_ENV,
    };
    assert!(missing.to_string().contains("VOYAGE_API_KEY"));
}

// ---- OpenAI + Gemini builder / round-trip --------------------------------

#[test]
fn openai_and_gemini_base_url_defaults() {
    let openai = Client::builder(Provider::OpenAi, "m")
        .api_key("k")
        .build()
        .unwrap();
    assert_eq!(openai.base_url, "https://api.openai.com/v1");
    let gemini = Client::builder(Provider::Gemini, "m")
        .api_key("k")
        .build()
        .unwrap();
    assert_eq!(
        gemini.base_url,
        "https://generativelanguage.googleapis.com/v1beta"
    );
}

#[test]
fn keyed_providers_error_without_a_key_when_env_unset() {
    for (provider, env) in [
        (Provider::OpenAi, OPENAI_API_KEY_ENV),
        (Provider::Gemini, GEMINI_API_KEY_ENV),
    ] {
        if std::env::var(env).is_ok() {
            continue; // keep deterministic without mutating process env
        }
        let err = Client::builder(provider, "m").build().unwrap_err();
        assert!(matches!(err, Error::MissingApiKey { .. }));
    }
}

#[tokio::test]
async fn openai_round_trip_sorts_and_sends_dimensions() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/embeddings"))
        .and(body_partial_json(
            json!({"encoding_format": "float", "dimensions": 2}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [
                {"embedding": [9.0, 9.0], "index": 1},
                {"embedding": [1.0, 1.0], "index": 0}
            ]
        })))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::OpenAi, "text-embedding-3-small")
        .api_key("k")
        .base_url(server.uri())
        .output_dimension(2)
        .build()
        .unwrap();
    let v = client
        .embed(&["x".into(), "y".into()], EmbedKind::Document)
        .await
        .unwrap();
    // Sorted back into input order despite the out-of-order response.
    assert_eq!(v, vec![vec![1.0, 1.0], vec![9.0, 9.0]]);
}

#[tokio::test]
async fn gemini_round_trip_uses_header_auth_and_task_type() {
    let server = MockServer::start().await;
    // Model is `models/`-prefixed in the path; auth is the x-goog-api-key header;
    // the body carries the query taskType and pinned dimensionality.
    Mock::given(method("POST"))
        .and(path("/models/text-embedding-004:batchEmbedContents"))
        .and(header("x-goog-api-key", "secret"))
        .and(body_partial_json(json!({
            "requests": [{"taskType": "RETRIEVAL_QUERY", "outputDimensionality": 3}]
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "embeddings": [{"values": [1.0, 2.0, 3.0]}]
        })))
        .mount(&server)
        .await;

    let client = Client::builder(Provider::Gemini, "text-embedding-004")
        .api_key("secret")
        .base_url(server.uri())
        .output_dimension(3)
        .build()
        .unwrap();
    let v = client
        .embed(&["a question".into()], EmbedKind::Query)
        .await
        .unwrap();
    assert_eq!(v, vec![vec![1.0, 2.0, 3.0]]);
}

#[tokio::test]
async fn gemini_accepts_already_prefixed_model() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/models/text-embedding-004:batchEmbedContents"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(json!({"embeddings": [{"values": [0.5]}]})),
        )
        .mount(&server)
        .await;
    // Passing the model already `models/`-prefixed must not double-prefix.
    let client = Client::builder(Provider::Gemini, "models/text-embedding-004")
        .api_key("k")
        .base_url(server.uri())
        .build()
        .unwrap();
    let v = client
        .embed(&["x".into()], EmbedKind::Document)
        .await
        .unwrap();
    assert_eq!(v, vec![vec![0.5]]);
}

#[test]
fn api_key_is_redacted_in_debug() {
    let client = Client::builder(Provider::OpenAi, "m")
        .api_key("super-secret-key")
        .build()
        .unwrap();
    let dbg = format!("{client:?}");
    assert!(
        !dbg.contains("super-secret-key"),
        "key leaked in Debug: {dbg}"
    );
    assert!(dbg.contains("<redacted>"));
}