1use super::http::{default_http_client, normalize_base_url, HttpClient};
4use super::structured;
5use super::types::*;
6use super::LlmClient;
7use crate::retry::{AttemptOutcome, RetryConfig};
8use anyhow::{Context, Result};
9use async_trait::async_trait;
10use futures::StreamExt;
11use serde::Deserialize;
12use std::sync::Arc;
13use std::time::Instant;
14use tokio::sync::mpsc;
15use tokio_util::sync::CancellationToken;
16
17pub(crate) const DEFAULT_MAX_TOKENS: usize = 8192;
19
20pub struct AnthropicClient {
22 pub(crate) provider_name: String,
23 pub(crate) api_key: SecretString,
24 pub(crate) model: String,
25 pub(crate) base_url: String,
26 pub(crate) max_tokens: usize,
27 pub(crate) temperature: Option<f32>,
28 pub(crate) thinking_budget: Option<usize>,
29 pub(crate) http: Arc<dyn HttpClient>,
30 pub(crate) retry_config: RetryConfig,
31}
32
33impl AnthropicClient {
34 pub fn new(api_key: String, model: String) -> Self {
35 Self {
36 provider_name: "anthropic".to_string(),
37 api_key: SecretString::new(api_key),
38 model,
39 base_url: "https://api.anthropic.com".to_string(),
40 max_tokens: DEFAULT_MAX_TOKENS,
41 temperature: None,
42 thinking_budget: None,
43 http: default_http_client(),
44 retry_config: RetryConfig::default(),
45 }
46 }
47
48 pub fn with_base_url(mut self, base_url: String) -> Self {
49 self.base_url = normalize_base_url(&base_url);
50 self
51 }
52
53 pub fn with_provider_name(mut self, provider_name: impl Into<String>) -> Self {
54 self.provider_name = provider_name.into();
55 self
56 }
57
58 pub fn with_max_tokens(mut self, max_tokens: usize) -> Self {
59 self.max_tokens = max_tokens;
60 self
61 }
62
63 pub fn with_temperature(mut self, temperature: f32) -> Self {
64 self.temperature = Some(temperature);
65 self
66 }
67
68 pub fn with_thinking_budget(mut self, budget: usize) -> Self {
69 self.thinking_budget = Some(budget);
70 self
71 }
72
73 pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
74 self.retry_config = retry_config;
75 self
76 }
77
78 pub fn with_http_client(mut self, http: Arc<dyn HttpClient>) -> Self {
79 self.http = http;
80 self
81 }
82
83 fn initial_tool_input_json(input: &serde_json::Value) -> Option<String> {
84 match input {
85 serde_json::Value::Object(map) if map.is_empty() => None,
86 serde_json::Value::Null => None,
87 value => serde_json::to_string(value).ok(),
88 }
89 }
90
91 pub(crate) fn build_request(
92 &self,
93 messages: &[Message],
94 system: Option<&str>,
95 tools: &[ToolDefinition],
96 ) -> serde_json::Value {
97 let mut request = serde_json::json!({
98 "model": self.model,
99 "max_tokens": self.max_tokens,
100 "messages": messages,
101 });
102
103 if let Some(sys) = system {
107 request["system"] = serde_json::json!([
108 {
109 "type": "text",
110 "text": sys,
111 "cache_control": { "type": "ephemeral" }
112 }
113 ]);
114 }
115
116 if !tools.is_empty() {
117 let mut tool_defs: Vec<serde_json::Value> = tools
118 .iter()
119 .map(|t| {
120 serde_json::json!({
121 "name": t.name,
122 "description": t.description,
123 "input_schema": t.parameters,
124 })
125 })
126 .collect();
127
128 if let Some(last) = tool_defs.last_mut() {
131 last["cache_control"] = serde_json::json!({ "type": "ephemeral" });
132 }
133
134 request["tools"] = serde_json::json!(tool_defs);
135 }
136
137 if let Some(temp) = self.temperature {
139 request["temperature"] = serde_json::json!(temp);
140 }
141
142 if let Some(budget) = self.thinking_budget {
144 request["thinking"] = serde_json::json!({
145 "type": "enabled",
146 "budget_tokens": budget
147 });
148 request["temperature"] = serde_json::json!(1.0);
150 }
151
152 request
153 }
154}
155
156impl AnthropicClient {
157 fn apply_directive(
162 request: &mut serde_json::Value,
163 directive: &structured::StructuredDirective,
164 ) {
165 if let Some(tool) = &directive.force_tool {
166 request["tool_choice"] = serde_json::json!({ "type": "tool", "name": tool });
167 }
168 }
169
170 async fn send_request(&self, request_body: serde_json::Value) -> Result<LlmResponse> {
172 {
173 let request_started_at = Instant::now();
174 let url = format!("{}/v1/messages", self.base_url);
175
176 let headers = vec![
177 ("x-api-key", self.api_key.expose()),
178 ("anthropic-version", "2023-06-01"),
179 ("anthropic-beta", "prompt-caching-2024-07-31"),
180 ];
181
182 let response = crate::retry::with_retry(&self.retry_config, |_attempt| {
183 let http = &self.http;
184 let url = &url;
185 let headers = headers.clone();
186 let request_body = &request_body;
187 async move {
188 match http
189 .post(url, headers, request_body, CancellationToken::new())
190 .await
191 {
192 Ok(resp) => {
193 let status = reqwest::StatusCode::from_u16(resp.status)
194 .unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
195 if status.is_success() {
196 AttemptOutcome::Success(resp.body)
197 } else if self.retry_config.is_retryable_status(status) {
198 AttemptOutcome::Retryable {
199 status,
200 body: resp.body,
201 retry_after: None,
202 }
203 } else {
204 AttemptOutcome::Fatal(anyhow::anyhow!(
205 "Anthropic API error at {} ({}): {}",
206 url,
207 status,
208 resp.body
209 ))
210 }
211 }
212 Err(e) => AttemptOutcome::Fatal(e),
213 }
214 }
215 })
216 .await?;
217
218 let parsed: AnthropicResponse =
219 serde_json::from_str(&response).context("Failed to parse Anthropic response")?;
220
221 tracing::debug!("Anthropic response: {:?}", parsed);
222
223 let content: Vec<ContentBlock> = parsed
224 .content
225 .into_iter()
226 .map(|block| match block {
227 AnthropicContentBlock::Text { text } => ContentBlock::Text { text },
228 AnthropicContentBlock::ToolUse { id, name, input } => {
229 ContentBlock::ToolUse { id, name, input }
230 }
231 })
232 .collect();
233
234 let llm_response = LlmResponse {
235 message: Message {
236 role: "assistant".to_string(),
237 content,
238 reasoning_content: None,
239 },
240 usage: TokenUsage {
241 prompt_tokens: parsed.usage.input_tokens,
242 completion_tokens: parsed.usage.output_tokens,
243 total_tokens: parsed.usage.input_tokens + parsed.usage.output_tokens,
244 cache_read_tokens: parsed.usage.cache_read_input_tokens,
245 cache_write_tokens: parsed.usage.cache_creation_input_tokens,
246 },
247 stop_reason: Some(parsed.stop_reason),
248 token_logprobs: Vec::new(),
249 meta: Some(LlmResponseMeta {
250 provider: Some(self.provider_name.clone()),
251 request_model: Some(self.model.clone()),
252 request_url: Some(url.clone()),
253 response_id: parsed.id,
254 response_model: parsed.model,
255 response_object: parsed.response_type,
256 first_token_ms: None,
257 duration_ms: Some(request_started_at.elapsed().as_millis() as u64),
258 }),
259 };
260
261 crate::telemetry::record_llm_usage(
262 llm_response.usage.prompt_tokens,
263 llm_response.usage.completion_tokens,
264 llm_response.usage.total_tokens,
265 llm_response.stop_reason.as_deref(),
266 );
267
268 Ok(llm_response)
269 }
270 }
271}
272
273#[async_trait]
274impl LlmClient for AnthropicClient {
275 async fn complete(
276 &self,
277 messages: &[Message],
278 system: Option<&str>,
279 tools: &[ToolDefinition],
280 ) -> Result<LlmResponse> {
281 self.send_request(self.build_request(messages, system, tools))
282 .await
283 }
284
285 async fn complete_structured(
286 &self,
287 messages: &[Message],
288 system: Option<&str>,
289 tools: &[ToolDefinition],
290 directive: &structured::StructuredDirective,
291 ) -> Result<LlmResponse> {
292 let mut request_body = self.build_request(messages, system, tools);
293 Self::apply_directive(&mut request_body, directive);
294 self.send_request(request_body).await
295 }
296
297 fn native_structured_support(&self) -> structured::NativeStructuredSupport {
298 structured::NativeStructuredSupport::ForcedTool
299 }
300
301 async fn complete_streaming(
302 &self,
303 messages: &[Message],
304 system: Option<&str>,
305 tools: &[ToolDefinition],
306 cancel_token: CancellationToken,
307 ) -> Result<mpsc::Receiver<StreamEvent>> {
308 self.send_streaming(self.build_request(messages, system, tools), cancel_token)
309 .await
310 }
311
312 async fn complete_streaming_structured(
313 &self,
314 messages: &[Message],
315 system: Option<&str>,
316 tools: &[ToolDefinition],
317 directive: &structured::StructuredDirective,
318 cancel_token: CancellationToken,
319 ) -> Result<mpsc::Receiver<StreamEvent>> {
320 let mut request_body = self.build_request(messages, system, tools);
321 Self::apply_directive(&mut request_body, directive);
322 self.send_streaming(request_body, cancel_token).await
323 }
324}
325
326impl AnthropicClient {
327 async fn send_streaming(
329 &self,
330 mut request_body: serde_json::Value,
331 cancel_token: CancellationToken,
332 ) -> Result<mpsc::Receiver<StreamEvent>> {
333 {
334 let request_started_at = Instant::now();
335 request_body["stream"] = serde_json::json!(true);
336
337 let url = format!("{}/v1/messages", self.base_url);
338
339 let headers = vec![
340 ("x-api-key", self.api_key.expose()),
341 ("anthropic-version", "2023-06-01"),
342 ("anthropic-beta", "prompt-caching-2024-07-31"),
343 ];
344
345 let streaming_resp = crate::retry::with_retry(&self.retry_config, |_attempt| {
346 let http = &self.http;
347 let url = &url;
348 let headers = headers.clone();
349 let request_body = &request_body;
350 let cancel_token = cancel_token.clone();
351 async move {
352 let resp = tokio::select! {
353 _ = cancel_token.cancelled() => {
354 return AttemptOutcome::Fatal(anyhow::anyhow!("HTTP request cancelled"));
355 }
356 result = http.post_streaming(url, headers, request_body, cancel_token.clone()) => {
357 match result {
358 Ok(r) => r,
359 Err(e) => {
360 return if crate::retry::is_transient_error(&e) {
366 AttemptOutcome::Retryable {
367 status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
368 body: format!("network error: {e}"),
369 retry_after: None,
370 }
371 } else {
372 AttemptOutcome::Fatal(anyhow::anyhow!(
373 "HTTP request failed: {}",
374 e
375 ))
376 };
377 }
378 }
379 }
380 };
381 let status = reqwest::StatusCode::from_u16(resp.status)
382 .unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
383 if status.is_success() {
384 AttemptOutcome::Success(resp)
385 } else {
386 let retry_after = resp
387 .retry_after
388 .as_deref()
389 .and_then(|v| RetryConfig::parse_retry_after(Some(v)));
390 if self.retry_config.is_retryable_status(status) {
391 AttemptOutcome::Retryable {
392 status,
393 body: resp.error_body,
394 retry_after,
395 }
396 } else {
397 AttemptOutcome::Fatal(anyhow::anyhow!(
398 "Anthropic API error at {} ({}): {}",
399 url,
400 status,
401 resp.error_body
402 ))
403 }
404 }
405 }
406 })
407 .await?;
408
409 let (tx, rx) = mpsc::channel(100);
410
411 let mut stream = streaming_resp.byte_stream;
412 let provider_name = self.provider_name.clone();
413 let request_model = self.model.clone();
414 let request_url = url.clone();
415 let stream_cancellation = cancel_token.clone();
416 tokio::spawn(async move {
417 let mut buffer = String::new();
418 let mut utf8_decoder = crate::sse::Utf8StreamDecoder::default();
419 let mut content_blocks: Vec<ContentBlock> = Vec::new();
420 let mut text_content = String::new();
421 let mut current_tool_id = String::new();
422 let mut current_tool_name = String::new();
423 let mut current_tool_input = String::new();
424 let mut usage = TokenUsage::default();
425 let mut stop_reason = None;
426 let mut response_id = None;
427 let mut response_model = None;
428 let mut response_object = Some("message".to_string());
429 let mut first_token_ms = None;
430
431 loop {
432 let chunk_result = tokio::select! {
433 biased;
434 _ = stream_cancellation.cancelled() => break,
435 _ = tx.closed() => break,
436 chunk = stream.next() => match chunk {
437 Some(chunk) => chunk,
438 None => break,
439 },
440 };
441 let chunk = match chunk_result {
442 Ok(c) => c,
443 Err(e) => {
444 tracing::error!("Stream error: {}", e);
445 break;
446 }
447 };
448
449 if let Err(error) = utf8_decoder.push_to(&chunk, &mut buffer) {
450 tracing::error!(%error, "Anthropic stream returned invalid UTF-8");
451 break;
452 }
453
454 while let Some(event_end) = buffer.find("\n\n") {
455 let event_data: String = buffer.drain(..event_end).collect();
456 buffer.drain(..2);
457
458 for line in event_data.lines() {
459 if let Some(data) = crate::sse::data_field_value(line) {
460 if data == "[DONE]" {
461 continue;
462 }
463
464 if let Ok(event) =
465 serde_json::from_str::<AnthropicStreamEvent>(data)
466 {
467 match event {
468 AnthropicStreamEvent::ContentBlockStart {
469 index: _,
470 content_block,
471 } => match content_block {
472 AnthropicContentBlock::Text { .. } => {}
473 AnthropicContentBlock::ToolUse { id, name, input } => {
474 if !text_content.is_empty() {
475 content_blocks.push(ContentBlock::Text {
476 text: std::mem::take(&mut text_content),
477 });
478 }
479 current_tool_id = id.clone();
480 current_tool_name = name.clone();
481 current_tool_input =
482 Self::initial_tool_input_json(&input)
483 .unwrap_or_default();
484 let _ = tx
485 .send(StreamEvent::ToolUseStart { id, name })
486 .await;
487 if !current_tool_input.is_empty() {
488 if first_token_ms.is_none() {
489 first_token_ms = Some(
490 request_started_at.elapsed().as_millis()
491 as u64,
492 );
493 }
494 let _ = tx
495 .send(StreamEvent::ToolUseInputDelta {
496 id: Some(current_tool_id.clone()),
497 delta: current_tool_input.clone(),
498 })
499 .await;
500 }
501 }
502 },
503 AnthropicStreamEvent::ContentBlockDelta {
504 index: _,
505 delta,
506 } => match delta {
507 AnthropicDelta::TextDelta { text } => {
508 if first_token_ms.is_none() {
509 first_token_ms = Some(
510 request_started_at.elapsed().as_millis()
511 as u64,
512 );
513 }
514 text_content.push_str(&text);
515 let _ = tx.send(StreamEvent::TextDelta(text)).await;
516 }
517 AnthropicDelta::InputJsonDelta { partial_json } => {
518 if first_token_ms.is_none() {
519 first_token_ms = Some(
520 request_started_at.elapsed().as_millis()
521 as u64,
522 );
523 }
524 current_tool_input.push_str(&partial_json);
525 let _ = tx
526 .send(StreamEvent::ToolUseInputDelta {
527 id: Some(current_tool_id.clone()),
528 delta: partial_json,
529 })
530 .await;
531 }
532 },
533 AnthropicStreamEvent::ContentBlockStop { index: _ }
534 if !current_tool_id.is_empty() =>
535 {
536 let input: serde_json::Value = if current_tool_input
537 .trim()
538 .is_empty()
539 {
540 serde_json::Value::Object(Default::default())
541 } else {
542 serde_json::from_str(¤t_tool_input)
543 .unwrap_or_else(|e| {
544 tracing::warn!(
545 "Failed to parse tool input JSON for tool '{}': {}",
546 current_tool_name, e
547 );
548 serde_json::json!({
549 "__parse_error": format!(
550 "Malformed tool arguments: {}. Raw input: {}",
551 e, ¤t_tool_input
552 )
553 })
554 })
555 };
556 content_blocks.push(ContentBlock::ToolUse {
557 id: current_tool_id.clone(),
558 name: current_tool_name.clone(),
559 input,
560 });
561 current_tool_id.clear();
562 current_tool_name.clear();
563 current_tool_input.clear();
564 }
565 AnthropicStreamEvent::MessageStart { message } => {
566 response_id = message.id;
567 response_model = message.model;
568 response_object = message.message_type;
569 usage.prompt_tokens = message.usage.input_tokens;
570 }
571 AnthropicStreamEvent::MessageDelta {
572 delta,
573 usage: msg_usage,
574 } => {
575 stop_reason = Some(delta.stop_reason);
576 usage.completion_tokens = msg_usage.output_tokens;
577 usage.total_tokens =
578 usage.prompt_tokens + usage.completion_tokens;
579 }
580 AnthropicStreamEvent::MessageStop => {
581 if !text_content.is_empty() {
582 content_blocks.push(ContentBlock::Text {
583 text: std::mem::take(&mut text_content),
584 });
585 }
586 crate::telemetry::record_llm_usage(
587 usage.prompt_tokens,
588 usage.completion_tokens,
589 usage.total_tokens,
590 stop_reason.as_deref(),
591 );
592
593 let response = LlmResponse {
594 message: Message {
595 role: "assistant".to_string(),
596 content: std::mem::take(&mut content_blocks),
597 reasoning_content: None,
598 },
599 usage: usage.clone(),
600 stop_reason: stop_reason.clone(),
601 token_logprobs: Vec::new(),
602 meta: Some(LlmResponseMeta {
603 provider: Some(provider_name.clone()),
604 request_model: Some(request_model.clone()),
605 request_url: Some(request_url.clone()),
606 response_id: response_id.clone(),
607 response_model: response_model.clone(),
608 response_object: response_object.clone(),
609 first_token_ms,
610 duration_ms: Some(
611 request_started_at.elapsed().as_millis()
612 as u64,
613 ),
614 }),
615 };
616 let _ = tx.send(StreamEvent::Done(response)).await;
617 }
618 _ => {}
619 }
620 }
621 }
622 }
623 }
624 }
625 if let Err(error) = utf8_decoder.finish() {
626 tracing::error!(%error, "Anthropic stream ended inside a UTF-8 code point");
627 }
628 });
629
630 Ok(rx)
631 }
632 }
633}
634
635#[derive(Debug, Deserialize)]
637pub(crate) struct AnthropicResponse {
638 #[serde(default)]
639 pub(crate) id: Option<String>,
640 #[serde(default)]
641 pub(crate) model: Option<String>,
642 #[serde(rename = "type", default)]
643 pub(crate) response_type: Option<String>,
644 pub(crate) content: Vec<AnthropicContentBlock>,
645 pub(crate) stop_reason: String,
646 pub(crate) usage: AnthropicUsage,
647}
648
649#[derive(Debug, Deserialize)]
650#[serde(tag = "type")]
651pub(crate) enum AnthropicContentBlock {
652 #[serde(rename = "text")]
653 Text { text: String },
654 #[serde(rename = "tool_use")]
655 ToolUse {
656 id: String,
657 name: String,
658 input: serde_json::Value,
659 },
660}
661
662#[derive(Debug, Deserialize)]
663pub(crate) struct AnthropicUsage {
664 pub(crate) input_tokens: usize,
665 pub(crate) output_tokens: usize,
666 pub(crate) cache_read_input_tokens: Option<usize>,
667 pub(crate) cache_creation_input_tokens: Option<usize>,
668}
669
670#[derive(Debug, Deserialize)]
671#[serde(tag = "type")]
672#[allow(dead_code)]
673pub(crate) enum AnthropicStreamEvent {
674 #[serde(rename = "message_start")]
675 MessageStart { message: AnthropicMessageStart },
676 #[serde(rename = "content_block_start")]
677 ContentBlockStart {
678 index: usize,
679 content_block: AnthropicContentBlock,
680 },
681 #[serde(rename = "content_block_delta")]
682 ContentBlockDelta { index: usize, delta: AnthropicDelta },
683 #[serde(rename = "content_block_stop")]
684 ContentBlockStop { index: usize },
685 #[serde(rename = "message_delta")]
686 MessageDelta {
687 delta: AnthropicMessageDeltaData,
688 usage: AnthropicOutputUsage,
689 },
690 #[serde(rename = "message_stop")]
691 MessageStop,
692 #[serde(rename = "ping")]
693 Ping,
694 #[serde(rename = "error")]
695 Error { error: AnthropicError },
696}
697
698#[derive(Debug, Deserialize)]
699pub(crate) struct AnthropicMessageStart {
700 #[serde(default)]
701 pub(crate) id: Option<String>,
702 #[serde(default)]
703 pub(crate) model: Option<String>,
704 #[serde(rename = "type", default)]
705 pub(crate) message_type: Option<String>,
706 pub(crate) usage: AnthropicUsage,
707}
708
709#[derive(Debug, Deserialize)]
710#[serde(tag = "type")]
711pub(crate) enum AnthropicDelta {
712 #[serde(rename = "text_delta")]
713 TextDelta { text: String },
714 #[serde(rename = "input_json_delta")]
715 InputJsonDelta { partial_json: String },
716}
717
718#[derive(Debug, Deserialize)]
719pub(crate) struct AnthropicMessageDeltaData {
720 pub(crate) stop_reason: String,
721}
722
723#[derive(Debug, Deserialize)]
724pub(crate) struct AnthropicOutputUsage {
725 pub(crate) output_tokens: usize,
726}
727
728#[derive(Debug, Deserialize)]
729#[allow(dead_code)]
730pub(crate) struct AnthropicError {
731 #[serde(rename = "type")]
732 pub(crate) error_type: String,
733 pub(crate) message: String,
734}
735
736#[cfg(test)]
741mod tests {
742 use super::*;
743 use crate::llm::types::{Message, ToolDefinition};
744
745 fn make_client() -> AnthropicClient {
746 AnthropicClient::new("test-key".to_string(), "claude-opus-4-6".to_string())
747 }
748
749 #[test]
750 fn test_build_request_basic() {
751 let client = make_client();
752 let messages = vec![Message::user("Hello")];
753 let req = client.build_request(&messages, None, &[]);
754
755 assert_eq!(req["model"], "claude-opus-4-6");
756 assert_eq!(req["max_tokens"], DEFAULT_MAX_TOKENS);
757 assert!(req["thinking"].is_null());
758 }
759
760 #[test]
761 fn test_build_request_with_thinking_budget() {
762 let client = make_client().with_thinking_budget(10_000);
763 let messages = vec![Message::user("Think carefully.")];
764 let req = client.build_request(&messages, None, &[]);
765
766 assert_eq!(req["thinking"]["type"], "enabled");
768 assert_eq!(req["thinking"]["budget_tokens"], 10_000);
769 assert_eq!(req["temperature"], 1.0_f64);
771 }
772
773 #[test]
774 fn test_build_request_thinking_overrides_temperature() {
775 let client = make_client()
777 .with_temperature(0.5)
778 .with_thinking_budget(5_000);
779 let messages = vec![Message::user("Test")];
780 let req = client.build_request(&messages, None, &[]);
781
782 assert_eq!(req["temperature"], 1.0_f64);
783 assert_eq!(req["thinking"]["budget_tokens"], 5_000);
784 }
785
786 #[test]
787 fn test_build_request_no_thinking_uses_temperature() {
788 let client = make_client().with_temperature(0.7);
789 let messages = vec![Message::user("Test")];
790 let req = client.build_request(&messages, None, &[]);
791
792 let temp = req["temperature"].as_f64().unwrap();
794 assert!((temp - 0.7).abs() < 0.01);
795 assert!(req["thinking"].is_null());
796 }
797
798 #[test]
799 fn test_build_request_with_system_prompt() {
800 let client = make_client();
801 let messages = vec![Message::user("Hello")];
802 let req = client.build_request(&messages, Some("You are helpful."), &[]);
803
804 let system = &req["system"];
805 assert!(system.is_array());
806 assert_eq!(system[0]["type"], "text");
807 assert_eq!(system[0]["text"], "You are helpful.");
808 assert!(system[0]["cache_control"].is_object());
809 }
810
811 #[test]
812 fn test_build_request_with_tools() {
813 let client = make_client();
814 let messages = vec![Message::user("Use a tool")];
815 let tools = vec![ToolDefinition {
816 name: "read_file".to_string(),
817 description: "Read a file".to_string(),
818 parameters: serde_json::json!({"type": "object", "properties": {}}),
819 }];
820 let req = client.build_request(&messages, None, &tools);
821
822 assert!(req["tools"].is_array());
823 assert_eq!(req["tools"][0]["name"], "read_file");
824 assert!(req["tools"][0]["cache_control"].is_object());
826 }
827
828 #[test]
829 fn test_build_request_thinking_budget_sets_max_tokens() {
830 let client = make_client()
832 .with_max_tokens(16_000)
833 .with_thinking_budget(8_000);
834 let messages = vec![Message::user("Test")];
835 let req = client.build_request(&messages, None, &[]);
836
837 assert_eq!(req["max_tokens"], 16_000);
838 assert_eq!(req["thinking"]["budget_tokens"], 8_000);
839 }
840
841 #[test]
842 fn test_apply_directive_forces_tool_choice() {
843 let mut req = serde_json::json!({ "model": "m", "messages": [] });
844 let directive = structured::StructuredDirective {
845 force_tool: Some("emit_person".to_string()),
846 response_format: None,
847 };
848 AnthropicClient::apply_directive(&mut req, &directive);
849 assert_eq!(req["tool_choice"]["type"], "tool");
850 assert_eq!(req["tool_choice"]["name"], "emit_person");
851 }
852
853 #[test]
854 fn test_apply_directive_ignores_response_format() {
855 let mut req = serde_json::json!({ "model": "m" });
858 AnthropicClient::apply_directive(
859 &mut req,
860 &structured::StructuredDirective {
861 force_tool: None,
862 response_format: Some(structured::ResponseFormat::JsonObject),
863 },
864 );
865 assert!(req.get("response_format").is_none());
866 assert!(req.get("tool_choice").is_none());
867 }
868
869 #[test]
870 fn test_native_structured_support_is_forced_tool() {
871 assert_eq!(
872 make_client().native_structured_support(),
873 structured::NativeStructuredSupport::ForcedTool
874 );
875 }
876}