Skip to main content

Crate claude_sdk

Crate claude_sdk 

Source
Expand description

§Claude SDK for Rust

Crates.io Documentation License: MIT

A native Rust implementation of the Claude API client with full support for streaming, tool execution, vision, batch processing, and more.

§Features

  • Complete API Coverage: Messages, streaming, tools, vision, batch processing
  • Multi-Platform: Anthropic API and AWS Bedrock support
  • Type-Safe: Comprehensive type definitions for all API structures
  • Async/Await: Built on tokio for efficient async operations
  • Streaming: Server-sent events (SSE) with typed event parsing
  • Tool Use: Define tools and handle programmatic tool calls
  • Prompt Caching: Cache system prompts and tools for cost savings
  • Extended Thinking: Enable Claude’s step-by-step reasoning
  • Token Counting: Estimate token usage before API calls
  • Retry Logic: Built-in exponential backoff for rate limits

§Quick Start

Add to your Cargo.toml:

[dependencies]
claude-sdk = "1.0"
tokio = { version = "1", features = ["full"] }

Basic usage:

use claude_sdk::{ClaudeClient, MessagesRequest, Message};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ClaudeClient::anthropic(
        std::env::var("ANTHROPIC_API_KEY")?
    );

    let request = MessagesRequest::new(
        "claude-sonnet-4-5-20250929",
        1024,
        vec![Message::user("Hello, Claude!")],
    );

    let response = client.send_message(request).await?;
    println!("Response: {:?}", response);
    Ok(())
}

§Feature Flags

The SDK uses feature flags to control optional functionality:

FeatureDefaultDescription
anthropicYesEnable Anthropic API support
bedrockNoEnable AWS Bedrock support
replNoInclude interactive REPL binary
fullNoEnable all features

To enable AWS Bedrock support:

[dependencies]
claude-sdk = { version = "1.0", features = ["bedrock"] }

§Streaming Responses

Use streaming for real-time token generation:

use claude_sdk::{ClaudeClient, MessagesRequest, Message, StreamEvent, ContentDelta};
use futures::StreamExt;

let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);

let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("Write a haiku about Rust.")],
);

let mut stream = client.send_streaming(request).await?;

while let Some(event) = stream.next().await {
    match event? {
        StreamEvent::ContentBlockDelta { delta, .. } => {
            if let ContentDelta::TextDelta { text } = delta {
                print!("{}", text);
            }
        }
        StreamEvent::MessageStop => println!("\n--- Done ---"),
        _ => {}
    }
}

§Tool Use

Define and handle tool calls:

use claude_sdk::{ClaudeClient, MessagesRequest, Message, CustomTool, ContentBlock};
use serde_json::json;

let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);

let weather_tool = CustomTool::new(
    "get_weather",
    "Get weather for a location",
    json!({
        "type": "object",
        "properties": {
            "location": { "type": "string" }
        },
        "required": ["location"]
    }),
)
.programmatic();

let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("What's the weather in Tokyo?")],
)
.with_custom_tools(vec![weather_tool]);

let response = client.send_message(request).await?;

// Handle tool use in response
for block in &response.content {
    if let ContentBlock::ToolUse { id, name, input, .. } = block {
        println!("Tool: {} ({})", name, id);
        println!("Input: {}", input);
        // Execute tool and return result...
    }
}

§AWS Bedrock

Use Claude through AWS Bedrock (requires bedrock feature):

use claude_sdk::ClaudeClient;

// Uses AWS credentials from environment/config
let client = ClaudeClient::bedrock("us-east-1").await?;

// Use the same API as Anthropic
// ...

§Modules

  • client - API client for Anthropic and AWS Bedrock
  • types - Request/response types and content blocks
  • streaming - SSE streaming types and event parsing
  • conversation - Multi-turn conversation builder
  • batch - Batch processing API for bulk operations
  • files - Files API for document uploads
  • models - Model constants and metadata
  • tokens - Token counting utilities
  • retry - Retry logic with exponential backoff
  • error - Error types and result aliases
  • prompts - Pre-built system prompts
  • structured - Structured output helpers

§Model Selection

Use model constants for type-safe model selection:

use claude_sdk::models::{CLAUDE_SONNET_4_5, CLAUDE_OPUS_4_5, CLAUDE_HAIKU_4_5};

// Latest models
let model = CLAUDE_SONNET_4_5;
println!("Using: {} ({})", model.name, model.anthropic_id);
println!("Max tokens: {}", model.max_output_tokens);
println!("Supports vision: {}", model.supports_vision);

§Error Handling

The SDK provides typed errors with retry information:

use claude_sdk::{ClaudeClient, MessagesRequest, Message, Error};

let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);
let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("Hello!")],
);

match client.send_message(request).await {
    Ok(response) => println!("Success!"),
    Err(Error::RateLimit { retry_after, .. }) => {
        println!("Rate limited. Retry after: {:?}s", retry_after);
    }
    Err(Error::Api { status, message, .. }) => {
        println!("API error ({}): {}", status, message);
    }
    Err(e) => println!("Other error: {}", e),
}

Re-exports§

pub use client::ClaudeClient;
pub use conversation::ConversationBuilder;
pub use error::Error;
pub use error::Result;
pub use models::BedrockRegion;
pub use models::Model;
pub use streaming::ContentDelta;
pub use streaming::MessageDelta;
pub use streaming::StreamEvent;
pub use types::CacheTtl;
pub use types::Container;
pub use types::ContentBlock;
pub use types::CustomTool;
pub use types::EffortLevel;
pub use types::Message;
pub use types::MessagesRequest;
pub use types::MessagesResponse;
pub use types::Metadata;
pub use types::OutputConfig;
pub use types::OutputFormat;
pub use types::OutputTokensDetails;
pub use types::RateLimitInfo;
pub use types::RefusalCategory;
pub use types::Role;
pub use types::ServerToolUsage;
pub use types::ServiceTier;
pub use types::StopDetails;
pub use types::StopReason;
pub use types::ThinkingConfig;
pub use types::ThinkingDisplay;
pub use types::TokenCount;
pub use types::Tool;Deprecated
pub use types::ToolChoice;
pub use types::ToolDefinition;
pub use types::ToolResultContent;
pub use types::Usage;

Modules§

batch
Message Batches API for async bulk processing.
client
Claude API client implementation
conversation
Conversation builder for multi-turn interactions.
error
Error types for the Claude SDK.
files
Files API client for uploading and managing files
models
Model identifiers and metadata for Claude models.
prompts
Pre-built system prompts for common use cases
retry
Retry logic with exponential backoff
server_tools
Server-side tool definitions for Claude API built-in tools.
streaming
Streaming support for Claude API.
structured
Structured outputs using forced tool use
tokens
Token counting utilities for context window management
types
Type definitions for Claude API requests and responses.