51 releases
Uses new Rust 2024
0.2.26 | Jul 21, 2025 |
---|---|
0.2.19 | May 25, 2025 |
0.2.0 | Mar 27, 2025 |
#185 in Web programming
135 downloads per month
Used in 4 crates
130KB
2.5K
SLoC
Anthropic Rust SDK
An unofficial Rust SDK for the Anthropic API.
Features
- Robust async/await implementation using Tokio
- Comprehensive error handling with detailed error types
- Built-in pagination support for list operations
- Token counting utilities for accurate message length estimation
- Type-safe API with full Rust type definitions
- Easy-to-use builder patterns for request construction
- Beta API support including Files API
Installation
cargo add anthropic-ai-sdk
Quick Start
Messages API
use anthropic_ai_sdk::client::AnthropicClient;
use anthropic_ai_sdk::types::message::{
CreateMessageParams, Message, MessageClient, MessageError, RequiredMessageParams, Role,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let anthropic_api_key = std::env::var("ANTHROPIC_API_KEY").unwrap();
let client = AnthropicClient::new::<MessageError>(anthropic_api_key, "2023-06-01").unwrap();
// stream(false)
let body = CreateMessageParams::new(RequiredMessageParams {
model: "claude-3-7-sonnet-latest".to_string(),
messages: vec![Message::new_text(Role::User, "Hello, Claude")],
max_tokens: 1024,
});
match client.create_message(Some(&body)).await {
Ok(message) => {
println!("Successfully created message: {:?}", message.content);
}
Err(e) => {
println!("Error: {}", e);
}
}
// stream(true)
let body = CreateMessageParams::new(RequiredMessageParams {
model: "claude-3-7-sonnet-latest".to_string(),
messages: vec![Message::new_text(Role::User, "Hello, Claude")],
max_tokens: 1024,
})
.with_stream(true);
match client.create_message_streaming(&body).await {
Ok(mut stream) => {
while let Some(result) = stream.next().await {
match result {
Ok(event) => info!("Received event: {:?}", event),
Err(e) => error!("Stream error: {}", e),
}
}
}
Err(e) => {
error!("Error: {}", e);
}
}
Ok(())
}
Files API (Beta)
use anthropic_ai_sdk::client::AnthropicClient;
use anthropic_ai_sdk::files::FileClient;
use anthropic_ai_sdk::types::files::{FileError, ListFilesParams};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let anthropic_api_key = std::env::var("ANTHROPIC_API_KEY").unwrap();
let client = AnthropicClient::new::<FileError>(anthropic_api_key, "2023-06-01").unwrap();
// List files with default parameters
let files = client.list_files(None).await?;
println!("Total files: {}", files.data.len());
// List files with pagination
let params = ListFilesParams::new()
.limit(20)
.after_id("file_xyz");
let files = client.list_files(Some(¶ms)).await?;
for file in files.data {
println!("File: {} ({} bytes)", file.filename, file.size_bytes);
}
// Get metadata for a specific file
let file_metadata = client.get_file_metadata("file_abc123").await?;
println!("File: {} ({})", file_metadata.filename, file_metadata.mime_type);
// Download file content
let content = client.download_file("file_abc123").await?;
std::fs::write("downloaded_file.pdf", content)?;
// Upload a file
let file_content = std::fs::read("document.pdf")?;
let uploaded_file = client.upload_file("document.pdf", file_content).await?;
println!("Uploaded file ID: {}", uploaded_file.id);
// Delete a file
let deleted_file = client.delete_file("file_abc123").await?;
println!("Deleted file: {}", deleted_file.id);
Ok(())
}
Examples
Check out the examples directory for more usage examples:
- Models
- List Models - How to retrieve a list of available models
- Get a Model - How to get a model
- Messages
- Message - How to create a message
- Count Message Tokens - How to count tokens in a message
- Message Batch
- Create a Message Batch - How to create a message batch
- Files (Beta)
- List Files - How to list files in the Anthropic system
- Get File Metadata - How to retrieve metadata for a specific file
- Download File - How to download file content
- Upload File - How to upload a file
- Delete File - How to delete a file
- Admin Invites
- Get Invite - How to retrieve an organization invite
- List Invites - How to list organization invites
- Create Invite - How to create an organization invite
- Delete Invite - How to delete an organization invite
Note: The examples listed above are only a subset. For additional detailed usage examples, please refer to the examples directory.
API Coverage
- Models
- List Models
- Get a Model
- Messages
- Messages
- Count Message Tokens
- Message Batches
- Create a Message Batch
- Retrieve a Message Batch
- Retrieve Message Batch Results
- List Message Batches
- Cancel a Message Batch
- Delete a Message Batch
- Files (Beta)
- Create a File
- List Files
- Get File Metadata
- Download a File
- Delete a File
- Admin API
- Organization Member Management
- Get User
- List Users
- Update User
- Remove User
- Organization Invites
- Get Invite
- List Invites
- Create Invite
- Delete Invite
- Workspace Management
- Get Workspace
- List Workspaces
- Update Workspace
- Create Workspace
- Archive Workspace
- Workspace Member Management
- Get Workspace Member
- List Workspace Members
- Add Workspace Member
- Update Workspace Member
- Delete Workspace Member
- API Keys
- Get API Key
- List API Keys
- Update API Keys
- Organization Member Management
Development
Prerequisites
- Rust 1.85.0 or later
- An Anthropic API key
Running Tests
cargo test
Running Examples
Set your API key
export ANTHROPIC_API_KEY="your-api-key"
Run an example
cd examples/models/list-models
cargo run
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Security
If you discover a security vulnerability within this package, please send an e-mail to the maintainers. All security vulnerabilities will be promptly addressed.
Support
For support questions, please use the GitHub Issues.
Dependencies
~9–22MB
~289K SLoC