Forge documentation
Library referenceRust

forge-provider-anthropic

Anthropic provider for the Forge SDK — implements the LanguageModel trait for the Anthropic Messages API

Anthropic provider for the Forge SDK — implements the LanguageModel trait for the Anthropic Messages API

Package contract

FieldValue
Languagerust
Source version0.2.0
Manifestforge-rs/crates/forge-provider-anthropic/Cargo.toml
Source files7
EvidenceSource reference; registry publication and runtime conformance are separate checks

Import boundary

use forge_provider_anthropic;

Use a source checkout or your verified private registry. Manifest coordinates identify the package; they do not establish that a public registry release exists.

Crate boundary

The following entries are taken from src/lib.rs. Feature conditions in the exact source still apply.

#[cfg(not(target_arch = "wasm32"))]
pub mod client;

#[cfg(not(target_arch = "wasm32"))]
pub mod config;

pub mod error;

#[cfg(not(target_arch = "wasm32"))]
pub mod model;

#[cfg(not(target_arch = "wasm32"))]
pub mod sse;

pub mod types;

#[cfg(not(target_arch = "wasm32"))]
pub use config::AnthropicConfig;

pub use error::AnthropicError;

#[cfg(not(target_arch = "wasm32"))]
pub use model::AnthropicLanguageModel;

Source reference

Download package reference JSON. Each original source file and generated declaration artifact has its own SHA-256 digest. Function bodies and constant values are omitted from downloads. These are source declaration inventories, not compiler-resolved rustdoc, TypeDoc, DocC, or Dokka output. Private modules can contain public declarations that are not reachable through the package boundary; consult the entry point before importing.

client.rs

Read declaration text · 5 declaration entries

pub struct AnthropicHttpClient {

}

pub fn new(config: &AnthropicConfig) -> Result<Self, AnthropicError>;

pub async fn send_messages(
        &self,
        request: &MessagesRequest,
    ) -> Result<MessagesResponse, AnthropicError>;

pub async fn send_streaming(
        &self,
        request: &MessagesRequest,
    ) -> Result<Vec<u8>, AnthropicError>;

pub async fn send_streaming_body(
        &self,
        request: &MessagesRequest,
    ) -> Result<Incoming, AnthropicError>;

config.rs

Read declaration text · 16 declaration entries

pub const DEFAULT_MAX_TOKENS: u32;

#[derive(Clone)]
pub struct AnthropicConfig {

}

pub fn new(api_key: impl Into<String>) -> Self;

pub fn no_credentials() -> Self;

pub fn has_credentials(&self) -> bool;

pub fn with_model(mut self, model: impl Into<String>) -> Self;

pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self;

pub fn with_api_version(mut self, version: impl Into<String>) -> Self;

pub fn with_timeout_seconds(mut self, seconds: u64) -> Self;

pub fn with_max_retries(mut self, retries: u32) -> Self;

pub fn api_key(&self) -> &str;

pub fn model(&self) -> &str;

pub fn base_url(&self) -> &str;

pub fn api_version(&self) -> &str;

pub fn timeout_seconds(&self) -> u64;

pub fn max_retries(&self) -> u32;

error.rs

Read declaration text · 1 declaration entries

