Skip to main content

Crate rust_claude_sdk

Crate rust_claude_sdk 

Source
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), document blocks with citations, images, tools, thinking and effort settings, task budgets, structured outputs, cache_control breakpoints and server-side refusal fallbacks (the matching anthropic-beta headers 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-after and x-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 as Authorization: Bearer, and requests checked against the version’s rules before sending (MessagesRequest::validate); LEGACY_API_VERSION keeps 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§

ApiErrorBody
The error object of an API error response or of an error stream event.
BatchRequest
One request of a batch. params is sent without stream; fallbacks is rejected here.
BatchResult
One line of a batch’s results.
BatchResults
A batch’s results, read line by line as they download.
CacheControl
CallOptions
Per-call settings.
CitationsConfig
Client
ClientConfig
CodeExecutionOutput
CodeExecutionTool
Server-side code execution in a sandbox. Output comes back as ContentBlock::BashCodeExecutionToolResult and TextEditorCodeExecutionToolResult blocks; files it writes can be downloaded with Client::download_file.
Deleted
The answer to a DELETE.
FallbackModel
FileMetadata
ListParams
Which page of a list to fetch. Pages run newest first; after_id moves to older items, before_id to newer ones.
Message
MessageBatch
MessageStream
An open stream. Read it event by event with next_event, or all at once with final_message; either way the message is accumulated as events arrive.
MessagesRequest
Model
ModelRef
OutputConfig
Page
One page of a list.
RequestCounts
ServerToolError
A server tool that ran but failed (max_uses_exceeded, too_many_requests, unavailable, url_not_accessible…). The response itself still succeeds.
ServerToolUsage
usage.server_tool_use: billable server tool calls.
SystemBlock
A system prompt block; serialised with "type": "text".
TaskBudget
output_config.task_budget.
Tool
ToolCall
One tool call the model asked for.
ToolLoopOptions
ToolOutput
What a tool returns to the model. A failure goes back with is_error set, so the model can try another way; it does not end the loop.
ToolReference
ToolRun
How a tool loop ended.
ToolSearchFound
ToolSearchTool
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
UserLocation
Where the user roughly is, to localise search results; serialised with "type": "approximate".
WebFetchResult
WebFetchTool
Server-side fetch of a URL already present in the conversation. The page comes back as a ContentBlock::WebFetchToolResult block.
WebSearchResult
WebSearchTool
Server-side web search. Results come back as ContentBlock::WebSearchToolResult blocks and cited text carries Citation::WebSearchResultLocation. A failed search is an error object inside the result block, not an API error.

Enums§

BatchOutcome
Citation
Where a cited span comes from.
CodeExecutionContent
What a code execution returned: its output, or an error object.
Content
ContentBlock
ContentBlockParam
Credential
Delta
DocumentSource
Effort
Error
Errors never carry the request body or the credential.
Fallbacks
Which model the API retries a refused request on.
ImageSource
MessageParam
One message of the conversation, typed by its role (serialised with its role).
ProcessingStatus
Role
StopReason
StreamEvent
System
ThinkingConfig
ThinkingDisplay
ToolChoice
ToolDefinition
A tool definition: a custom tool, a server tool Anthropic runs, or anything else as raw JSON.
ToolResultContent
ToolSearchContent
What a tool search found: references to the tools now loaded, or an error object.
WebFetchContent
What a web fetch returned: the page, or an error object.
WebSearchContent
What a web search returned: a list of results, or an error object.

Constants§

API_VERSION
Default value of the anthropic-version header (see ClientConfig::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).