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//! | [`vertex`] | GCP `OAuth2` [`vertex::VertexSigner`] (feature `vertex`) |
63//! | [`beta`] | [`BetaHeader`] open-string enum for the `anthropic-beta` header |
64//! | [`retry`] | [`retry::RetryPolicy`] honoring `Retry-After` |
65//! | [`error`] | [`Error`] with `request_id`, retry classification |
66//! | [`pagination`] | [`Paginated`](pagination::Paginated) and [`PaginatedNextPage`](pagination::PaginatedNextPage) |
67//! | [`types`] | Shared primitives: [`ModelId`](types::ModelId), [`Role`](types::Role), [`Usage`](types::Usage), [`StopReason`](types::StopReason) |
68//! | [`conversation`] | Multi-turn helper with cumulative usage (feature `conversation`) |
69//! | [`tool_dispatch`] | [`ToolRegistry`](tool_dispatch::ToolRegistry), agent loop, parallel dispatch, approval gates |
70//! | [`pricing`] | [`PricingTable`](pricing::PricingTable) (feature `pricing`) |
71//! | [`cost_preview`] | Pre-flight USD estimates (features `async` + `pricing`) |
72//! | [`dry_run`] | Render the would-be HTTP request without sending |
73//! | [`sse`] | SSE wrapper used by streaming endpoints (feature `streaming`) |
74//!
75//! # Forward compatibility
76//!
77//! Every wire-level discriminated union has an `Other` arm:
78//!
79//! - [`messages::ContentBlock`] -- text / image / `tool_use` /
80//! thinking / ... / `Other(Value)`
81//! - [`messages::KnownBlock`] -- the typed variants
82//! - [`messages::stream::StreamEvent`] -- SSE events
83//! - [`messages::citation::Citation`] -- citation kinds
84//! - [`BetaHeader`] -- known beta header values + `Other(String)`
85//!
86//! When Anthropic adds a new variant, your code that pattern-matches
87//! on `Known(...)` continues to compile; the new variant lands in
88//! `Other(...)` until you upgrade. See the **upgrade contract** in
89//! the README before bumping past a release that promotes an `Other`
90//! to `Known`.
91//!
92//! # Error handling
93//!
94//! All endpoint methods return [`Result<T>`](Result) where
95//! [`Error`] carries:
96//!
97//! - HTTP status (when the API responded)
98//! - `request-id` (always populated when the server sent one)
99//! - Retry classification (`is_retryable()`) and parsed
100//! `Retry-After` (`retry_after()`)
101//! - Structured kind ([`error::ApiErrorKind`]) for known
102//! error types
103//!
104//! The [`retry::RetryPolicy`] applied by the client respects
105//! `Retry-After` by default and uses jittered exponential backoff
106//! otherwise. Disable retries with `RetryPolicy::none()` if your
107//! caller wraps its own retry logic.
108//!
109//! # Observability
110//!
111//! Every HTTP request emits a `tracing` span at `debug` level with
112//! `method`, `path`, and `request_id` fields. Retries log at `warn`
113//! with `attempt`, `retry_in_ms`, and `status`. No env-var gating
114//! is required; install a `tracing-subscriber` to capture the
115//! events.
116
117#![cfg_attr(docsrs, feature(doc_cfg))]
118
119#[allow(dead_code)]
120pub(crate) const ANTHROPIC_VERSION: &str = "2023-06-01";
121#[allow(dead_code)]
122pub(crate) const DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
123#[allow(dead_code)]
124pub(crate) const USER_AGENT: &str = concat!("claude-api-rs/", env!("CARGO_PKG_VERSION"));
125
126pub mod auth;
127pub mod beta;
128pub mod error;
129
130#[cfg(feature = "bedrock")]
131#[cfg_attr(docsrs, doc(cfg(feature = "bedrock")))]
132pub mod bedrock;
133
134#[cfg(feature = "vertex")]
135#[cfg_attr(docsrs, doc(cfg(feature = "vertex")))]
136pub mod vertex;
137
138#[cfg(feature = "async")]
139#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
140pub mod client;
141
142#[cfg(feature = "sync")]
143#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
144pub mod blocking;
145
146#[cfg(any(feature = "async", feature = "sync"))]
147#[cfg_attr(docsrs, doc(cfg(any(feature = "async", feature = "sync"))))]
148pub mod retry;
149
150pub(crate) mod forward_compat;
151
152#[cfg(feature = "streaming")]
153#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
154pub mod sse;
155
156pub mod pagination;
157
158#[cfg(feature = "pricing")]
159#[cfg_attr(docsrs, doc(cfg(feature = "pricing")))]
160pub mod pricing;
161
162#[cfg(feature = "conversation")]
163#[cfg_attr(docsrs, doc(cfg(feature = "conversation")))]
164pub mod conversation;
165
166#[cfg(feature = "async")]
167#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
168pub mod tool_dispatch;
169
170#[cfg(feature = "async")]
171#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
172pub mod dry_run;
173
174#[cfg(all(feature = "async", feature = "pricing"))]
175#[cfg_attr(docsrs, doc(cfg(all(feature = "async", feature = "pricing"))))]
176pub mod cost_preview;
177
178pub mod types;
179
180pub mod batches;
181pub mod files;
182pub mod messages;
183pub mod models;
184
185#[cfg(feature = "managed-agents-preview")]
186#[cfg_attr(docsrs, doc(cfg(feature = "managed-agents-preview")))]
187pub mod managed_agents;
188
189#[cfg(feature = "admin")]
190#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
191pub mod admin;
192
193#[cfg(feature = "skills")]
194#[cfg_attr(docsrs, doc(cfg(feature = "skills")))]
195pub mod skills;
196
197#[cfg(feature = "user-profiles")]
198#[cfg_attr(docsrs, doc(cfg(feature = "user-profiles")))]
199pub mod user_profiles;
200
201pub use beta::BetaHeader;
202#[cfg(feature = "async")]
203pub use client::{Client, ClientBuilder};
204pub use error::{Error, Result};
205
206/// Procedural-macro re-exports for the `derive` feature.
207///
208/// Bring [`Tool`](crate::derive::Tool) into scope to derive
209/// [`tool_dispatch::Tool`] on a struct that
210/// implements [`serde::Deserialize`] and [`schemars::JsonSchema`].
211#[cfg(feature = "derive")]
212#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
213pub mod derive {
214 pub use claude_api_derive::Tool;
215}
216
217/// Implementation detail: re-exports used by macros generated by the
218/// `derive` feature. Not part of the public API; do not use directly.
219#[cfg(feature = "derive")]
220#[doc(hidden)]
221pub mod __private {
222 pub use async_trait;
223 pub use schemars;
224 pub use serde_json;
225}