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
//! Message content types
//!
//! `Role`, `Content` variants, `ImageContent`, and `ImageSource`.

mod private
{
  use serde::{ Serialize, Deserialize };

  use serde_json::Value;

  /// Message role in conversation
  ///
  /// # Examples
  ///
  /// ```
  /// use api_claude::Role;
  ///
  /// // Create different message roles
  /// let user_role = Role::User;
  /// let assistant_role = Role::Assistant;
  /// let system_role = Role::System;
  ///
  /// // Roles can be compared
  /// assert_eq!( user_role, Role::User );
  /// assert_ne!( user_role, Role::Assistant );
  /// ```
  #[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
  pub enum Role
  {
    /// User message
    #[ serde( rename = "user" ) ]
    User,
    /// Assistant message
    #[ serde( rename = "assistant" ) ]
    Assistant,
    /// System message
    #[ serde( rename = "system" ) ]
    System,
  }

  /// Content block in a message
  ///
  /// # Examples
  ///
  /// ```
  /// use api_claude::Content;
  ///
  /// // Create text content
  /// let text_content = Content::Text {
  ///   r#type : "text".to_string(),
  ///   text : "Hello, Claude!".to_string(),
  /// };
  ///
  /// // Content can be serialized/deserialized
  /// let json = serde_json::to_string( &text_content ).unwrap();
  /// assert!( json.contains( "Hello, Claude!" ) );
  /// ```
  #[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
  #[ serde( untagged ) ]
  pub enum Content
  {
    /// Text content
    Text
    {
      /// Type - always "text"
      r#type : String,
      /// Text content
      text : String,
    },
    /// Image content (vision feature)
    #[ cfg( feature = "vision" ) ]
    Image
    {
      /// Type - always "image"
      r#type : String,
      /// Image source information
      source : ImageSource,
    },
    /// Tool use content
    #[ cfg( feature = "tools" ) ]
    ToolUse
    {
      /// Type - always "`tool_use`"
      r#type : String,
      /// Unique ID for this tool use
      id : String,
      /// Name of the tool being used
      name : String,
      /// Input parameters for the tool
      input : Value,
    },
    /// Tool result content
    #[ cfg( feature = "tools" ) ]
    ToolResult
    {
      /// Type - always "`tool_result`"
      r#type : String,
      /// ID of the tool use this result corresponds to
      tool_use_id : String,
      /// Result content from the tool
      content : String,
      /// Whether this result represents an error
      #[ serde( skip_serializing_if = "Option::is_none" ) ]
      is_error : Option< bool >,
    },
  }

  impl Content
  {
    /// Create new text content
    #[ inline ]
    #[ must_use ]
    pub fn new_text< S : Into< String > >( text : S ) -> Self
    {
      Self::Text
      {
        r#type : "text".to_string(),
        text : text.into(),
      }
    }

    /// Create new image content (requires vision feature)
    #[ cfg( feature = "vision" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn image( source : ImageSource ) -> Self
    {
      Self::Image
      {
        r#type : "image".to_string(),
        source,
      }
    }

    /// Create new tool use content
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn tool_use< S1 : Into< String >, S2 : Into< String > >( id : S1, name : S2, input : Value ) -> Self
    {
      Self::ToolUse
      {
        r#type : "tool_use".to_string(),
        id : id.into(),
        name : name.into(),
        input,
      }
    }

    /// Create new tool result content
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn tool_result< S1 : Into< String >, S2 : Into< String > >( tool_use_id : S1, content : S2 ) -> Self
    {
      Self::ToolResult
      {
        r#type : "tool_result".to_string(),
        tool_use_id : tool_use_id.into(),
        content : content.into(),
        is_error : None,
      }
    }

    /// Create new tool result content with error flag
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn tool_result_error< S1 : Into< String >, S2 : Into< String > >( tool_use_id : S1, content : S2, is_error : bool ) -> Self
    {
      Self::ToolResult
      {
        r#type : "tool_result".to_string(),
        tool_use_id : tool_use_id.into(),
        content : content.into(),
        is_error : Some( is_error ),
      }
    }

