anthropic-sdk-rust 0.1.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
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
# Anthropic Rust SDK

[![Crates.io](https://img.shields.io/crates/v/anthropic-sdk-rust.svg)](https://crates.io/crates/anthropic-sdk-rust)
[![Documentation](https://docs.rs/anthropic-sdk-rust/badge.svg)](https://docs.rs/anthropic-sdk-rust)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

An unofficial, comprehensive, type-safe Rust SDK for the Anthropic API with full feature parity to the TypeScript SDK. Built with modern async/await patterns, extensive error handling, and ergonomic builder APIs.

## โœจ Features

- **๐Ÿš€ Full API Coverage**: Messages, Streaming, Tools, Vision, Files, Batches, and Models APIs
- **๐Ÿ›ก๏ธ Type Safety**: Comprehensive type system with serde integration
- **๐Ÿ”„ Async/Await**: Built on tokio with efficient async operations
- **๐Ÿ”ง Builder Patterns**: Ergonomic fluent APIs for easy usage
- **๐Ÿ“ก Streaming Support**: Real-time streaming responses with proper backpressure
- **๐Ÿ› ๏ธ Tool Integration**: Complete tool use system with custom tool support
- **๐Ÿ‘๏ธ Vision Support**: Image analysis with base64 and URL inputs
- **๐Ÿ“ File Management**: Upload, manage, and process files
- **๐Ÿ“Š Batch Processing**: Efficient batch operations for large workloads
- **๐Ÿค– Model Intelligence**: Smart model selection and comparison utilities
- **โšก Production Ready**: Comprehensive error handling, retries, and logging

## ๐Ÿ“ฆ Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
anthropic-sdk-rust = "0.1.0"
tokio = { version = "1.0", features = ["rt-multi-thread", "macros"] }
```

## ๐Ÿš€ Quick Start

### Basic Setup

```rust
use anthropic_sdk::{Anthropic, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Create client with API key from environment or directly
    let client = Anthropic::new("your-api-key")?;
    
    // Or use environment variable ANTHROPIC_API_KEY
    let client = Anthropic::from_env()?;
    
    Ok(())
}
```

### Simple Message

```rust
use anthropic_sdk::{Anthropic, MessageCreateBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let client = Anthropic::from_env()?;
    
    let response = client.messages()
        .create(
            MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
                .user("Hello, Claude! How are you today?")
                .build()
        )
        .await?;
    
    println!("Claude: {}", response.content.get_text());
    Ok(())
}
```

## ๐Ÿ“– Comprehensive Usage Guide

### ๐Ÿ”ง Client Configuration

```rust
use anthropic_sdk::{Anthropic, ClientConfig, LogLevel};
use std::time::Duration;

let config = ClientConfig::new("your-api-key")
    .with_timeout(Duration::from_secs(30))
    .with_max_retries(3)
    .with_log_level(LogLevel::Info)
    .with_base_url("https://api.anthropic.com");

let client = Anthropic::with_config(config)?;
```

### ๐Ÿ’ฌ Messages API

#### Basic Conversation
```rust
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user("What's the capital of France?")
            .system("You are a helpful geography assistant.")
            .build()
    )
    .await?;
```

#### Multi-turn Conversation
```rust
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user("Hi! What's your name?")
            .assistant("Hello! I'm Claude, an AI assistant.")
            .user("Nice to meet you! Can you help me with math?")
            .system("You are a helpful math tutor.")
            .temperature(0.3)
            .build()
    )
    .await?;
```

#### Advanced Parameters
```rust
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 2048)
            .user("Write a creative story about space exploration.")
            .temperature(0.8)  // More creative
            .top_p(0.9)        // Nucleus sampling
            .top_k(50)         // Top-k sampling
            .stop_sequences(vec!["THE END".to_string()])
            .build()
    )
    .await?;
```

### ๐Ÿ”„ Streaming Responses

```rust
use anthropic_sdk::{MessageCreateBuilder, StreamEvent};
use futures::StreamExt;

let mut stream = client.messages()
    .stream(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user("Tell me a story")
            .build()
    )
    .await?;

while let Some(event) = stream.next().await {
    match event? {
        StreamEvent::ContentBlockDelta { delta, .. } => {
            if let Some(text) = delta.text {
                print!("{}", text);
            }
        }
        StreamEvent::MessageStop => break,
        _ => {}
    }
}
```

### ๐Ÿ‘๏ธ Vision (Image Analysis)

```rust
use anthropic_sdk::{ContentBlockParam, MessageContent};

