claude_sdk/lib.rs
1//! # Claude SDK for Rust
2//!
3//! [](https://crates.io/crates/claude-sdk)
4//! [](https://docs.rs/claude-sdk)
5//! [](https://opensource.org/licenses/MIT)
6//!
7//! A native Rust implementation of the Claude API client with full support for
8//! streaming, tool execution, vision, batch processing, and more.
9//!
10//! ## Features
11//!
12//! - **Complete API Coverage**: Messages, streaming, tools, vision, batch processing
13//! - **Multi-Platform**: Anthropic API and AWS Bedrock support
14//! - **Type-Safe**: Comprehensive type definitions for all API structures
15//! - **Async/Await**: Built on tokio for efficient async operations
16//! - **Streaming**: Server-sent events (SSE) with typed event parsing
17//! - **Tool Use**: Define tools and handle programmatic tool calls
18//! - **Prompt Caching**: Cache system prompts and tools for cost savings
19//! - **Extended Thinking**: Enable Claude's step-by-step reasoning
20//! - **Token Counting**: Estimate token usage before API calls
21//! - **Retry Logic**: Built-in exponential backoff for rate limits
22//!
23//! ## Quick Start
24//!
25//! Add to your `Cargo.toml`:
26//!
27//! ```toml
28//! [dependencies]
29//! claude-sdk = "1.0"
30//! tokio = { version = "1", features = ["full"] }
31//! ```
32//!
33//! Basic usage:
34//!
35//! ```rust,no_run
36//! use claude_sdk::{ClaudeClient, MessagesRequest, Message};
37//!
38//! #[tokio::main]
39//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
40//! let client = ClaudeClient::anthropic(
41//! std::env::var("ANTHROPIC_API_KEY")?
42//! );
43//!
44//! let request = MessagesRequest::new(
45//! "claude-sonnet-4-5-20250929",
46//! 1024,
47//! vec![Message::user("Hello, Claude!")],
48//! );
49//!
50//! let response = client.send_message(request).await?;
51//! println!("Response: {:?}", response);
52//! Ok(())
53//! }
54//! ```
55//!
56//! ## Feature Flags
57//!
58//! The SDK uses feature flags to control optional functionality:
59//!
60//! | Feature | Default | Description |
61//! |---------|---------|-------------|
62//! | `anthropic` | Yes | Enable Anthropic API support |
63//! | `bedrock` | No | Enable AWS Bedrock support |
64//! | `repl` | No | Include interactive REPL binary |
65//! | `full` | No | Enable all features |
66//!
67//! To enable AWS Bedrock support:
68//!
69//! ```toml
70//! [dependencies]
71//! claude-sdk = { version = "1.0", features = ["bedrock"] }
72//! ```
73//!
74//! ## Streaming Responses
75//!
76//! Use streaming for real-time token generation:
77//!
78//! ```rust,no_run
79//! use claude_sdk::{ClaudeClient, MessagesRequest, Message, StreamEvent, ContentDelta};
80//! use futures::StreamExt;
81//!
82//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
83//! let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);
84//!
85//! let request = MessagesRequest::new(
86//! "claude-sonnet-4-5-20250929",
87//! 1024,
88//! vec![Message::user("Write a haiku about Rust.")],
89//! );
90//!
91//! let mut stream = client.send_streaming(request).await?;
92//!
93//! while let Some(event) = stream.next().await {
94//! match event? {
95//! StreamEvent::ContentBlockDelta { delta, .. } => {
96//! if let ContentDelta::TextDelta { text } = delta {
97//! print!("{}", text);
98//! }
99//! }
100//! StreamEvent::MessageStop => println!("\n--- Done ---"),
101//! _ => {}
102//! }
103//! }
104//! # Ok(())
105//! # }
106//! ```
107//!
108//! ## Tool Use
109//!
110//! Define and handle tool calls:
111//!
112//! ```rust,no_run
113//! use claude_sdk::{ClaudeClient, MessagesRequest, Message, CustomTool, ContentBlock};
114//! use serde_json::json;
115//!
116//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
117//! let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);
118//!
119//! let weather_tool = CustomTool::new(
120//! "get_weather",
121//! "Get weather for a location",
122//! json!({
123//! "type": "object",
124//! "properties": {
125//! "location": { "type": "string" }
126//! },
127//! "required": ["location"]
128//! }),
129//! )
130//! .programmatic();
131//!
132//! let request = MessagesRequest::new(
133//! "claude-sonnet-4-5-20250929",
134//! 1024,
135//! vec![Message::user("What's the weather in Tokyo?")],
136//! )
137//! .with_custom_tools(vec![weather_tool]);
138//!
139//! let response = client.send_message(request).await?;
140//!
141//! // Handle tool use in response
142//! for block in &response.content {
143//! if let ContentBlock::ToolUse { id, name, input, .. } = block {
144//! println!("Tool: {} ({})", name, id);
145//! println!("Input: {}", input);
146//! // Execute tool and return result...
147//! }
148//! }
149//! # Ok(())
150//! # }
151//! ```
152//!
153//! ## AWS Bedrock
154//!
155//! Use Claude through AWS Bedrock (requires `bedrock` feature):
156//!
157//! ```rust,ignore
158//! use claude_sdk::ClaudeClient;
159//!
160//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
161//! // Uses AWS credentials from environment/config
162//! let client = ClaudeClient::bedrock("us-east-1").await?;
163//!
164//! // Use the same API as Anthropic
165//! // ...
166//! # Ok(())
167//! # }
168//! ```
169//!
170//! ## Modules
171//!
172//! - [`client`] - API client for Anthropic and AWS Bedrock
173//! - [`types`] - Request/response types and content blocks
174//! - [`streaming`] - SSE streaming types and event parsing
175//! - [`conversation`] - Multi-turn conversation builder
176//! - [`batch`] - Batch processing API for bulk operations
177//! - [`files`] - Files API for document uploads
178//! - [`models`] - Model constants and metadata
179//! - [`tokens`] - Token counting utilities
180//! - [`retry`] - Retry logic with exponential backoff
181//! - [`error`] - Error types and result aliases
182//! - [`prompts`] - Pre-built system prompts
183//! - [`structured`] - Structured output helpers
184//!
185//! ## Model Selection
186//!
187//! Use model constants for type-safe model selection:
188//!
189//! ```rust
190//! use claude_sdk::models::{CLAUDE_SONNET_4_5, CLAUDE_OPUS_4_5, CLAUDE_HAIKU_4_5};
191//!
192//! // Latest models
193//! let model = CLAUDE_SONNET_4_5;
194//! println!("Using: {} ({})", model.name, model.anthropic_id);
195//! println!("Max tokens: {}", model.max_output_tokens);
196//! println!("Supports vision: {}", model.supports_vision);
197//! ```
198//!
199//! ## Error Handling
200//!
201//! The SDK provides typed errors with retry information:
202//!
203//! ```rust,no_run
204//! use claude_sdk::{ClaudeClient, MessagesRequest, Message, Error};
205//!
206//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
207//! let client = ClaudeClient::anthropic(std::env::var("ANTHROPIC_API_KEY")?);
208//! let request = MessagesRequest::new(
209//! "claude-sonnet-4-5-20250929",
210//! 1024,
211//! vec![Message::user("Hello!")],
212//! );
213//!
214//! match client.send_message(request).await {
215//! Ok(response) => println!("Success!"),
216//! Err(Error::RateLimit { retry_after, .. }) => {
217//! println!("Rate limited. Retry after: {:?}s", retry_after);
218//! }
219//! Err(Error::Api { status, message, .. }) => {
220//! println!("API error ({}): {}", status, message);
221//! }
222//! Err(e) => println!("Other error: {}", e),
223//! }
224//! # Ok(())
225//! # }
226//! ```
227
228pub mod batch;
229pub mod client;
230pub mod conversation;
231pub mod error;
232pub mod files;
233pub mod models;
234pub mod prompts;
235pub mod retry;
236pub mod server_tools;
237pub mod streaming;
238pub mod structured;
239pub mod tokens;
240pub mod types;
241
242// Re-export main types for convenience
243pub use client::ClaudeClient;
244pub use conversation::ConversationBuilder;
245pub use error::{Error, Result};
246pub use models::{BedrockRegion, Model};
247pub use streaming::{ContentDelta, MessageDelta, StreamEvent};
248#[allow(deprecated)]
249pub use types::{
250 CacheTtl, Container, ContentBlock, CustomTool, EffortLevel, Message, MessagesRequest,
251 MessagesResponse, Metadata, OutputConfig, OutputFormat, OutputTokensDetails, RateLimitInfo,
252 RefusalCategory, Role, ServerToolUsage, ServiceTier, StopDetails, StopReason, ThinkingConfig,
253 ThinkingDisplay, TokenCount, Tool, ToolChoice, ToolDefinition, ToolResultContent, Usage,
254};