api_claude 0.4.0

Claude API for accessing Anthropic's 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
534
535
536
537
538
539
540
541
542
543
//! Request Caching Integration Tests - STRICT FAILURE POLICY
//!
//! MANDATORY INTEGRATION TEST REQUIREMENTS:
//! - These tests use REAL Anthropic API endpoints - NO MOCKING ALLOWED
//! - Tests MUST FAIL IMMEDIATELY if API secrets are not available (no graceful fallbacks)
//! - Tests MUST FAIL IMMEDIATELY on network connectivity issues
//! - Tests MUST FAIL IMMEDIATELY on API authentication failures
//! - Tests MUST FAIL IMMEDIATELY on any API endpoint errors
//! - NO SILENT PASSES allowed when problems occur
//!
//! Run with : cargo test --features integration
//! Requires : Valid `ANTHROPIC_API_KEY` in environment or ../../secret/-secrets.sh


use super::*;

mod request_caching_functionality_tests
{
  use super::*;
  use std::time::{ Duration, Instant };

  /// Test cache configuration validation
  #[ test ]
  fn test_cache_config_validation()
  {
    // Test valid configuration
    let valid_config = the_module::CacheConfig::new()
      .with_ttl_seconds( 300 )
      .with_max_entries( 1000 )
      .with_memory_limit_mb( 100 );

    assert!( valid_config.is_valid() );
    assert_eq!( valid_config.ttl_seconds(), 300 );
    assert_eq!( valid_config.max_entries(), 1000 );
    assert_eq!( valid_config.memory_limit_mb(), 100 );

    // Test invalid configurations
    let invalid_config = the_module::CacheConfig::new()
      .with_ttl_seconds( 0 ); // Should fail - TTL must be > 0

    assert!( !invalid_config.is_valid() );

    let invalid_config2 = the_module::CacheConfig::new()
      .with_max_entries( 0 ); // Should fail - max entries must be > 0

    assert!( !invalid_config2.is_valid() );
  }