// Using base64 image
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user(MessageContent::Blocks(vec![
                ContentBlockParam::text("What do you see in this image?"),
                ContentBlockParam::image_base64("image/jpeg", base64_image_data),
            ]))
            .build()
    )
    .await?;

// Using image URL
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user(MessageContent::Blocks(vec![
                ContentBlockParam::text("Describe this image"),
                ContentBlockParam::image_url("https://example.com/image.jpg"),
            ]))
            .build()
    )
    .await?;
```

### ๐Ÿ› ๏ธ Tool Use

```rust
use anthropic_sdk::{Tool, ToolFunction, MessageCreateBuilder};

// Define a weather tool
let weather_tool = Tool {
    name: "get_weather".to_string(),
    description: "Get current weather for a location".to_string(),
    input_schema: serde_json::json!({
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "City name"
            }
        },
        "required": ["location"]
    }),
};

let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user("What's the weather like in Paris?")
            .tools(vec![weather_tool])
            .build()
    )
    .await?;

// Handle tool use in response
if let Some(tool_use) = response.content.get_tool_use() {
    println!("Claude wants to use tool: {}", tool_use.name);
    println!("With input: {}", tool_use.input);
}
```

### ๐Ÿ“ File Management

```rust
// Upload a file
let file = client.files()
    .upload("path/to/document.pdf", "assistants")
    .await?;

println!("Uploaded file: {} ({})", file.filename, file.id);

// List files
let files = client.files()
    .list(Some("assistants"), None, None)
    .await?;

// Use file in conversation
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .user(MessageContent::Blocks(vec![
                ContentBlockParam::text("Summarize this document"),
                ContentBlockParam::document(file.id, "Document to analyze"),
            ]))
            .build()
    )
    .await?;
```

### ๐Ÿ“Š Batch Processing

```rust
use anthropic_sdk::{BatchCreateBuilder, BatchRequestBuilder};

// Create batch requests
let requests = vec![
    BatchRequestBuilder::new("req_1")
        .messages(
            MessageCreateBuilder::new("claude-3-5-sonnet-latest", 100)
                .user("What is 2+2?")
                .build()
        )
        .build(),
    BatchRequestBuilder::new("req_2")
        .messages(
            MessageCreateBuilder::new("claude-3-5-sonnet-latest", 100)
                .user("What is 3+3?")
                .build()
        )
        .build(),
];

// Create and submit batch
let batch = client.batches()
    .create(
        BatchCreateBuilder::new(requests)
            .completion_window("24h")
            .build()
    )
    .await?;

println!("Batch created: {}", batch.id);

// Check batch status
let status = client.batches().retrieve(&batch.id).await?;
println!("Batch status: {:?}", status.processing_status);
```

### ๐Ÿค– Model Intelligence

```rust
use anthropic_sdk::{ModelRequirements, ModelCapability};

// List available models
let models = client.models().list(None).await?;
for model in models.data {
    println!("Model: {} ({})", model.display_name, model.id);
}

// Find best model for requirements
let requirements = ModelRequirements::new()
    .max_cost_per_million_tokens(15.0)
    .min_context_length(100000)
    .required_capabilities(vec![
        ModelCapability::Vision,
        ModelCapability::ToolUse,
    ])
    .build();

let best_model = client.models()
    .find_best_model(&requirements)
    .await?;

println!("Best model: {}", best_model.display_name);

// Compare models
let comparison = client.models()
    .compare_models(&["claude-3-5-sonnet-latest", "claude-3-5-haiku-latest"])
    .await?;

println!("Comparison: {}", comparison.summary.recommendation);
```

## ๐Ÿ—๏ธ Architecture & Design

### Type System
The SDK uses a comprehensive type system with:
- **Builders**: Fluent APIs for easy construction
- **Enums**: Type-safe model and parameter selection
- **Validation**: Compile-time and runtime validation
- **Serialization**: Automatic JSON handling with serde

### Error Handling
```rust
use anthropic_sdk::{AnthropicError, Result};

match client.messages().create(params).await {
    Ok(response) => println!("Success: {}", response.content.get_text()),
    Err(AnthropicError::ApiError { status, message, .. }) => {
        eprintln!("API Error {}: {}", status, message);
    }
    Err(AnthropicError::NetworkError { source }) => {
        eprintln!("Network Error: {}", source);
    }
    Err(e) => eprintln!("Other Error: {}", e),
}
```

### Async Patterns
Built on tokio with:
- Efficient connection pooling
- Automatic retries with exponential backoff
- Proper timeout handling
- Stream processing with backpressure

## ๐Ÿ”ง Configuration Options

### Environment Variables
```bash
ANTHROPIC_API_KEY=your-api-key
ANTHROPIC_BASE_URL=https://api.anthropic.com  # Optional
ANTHROPIC_TIMEOUT=30                          # Seconds
ANTHROPIC_MAX_RETRIES=3                       # Retry attempts
```

### Custom Configuration
```rust
use anthropic_sdk::{ClientConfig, LogLevel, Anthropic};
use std::time::Duration;

