use crate::types::{
Attachment, Content, ContentPart, Effort, Message, ModelSpec, Role, StopReason, ToolDefinition,
Usage, WebCitation, WebSearchResult, replay_safe_tool_args,
};
use anyhow::Result;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashSet;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct AnthropicMessage {
pub role: String,
pub content: AnthropicContent,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub(in crate::anthropic) enum AnthropicContent {
Text(String),
Blocks(Vec<ContentBlock>),
}
impl AnthropicContent {
pub(in crate::anthropic) fn as_text(&self) -> String {
match self {
Self::Text(text) => text.clone(),
Self::Blocks(blocks) => blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n"),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum ContentBlock {
Text {
text: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
citations: Vec<Citation>,
#[serde(skip_serializing_if = "Option::is_none")]
cache_control: Option<CacheControl>,
},
Image {
source: Source,
#[serde(skip_serializing_if = "Option::is_none")]
cache_control: Option<CacheControl>,
},
Document {
source: Source,
#[serde(skip_serializing_if = "Option::is_none")]
cache_control: Option<CacheControl>,
},
ToolUse {
id: String,
name: String,
input: serde_json::Value,
#[serde(skip_serializing_if = "Option::is_none")]
cache_control: Option<CacheControl>,
},
ToolResult {
tool_use_id: String,
content: AnthropicContent,
is_error: bool,
#[serde(skip_serializing_if = "Option::is_none")]
cache_control: Option<CacheControl>,
},
ServerToolUse {
id: String,
name: String,
input: serde_json::Value,
},
WebSearchToolResult {
tool_use_id: String,
content: WebSearchContent,
},
Thinking {
thinking: String,
#[serde(skip_serializing_if = "Option::is_none")]
signature: Option<String>,
},
RedactedThinking {
data: String,
},
#[serde(untagged)]
Unknown(serde_json::Value),
}
fn parse_payload<T, E>(payload: serde_json::Value) -> std::result::Result<T, E>
where
T: serde::de::DeserializeOwned,
E: serde::de::Error,
{
serde_json::from_value(payload).map_err(E::custom)
}
impl<'de> Deserialize<'de> for ContentBlock {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let payload = serde_json::Value::deserialize(deserializer)?;
match payload.get("type").and_then(serde_json::Value::as_str) {
Some("text") => {
#[derive(Deserialize)]
struct TextBlock {
text: String,
#[serde(default)]
citations: Vec<Citation>,
#[serde(default)]
cache_control: Option<CacheControl>,
}
let block: TextBlock = parse_payload(payload)?;
Ok(Self::Text {
text: block.text,
citations: block.citations,
cache_control: block.cache_control,
})
}
Some("image") => {
#[derive(Deserialize)]
struct ImageBlock {
source: Source,
#[serde(default)]
cache_control: Option<CacheControl>,
}
let block: ImageBlock = parse_payload(payload)?;
Ok(Self::Image { source: block.source, cache_control: block.cache_control })
}
Some("document") => {
#[derive(Deserialize)]
struct DocumentBlock {
source: Source,
#[serde(default)]
cache_control: Option<CacheControl>,
}
let block: DocumentBlock = parse_payload(payload)?;
Ok(Self::Document { source: block.source, cache_control: block.cache_control })
}
Some("tool_use") => {
#[derive(Deserialize)]
struct ToolUseBlock {
id: String,
name: String,
input: serde_json::Value,
#[serde(default)]
cache_control: Option<CacheControl>,
}
let block: ToolUseBlock = parse_payload(payload)?;
Ok(Self::ToolUse {
id: block.id,
name: block.name,
input: block.input,
cache_control: block.cache_control,
})
}
Some("tool_result") => {
#[derive(Deserialize)]
struct ToolResultBlock {
tool_use_id: String,
content: AnthropicContent,
is_error: bool,
#[serde(default)]
cache_control: Option<CacheControl>,
}
let block: ToolResultBlock = parse_payload(payload)?;
Ok(Self::ToolResult {
tool_use_id: block.tool_use_id,
content: block.content,
is_error: block.is_error,
cache_control: block.cache_control,
})
}
Some("server_tool_use") => {
#[derive(Deserialize)]
struct ServerToolUseBlock {
id: String,
name: String,
input: serde_json::Value,
}
let block: ServerToolUseBlock = parse_payload(payload)?;
Ok(Self::ServerToolUse { id: block.id, name: block.name, input: block.input })
}
Some("web_search_tool_result") => {
#[derive(Deserialize)]
struct WebSearchToolResultBlock {
tool_use_id: String,
content: WebSearchContent,
}
let block: WebSearchToolResultBlock = parse_payload(payload)?;
Ok(Self::WebSearchToolResult {
tool_use_id: block.tool_use_id,
content: block.content,
})
}
Some("thinking") => {
#[derive(Deserialize)]
struct ThinkingBlock {
thinking: String,
signature: Option<String>,
}
let block: ThinkingBlock = parse_payload(payload)?;
Ok(Self::Thinking { thinking: block.thinking, signature: block.signature })
}
Some("redacted_thinking") => {
#[derive(Deserialize)]
struct RedactedThinkingBlock {
data: String,
}
let block: RedactedThinkingBlock = parse_payload(payload)?;
Ok(Self::RedactedThinking { data: block.data })
}
_ => Ok(Self::Unknown(payload)),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct WebSearchResultContent {
#[serde(rename = "type")]
pub result_type: String,
pub title: String,
pub url: String,
#[serde(default)]
pub encrypted_content: String,
pub page_age: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub(in crate::anthropic) enum WebSearchContent {
Results(Vec<WebSearchResultContent>),
Error(WebSearchError),
Unknown(serde_json::Value), }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct WebSearchError {
#[serde(rename = "type")]
pub error_type: String,
pub error_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct Citation {
#[serde(rename = "type")]
pub citation_type: String,
pub url: String,
pub title: String,
#[serde(default)]
pub cited_text: String,
#[serde(default)]
pub encrypted_index: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub(in crate::anthropic) enum Source {
#[serde(rename = "url")]
Url { url: String },
#[serde(rename = "base64")]
Base64 { media_type: String, data: String },
}
impl From<&Attachment> for Source {
fn from(attachment: &Attachment) -> Self {
match attachment {
Attachment::Url { url } => Self::Url { url: url.clone() },
Attachment::Base64 { media_type, data } => {
Self::Base64 { media_type: media_type.clone(), data: data.clone() }
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum ThinkingConfig {
Enabled {
budget_tokens: u32,
#[serde(skip_serializing_if = "Option::is_none")]
display: Option<ThinkingDisplay>,
},
Disabled,
BetweenTools,
Adaptive {
#[serde(skip_serializing_if = "Option::is_none")]
display: Option<ThinkingDisplay>,
},
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(in crate::anthropic) enum ThinkingDisplay {
Summarized,
Omitted,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub(in crate::anthropic) enum OutputEffort {
Low,
Medium,
High,
#[serde(rename = "xhigh")]
XHigh,
Max,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct OutputConfig {
pub(in crate::anthropic) effort: OutputEffort,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum CacheControl {
Ephemeral {
#[serde(default, skip_serializing_if = "Option::is_none")]
ttl: Option<Ttl>,
},
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub(in crate::anthropic) enum Ttl {
#[serde(rename = "1h")]
Hour,
}
#[derive(Debug, Deserialize)]
pub(in crate::anthropic) struct ListModelsResponse {
pub data: Vec<AnthropicModel>,
}
#[derive(Debug, Deserialize)]
pub(in crate::anthropic) struct AnthropicModel {
id: String,
#[serde(default, alias = "name")]
display_name: Option<String>,
#[serde(default)]
max_input_tokens: Option<u32>,
#[serde(default)]
max_tokens: Option<u32>,
#[serde(default)]
capabilities: Option<AnthropicModelCapabilities>,
}
#[derive(Debug, Deserialize)]
struct AnthropicModelCapabilities {
#[serde(default)]
image_input: Option<CapabilitySupport>,
#[serde(default)]
thinking: Option<CapabilitySupport>,
}
#[derive(Debug, Deserialize)]
struct CapabilitySupport {
supported: bool,
}
impl From<AnthropicModel> for ModelSpec {
fn from(model: AnthropicModel) -> Self {
let support_vision = model
.capabilities
.as_ref()
.and_then(|capabilities| capabilities.image_input.as_ref())
.map(|capability| capability.supported);
let effort = model
.capabilities
.as_ref()
.and_then(|capabilities| capabilities.thinking.as_ref())
.and_then(|capability| capability.supported.then_some(Effort::Medium));
ModelSpec {
id: model.id,
display_name: model.display_name,
max_tokens: model.max_tokens,
context_limit: model.max_input_tokens,
effort,
support_vision,
..Default::default()
}
}
}
#[derive(Debug, Clone, Serialize)]
pub(in crate::anthropic) struct SystemBlock {
#[serde(rename = "type")]
pub block_type: String,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub cache_control: Option<CacheControl>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub(in crate::anthropic) struct MessageRequest {
pub model: String,
pub max_tokens: u32,
pub messages: Vec<AnthropicMessage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub system: Option<Vec<SystemBlock>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<Vec<AnthropicTool>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_choice: Option<AnthropicToolChoice>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stream: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thinking: Option<ThinkingConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop_sequences: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_config: Option<OutputConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cache_control: Option<CacheControl>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum AnthropicToolChoice {
Any,
Tool { name: String },
None,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub(in crate::anthropic) enum AnthropicTool {
Function {
#[serde(flatten)]
definition: ToolDefinition,
#[serde(skip_serializing_if = "Option::is_none")]
cache_control: Option<CacheControl>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
eager_input_streaming: bool,
},
ServerTool(ServerTool),
}
#[derive(Debug, Clone, Serialize)]
pub(in crate::anthropic) struct ServerTool {
#[serde(rename = "type")]
pub tool_type: String,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_uses: Option<u32>,
}
#[derive(Debug, Deserialize)]
pub(in crate::anthropic) struct MessageResponse {
pub content: Vec<ContentBlock>,
pub stop_reason: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, Deserialize)]
pub(in crate::anthropic) struct AnthropicUsageDelta {
pub input_tokens: Option<u32>,
pub output_tokens: Option<u32>,
pub cache_creation_input_tokens: Option<u32>,
pub cache_read_input_tokens: Option<u32>,
}
impl AnthropicUsageDelta {
pub(in crate::anthropic) fn patch(&mut self, later: AnthropicUsageDelta) {
self.input_tokens = later.input_tokens.or(self.input_tokens);
self.output_tokens = later.output_tokens.or(self.output_tokens);
self.cache_creation_input_tokens =
later.cache_creation_input_tokens.or(self.cache_creation_input_tokens);
self.cache_read_input_tokens =
later.cache_read_input_tokens.or(self.cache_read_input_tokens);
}
}
impl From<AnthropicUsageDelta> for Usage {
fn from(usage: AnthropicUsageDelta) -> Self {
let cache_write_tokens = usage.cache_creation_input_tokens;
let cache_read_tokens = usage.cache_read_input_tokens;
Usage {
input_tokens: usage
.input_tokens
.unwrap_or_default()
.saturating_add(cache_write_tokens.unwrap_or_default())
.saturating_add(cache_read_tokens.unwrap_or_default()),
output_tokens: usage.output_tokens.unwrap_or_default(),
cache_read_tokens,
cache_write_tokens,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub(in crate::anthropic) struct AnthropicStreamMessage {
#[serde(default)]
pub usage: AnthropicUsageDelta,
}
#[derive(Debug, Clone)]
pub(in crate::anthropic) enum AnthropicStreamEvent {
MessageStart { message: AnthropicStreamMessage },
ContentBlockStart { index: u32, content_block: ContentBlock },
ContentBlockDelta { index: u32, delta: AnthropicDelta },
ContentBlockStop { index: u32 },
MessageDelta { delta: AnthropicMessageDelta, usage: AnthropicUsageDelta },
MessageStop,
Ping,
Error { error: AnthropicError },
Unknown { event_type: Option<String>, payload: serde_json::Value },
}
impl<'de> Deserialize<'de> for AnthropicStreamEvent {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let payload = serde_json::Value::deserialize(deserializer)?;
let event_type =
payload.get("type").and_then(serde_json::Value::as_str).map(str::to_string);
match event_type.as_deref() {
Some("message_start") => {
#[derive(Deserialize)]
struct MessageStartEvent {
message: AnthropicStreamMessage,
}
let event: MessageStartEvent = parse_payload(payload)?;
Ok(Self::MessageStart { message: event.message })
}
Some("content_block_start") => {
#[derive(Deserialize)]
struct ContentBlockStartEvent {
index: u32,
content_block: ContentBlock,
}
let event: ContentBlockStartEvent = parse_payload(payload)?;
Ok(Self::ContentBlockStart {
index: event.index,
content_block: event.content_block,
})
}
Some("content_block_delta") => {
#[derive(Deserialize)]
struct ContentBlockDeltaEvent {
index: u32,
delta: AnthropicDelta,
}
let event: ContentBlockDeltaEvent = parse_payload(payload)?;
Ok(Self::ContentBlockDelta { index: event.index, delta: event.delta })
}
Some("content_block_stop") => {
#[derive(Deserialize)]
struct ContentBlockStopEvent {
index: u32,
}
let event: ContentBlockStopEvent = parse_payload(payload)?;
Ok(Self::ContentBlockStop { index: event.index })
}
Some("message_delta") => {
#[derive(Deserialize)]
struct MessageDeltaEvent {
delta: AnthropicMessageDelta,
#[serde(default)]
usage: AnthropicUsageDelta,
}
let event: MessageDeltaEvent = parse_payload(payload)?;
Ok(Self::MessageDelta { delta: event.delta, usage: event.usage })
}
Some("message_stop") => Ok(Self::MessageStop),
Some("ping") => Ok(Self::Ping),
Some("error") => {
#[derive(Deserialize)]
struct ErrorEvent {
error: AnthropicError,
}
let event: ErrorEvent = parse_payload(payload)?;
Ok(Self::Error { error: event.error })
}
_ => Ok(Self::Unknown { event_type, payload }),
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub(in crate::anthropic) struct AnthropicError {
#[serde(rename = "type")]
pub error_type: String,
pub message: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum AnthropicDelta {
TextDelta {
text: String,
},
InputJsonDelta {
partial_json: String,
},
ThinkingDelta {
thinking: String,
},
SignatureDelta {
signature: String,
},
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Deserialize)]
pub(in crate::anthropic) struct AnthropicMessageDelta {
pub stop_reason: Option<String>,
}
impl TryFrom<&Content> for AnthropicContent {
type Error = anyhow::Error;
fn try_from(content: &Content) -> Result<Self> {
match content {
Content::Text(text) => Ok(AnthropicContent::Text(text.clone())),
Content::Parts(parts) => Ok(AnthropicContent::Blocks(
parts
.iter()
.filter(|p| !matches!(p, ContentPart::Thinking { signature: None, .. }))
.map(ContentBlock::try_from)
.collect::<Result<Vec<_>>>()?,
)),
}
}
}
impl TryFrom<&ContentPart> for ContentBlock {
type Error = anyhow::Error;
fn try_from(content: &ContentPart) -> Result<Self> {
match content {
ContentPart::Text(text) => Ok(ContentBlock::Text {
text: text.clone(),
citations: vec![],
cache_control: None,
}),
ContentPart::Image(image) => {
Ok(ContentBlock::Image { source: image.into(), cache_control: None })
}
ContentPart::Document(document) => {
Ok(ContentBlock::Document { source: document.into(), cache_control: None })
}
ContentPart::Thinking { text, signature } => {
Ok(ContentBlock::Thinking { thinking: text.clone(), signature: signature.clone() })
}
ContentPart::RedactedThinking { data } => {
Ok(ContentBlock::RedactedThinking { data: data.clone() })
}
ContentPart::ToolUse(tool_use) => Ok(ContentBlock::ToolUse {
id: wire_tool_id(&tool_use.id),
name: tool_use.name.clone(),
input: replay_safe_tool_args(tool_use).into_owned(),
cache_control: None,
}),
ContentPart::ToolResult(tool_result) => Ok(ContentBlock::ToolResult {
tool_use_id: wire_tool_id(&tool_result.tool_use_id),
content: AnthropicContent::try_from(&tool_result.content)?,
is_error: tool_result.is_error,
cache_control: None,
}),
}
}
}
fn wire_tool_id(id: &str) -> String {
use sha2::{Digest, Sha256};
let valid = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
if !id.is_empty() && id.chars().all(valid) {
return id.to_string();
}
let cleaned: String = id.chars().map(|c| if valid(c) { c } else { '_' }).collect();
let digest = Sha256::digest(id.as_bytes());
let hash: String = digest[..4].iter().map(|byte| format!("{byte:02x}")).collect();
format!("{cleaned}_{hash}")
}
impl AnthropicMessage {
pub(in crate::anthropic) fn is_content_empty(&self) -> bool {
matches!(&self.content, AnthropicContent::Blocks(blocks) if blocks.is_empty())
}
}
impl TryFrom<&Message> for AnthropicMessage {
type Error = anyhow::Error;
fn try_from(message: &Message) -> Result<Self> {
Ok(AnthropicMessage {
role: match &message.role {
Role::User => "user".to_string(),
Role::Model => "assistant".to_string(),
Role::System => "system".to_string(),
Role::Custom(role) => role.clone(),
},
content: AnthropicContent::try_from(&message.content)?,
})
}
}
impl TryFrom<MessageResponse> for WebSearchResult {
type Error = anyhow::Error;
fn try_from(response: MessageResponse) -> Result<Self> {
let mut text_parts: Vec<String> = Vec::new();
let mut citations: Vec<WebCitation> = Vec::new();
let mut seen_urls: HashSet<String> = HashSet::new();
for block in response.content {
match block {
ContentBlock::Text { text, citations: block_citations, .. } => {
if !text.is_empty() {
text_parts.push(text);
}
for citation in block_citations {
if seen_urls.insert(citation.url.clone()) {
citations
.push(WebCitation { title: citation.title, uri: citation.url });
}
}
}
ContentBlock::WebSearchToolResult { content, .. } => match content {
WebSearchContent::Results(results) => {
for result in results {
if seen_urls.insert(result.url.clone()) {
citations
.push(WebCitation { title: result.title, uri: result.url });
}
}
}
WebSearchContent::Error(error) => {
anyhow::bail!(
"Web search failed: {} ({})",
error.error_code,
error.error_type
);
}
WebSearchContent::Unknown(value) => {
anyhow::bail!(
"Web search returned unexpected format: {}",
serde_json::to_string(&value).unwrap_or_default()
);
}
},
_ => {}
}
}
let content = Content::Text(text_parts.join("\n"));
Ok(WebSearchResult { content, citations })
}
}
pub(in crate::anthropic) fn stop_reason(value: &str) -> StopReason {
match value {
"end_turn" => StopReason::EndTurn,
"max_tokens" => StopReason::MaxTokens,
"refusal" => StopReason::Refusal,
other => StopReason::Other(other.to_string()),
}
}