anthropic-sdk-rust 0.1.1

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
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
use anthropic_sdk::{
    Anthropic,
    FileUploadParams, FileListParams, FilePurpose, FileOrder, FileStatus,
    UploadProgress, StorageInfo, FileDownload,
};
use std::{collections::HashMap, time::Duration};
use tokio::time::sleep;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿš€ Phase 5.2: Files API Enhancement Demo");
    println!("========================================");

    // Initialize client (would normally use real API key)
    let client = match Anthropic::from_env() {
        Ok(client) => client,
        Err(_) => {
            println!("โš ๏ธ  ANTHROPIC_API_KEY not set. This is a demo of the Files API structure.");
            simulate_files_api_operations().await?;
            return Ok(());
        }
    };

    // Demo 1: File Upload with Different Purposes
    println!("\n๐Ÿ“ค Demo 1: File Upload with Different Purposes");
    println!("----------------------------------------------");
    
    // Create sample files for different purposes
    demonstrate_file_uploads().await?;
    
    // Demo 2: Upload Progress Tracking
    println!("\n๐Ÿ“ˆ Demo 2: Upload Progress Tracking");
    println!("-----------------------------------");
    
    simulate_upload_progress().await?;
    
    // Demo 3: File Listing and Management
    println!("\n๐Ÿ“‹ Demo 3: File Listing and Management");
    println!("--------------------------------------");
    
    demonstrate_file_listing().await?;
    
    // Demo 4: Storage Management
    println!("\n๐Ÿ’พ Demo 4: Storage Management");
    println!("-----------------------------");
    
    demonstrate_storage_management().await?;
    
    // Demo 5: File Processing and Status Monitoring
    println!("\nโณ Demo 5: File Processing and Status Monitoring");
    println!("------------------------------------------------");
    
    simulate_file_processing().await?;
    
    // Demo 6: Advanced File Operations
    println!("\n๐Ÿ”ง Demo 6: Advanced File Operations");
    println!("-----------------------------------");
    
    demonstrate_advanced_operations().await?;
    
    println!("\n๐ŸŽ‰ Phase 5.2 Files API Enhancement Demo Complete!");
    println!("==================================================");
    println!("โœ… File Upload: Multi-format support with progress tracking");
    println!("โœ… File Management: List, filter, sort, and organize files");
    println!("โœ… Storage Monitoring: Quota tracking and usage analytics");
    println!("โœ… Status Tracking: Real-time processing status monitoring");
    println!("โœ… Batch Operations: Concurrent uploads and cleanup utilities");
    println!("โœ… Download & Processing: Content retrieval and format conversion");

    Ok(())
}

async fn simulate_files_api_operations() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ”„ Simulating Files API operations...");
    
    // Simulate the full workflow without actual API calls
    demonstrate_file_uploads().await?;
    simulate_upload_progress().await?;
    demonstrate_file_listing().await?;
    demonstrate_storage_management().await?;
    simulate_file_processing().await?;
    demonstrate_advanced_operations().await?;
    
    println!("โœ… Files API simulation complete!");
    Ok(())
}

