anthropic_sdk_dart library

Anthropic API client for Dart.

Provides type-safe access to Claude models via the Anthropic API.

Getting Started

import 'package:anthropic_sdk_dart/anthropic_sdk_dart.dart';

final client = AnthropicClient(
  config: AnthropicConfig(
    authProvider: ApiKeyProvider('your-api-key'),
  ),
);

// Use client.messages, client.models, etc.

client.close();

Environment Configuration

final client = AnthropicClient.fromEnvironment();
// Uses ANTHROPIC_API_KEY environment variable

Classes

Agent
A Managed Agents agent.
AgentCustomToolUseEvent
Agent custom tool invocation event.
AgentMcpToolResultEvent
Result of an MCP tool execution.
AgentMcpToolUseEvent
Agent MCP tool invocation event.
AgentMessageEvent
An agent response event with text content.
AgentParams
Agent parameter — either a plain agent ID string or an object with id, type, and optional version.
AgentParamsId
A plain agent ID string.
AgentParamsObject
An agent specification with id, type, and optional version.
AgentSkill
Resolved skill as returned in API responses.
AgentSkillParams
Skill parameter for create/update requests.
AgentsResource
Resource for the Agents API (Beta).
AgentThinkingEvent
Agent thinking progress signal.
AgentThreadContextCompactedEvent
Context compaction (summarization) occurred during the session.
AgentTool
Union type for tool configurations returned in API responses.
AgentToolConfig
Configuration for a specific agent tool (response variant).
AgentToolConfigParams
Configuration override for a specific agent tool (request variant).
AgentToolParams
Union type for tool configurations in create/update requests.
AgentToolResultEvent
Result of a built-in agent tool execution.
AgentToolset20260401
Configuration for built-in agent tools (response variant).
AgentToolset20260401Params
Configuration for built-in agent tools (request variant).
AgentToolsetDefaultConfig
Resolved default configuration for agent tools.
AgentToolsetDefaultConfigParams
Default configuration for agent tools (request variant).
AgentToolUseEvent
Agent built-in tool invocation event.
AlwaysAllowPolicy
Tool calls are automatically approved without user confirmation.
AlwaysAskPolicy
Tool calls require user confirmation before execution.
AnthropicClient
Dart client for the Anthropic API.
AnthropicConfig
Configuration for the Anthropic client.
AnthropicSkill
A resolved Anthropic-managed skill.
AnthropicSkillParams
An Anthropic-managed skill parameter.
ApiKeyCredentials
API key authentication credentials.
ApiKeyProvider
Simple API key provider with static credentials.
AuthCredentials
Authentication credentials returned by AuthProvider.
AuthProvider
Authentication provider interface for the Anthropic client.
Base64ImageSource
Base64-encoded image source.
Base64PdfSource
Base64-encoded PDF document source.
BashCodeExecutionToolResultBlock
Bash code execution tool result block.
BashCodeExecutionToolResultInputBlock
Bash code execution tool result block in input.
BashTool
Bash tool for executing shell commands.
BatchError
Error information in batch results.
BatchIndividualResponse
Individual batch response item.
BatchRequestItem
Individual request item for batch creation.
BatchResult
Result of a batch request.
BatchResultCanceled
Canceled batch result.
BatchResultErrored
Errored batch result.
BatchResultExpired
Expired batch result.
BatchResultSucceeded
Successful batch result.
BillingError
Billing error — out of credits or spend limit reached.
BlocksMessageContent
Block content for a message.
BlocksSystemPrompt
Blocks system prompt.
BranchCheckout
Check out a branch.
BuiltInTool
Base class for Anthropic built-in tools.
BuiltInToolDefinition
A built-in Anthropic tool.
CacheControlEphemeral
Cache control configuration for ephemeral caching.
CacheCreation
Token usage breakdown for cache creation.
CacheCreationUsage
Prompt-cache creation token usage broken down by cache lifetime.
CacheRead
Token usage breakdown for cache reads.
CapabilitySupport
Indicates whether a capability is supported.
CharLocationCitation
Citation with character location (for plain text sources).
Citation
Citation for text content.
CitationsDelta
Delta for citation content updates.
CodeExecutionBuiltInTool
Code execution built-in tool.
CodeExecutionTool
Code execution tool for running code in a sandboxed environment.
CodeExecutionToolResultBlock
Code execution tool result block.
CodeExecutionToolResultInputBlock
Code execution tool result block in input.
CommitCheckout
Check out a specific commit.
CompactionBlock
Compaction content block (beta).
CompactionDelta
Delta for compaction content updates (beta).
CompactionInputBlock
Compaction block in input (beta).
CompletionRequest
Legacy completion request.
CompletionResponse
Legacy completion response.
ComputerUseTool
Computer use tool for GUI automation (Beta).
Container
Container information in response.
ContainerParams
Container configuration for code execution.
ContainerUploadBlock
Container upload content block.
ContainerUploadInputBlock
Container upload block in input.
ContentBlock
Content block in a response message.
ContentBlockDelta
Delta content for streaming content block updates.
ContentBlockDeltaEvent
Event indicating an update to a content block.
ContentBlockLocationCitation
Citation with content block location.
ContentBlockStartEvent
Event indicating the start of a content block.
ContentBlockStopEvent
Event indicating the end of a content block.
ContextManagementCapability
Context management capability details.
CreateAgentParams
Request parameters for creating an agent.
CreateCredentialParams
Request parameters for creating a credential.
CreateSessionParams
Request parameters for creating a session.
CreateVaultParams
Request parameters for creating a vault.
Credential
A credential stored in a vault.
CredentialAuth
Authentication details for a credential (response).
CredentialCreateAuth
Authentication details for creating a credential.
CredentialUpdateAuth
Updated authentication details for a credential.
CustomSkill
A resolved user-created custom skill.
CustomSkillParams
A user-created custom skill parameter.
CustomTool
A custom tool as returned in API responses.
CustomToolDefinition
A custom user-defined tool.
CustomToolInputSchema
JSON Schema for custom tool input parameters.
CustomToolParams
A custom tool parameter for create/update requests.
DeletedCredential
Confirmation of a deleted credential.
DeletedMessageBatch
Delete response for a message batch.
DeletedSession
Confirmation that a session has been permanently deleted.
DeletedSessionResource
Confirmation of resource deletion.
DeletedVault
Confirmation of a deleted vault.
DirectToolCaller
Direct model caller.
DocumentInputBlock
Document content block for input.
DocumentSource
Source for document content.
EffortCapability
Effort (reasoning_effort) capability details.
ErrorEvent
Error event during streaming.
EventParams
Union type for event parameters that can be sent to a session.
FileDeleteResponse
Response when a file is deleted.
FileListResponse
Response for listing files.
FileMetadata
Metadata for a file uploaded to Anthropic.
FileResource
A file resource attached to a session.
FileResourceParams
Mount a file uploaded via the Files API into the session.
FileScope
The scope of a file, indicating the context in which it was created.
FilesResource
Stub resource for the Files API (unsupported platforms).
GitHubRepositoryResource
A GitHub repository resource attached to a session.
GitHubRepositoryResourceParams
Mount a GitHub repository into the session's container.
ImageInputBlock
Image content block for input.
ImageSource
Source for image content.
InputContentBlock
Content block for input messages.
InputJsonDelta
Delta for input JSON content updates (tool use).
InputMessage
A message in the conversation input.
InputSchema
JSON Schema for tool input.
IterationUsage
Token usage for a single iteration (message or compaction).
JsonOutputFormat
JSON schema output format for structured outputs.
ListAgentsResponse
Paginated list of agents.
ListAgentVersionsResponse
Paginated list of agent versions.
ListCredentialsResponse
Response containing a paginated list of credentials.
ListSessionEventsResponse
Paginated list of session events.
ListSessionResourcesResponse
Paginated list of resources attached to a session.
ListSessionsResponse
Paginated list of sessions.
ListVaultsResponse
Response containing a paginated list of vaults.
McpAuthenticationFailedError
Authentication to an MCP server failed.
McpConnectionFailedError
Failed to connect to an MCP server.
McpOauthAuthResponse
OAuth credential details for an MCP server.
McpOauthCreateParams
Parameters for creating an MCP OAuth credential.
McpOauthRefreshParams
OAuth refresh token parameters for creating a credential with refresh support.
McpOauthRefreshResponse
OAuth refresh token configuration returned in credential responses.
McpOauthRefreshUpdateParams
Parameters for updating OAuth refresh token configuration.
McpOauthUpdateParams
Parameters for updating an MCP OAuth credential.
MCPServer
MCP server connection definition as returned in API responses.
MCPServerParams
MCP server connection parameter for create/update requests.
MCPServerURLDefinition
URL-based MCP server connection.
McpServerUrlDefinition
MCP server URL definition.
MCPToolConfig
Configuration for a specific MCP tool (response variant).
McpToolConfig
MCP tool configuration.
MCPToolConfigParams
Configuration override for a specific MCP tool (request variant).
MCPToolset
Configuration for tools from an MCP server (response variant).
McpToolset
MCP (Model Context Protocol) toolset configuration (Beta).
MCPToolsetDefaultConfig
Resolved default configuration for MCP toolset tools.
MCPToolsetDefaultConfigParams
Default configuration for MCP toolset tools (request variant).
MCPToolsetParams
Configuration for tools from an MCP server (request variant).
MemoryTool
Memory built-in tool.
Message
A message response from the API.
MessageBatch
A message batch object.
MessageBatchCreateRequest
Request for creating a message batch.
MessageBatchesResource
Resource for the Message Batches API.
MessageBatchListResponse
Response for listing message batches.
MessageContent
Content for an input message.
MessageCreateRequest
Request parameters for creating a message.
MessageDelta
Delta update for message properties during streaming.
MessageDeltaEvent
Event indicating an update to the message.
MessageDeltaUsage
Usage information in delta events.
MessagesResource
Resource for the Messages API.
MessageStartEvent
Event indicating the start of message generation.
MessageStopEvent
Event indicating the end of message generation.
MessageStreamAccumulator
Accumulates MessageStreamEvents into a complete Message.
MessageStreamEvent
Server-sent event for message streaming.
Metadata
Metadata about the request.
ModelCapabilities
Model capability information.
ModelConfig
Model identifier and configuration as returned in API responses.
ModelInfo
Information about an Anthropic model.
ModelListResponse
Response for listing models.
ModelOverloadedError
The model is currently overloaded.
ModelParams
Model parameter — either a simple model ID string or a ModelConfig.
ModelParamsConfig
A model configuration object with optional speed setting.
ModelParamsId
A plain model ID string.
ModelRateLimitedError
The model request was rate-limited.
ModelRequestFailedError
A model request failed for a reason other than overload or rate-limiting.
ModelsResource
Resource for the Models API.
NoAuthCredentials
No authentication credentials.
NoAuthProvider
Provider that returns no authentication credentials.
OutputConfig
Configuration for model output behavior.
PageLocationCitation
Citation with page location (for PDF sources).
PermissionPolicy
Permission policy for tool execution.
PingEvent
Ping event to keep connection alive.
PlainTextSource
Plain text document source.
RedactedThinkingBlock
Redacted thinking block (when thinking content is not available).
RefusalStopDetails
Structured information about why model output stopped due to a refusal.
RepositoryCheckout
Branch or commit checkout configuration.
RequestCitationsConfig
Citations configuration for web fetch tool output.
RequestCounts
Counts of requests in different states within a batch.
RequestMetadata
Metadata about the HTTP request that caused an error.
ResponseMetadata
Metadata about the HTTP response that caused an error.
RetryPolicy
Retry policy configuration.
RetryStatus
What the client should do next in response to a session error.
RetryStatusExhausted
The turn is dead; queued inputs are flushed.
RetryStatusRetrying
The server is retrying automatically.
RetryStatusTerminal
The session encountered a terminal error and will transition to terminated.
SendSessionEventsParams
Request parameters for sending events to a session.
SendSessionEventsResponse
Response for sending events to a session.
ServerToolCaller
Server-side caller (for code execution initiated calls).
ServerToolUsage
Server tool usage statistics.
ServerToolUseBlock
Server-side tool use block (e.g., web search).
ServerToolUseInputBlock
Server tool use block for assistant messages in input.
Session
A Managed Agents session.
SessionAgent
Resolved agent definition for a session — snapshot at session creation time.
SessionDeletedEvent
Session has been deleted.
SessionEndTurn
The agent completed its turn naturally.
SessionErrorEvent
An error event during session execution.
SessionEvent
Server-sent event in a managed agents session.
SessionEventsResource
Resource for session events (Beta).
SessionRequiresAction
The agent is idle waiting on blocking user-input events.
SessionResource
A resource attached to a session.
SessionResourceParams
Request parameters for adding a resource to a session.
SessionResourcesResource
Resource for session resources (Beta).
SessionRetriesExhausted
The turn ended because the retry budget was exhausted.
SessionsResource
Resource for the Sessions API (Beta).
SessionStats
Timing statistics for a session.
SessionStatusIdleEvent
Session is idle, awaiting user input.
SessionStatusRescheduledEvent
Session rescheduled after recovering from an error.
SessionStatusRunningEvent
Session is actively running and the agent is working.
SessionStatusTerminatedEvent
Session has terminated.
SessionStopReason
The reason the session transitioned to idle.
SessionUsage
Cumulative token usage for a session across all turns.
SignatureDelta
Delta for signature content updates (extended thinking verification).
Skill
A skill in the Anthropic API.
SkillListResponse
Response for listing skills.
SkillsResource
Resource for the Skills API.
SkillVersion
A version of a skill in the Anthropic API.
SkillVersionListResponse
Response for listing skill versions.
SpanModelRequestEndEvent
Model request completed.
SpanModelRequestStartEvent
Model request started.
SpanModelUsage
Token usage for a single model request.
SseParser
Parses Server-Sent Events (SSE) streams.
StaticBearerAuthResponse
Static bearer token credential details for an MCP server.
StaticBearerCreateParams
Parameters for creating a static bearer token credential.
StaticBearerUpdateParams
Parameters for updating a static bearer token credential.
SystemPrompt
System prompt content.
SystemTextBlock
Text block for system prompts.
TextBlock
Text content block in a response.
TextDelta
Delta for text content updates.
TextEditorCodeExecutionToolResultBlock
Text editor code execution tool result block.
TextEditorCodeExecutionToolResultInputBlock
Text-editor code execution tool result block in input.
TextEditorTool
Text editor tool (version 2025-07-28, latest).
TextEditorTool20250124
Text editor tool (version 2025-01-24).
TextEditorTool20250429
Text editor tool (version 2025-04-29).
TextEditorToolBase
Base class for text editor tool versions.
TextInputBlock
Text content block for input.
TextMessageContent
Text content for a message.
TextSystemPrompt
Text system prompt.
ThinkingAdaptive
Enables adaptive thinking where budget is determined by the model.
ThinkingBlock
Thinking (reasoning) content block in a response.
ThinkingCapability
Thinking capability details.
ThinkingConfig
Configuration for extended thinking mode.
ThinkingDelta
Delta for thinking content updates.
ThinkingDisabled
Disables extended thinking.
ThinkingEnabled
Enables extended thinking with a token budget.
ThinkingTypes
Supported thinking type configurations.
TokenCountRequest
Request for counting tokens.
TokenCountResponse
Response for token counting.
TokenEndpointAuthBasicParam
Token endpoint uses HTTP Basic authentication with client credentials.
TokenEndpointAuthBasicResponse
Token endpoint uses HTTP Basic authentication with client credentials.
TokenEndpointAuthBasicUpdateParam
Updated HTTP Basic authentication parameters for the token endpoint.
TokenEndpointAuthNoneParam
Token endpoint requires no client authentication.
TokenEndpointAuthNoneResponse
Token endpoint requires no client authentication.
TokenEndpointAuthParam
Token endpoint authentication method (create params).
TokenEndpointAuthPostParam
Token endpoint uses POST body authentication with client credentials.
TokenEndpointAuthPostResponse
Token endpoint uses POST body authentication with client credentials.
TokenEndpointAuthPostUpdateParam
Updated POST body authentication parameters for the token endpoint.
TokenEndpointAuthResponse
Token endpoint authentication method (response).
TokenEndpointAuthUpdateParam
Token endpoint authentication method (update params).
Tool
A tool that can be used by the model.
ToolCaller
Origin of a tool invocation/result.
ToolChoice
How the model should use the provided tools.
ToolChoiceAny
The model will use any available tools.
ToolChoiceAuto
The model will automatically decide whether to use tools.
ToolChoiceNone
The model will not be allowed to use tools.
ToolChoiceTool
The model will use the specified tool.
ToolDefinition
A tool definition that can be passed to the model.
ToolReferenceInputBlock
Tool reference block in input.
ToolResultContent
Content type for tool results.
ToolResultImageContent
Image content for tool results.
ToolResultInputBlock
Tool result block for user messages.
ToolResultTextContent
Text content for tool results.
ToolSearchTool
Base class for tool search built-ins.
ToolSearchToolBm25
BM25 tool search built-in.
ToolSearchToolRegex
Regex tool search built-in.
ToolSearchToolResultBlock
Tool search tool result block.
ToolSearchToolResultInputBlock
Tool-search tool result block in input.
ToolUseBlock
Tool use block in a response.
ToolUseInputBlock
Tool use block for assistant messages in input.
UnknownAgentSkill
Unrecognised skill type — preserves the raw JSON.
UnknownAgentSkillParams
Unrecognised skill params type — preserves the raw JSON.
UnknownAgentTool
Unrecognised agent tool type — preserves the raw JSON.
UnknownAgentToolParams
Unrecognised agent tool params type — preserves the raw JSON.
UnknownCredentialAuth
Unrecognized credential auth type (preserves raw JSON).
UnknownCredentialCreateAuth
Unrecognized credential create auth type (preserves raw JSON).
UnknownCredentialUpdateAuth
Unrecognized credential update auth type (preserves raw JSON).
UnknownEventParams
Unrecognized event params — preserves raw JSON.
UnknownManagedAgentError
An unknown managed agent error (preserves raw JSON).
UnknownMCPServer
Unrecognised MCP server type — preserves the raw JSON.
UnknownMCPServerParams
Unrecognised MCP server params type — preserves the raw JSON.
UnknownPermissionPolicy
Unrecognised permission policy — preserves the raw JSON.
UnknownRepositoryCheckout
Unrecognized repository checkout type (preserves raw JSON).
UnknownRetryStatus
Unrecognized retry status — preserves raw JSON.
UnknownSessionEvent
Unrecognized session event — preserves raw JSON.
UnknownSessionResource
Unrecognized session resource type (preserves raw JSON).
UnknownSessionResourceParams
Unrecognized session resource params type (preserves raw JSON).
UnknownSessionStopReason
Unrecognized stop reason — preserves raw JSON.
UnknownTokenEndpointAuthParam
Unrecognized token endpoint auth type (preserves raw JSON).
UnknownTokenEndpointAuthResponse
Unrecognized token endpoint auth type (preserves raw JSON).
UnknownTokenEndpointAuthUpdateParam
Unrecognized token endpoint auth update type (preserves raw JSON).
UpdateAgentParams
Request parameters for updating an agent.
UpdateCredentialParams
Request parameters for updating a credential.
UpdateSessionParams
Request parameters for updating a session.
UpdateSessionResourceParams
Request parameters for updating a session resource.
UpdateVaultParams
Request parameters for updating a vault.
UrlImageSource
URL-based image source.
URLMCPServerParams
URL-based MCP server connection parameters.
UrlPdfSource
URL-based PDF document source.
Usage
Token usage statistics for a request.
UserCustomToolResultEvent
Custom tool result event sent by the client.
UserCustomToolResultEventParams
Parameters for providing a custom tool execution result.
UserInterruptEvent
An interrupt event that pauses agent execution.
UserInterruptEventParams
Parameters for sending an interrupt.
UserLocation
User location for web search personalization.
UserMessageEvent
A user message event.
UserMessageEventParams
Parameters for sending a user message.
UserToolConfirmationEvent
A tool confirmation event that approves or denies a pending tool execution.
UserToolConfirmationEventParams
Parameters for confirming or denying a tool execution request.
Vault
A vault that stores credentials for use by agents during sessions.
VaultCredentialsResource
Resource for vault credentials (Beta).
VaultsResource
Resource for the Vaults API (Beta).
WebFetchTool
Web fetch built-in tool.
WebFetchToolResultBlock
Web fetch tool result block.
WebFetchToolResultInputBlock
Web fetch tool result block in input.
WebSearchResult
Web search result content.
WebSearchResultError
Web search error result.
WebSearchResultItem
A single web search result item.
WebSearchResultLocationCitation
Citation from web search result.
WebSearchResultSuccess
Successful web search result.
WebSearchTool
Web search tool for searching the internet.
WebSearchToolResultBlock
Web search tool result block.
WebSearchToolResultInputBlock
Web search tool result block in input.

