api_openai 0.3.0

OpenAI's API for accessing large language models (LLMs).
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
//! Comprehensive tests for `OpenAI` Embeddings API functionality
//!
//! This test suite covers all aspects of the embeddings API including:
//! - Basic embedding creation
//! - Multiple embedding models (ada-002, 3-small, 3-large)
//! - Dimension parameter handling for embedding-3 models
//! - Error handling for malformed requests
//! - Integration tests for complete workflows
//! - Performance benchmarks

// Unit tests run without feature flags, integration tests require integration feature

use api_openai::ClientApiAccessors;
use api_openai::components::
{
  embeddings ::{ CreateEmbeddingResponse, Embedding },
  embeddings_request ::CreateEmbeddingRequest,
  common ::ResponseUsage,
};

#[ cfg( feature = "integration" ) ]
use api_openai::
{
  Client,
  error ::Result,
  environment ::OpenaiEnvironmentImpl,
  secret ::Secret,
  components ::embeddings_request::EmbeddingInput,
};

// json macro is no longer needed with typed requests

#[ cfg( feature = "integration" ) ]
use std::time::Instant;

// ===== UNIT TESTS =====

#[ test ]
fn test_embedding_structure_creation()
{
  let embedding = Embedding
  {
    index : 0,
    embedding : vec![0.1, 0.2, 0.3],
    object : "embedding".to_string(),
  };

  assert_eq!(embedding.index, 0);
  assert_eq!(embedding.embedding.len(), 3);
  assert_eq!(embedding.object, "embedding");
}

#[ test ]
fn test_create_embedding_response_structure()
{
  let usage = ResponseUsage
  {
    prompt_tokens : 10,
    completion_tokens : None,
    total_tokens : 10,
  };

  let embedding = Embedding
  {
    index : 0,
    embedding : vec![0.1, 0.2, 0.3],
    object : "embedding".to_string(),
  };

  let response = CreateEmbeddingResponse
  {
    data : vec![embedding],
    model : "text-embedding-ada-002".to_string(),
    object : "list".to_string(),
    usage,
  };

  assert_eq!(response.data.len(), 1);
  assert_eq!(response.model, "text-embedding-ada-002");
  assert_eq!(response.object, "list");
  assert_eq!(response.usage.prompt_tokens, 10);
}

#[ test ]
fn test_embedding_serialization()
{
  let embedding = Embedding
  {
    index : 0,
    embedding : vec![0.1, 0.2, 0.3],
    object : "embedding".to_string(),
  };

  let serialized = serde_json::to_string(&embedding).expect("Failed to serialize embedding");
  assert!(serialized.contains("\"index\":0"));
  assert!(serialized.contains("\"embedding\":[0.1,0.2,0.3]"));
  assert!(serialized.contains("\"object\":\"embedding\""));
}

#[ test ]
fn test_embedding_deserialization()
{
  let json_data = r#"
  {
    "index": 0,
    "embedding": [0.1, 0.2, 0.3],
    "object": "embedding"
  }
  "#;

  let embedding : Embedding = serde_json::from_str(json_data).expect("Failed to deserialize embedding");
  assert_eq!(embedding.index, 0);
  assert_eq!(embedding.embedding, vec![0.1, 0.2, 0.3]);
  assert_eq!(embedding.object, "embedding");
}

#[ test ]
fn test_create_embedding_response_deserialization()
{
  let json_data = r#"
  {
    "data": [
      {
        "index": 0,
        "embedding": [0.1, 0.2, 0.3],
        "object": "embedding"
      }
    ],
    "model": "text-embedding-ada-002",
    "object": "list",
    "usage": {
      "prompt_tokens": 10,
      "total_tokens": 10
    }
  }
  "#;

  let response : CreateEmbeddingResponse = serde_json::from_str(json_data)
    .expect("Failed to deserialize embedding response");

  assert_eq!(response.data.len(), 1);
  assert_eq!(response.data[0].index, 0);
  assert_eq!(response.data[0].embedding, vec![0.1, 0.2, 0.3]);
  assert_eq!(response.model, "text-embedding-ada-002");
  assert_eq!(response.object, "list");
  assert_eq!(response.usage.prompt_tokens, 10);
}

