Skip to main content

aither_claude/
client.rs

1//! Claude API client implementation.
2
3use std::{sync::Arc, time::Duration};
4
5use aither_core::{
6    LanguageModel,
7    llm::{
8        Event, GenerateError, LLMRequest, TokenCounting,
9        model::{Ability, Profile as ModelProfile, ToolChoice},
10        oneshot,
11    },
12};
13use futures_core::Stream;
14use futures_lite::StreamExt;
15use tracing::debug;
16use zenwave::{Client, client, header};
17
18use crate::{
19    constant::{
20        ANTHROPIC_VERSION, CLAUDE_BASE_URL, DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_TOKENS,
21        DEFAULT_MODEL, MID_CONVERSATION_OUTPUT_CONFIG_BETA,
22    },
23    error::ClaudeError,
24    request::{
25        CountTokensRequest, MessagePayload, MessagesRequest, ParameterSnapshot,
26        apply_cache_strategy, build_output_config, build_thinking, convert_native_tools,
27        convert_tools, filter_tool_definitions, to_claude_messages, tool_choice_payload,
28    },
29    response::{
30        CountTokensResponse, MessagesResponse, StreamState, parse_event, response_events,
31        should_skip_event,
32    },
33};
34
35/// Claude chat model client for the Anthropic Messages API.
36///
37/// # Example
38///
39/// ```ignore
40/// use aither_claude::Claude;
41/// use aither_core::{LanguageModel, llm::oneshot};
42///
43/// let client = Claude::new(std::env::var("ANTHROPIC_API_KEY")?);
44///
45/// let response = client.respond(oneshot(
46///     "You are a helpful assistant.",
47///     "What is the capital of France?"
48/// )).await?;
49///
50/// println!("{response}");
51/// ```
52#[derive(Clone, Debug)]
53pub struct Claude {
54    inner: Arc<Config>,
55}
56
57impl Claude {
58    /// Create a new client using the provided API key.
59    pub fn new(api_key: impl Into<String>) -> Self {
60        Self::builder(api_key).build()
61    }
62
63    /// Start building a Claude client with custom configuration.
64    #[must_use]
65    pub fn builder(api_key: impl Into<String>) -> Builder {
66        Builder::new(api_key)
67    }
68
69    /// Override the default model in-place.
70    #[must_use]
71    pub fn with_model(mut self, model: impl Into<String>) -> Self {
72        Arc::make_mut(&mut self.inner).model = sanitize_model(model);
73        self
74    }
75
76    /// Override the base URL (useful for proxies or local deployments).
77    #[must_use]
78    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
79        Arc::make_mut(&mut self.inner).base_url = base_url.into();
80        self
81    }
82
83    /// Override the default `max_tokens`.
84    #[must_use]
85    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
86        Arc::make_mut(&mut self.inner).default_max_tokens = max_tokens;
87        self
88    }
89
90    /// Override how long a response stream may stay silent before it ends with
91    /// a [`FailureKind::Network`](aither_core::llm::FailureKind::Network)
92    /// error. Defaults to 90 seconds.
93    #[must_use]
94    pub fn with_idle_timeout(mut self, idle_timeout: Duration) -> Self {
95        Arc::make_mut(&mut self.inner).idle_timeout = idle_timeout;
96        self
97    }
98
99    pub(crate) fn config(&self) -> Arc<Config> {
100        self.inner.clone()
101    }
102}
103
104impl LanguageModel for Claude {
105    type Error = ClaudeError;
106
107    fn token_counting(&self) -> TokenCounting {
108        TokenCounting::Endpoint
109    }
110
111    /// `POST /v1/messages/count_tokens` with the same body a messages call
112    /// would send, minus `max_tokens`, `stream`, and the sampling fields the
113    /// endpoint rejects. Cache control is omitted too — counting never
114    /// simulates the cache.
115    async fn count_tokens(
116        &self,
117        request: &LLMRequest,
118    ) -> Result<Option<u32>, GenerateError<Self::Error>> {
119        let cfg = self.config();
120        let (core_messages, parameters, tool_definitions) = request.clone().into_parts();
121        {
122            let snapshot = ParameterSnapshot::from(&parameters);
123            let filtered_tool_definitions =
124                filter_tool_definitions(tool_definitions, &snapshot.tool_choice);
125            let mut claude_tool_payloads = convert_tools(&filtered_tool_definitions);
126            claude_tool_payloads.extend(convert_native_tools(&snapshot.native_tools));
127            let has_tools = !claude_tool_payloads.is_empty();
128            let (system_prompt, claude_messages) =
129                to_claude_messages(&core_messages, takes_mid_conversation_system(&cfg))
130                    .await
131                    .map_err(|error| GenerateError::Provider(ClaudeError::Api(error)))?;
132            let request_body = CountTokensRequest {
133                model: cfg.model.clone(),
134                messages: claude_messages,
135                system: system_prompt,
136                tools: has_tools.then_some(claude_tool_payloads),
137                tool_choice: tool_choice_payload(
138                    &snapshot.tool_choice,
139                    has_tools,
140                    snapshot.parallel_tool_calls,
141                ),
142                thinking: build_thinking(&snapshot),
143                output_config: build_output_config(&snapshot).map_err(GenerateError::Provider)?,
144            };
145            let endpoint = cfg.request_url("/v1/messages/count_tokens");
146            let mut backend = client();
147            let response = backend
148                .post(endpoint)
149                .and_then(|b| b.header("x-api-key", cfg.api_key.clone()))
150                .and_then(|b| b.header("anthropic-version", ANTHROPIC_VERSION))
151                .and_then(|b| b.header(header::CONTENT_TYPE.as_str(), "application/json"))
152                .and_then(|b| b.header(header::USER_AGENT.as_str(), "aither-claude/0.1"))
153                .and_then(|b| b.json_body(&request_body))
154                .map_err(ClaudeError::Http)
155                .map_err(GenerateError::Provider)?
156                .json::<CountTokensResponse>()
157                .await
158                .map_err(ClaudeError::Http)
159                .map_err(GenerateError::Provider)?;
160            Ok(Some(response.input_tokens))
161        }
162    }
163
164    #[allow(clippy::too_many_lines)]
165    fn respond(
166        &self,
167        request: LLMRequest,
168    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
169        let cfg = self.config();
170        let (core_messages, parameters, tool_definitions) = request.into_parts();
171        let snapshot = ParameterSnapshot::from(&parameters);
172        let filtered_tool_definitions =
173            filter_tool_definitions(tool_definitions, &snapshot.tool_choice);
174        let missing_exact_tool = match &snapshot.tool_choice {
175            ToolChoice::Exact(name)
176                if filtered_tool_definitions.is_empty()
177                    && !native_tool_name_enabled(&snapshot, name) =>
178            {
179                Some(name.clone())
180            }
181            _ => None,
182        };
183        let mut claude_tool_payloads = convert_tools(&filtered_tool_definitions);
184        claude_tool_payloads.extend(convert_native_tools(&snapshot.native_tools));
185        let has_tools = !claude_tool_payloads.is_empty();
186        let mut claude_tools = has_tools.then_some(claude_tool_payloads);
187        let claude_tool_choice = tool_choice_payload(
188            &snapshot.tool_choice,
189            has_tools,
190            snapshot.parallel_tool_calls,
191        );
192
193        let max_tokens = snapshot.max_tokens.unwrap_or(cfg.default_max_tokens);
194
195        async_stream::stream! {
196            let (mut system_prompt, mut claude_messages) =
197                match to_claude_messages(&core_messages, takes_mid_conversation_system(&cfg)).await {
198                    Ok(payload) => payload,
199                    Err(error) => {
200                        yield Err(ClaudeError::Api(error));
201                        return;
202                    }
203                };
204
205            if let Some(tool_name) = &missing_exact_tool {
206                yield Err(ClaudeError::Api(format!(
207                    "Exact tool choice '{tool_name}' is not present in tool definitions"
208                )));
209                return;
210            }
211
212            let top_level_cache_control = if let Some(cache) = snapshot.cache {
213                match apply_cache_strategy(
214                    &mut system_prompt,
215                    &mut claude_messages,
216                    &mut claude_tools,
217                    cache,
218                ) {
219                    Ok(control) => control,
220                    Err(error) => {
221                        yield Err(ClaudeError::Api(error));
222                        return;
223                    }
224                }
225            } else {
226                None
227            };
228
229            let thinking = build_thinking(&snapshot);
230            let output_config = match build_output_config(&snapshot) {
231                Ok(config) => config,
232                Err(error) => {
233                    yield Err(error);
234                    return;
235                }
236            };
237
238            // Build and send request
239            let stream_requested = snapshot.stream.unwrap_or(true);
240            let request_body = MessagesRequest {
241                model: cfg.model.clone(),
242                max_tokens,
243                messages: claude_messages,
244                system: system_prompt,
245                stream: stream_requested,
246                temperature: snapshot.temperature,
247                top_p: snapshot.top_p,
248                top_k: snapshot.top_k,
249                stop_sequences: snapshot.stop_sequences.clone(),
250                tools: claude_tools,
251                tool_choice: claude_tool_choice,
252                thinking,
253                output_config,
254                cache_control: top_level_cache_control,
255            };
256
257            debug!("Claude request: {:?}", request_body);
258            let effort_updates = request_body
259                .messages
260                .iter()
261                .any(MessagePayload::is_effort_update);
262
263            let endpoint = cfg.request_url("/v1/messages");
264            let mut backend = client();
265
266            // Claude-specific headers
267            let builder = match backend
268                .post(endpoint)
269                .and_then(|b| b.header("x-api-key", cfg.api_key.clone()))
270                .and_then(|b| b.header("anthropic-version", ANTHROPIC_VERSION))
271                .and_then(|b| b.header(header::CONTENT_TYPE.as_str(), "application/json"))
272                .and_then(|b| {
273                    if stream_requested {
274                        b.header(header::ACCEPT.as_str(), "text/event-stream")
275                    } else {
276                        Ok(b)
277                    }
278                })
279                .and_then(|b| b.header(header::USER_AGENT.as_str(), "aither-claude/0.1"))
280                .and_then(|b| {
281                    if effort_updates {
282                        b.header("anthropic-beta", MID_CONVERSATION_OUTPUT_CONFIG_BETA)
283                    } else {
284                        Ok(b)
285                    }
286                })
287                .and_then(|b| b.json_body(&request_body))
288            {
289                Ok(b) => b,
290                Err(e) => {
291                    yield Err(ClaudeError::Http(e));
292                    return;
293                }
294            };
295
296            if !stream_requested {
297                match builder.json::<MessagesResponse>().await {
298                    Ok(response) => {
299                        for event in response_events(response) {
300                            yield Ok(event);
301                        }
302                    }
303                    Err(e) => yield Err(ClaudeError::Http(e)),
304                }
305                return;
306            }
307
308            let sse_stream = match builder.sse().await {
309                Ok(stream) => stream,
310                Err(e) => {
311                    yield Err(ClaudeError::Http(e));
312                    return;
313                }
314            };
315            futures_lite::pin!(sse_stream);
316
317            let mut state = StreamState::new();
318
319            loop {
320                // Bytes that never come are the signature of a socket that
321                // died while the machine slept.
322                let next = futures_lite::future::or(
323                    async { Some(sse_stream.next().await) },
324                    async {
325                        aither_core::time::sleep(cfg.idle_timeout).await;
326                        None
327                    },
328                )
329                .await;
330                let Some(event) = next else {
331                    yield Err(ClaudeError::IdleTimeout { idle: cfg.idle_timeout });
332                    return;
333                };
334                let Some(event) = event else { break };
335                let event = match event {
336                    Ok(event) => event,
337                    Err(e) => {
338                        yield Err(ClaudeError::from(e));
339                        return;
340                    }
341                };
342                if should_skip_event(&event) {
343                    continue;
344                }
345                match parse_event(&event, &mut state) {
346                    Ok(llm_events) => {
347                        for llm_event in llm_events {
348                            yield Ok(llm_event);
349                        }
350                    }
351                    Err(e) => {
352                        yield Err(e);
353                        return;
354                    }
355                }
356            }
357
358            // Tool calls are reported, never executed: the consumer decides.
359            for call in state.tool_calls {
360                // Claude scopes thinking to the turn, not to the individual
361                // call, so the state rides on the assistant message instead.
362                yield Ok(Event::tool_call(call.id, call.name, call.input));
363            }
364
365            debug!("Claude response complete, stop_reason: {:?}", state.stop_reason);
366        }
367    }
368
369    fn complete(&self, prefix: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
370        self.respond(oneshot(
371            "Continue the user provided text without additional commentary.",
372            prefix,
373        ))
374    }
375
376    fn profile(
377        &self,
378    ) -> impl core::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
379        let cfg = self.inner.clone();
380        async move {
381            // Try to fetch context window from proxy API (e.g., OpenRouter)
382            // Native Anthropic API doesn't expose this
383            let context_length = match fetch_model_context_length(&cfg).await {
384                Ok(len) => len,
385                Err(e) => {
386                    tracing::debug!("API did not return context_length: {e}");
387                    // Fallback to models database
388                    aither_models::lookup(&cfg.model)
389                        .and_then(aither_models::ModelEntry::max_input_tokens)
390                        .ok_or_else(|| {
391                            ClaudeError::Api(format!(
392                                "cannot determine context length for model '{model}': \
393                                 {models_url} request failed ({e}) and aither-models has no entry",
394                                model = cfg.model,
395                                models_url = cfg.request_url("/models"),
396                            ))
397                        })?
398                }
399            };
400
401            let mut profile = ModelProfile::new(
402                cfg.model.clone(),
403                "Anthropic",
404                cfg.model.clone(),
405                "Claude model by Anthropic",
406                context_length,
407            )
408            .with_abilities([Ability::ToolUse, Ability::Vision]);
409            if takes_per_message_effort(&cfg) {
410                profile.abilities.push(Ability::PerMessageEffort);
411            }
412            if takes_mid_conversation_system(&cfg) {
413                profile.abilities.push(Ability::MidConversationSystem);
414            }
415            profile.default_reasoning_effort = aither_models::default_reasoning_effort(&cfg.model);
416
417            for ability in &cfg.native_abilities {
418                if !profile.abilities.contains(ability) {
419                    profile.abilities.push(*ability);
420                }
421            }
422            Ok(profile)
423        }
424    }
425}
426
427/// Whether this client's model takes a per-message effort change: the
428/// registry lists the model for it, and the client talks to the Claude API
429/// itself, one of the platforms Anthropic documents the beta on (a proxy
430/// behind another base URL is not).
431fn takes_per_message_effort(cfg: &Config) -> bool {
432    cfg.base_url.trim_end_matches('/') == CLAUDE_BASE_URL
433        && aither_models::lookup(&cfg.model)
434            .is_some_and(|entry| entry.has_ability(Ability::PerMessageEffort))
435}
436
437/// Whether this client's model takes a system message inside `messages`: the
438/// registry lists the model for it and the client talks to the Claude API
439/// itself.
440fn takes_mid_conversation_system(cfg: &Config) -> bool {
441    cfg.base_url.trim_end_matches('/') == CLAUDE_BASE_URL
442        && aither_models::lookup(&cfg.model)
443            .is_some_and(|entry| entry.has_ability(Ability::MidConversationSystem))
444}
445
446fn native_tool_name_enabled(snapshot: &ParameterSnapshot, name: &str) -> bool {
447    let tools = &snapshot.native_tools;
448    matches!(
449        name,
450        "web_search" if tools.web_search
451    ) || matches!(
452        name,
453        "web_fetch" if tools.web_fetch
454    ) || matches!(
455        name,
456        "code_execution" if tools.code_execution
457    ) || matches!(
458        name,
459        "bash" if tools.bash
460    ) || matches!(
461        name,
462        "str_replace_based_edit_tool" if tools.text_editor.is_some()
463    )
464}
465
466/// Try to fetch context length from the models endpoint.
467async fn fetch_model_context_length(cfg: &Config) -> Result<u32, ClaudeError> {
468    #[derive(serde::Deserialize)]
469    struct ModelsResponse {
470        data: Vec<ModelInfo>,
471    }
472    #[derive(serde::Deserialize)]
473    struct ModelInfo {
474        id: String,
475        /// Anthropic uses `max_tokens`, `OpenRouter` uses `context_length`
476        #[serde(default, alias = "max_tokens")]
477        context_length: Option<u32>,
478    }
479
480    let url = format!("{}/models", cfg.base_url.trim_end_matches('/'));
481    let mut backend = client();
482    let mut req = backend.get(&url).map_err(ClaudeError::Http)?;
483
484    // Anthropic uses x-api-key header, proxies use Bearer token
485    if cfg.base_url.contains("anthropic.com") {
486        req = req
487            .header("x-api-key", cfg.api_key.clone())
488            .map_err(ClaudeError::Http)?
489            .header("anthropic-version", ANTHROPIC_VERSION)
490            .map_err(ClaudeError::Http)?;
491    } else {
492        req = req
493            .header(
494                header::AUTHORIZATION.as_str(),
495                format!("Bearer {}", cfg.api_key),
496            )
497            .map_err(ClaudeError::Http)?;
498    }
499
500    let response: ModelsResponse = req.json().await.map_err(ClaudeError::Http)?;
501
502    for model in response.data {
503        if model.id == cfg.model
504            && let Some(ctx) = model.context_length
505        {
506            return Ok(ctx);
507        }
508    }
509
510    Err(ClaudeError::Api(format!(
511        "Model '{}' not found or missing context_length",
512        cfg.model
513    )))
514}
515
516/// Builder for Claude clients.
517#[derive(Debug)]
518pub struct Builder {
519    api_key: String,
520    base_url: String,
521    model: String,
522    default_max_tokens: u32,
523    native_abilities: Vec<Ability>,
524    idle_timeout: Duration,
525}
526
527impl Builder {
528    fn new(api_key: impl Into<String>) -> Self {
529        Self {
530            api_key: api_key.into(),
531            base_url: CLAUDE_BASE_URL.to_string(),
532            model: DEFAULT_MODEL.to_string(),
533            default_max_tokens: DEFAULT_MAX_TOKENS,
534            native_abilities: Vec::new(),
535            idle_timeout: DEFAULT_IDLE_TIMEOUT,
536        }
537    }
538
539    /// Set a custom API base URL.
540    #[must_use]
541    pub fn base_url(mut self, url: impl Into<String>) -> Self {
542        self.base_url = url.into();
543        self
544    }
545
546    /// Select a model identifier.
547    #[must_use]
548    pub fn model(mut self, model: impl Into<String>) -> Self {
549        self.model = sanitize_model(model);
550        self
551    }
552
553    /// Set the default `max_tokens` for requests.
554    #[must_use]
555    pub const fn max_tokens(mut self, max_tokens: u32) -> Self {
556        self.default_max_tokens = max_tokens;
557        self
558    }
559
560    /// Set how long a response stream may stay silent before it ends with a
561    /// [`FailureKind::Network`](aither_core::llm::FailureKind::Network) error;
562    /// 90 seconds by default.
563    #[must_use]
564    pub const fn idle_timeout(mut self, idle_timeout: Duration) -> Self {
565        self.idle_timeout = idle_timeout;
566        self
567    }
568
569    /// Declare extra native capabilities supported by the model.
570    #[must_use]
571    pub fn native_capabilities(mut self, abilities: impl IntoIterator<Item = Ability>) -> Self {
572        for ability in abilities {
573            if !self.native_abilities.contains(&ability) {
574                self.native_abilities.push(ability);
575            }
576        }
577        self
578    }
579
580    /// Mark this model as having built-in PDF understanding.
581    #[must_use]
582    pub fn enable_native_pdf(self) -> Self {
583        self.native_capabilities([Ability::Pdf])
584    }
585
586    /// Consume the builder and create a Claude client.
587    #[must_use]
588    pub fn build(self) -> Claude {
589        Claude {
590            inner: Arc::new(Config {
591                api_key: self.api_key,
592                base_url: self.base_url,
593                model: self.model,
594                default_max_tokens: self.default_max_tokens,
595                native_abilities: self.native_abilities,
596                idle_timeout: self.idle_timeout,
597            }),
598        }
599    }
600}
601
602/// Internal configuration for the Claude client.
603#[derive(Debug, Clone)]
604pub struct Config {
605    pub(crate) api_key: String,
606    pub(crate) base_url: String,
607    pub(crate) model: String,
608    pub(crate) default_max_tokens: u32,
609    pub(crate) native_abilities: Vec<Ability>,
610    pub(crate) idle_timeout: Duration,
611}
612
613impl Config {
614    pub(crate) fn request_url(&self, path: &str) -> String {
615        format!(
616            "{}/{}",
617            self.base_url.trim_end_matches('/'),
618            path.trim_start_matches('/')
619        )
620    }
621}
622
623fn sanitize_model(model: impl Into<String>) -> String {
624    model.into().trim().to_string()
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630    use aither_core::llm::{Message, model::Parameters, model::ReasoningEffort};
631
632    /// A loopback server that records the one request it receives, headers
633    /// and body, and answers it with an error.
634    fn capturing_server() -> (String, std::sync::mpsc::Receiver<String>) {
635        use std::io::{Read, Write};
636
637        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind stub server");
638        let addr = listener.local_addr().expect("stub server address");
639        let (sender, received) = std::sync::mpsc::channel();
640        std::thread::spawn(move || {
641            let (mut stream, _) = listener.accept().expect("accept the request");
642            let mut request = Vec::new();
643            let mut chunk = [0_u8; 8192];
644            let body_start = loop {
645                let read = stream.read(&mut chunk).expect("read the request");
646                request.extend_from_slice(chunk.get(..read).expect("read within the chunk"));
647                if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
648                    break end + 4;
649                }
650            };
651            let head =
652                String::from_utf8_lossy(request.get(..body_start).expect("head")).into_owned();
653            let length = head.lines().find_map(|line| {
654                line.to_ascii_lowercase()
655                    .strip_prefix("content-length:")
656                    .map(|length| length.trim().parse::<usize>().expect("a numeric length"))
657            });
658            let complete = |request: &[u8]| {
659                length.map_or_else(
660                    || request.ends_with(b"0\r\n\r\n"),
661                    |length| request.len() >= body_start + length,
662                )
663            };
664            while !complete(&request) {
665                let read = stream.read(&mut chunk).expect("read the body");
666                request.extend_from_slice(chunk.get(..read).expect("read within the chunk"));
667            }
668            let raw = String::from_utf8_lossy(request.get(body_start..).expect("body"));
669            let body = if length.is_some() {
670                raw.into_owned()
671            } else {
672                dechunk(&raw)
673            };
674            sender
675                .send(format!("{head}{body}"))
676                .expect("the test is listening");
677            let _ = stream.write_all(
678                b"HTTP/1.1 400 Bad Request\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}",
679            );
680        });
681        (format!("http://{addr}"), received)
682    }
683
684    /// The payload of a chunked transfer-encoded body.
685    fn dechunk(mut raw: &str) -> String {
686        let mut body = String::new();
687        loop {
688            let (size, rest) = raw.split_once("\r\n").expect("a chunk size line");
689            let size = usize::from_str_radix(size.trim(), 16).expect("a hex chunk size");
690            if size == 0 {
691                return body;
692            }
693            body.push_str(rest.get(..size).expect("the chunk is complete"));
694            raw = rest
695                .get(size..)
696                .and_then(|rest| rest.strip_prefix("\r\n"))
697                .expect("the chunk ends with CRLF");
698        }
699    }
700
701    /// A loopback server that records the request and answers `200` with
702    /// the given JSON body — the shape `count_tokens` needs.
703    fn responding_server(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
704        let (base_url, received) = {
705            use std::io::{Read, Write};
706            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind stub server");
707            let addr = listener.local_addr().expect("stub server address");
708            let (sender, received) = std::sync::mpsc::channel();
709            std::thread::spawn(move || {
710                let (mut stream, _) = listener.accept().expect("accept the request");
711                let mut request = Vec::new();
712                let mut chunk = [0_u8; 8192];
713                let body_start = loop {
714                    let read = stream.read(&mut chunk).expect("read the request");
715                    request.extend_from_slice(chunk.get(..read).expect("read within the chunk"));
716                    if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
717                        break end + 4;
718                    }
719                };
720                let head_str =
721                    String::from_utf8_lossy(request.get(..body_start).expect("head")).into_owned();
722                let length = head_str.lines().find_map(|line| {
723                    line.to_ascii_lowercase()
724                        .strip_prefix("content-length:")
725                        .map(|v| v.trim().parse::<usize>().expect("numeric length"))
726                });
727                let chunked = head_str
728                    .to_ascii_lowercase()
729                    .contains("transfer-encoding: chunked");
730                let complete = |request: &[u8]| {
731                    if chunked {
732                        request.ends_with(b"0\r\n\r\n")
733                    } else {
734                        request.len() >= body_start + length.unwrap_or(0)
735                    }
736                };
737                while !complete(&request) {
738                    let read = stream.read(&mut chunk).expect("read the body");
739                    request.extend_from_slice(chunk.get(..read).expect("read within the chunk"));
740                }
741                let raw =
742                    String::from_utf8_lossy(request.get(body_start..).expect("body")).into_owned();
743                let decoded_body = if chunked { dechunk(&raw) } else { raw };
744                sender
745                    .send(format!("{head_str}{decoded_body}"))
746                    .expect("the test is listening");
747                let response = format!(
748                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
749                    body.len(),
750                    body
751                );
752                let _ = stream.write_all(response.as_bytes());
753            });
754            (format!("http://{addr}"), received)
755        };
756        (base_url, received)
757    }
758
759    /// `count_tokens` posts the messages payload — minus generation fields —
760    /// to `/v1/messages/count_tokens` and reads `input_tokens` back.
761    #[tokio::test]
762    async fn count_tokens_posts_to_the_count_endpoint() {
763        let (base_url, received) = responding_server("{\"input_tokens\": 2097}");
764        let client = Claude::builder("key")
765            .base_url(base_url)
766            .model("claude-opus-5-5")
767            .build();
768        assert_eq!(client.token_counting(), TokenCounting::Endpoint);
769        let request = LLMRequest::new(vec![Message::user("Plan the migration.")])
770            .with_parameters(Parameters::default().max_tokens(512));
771        let counted = client.count_tokens(&request).await.expect("count succeeds");
772        assert_eq!(counted, Some(2097));
773
774        let sent = received.recv().expect("the request arrives");
775        let (head, body) = sent.split_once("\r\n\r\n").expect("head and body");
776        assert!(
777            head.lines()
778                .next()
779                .is_some_and(|line| line.contains("POST /v1/messages/count_tokens")),
780            "{head}"
781        );
782        let body: serde_json::Value = serde_json::from_str(body).expect("a JSON body");
783        assert_eq!(body["model"], "claude-opus-5-5");
784        assert_eq!(body["messages"][0]["role"], "user");
785        assert!(body.get("max_tokens").is_none(), "{body}");
786        assert!(body.get("stream").is_none(), "{body}");
787    }
788
789    /// A request carrying an effort update sends the beta header and the
790    /// effort-only system message, with the request-level effort as given.
791    #[tokio::test]
792    async fn an_effort_update_sends_the_beta_and_the_per_message_form() {
793        let (base_url, received) = capturing_server();
794        let client = Claude::builder("key")
795            .base_url(base_url)
796            .model("claude-opus-5-5")
797            .build();
798        let request = LLMRequest::new(vec![
799            Message::user("Plan the migration."),
800            Message::assistant("Here is the plan."),
801            Message::configuration(ReasoningEffort::Low),
802            Message::user("Now rename the config file."),
803        ])
804        .with_parameters(
805            Parameters::default()
806                .reasoning_effort(ReasoningEffort::High)
807                .stream(false),
808        );
809        let stream = client.respond(request);
810        futures_lite::pin!(stream);
811        let _ = stream.next().await;
812
813        let sent = received.recv().expect("the request arrives");
814        let (head, body) = sent.split_once("\r\n\r\n").expect("head and body");
815        assert!(
816            head.to_ascii_lowercase()
817                .contains("anthropic-beta: mid-conversation-output-config-2026-07-01"),
818            "{head}"
819        );
820        let body: serde_json::Value = serde_json::from_str(body).expect("a JSON body");
821        assert_eq!(body["output_config"]["effort"], "high");
822        assert_eq!(
823            body["messages"][2],
824            serde_json::json!({"role": "system", "content": [], "output_config": {"effort": "low"}})
825        );
826    }
827
828    #[test]
829    fn per_message_effort_is_the_claude_apis_on_the_listed_models() {
830        let config = |model: &str, base_url: &str| {
831            Claude::builder("key")
832                .model(model)
833                .base_url(base_url)
834                .build()
835                .config()
836        };
837        assert!(takes_per_message_effort(&config(
838            "claude-opus-5-5",
839            CLAUDE_BASE_URL
840        )));
841        assert!(!takes_per_message_effort(&config(
842            "claude-sonnet-5",
843            CLAUDE_BASE_URL
844        )));
845        assert!(!takes_per_message_effort(&config(
846            "claude-opus-5-5",
847            "https://openrouter.ai/api/v1"
848        )));
849    }
850}