Enums

AbortionStage
Stage at which request was aborted.
AgentEvaluatedPermission
Evaluated permission for agent tool invocations.
AgentSpeed
Inference speed mode for agents.
AgentToolName
Built-in agent tool identifier.
CacheTtl
Time-to-live values for cache control.
EffortLevel
Response effort level for model generation.
ImageMediaType
Supported image media types.
ListOrder
Sort order for paginated list operations.
MessageRole
Role of a message in a conversation.
ProcessingStatus
Processing status of a Message Batch.
RefusalCategory
Policy category that triggered a refusal.
ServiceTier
Service tier used for the request.
ServiceTierRequest
Service tier for request capacity (input).
ServiceTierResponse
Service tier used for the response (output).
SessionStatus
Session status.
SkillSource
Source of a skill in the Anthropic API.
Speed
Inference speed mode.
StopReason
Reason for the model to stop generating content.
ThinkingDisplayMode
Controls how thinking content appears in the response.
UserToolConfirmationResult
Confirmation result for tool execution.

Extensions

MessageExtensions on Message
Extensions on Message for convenient access to content.
MessageStreamExtension on Stream<MessageStreamEvent>
Convenience extensions on Stream<MessageStreamEvent>.
SseEventExtension on Map<String, dynamic>
Extension to handle SSE event types.

Exceptions / Errors

AbortedException
Exception thrown when a request is aborted by user.
AnthropicException
Base sealed class for all Anthropic exceptions.
ApiException
Exception for HTTP/API errors.
AuthenticationException
Exception for authentication errors (HTTP 401).
RateLimitException
Exception for rate limit (429) errors.
TimeoutException
Exception for request timeouts.
ValidationException
Exception for client-side validation errors.