// ===== INTEGRATION TESTS =====

#[ cfg( feature = "integration" ) ]
fn create_test_client() -> Result< Client< OpenaiEnvironmentImpl > >
{
  let secret = Secret::load_with_fallbacks("OPENAI_API_KEY")?;
  let env = OpenaiEnvironmentImpl::build(secret, None, None, api_openai::environment::OpenAIRecommended::base_url().to_string(), api_openai::environment::OpenAIRecommended::realtime_base_url().to_string())?;
  Client::build(env)
}


#[ cfg( feature = "integration" ) ]
#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_basic_embedding_creation_ada_002()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::new_single(
    "The quick brown fox jumps over the lazy dog".to_string(),
    "text-embedding-ada-002".to_string()
  );

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.object, "list");
      assert!(response.model.starts_with("text-embedding-ada-002"),
              "Expected model to start with 'text-embedding-ada-002', got : {}", response.model);
      assert_eq!(response.data.len(), 1);
      assert_eq!(response.data[0].index, 0);
      assert_eq!(response.data[0].object, "embedding");
      assert_eq!(response.data[0].embedding.len(), 1536); // ada-002 has 1536 dimensions
      assert!(response.usage.prompt_tokens > 0);
      assert!(response.usage.total_tokens > 0);
    },
    Err(e) => panic!("Expected successful embedding creation, got error : {e:?}"),
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_embedding_creation_3_small()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::new_single(
    "This is a test sentence for text-embedding-3-small".to_string(),
    "text-embedding-3-small".to_string()
  );

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.object, "list");
      assert_eq!(response.model, "text-embedding-3-small");
      assert_eq!(response.data.len(), 1);
      assert_eq!(response.data[0].index, 0);
      assert_eq!(response.data[0].object, "embedding");
      assert_eq!(response.data[0].embedding.len(), 1536); // default dimensions for 3-small
      assert!(response.usage.prompt_tokens > 0);
    },
    Err(e) => panic!("Expected successful embedding creation, got error : {e:?}"),
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_embedding_creation_3_large()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::new_single(
    "This is a test sentence for text-embedding-3-large".to_string(),
    "text-embedding-3-large".to_string()
  );

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.object, "list");
      assert_eq!(response.model, "text-embedding-3-large");
      assert_eq!(response.data.len(), 1);
      assert_eq!(response.data[0].index, 0);
      assert_eq!(response.data[0].object, "embedding");
      assert_eq!(response.data[0].embedding.len(), 3072); // default dimensions for 3-large
      assert!(response.usage.prompt_tokens > 0);
    },
    Err(e) => panic!("Expected successful embedding creation, got error : {e:?}"),
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_embedding_with_custom_dimensions_3_small()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::former()
    .input( EmbeddingInput::Single(
      "Testing custom dimensions with text-embedding-3-small".to_string()
    ))
    .model( "text-embedding-3-small".to_string() )
    .dimensions( 512u32 )
    .form();

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.data[0].embedding.len(), 512);
    },
    Err(e) => panic!("Expected successful embedding creation with custom dimensions, got error : {e:?}"),
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_embedding_with_custom_dimensions_3_large()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::former()
    .input( EmbeddingInput::Single(
      "Testing custom dimensions with text-embedding-3-large".to_string()
    ))
    .model( "text-embedding-3-large".to_string() )
    .dimensions( 1024u32 )
    .form();

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.data[0].embedding.len(), 1024);
    },
    Err(e) => panic!("Expected successful embedding creation with custom dimensions, got error : {e:?}"),
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_batch_embedding_creation()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::new_multiple(
    vec![
      "First test sentence".to_string(),
      "Second test sentence".to_string(),
      "Third test sentence".to_string()
    ],
    "text-embedding-ada-002".to_string()
  );

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.data.len(), 3);
      assert_eq!(response.data[0].index, 0);
      assert_eq!(response.data[1].index, 1);
      assert_eq!(response.data[2].index, 2);

      for embedding in &response.data
      {
        assert_eq!(embedding.object, "embedding");
        assert_eq!(embedding.embedding.len(), 1536);
      }
    },
    Err(e) => panic!("Expected successful batch embedding creation, got error : {e:?}"),
  }
}