#[derive(Debug, Error)]
pub enum AnthropicError {
    /// The API returned an HTTP error status code.
    ///
    /// Anthropic returns structured error bodies; the `error_type` and `message`
    /// fields come from the API response.
    #[error(
        "Anthropic API returned HTTP {status_code}: type='{error_type}', message='{message}' \
         (model='{model}', request_id='{request_id}')"
    )]
    ApiError {
        /// The HTTP status code (e.g., 400, 401, 429, 500).
        status_code: u16,
        /// The Anthropic error type (e.g., "invalid_request_error", "authentication_error").
        error_type: String,
        /// Human-readable error message from the API.
        message: String,
        /// The model that was being called.
        model: String,
        /// The request ID from the `request-id` response header, or "unknown".
        request_id: String,
    },

    /// An HTTP transport error occurred (DNS failure, connection reset, TLS error).
    #[error("HTTP transport error calling Anthropic API at '{url}': {reason}")]
    HttpTransport {
        /// The URL that was being called.
        url: String,
        /// Description of the transport failure.
        reason: String,
    },

    /// The API response body could not be deserialized.
    #[error(
        "failed to deserialize Anthropic API response for model '{model}': {reason} \
         (response snippet: '{snippet}')"
    )]
    DeserializationFailed {
        /// The model that produced the response.
        model: String,
        /// What went wrong during deserialization.
        reason: String,
        /// First 200 bytes of the response body for debugging.
        snippet: String,
    },

    /// Request serialization failed.
    #[error("failed to serialize request for Anthropic model '{model}': {reason}")]
    SerializationFailed {
        /// The model the request was for.
        model: String,
        /// What went wrong during serialization.
        reason: String,
    },

    /// An SSE stream event could not be parsed.
    #[error("SSE parse error on event '{event_type}': {reason} (data snippet: '{snippet}')")]
    SseParseFailed {
        /// The SSE event type (e.g., "content_block_delta").
        event_type: String,
        /// What went wrong.
        reason: String,
        /// First 200 bytes of the data field for debugging.
        snippet: String,
    },

    /// The request timed out.
    #[error(
        "Anthropic API request timed out after {timeout_seconds}s for model '{model}' \
         — consider increasing timeout or reducing max_tokens"
    )]
    Timeout {
        /// The model being called.
        model: String,
        /// The timeout that was exceeded, in seconds.
        timeout_seconds: u64,
    },

    /// All retry attempts were exhausted.
    #[error(
        "Anthropic API request failed after {attempts} attempts for model '{model}': {last_error}"
    )]
    RetriesExhausted {
        /// The model being called.
        model: String,
        /// How many attempts were made.
        attempts: u32,
        /// The last error message.
        last_error: String,
    },

    /// The configuration is invalid.
    #[error("invalid Anthropic configuration: {reason}")]
    InvalidConfig {
        /// What is wrong with the configuration.
        reason: String,
    },
}

lib.rs

Read declaration text · 9 declaration entries

#[cfg(not(target_arch = "wasm32"))]
pub mod client;

#[cfg(not(target_arch = "wasm32"))]
pub mod config;

pub mod error;

#[cfg(not(target_arch = "wasm32"))]
pub mod model;

#[cfg(not(target_arch = "wasm32"))]
pub mod sse;

pub mod types;

#[cfg(not(target_arch = "wasm32"))]
pub use config::AnthropicConfig;

pub use error::AnthropicError;

#[cfg(not(target_arch = "wasm32"))]
pub use model::AnthropicLanguageModel;

model.rs

Read declaration text · 3 declaration entries

pub struct AnthropicLanguageModel {

}

pub fn new(config: AnthropicConfig) -> Result<Self, AnthropicError>;

pub fn convert_tool_definition(tool: &ToolDefinition) -> AnthropicToolDef;

sse.rs

Read declaration text · 10 declaration entries

#[derive(Debug, Clone)]
pub enum AnthropicSseEvent {
    /// Stream started with message metadata.
    MessageStart {
        /// Input token count from the initial message.
        input_tokens: u64,
    },
    /// A new content block started.
    ContentBlockStart {
        /// Zero-based index of this block.
        index: u32,
        /// The initial content block.
        block: ContentBlock,
    },
    /// Incremental update to the current content block.
    ContentBlockDelta {
        /// Zero-based index of the block being updated.
        index: u32,
        /// The delta update.
        delta: DeltaBlock,
    },
    /// A content block finished.
    ContentBlockStop {
        /// Zero-based index of the completed block.
        index: u32,
    },
    /// Stream metadata update (stop reason, output usage).
    MessageDelta {
        /// Why generation stopped.
        stop_reason: Option<String>,
        /// Output tokens generated.
        output_tokens: Option<u64>,
    },
    /// Stream completed.
    MessageStop,
    /// Keepalive ping (ignored by consumers).
    Ping,
}

pub fn parse_sse_stream(sse_bytes: &[u8]) -> Result<Vec<StreamChunk>, AnthropicError>;

pub struct SseDecoder {

}

pub fn new() -> Self;

pub fn feed(&mut self, bytes: &[u8]) -> Result<(), AnthropicError>;

pub fn drain(&mut self) -> Vec<AnthropicSseEvent>;

pub fn finish(&mut self) -> Result<Vec<AnthropicSseEvent>, AnthropicError>;

pub struct ChunkEmitter {

}

pub fn new() -> Self;

pub fn emit(&mut self, event: AnthropicSseEvent) -> Vec<StreamChunk>;

types.rs

Read declaration text · 16 declaration entries

