agentik-sdk 0.2.0

Comprehensive, type-safe Rust SDK for the Anthropic API with streaming, tools, vision, files, and batch processing support.
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
use serde::{Deserialize, Serialize};
use crate::types::shared::{RequestId, Usage};
use crate::files::{File, FileError};

/// A message from Claude
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Message {
    /// Unique object identifier
    pub id: String,
    
    /// Object type - always "message" for Messages
    #[serde(rename = "type")]
    pub type_: String,
    
    /// Conversational role - always "assistant" for responses
    pub role: Role,
    
    /// Content generated by the model
    #[serde(default)]
    pub content: Vec<ContentBlock>,
    
    /// The model that completed the prompt
    pub model: String,
    
    /// The reason that generation stopped
    pub stop_reason: Option<StopReason>,
    
    /// Which custom stop sequence was generated, if any
    pub stop_sequence: Option<String>,
    
    /// Billing and rate-limit usage
    pub usage: Usage,
    
    /// Request ID for tracking (extracted from headers)
    #[serde(skip)]
    pub request_id: Option<RequestId>,
}

/// Conversational role
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    User,
    Assistant,
}

/// Content blocks that can appear in messages
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum ContentBlock {
    #[serde(rename = "text")]
    Text { text: String },

    #[serde(rename = "thinking")]
    Thinking {
        thinking: String,
        signature: String,
    },

    #[serde(rename = "image")]
    Image { source: ImageSource },

    #[serde(rename = "tool_use")]
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
    },

    #[serde(rename = "tool_result")]
    ToolResult {
        tool_use_id: String,
        content: Option<String>,
        is_error: Option<bool>,
    },
}

/// Image source for image content blocks
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum ImageSource {
    #[serde(rename = "base64")]
    Base64 {
        media_type: String,
        data: String,
    },
    
    #[serde(rename = "url")]
    Url {
        url: String,
    },
}

/// Reasons why the model stopped generating
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    EndTurn,
    MaxTokens,
    StopSequence,
    ToolUse,
}

/// Parameters for creating a new message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageCreateParams {
    /// The model to use for completion
    pub model: String,
    
    /// Maximum number of tokens to generate
    pub max_tokens: u32,
    
    /// Input messages for the conversation
    pub messages: Vec<MessageParam>,
    
    /// System prompt (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
    
    /// Amount of randomness (0.0 to 1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    
    /// Use nucleus sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    
    /// Only sample from top K options
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<u32>,
    
    /// Custom stop sequences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
    
    /// Whether to stream the response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    
    /// Tools available for the model to use
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<crate::types::Tool>>,
    
    /// Tool choice strategy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<crate::types::ToolChoice>,
    
    /// Additional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<std::collections::HashMap<String, String>>,
}

/// A single message in the conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageParam {
    pub role: Role,
    pub content: MessageContent,
}

/// Content for a message parameter  
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContent {
    /// Simple text content
    Text(String),
    /// Array of content blocks (text, images, etc.)
    Blocks(Vec<ContentBlockParam>),
}

/// Content block parameters for input messages
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ContentBlockParam {
    #[serde(rename = "text")]
    Text { text: String },

    #[serde(rename = "thinking")]
    Thinking {
        thinking: String,
        signature: String,
    },

    #[serde(rename = "image")]
    Image { source: ImageSource },

    #[serde(rename = "tool_use")]
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
    },

    #[serde(rename = "tool_result")]
    ToolResult {
        tool_use_id: String,
        content: Option<String>,
        is_error: Option<bool>,
    },
}

/// Builder for creating message requests ergonomically
#[derive(Debug, Clone)]
pub struct MessageCreateBuilder {
    params: MessageCreateParams,
}

impl MessageCreateBuilder {
    /// Create a new message builder
    pub fn new(model: impl Into<String>, max_tokens: u32) -> Self {
        Self {
            params: MessageCreateParams {
                model: model.into(),
                max_tokens,
                messages: Vec::new(),
                system: None,
                temperature: None,
                top_p: None,
                top_k: None,
                stop_sequences: None,
                stream: None,
                tools: None,
                tool_choice: None,
                metadata: None,
            },
        }
    }
    
    /// Add a message to the conversation
    pub fn message(mut self, role: Role, content: impl Into<MessageContent>) -> Self {
        self.params.messages.push(MessageParam {
            role,
            content: content.into(),
        });
        self
    }
    
    /// Add a user message
    pub fn user(self, content: impl Into<MessageContent>) -> Self {
        self.message(Role::User, content)
    }
    
    /// Add an assistant message
    pub fn assistant(self, content: impl Into<MessageContent>) -> Self {
        self.message(Role::Assistant, content)
    }
    
