1#[cfg(feature = "bedrock")]
47mod bedrock;
48mod client;
49mod format;
50mod stream;
51
52use std::fmt;
53use std::sync::{Arc, Mutex, PoisonError, RwLock};
54use std::time::Duration;
55
56use async_trait::async_trait;
57use futures::StreamExt;
58
59use self::anthropic_model_options_builder::IsComplete;
60#[cfg(feature = "bedrock")]
61pub use self::bedrock::AnthropicBedrockConfig;
62use self::client::{
63 AnthropicClient, ApiVersion, ClientRequest, HttpAnthropicClient, header_values, resolve_api_version,
64};
65use self::format::{FormatOptions, Formatter, from_last_compaction, is_tool_forced, validate_anthropic_tools};
66use self::stream::{MessageAccumulator, ResponseState, UsageCounters, format_compaction_usage, stream_usage};
67use super::defaults::{MODEL_DEFAULTS, default_max_tokens_warning_message, default_model_warning_message};
68use super::http::{HttpError, RedactedHeaders, read_env};
69use super::model_info::{accepts_mime_type, lookup_model_info};
70use super::native_output::to_native_output_schema;
71use super::native_output::{StructuredOutputMechanism, handle_rejected_mechanism, structured_output_mechanisms};
72use super::streaming::{
73 ANTHROPIC_REASONING_PROVIDER, ModelMessageStopEvent, ModelMetadataEvent, ModelStreamEvent, Usage,
74 tag_signed_reasoning,
75};
76use super::thinking_binding::{is_thinking_binding_error, thinking_with_drop_block};
77use super::{
78 BaseModelConfig, BoxStream, CacheConfig, CountTokensOptions, Model, ModelCapabilities, ModelInfo, ModelRequest,
79 SummarizeOptions, SummarizeResult, base_model_info, estimate_tokens, resolve_config_metadata, resolve_max_tokens,
80 summarize_client_side,
81};
82use crate::error::{ContextWindowOverflowError, Error, ModelError, ModelNetworkError, ModelThrottledError, Result};
83use crate::logging::warn_once;
84use crate::types::{ContentBlock, JsonObject, JsonValue, Message, StopReason, SummaryBlock, ToolChoice};
85
86const CONTEXT_WINDOW_OVERFLOW_ERRORS: [&str; 6] = [
88 "prompt is too long",
89 "max_tokens exceeded",
90 "input too long",
91 "input is too long",
92 "input length exceeds context window",
93 "input and output tokens exceed your context limit",
94];
95
96const MAX_PAUSE_TURN_CONTINUATIONS: u32 = 10;
98
99const TURN_SCOPED_SYSTEM_BETA: &str = "mid-conversation-system-clear-at-2026-08-21";
101
102const COMPACTION_BETA: &str = "compact-2026-09-04";
104
105#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
108pub struct AnthropicModelConfig {
109 #[builder(into)]
112 pub model_id: Option<String>,
113 pub max_tokens: Option<u64>,
116 pub temperature: Option<f64>,
118 pub top_p: Option<f64>,
120 pub context_window_limit: Option<u64>,
122 pub model_info: Option<ModelInfo>,
124 pub stop_sequences: Option<Vec<String>>,
126 pub params: Option<JsonValue>,
132 pub anthropic_tools: Option<Vec<JsonValue>>,
137 pub betas: Option<Vec<String>>,
140 pub use_native_token_count: Option<bool>,
143 pub cache_config: Option<CacheConfig>,
147}
148
149impl AnthropicModelConfig {
150 pub fn merge(&mut self, update: Self) {
152 let Self {
153 model_id,
154 max_tokens,
155 temperature,
156 top_p,
157 context_window_limit,
158 model_info,
159 stop_sequences,
160 params,
161 anthropic_tools,
162 betas,
163 use_native_token_count,
164 cache_config,
165 } = update;
166 self.model_id = model_id.or(self.model_id.take());
167 self.max_tokens = max_tokens.or(self.max_tokens);
168 self.temperature = temperature.or(self.temperature);
169 self.top_p = top_p.or(self.top_p);
170 self.context_window_limit = context_window_limit.or(self.context_window_limit);
171 self.model_info = model_info.or(self.model_info.take());
172 self.stop_sequences = stop_sequences.or(self.stop_sequences.take());
173 self.params = params.or(self.params.take());
174 self.anthropic_tools = anthropic_tools.or(self.anthropic_tools.take());
175 self.betas = betas.or(self.betas.take());
176 self.use_native_token_count = use_native_token_count.or(self.use_native_token_count);
177 self.cache_config = cache_config.or(self.cache_config.take());
178 }
179
180 #[must_use]
182 pub fn to_base(&self) -> BaseModelConfig {
183 BaseModelConfig {
184 model_id: self.model_id.clone(),
185 max_tokens: self.max_tokens,
186 temperature: self.temperature,
187 top_p: self.top_p,
188 context_window_limit: self.context_window_limit,
189 model_info: self.model_info.clone(),
190 }
191 }
192}
193
194impl From<BaseModelConfig> for AnthropicModelConfig {
195 fn from(config: BaseModelConfig) -> Self {
196 Self {
197 model_id: config.model_id,
198 max_tokens: config.max_tokens,
199 temperature: config.temperature,
200 top_p: config.top_p,
201 context_window_limit: config.context_window_limit,
202 model_info: config.model_info,
203 ..Self::default()
204 }
205 }
206}
207
208#[derive(Clone, Default, PartialEq, Eq, bon::Builder)]
213pub struct AnthropicClientConfig {
214 #[builder(into)]
216 pub base_url: Option<String>,
217 #[builder(default)]
222 pub default_headers: Vec<(String, String)>,
223 pub max_retries: Option<u32>,
225 pub timeout: Option<Duration>,
227}
228
229impl fmt::Debug for AnthropicClientConfig {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 f.debug_struct("AnthropicClientConfig")
232 .field("base_url", &self.base_url)
233 .field("default_headers", &RedactedHeaders(&self.default_headers))
234 .field("max_retries", &self.max_retries)
235 .field("timeout", &self.timeout)
236 .finish()
237 }
238}
239
240#[derive(Clone, Default, PartialEq, bon::Builder)]
246#[builder(finish_fn = build_options)]
247pub struct AnthropicModelOptions {
248 #[builder(into)]
250 pub model_id: Option<String>,
251 pub max_tokens: Option<u64>,
253 pub temperature: Option<f64>,
255 pub top_p: Option<f64>,
257 pub context_window_limit: Option<u64>,
259 pub model_info: Option<ModelInfo>,
261 pub stop_sequences: Option<Vec<String>>,
263 pub params: Option<JsonValue>,
265 pub anthropic_tools: Option<Vec<JsonValue>>,
267 pub betas: Option<Vec<String>>,
269 pub use_native_token_count: Option<bool>,
271 pub cache_config: Option<CacheConfig>,
273 #[builder(into)]
275 pub api_key: Option<String>,
276 pub client_config: Option<AnthropicClientConfig>,
278}
279
280impl fmt::Debug for AnthropicModelOptions {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.debug_struct("AnthropicModelOptions")
283 .field("config", &self.clone().into_parts().0)
284 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
285 .field("client_config", &self.client_config)
286 .finish()
287 }
288}
289
290impl AnthropicModelOptions {
291 fn into_parts(self) -> (AnthropicModelConfig, Option<String>, AnthropicClientConfig) {
292 let config = AnthropicModelConfig {
293 model_id: self.model_id,
294 max_tokens: self.max_tokens,
295 temperature: self.temperature,
296 top_p: self.top_p,
297 context_window_limit: self.context_window_limit,
298 model_info: self.model_info,
299 stop_sequences: self.stop_sequences,
300 params: self.params,
301 anthropic_tools: self.anthropic_tools,
302 betas: self.betas,
303 use_native_token_count: self.use_native_token_count,
304 cache_config: self.cache_config,
305 };
306 (config, self.api_key, self.client_config.unwrap_or_default())
307 }
308}
309
310impl From<AnthropicModelConfig> for AnthropicModelOptions {
311 fn from(config: AnthropicModelConfig) -> Self {
312 let AnthropicModelConfig {
313 model_id,
314 max_tokens,
315 temperature,
316 top_p,
317 context_window_limit,
318 model_info,
319 stop_sequences,
320 params,
321 anthropic_tools,
322 betas,
323 use_native_token_count,
324 cache_config,
325 } = config;
326 Self {
327 model_id,
328 max_tokens,
329 temperature,
330 top_p,
331 context_window_limit,
332 model_info,
333 stop_sequences,
334 params,
335 anthropic_tools,
336 betas,
337 use_native_token_count,
338 cache_config,
339 ..Self::default()
340 }
341 }
342}
343
344impl<S: IsComplete> AnthropicModelOptionsBuilder<S> {
345 pub fn build(self) -> Result<AnthropicModel> {
351 AnthropicModel::new(self.build_options())
352 }
353}
354
355#[derive(Clone)]
360pub struct AnthropicModel {
361 inner: Arc<Inner>,
362}
363
364impl fmt::Debug for AnthropicModel {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 f.debug_struct("AnthropicModel")
367 .field("config", &self.inner.config())
368 .finish_non_exhaustive()
369 }
370}
371
372struct Inner {
373 config: RwLock<AnthropicModelConfig>,
374 client: Arc<dyn AnthropicClient>,
375 client_betas: Vec<String>,
377 api_version: Option<ApiVersion>,
379 bedrock_runtime: bool,
381 drop_stale_thinking_model_id: Mutex<Option<String>>,
383}
384
385impl AnthropicModel {
386 pub fn builder() -> AnthropicModelOptionsBuilder {
388 AnthropicModelOptions::builder()
389 }
390
391 pub fn new(options: impl Into<AnthropicModelOptions>) -> Result<Self> {
401 Self::with_env(options.into(), &|name| std::env::var(name).ok())
402 }
403
404 fn with_env(options: AnthropicModelOptions, env: &dyn Fn(&str) -> Option<String>) -> Result<Self> {
405 let env = |name: &str| read_env(env, name);
406 let (config, api_key, client_config) = options.into_parts();
407 let config = prepare_config(config)?;
408 let api_key = api_key
409 .filter(|key| !key.is_empty())
410 .or_else(|| env("ANTHROPIC_API_KEY"))
411 .ok_or_else(|| {
412 Error::other(
413 "Anthropic API key is required. Provide it via the 'api_key' option or set the ANTHROPIC_API_KEY environment variable.",
414 )
415 })?;
416 let custom_headers = env("ANTHROPIC_CUSTOM_HEADERS");
417 let client = HttpAnthropicClient::new(
418 &api_key,
419 &client_config,
420 env("ANTHROPIC_BASE_URL"),
421 custom_headers.as_deref(),
422 )
423 .map_err(|error| Error::from(ModelError::new(error.to_string()).with_source(error)))?;
424 let api_version = resolve_api_version(&client_config, custom_headers.as_deref());
425 Ok(Self::from_parts(
426 config,
427 Arc::new(client),
428 client_betas(&client_config),
429 Some(api_version),
430 ))
431 }
432
433 fn from_parts(
434 config: AnthropicModelConfig,
435 client: Arc<dyn AnthropicClient>,
436 client_betas: Vec<String>,
437 api_version: Option<ApiVersion>,
438 ) -> Self {
439 Self::from_client(config, client, client_betas, api_version, false)
440 }
441
442 fn from_client(
443 config: AnthropicModelConfig,
444 client: Arc<dyn AnthropicClient>,
445 client_betas: Vec<String>,
446 api_version: Option<ApiVersion>,
447 bedrock_runtime: bool,
448 ) -> Self {
449 Self {
450 inner: Arc::new(Inner {
451 config: RwLock::new(config),
452 client,
453 client_betas,
454 api_version,
455 bedrock_runtime,
456 drop_stale_thinking_model_id: Mutex::new(None),
457 }),
458 }
459 }
460
461 #[must_use]
464 pub fn config(&self) -> AnthropicModelConfig {
465 self.inner.resolved_config()
466 }
467
468 pub fn update_config(&self, config: impl Into<AnthropicModelConfig>) -> Result<()> {
476 let config = config.into();
477 validate_json_fields(&config)?;
478 self.inner.write_config().merge(config);
479 Ok(())
480 }
481}
482
483fn prepare_config(mut config: AnthropicModelConfig) -> Result<AnthropicModelConfig> {
485 validate_json_fields(&config)?;
486 let default_model_id = MODEL_DEFAULTS.anthropic.model_id;
487 if config.model_id.is_none() {
488 warn_once(&default_model_warning_message(default_model_id));
489 config.model_id = Some(default_model_id.to_owned());
490 }
491 let pinned_by_info = config
492 .model_info
493 .as_ref()
494 .is_some_and(|info| info.limits.max_output_tokens.is_some());
495 if config.max_tokens.is_none() && !pinned_by_info {
496 warn_once(&default_max_tokens_warning_message(resolved_max_tokens(&config)));
497 }
498 Ok(config)
499}
500
501fn validate_json_fields(config: &AnthropicModelConfig) -> Result<()> {
503 if config.params.as_ref().is_some_and(|params| !params.is_object()) {
504 return Err(Error::other("'params' must be a JSON object"));
505 }
506 if let Some(tools) = &config.anthropic_tools {
507 validate_anthropic_tools(tools)?;
508 }
509 Ok(())
510}
511
512fn client_betas(config: &AnthropicClientConfig) -> Vec<String> {
514 header_values(&config.default_headers, "anthropic-beta")
515 .into_iter()
516 .flat_map(|value| value.split(','))
517 .map(str::trim)
518 .filter(|beta| !beta.is_empty())
519 .map(str::to_owned)
520 .collect()
521}
522
523fn model_id_of(config: &AnthropicModelConfig) -> &str {
524 config.model_id.as_deref().unwrap_or(MODEL_DEFAULTS.anthropic.model_id)
525}
526
527fn resolved_max_tokens(config: &AnthropicModelConfig) -> u64 {
530 resolve_max_tokens(&config.to_base(), model_id_of(config))
531 .or(MODEL_DEFAULTS.anthropic.max_tokens)
532 .unwrap_or(64_000)
533}
534
535fn resolve(config: &AnthropicModelConfig) -> AnthropicModelConfig {
537 let base = resolve_config_metadata(config.to_base(), model_id_of(config));
538 AnthropicModelConfig {
539 model_id: Some(model_id_of(config).to_owned()),
540 max_tokens: Some(resolved_max_tokens(config)),
541 context_window_limit: base.context_window_limit,
542 ..config.clone()
543 }
544}
545
546const SENDABLE_MIME_TYPES: [&str; 9] = [
550 "image/png",
551 "image/jpeg",
552 "image/gif",
553 "image/webp",
554 "application/pdf",
555 "text/csv",
556 "text/html",
557 "text/markdown",
558 "text/plain",
559];
560
561fn sendable_mime_types(shared: &ModelInfo) -> Vec<String> {
564 let as_text: &[&str] = if accepts_mime_type(shared, "text/plain") {
565 &["application/json", "application/xml"]
566 } else {
567 &[]
568 };
569 SENDABLE_MIME_TYPES
570 .into_iter()
571 .filter(|mime_type| accepts_mime_type(shared, mime_type))
572 .chain(as_text.iter().copied())
573 .map(str::to_owned)
574 .collect()
575}
576
577fn model_info_of(config: &AnthropicModelConfig) -> ModelInfo {
578 let resolved = resolve(config).to_base();
579 let shared = lookup_model_info(model_id_of(config));
580 let provider = ModelInfo {
581 capabilities: ModelCapabilities {
582 temporary_messages: shared.capabilities.temporary_messages,
583 deferred_tool_loading: shared.capabilities.deferred_tool_loading,
584 accepted_mime_types: Some(sendable_mime_types(&shared)),
585 reasoning_provider: Some(ANTHROPIC_REASONING_PROVIDER.to_owned()),
587 ..ModelCapabilities::default()
588 },
589 ..ModelInfo::default()
590 };
591 ModelInfo::merge([
592 Some(&base_model_info(&resolved)),
593 Some(&provider),
594 config.model_info.as_ref(),
595 ])
596}
597
598enum AttemptError {
600 Http(HttpError),
601 Sdk(Error),
602}
603
604struct AttemptFailure {
605 error: AttemptError,
606 continuations: u32,
607 thinking: Option<JsonValue>,
608 tool_forced: bool,
609}
610
611impl AttemptError {
612 fn message(&self) -> String {
613 match self {
614 Self::Http(error) => error.message().to_owned(),
615 Self::Sdk(error) => error.to_string(),
616 }
617 }
618
619 fn status(&self) -> Option<u16> {
620 match self {
621 Self::Http(error) => error.status_code(),
622 Self::Sdk(_) => None,
623 }
624 }
625
626 fn api_message(&self) -> String {
629 let Self::Http(error) = self else {
630 return self.message();
631 };
632 error
633 .body()
634 .and_then(|body| body.get("error"))
635 .and_then(|error| error.get("message"))
636 .and_then(JsonValue::as_str)
637 .map_or_else(|| self.message(), str::to_owned)
638 }
639}
640
641const BEDROCK_THROTTLING_EVENTS: [&str; 2] = ["throttlingException", "serviceUnavailableException"];
643
644fn is_throttle(error: &HttpError) -> bool {
645 error.status_code() == Some(429)
646 || error
647 .body()
648 .and_then(|body| body.get("type"))
649 .and_then(JsonValue::as_str)
650 .is_some_and(|kind| BEDROCK_THROTTLING_EVENTS.contains(&kind))
651}
652
653fn translate_error(error: AttemptError) -> Error {
655 let message = error.message();
656 let lowered = message.to_lowercase();
657 if CONTEXT_WINDOW_OVERFLOW_ERRORS
658 .iter()
659 .any(|phrase| lowered.contains(phrase))
660 {
661 return ContextWindowOverflowError::new(message).into();
662 }
663 match error {
664 AttemptError::Http(error) if is_throttle(&error) => {
665 tracing::debug!("throttled | error_message=<{message}>");
666 ModelThrottledError::new(message).with_source(error).into()
667 }
668 AttemptError::Http(error) if error.is_network() => ModelNetworkError::new(message).with_source(error).into(),
669 AttemptError::Http(error) => ModelError::new(message).with_source(error).into(),
670 AttemptError::Sdk(error) => error,
671 }
672}
673
674fn with_native_output(request: &mut JsonObject, schema: &JsonValue) -> Result<()> {
675 let schema = to_native_output_schema(schema)?;
676 request.insert("tool_choice".to_owned(), serde_json::json!({"type": "none"}));
677 let mut output_config = request
678 .get("output_config")
679 .and_then(JsonValue::as_object)
680 .cloned()
681 .unwrap_or_default();
682 output_config.insert(
683 "format".to_owned(),
684 serde_json::json!({"type": "json_schema", "schema": schema}),
685 );
686 request.insert("output_config".to_owned(), JsonValue::Object(output_config));
687 Ok(())
688}
689
690impl Inner {
691 fn config(&self) -> AnthropicModelConfig {
692 self.config.read().unwrap_or_else(PoisonError::into_inner).clone()
693 }
694
695 fn write_config(&self) -> std::sync::RwLockWriteGuard<'_, AnthropicModelConfig> {
696 self.config.write().unwrap_or_else(PoisonError::into_inner)
697 }
698
699 fn resolved_config(&self) -> AnthropicModelConfig {
700 resolve(&self.config())
701 }
702
703 fn drops_stale_thinking(&self, config: &AnthropicModelConfig) -> bool {
704 let model_id = self
705 .drop_stale_thinking_model_id
706 .lock()
707 .unwrap_or_else(PoisonError::into_inner);
708 model_id.is_some() && model_id.as_deref() == config.model_id.as_deref()
709 }
710
711 fn formatter<'a>(&'a self, config: &'a AnthropicModelConfig) -> Formatter<'a> {
712 Formatter {
713 config,
714 model_info: model_info_of(config),
715 api_version: self.api_version.as_ref(),
716 bedrock_runtime: self.bedrock_runtime,
717 drops_stale_thinking: self.drops_stale_thinking(config),
718 client_betas: &self.client_betas,
719 max_tokens: resolved_max_tokens(config),
720 }
721 }
722
723 fn structured_output_mechanism(&self, request: &ModelRequest) -> Option<StructuredOutputMechanism> {
725 let schema = request.structured_output_schema.as_ref()?;
726 let config = self.config();
727 let model_id = config.model_id.as_deref().filter(|id| !id.is_empty())?;
728 structured_output_mechanisms(
729 "anthropic",
730 model_id,
731 request.tool_choice.as_ref(),
732 schema,
733 &model_info_of(&config),
734 )
735 .first()
736 .copied()
737 }
738
739 fn record_rejected_mechanism(
742 &self,
743 error: &AttemptError,
744 mechanism: Option<StructuredOutputMechanism>,
745 request: &ModelRequest,
746 ) -> bool {
747 let config = self.config();
748 let (Some(mechanism), Some(schema), Some(model_id)) = (
749 mechanism,
750 request.structured_output_schema.as_ref(),
751 config.model_id.as_deref().filter(|id| !id.is_empty()),
752 ) else {
753 return false;
754 };
755 error.status() == Some(400)
756 && handle_rejected_mechanism("anthropic", model_id, mechanism, schema, &error.api_message())
757 }
758
759 fn prepare(
761 &self,
762 request: &ModelRequest,
763 mechanism: Option<StructuredOutputMechanism>,
764 ) -> Result<(JsonObject, Option<String>)> {
765 let config = self.config();
766 let formatter = self.formatter(&config);
767 let forces_auto = matches!(
768 mechanism,
769 Some(StructuredOutputMechanism::Native | StructuredOutputMechanism::Auto)
770 );
771 let options = FormatOptions {
772 system_prompt: request.system_prompt.as_ref(),
773 tool_specs: &request.tool_specs,
774 tool_choice: if forces_auto {
775 Some(&ToolChoice::Auto)
776 } else {
777 request.tool_choice.as_ref()
778 },
779 dynamic_trailing_blocks: request.dynamic_trailing_blocks.unwrap_or_default(),
780 deferred_tools: Some(&request.deferred_tools),
781 };
782 let mut body = formatter.format_request(&request.messages, &options)?;
783 if let (Some(StructuredOutputMechanism::Native), Some(schema)) =
784 (mechanism, request.structured_output_schema.as_ref())
785 {
786 with_native_output(&mut body, schema)?;
787 }
788 let beta = formatter.request_beta(&body, &formatter.compaction_betas(&request.messages));
789 Ok((body, beta))
790 }
791
792 fn stream(self: Arc<Self>, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
795 Box::pin(async_stream::stream! {
796 let mut latched_over = None;
798 loop {
799 let mechanism = self.structured_output_mechanism(&request);
800 let mut attempt = Arc::clone(&self).attempt(request.clone(), mechanism);
801 let mut failure = None;
802 while let Some(item) = attempt.next().await {
803 match item {
804 Ok(event) => {
805 latched_over = None;
806 yield Ok(event);
807 }
808 Err(error) => {
809 failure = Some(error);
810 break;
811 }
812 }
813 }
814 drop(attempt);
815 let Some(failure) = failure else {
816 return;
817 };
818 if let Some(previous) = self.retry_with_drop_block(&failure) {
819 latched_over = Some(previous);
820 continue;
821 }
822 if failure.continuations == 0
825 && self.record_rejected_mechanism(&failure.error, mechanism, &request)
826 {
827 continue;
828 }
829 if let Some(previous) = latched_over {
831 *self.drop_stale_thinking_model_id.lock().unwrap_or_else(PoisonError::into_inner) = previous;
832 }
833 yield Err(translate_error(failure.error));
834 return;
835 }
836 })
837 }
838
839 fn retry_with_drop_block(&self, failure: &AttemptFailure) -> Option<Option<String>> {
843 let binding = failure.continuations == 0
844 && failure.error.status() == Some(400)
845 && is_thinking_binding_error(&failure.error.message())
846 && thinking_with_drop_block(failure.thinking.as_ref(), failure.tool_forced).is_some();
847 if !binding {
848 return None;
849 }
850 let model_id = self.config().model_id;
851 tracing::warn!(
852 "model_id=<{}> | history edit invalidated replayed thinking blocks, retrying with drop_block",
853 model_id.as_deref().unwrap_or_default()
854 );
855 let mut latched = self
856 .drop_stale_thinking_model_id
857 .lock()
858 .unwrap_or_else(PoisonError::into_inner);
859 Some(std::mem::replace(&mut latched, model_id))
860 }
861
862 fn attempt(
865 self: Arc<Self>,
866 request: ModelRequest,
867 mechanism: Option<StructuredOutputMechanism>,
868 ) -> BoxStream<'static, std::result::Result<ModelStreamEvent, AttemptFailure>> {
869 Box::pin(async_stream::stream! {
870 let model_id = model_id_of(&self.config()).to_owned();
871 let (mut body, beta) = match self.prepare(&request, mechanism) {
872 Ok(prepared) => prepared,
873 Err(error) => {
874 yield Err(AttemptFailure { error: AttemptError::Sdk(error), continuations: 0, thinking: None, tool_forced: false });
875 return;
876 }
877 };
878 let thinking = body.get("thinking").cloned();
879 let tool_forced = is_tool_forced(&body);
880 let mut continuations = 0;
881 let mut total = UsageCounters::default();
882 loop {
883 let client_request = ClientRequest { body: JsonValue::Object(body.clone()), beta: beta.clone() };
884 let mut events = self.client.stream(client_request);
885 let mut state = ResponseState::default();
886 while let Some(event) = events.next().await {
887 let event = match event {
888 Ok(event) => event,
889 Err(error) => {
890 yield Err(AttemptFailure { error: AttemptError::Http(error), continuations, thinking: thinking.clone(), tool_forced });
891 return;
892 }
893 };
894 for output in state.handle(&event, continuations == 0) {
895 yield Ok(tag_signed_reasoning(output, ANTHROPIC_REASONING_PROVIDER, &model_id));
896 }
897 }
898 drop(events);
899 if !state.stopped {
902 return;
903 }
904 add_response_usage(&mut total, &state.usage);
905 if state.stop_reason == StopReason::PauseTurn {
906 if continuations >= MAX_PAUSE_TURN_CONTINUATIONS {
907 let error = ModelError::new(format!(
908 "server-side tool turn did not complete after {continuations} continuations"
909 ));
910 yield Err(AttemptFailure { error: AttemptError::Sdk(error.into()), continuations, thinking: thinking.clone(), tool_forced });
911 return;
912 }
913 continuations += 1;
914 let paused = serde_json::json!({"role": "assistant", "content": state.message.content()});
915 if let Some(JsonValue::Array(messages)) = body.get_mut("messages") {
916 messages.push(paused);
917 }
918 tracing::debug!("continuation=<{continuations}> | resuming paused server-side tool turn");
919 continue;
920 }
921 yield Ok(ModelMetadataEvent::new().with_usage(stream_usage(total)).into());
922 yield Ok(ModelMessageStopEvent::new(state.stop_reason).into());
923 return;
924 }
925 })
926 }
927
928 async fn count_tokens(&self, messages: &[Message], options: CountTokensOptions) -> Result<u64> {
929 let config = self.config();
930 let formatter = self.formatter(&config);
931 let compacted;
933 let messages = if formatter.server_side_summary() {
934 compacted = from_last_compaction(messages);
935 compacted.as_slice()
936 } else {
937 messages
938 };
939 if config.use_native_token_count != Some(true) {
940 return Ok(estimate_tokens(messages, &options));
941 }
942 let format_options = FormatOptions {
943 system_prompt: options.system_prompt.as_ref(),
944 tool_specs: &options.tool_specs,
945 ..FormatOptions::default()
946 };
947 let request = match formatter.format_request(messages, &format_options) {
948 Ok(request) => request,
949 Err(error) => {
950 tracing::debug!("error=<{error}> | native token counting failed, falling back to estimation");
951 return Ok(estimate_tokens(messages, &options));
952 }
953 };
954 let mut params = JsonObject::new();
955 for key in ["model", "messages", "system", "tools", "tool_choice"] {
956 if let Some(value) = request.get(key) {
957 params.insert(key.to_owned(), value.clone());
958 }
959 }
960 let beta = formatter.request_beta(&request, &formatter.compaction_betas(messages));
961 let client_request = ClientRequest {
962 body: JsonValue::Object(params),
963 beta,
964 };
965 let Some(response) = self.client.count_tokens(client_request) else {
967 return Ok(estimate_tokens(messages, &options));
968 };
969 let counted = response.await.map_err(|error| error.to_string()).and_then(|body| {
970 body.get("input_tokens")
971 .and_then(JsonValue::as_u64)
972 .ok_or_else(|| "response has no input_tokens".to_owned())
973 });
974 match counted {
975 Ok(tokens) => {
976 tracing::debug!("total_tokens=<{tokens}> | native token count");
977 Ok(tokens)
978 }
979 Err(error) => {
980 tracing::debug!("error=<{error}> | native token counting failed, falling back to estimation");
981 Ok(estimate_tokens(messages, &options))
982 }
983 }
984 }
985
986 async fn compact(&self, messages: &[Message], options: &SummarizeOptions) -> Result<SummarizeResult> {
989 let config = self.config();
990 let formatter = self.formatter(&config);
991 let model_id = formatter.model_id().to_owned();
992 let format_options = FormatOptions {
993 system_prompt: options.system_prompt.as_ref(),
994 tool_specs: &options.tool_specs,
995 deferred_tools: Some(&options.deferred_tools),
996 ..FormatOptions::default()
997 };
998 let mut params = formatter.format_request(messages, &format_options)?;
999 let beta = formatter.request_beta(¶ms, &[COMPACTION_BETA]);
1000 params.shift_remove("stop_sequences");
1002 params.shift_remove("context_management");
1003 let mut compaction = serde_json::json!({"type": "summarize"});
1004 if let (Some(instructions), JsonValue::Object(map)) = (
1005 options
1006 .instructions
1007 .as_ref()
1008 .filter(|instructions| !instructions.is_empty()),
1009 &mut compaction,
1010 ) {
1011 map.insert("instructions".to_owned(), instructions.clone().into());
1012 }
1013 params.insert("compaction".to_owned(), compaction);
1014 let client_request = ClientRequest {
1015 body: JsonValue::Object(params),
1016 beta,
1017 };
1018 let Some(mut events) = self.client.beta_stream(client_request) else {
1020 tracing::warn!("model_id=<{model_id}> | client has no beta messages API | summarizing client-side");
1021 return Ok(SummarizeResult::new(Vec::new()));
1022 };
1023 let mut response = MessageAccumulator::default();
1024 while let Some(event) = events.next().await {
1025 match event {
1026 Ok(event) => response.apply(&event),
1027 Err(error) if error.is_api_error() => {
1028 tracing::warn!(
1029 "model_id=<{model_id}>, error=<{error}> | compaction request failed | summarizing client-side"
1030 );
1031 return Ok(SummarizeResult::new(Vec::new()));
1032 }
1033 Err(error) => return Err(translate_error(AttemptError::Http(error))),
1034 }
1035 }
1036 let usage = response.usage().map(|usage| format_compaction_usage(&usage));
1037 let with_usage = |result: SummarizeResult| match usage {
1038 Some(usage) => result.with_usage(usage),
1039 None => result,
1040 };
1041 let block = response
1042 .content()
1043 .iter()
1044 .find(|block| block.get("type").and_then(JsonValue::as_str) == Some("compaction"));
1045 let text = block
1046 .and_then(|block| block.get("content"))
1047 .and_then(JsonValue::as_str)
1048 .filter(|text| !text.is_empty());
1049 let (Some("compaction"), Some(text), Some(block)) = (response.stop_reason(), text, block) else {
1050 tracing::debug!(
1051 "model_id=<{model_id}>, stop_reason=<{}> | compaction returned no summary | summarizing client-side",
1052 response.stop_reason().unwrap_or("undefined")
1053 );
1054 return Ok(with_usage(SummarizeResult::new(Vec::new())));
1055 };
1056 let mut summary = SummaryBlock::new(text).with_provider("anthropic");
1057 if let Some(signature) = block.get("signature").and_then(JsonValue::as_str) {
1058 summary = summary.with_signature(signature);
1059 }
1060 Ok(with_usage(SummarizeResult::new(vec![ContentBlock::Summary(summary)])))
1061 }
1062}
1063
1064fn add_response_usage(total: &mut UsageCounters, response: &UsageCounters) {
1066 let add = |current: Option<u64>, value: Option<u64>| Some(current.unwrap_or_default() + value.unwrap_or_default());
1067 total.input_tokens = add(total.input_tokens, response.input_tokens);
1068 total.output_tokens = add(total.output_tokens, response.output_tokens);
1069 if response.cache_creation_input_tokens.is_some() {
1070 total.cache_creation_input_tokens =
1071 add(total.cache_creation_input_tokens, response.cache_creation_input_tokens);
1072 }
1073 if response.cache_read_input_tokens.is_some() {
1074 total.cache_read_input_tokens = add(total.cache_read_input_tokens, response.cache_read_input_tokens);
1075 }
1076}
1077
1078fn sum_usage(first: Option<Usage>, second: Option<Usage>) -> Option<Usage> {
1080 match (first, second) {
1081 (Some(mut first), Some(second)) => {
1082 first.accumulate(&second);
1083 Some(first)
1084 }
1085 (first, second) => first.or(second),
1086 }
1087}
1088
1089#[async_trait]
1090impl Model for AnthropicModel {
1091 fn stream(&self, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
1092 Arc::clone(&self.inner).stream(request)
1093 }
1094
1095 fn get_config(&self) -> BaseModelConfig {
1096 self.inner.resolved_config().to_base()
1097 }
1098
1099 fn update_config(&self, config: BaseModelConfig) -> Result<()> {
1100 self.inner.write_config().merge(config.into());
1101 Ok(())
1102 }
1103
1104 fn model_id(&self) -> Option<String> {
1105 Some(model_id_of(&self.inner.config()).to_owned())
1106 }
1107
1108 fn model_info(&self) -> ModelInfo {
1109 model_info_of(&self.inner.config())
1110 }
1111
1112 async fn count_tokens(&self, messages: &[Message], options: CountTokensOptions) -> Result<u64> {
1116 self.inner.count_tokens(messages, options).await
1117 }
1118
1119 async fn summarize(&self, messages: Vec<Message>, options: SummarizeOptions) -> Result<SummarizeResult> {
1125 if self.model_info().capabilities.server_side_summary != Some(true) {
1126 return summarize_client_side(self, messages, options).await;
1127 }
1128 let result = self.inner.compact(&messages, &options).await?;
1129 if !result.content.is_empty() {
1130 return Ok(result);
1131 }
1132 let fallback = summarize_client_side(self, messages, options).await?;
1133 let usage = sum_usage(result.usage, fallback.usage);
1134 let fallback = SummarizeResult::new(fallback.content);
1135 Ok(match usage {
1136 Some(usage) => fallback.with_usage(usage),
1137 None => fallback,
1138 })
1139 }
1140}
1141
1142#[cfg(test)]
1143mod tests;