#[derive(Debug, Clone, Serialize)]
pub struct MessagesRequest {
/// The model to use (e.g., "claude-sonnet-4-5-20250929").

pub model: String,
/// The conversation messages. Must not contain system messages; use

/// the `system` field instead.

pub messages: Vec<AnthropicMessage>,
/// Top-level system prompt. Anthropic does not use a system role in

/// the messages array.

#[serde(skip_serializing_if = "Option::is_none")]
pub system: Option<String>,
/// Maximum tokens to generate. Required by the Anthropic API.

pub max_tokens: u32,
/// Tool definitions available to the model.

#[serde(skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<AnthropicToolDef>,
/// Sampling temperature (0.0..1.0).

#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
/// Top-p (nucleus) sampling threshold.

#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>,
/// Stop sequences.

#[serde(skip_serializing_if = "Option::is_none")]
pub stop_sequences: Option<Vec<String>>,
/// Whether to stream the response via SSE.

#[serde(skip_serializing_if = "Option::is_none")]
pub stream: Option<bool>
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnthropicMessage {
/// The message role: "user" or "assistant".

pub role: String,
/// Content blocks making up the message.

pub content: Vec<ContentBlock>
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// A text content block.
    Text {
        /// The text content.
        text: String,
    },

    /// A tool use (tool call) content block — returned by the model.
    ToolUse {
        /// Unique identifier for this tool use.
        id: String,
        /// The tool name.
        name: String,
        /// The input arguments as a JSON object.
        input: serde_json::Value,
    },

    /// A tool result content block — sent by the client after executing a tool.
    ToolResult {
        /// The `tool_use` ID this result corresponds to.
        tool_use_id: String,
        /// The result content.
        content: String,
        /// Whether the tool execution resulted in an error.
        #[serde(skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,
    },

    /// An image content block.
    Image {
        /// The image source.
        source: ImageSource,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageSource {
/// The source type — always "base64" for inline images.

#[serde(rename = "type")]
pub source_type: String,
/// The MIME type (e.g., "image/png", "image/jpeg").

pub media_type: String,
/// The base64-encoded image data.

pub data: String
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnthropicToolDef {
/// The tool name.

pub name: String,
/// Human-readable description.

pub description: String,
/// JSON Schema for the tool's input parameters.

pub input_schema: serde_json::Value
}

#[derive(Debug, Clone, Deserialize)]
pub struct MessagesResponse {
/// Unique message identifier (e.g., "msg_01XFDUDYJgAACzvnptvVoYEL").

pub id: String,
/// Object type — always "message".

#[serde(rename = "type")]
pub object_type: String,
/// The role — always "assistant" for responses.

pub role: String,
/// The response content blocks (text, tool_use).

pub content: Vec<ContentBlock>,
/// The model that generated the response.

pub model: String,
/// Why generation stopped: "end_turn", "max_tokens", "tool_use", "stop_sequence".

pub stop_reason: Option<String>,
/// Token usage statistics.

pub usage: AnthropicUsage
}

#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
pub struct AnthropicUsage {
/// Number of input (prompt) tokens.

pub input_tokens: u64,
/// Number of output (completion) tokens.

pub output_tokens: u64
}

#[derive(Debug, Clone, Deserialize)]
pub struct AnthropicApiErrorResponse {
/// The error type (e.g., "invalid_request_error").

#[serde(rename = "type")]
pub error_type: String,
/// The error details.

pub error: AnthropicApiErrorDetail
}

#[derive(Debug, Clone, Deserialize)]
pub struct AnthropicApiErrorDetail {
/// The error type (e.g., "invalid_request_error").

#[serde(rename = "type")]
pub error_type: String,
/// Human-readable error message.

pub message: String
}

#[derive(Debug, Clone, Deserialize)]
pub struct MessageStartEvent {
/// The message response metadata.

pub message: MessagesResponse
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContentBlockStartEvent {
/// The zero-based index of this content block.

pub index: u32,
/// The initial content block (may have empty text or partial tool_use).

pub content_block: ContentBlock
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContentBlockDeltaEvent {
/// The zero-based index of the content block being updated.

pub index: u32,
/// The delta update.

pub delta: DeltaBlock
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DeltaBlock {
    /// Incremental text content.
    TextDelta {
        /// The text fragment.
        text: String,
    },
    /// Incremental JSON for tool use input.
    InputJsonDelta {
        /// A fragment of the JSON input string.
        partial_json: String,
    },
}

#[derive(Debug, Clone, Deserialize)]
pub struct MessageDeltaEvent {
/// The delta with the stop reason.

pub delta: MessageDelta,
/// Updated usage statistics.

pub usage: Option<MessageDeltaUsage>
}

#[derive(Debug, Clone, Deserialize)]
pub struct MessageDelta {
/// Why generation stopped: "end_turn", "max_tokens", "tool_use", "stop_sequence".

pub stop_reason: Option<String>
}

#[derive(Debug, Clone, Copy, Deserialize)]
pub struct MessageDeltaUsage {
/// The output tokens generated so far.

pub output_tokens: u64
}

Continue

On this page