async fn demonstrate_file_uploads() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ“‚ Creating upload parameters for different file types...");
    
    // Vision file upload
    let vision_upload = create_sample_upload(
        "sample_image.jpg",
        "image/jpeg", 
        FilePurpose::Vision,
        b"fake_jpeg_data"
    ).with_meta("description", "Sample image for vision analysis");
    
    println!("   โœ… Vision upload: {} ({}) - {}", 
        vision_upload.filename, 
        vision_upload.content_type,
        format_bytes(vision_upload.content.len() as u64)
    );
    
    // Document upload
    let document_upload = create_sample_upload(
        "research_paper.pdf",
        "application/pdf",
        FilePurpose::Document,
        &create_fake_pdf_content()
    ).with_meta("category", "research")
     .with_meta("author", "AI Research Team");
    
    println!("   โœ… Document upload: {} ({}) - {}",
        document_upload.filename,
        document_upload.content_type, 
        format_bytes(document_upload.content.len() as u64)
    );
    
    // Batch input file
    let batch_upload = create_sample_upload(
        "batch_requests.jsonl",
        "application/json",
        FilePurpose::BatchInput,
        &create_sample_jsonl()
    );
    
    println!("   โœ… Batch input upload: {} ({}) - {}",
        batch_upload.filename,
        batch_upload.content_type,
        format_bytes(batch_upload.content.len() as u64)
    );
    
    // Validate uploads
    println!("\n๐Ÿ” Validating upload parameters...");
    if let Err(e) = vision_upload.validate() {
        println!("   โŒ Vision upload validation failed: {}", e);
    } else {
        println!("   โœ… Vision upload parameters valid");
    }
    
    if let Err(e) = document_upload.validate() {
        println!("   โŒ Document upload validation failed: {}", e);
    } else {
        println!("   โœ… Document upload parameters valid");
    }
    
    if let Err(e) = batch_upload.validate() {
        println!("   โŒ Batch upload validation failed: {}", e);
    } else {
        println!("   โœ… Batch upload parameters valid");
    }
    
    Ok(())
}

async fn simulate_upload_progress() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ“Š Simulating file upload with progress tracking...");
    
    let file_size = 5 * 1024 * 1024; // 5MB file
    let mut uploaded = 0u64;
    let chunk_size = 256 * 1024; // 256KB chunks
    
    let start_time = std::time::Instant::now();
    
    while uploaded < file_size {
        let chunk = chunk_size.min(file_size - uploaded);
        uploaded += chunk;
        
        let elapsed = start_time.elapsed().as_secs_f64();
        let speed = if elapsed > 0.0 { uploaded as f64 / elapsed } else { 0.0 };
        
        let progress = UploadProgress::new(uploaded, file_size).with_speed(speed);
        
        println!("   ๐Ÿ“ˆ Upload Progress: {} | {} | Speed: {} | ETA: {}",
            progress.percentage_string(),
            progress.size_string(),
            progress.speed_string().unwrap_or("N/A".to_string()),
            progress.eta_string().unwrap_or("N/A".to_string())
        );
        
        // Simulate upload time
        sleep(Duration::from_millis(100)).await;
    }
    
    println!("   โœ… Upload completed successfully!");
    Ok(())
}

async fn demonstrate_file_listing() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ“„ Creating file listing parameters...");
    
    // List all files
    let all_files_params = FileListParams::new()
        .limit(50)
        .order(FileOrder::NewestFirst);
    
    println!("   ๐Ÿ“‹ All files query: limit={:?}, order={:?}",
        all_files_params.limit,
        all_files_params.order
    );
    
    // List vision files only
    let vision_files_params = FileListParams::new()
        .purpose(FilePurpose::Vision)
        .limit(20)
        .order(FileOrder::NewestFirst);
    
    println!("   ๐Ÿ–ผ๏ธ  Vision files query: purpose={:?}, limit={:?}",
        vision_files_params.purpose,
        vision_files_params.limit
    );
    
    // List with pagination
    let paginated_params = FileListParams::new()
        .after("file_abc123")
        .limit(10);
    
    println!("   ๐Ÿ“„ Paginated query: after={:?}, limit={:?}",
        paginated_params.after,
        paginated_params.limit
    );
    
    // Simulate file listing results
    simulate_file_list_results().await;
    
    Ok(())
}

