Skip to main content

adk_model/anthropic/
token_count.rs

1//! Token counting API for Anthropic.
2//!
3//! Provides [`TokenCount`] and the `count_tokens` method on [`AnthropicClient`],
4//! wrapping the `POST /v1/messages/count_tokens` endpoint.
5
6use super::client::{AnthropicClient, convert_anthropic_error};
7use adk_anthropic::{MessageCountTokensParams, Model};
8use adk_core::{AdkError, LlmRequest};
9
10/// Result of a token counting request.
11///
12/// Contains the input token count for a given request without generating
13/// a response.
14///
15/// # Example
16///
17/// ```rust,ignore
18/// use adk_model::anthropic::{AnthropicClient, AnthropicConfig};
19/// use adk_core::LlmRequest;
20///
21/// let client = AnthropicClient::new(AnthropicConfig::new("sk-ant-xxx", "claude-sonnet-4-6"))?;
22/// let request = LlmRequest::default();
23/// let count = client.count_tokens(&request).await?;
24/// println!("Input tokens: {}", count.input_tokens);
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct TokenCount {
28    /// The total number of input tokens across messages, system prompt, and tools.
29    pub input_tokens: u32,
30}
31
32impl AnthropicClient {
33    /// Count tokens for a request without generating a response.
34    ///
35    /// Calls `POST /v1/messages/count_tokens` using the same request
36    /// construction as `generate_content`, so system prompt extraction,
37    /// multimodal mapping, and tool conversion all apply.
38    ///
39    /// # Errors
40    ///
41    /// Returns `AdkError::Model` with structured error context if the
42    /// API returns an error, consistent with the messages API.
43    pub async fn count_tokens(&self, request: &LlmRequest) -> Result<TokenCount, AdkError> {
44        let params =
45            Self::build_message_params(&self.model, self.max_tokens, request, &self.config)?;
46
47        // Build MessageCountTokensParams from the already-constructed message params.
48        let mut count_params =
49            MessageCountTokensParams::new(params.messages, Model::Custom(self.model.clone()));
50
51        if let Some(system) = params.system {
52            count_params = count_params.with_system(system);
53        }
54
55        if let Some(tools) = params.tools {
56            count_params = count_params.with_tools(tools);
57        }
58
59        if let Some(thinking) = params.thinking {
60            count_params = count_params.with_thinking(thinking);
61        }
62
63        let result =
64            self.client.count_tokens(count_params).await.map_err(convert_anthropic_error)?;
65
66        Ok(TokenCount { input_tokens: result.input_tokens })
67    }
68}