    /// Set the system prompt
    pub fn system(mut self, system: impl Into<String>) -> Self {
        self.params.system = Some(system.into());
        self
    }
    
    /// Set the temperature
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.params.temperature = Some(temperature);
        self
    }
    
    /// Set top_p
    pub fn top_p(mut self, top_p: f32) -> Self {
        self.params.top_p = Some(top_p);
        self
    }
    
    /// Set top_k
    pub fn top_k(mut self, top_k: u32) -> Self {
        self.params.top_k = Some(top_k);
        self
    }
    
    /// Set custom stop sequences
    pub fn stop_sequences(mut self, stop_sequences: Vec<String>) -> Self {
        self.params.stop_sequences = Some(stop_sequences);
        self
    }
    
    /// Enable streaming
    pub fn stream(mut self, stream: bool) -> Self {
        self.params.stream = Some(stream);
        self
    }
    
    /// Set tools available for the model to use
    pub fn tools(mut self, tools: Vec<crate::types::Tool>) -> Self {
        self.params.tools = Some(tools);
        self
    }
    
    /// Set tool choice strategy
    pub fn tool_choice(mut self, tool_choice: crate::types::ToolChoice) -> Self {
        self.params.tool_choice = Some(tool_choice);
        self
    }
    
    /// Set metadata
    pub fn metadata(mut self, metadata: std::collections::HashMap<String, String>) -> Self {
        self.params.metadata = Some(metadata);
        self
    }
    
    /// Build the message creation parameters
    pub fn build(self) -> MessageCreateParams {
        self.params
    }
}

// Convenient conversions for MessageContent
impl From<String> for MessageContent {
    fn from(text: String) -> Self {
        Self::Text(text)
    }
}

impl From<&str> for MessageContent {
    fn from(text: &str) -> Self {
        Self::Text(text.to_string())
    }
}

impl From<Vec<ContentBlockParam>> for MessageContent {
    fn from(blocks: Vec<ContentBlockParam>) -> Self {
        Self::Blocks(blocks)
    }
}

// Helper constructors for ContentBlockParam
impl ContentBlockParam {
    /// Create a text content block
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }
    
    /// Create an image content block from base64 data
    pub fn image_base64(media_type: impl Into<String>, data: impl Into<String>) -> Self {
        Self::Image {
            source: ImageSource::Base64 {
                media_type: media_type.into(),
                data: data.into(),
            },
        }
    }
    
    /// Create an image content block from URL
    pub fn image_url(url: impl Into<String>) -> Self {
        Self::Image {
            source: ImageSource::Url {
                url: url.into(),
            },
        }
    }

    /// Create an image content block from a File
    pub async fn image_file(file: File) -> Result<Self, FileError> {
        if !file.is_image() {
            return Err(FileError::InvalidMimeType {
                mime_type: file.mime_type.to_string(),
                allowed: vec!["image/*".to_string()],
            });
        }

        let base64_data = file.to_base64().await?;
        Ok(Self::Image {
            source: ImageSource::Base64 {
                media_type: file.mime_type.to_string(),
                data: base64_data,
            },
        })
    }

    /// Create an image content block from a File (convenience method)
    pub async fn from_file(file: File) -> Result<Self, FileError> {
        Self::image_file(file).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_message_builder() {
        let params = MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user("Hello, Claude!")
            .system("You are a helpful assistant.")
            .temperature(0.7)
            .build();

        assert_eq!(params.model, "claude-3-5-sonnet-latest");
        assert_eq!(params.max_tokens, 1024);
        assert_eq!(params.messages.len(), 1);
        assert_eq!(params.messages[0].role, Role::User);
        assert_eq!(params.system, Some("You are a helpful assistant.".to_string()));
        assert_eq!(params.temperature, Some(0.7));
    }

    #[test]
    fn test_content_block_creation() {
        let text_block = ContentBlockParam::text("Hello world");
        match text_block {
            ContentBlockParam::Text { text } => assert_eq!(text, "Hello world"),
            _ => panic!("Expected text block"),
        }

        let image_block = ContentBlockParam::image_base64("image/jpeg", "base64data");
        match image_block {
            ContentBlockParam::Image { source } => match source {
                ImageSource::Base64 { media_type, data } => {
                    assert_eq!(media_type, "image/jpeg");
                    assert_eq!(data, "base64data");
                },
                _ => panic!("Expected base64 image source"),
            },
            _ => panic!("Expected image block"),
        }
    }

    #[test]
    fn test_message_content_from_string() {
        let content: MessageContent = "Hello".into();
        match content {
            MessageContent::Text(text) => assert_eq!(text, "Hello"),
            _ => panic!("Expected text content"),
        }
    }
}