// ===== ERROR HANDLING TESTS =====

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_invalid_model_error()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::new_single(
    "Test input".to_string(),
    "invalid-model-name".to_string()
  );

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(_) => panic!("Expected error for invalid model, but got success"),
    Err(e) =>
    {
      // Check if the error contains information about the invalid model
      let error_str = format!("{e:?}");
      assert!(error_str.contains("model") || error_str.contains("invalid"),
              "Error should mention model or invalid : {error_str}");
    },
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_empty_input_invalid_model_error()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  // Use an invalid model to trigger an error instead of empty input
  // since OpenAI API accepts empty strings
  let request = CreateEmbeddingRequest::new_single(
    "valid input".to_string(),
    "invalid-model-name".to_string()
  );

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(_) => panic!("Expected error for invalid model, but got success"),
    Err(e) =>
    {
      // Check if the error contains information about the invalid model
      let error_str = format!("{e:?}");
      assert!(error_str.contains("model") || error_str.contains("invalid"),
              "Error should mention model or invalid : {error_str}");
    },
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_invalid_dimensions_error()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::former()
    .input( EmbeddingInput::Single( "Test input".to_string() ))
    .model( "text-embedding-3-small".to_string() )
    .dimensions( 99999u32 ) // Invalid dimension size
    .form();

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(_) => panic!("Expected error for invalid dimensions, but got success"),
    Err(e) =>
    {
      // Check if the error contains information about the invalid dimensions
      let error_str = format!("{e:?}");
      assert!(error_str.contains("dimensions") || error_str.contains("invalid"),
              "Error should mention dimensions or invalid : {error_str}");
    },
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_dimensions_with_ada_002_error()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::former()
    .input( EmbeddingInput::Single( "Test input".to_string() ))
    .model( "text-embedding-ada-002".to_string() )
    .dimensions( 512u32 ) // ada-002 doesn't support custom dimensions
    .form();

  let result = client.embeddings().create(request).await;

  match result
  {
    Ok(_) => panic!("Expected error for dimensions with ada-002, but got success"),
    Err(e) =>
    {
      // Check if the error contains information about unsupported dimensions
      let error_str = format!("{e:?}");
      assert!(error_str.contains("dimensions") || error_str.contains("support"),
              "Error should mention dimensions or support : {error_str}");
    },
  }
}

// ===== PERFORMANCE BENCHMARKS =====

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_embedding_performance_benchmark()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let request = CreateEmbeddingRequest::new_single(
    "This is a performance test for embedding generation with a reasonably long sentence to measure typical response times.".to_string(),
    "text-embedding-ada-002".to_string()
  );

  let start = Instant::now();
  let result = client.embeddings().create(request).await;
  let duration = start.elapsed();

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.data.len(), 1);
      // Performance should be reasonable (under 10 seconds for single embedding)
      assert!(duration.as_secs() < 10, "Embedding creation took too long : {duration:?}");
      println!("Embedding creation time : {duration:?}");
    },
    Err(e) => panic!("Performance test failed with error : {e:?}"),
  }
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_batch_embedding_performance()
{
  // REAL API ONLY - No conditional skipping

  let client = create_test_client().expect("Failed to create test client");

  let batch_size = 10;
  let inputs : Vec< String > = (0..batch_size)
    .map(|i| format!("Performance test sentence number {i}"))
    .collect();

  let request = CreateEmbeddingRequest::new_multiple(
    inputs,
    "text-embedding-ada-002".to_string()
  );

  let start = Instant::now();
  let result = client.embeddings().create(request).await;
  let duration = start.elapsed();

  match result
  {
    Ok(response) =>
    {
      assert_eq!(response.data.len(), batch_size);
      // Batch performance should be reasonable (under 30 seconds for 10 embeddings)
      assert!(duration.as_secs() < 30, "Batch embedding creation took too long : {duration:?}");
      println!("Batch embedding creation time for {batch_size} items : {duration:?}");
    },
    Err(e) => panic!("Batch performance test failed with error : {e:?}"),
  }
}