anthropic-ai-sdk

Crates.ioanthropic-ai-sdk
lib.rsanthropic-ai-sdk
version0.2.27
created_at2025-01-14 21:38:55.103734+00
updated_at2026-01-11 12:41:28.883135+00
descriptionAn unofficial Rust SDK for Anthropic's Claude AI API
homepage
repositoryhttps://github.com/katsuhirohonda/anthropic-sdk-rs/tree/main/anthropic-ai-sdk
max_upload_size
id1516711
size176,866
Katsuhiro Honda (katsuhirohonda)

documentation

README

Anthropic Rust SDK

Crates.io Documentation License: MIT

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(&params)).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:

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

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.

Commit count: 320

cargo fmt