use super::error::ConversionError;
use crate::attachment;
use adk_anthropic::ImageMediaType;
use adk_anthropic::{
Base64ImageSource, Base64PdfSource, CacheControlEphemeral, CacheTtl, ContentBlock,
ContextManagement, DocumentBlock, ImageBlock, Message, MessageCreateParams, MessageParam,
MessageRole, Model, PlainTextSource, StopReason, SystemPrompt, TextBlock, ThinkingBlock,
ToolParam, ToolResultBlock, ToolResultBlockContent, ToolUnionParam, UrlImageSource,
UrlPdfSource,
};
use adk_core::{
BuiltinToolUse, Content, FinishReason, LlmResponse, Part, SchemaAdapter, SchemaCache,
UsageMetadata,
};
use serde_json::Value;
use std::collections::HashMap;
use super::toolsets::{self, ToolsetForms};
fn image_media_type(mime_type: &str) -> Option<ImageMediaType> {
match mime_type {
"image/jpeg" => Some(ImageMediaType::Jpeg),
"image/png" => Some(ImageMediaType::Png),
"image/gif" => Some(ImageMediaType::Gif),
"image/webp" => Some(ImageMediaType::Webp),
_ => None,
}
}
fn tool_result_content(response: &adk_core::FunctionResponseData) -> ToolResultBlockContent {
let text = match &response.response {
Value::String(text) => text.clone(),
Value::Object(_) | Value::Array(_) => {
serde_json::to_string(&response.response).unwrap_or_default()
}
other => other.to_string(),
};
if response.inline_data.is_empty() && response.file_data.is_empty() {
return ToolResultBlockContent::String(text);
}
let mut items = Vec::new();
if !text.trim().is_empty() {
items.push(adk_anthropic::Content::Text(TextBlock::new(text)));
}
for data in &response.inline_data {
items.push(match image_media_type(&data.mime_type) {
Some(media_type) => adk_anthropic::Content::Image(ImageBlock::new_with_base64(
Base64ImageSource::new(attachment::encode_base64(&data.data), media_type),
)),
None => adk_anthropic::Content::Text(TextBlock::new(
attachment::inline_attachment_to_text(&data.mime_type, &data.data),
)),
});
}
for file in &response.file_data {
items.push(match image_media_type(&file.mime_type) {
Some(_) => adk_anthropic::Content::Image(ImageBlock::new_with_url(
UrlImageSource::new(file.file_uri.clone()),
)),
None => adk_anthropic::Content::Text(TextBlock::new(
attachment::file_attachment_to_text(&file.mime_type, &file.file_uri),
)),
});
}
ToolResultBlockContent::Array(items)
}
pub fn content_to_message(
content: &Content,
_prompt_caching: bool,
forms: ToolsetForms,
) -> Result<MessageParam, ConversionError> {
let role = match content.role.as_str() {
"user" | "function" | "tool" => MessageRole::User,
"model" | "assistant" => MessageRole::Assistant,
_ => MessageRole::User,
};
if let Some(mut blocks) = super::history::restore(content, forms) {
blocks.retain(
|block| !matches!(block, ContentBlock::Text(text) if text.text.trim().is_empty()),
);
return Ok(MessageParam::new_with_blocks(blocks, role));
}
let blocks: Vec<ContentBlock> = content
.parts
.iter()
.filter_map(|part| match part {
Part::Text { text } => {
if text.trim().is_empty() {
None
} else {
Some(ContentBlock::Text(TextBlock::new(text.clone())))
}
}
Part::FunctionCall { name, args, id, .. } => {
let id = id.clone().unwrap_or_else(|| format!("call_{name}"));
Some(ContentBlock::ToolUse(toolsets::tool_use_from_call(id, name, args, forms)))
}
Part::FunctionResponse { function_response, id, .. } => {
let is_error =
part.tool_result_status().is_some_and(adk_core::ToolResultStatus::is_error);
let toolset = toolsets::result_toolset(&function_response.name, forms);
let content = match toolset {
Some(toolset) => {
toolsets::member_result_content(function_response, toolset, is_error)
}
None => tool_result_content(function_response),
};
Some(ContentBlock::ToolResult(ToolResultBlock {
tool_use_id: id.clone().unwrap_or_else(|| "unknown".to_string()),
content: Some(content),
is_error: is_error.then_some(true),
cache_control: None,
toolset_name: toolset.map(str::to_string),
}))
}
Part::InlineData { mime_type, data, .. } => {
if let Some(media_type) = image_media_type(mime_type) {
let encoded = attachment::encode_base64(data);
Some(ContentBlock::Image(ImageBlock::new_with_base64(Base64ImageSource::new(
encoded, media_type,
))))
} else if mime_type == "application/pdf" {
let encoded = attachment::encode_base64(data);
Some(ContentBlock::Document(DocumentBlock::new_with_base64_pdf(
Base64PdfSource::new(encoded),
)))
} else if mime_type.starts_with("text/") {
match String::from_utf8(data.clone()) {
Ok(text) => Some(ContentBlock::Document(
DocumentBlock::new_with_plain_text(PlainTextSource::new(text)),
)),
Err(_) => Some(ContentBlock::Text(TextBlock::new(
attachment::inline_attachment_to_text(mime_type, data),
))),
}
} else {
Some(ContentBlock::Text(TextBlock::new(attachment::inline_attachment_to_text(
mime_type, data,
))))
}
}
Part::FileData { mime_type, file_uri, .. } => {
if mime_type == "application/pdf" {
Some(ContentBlock::Document(DocumentBlock::new_with_url_pdf(
UrlPdfSource::new(file_uri.clone()),
)))
} else if matches!(
mime_type.as_str(),
"image/jpeg" | "image/png" | "image/gif" | "image/webp"
) {
Some(ContentBlock::Image(ImageBlock::new_with_url(UrlImageSource::new(
file_uri.clone(),
))))
} else {
Some(ContentBlock::Text(TextBlock::new(attachment::file_attachment_to_text(
mime_type, file_uri,
))))
}
}
Part::Thinking { thinking, signature: Some(signature) }
if role == MessageRole::Assistant && !signature.is_empty() =>
{
Some(ContentBlock::Thinking(ThinkingBlock::new(
thinking.clone(),
signature.clone(),
)))
}
Part::Thinking { .. } => None,
Part::ServerToolCall { server_tool_call } if role == MessageRole::Assistant => {
serde_json::from_value::<adk_anthropic::ServerToolUseBlock>(
server_tool_call.clone(),
)
.ok()
.map(ContentBlock::ServerToolUse)
}
Part::ServerToolResponse { server_tool_response } if role == MessageRole::Assistant => {
serde_json::from_value::<ContentBlock>(server_tool_response.clone()).ok().filter(
|block| {
matches!(
block,
ContentBlock::WebSearchToolResult(_)
| ContentBlock::WebFetchToolResult(_)
| ContentBlock::CodeExecutionToolResult(_)
| ContentBlock::BashCodeExecutionToolResult(_)
| ContentBlock::TextEditorCodeExecutionToolResult(_)
)
},
)
}
Part::ServerToolCall { .. } | Part::ServerToolResponse { .. } => None,
Part::EmbeddedResource { resource } => match resource {
adk_core::EmbeddedResource::Text(text) => {
if text.text.trim().is_empty() {
None
} else {
Some(ContentBlock::Text(TextBlock::new(text.text.clone())))
}
}
adk_core::EmbeddedResource::Blob(blob) => {
let mime_type = blob.mime_type.as_deref().unwrap_or("application/octet-stream");
if let Some(media_type) = image_media_type(mime_type) {
let encoded = attachment::encode_base64(&blob.data);
Some(ContentBlock::Image(ImageBlock::new_with_base64(
Base64ImageSource::new(encoded, media_type),
)))
} else if mime_type == "application/pdf" {
let encoded = attachment::encode_base64(&blob.data);
Some(ContentBlock::Document(DocumentBlock::new_with_base64_pdf(
Base64PdfSource::new(encoded),
)))
} else if mime_type.starts_with("text/") {
match String::from_utf8(blob.data.clone()) {
Ok(text) => Some(ContentBlock::Document(
DocumentBlock::new_with_plain_text(PlainTextSource::new(text)),
)),
Err(_) => Some(ContentBlock::Text(TextBlock::new(
attachment::inline_attachment_to_text(mime_type, &blob.data),
))),
}
} else {
Some(ContentBlock::Text(TextBlock::new(
attachment::inline_attachment_to_text(mime_type, &blob.data),
)))
}
}
},
})
.collect();
Ok(MessageParam::new_with_blocks(blocks, role))
}
pub fn convert_tools(
model: &str,
tools: &adk_core::ToolDeclarations,
adapter: &dyn SchemaAdapter,
cache: &SchemaCache,
) -> Result<Vec<ToolUnionParam>, ConversionError> {
let mut members = toolsets::DeclaredMembers::default();
let mut slots: Vec<(usize, bool)> = Vec::new();
let mut converted = Vec::with_capacity(tools.len());
for (name, decl) in tools.iter() {
let had_computer = members.has_computer();
let had_browser = members.has_browser();
if members.record(name, decl)? {
if !had_computer && members.has_computer() {
slots.push((converted.len(), true));
}
if !had_browser && members.has_browser() {
slots.push((converted.len(), false));
}
continue;
}
converted.push(convert_tool(name, decl, adapter, cache)?);
}
for (position, computer) in slots.into_iter().rev() {
let entry = if computer { members.computer_entry(model)? } else { members.browser_entry() };
if let Some(entry) = entry {
converted.insert(position, entry);
}
}
Ok(converted)
}
fn convert_tool(
name: &str,
decl: &Value,
adapter: &dyn SchemaAdapter,
cache: &SchemaCache,
) -> Result<ToolUnionParam, ConversionError> {
if let Some(provider_tool) = decl.get("x-adk-anthropic-tool") {
return serde_json::from_value::<ToolUnionParam>(provider_tool.clone()).map_err(|error| {
ConversionError::InvalidToolDeclaration(format!(
"failed to deserialize Anthropic native tool '{name}': {error}"
))
});
}
let description = decl.get("description").and_then(|d| d.as_str()).map(String::from);
let input_schema = decl.get("parameters").cloned().unwrap_or_else(|| adapter.empty_schema());
let mut normalized_schema = cache.normalize(&input_schema);
let strict = decl.get("strict").and_then(Value::as_bool);
if strict != Some(true) {
super::schema_adapter::nest_composition(&mut normalized_schema);
}
let normalized_name = adapter.normalize_tool_name(name);
let mut tool_param = ToolParam::new(normalized_name.into_owned(), normalized_schema);
if let Some(desc) = description {
tool_param = tool_param.with_description(desc);
}
if let Some(strict) = strict {
tool_param = tool_param.with_strict(strict);
}
Ok(ToolUnionParam::CustomTool(tool_param))
}
pub(super) fn server_tool_part(block: &ContentBlock) -> Option<Part> {
match block {
ContentBlock::ServerToolUse(server_tool_use) => serde_json::to_value(server_tool_use)
.ok()
.map(|server_tool_call| Part::ServerToolCall { server_tool_call }),
ContentBlock::WebSearchToolResult(web_search_result) => {
serde_json::to_value(web_search_result)
.ok()
.map(|server_tool_response| Part::ServerToolResponse { server_tool_response })
}
ContentBlock::WebFetchToolResult(_)
| ContentBlock::CodeExecutionToolResult(_)
| ContentBlock::BashCodeExecutionToolResult(_)
| ContentBlock::TextEditorCodeExecutionToolResult(_) => serde_json::to_value(block)
.ok()
.map(|server_tool_response| Part::ServerToolResponse { server_tool_response }),
_ => None,
}
}
fn iteration_usage(usage: &adk_anthropic::Usage) -> Option<adk_anthropic::Usage> {
let iterations = usage.raw.as_deref()?.get("iterations")?.as_array()?;
if iterations.is_empty() {
return None;
}
let count = |iteration: &Value, field: &str| {
iteration.get(field).and_then(Value::as_i64).and_then(|n| i32::try_from(n).ok())
};
let sum = |field: &str| -> i32 {
iterations
.iter()
.filter_map(|iteration| count(iteration, field))
.fold(0, i32::saturating_add)
};
let optional_sum = |field: &str| -> Option<i32> {
iterations
.iter()
.filter_map(|iteration| count(iteration, field))
.reduce(i32::saturating_add)
};
let mut summed = usage.clone();
summed.input_tokens = sum("input_tokens");
summed.output_tokens = sum("output_tokens");
summed.cache_read_input_tokens =
optional_sum("cache_read_input_tokens").or(usage.cache_read_input_tokens);
summed.cache_creation_input_tokens =
optional_sum("cache_creation_input_tokens").or(usage.cache_creation_input_tokens);
Some(summed)
}
pub fn from_anthropic_message(
message: &Message,
forms: ToolsetForms,
) -> (LlmResponse, HashMap<String, String>) {
let mut parts = Vec::new();
for block in &message.content {
match block {
ContentBlock::Text(text_block) if !text_block.text.is_empty() => {
parts.push(Part::Text { text: text_block.text.clone() });
}
ContentBlock::ToolUse(tool_use) => {
let (name, args) = toolsets::call_from_tool_use(tool_use, forms);
parts.push(Part::FunctionCall {
name,
args,
id: Some(tool_use.id.clone()),
thought_signature: None,
});
}
ContentBlock::Thinking(thinking_block)
if !thinking_block.thinking.is_empty() || !thinking_block.signature.is_empty() =>
{
parts.push(Part::Thinking {
thinking: thinking_block.thinking.clone(),
signature: if thinking_block.signature.is_empty() {
None
} else {
Some(thinking_block.signature.clone())
},
});
}
ContentBlock::ServerToolUse(_)
| ContentBlock::WebSearchToolResult(_)
| ContentBlock::WebFetchToolResult(_)
| ContentBlock::CodeExecutionToolResult(_)
| ContentBlock::BashCodeExecutionToolResult(_)
| ContentBlock::TextEditorCodeExecutionToolResult(_) => {
parts.extend(server_tool_part(block));
}
ContentBlock::Unknown(raw) if raw["type"] == "advisor_tool_result" => {}
ContentBlock::Compaction(compaction) => {
parts.push(Part::Text {
text: adk_core::intra_compaction::compaction_summary_text(&compaction.content),
});
}
ContentBlock::Unknown(raw) => {
tracing::warn!(
anthropic.block_type = raw["type"].as_str().unwrap_or_default(),
"skipping an anthropic content block type this client does not know"
);
}
_ => {}
}
}
if let Some(native) = super::history::preserve(message) {
parts.push(native);
}
let content =
if parts.is_empty() { None } else { Some(Content { role: "model".to_string(), parts }) };
let usage = match message.stop_reason {
Some(StopReason::Compaction) => iteration_usage(&message.usage),
_ => None,
}
.unwrap_or_else(|| message.usage.clone());
let prompt_token_count = usage
.input_tokens
.saturating_add(usage.cache_read_input_tokens.unwrap_or(0))
.saturating_add(usage.cache_creation_input_tokens.unwrap_or(0));
let usage_metadata = Some(UsageMetadata {
prompt_token_count,
candidates_token_count: usage.output_tokens,
total_token_count: prompt_token_count.saturating_add(usage.output_tokens),
cache_read_input_token_count: usage.cache_read_input_tokens,
cache_creation_input_token_count: usage.cache_creation_input_tokens,
thinking_token_count: message
.usage
.raw
.as_deref()
.and_then(|raw| raw["output_tokens_details"]["thinking_tokens"].as_i64())
.and_then(|tokens| i32::try_from(tokens).ok()),
provider_usage: message
.usage
.raw
.as_deref()
.cloned()
.or_else(|| serde_json::to_value(&message.usage).ok()),
builtin_tool_uses: builtin_tool_uses(message),
..Default::default()
});
let finish_reason = message.stop_reason.as_ref().map(|sr| match sr {
StopReason::EndTurn
| StopReason::StopSequence
| StopReason::ToolUse
| StopReason::PauseTurn
| StopReason::PauseRun
| StopReason::Compaction => FinishReason::Stop,
StopReason::MaxTokens | StopReason::ModelContextWindowExceeded => FinishReason::MaxTokens,
StopReason::Refusal => FinishReason::Refusal,
StopReason::Unknown(reason) => {
tracing::warn!(
anthropic.stop_reason = %reason,
"anthropic returned a stop reason this client does not know"
);
FinishReason::Other
}
});
let paused = matches!(message.stop_reason, Some(StopReason::PauseTurn));
let tool_call_turn = matches!(message.stop_reason, Some(StopReason::ToolUse))
|| content.as_ref().is_some_and(Content::has_function_calls);
let cache_meta = extract_cache_usage(&message.usage);
let refused = matches!(message.stop_reason, Some(StopReason::Refusal));
let details = message.stop_details.as_ref();
let refusal_message = refused.then(|| {
let category = details.and_then(|details| details.category.as_deref());
let explanation = details.and_then(|details| details.explanation.as_deref());
match (category, explanation) {
(Some(category), Some(explanation)) => {
format!("Claude declined the request (category {category}): {explanation}")
}
(Some(category), None) => format!("Claude declined the request (category {category})"),
(None, Some(explanation)) => format!("Claude declined the request: {explanation}"),
(None, None) => "Claude declined the request".to_string(),
}
});
let mut provider_metadata = paused.then(|| serde_json::json!({"continue_turn": true}));
if let Some(details) = details.and_then(|details| serde_json::to_value(details).ok()) {
provider_metadata.get_or_insert_with(|| serde_json::json!({}))["stop_details"] = details;
}
(
LlmResponse {
content,
usage_metadata,
finish_reason,
citation_metadata: super::history::citations(message),
partial: false,
turn_complete: !tool_call_turn && !paused,
interrupted: false,
error_code: refused.then(|| "refusal".to_string()),
error_message: refusal_message,
provider_metadata,
interaction_id: None,
model: Some(message.model.to_string()).filter(|model| !model.is_empty()),
provider: None,
},
cache_meta,
)
}
fn builtin_tool_uses(message: &Message) -> Vec<BuiltinToolUse> {
let counts: Vec<(&str, u32)> = match message.usage.server_tool_use {
Some(reported) => vec![
("web_search", u32::try_from(reported.web_search_requests).unwrap_or(0)),
("web_fetch", u32::try_from(reported.web_fetch_requests).unwrap_or(0)),
("code_execution", u32::try_from(reported.code_execution_requests).unwrap_or(0)),
],
None => {
let mut counts = std::collections::BTreeMap::<&str, u32>::new();
for block in &message.content {
if let ContentBlock::ServerToolUse(server_tool_use) = block {
let kind = match server_tool_use.name.as_str() {
"bash_code_execution" | "text_editor_code_execution" => "code_execution",
name => name,
};
*counts.entry(kind).or_default() += 1;
}
}
counts.into_iter().collect()
}
};
counts
.into_iter()
.filter(|(_, count)| *count > 0)
.map(|(kind, count)| BuiltinToolUse::new(kind, count))
.collect()
}
pub fn from_text_delta(text: &str) -> LlmResponse {
LlmResponse {
content: Some(Content {
role: "model".to_string(),
parts: vec![Part::Text { text: text.to_string() }],
}),
usage_metadata: None,
finish_reason: None,
citation_metadata: None,
partial: true,
turn_complete: false,
interrupted: false,
error_code: None,
error_message: None,
provider_metadata: None,
interaction_id: None,
model: None,
provider: None,
}
}
pub fn from_thinking_delta(thinking_text: &str) -> LlmResponse {
LlmResponse {
content: Some(Content {
role: "model".to_string(),
parts: vec![Part::Thinking { thinking: thinking_text.to_string(), signature: None }],
}),
partial: true,
turn_complete: false,
..Default::default()
}
}
pub fn from_stream_error(error_type: &str, message: &str) -> LlmResponse {
LlmResponse {
content: None,
usage_metadata: None,
finish_reason: None,
citation_metadata: None,
partial: false,
turn_complete: true,
interrupted: false,
error_code: Some(error_type.to_string()),
error_message: Some(adk_core::upstream_excerpt(message).to_string()),
provider_metadata: None,
interaction_id: None,
model: None,
provider: None,
}
}
pub fn extract_cache_usage(usage: &adk_anthropic::Usage) -> HashMap<String, String> {
let mut metadata = HashMap::new();
if let Some(tokens) = usage.cache_creation_input_tokens {
metadata.insert("anthropic.cache_creation_input_tokens".to_string(), tokens.to_string());
}
if let Some(tokens) = usage.cache_read_input_tokens {
metadata.insert("anthropic.cache_read_input_tokens".to_string(), tokens.to_string());
}
metadata
}
#[allow(clippy::too_many_arguments)]
pub fn build_message_params(
model: &str,
max_tokens: u32,
messages: Vec<MessageParam>,
tools: Vec<ToolUnionParam>,
system_prompt: Option<String>,
temperature: Option<f32>,
top_p: Option<f32>,
top_k: Option<i32>,
prompt_caching: bool,
prompt_cache_ttl: Option<&CacheTtl>,
thinking: Option<&super::config::ThinkingMode>,
effort: Option<super::config::Effort>,
fast_mode: bool,
inference_geo: Option<&str>,
service_tier: Option<&str>,
context_management: Option<&ContextManagement>,
) -> MessageCreateParams {
let mut params =
MessageCreateParams::new(max_tokens, messages, Model::Custom(model.to_string()));
let cache_control = || match prompt_cache_ttl {
Some(ttl) => CacheControlEphemeral::new().with_ttl(ttl.clone()),
None => CacheControlEphemeral::new(),
};
if !tools.is_empty() {
params.tools = Some(tools);
}
if let Some(sys) = system_prompt {
if prompt_caching {
let block = TextBlock::new(sys).with_cache_control(cache_control());
params.system = Some(SystemPrompt::from_blocks(vec![block]));
} else {
params.system = Some(SystemPrompt::from_string(sys));
}
}
if let Some(temp) = temperature {
params.temperature = Some(temp);
}
if let Some(p) = top_p {
params.top_p = Some(p);
}
if let Some(k) = top_k {
params.top_k = Some(k as u32);
}
match thinking {
Some(super::config::ThinkingMode::Enabled { budget_tokens }) => {
params.thinking = Some(adk_anthropic::ThinkingConfig::enabled(*budget_tokens));
}
Some(super::config::ThinkingMode::Adaptive) => {
params.thinking = Some(adk_anthropic::ThinkingConfig::adaptive());
}
Some(super::config::ThinkingMode::BetweenTools) => {
params.thinking = Some(adk_anthropic::ThinkingConfig::between_tools());
}
None => {}
}
if let Some(effort) = effort {
let level = match effort {
super::config::Effort::Low => adk_anthropic::EffortLevel::Low,
super::config::Effort::Medium => adk_anthropic::EffortLevel::Medium,
super::config::Effort::High => adk_anthropic::EffortLevel::High,
super::config::Effort::XHigh => adk_anthropic::EffortLevel::XHigh,
super::config::Effort::Max => adk_anthropic::EffortLevel::Max,
};
params.output_config = Some(adk_anthropic::OutputConfig::with_effort(level));
}
if fast_mode {
params.speed = Some(adk_anthropic::SpeedMode::Fast);
}
if let Some(geo) = inference_geo {
params.inference_geo = Some(geo.to_string());
}
if let Some(tier) = service_tier {
params.service_tier = Some(tier.to_string());
}
if prompt_caching {
params.cache_control = Some(cache_control());
}
if let Some(cm) = context_management {
params.context_management = Some(cm.clone());
}
params
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn code_execution_results_become_server_tool_responses() {
let message: Message = serde_json::from_value(serde_json::json!({
"id": "msg_01",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-5-5",
"content": [
{"type": "server_tool_use", "id": "srvtoolu_01", "name": "code_execution", "input": {"code": "print(2+2)"}},
{"type": "code_execution_tool_result", "tool_use_id": "srvtoolu_01",
"content": {"type": "code_execution_result", "stdout": "4\n", "stderr": "", "return_code": 0, "content": []}},
{"type": "text", "text": "4"}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {"input_tokens": 10, "output_tokens": 5}
}))
.unwrap();
let (response, _) = from_anthropic_message(&message, ToolsetForms::default());
let parts = response.content.unwrap().parts;
let result = parts
.iter()
.find_map(|part| match part {
Part::ServerToolResponse { server_tool_response }
if server_tool_response["type"] == "code_execution_tool_result" =>
{
Some(server_tool_response)
}
_ => None,
})
.expect("code execution result part");
assert_eq!(result["tool_use_id"], "srvtoolu_01");
assert_eq!(result["content"]["stdout"], "4\n");
}
#[test]
fn tool_result_carries_the_images_a_tool_returned() {
let content = Content {
role: "function".to_string(),
parts: vec![Part::FunctionResponse {
function_response: adk_core::FunctionResponseData::with_multimodal(
"render",
serde_json::json!({"status": "rendered"}),
vec![adk_core::InlineDataPart {
mime_type: "image/png".to_string(),
data: vec![1, 2, 3],
uri: None,
annotations: None,
}],
vec![adk_core::FileDataPart {
mime_type: "image/jpeg".to_string(),
file_uri: "https://example.com/badge.jpg".to_string(),
annotations: None,
}],
),
id: Some("toolu_1".to_string()),
annotations: None,
}],
};
let message = serde_json::to_value(
content_to_message(&content, false, ToolsetForms::default()).unwrap(),
)
.unwrap();
assert_eq!(
message["content"][0]["content"],
serde_json::json!([
{"type": "text", "text": "{\"status\":\"rendered\"}"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AQID"}},
{"type": "image", "source": {"type": "url", "url": "https://example.com/badge.jpg"}}
])
);
}
#[test]
fn test_content_to_message_user() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::Text { text: "Hello".to_string() }],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
assert!(matches!(msg.role, MessageRole::User));
}
#[test]
fn test_content_to_message_assistant() {
let content = Content {
role: "model".to_string(),
parts: vec![Part::Text { text: "Hi there".to_string() }],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
assert!(matches!(msg.role, MessageRole::Assistant));
}
#[test]
fn test_content_to_message_with_inline_image() {
let content = Content {
role: "user".to_string(),
parts: vec![
Part::Text { text: "What is in this image?".to_string() },
Part::inline_data("image/png", vec![0x89, 0x50, 0x4E, 0x47]),
],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
assert!(matches!(msg.role, MessageRole::User));
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 2);
assert_eq!(content_blocks[0]["type"], "text");
assert_eq!(content_blocks[0]["text"], "What is in this image?");
assert_eq!(content_blocks[1]["type"], "image");
assert_eq!(content_blocks[1]["source"]["type"], "base64");
assert_eq!(content_blocks[1]["source"]["media_type"], "image/png");
assert!(!content_blocks[1]["source"]["data"].as_str().unwrap().is_empty());
}
#[test]
fn test_content_to_message_unsupported_mime_type_falls_back_to_text() {
let content = Content {
role: "user".to_string(),
parts: vec![
Part::Text { text: "Check this".to_string() },
Part::inline_data(
"audio/wav", vec![0x52, 0x49, 0x46, 0x46],
),
],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 2);
assert_eq!(content_blocks[0]["type"], "text");
assert_eq!(content_blocks[1]["type"], "text");
assert!(content_blocks[1]["text"].as_str().unwrap_or_default().contains("audio/wav"));
}
#[test]
fn test_content_to_message_multiple_images() {
let content = Content {
role: "user".to_string(),
parts: vec![
Part::Text { text: "Compare".to_string() },
Part::inline_data("image/jpeg", vec![0xFF, 0xD8]),
Part::inline_data("image/webp", vec![0x52, 0x49]),
],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 3); assert_eq!(content_blocks[1]["source"]["media_type"], "image/jpeg");
assert_eq!(content_blocks[2]["source"]["media_type"], "image/webp");
}
#[test]
fn test_content_to_message_pdf_inline_data_maps_to_document_block() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::inline_data("application/pdf", b"%PDF-1.4".to_vec())],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 1);
assert_eq!(content_blocks[0]["type"], "document");
assert_eq!(content_blocks[0]["source"]["type"], "base64");
assert_eq!(content_blocks[0]["source"]["media_type"], "application/pdf");
}
#[test]
fn test_content_to_message_pdf_file_uri_maps_to_document_block() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::file_data("application/pdf", "https://example.com/test.pdf")],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 1);
assert_eq!(content_blocks[0]["type"], "document");
assert_eq!(content_blocks[0]["source"]["type"], "url");
assert_eq!(content_blocks[0]["source"]["url"], "https://example.com/test.pdf");
}
#[test]
fn test_content_to_message_image_file_data_maps_to_url_image() {
let content = Content {
role: "user".to_string(),
parts: vec![
Part::Text { text: "Describe this".to_string() },
Part::file_data("image/jpeg", "https://example.com/photo.jpg"),
],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 2);
assert_eq!(content_blocks[0]["type"], "text");
assert_eq!(content_blocks[1]["type"], "image");
assert_eq!(content_blocks[1]["source"]["type"], "url");
assert_eq!(content_blocks[1]["source"]["url"], "https://example.com/photo.jpg");
}
#[test]
fn test_content_to_message_webp_file_data_maps_to_url_image() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::file_data("image/webp", "https://example.com/image.webp")],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 1);
assert_eq!(content_blocks[0]["type"], "image");
assert_eq!(content_blocks[0]["source"]["url"], "https://example.com/image.webp");
}
#[test]
fn test_content_to_message_unsupported_file_data_falls_back_to_text() {
let content = Content {
role: "user".to_string(),
parts: vec![Part::file_data("audio/wav", "https://example.com/audio.wav")],
};
let msg = content_to_message(&content, false, ToolsetForms::default()).unwrap();
let json = serde_json::to_value(&msg).unwrap();
let content_blocks = json["content"].as_array().unwrap();
assert_eq!(content_blocks.len(), 1);
assert_eq!(content_blocks[0]["type"], "text");
assert!(content_blocks[0]["text"].as_str().unwrap().contains("audio/wav"));
}
#[test]
fn test_convert_tools() {
use super::super::schema_adapter::AnthropicSchemaAdapter;
let mut tools = adk_core::ToolDeclarations::new();
tools.insert(
"get_weather".to_string(),
serde_json::json!({
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string" }
}
}
}),
);
let adapter = AnthropicSchemaAdapter;
let cache = SchemaCache::for_adapter(std::sync::Arc::new(AnthropicSchemaAdapter));
let claude_tools = convert_tools("claude-sonnet-5-5", &tools, &adapter, &cache)
.expect("tool conversion should succeed");
assert_eq!(claude_tools.len(), 1);
}
#[test]
fn convert_tools_keeps_declaration_order() {
use super::super::schema_adapter::AnthropicSchemaAdapter;
let names: Vec<String> = (0..12).map(|i| format!("tool_{i:02}")).collect();
let declaration = |name: &str| {
serde_json::json!({
"description": format!("{name} description"),
"parameters": {"type": "object", "properties": {}}
})
};
let adapter = AnthropicSchemaAdapter;
let cache = SchemaCache::for_adapter(std::sync::Arc::new(AnthropicSchemaAdapter));
let converted_names = |tools: &adk_core::ToolDeclarations| -> Vec<String> {
convert_tools("claude-sonnet-5-5", tools, &adapter, &cache)
.unwrap()
.iter()
.map(|tool| {
serde_json::to_value(tool).unwrap()["name"].as_str().unwrap().to_string()
})
.collect()
};
let forward: adk_core::ToolDeclarations =
names.iter().map(|name| (name.clone(), declaration(name))).collect();
let reversed: Vec<String> = names.iter().rev().cloned().collect();
let reverse: adk_core::ToolDeclarations =
reversed.iter().map(|name| (name.clone(), declaration(name))).collect();
assert_eq!(converted_names(&forward), names);
assert_eq!(converted_names(&reverse), reversed);
}
#[test]
fn test_convert_tools_supports_native_anthropic_tool_declarations() {
use super::super::schema_adapter::AnthropicSchemaAdapter;
let mut tools = adk_core::ToolDeclarations::new();
tools.insert(
"bash".to_string(),
serde_json::json!({
"x-adk-anthropic-tool": {
"type": "bash_20250124",
"name": "bash"
}
}),
);
let adapter = AnthropicSchemaAdapter;
let cache = SchemaCache::for_adapter(std::sync::Arc::new(AnthropicSchemaAdapter));
let claude_tools = convert_tools("claude-sonnet-5-5", &tools, &adapter, &cache)
.expect("tool conversion should succeed");
assert_eq!(claude_tools.len(), 1);
let value = serde_json::to_value(&claude_tools[0]).expect("tool should serialize");
assert_eq!(value["type"], "bash_20250124");
assert_eq!(value["name"], "bash");
}
#[test]
fn test_convert_tools_supports_dynamic_filtering_web_search() {
use super::super::schema_adapter::AnthropicSchemaAdapter;
let mut tools = adk_core::ToolDeclarations::new();
tools.insert(
"web_search".to_string(),
serde_json::json!({
"name": "web_search",
"x-adk-anthropic-tool": {
"type": "web_search_20260209",
"name": "web_search",
"allowed_domains": null,
"blocked_domains": ["spam.example"],
"max_uses": 2,
"user_location": null
}
}),
);
let adapter = AnthropicSchemaAdapter;
let cache = SchemaCache::for_adapter(std::sync::Arc::new(AnthropicSchemaAdapter));
let claude_tools = convert_tools("claude-sonnet-5-5", &tools, &adapter, &cache)
.expect("tool conversion should succeed");
assert_eq!(
claude_tools,
vec![ToolUnionParam::WebSearch20260209(
adk_anthropic::WebSearchTool20260209::new()
.with_blocked_domains(vec!["spam.example".to_string()])
.with_max_uses(2)
)]
);
}
#[test]
fn test_convert_tools_sends_direct_allowed_callers() {
use super::super::schema_adapter::AnthropicSchemaAdapter;
let mut tools = adk_core::ToolDeclarations::new();
tools.insert(
"web_search".to_string(),
serde_json::json!({
"name": "web_search",
"x-adk-anthropic-tool": {
"type": "web_search_20260209",
"name": "web_search",
"allowed_callers": ["direct"]
}
}),
);
let adapter = AnthropicSchemaAdapter;
let cache = SchemaCache::for_adapter(std::sync::Arc::new(AnthropicSchemaAdapter));
let claude_tools = convert_tools("claude-sonnet-5-5", &tools, &adapter, &cache)
.expect("tool conversion should succeed");
assert_eq!(
serde_json::to_value(&claude_tools).unwrap(),
serde_json::json!([{
"type": "web_search_20260209",
"name": "web_search",
"allowed_callers": ["direct"]
}])
);
}
#[test]
fn only_a_refused_unrun_or_failed_answer_is_flagged_an_error() {
use adk_core::ToolResultStatus;
let block = |status: Option<ToolResultStatus>| {
let mut part = Part::FunctionResponse {
function_response: adk_core::FunctionResponseData::new(
"pay",
serde_json::json!({ "error": "declined" }),
),
id: Some("toolu_1".to_string()),
annotations: None,
};
if let Some(status) = status {
part.set_tool_result_status(status, None);
}
let content = Content { role: "function".to_string(), parts: vec![part] };
let message = content_to_message(&content, false, ToolsetForms::default())
.expect("content should convert");
serde_json::to_value(message).expect("message should serialize")["content"][0].clone()
};
let flagged = |status| block(Some(status)).get("is_error").cloned();
for status in
[ToolResultStatus::Refused, ToolResultStatus::NotRun, ToolResultStatus::Failed]
{
assert_eq!(flagged(status), Some(Value::Bool(true)), "{status:?}");
}
for status in [
ToolResultStatus::Held,
ToolResultStatus::OutcomeUnknown,
ToolResultStatus::Withheld,
ToolResultStatus::Succeeded,
] {
assert_eq!(flagged(status), None, "{status:?}");
}
assert_eq!(block(None).get("is_error"), None, "a tool's own payload is not read");
}
#[test]
fn test_function_response_string_is_not_double_encoded() {
let content = Content {
role: "function".to_string(),
parts: vec![Part::FunctionResponse {
function_response: adk_core::FunctionResponseData::new(
"bash",
Value::String("hello".to_string()),
),
id: Some("tool_123".to_string()),
annotations: None,
}],
};
let message = content_to_message(&content, false, ToolsetForms::default())
.expect("content should convert");
let json = serde_json::to_value(message).expect("message should serialize");
let block = &json["content"][0];
assert_eq!(block["type"], "tool_result");
assert_eq!(block["content"], "hello");
}
#[test]
fn test_from_anthropic_message_with_thinking_block() {
use adk_anthropic::{ThinkingBlock, Usage};
let message = Message {
id: "msg_123".to_string(),
model: Model::Custom("claude-3-5-sonnet-20241022".to_string()),
role: MessageRole::Assistant,
container: None,
content: vec![
ContentBlock::Thinking(ThinkingBlock::new(
"Let me reason through this step by step...",
"sig_abc123",
)),
ContentBlock::Text(TextBlock::new("The answer is 42.")),
],
stop_reason: Some(StopReason::EndTurn),
stop_sequence: None,
stop_details: None,
r#type: "message".to_string(),
usage: Usage {
input_tokens: 10,
output_tokens: 20,
cache_creation_input_tokens: None,
cache_read_input_tokens: None,
cache_creation_input_tokens_1h: None,
server_tool_use: None,
raw: None,
},
};
let (response, _cache_meta) = from_anthropic_message(&message, ToolsetForms::default());
let content = response.content.expect("should have content");
assert_eq!(content.parts.len(), 2);
assert!(content.parts[0].is_thinking());
assert_eq!(
content.parts[0].thinking_text(),
Some("Let me reason through this step by step...")
);
assert!(!content.parts[1].is_thinking());
assert_eq!(content.parts[1].text(), Some("The answer is 42."));
}
#[test]
fn test_from_anthropic_message_unsigned_empty_thinking_block_skipped() {
use adk_anthropic::{ThinkingBlock, Usage};
let message = Message {
id: "msg_456".to_string(),
model: Model::Custom("claude-3-5-sonnet-20241022".to_string()),
role: MessageRole::Assistant,
container: None,
content: vec![
ContentBlock::Thinking(ThinkingBlock::new("", "")),
ContentBlock::Text(TextBlock::new("Just text.")),
],
stop_reason: Some(StopReason::EndTurn),
stop_sequence: None,
stop_details: None,
r#type: "message".to_string(),
usage: Usage {
input_tokens: 5,
output_tokens: 10,
cache_creation_input_tokens: None,
cache_read_input_tokens: None,
cache_creation_input_tokens_1h: None,
server_tool_use: None,
raw: None,
},
};
let (response, _) = from_anthropic_message(&message, ToolsetForms::default());
let content = response.content.expect("should have content");
assert_eq!(content.parts.len(), 1);
assert_eq!(content.parts[0].text(), Some("Just text."));
}
#[test]
fn test_from_anthropic_tool_call_keeps_turn_open() {
use adk_anthropic::{ToolUseBlock, Usage};
let message = Message {
id: "msg_tool".to_string(),
model: Model::Custom("claude-sonnet-5".to_string()),
role: MessageRole::Assistant,
container: None,
content: vec![ContentBlock::ToolUse(ToolUseBlock::new(
"tool_123",
"get_weather",
serde_json::json!({"city": "Paris"}),
))],
stop_reason: Some(StopReason::ToolUse),
stop_sequence: None,
stop_details: None,
r#type: "message".to_string(),
usage: Usage {
input_tokens: 10,
output_tokens: 12,
cache_creation_input_tokens: None,
cache_read_input_tokens: None,
cache_creation_input_tokens_1h: None,
server_tool_use: None,
raw: None,
},
};
let (response, _) = from_anthropic_message(&message, ToolsetForms::default());
assert!(!response.turn_complete, "tool-call turns must remain open for execution");
assert!(response.content.is_some_and(|content| content.has_function_calls()));
}
}