Expand description
A small typed client for Anthropic’s Messages API (POST /v1/messages) and the endpoints
around it, over raw HTTPS following the documented wire format:
- requests with system prompts (top-level or mid-conversation),
documentblocks with citations, images, tools, thinking and effort settings, task budgets, structured outputs,cache_controlbreakpoints and server-side refusalfallbacks(the matchinganthropic-betaheaders are added automatically); - responses with text, citations, thinking, tool calls and fallback markers, keeping any block, citation, event or delta type it does not know as raw JSON instead of failing, so a new API feature never breaks decoding and assistant turns echo back intact;
- retries on connection errors, 408, 409, 429 and 5xx (honouring
retry-afterandx-should-retry), bounded by an optional deadline that also cuts retries short; - streaming over server-sent events, event by event or accumulated into the final message;
- server tools (web search, web fetch, code execution, tool search) with typed
definitions, result blocks, web search citations and
usage.server_tool_use; - a tool-use loop (
Client::run_tools) that runs your tools and resumes paused turns; POST /v1/messages/count_tokens, Message Batches, the Files API and the Models API;- API version
2026-10-21(API_VERSION): messages typed by role, API keys sent asAuthorization: Bearer, and requests checked against the version’s rules before sending (MessagesRequest::validate);LEGACY_API_VERSIONkeeps the old behaviour.
use rust_claude_sdk::{Client, ClientConfig, ContentBlockParam, MessageParam, MessagesRequest};
let client = Client::new(ClientConfig::from_env().expect("ANTHROPIC_API_KEY"))?;
let request = MessagesRequest::new("claude-opus-5-5", 2048)
.system_cached("Answer only from the documents and cite them.")
.message(MessageParam::user(vec![
ContentBlockParam::text_document("Cartea de identitate se eliberează în 30 de zile.", "Ghid CI").with_citations(),
ContentBlockParam::text("În cât timp primesc buletinul?"),
]));
let message = client.create(&request).await?;
if message.is_refusal() {
return Ok(());
}
println!("{}", message.text());
for (span, citation) in message.citations() {
println!("{span:?} ← {:?}", citation.cited_text());
}Structs§
- ApiError
Body - The
errorobject of an API error response or of anerrorstream event. - Batch
Request - One request of a batch.
paramsis sent withoutstream;fallbacksis rejected here. - Batch
Result - One line of a batch’s results.
- Batch
Results - A batch’s results, read line by line as they download.
- Cache
Control - Call
Options - Per-call settings.
- Citations
Config - Client
- Client
Config - Code
Execution Output - Code
Execution Tool - Server-side code execution in a sandbox. Output comes back as
ContentBlock::BashCodeExecutionToolResultandTextEditorCodeExecutionToolResultblocks; files it writes can be downloaded withClient::download_file. - Deleted
- The answer to a
DELETE. - Fallback
Model - File
Metadata - List
Params - Which page of a list to fetch. Pages run newest first;
after_idmoves to older items,before_idto newer ones. - Message
- Message
Batch - Message
Stream - An open stream. Read it event by event with
next_event, or all at once withfinal_message; either way the message is accumulated as events arrive. - Messages
Request - Model
- Model
Ref - Output
Config - Page
- One page of a list.
- Request
Counts - Server
Tool Error - A server tool that ran but failed (
max_uses_exceeded,too_many_requests,unavailable,url_not_accessible…). The response itself still succeeds. - Server
Tool Usage usage.server_tool_use: billable server tool calls.- System
Block - A system prompt block; serialised with
"type": "text". - Task
Budget output_config.task_budget.- Tool
- Tool
Call - One tool call the model asked for.
- Tool
Loop Options - Tool
Output - What a tool returns to the model. A failure goes back with
is_errorset, so the model can try another way; it does not end the loop. - Tool
Reference - ToolRun
- How a tool loop ended.
- Tool
Search Found - Tool
Search Tool - Server-side search over the request’s deferred tools (
Tool::deferred): only the tools it finds are loaded. Keep at least one tool, this one included, not deferred. - Usage
- User
Location - Where the user roughly is, to localise search results; serialised with
"type": "approximate". - WebFetch
Result - WebFetch
Tool - Server-side fetch of a URL already present in the conversation. The page comes back as
a
ContentBlock::WebFetchToolResultblock. - WebSearch
Result - WebSearch
Tool - Server-side web search. Results come back as
ContentBlock::WebSearchToolResultblocks and cited text carriesCitation::WebSearchResultLocation. A failed search is an error object inside the result block, not an API error.
Enums§
- Batch
Outcome - Citation
- Where a cited span comes from.
- Code
Execution Content - What a code execution returned: its output, or an error object.
- Content
- Content
Block - Content
Block Param - Credential
- Delta
- Document
Source - Effort
- Error
- Errors never carry the request body or the credential.
- Fallbacks
- Which model the API retries a refused request on.
- Image
Source - Message
Param - One message of the conversation, typed by its role (serialised with its
role). - Processing
Status - Role
- Stop
Reason - Stream
Event - System
- Thinking
Config - Thinking
Display - Tool
Choice - Tool
Definition - A tool definition: a custom tool, a server tool Anthropic runs, or anything else as raw JSON.
- Tool
Result Content - Tool
Search Content - What a tool search found: references to the tools now loaded, or an error object.
- WebFetch
Content - What a web fetch returned: the page, or an error object.
- WebSearch
Content - What a web search returned: a list of results, or an error object.
Constants§
- API_
VERSION - Default value of the
anthropic-versionheader (seeClientConfig::api_version). - DEFAULT_
BASE_ URL - LEGACY_
API_ VERSION - The previous API version, for requests that still need its behaviour (e.g. sampling parameters on models that accept non-default values).