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
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
//! Vision Support 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 vision,integration
//! Requires : Valid `ANTHROPIC_API_KEY` in environment or ../../secret/-secrets.sh

#[ allow( unused_imports ) ]
use super::*;

#[ tokio::test ]
async fn test_image_content_structure()
{
  // Test that ImageContent has correct structure according to Claude API
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==".to_string(),
    },
  };
  
  assert_eq!( image_content.r#type, "image" );
  assert_eq!( image_content.source.r#type, "base64" );
  assert_eq!( image_content.source.media_type, "image/jpeg" );
  assert!( !image_content.source.data.is_empty() );
}

#[ tokio::test ]
async fn test_image_source_types()
{
  // Test different image source types
  let base64_source = the_module::ImageSource
  {
    r#type : "base64".to_string(),
    media_type : "image/png".to_string(),
    data : "base64datahere".to_string(),
  };
  
  assert_eq!( base64_source.r#type, "base64" );
  assert_eq!( base64_source.media_type, "image/png" );
  
  // Test different media types
  let media_types = vec![ "image/jpeg", "image/png", "image/gif", "image/webp" ];
  
  for media_type in media_types
  {
    let source = the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : media_type.to_string(),
      data : "test_data".to_string(),
    };
    
    assert_eq!( source.media_type, media_type );
  }
}

#[ tokio::test ]
async fn test_mixed_content_message()
{
  // Test message with both text and image content
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : "base64imagedata".to_string(),
    },
  };
  
  let message = the_module::Message::user_with_image( 
    "What's in this picture?".to_string(), 
    image_content 
  );
  
  match message.role
  {
    the_module::Role::User => {},
    _ => panic!( "Expected User role" ),
  }
  
  assert_eq!( message.content.len(), 2 ); // Text + Image
}

#[ tokio::test ]
async fn test_image_only_message()
{
  // Test message with only image content
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/png".to_string(),
      data : "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==".to_string(),
    },
  };
  
  let message = the_module::Message::user_image( image_content.clone() );
  
  match message.role
  {
    the_module::Role::User => {},
    _ => panic!( "Expected User role" ),
  }
  
  assert_eq!( message.content.len(), 1 );
}

#[ tokio::test ]
async fn test_multiple_images_message()
{
  // Test message with multiple images
  let image1 = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : "first_image_data".to_string(),
    },
  };
  
  let image2 = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/png".to_string(),
      data : "second_image_data".to_string(),
    },
  };
  
  let message = the_module::Message::user_with_images(
    "Compare these two images".to_string(),
    vec![ image1, image2 ]
  );
  
  assert_eq!( message.content.len(), 3 ); // Text + 2 images
  
  // Verify content types
  assert_eq!( message.content[0].r#type(), "text" );
}

#[ tokio::test ]
async fn test_vision_api_request()
{
  // Test API request with vision content
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : "test_image_base64_data".to_string(),
    },
  };
  
  let message = the_module::Message::user_with_image(
    "Describe what you see in this image".to_string(),
    image_content
  );
  
  let request = the_module::CreateMessageRequest::builder()
    .model( "claude-sonnet-4-5-20250929" )
    .max_tokens( 500 )
    .message( message )
    .build();
  
  assert_eq!( request.model, "claude-sonnet-4-5-20250929" );
  assert_eq!( request.messages.len(), 1 );
  assert_eq!( request.messages[0].content.len(), 2 ); // Text + Image
}

#[ tokio::test ]
async fn test_vision_conversation_flow()
{
  // Test multi-turn conversation with vision
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/png".to_string(),
      data : "conversation_image_data".to_string(),
    },
  };
  
  let messages = vec![
    the_module::Message::user_with_image( 
      "What's in this image?".to_string(), 
      image_content 
    ),
    the_module::Message::assistant( 
      "I can see a beautiful landscape with mountains and trees.".to_string() 
    ),
    the_module::Message::user( 
      "What time of day do you think it is?".to_string() 
    ),
  ];
  
  let request = the_module::CreateMessageRequest::builder()
    .model( "claude-sonnet-4-5-20250929" )
    .max_tokens( 300 )
    .messages( messages.clone() )
    .build();
  
  assert_eq!( request.messages.len(), 3 );
  
  // Check first message has both text and image
  assert_eq!( request.messages[0].content.len(), 2 );
  
  // Check subsequent messages are text only
  assert_eq!( request.messages[1].content.len(), 1 );
  assert_eq!( request.messages[2].content.len(), 1 );
}

#[ tokio::test ]
async fn test_image_content_serialization()
{
  // Test that image content serializes correctly to JSON
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : "test123".to_string(),
    },
  };
  
  let json = serde_json::to_string( &image_content ).expect( "Should serialize successfully" );
  
  // Verify JSON structure matches expected format
  assert!( json.contains( "\"type\":\"image\"" ) );
  assert!( json.contains( "\"source\":" ) );
  assert!( json.contains( "\"type\":\"base64\"" ) );
  assert!( json.contains( "\"media_type\":\"image/jpeg\"" ) );
  assert!( json.contains( "\"data\":\"test123\"" ) );
}

