Skip to main content

adk_anthropic/
lib.rs

1//! # adk-anthropic
2//!
3//! Dedicated Anthropic API client for ADK-Rust.
4//!
5//! This crate provides the HTTP client, type system, SSE streaming, error handling,
6//! and backoff logic for interacting with the Anthropic API. Agent framework,
7//! CLI tools, chat session management, and observability are handled by other
8//! ADK crates.
9
10mod accumulating_stream;
11mod backoff;
12mod cache_control;
13mod client;
14mod client_logger;
15mod error;
16mod json_schema;
17mod observability;
18pub mod pricing;
19mod sse;
20mod tool_search;
21mod types;
22
23pub use accumulating_stream::AccumulatingStream;
24pub use backoff::ExponentialBackoff;
25pub use cache_control::{
26    MAX_CACHE_BREAKPOINTS, apply_cache_control_to_messages, count_system_cache_controls,
27    prune_cache_controls_in_messages,
28};
29pub use client::{Anthropic, LoggingStream};
30pub use client_logger::ClientLogger;
31pub use error::{Error, Result};
32pub use json_schema::JsonSchema;
33pub use tool_search::ToolSearchConfig;
34pub use types::*;
35
36/// Pushes a message to the messages vector, or merges it with the last message if they have the same role.
37pub fn push_or_merge_message(messages: &mut Vec<MessageParam>, to_push: MessageParam) {
38    if let Some(last) = messages.last_mut() {
39        if last.role != to_push.role {
40            messages.push(to_push);
41        } else {
42            merge_message_content(&mut last.content, to_push.content);
43        }
44    } else {
45        messages.push(to_push);
46    }
47}
48
49/// Merges new message content into existing message content.
50pub fn merge_message_content(existing: &mut MessageParamContent, new: MessageParamContent) {
51    match (&mut *existing, new) {
52        (MessageParamContent::Array(existing_blocks), MessageParamContent::Array(new_blocks)) => {
53            existing_blocks.extend(new_blocks);
54        }
55        (MessageParamContent::Array(existing_blocks), MessageParamContent::String(new_string)) => {
56            existing_blocks.push(ContentBlock::Text(crate::TextBlock::new(new_string)));
57        }
58        (MessageParamContent::String(existing_string), MessageParamContent::Array(new_blocks)) => {
59            let mut combined =
60                vec![ContentBlock::Text(crate::TextBlock::new(existing_string.clone()))];
61            combined.extend(new_blocks);
62            *existing = MessageParamContent::Array(combined);
63        }
64        (MessageParamContent::String(existing_string), MessageParamContent::String(new_string)) => {
65            existing_string.push_str(&new_string);
66        }
67    }
68}