async fn simulate_file_list_results() {
    println!("\n๐Ÿ“Š Simulated file listing results:");
    
    let mock_files = vec![
        ("file_001", "image.jpg", "image/jpeg", FilePurpose::Vision, FileStatus::Processed, 2048576),
        ("file_002", "document.pdf", "application/pdf", FilePurpose::Document, FileStatus::Processed, 5242880),
        ("file_003", "batch.jsonl", "application/json", FilePurpose::BatchInput, FileStatus::Processing, 1024),
        ("file_004", "photo.png", "image/png", FilePurpose::Vision, FileStatus::Error, 3145728),
        ("file_005", "data.txt", "text/plain", FilePurpose::Upload, FileStatus::Processed, 512),
    ];
    
    for (id, name, content_type, purpose, status, size) in mock_files {
        let status_icon = match status {
            FileStatus::Processed => "โœ…",
            FileStatus::Processing => "โณ",
            FileStatus::Error => "โŒ",
            FileStatus::Deleted => "๐Ÿ—‘๏ธ",
        };
        
        let purpose_icon = match purpose {
            FilePurpose::Vision => "๐Ÿ–ผ๏ธ",
            FilePurpose::Document => "๐Ÿ“„",
            FilePurpose::BatchInput => "๐Ÿ“ฆ",
            FilePurpose::BatchOutput => "๐Ÿ“ค",
            FilePurpose::Upload => "๐Ÿ“",
        };
        
        println!("   {} {} {} | {} | {} | {}",
            status_icon,
            purpose_icon,
            id,
            name,
            content_type,
            format_bytes(size)
        );
    }
}

async fn demonstrate_storage_management() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ’พ Simulating storage information...");
    
    let storage = create_mock_storage_info();
    
    println!("   ๐Ÿ“Š Storage Usage: {}", storage.usage_string());
    println!("   ๐Ÿ“ˆ Usage Percentage: {:.1}%", storage.usage_percentage());
    println!("   ๐Ÿ“ File Count: {}", storage.file_count);
    println!("   ๐Ÿ’ฝ Total Quota: {}", storage.quota_string());
    
    if storage.is_nearly_full() {
        println!("   โš ๏ธ  Storage is nearly full (>90%)");
    } else if storage.is_full() {
        println!("   ๐Ÿšจ Storage is full!");
    } else {
        println!("   โœ… Storage has sufficient space");
    }
    
    // Show usage by purpose
    println!("\n   ๐Ÿ“‚ Usage by Purpose:");
    for (purpose, bytes) in &storage.usage_by_purpose {
        let percentage = if storage.used_bytes > 0 {
            (*bytes as f64 / storage.used_bytes as f64) * 100.0
        } else {
            0.0
        };
        
        println!("      {} {} ({:.1}%)",
            purpose,
            format_bytes(*bytes),
            percentage
        );
    }
    
    Ok(())
}

async fn simulate_file_processing() -> Result<(), Box<dyn std::error::Error>> {
    println!("โš™๏ธ Simulating file processing status monitoring...");
    
    let file_id = "file_processing_demo";
    let statuses = [
        (FileStatus::Processing, "File is being validated and processed"),
        (FileStatus::Processing, "Extracting content and metadata"),
        (FileStatus::Processing, "Running content analysis"),
        (FileStatus::Processed, "File processing completed successfully"),
    ];
    
    for (status, description) in statuses {
        let status_icon = match status {
            FileStatus::Processing => "โณ",
            FileStatus::Processed => "โœ…",
            FileStatus::Error => "โŒ",
            FileStatus::Deleted => "๐Ÿ—‘๏ธ",
        };
        
        println!("   {} {}: {}", status_icon, file_id, description);
        
        if status.is_ready() {
            println!("   ๐ŸŽ‰ File is ready for use!");
            break;
        }
        
        // Simulate processing time
        sleep(Duration::from_millis(800)).await;
    }
    
    Ok(())
}

