claude_api/lib.rs
1//! Type-safe Rust client for the [Anthropic API](https://docs.anthropic.com/).
2//!
3//! Every documented Anthropic endpoint is reachable through a typed
4//! namespace handle off [`Client`]. Forward-compatible by design --
5//! unknown content blocks, stream events, citations, and similar
6//! discriminated unions round-trip through `Other(Value)` arms so
7//! new server-side variants don't break older SDK builds.
8//!
9//! # Quick start
10//!
11//! ```no_run
12//! use claude_api::{Client, messages::CreateMessageRequest, types::ModelId};
13//!
14//! # async fn run() -> Result<(), claude_api::Error> {
15//! let client = Client::new(std::env::var("ANTHROPIC_API_KEY").unwrap());
16//!
17//! let resp = client
18//! .messages()
19//! .create(
20//! CreateMessageRequest::builder()
21//! .model(ModelId::SONNET_4_6)
22//! .max_tokens(256)
23//! .user("Hello!")
24//! .build()?,
25//! )
26//! .await?;
27//!
28//! for block in &resp.content {
29//! if let claude_api::messages::ContentBlock::Known(
30//! claude_api::messages::KnownBlock::Text { text, .. },
31//! ) = block
32//! {
33//! println!("{text}");
34//! }
35//! }
36//! # Ok(())
37//! # }
38//! ```
39//!
40//! # Module map
41//!
42//! Endpoints are organized by Anthropic resource. Each namespace
43//! handle is reached via a method on [`Client`]:
44//!
45//! | Module | Namespace | Default? |
46//! |---|---|---|
47//! | [`messages`] | `client.messages()` | yes |
48//! | [`models`] | `client.models()` | yes |
49//! | [`batches`] | `client.batches()` | yes |
50//! | [`files`] | `client.files()` | yes |
51//! | [`skills`] | `client.skills()` | feature `skills` |
52//! | [`user_profiles`] | `client.user_profiles()` | feature `user-profiles` |
53//! | [`managed_agents`] | `client.managed_agents()` | feature `managed-agents-preview` |
54//! | [`admin`] | `client.admin()` | feature `admin` |
55//!
56//! Cross-cutting machinery:
57//!
58//! | Module | Purpose |
59//! |---|---|
60//! | [`auth`] | API-key wrapper + [`auth::RequestSigner`] trait |
61//! | [`bedrock`] | AWS sigv4 [`bedrock::BedrockSigner`] (feature `bedrock`) |
62//! | [`beta`] | [`BetaHeader`] open-string enum for the `anthropic-beta` header |
63//! | [`retry`] | [`retry::RetryPolicy`] honoring `Retry-After` |
64//! | [`error`] | [`Error`] with `request_id`, retry classification |
65//! | [`pagination`] | [`Paginated`](pagination::Paginated) and [`PaginatedNextPage`](pagination::PaginatedNextPage) |
66//! | [`types`] | Shared primitives: [`ModelId`](types::ModelId), [`Role`](types::Role), [`Usage`](types::Usage), [`StopReason`](types::StopReason) |
67//! | [`conversation`] | Multi-turn helper with cumulative usage (feature `conversation`) |
68//! | [`tool_dispatch`] | [`ToolRegistry`](tool_dispatch::ToolRegistry), agent loop, parallel dispatch, approval gates |
69//! | [`pricing`] | [`PricingTable`](pricing::PricingTable) (feature `pricing`) |
70//! | [`cost_preview`] | Pre-flight USD estimates (features `async` + `pricing`) |
71//! | [`dry_run`] | Render the would-be HTTP request without sending |
72//! | [`sse`] | SSE wrapper used by streaming endpoints (feature `streaming`) |
73//!
74//! # Forward compatibility
75//!
76//! Every wire-level discriminated union has an `Other` arm:
77//!
78//! - [`messages::ContentBlock`] -- text / image / `tool_use` /
79//! thinking / ... / `Other(Value)`
80//! - [`messages::KnownBlock`] -- the typed variants
81//! - [`messages::stream::StreamEvent`] -- SSE events
82//! - [`messages::citation::Citation`] -- citation kinds
83//! - [`BetaHeader`] -- known beta header values + `Other(String)`
84//!
85//! When Anthropic adds a new variant, your code that pattern-matches
86//! on `Known(...)` continues to compile; the new variant lands in
87//! `Other(...)` until you upgrade. See the **upgrade contract** in
88//! the README before bumping past a release that promotes an `Other`
89//! to `Known`.
90//!
91//! # Error handling
92//!
93//! All endpoint methods return [`Result<T>`](Result) where
94//! [`Error`] carries:
95//!
96//! - HTTP status (when the API responded)
97//! - `request-id` (always populated when the server sent one)
98//! - Retry classification (`is_retryable()`) and parsed
99//! `Retry-After` (`retry_after()`)
100//! - Structured kind ([`error::ApiErrorKind`]) for known
101//! error types
102//!
103//! The [`retry::RetryPolicy`] applied by the client respects
104//! `Retry-After` by default and uses jittered exponential backoff
105//! otherwise. Disable retries with `RetryPolicy::none()` if your
106//! caller wraps its own retry logic.
107//!
108//! # Observability
109//!
110//! Every HTTP request emits a `tracing` span at `debug` level with
111//! `method`, `path`, and `request_id` fields. Retries log at `warn`
112//! with `attempt`, `retry_in_ms`, and `status`. No env-var gating
113//! is required; install a `tracing-subscriber` to capture the
114//! events.
115
116#![cfg_attr(docsrs, feature(doc_cfg))]
117
118#[allow(dead_code)]
119pub(crate) const ANTHROPIC_VERSION: &str = "2023-06-01";
120#[allow(dead_code)]
121pub(crate) const DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
122#[allow(dead_code)]
123pub(crate) const USER_AGENT: &str = concat!("claude-api-rs/", env!("CARGO_PKG_VERSION"));
124
125pub mod auth;
126pub mod beta;
127pub mod error;
128
129#[cfg(feature = "bedrock")]
130#[cfg_attr(docsrs, doc(cfg(feature = "bedrock")))]
131pub mod bedrock;
132
133#[cfg(feature = "async")]
134#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
135pub mod client;
136
137#[cfg(feature = "sync")]
138#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
139pub mod blocking;
140
141#[cfg(any(feature = "async", feature = "sync"))]
142#[cfg_attr(docsrs, doc(cfg(any(feature = "async", feature = "sync"))))]
143pub mod retry;
144
145pub(crate) mod forward_compat;
146
147#[cfg(feature = "streaming")]
148#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
149pub mod sse;
150
151pub mod pagination;
152
153#[cfg(feature = "pricing")]
154#[cfg_attr(docsrs, doc(cfg(feature = "pricing")))]
155pub mod pricing;
156
157#[cfg(feature = "conversation")]
158#[cfg_attr(docsrs, doc(cfg(feature = "conversation")))]
159pub mod conversation;
160
161#[cfg(feature = "async")]
162#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
163pub mod tool_dispatch;
164
165#[cfg(feature = "async")]
166#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
167pub mod dry_run;
168
169#[cfg(all(feature = "async", feature = "pricing"))]
170#[cfg_attr(docsrs, doc(cfg(all(feature = "async", feature = "pricing"))))]
171pub mod cost_preview;
172
173pub mod types;
174
175pub mod batches;
176pub mod files;
177pub mod messages;
178pub mod models;
179
180#[cfg(feature = "managed-agents-preview")]
181#[cfg_attr(docsrs, doc(cfg(feature = "managed-agents-preview")))]
182pub mod managed_agents;
183
184#[cfg(feature = "admin")]
185#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
186pub mod admin;
187
188#[cfg(feature = "skills")]
189#[cfg_attr(docsrs, doc(cfg(feature = "skills")))]
190pub mod skills;
191
192#[cfg(feature = "user-profiles")]
193#[cfg_attr(docsrs, doc(cfg(feature = "user-profiles")))]
194pub mod user_profiles;
195
196pub use beta::BetaHeader;
197#[cfg(feature = "async")]
198pub use client::{Client, ClientBuilder};
199pub use error::{Error, Result};
200
201/// Procedural-macro re-exports for the `derive` feature.
202///
203/// Bring [`Tool`](crate::derive::Tool) into scope to derive
204/// [`tool_dispatch::Tool`] on a struct that
205/// implements [`serde::Deserialize`] and [`schemars::JsonSchema`].
206#[cfg(feature = "derive")]
207#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
208pub mod derive {
209 pub use claude_api_derive::Tool;
210}
211
212/// Implementation detail: re-exports used by macros generated by the
213/// `derive` feature. Not part of the public API; do not use directly.
214#[cfg(feature = "derive")]
215#[doc(hidden)]
216pub mod __private {
217 pub use async_trait;
218 pub use schemars;
219 pub use serde_json;
220}