let config = ClientConfig::new("api-key")
    .with_base_url("https://api.anthropic.com")
    .with_timeout(Duration::from_secs(60))
    .with_max_retries(5)
    .with_log_level(LogLevel::Debug)
    .with_user_agent("MyApp/1.0");

let client = Anthropic::with_config(config)?;
```

## ๐Ÿ“Š Examples

The `examples/` directory contains comprehensive demonstrations:

- **`basic_client.rs`** - Basic client setup and configuration
- **`messages_api.rs`** - Complete Messages API usage
- **`streaming_example.rs`** - Real-time streaming responses
- **`comprehensive_tool_use.rs`** - Advanced tool integration
- **`comprehensive_file_upload.rs`** - File management workflows
- **`phase5_1_batches.rs`** - Batch processing examples
- **`phase5_3_models_api.rs`** - Model selection and comparison
- **`production_patterns.rs`** - Production-ready patterns

Run examples:
```bash
cargo run --example basic_client
cargo run --example messages_api
cargo run --example streaming_example
```

## ๐Ÿงช Testing

```bash
# Run all tests
cargo test

# Run with output
cargo test -- --nocapture

# Test specific module
cargo test messages

# Run integration tests
cargo test --test integration
```

## ๐Ÿ“š Documentation

Generate and view documentation:
```bash
# Generate docs
cargo doc --open --no-deps

# View online documentation
# https://docs.rs/anthropic-sdk-rust
```

## ๐Ÿš€ Performance & Production

### Connection Pooling
The SDK automatically manages HTTP connections with:
- Keep-alive connections
- Connection pooling via reqwest
- Automatic retries with exponential backoff

### Memory Management
- Streaming responses to handle large outputs
- Efficient JSON parsing with serde
- Minimal allocations in hot paths

### Error Recovery
- Automatic retries for transient failures
- Circuit breaker patterns for reliability
- Comprehensive error types for debugging

## ๐Ÿ›ก๏ธ Security

- API keys handled securely (never logged)
- HTTPS-only communication
- Input validation and sanitization
- Rate limiting awareness

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes and add tests
4. Run tests: `cargo test`
5. Commit: `git commit -m 'Add amazing feature'`
6. Push: `git push origin feature/amazing-feature`
7. Open a Pull Request

## ๐Ÿ“‹ Roadmap

- [x] **Phase 1**: Foundation & Client Setup
- [x] **Phase 2**: Messages API
- [x] **Phase 3**: Streaming & Tools
- [x] **Phase 4**: Vision & Advanced Features  
- [x] **Phase 5**: Files, Batches & Models APIs
- [ ] **Phase 6**: Cloud Integrations (AWS Bedrock, GCP Vertex AI)
- [ ] **Phase 7**: Advanced Streaming & WebSockets
- [ ] **Phase 8**: Caching & Performance Optimization

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™‹โ€โ™‚๏ธ Support

- **Documentation**: [docs.rs/anthropic-sdk-rust]https://docs.rs/anthropic-sdk-rust
- **Issues**: [GitHub Issues]https://github.com/anthropics/anthropic-sdk-rust/issues
- **Discussions**: [GitHub Discussions]https://github.com/anthropics/anthropic-sdk-rust/discussions

## ๐ŸŽฏ Examples Gallery

### Real-world Use Cases

```rust
// Customer Support Bot
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 1024)
            .system("You are a helpful customer support agent.")
            .user("I need help with my order #12345")
            .temperature(0.1) // Consistent responses
            .build()
    )
    .await?;

// Code Review Assistant
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 2048)
            .system("You are an expert code reviewer.")
            .user("Please review this Rust code for potential issues")
            .tools(vec![code_analysis_tool])
            .build()
    )
    .await?;

// Document Analysis
let response = client.messages()
    .create(
        MessageCreateBuilder::new("claude-3-5-sonnet-latest", 4096)
            .user(MessageContent::Blocks(vec![
                ContentBlockParam::text("Analyze this financial report"),
                ContentBlockParam::document(uploaded_file.id, "Q3 Report"),
            ]))
            .build()
    )
    .await?;
```

---

**Ready to build amazing AI-powered applications with Rust? Get started with the Anthropic SDK today!** ๐Ÿฆ€โœจ