async fn demonstrate_advanced_operations() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿ”ง Demonstrating advanced file operations...");
    
    // Batch upload simulation
    println!("\n   ๐Ÿ“ฆ Batch Upload (3 files concurrently):");
    let uploads = vec![
        ("file1.txt", "text/plain", 1024),
        ("file2.jpg", "image/jpeg", 2048576),
        ("file3.pdf", "application/pdf", 5242880),
    ];
    
    for (name, content_type, size) in uploads {
        println!("      โฌ†๏ธ  {} ({}) - {}", name, content_type, format_bytes(size));
        sleep(Duration::from_millis(200)).await;
    }
    println!("      โœ… All files uploaded successfully!");
    
    // File cleanup simulation
    println!("\n   ๐Ÿงน Cleanup Old Files (>30 days):");
    let old_files = ["old_file1.txt", "deprecated_image.jpg", "archived_doc.pdf"];
    for file in old_files {
        println!("      ๐Ÿ—‘๏ธ  Deleting: {}", file);
        sleep(Duration::from_millis(100)).await;
    }
    println!("      โœ… Cleaned up {} old files", old_files.len());
    
    // Download and processing simulation
    println!("\n   ๐Ÿ“ฅ File Download and Processing:");
    let download = create_mock_download();
    println!("      ๐Ÿ“„ Downloaded: {} ({}) - {}",
        download.filename,
        download.content_type,
        format_bytes(download.size)
    );
    
    // Show different content processing options
    if download.content_type.starts_with("text/") {
        println!("      ๐Ÿ“ Text content preview: \"{}...\"", 
            String::from_utf8_lossy(&download.content[..50.min(download.content.len())])
        );
    } else if download.content_type == "application/json" {
        println!("      ๐Ÿ” JSON structure detected - ready for parsing");
    } else {
        println!("      ๐Ÿ“ฆ Binary content - {} bytes available", download.content.len());
    }
    
    Ok(())
}

// Helper functions

fn create_sample_upload(filename: &str, content_type: &str, purpose: FilePurpose, content: &[u8]) -> FileUploadParams {
    FileUploadParams::new(
        content.to_vec(),
        filename,
        content_type,
        purpose,
    )
}

fn create_fake_pdf_content() -> Vec<u8> {
    // Simplified PDF header + content
    let mut content = b"%PDF-1.4\n".to_vec();
    content.extend_from_slice(b"Fake PDF content for demonstration purposes. ");
    content.extend_from_slice(b"This would be actual PDF binary data in a real scenario. ");
    content.extend_from_slice(&vec![0u8; 1024]); // Pad to make it look like a real file
    content
}

fn create_sample_jsonl() -> Vec<u8> {
    let jsonl_content = r#"{"custom_id": "req1", "method": "POST", "url": "/v1/messages", "body": {"model": "claude-3-5-sonnet-latest", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}]}}
{"custom_id": "req2", "method": "POST", "url": "/v1/messages", "body": {"model": "claude-3-5-sonnet-latest", "max_tokens": 1024, "messages": [{"role": "user", "content": "World"}]}}
"#;
    jsonl_content.as_bytes().to_vec()
}

fn create_mock_storage_info() -> StorageInfo {
    let mut usage_by_purpose = HashMap::new();
    usage_by_purpose.insert("vision".to_string(), 50 * 1024 * 1024);       // 50MB
    usage_by_purpose.insert("document".to_string(), 100 * 1024 * 1024);    // 100MB
    usage_by_purpose.insert("batch_input".to_string(), 10 * 1024 * 1024);  // 10MB
    usage_by_purpose.insert("upload".to_string(), 25 * 1024 * 1024);       // 25MB
    
    StorageInfo {
        quota_bytes: 1024 * 1024 * 1024,        // 1GB
        used_bytes: 185 * 1024 * 1024,          // 185MB
        available_bytes: 839 * 1024 * 1024,     // 839MB
        file_count: 42,
        usage_by_purpose,
    }
}

fn create_mock_download() -> FileDownload {
    let content = b"Sample file content for demonstration.\nThis could be text, JSON, or binary data.".to_vec();
    
    FileDownload {
        content: content.clone(),
        content_type: "text/plain".to_string(),
        filename: "sample_download.txt".to_string(),
        size: content.len() as u64,
    }
}

fn format_bytes(bytes: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    
    if bytes == 0 {
        return "0 B".to_string();
    }
    
    let mut size = bytes as f64;
    let mut unit_index = 0;
    
    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }
    
    if unit_index == 0 {
        format!("{} {}", size as u64, UNITS[unit_index])
    } else {
        format!("{:.1} {}", size, UNITS[unit_index])
    }
}