Skip to main content

rust_claude_sdk/
lib.rs

1//! A small typed client for Anthropic's Messages API (`POST /v1/messages`) and the endpoints
2//! around it, over raw HTTPS following the documented wire format:
3//!
4//! - requests with system prompts (top-level or mid-conversation), `document` blocks with
5//!   citations, images, tools, thinking and effort settings, task budgets, structured outputs,
6//!   `cache_control` breakpoints and server-side refusal `fallbacks` (the matching
7//!   `anthropic-beta` headers are added automatically);
8//! - responses with text, citations, thinking, tool calls and fallback markers, keeping
9//!   any block, citation, event or delta type it does not know as raw JSON instead of
10//!   failing, so a new API feature never breaks decoding and assistant turns echo back intact;
11//! - retries on connection errors, 408, 409, 429 and 5xx (honouring `retry-after` and
12//!   `x-should-retry`), bounded by an optional deadline that also cuts retries short;
13//! - streaming over server-sent events, event by event or accumulated into the final message;
14//! - server tools (web search, web fetch, code execution, tool search) with typed
15//!   definitions, result blocks, web search citations and `usage.server_tool_use`;
16//! - a tool-use loop (`Client::run_tools`) that runs your tools and resumes paused turns;
17//! - `POST /v1/messages/count_tokens`, Message Batches, the Files API and the Models API;
18//! - API version `2026-10-21` (`API_VERSION`): messages typed by role, API keys sent as
19//!   `Authorization: Bearer`, and requests checked against the version's rules before
20//!   sending (`MessagesRequest::validate`); `LEGACY_API_VERSION` keeps the old behaviour.
21//!
22//! ```no_run
23//! use rust_claude_sdk::{Client, ClientConfig, ContentBlockParam, MessageParam, MessagesRequest};
24//!
25//! # async fn run() -> Result<(), rust_claude_sdk::Error> {
26//! let client = Client::new(ClientConfig::from_env().expect("ANTHROPIC_API_KEY"))?;
27//! let request = MessagesRequest::new("claude-opus-5-5", 2048)
28//!     .system_cached("Answer only from the documents and cite them.")
29//!     .message(MessageParam::user(vec![
30//!         ContentBlockParam::text_document("Cartea de identitate se eliberează în 30 de zile.", "Ghid CI").with_citations(),
31//!         ContentBlockParam::text("În cât timp primesc buletinul?"),
32//!     ]));
33//! let message = client.create(&request).await?;
34//! if message.is_refusal() {
35//!     return Ok(());
36//! }
37//! println!("{}", message.text());
38//! for (span, citation) in message.citations() {
39//!     println!("{span:?} ← {:?}", citation.cited_text());
40//! }
41//! # Ok(())
42//! # }
43//! ```
44#[macro_use]
45mod open;
46
47mod batches;
48mod client;
49mod error;
50mod files;
51mod models;
52mod page;
53mod request;
54mod response;
55mod stream;
56mod tools;
57
58pub use batches::{BatchOutcome, BatchRequest, BatchResult, BatchResults, MessageBatch, ProcessingStatus, RequestCounts};
59pub use client::{CallOptions, Client, ClientConfig, Credential, API_VERSION, DEFAULT_BASE_URL, LEGACY_API_VERSION};
60pub use error::{ApiErrorBody, Error};
61pub use files::FileMetadata;
62pub use models::Model;
63pub use page::{Deleted, ListParams, Page};
64pub use request::{
65    CacheControl, CitationsConfig, CodeExecutionTool, Content, ContentBlockParam, DocumentSource, Effort, FallbackModel, Fallbacks, ImageSource, MessageParam,
66    MessagesRequest, OutputConfig, Role, System, SystemBlock, TaskBudget, ThinkingConfig, ThinkingDisplay, Tool, ToolChoice, ToolDefinition, ToolResultContent,
67    ToolSearchTool, UserLocation, WebFetchTool, WebSearchTool,
68};
69pub use response::{
70    Citation, CodeExecutionContent, CodeExecutionOutput, ContentBlock, Message, ModelRef, ServerToolError, ServerToolUsage, StopReason, ToolReference,
71    ToolSearchContent, ToolSearchFound, Usage, WebFetchContent, WebFetchResult, WebSearchContent, WebSearchResult,
72};
73pub use stream::{Delta, MessageStream, StreamEvent};
74pub use tools::{ToolCall, ToolLoopOptions, ToolOutput, ToolRun};