  /// Test cache key generation
  #[ test ]
  fn test_cache_key_generation()
  {
    let cache = the_module::RequestCache::new( the_module::CacheConfig::default() );

    // Test that identical requests generate identical keys
    let request1 = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Hello, world!" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let request2 = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Hello, world!" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let key1 = cache.generate_cache_key( &request1 );
    let key2 = cache.generate_cache_key( &request2 );
    assert_eq!( key1, key2, "Identical requests should generate identical cache keys" );

    // Test that different requests generate different keys
    let request3 = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 200, // Different max_tokens
      messages : vec![ the_module::Message::user( "Hello, world!" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let key3 = cache.generate_cache_key( &request3 );
    assert_ne!( key1, key3, "Different requests should generate different cache keys" );
  }

  /// Test cache storage and retrieval
  #[ test ]
  fn test_cache_storage_and_retrieval()
  {
    let cache = the_module::RequestCache::new( the_module::CacheConfig::default() );

    let request = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Test message" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let response = the_module::CreateMessageResponse
    {
      id : "msg_123".to_string(),
      r#type : "message".to_string(),
      role : "assistant".to_string(),
      content : vec![ the_module::ResponseContent
      {
        r#type : "text".to_string(),
        text : Some( "Cached response".to_string() ),
      } ],
      model : "claude-3-5-haiku-20241022".to_string(),
      stop_reason : Some( "end_turn".to_string() ),
      stop_sequence : None,
      usage : the_module::Usage
      {
        input_tokens : 10,
        output_tokens : 5,
      },
    };

    // Store response in cache
    cache.store( &request, response.clone() );

    // Retrieve response from cache
    let cached_response = cache.get( &request );
    assert!( cached_response.is_some(), "Response should be cached" );

    let cached = cached_response.unwrap();
    assert_eq!( cached.id, response.id );
    assert_eq!( cached.content.len(), response.content.len() );
  }

  /// Test cache expiration (TTL)
  #[ test ]
  fn test_cache_expiration()
  {
    let config = the_module::CacheConfig::new()
      .with_ttl_seconds( 1 ); // 1 second TTL for testing

    let cache = the_module::RequestCache::new( config );

    let request = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Expiring message" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let response = the_module::CreateMessageResponse
    {
      id : "msg_exp".to_string(),
      r#type : "message".to_string(),
      role : "assistant".to_string(),
      content : vec![ the_module::ResponseContent
      {
        r#type : "text".to_string(),
        text : Some( "This will expire".to_string() ),
      } ],
      model : "claude-3-5-haiku-20241022".to_string(),
      stop_reason : Some( "end_turn".to_string() ),
      stop_sequence : None,
      usage : the_module::Usage
      {
        input_tokens : 8,
        output_tokens : 4,
      },
    };

    // Store response
    cache.store( &request, response.clone() );

    // Should be available immediately
    assert!( cache.get( &request ).is_some(), "Response should be cached immediately" );

    // Wait for expiration (1+ seconds)
    std::thread::sleep( Duration::from_millis( 1100 ) );

    // Should be expired now
    assert!( cache.get( &request ).is_none(), "Response should be expired after TTL" );
  }

  /// Test cache size limits
  #[ test ]
  fn test_cache_size_limits()
  {
    let config = the_module::CacheConfig::new()
      .with_max_entries( 2 ); // Only allow 2 entries

    let cache = the_module::RequestCache::new( config );

    // Create 3 different requests
    let requests = vec![
      the_module::CreateMessageRequest
      {
        model : "claude-3-5-haiku-20241022".to_string(),
        max_tokens : 100,
        messages : vec![ the_module::Message::user( "Message 1" ) ],
        system : None,
        temperature : None,
        stream : None,
        #[ cfg( feature = "tools" ) ]
        tools : None,
        #[ cfg( feature = "tools" ) ]
        tool_choice : None,
      },
      the_module::CreateMessageRequest
      {
        model : "claude-3-5-haiku-20241022".to_string(),
        max_tokens : 100,
        messages : vec![ the_module::Message::user( "Message 2" ) ],
        system : None,
        temperature : None,
        stream : None,
        #[ cfg( feature = "tools" ) ]
        tools : None,
        #[ cfg( feature = "tools" ) ]
        tool_choice : None,
      },
      the_module::CreateMessageRequest
      {
        model : "claude-3-5-haiku-20241022".to_string(),
        max_tokens : 100,
        messages : vec![ the_module::Message::user( "Message 3" ) ],
        system : None,
        temperature : None,
        stream : None,
        #[ cfg( feature = "tools" ) ]
        tools : None,
        #[ cfg( feature = "tools" ) ]
        tool_choice : None,
      },
    ];

    // Create sample responses
    for ( i, request ) in requests.iter().enumerate()
    {
      let response = the_module::CreateMessageResponse
      {
        id : format!( "msg_{}", i + 1 ),
        r#type : "message".to_string(),
        role : "assistant".to_string(),
        content : vec![ the_module::ResponseContent
        {
          r#type : "text".to_string(),
          text : Some( format!( "Response {}", i + 1 ) ),
        } ],
        model : "claude-3-5-haiku-20241022".to_string(),
        stop_reason : Some( "end_turn".to_string() ),
        stop_sequence : None,
        usage : the_module::Usage
        {
          input_tokens : 5,
          output_tokens : 3,
        },
      };

      cache.store( request, response.clone() );
    }

    // First two should be cached, third should evict the first
    assert!( cache.get( &requests[ 0 ] ).is_none(), "First entry should be evicted" );
    assert!( cache.get( &requests[ 1 ] ).is_some(), "Second entry should still be cached" );
    assert!( cache.get( &requests[ 2 ] ).is_some(), "Third entry should be cached" );

    // Check cache size
    assert_eq!( cache.size(), 2, "Cache should contain exactly 2 entries" );
  }

  /// Test cache invalidation
  #[ test ]
  fn test_cache_invalidation()
  {
    let cache = the_module::RequestCache::new( the_module::CacheConfig::default() );

    let request = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Invalidate me" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let response = the_module::CreateMessageResponse
    {
      id : "msg_inv".to_string(),
      r#type : "message".to_string(),
      role : "assistant".to_string(),
      content : vec![ the_module::ResponseContent
      {
        r#type : "text".to_string(),
        text : Some( "To be invalidated".to_string() ),
      } ],
      model : "claude-3-5-haiku-20241022".to_string(),
      stop_reason : Some( "end_turn".to_string() ),
      stop_sequence : None,
      usage : the_module::Usage
      {
        input_tokens : 6,
        output_tokens : 4,
      },
    };

    // Store and verify
    cache.store( &request, response.clone() );
    assert!( cache.get( &request ).is_some(), "Response should be cached" );

    // Invalidate specific entry
    cache.invalidate( &request );
    assert!( cache.get( &request ).is_none(), "Response should be invalidated" );

    // Test clear all
    cache.store( &request, response.clone() );
    assert!( cache.get( &request ).is_some(), "Response should be cached again" );

    cache.clear();
    assert!( cache.get( &request ).is_none(), "Cache should be empty after clear" );
    assert_eq!( cache.size(), 0, "Cache size should be 0 after clear" );
  }

  /// Test cache metrics and statistics
  #[ test ]
  fn test_cache_metrics()
  {
    let cache = the_module::RequestCache::new( the_module::CacheConfig::default() );

    let request = the_module::CreateMessageRequest
    {
      model : "claude-3-5-haiku-20241022".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Metrics test" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    };

    let response = the_module::CreateMessageResponse
    {
      id : "msg_metrics".to_string(),
      r#type : "message".to_string(),
      role : "assistant".to_string(),
      content : vec![ the_module::ResponseContent
      {
        r#type : "text".to_string(),
        text : Some( "Metrics response".to_string() ),
      } ],
      model : "claude-3-5-haiku-20241022".to_string(),
      stop_reason : Some( "end_turn".to_string() ),
      stop_sequence : None,
      usage : the_module::Usage
      {
        input_tokens : 5,
        output_tokens : 3,
      },
    };

    let metrics = cache.metrics();
    assert_eq!( metrics.hits(), 0 );
    assert_eq!( metrics.misses(), 0 );
    assert_eq!( metrics.stores(), 0 );

    // Store response
    cache.store( &request, response.clone() );
    let metrics = cache.metrics();
    assert_eq!( metrics.stores(), 1 );

    // Cache miss
    cache.get( &the_module::CreateMessageRequest
    {
      model : "different-model".to_string(),
      max_tokens : 100,
      messages : vec![ the_module::Message::user( "Different request" ) ],
      system : None,
      temperature : None,
      stream : None,
      #[ cfg( feature = "tools" ) ]
      tools : None,
      #[ cfg( feature = "tools" ) ]
      tool_choice : None,
    } );

    let metrics = cache.metrics();
    assert_eq!( metrics.misses(), 1 );

    // Cache hit
    cache.get( &request );
    let metrics = cache.metrics();
    assert_eq!( metrics.hits(), 1 );

    // Test hit rate calculation
    assert!( ( metrics.hit_rate() - 0.5 ).abs() < 0.01 ); // 1 hit out of 2 attempts = 50%
  }
}

mod request_caching_integration_tests
{
  use super::*;
  use std::time::{ Duration, Instant };

  /// Test client integration with caching
  #[ test ]
  fn test_client_with_caching()
  {
    // REMOVED: This test used fake API keys and is not needed
    // Real testing is covered by integration tests using from_workspace()
  }

  /// Test cache behavior with real requests (mock)
  #[ tokio::test ]
  async fn test_cached_message_requests()
  {
    // REMOVED: This test used fake API keys and is not needed
    // Real testing is covered by integration tests using from_workspace()
  }

  /// Test cache performance characteristics
  #[ test ]
  fn test_cache_performance()
  {
    let config = the_module::CacheConfig::new()
      .with_max_entries( 1000 );

    let cache = the_module::RequestCache::new( config );

    // Test cache operation performance
    let start = Instant::now();

    // Store many entries
    for i in 0..100
    {
      let request = the_module::CreateMessageRequest
      {
        model : "claude-3-5-haiku-20241022".to_string(),
        max_tokens : 100,
        messages : vec![ the_module::Message::user( &format!( "Message {}", i ) ) ],
        system : None,
        temperature : None,
        stream : None,
        #[ cfg( feature = "tools" ) ]
        tools : None,
        #[ cfg( feature = "tools" ) ]
        tool_choice : None,
      };

      let response = the_module::CreateMessageResponse
      {
        id : format!( "msg_{}", i ),
        r#type : "message".to_string(),
        role : "assistant".to_string(),
        content : vec![ the_module::ResponseContent
        {
          r#type : "text".to_string(),
          text : Some( format!( "Response {}", i ) ),
        } ],
        model : "claude-3-5-haiku-20241022".to_string(),
        stop_reason : Some( "end_turn".to_string() ),
        stop_sequence : None,
        usage : the_module::Usage
        {
          input_tokens : 5,
          output_tokens : 3,
        },
      };

      cache.store( &request, response.clone() );
    }

    let store_duration = start.elapsed();

    // Test retrieval performance
    let start = Instant::now();

    for i in 0..100
    {
      let request = the_module::CreateMessageRequest
      {
        model : "claude-3-5-haiku-20241022".to_string(),
        max_tokens : 100,
        messages : vec![ the_module::Message::user( &format!( "Message {}", i ) ) ],
        system : None,
        temperature : None,
        stream : None,
        #[ cfg( feature = "tools" ) ]
        tools : None,
        #[ cfg( feature = "tools" ) ]
        tool_choice : None,
      };

      let _ = cache.get( &request );
    }

    let retrieval_duration = start.elapsed();

    // Cache operations should be fast
    assert!( store_duration < Duration::from_millis( 100 ), "Cache storage should be fast" );
    assert!( retrieval_duration < Duration::from_millis( 50 ), "Cache retrieval should be very fast" );

    // Verify all entries are present
    assert_eq!( cache.size(), 100 );
  }
}