#[ tokio::test ]
async fn test_image_content_deserialization()
{
  // Test that we can deserialize image content from JSON
  let json = r#"{
    "type": "image",
    "source": {
      "type": "base64",
      "media_type": "image/png",
      "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
    }
  }"#;
  
  let image_content : the_module::ImageContent = serde_json::from_str( json ).expect( "Should deserialize successfully" );
  
  assert_eq!( image_content.r#type, "image" );
  assert_eq!( image_content.source.r#type, "base64" );
  assert_eq!( image_content.source.media_type, "image/png" );
  assert!( !image_content.source.data.is_empty() );
}

#[ tokio::test ]
async fn test_vision_with_tools()
{
  // Test vision functionality combined with tool calling
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : "image_for_tool_analysis".to_string(),
    },
  };
  
  let tools = vec![
    the_module::ToolDefinition
    {
      name : "image_analyzer".to_string(),
      description : "Analyze image content and extract information".to_string(),
      input_schema : serde_json::json!(
      {
        "type": "object",
        "properties": {
          "analysis_type": {"type": "string", "enum": ["objects", "colors", "text", "emotions"]}
        },
        "required": ["analysis_type"]
      }),
    }
  ];
  
  let message = the_module::Message::user_with_image(
    "Analyze this image for objects".to_string(),
    image_content
  );
  
  let request = the_module::CreateMessageRequest::builder()
    .model( "claude-sonnet-4-5-20250929" )
    .max_tokens( 400 )
    .message( message )
    .tools( tools )
    .tool_choice( the_module::ToolChoice::Auto )
    .build();
  
  assert!( request.tools.is_some() );
  assert!( request.tool_choice.is_some() );
  assert_eq!( request.messages[0].content.len(), 2 ); // Text + Image
}

// Removed test_vision_api_call - used fake API keys

#[ tokio::test ]
async fn test_image_validation()
{
  // Test image content validation
  
  // Test empty image data
  let empty_image = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : String::new(), // Empty data
    },
  };
  
  assert!( empty_image.source.data.is_empty() );
  
  // Test invalid media type (should be handled gracefully)
  let invalid_media_type = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "invalid/type".to_string(),
      data : "test_data".to_string(),
    },
  };
  
  assert_eq!( invalid_media_type.source.media_type, "invalid/type" );
}

#[ tokio::test ]
async fn test_large_image_handling()
{
  // Test handling of larger image data
  let large_data = "a".repeat( 1000 ); // Simulate larger base64 data
  
  let large_image = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/jpeg".to_string(),
      data : large_data.clone(),
    },
  };
  
  assert_eq!( large_image.source.data.len(), 1000 );
  
  // Test serialization of large image
  let json = serde_json::to_string( &large_image ).expect( "Should handle large images" );
  assert!( json.len() > 1000 );
}

#[ tokio::test ]
async fn test_vision_with_streaming()
{
  // Test vision functionality combined with streaming
  let image_content = the_module::ImageContent
  {
    r#type : "image".to_string(),
    source : the_module::ImageSource
    {
      r#type : "base64".to_string(),
      media_type : "image/png".to_string(),
      data : "streaming_test_image".to_string(),
    },
  };
  
  let message = the_module::Message::user_with_image(
    "Describe this image in detail".to_string(),
    image_content
  );
  
  let request = the_module::CreateMessageRequest::builder()
    .model( "claude-sonnet-4-5-20250929" )
    .max_tokens( 600 )
    .message( message )
    .stream( true )
    .build();
  
  assert!( request.stream.unwrap() );
  assert_eq!( request.messages[0].content.len(), 2 );
}

#[ tokio::test ]
async fn test_mixed_content_serialization()
{
  // Test serialization of mixed content message
  let message = the_module::Message::user_with_image(
    "Analyze this".to_string(),
    the_module::ImageContent
    {
      r#type : "image".to_string(),
      source : the_module::ImageSource
      {
        r#type : "base64".to_string(),
        media_type : "image/jpeg".to_string(),
        data : "mixed_content_test".to_string(),
      },
    }
  );
  
  let json = serde_json::to_string( &message ).expect( "Should serialize mixed content" );
  
  // Should contain both text and image content
  assert!( json.contains( "\"role\":\"user\"" ) );
  assert!( json.contains( "\"content\":" ) );
  assert!( json.contains( "\"type\":\"text\"" ) );
  assert!( json.contains( "\"type\":\"image\"" ) );
  assert!( json.contains( "\"source\":" ) );
}

// ============================================================================
// INTEGRATION TESTS - REAL API VISION SUPPORT
// ============================================================================