    /// Get the content type
    #[ inline ]
    #[ must_use ]
    #[ allow( clippy::match_same_arms ) ] // Different enum variants with conditional compilation
    pub fn r#type( &self ) -> &str
    {
      match self
      {
        Content::Text { r#type, .. } => r#type,
        #[ cfg( feature = "vision" ) ]
        Content::Image { r#type, .. } => r#type,
        #[ cfg( feature = "tools" ) ]
        Content::ToolUse { r#type, .. } => r#type,
        #[ cfg( feature = "tools" ) ]
        Content::ToolResult { r#type, .. } => r#type,
      }
    }

    /// Get text content if this is a text content type
    #[ inline ]
    #[ must_use ]
    pub fn text( &self ) -> Option< &str >
    {
      match self
      {
        Content::Text { text, .. } => Some( text ),
        _ => None,
      }
    }

    /// Check if this content is text type
    #[ inline ]
    #[ must_use ]
    pub fn is_text( &self ) -> bool
    {
      matches!( self, Content::Text { .. } )
    }

    /// Check if this content is image type (requires vision feature)
    #[ cfg( feature = "vision" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn is_image( &self ) -> bool
    {
      matches!( self, Content::Image { .. } )
    }

    /// Check if this content is tool use type
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn is_tool_use( &self ) -> bool
    {
      matches!( self, Content::ToolUse { .. } )
    }

    /// Check if this content is tool result type
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn is_tool_result( &self ) -> bool
    {
      matches!( self, Content::ToolResult { .. } )
    }

    /// Get tool use ID if this is a tool use content
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn tool_use_id( &self ) -> Option< &str >
    {
      match self
      {
        Content::ToolUse { id, .. } => Some( id ),
        _ => None,
      }
    }

    /// Get tool use name if this is a tool use content
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn tool_name( &self ) -> Option< &str >
    {
      match self
      {
        Content::ToolUse { name, .. } => Some( name ),
        _ => None,
      }
    }

    /// Get tool use input if this is a tool use content
    #[ cfg( feature = "tools" ) ]
    #[ inline ]
    #[ must_use ]
    pub fn tool_input( &self ) -> Option< &Value >
    {
      match self
      {
        Content::ToolUse { input, .. } => Some( input ),
        _ => None,
      }
    }
  }

  /// Image content for vision support (requires vision feature)
  #[ cfg( feature = "vision" ) ]
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ImageContent
  {
    /// Type - always "`image`"
    pub r#type : String,
    /// Image source information
    pub source : ImageSource,
  }

  #[ cfg( feature = "vision" ) ]
  impl ImageContent
  {
    /// Create a new image content with the given source
    #[ inline ]
    #[ must_use ]
    pub fn new( source : ImageSource ) -> Self
    {
      Self
      {
        r#type : "image".to_string(),
        source,
      }
    }

    /// Create image content from JPEG base64 data
    #[ inline ]
    #[ must_use ]
    pub fn jpeg< S : Into< String > >( data : S ) -> Self
    {
      Self::new( ImageSource::jpeg( data ) )
    }

    /// Create image content from PNG base64 data
    #[ inline ]
    #[ must_use ]
    pub fn png< S : Into< String > >( data : S ) -> Self
    {
      Self::new( ImageSource::png( data ) )
    }

    /// Create image content from GIF base64 data
    #[ inline ]
    #[ must_use ]
    pub fn gif< S : Into< String > >( data : S ) -> Self
    {
      Self::new( ImageSource::gif( data ) )
    }

    /// Create image content from WebP base64 data
    #[ inline ]
    #[ must_use ]
    pub fn webp< S : Into< String > >( data : S ) -> Self
    {
      Self::new( ImageSource::webp( data ) )
    }

    /// Validate image content
    ///
    /// # Errors
    ///
    /// Returns an error if the image content type is invalid or image source validation fails
    #[ inline ]
    pub fn validate( &self ) -> Result< (), crate::error_tools::Error >
    {
      if self.r#type != "image"
      {
        return Err( crate::error_tools::Error::msg( format!( "Invalid image content type : '{}'. Expected 'image'.", self.r#type ) ) );
      }

      self.source.validate()
    }

    /// Check if the image content is valid
    #[ inline ]
    #[ must_use ]
    pub fn is_valid( &self ) -> bool
    {
      self.r#type == "image" && self.source.is_valid_base64()
    }

    /// Get the media type of the image
    #[ inline ]
    #[ must_use ]
    pub fn media_type( &self ) -> &str
    {
      &self.source.media_type
    }

    /// Get estimated size in bytes
    #[ inline ]
    #[ must_use ]
    pub fn estimated_size_bytes( &self ) -> usize
    {
      self.source.estimated_size_bytes()
    }
  }

  /// Image source specification (requires vision feature)
  #[ cfg( feature = "vision" ) ]
  #[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ]
  pub struct ImageSource
  {
    /// Type of image source - currently only "`base64`" 
    pub r#type : String,
    /// MIME type of the image (e.g., "image/jpeg", "image/png", "image/gif", "image/webp")
    pub media_type : String,
    /// Base64-encoded image data
    pub data : String,
  }

  #[ cfg( feature = "vision" ) ]
  impl ImageSource
  {
    /// Create a new base64 image source
    #[ inline ]
    #[ must_use ]
    pub fn base64< S1 : Into< String >, S2 : Into< String > >( media_type : S1, data : S2 ) -> Self
    {
      Self
      {
        r#type : "base64".to_string(),
        media_type : media_type.into(),
        data : data.into(),
      }
    }

    /// Create a JPEG image source from base64 data
    #[ inline ]
    #[ must_use ]
    pub fn jpeg< S : Into< String > >( data : S ) -> Self
    {
      Self::base64( "image/jpeg", data )
    }

    /// Create a PNG image source from base64 data
    #[ inline ]
    #[ must_use ]
    pub fn png< S : Into< String > >( data : S ) -> Self
    {
      Self::base64( "image/png", data )
    }

    /// Create a GIF image source from base64 data
    #[ inline ]
    #[ must_use ]
    pub fn gif< S : Into< String > >( data : S ) -> Self
    {
      Self::base64( "image/gif", data )
    }

    /// Create a WebP image source from base64 data
    #[ inline ]
    #[ must_use ]
    pub fn webp< S : Into< String > >( data : S ) -> Self
    {
      Self::base64( "image/webp", data )
    }

    /// Validate image source format and content
    ///
    /// # Errors
    ///
    /// Returns an error if the source type, media type, or data format is invalid
    #[ inline ]
    pub fn validate( &self ) -> Result< (), crate::error_tools::Error >
    {
      // Validate source type
      if self.r#type != "base64"
      {
        return Err( crate::error_tools::Error::msg( format!( "Invalid image source type : '{}'. Only 'base64' is supported.", self.r#type ) ) );
      }

      // Validate media type
      const VALID_MEDIA_TYPES : &[ &str ] = &[ "image/jpeg", "image/png", "image/gif", "image/webp" ];
      if !VALID_MEDIA_TYPES.contains( &self.media_type.as_str() )
      {
        return Err( crate::error_tools::Error::msg( format!( "Invalid image media type : '{}'. Supported types : {:?}", self.media_type, VALID_MEDIA_TYPES ) ) );
      }

      // Validate data is not empty
      if self.data.is_empty()
      {
        return Err( crate::error_tools::Error::msg( "Image data cannot be empty" ) );
      }

      // Validate base64 format (basic check)
      if !self.data.chars().all( | c | c.is_alphanumeric() || c == '+' || c == '/' || c == '=' )
      {
        return Err( crate::error_tools::Error::msg( "Invalid base64 image data format" ) );
      }

      Ok( () )
    }

    /// Check if image data appears to be valid base64
    #[ inline ]
    #[ must_use ]
    pub fn is_valid_base64( &self ) -> bool
    {
      !self.data.is_empty() && self.data.chars().all( | c | c.is_alphanumeric() || c == '+' || c == '/' || c == '=' )
    }

    /// Get estimated size in bytes (rough approximation from base64 length)
    #[ inline ]
    #[ must_use ]
    pub fn estimated_size_bytes( &self ) -> usize
    {
      // Base64 encoding increases size by ~33%, so reverse estimate
      ( self.data.len() * 3 ) / 4
    }
  }
}

crate::mod_interface!
{
  exposed use Role;
  exposed use Content;

  #[ cfg( feature = "vision" ) ]
  exposed use ImageContent;
  #[ cfg( feature = "vision" ) ]
  exposed use ImageSource;
}