#[ tokio::test ]
#[ cfg( all( feature = "integration", feature = "vision" ) ) ]
#[ ignore = "Requires workspace secrets file" ]
async fn integration_vision_real_image_processing()
{
  let client = the_module::Client::from_workspace()
    .expect( "INTEGRATION: Must have valid API key for vision testing" );

  // Create a simple base64 test image (1x1 red pixel PNG)
  let test_image_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
  
  let image_source = the_module::ImageSource::png( test_image_base64 );
  let image_content = the_module::ImageContent::new( image_source );

  let request = the_module::CreateMessageRequest
  {
    model : "claude-sonnet-4-5-20250929".to_string(), // Vision-capable model
    max_tokens : 50,
    messages : vec![ 
      the_module::Message::user_with_image(
        "What color is this image?".to_string(),
        image_content
      )
    ],
    system : None,
    temperature : None,
    stream : None,
    tools : None,
    tool_choice : None,
  };

  let response = match client.create_message( request ).await
  {
    Ok( response ) => response,
    Err( the_module::AnthropicError::Api( ref api_err ) ) if api_err.message.contains( "credit balance is too low" ) =>
    {
      println!( "INTEGRATION TEST SKIPPED: Credit balance exhausted - this confirms real API usage" );
      return;
    },
    Err( err ) => panic!( "INTEGRATION: Vision API call must work : {err}" ),
  };

  // Verify real API vision response
  assert!( !response.id.is_empty(), "Vision API must return message ID" );
  assert_eq!( response.r#type, "message" );
  assert_eq!( response.role, "assistant" );
  assert!( !response.content.is_empty(), "Vision API must return content" );
  assert!( response.usage.input_tokens > 0, "Vision API must track input tokens" );
  assert!( response.usage.output_tokens > 0, "Vision API must track output tokens" );
  
  let content_text = response.content[0].text.as_ref()
    .expect( "Vision response must have text content" );
  
  // Verify the API processed the image (should mention color/image analysis)
  let response_lower = content_text.to_lowercase();
  assert!( 
    response_lower.contains( "red" ) || 
    response_lower.contains( "color" ) || 
    response_lower.contains( "image" ) ||
    response_lower.contains( "pixel" ),
    "Vision API should analyze image content, got : {content_text}"
  );
  
  println!( "✅ Vision integration test passed!" );
  println!( "   Vision response : {content_text}" );
  println!( "   Input tokens : {}", response.usage.input_tokens );
  println!( "   Output tokens : {}", response.usage.output_tokens );
}

#[ tokio::test ]
#[ cfg( all( feature = "integration", feature = "vision" ) ) ]
#[ ignore = "Requires workspace secrets file" ]
async fn integration_vision_mixed_content_real_api()
{
  let client = the_module::Client::from_workspace()
    .expect( "INTEGRATION: Must have valid API key for mixed content testing" );

  // Create test image (simple 1x1 red pixel - using known working base64)
  let test_image_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
  
  let image_content = the_module::ImageContent::png( test_image_base64 );

  // Test mixed text + image content
  let message = the_module::Message::user_with_image(
    "I'm sending you an image and asking : What do you see in this small image? Please be specific about any colors or patterns.".to_string(),
    image_content
  );

  let request = the_module::CreateMessageRequest
  {
    model : "claude-sonnet-4-5-20250929".to_string(),
    max_tokens : 100,
    messages : vec![ message ],
    system : Some( vec![ the_module::SystemContent::text( "You are a helpful vision assistant. Describe images accurately." ) ] ),
    temperature : Some( 0.1 ),
    stream : None,
    tools : None,
    tool_choice : None,
  };

  let response = match client.create_message( request ).await
  {
    Ok( response ) => response,
    Err( the_module::AnthropicError::Api( ref api_err ) ) if api_err.message.contains( "credit balance is too low" ) =>
    {
      println!( "INTEGRATION TEST SKIPPED: Credit balance exhausted - this confirms real API usage" );
      return;
    },
    Err( err ) => panic!( "INTEGRATION: Mixed content vision API call must work : {err}" ),
  };

  // Verify mixed content response
  assert!( !response.id.is_empty() );
  assert!( response.usage.input_tokens > 0 );
  assert!( response.usage.output_tokens > 0 );
  
  let content_text = response.content[0].text.as_ref()
    .expect( "Mixed content response must have text" );
    
  // Should acknowledge both the text instruction and image analysis
  let response_lower = content_text.to_lowercase();
  assert!(
    response_lower.contains( "image" ) || response_lower.contains( "see" ) ||
    response_lower.contains( "blank" ) || response_lower.contains( "tint" ) ||
    response_lower.contains( "color" ) || response_lower.contains( "pixel" ),
    "Mixed content should show vision processing, got : {content_text}"
  );
  
  println!( "✅ Vision mixed content integration test passed!" );
  println!( "   Mixed content response : {content_text}" );
}