1use std::collections::HashSet;
4use std::pin::Pin;
5
6use async_trait::async_trait;
7use futures::{Stream, StreamExt};
8use serde::{Deserialize, Serialize};
9
10use super::model_info::lookup_model_info;
11use super::model_info::{DeferredToolLoading, ModelCapabilities, ModelInfo, ModelLimits, default_context_window_limit};
12use super::streaming::{
13 ContentBlockDelta, ContentBlockStart, ModelContentBlockStartEvent, ModelMetadataEvent, ModelRedactionEvent,
14 ModelStreamEvent, ReasoningContentDelta,
15};
16use super::summarize::{SummarizeResult, summarize_client_side};
17use crate::cancel::CancelSignal;
18use crate::error::{Error, MaxTokensError, ModelError, Result};
19use crate::logging::warn_once;
20use crate::state_store::StateStore;
21use crate::types::{
22 AgentMetadata, Citation, CitationGeneratedContent, CitationsBlock, ContentBlock, JsonValue, Message,
23 MessageMetadata, ReasoningBlock, Role, StopReason, SystemContentBlock, SystemPrompt, TextBlock, ToolChoice,
24 ToolResultContent, ToolSpec, ToolUseBlock,
25};
26
27pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
29
30#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
35pub struct BaseModelConfig {
36 #[builder(into)]
38 pub model_id: Option<String>,
39 pub max_tokens: Option<u64>,
41 pub temperature: Option<f64>,
43 pub top_p: Option<f64>,
45 pub context_window_limit: Option<u64>,
49 pub model_info: Option<ModelInfo>,
52}
53
54impl BaseModelConfig {
55 pub fn merge(&mut self, update: Self) {
58 let Self {
59 model_id,
60 max_tokens,
61 temperature,
62 top_p,
63 context_window_limit,
64 model_info,
65 } = update;
66 self.model_id = model_id.or(self.model_id.take());
67 self.max_tokens = max_tokens.or(self.max_tokens);
68 self.temperature = temperature.or(self.temperature);
69 self.top_p = top_p.or(self.top_p);
70 self.context_window_limit = context_window_limit.or(self.context_window_limit);
71 self.model_info = model_info.or(self.model_info.take());
72 }
73}
74
75#[derive(Debug, Clone, Default, bon::Builder)]
79pub struct ModelRequest {
80 #[builder(default)]
82 pub messages: Vec<Message>,
83 #[builder(into)]
85 pub system_prompt: Option<SystemPrompt>,
86 #[builder(default)]
88 pub tool_specs: Vec<ToolSpec>,
89 pub tool_choice: Option<ToolChoice>,
91 #[builder(default)]
95 pub model_state: StateStore,
96 pub dynamic_trailing_blocks: Option<usize>,
98 pub agent_metadata: Option<AgentMetadata>,
100 pub structured_output_schema: Option<JsonValue>,
104 pub cancel_signal: Option<CancelSignal>,
106 #[builder(default)]
112 pub deferred_tools: HashSet<String>,
113}
114
115#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
117pub struct CountTokensOptions {
118 #[builder(into)]
120 pub system_prompt: Option<SystemPrompt>,
121 #[builder(default)]
123 pub tool_specs: Vec<ToolSpec>,
124}
125
126#[derive(Debug, Clone, Default, bon::Builder)]
128pub struct SummarizeOptions {
129 #[builder(into)]
131 pub system_prompt: Option<SystemPrompt>,
132 #[builder(default)]
134 pub tool_specs: Vec<ToolSpec>,
135 #[builder(into)]
138 pub instructions: Option<String>,
139 pub cancel_signal: Option<CancelSignal>,
141 pub agent_metadata: Option<AgentMetadata>,
144 #[builder(default)]
147 pub deferred_tools: HashSet<String>,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153#[non_exhaustive]
154pub struct Redaction {
155 pub user_message: String,
157}
158
159impl Redaction {
160 pub fn new(user_message: impl Into<String>) -> Self {
162 Self {
163 user_message: user_message.into(),
164 }
165 }
166}
167
168#[derive(Debug, Clone, PartialEq)]
170#[non_exhaustive]
171pub struct StreamAggregatedResult {
172 pub message: Message,
174 pub stop_reason: StopReason,
176 pub metadata: Option<ModelMetadataEvent>,
178 pub redaction: Option<Redaction>,
180}
181
182impl StreamAggregatedResult {
183 pub fn new(message: Message, stop_reason: StopReason) -> Self {
185 Self {
186 message,
187 stop_reason,
188 metadata: None,
189 redaction: None,
190 }
191 }
192
193 #[must_use]
195 pub fn with_metadata(mut self, metadata: ModelMetadataEvent) -> Self {
196 self.metadata = Some(metadata);
197 self
198 }
199
200 #[must_use]
202 pub fn with_redaction(mut self, redaction: Redaction) -> Self {
203 self.redaction = Some(redaction);
204 self
205 }
206}
207
208#[derive(Debug, Clone, PartialEq)]
210#[non_exhaustive]
211#[allow(clippy::large_enum_variant, reason = "`Done` is the single last item of each stream")]
212pub enum AggregatedEvent {
213 ModelStreamEvent(ModelStreamEvent),
215 ContentBlock(ContentBlock),
217 Done(StreamAggregatedResult),
219}
220
221#[async_trait]
286pub trait Model: Send + Sync + 'static {
287 fn stream(&self, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>>;
300
301 fn stream_aggregated(&self, request: ModelRequest) -> BoxStream<'static, Result<AggregatedEvent>> {
309 aggregate(self.stream(request))
310 }
311
312 fn get_config(&self) -> BaseModelConfig;
314
315 fn update_config(&self, config: BaseModelConfig) -> Result<()>;
323
324 fn model_id(&self) -> Option<String> {
326 self.get_config().model_id
327 }
328
329 fn model_info(&self) -> ModelInfo {
340 base_model_info(&self.get_config())
341 }
342
343 fn stateful(&self) -> bool {
349 self.model_info().capabilities.stateful.unwrap_or(false)
350 }
351
352 async fn count_tokens(&self, messages: &[Message], options: CountTokensOptions) -> Result<u64> {
359 Ok(estimate_tokens(messages, &options))
360 }
361
362 async fn summarize(&self, messages: Vec<Message>, options: SummarizeOptions) -> Result<SummarizeResult> {
374 summarize_client_side(self, messages, options).await
375 }
376
377 fn estimate_utilization(&self, input_tokens: u64) -> f64 {
382 let limit = self
383 .model_info()
384 .limits
385 .context_window
386 .filter(|limit| *limit > 0)
387 .unwrap_or_else(|| {
388 let default = default_context_window_limit();
389 warn_once(&default_context_window_warning(default));
390 default
391 });
392 input_tokens as f64 / limit as f64
393 }
394}
395
396fn default_context_window_warning(default: u64) -> String {
397 format!(
398 "contextWindowLimit is not set on the model, using default of {default} for utilization estimate | set contextWindowLimit in your model config for accurate results"
399 )
400}
401
402#[must_use]
407pub fn base_model_info(config: &BaseModelConfig) -> ModelInfo {
408 let shared = lookup_model_info(config.model_id.as_deref().unwrap_or_default());
409 let deferred_tool_loading = match shared.capabilities.deferred_tool_loading {
410 Some(DeferredToolLoading::Unsupported) => DeferredToolLoading::Unsupported,
411 _ => DeferredToolLoading::Stubs,
412 };
413 let defaults = ModelInfo {
414 capabilities: ModelCapabilities {
415 temporary_messages: Some(false),
416 deferred_tool_loading: Some(deferred_tool_loading),
417 ..ModelCapabilities::default()
418 },
419 limits: ModelLimits {
420 context_window: config.context_window_limit,
421 ..ModelLimits::default()
422 },
423 };
424 ModelInfo::merge([Some(&shared), Some(&defaults), config.model_info.as_ref()])
425}
426
427#[allow(dead_code, reason = "providers fill the context window of `get_config` with it")]
429pub(crate) fn resolve_config_metadata(mut config: BaseModelConfig, model_id: &str) -> BaseModelConfig {
430 if config.context_window_limit.is_some() {
431 return config;
432 }
433 let info = ModelInfo::merge([Some(&lookup_model_info(model_id)), config.model_info.as_ref()]);
434 config.context_window_limit = info.limits.context_window;
435 config
436}
437
438#[allow(dead_code, reason = "providers that need a max_tokens resolve it with this")]
441pub(crate) fn resolve_max_tokens(config: &BaseModelConfig, model_id: &str) -> Option<u64> {
442 config.max_tokens.or_else(|| {
443 ModelInfo::merge([Some(&lookup_model_info(model_id)), config.model_info.as_ref()])
444 .limits
445 .max_output_tokens
446 })
447}
448
449pub(crate) fn latest_user_index(messages: &[Message]) -> Option<usize> {
451 messages.iter().rposition(|message| message.role == Role::User)
452}
453
454#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
456#[non_exhaustive]
457pub enum CacheStrategy {
458 #[default]
460 Auto,
461 Anthropic,
464}
465
466pub type CacheTtl = String;
468
469#[derive(Debug, Clone, PartialEq, Eq)]
471#[non_exhaustive]
472pub enum CacheSectionSetting {
473 Enabled(bool),
475 Ttl(CacheTtl),
477}
478
479impl From<bool> for CacheSectionSetting {
480 fn from(enabled: bool) -> Self {
481 Self::Enabled(enabled)
482 }
483}
484
485impl From<&str> for CacheSectionSetting {
486 fn from(ttl: &str) -> Self {
487 Self::Ttl(ttl.to_owned())
488 }
489}
490
491impl From<String> for CacheSectionSetting {
492 fn from(ttl: String) -> Self {
493 Self::Ttl(ttl)
494 }
495}
496
497#[derive(Debug, Clone, PartialEq, Eq)]
499#[non_exhaustive]
500pub enum CacheKey {
501 Key(String),
503 Disabled,
505}
506
507impl From<&str> for CacheKey {
508 fn from(key: &str) -> Self {
509 Self::Key(key.to_owned())
510 }
511}
512
513impl From<String> for CacheKey {
514 fn from(key: String) -> Self {
515 Self::Key(key)
516 }
517}
518
519#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
521pub struct CacheConfig {
522 pub strategy: Option<CacheStrategy>,
524 #[builder(into)]
530 pub ttl: Option<CacheTtl>,
531 #[builder(into)]
534 pub tools_ttl: Option<CacheSectionSetting>,
535 #[builder(into)]
538 pub system_prompt_ttl: Option<CacheSectionSetting>,
539 #[builder(into)]
542 pub messages_ttl: Option<CacheSectionSetting>,
543 #[builder(into)]
547 pub cache_key: Option<CacheKey>,
548}
549
550#[derive(Debug, Clone, PartialEq, Eq)]
552pub(crate) struct ResolvedCacheSection {
553 pub(crate) enabled: bool,
555 pub(crate) ttl: Option<CacheTtl>,
557}
558
559#[allow(dead_code, reason = "providers place cache points with it")]
563pub(crate) fn resolve_cache_section(
564 section: Option<&CacheSectionSetting>,
565 ttl_fallbacks: &[Option<&str>],
566) -> ResolvedCacheSection {
567 let enabled = !matches!(section, Some(CacheSectionSetting::Enabled(false)));
568 let section_ttl = match section {
569 Some(CacheSectionSetting::Ttl(ttl)) => Some(ttl.as_str()),
570 _ => None,
571 };
572 let ttl = std::iter::once(section_ttl)
573 .chain(ttl_fallbacks.iter().copied())
574 .flatten()
575 .find(|ttl| !ttl.is_empty())
576 .map(str::to_owned);
577 ResolvedCacheSection { enabled, ttl }
578}
579
580fn into_model_error(error: Error) -> Error {
582 if error.is_model_error() {
583 return error;
584 }
585 ModelError::new(error.to_string()).with_source(error).into()
586}
587
588pub(crate) fn aggregate(
590 mut events: BoxStream<'static, Result<ModelStreamEvent>>,
591) -> BoxStream<'static, Result<AggregatedEvent>> {
592 Box::pin(async_stream::stream! {
593 let mut aggregator = Aggregator::default();
594 while let Some(event) = events.next().await {
595 let event = match event {
596 Ok(event) => event,
597 Err(error) => {
598 yield Err(into_model_error(error));
599 return;
600 }
601 };
602 let block = aggregator.apply(&event);
603 yield Ok(AggregatedEvent::ModelStreamEvent(event));
604 if let Some(block) = block {
605 yield Ok(AggregatedEvent::ContentBlock(block));
606 }
607 }
608 yield aggregator.finish().map(AggregatedEvent::Done);
609 })
610}
611
612pub(crate) fn is_js_whitespace(c: char) -> bool {
614 (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'
615}
616
617#[derive(Default)]
618struct Aggregator {
619 role: Option<Role>,
620 blocks: Vec<ContentBlock>,
621 text: String,
622 tool_input: String,
623 tool_name: String,
624 tool_use_id: String,
625 tool_signature: String,
626 reasoning: ReasoningBlock,
627 citations: Vec<Citation>,
628 citation_content: Vec<CitationGeneratedContent>,
629 stopped: Option<Message>,
630 stop_reason: Option<StopReason>,
631 metadata: Option<ModelMetadataEvent>,
632 redaction: Option<String>,
633 parse_error: Option<serde_json::Error>,
634}
635
636impl Aggregator {
637 fn apply(&mut self, event: &ModelStreamEvent) -> Option<ContentBlock> {
638 match event {
639 ModelStreamEvent::MessageStart(start) => {
640 self.role = Some(start.role);
641 self.blocks.clear();
642 }
643 ModelStreamEvent::ContentBlockStart(start) => self.start_block(start),
644 ModelStreamEvent::ContentBlockDelta(delta) => self.add_delta(&delta.delta),
645 ModelStreamEvent::ContentBlockStop(_) => return self.finish_block(),
646 ModelStreamEvent::MessageStop(stop) => {
647 let content = self
648 .blocks
649 .iter()
650 .filter(|block| !matches!(block, ContentBlock::Text(text) if text.text.trim_matches(is_js_whitespace).is_empty()))
651 .cloned()
652 .collect();
653 self.stopped = Some(Message::new(self.role.unwrap_or(Role::Assistant), content));
654 self.stop_reason = Some(stop.stop_reason.clone());
655 }
656 ModelStreamEvent::Metadata(metadata) => self.metadata = Some(metadata.clone()),
657 ModelStreamEvent::Redaction(redaction) => self.redact(redaction),
658 }
659 None
660 }
661
662 fn start_block(&mut self, start: &ModelContentBlockStartEvent) {
663 if let Some(ContentBlockStart::ToolUse(tool_use)) = &start.start {
664 self.tool_name.clone_from(&tool_use.name);
665 self.tool_use_id.clone_from(&tool_use.tool_use_id);
666 self.tool_signature = tool_use.reasoning_signature.clone().unwrap_or_default();
667 }
668 self.tool_input.clear();
669 self.text.clear();
670 self.reasoning = ReasoningBlock::default();
671 self.reset_citations();
672 }
673
674 fn add_delta(&mut self, delta: &ContentBlockDelta) {
675 match delta {
676 ContentBlockDelta::Text(text) => self.text.push_str(&text.text),
677 ContentBlockDelta::ToolUseInput(input) => self.tool_input.push_str(&input.input),
678 ContentBlockDelta::ReasoningContent(reasoning) => self.add_reasoning(reasoning),
679 ContentBlockDelta::Citations(citations) => {
680 self.citations.extend(citations.citations.iter().cloned());
681 self.citation_content.extend(citations.content.iter().cloned());
682 }
683 }
684 }
685
686 fn add_reasoning(&mut self, delta: &ReasoningContentDelta) {
687 if let Some(text) = delta.text.as_deref().filter(|text| !text.is_empty()) {
688 self.reasoning.text.get_or_insert_with(String::new).push_str(text);
689 }
690 if let Some(signature) = delta.signature.as_deref().filter(|signature| !signature.is_empty()) {
691 self.reasoning.signature = Some(signature.to_owned());
692 }
693 if let Some(redacted) = &delta.redacted_content {
694 self.reasoning.redacted_content = Some(redacted.clone());
695 }
696 if let Some(provider_data) = &delta.provider_data {
697 self.reasoning.provider_data = Some(provider_data.clone());
698 }
699 }
700
701 fn has_reasoning(&self) -> bool {
702 self.reasoning.text.is_some()
703 || self.reasoning.signature.is_some()
704 || self.reasoning.redacted_content.is_some()
705 || self.reasoning.provider_data.is_some()
706 }
707
708 fn reset_citations(&mut self) {
709 self.citations.clear();
710 self.citation_content.clear();
711 }
712
713 fn finish_block(&mut self) -> Option<ContentBlock> {
715 let block = if !self.tool_use_id.is_empty() {
716 self.finish_tool_use()?
717 } else if self.has_reasoning() {
718 ContentBlock::Reasoning(std::mem::take(&mut self.reasoning))
719 } else if !self.citations.is_empty() {
720 self.finish_citations()
721 } else {
722 ContentBlock::Text(TextBlock::new(std::mem::take(&mut self.text)))
723 };
724 self.blocks.push(block.clone());
725 Some(block)
726 }
727
728 fn finish_tool_use(&mut self) -> Option<ContentBlock> {
729 let name = std::mem::take(&mut self.tool_name);
730 let tool_use_id = std::mem::take(&mut self.tool_use_id);
731 let signature = std::mem::take(&mut self.tool_signature);
732 let input = if self.tool_input.is_empty() {
733 Ok(JsonValue::Object(serde_json::Map::new()))
734 } else {
735 serde_json::from_str(&self.tool_input)
736 };
737 let input = match input {
738 Ok(input) => input,
739 Err(error) => {
740 tracing::error!("error=<{error}> | unable to parse tool input JSON");
741 self.parse_error = Some(error);
742 return None;
743 }
744 };
745 let mut block = ToolUseBlock::new(name, tool_use_id, input);
746 if !signature.is_empty() {
747 block = block.with_reasoning_signature(signature);
748 }
749 Some(ContentBlock::ToolUse(block))
750 }
751
752 fn finish_citations(&mut self) -> ContentBlock {
753 let text = std::mem::take(&mut self.text);
754 let mut content = std::mem::take(&mut self.citation_content);
755 if content.is_empty() && !text.is_empty() {
756 content.push(CitationGeneratedContent::new(text));
757 }
758 let citations = std::mem::take(&mut self.citations);
759 ContentBlock::Citations(CitationsBlock::new(citations, content))
760 }
761
762 fn redact(&mut self, redaction: &ModelRedactionEvent) {
763 if let Some(input) = &redaction.input_redaction {
764 self.redaction = Some(input.replace_content.clone());
765 }
766 if let Some(output) = &redaction.output_redaction {
767 self.stopped = Some(Message::assistant(output.replace_content.clone()));
768 }
769 }
770
771 fn finish(self) -> Result<StreamAggregatedResult> {
772 let (Some(mut message), Some(stop_reason)) = (self.stopped, self.stop_reason) else {
773 let mut error = ModelError::new("Stream ended without completing a message");
774 if let Some(parse_error) = self.parse_error {
775 error = error.with_source(parse_error);
776 }
777 return Err(error.into());
778 };
779 let usage = self.metadata.as_ref().and_then(|metadata| metadata.usage);
780 let metrics = self.metadata.as_ref().and_then(|metadata| metadata.metrics);
781 if usage.is_some() || metrics.is_some() {
782 message = message.with_metadata(MessageMetadata {
783 usage,
784 metrics,
785 ..MessageMetadata::default()
786 });
787 }
788 if stop_reason == StopReason::MaxTokens {
789 return Err(MaxTokensError::new(
790 "Model reached maximum token limit. This is an unrecoverable state that requires intervention.",
791 message,
792 )
793 .into());
794 }
795 if let Some(parse_error) = self.parse_error {
796 return Err(ModelError::new("unable to parse tool input JSON")
797 .with_source(parse_error)
798 .into());
799 }
800 Ok(StreamAggregatedResult {
801 message,
802 stop_reason,
803 metadata: self.metadata,
804 redaction: self.redaction.map(Redaction::new),
805 })
806 }
807}
808
809fn utf16_len(text: &str) -> u64 {
810 text.encode_utf16().count() as u64
811}
812
813fn heuristic_text(text: &str) -> u64 {
814 utf16_len(text).div_ceil(4)
815}
816
817fn normalize_js_numbers(value: &mut JsonValue) {
819 match value {
820 JsonValue::Number(number) => {
821 let Some(float) = number.as_f64().filter(|_| number.is_f64()) else {
822 return;
823 };
824 if float.fract() == 0.0 && float.abs() <= MAX_SAFE_INTEGER {
825 *value = JsonValue::from(float as i64);
826 }
827 }
828 JsonValue::Array(items) => items.iter_mut().for_each(normalize_js_numbers),
829 JsonValue::Object(map) => map.values_mut().for_each(normalize_js_numbers),
830 _ => {}
831 }
832}
833
834const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
836
837pub(crate) fn heuristic_json(value: &impl Serialize) -> u64 {
838 let Ok(mut json) = serde_json::to_value(value) else {
839 tracing::debug!("unable to serialize object for token estimation, skipping");
840 return 0;
841 };
842 normalize_js_numbers(&mut json);
843 utf16_len(&json.to_string()).div_ceil(2)
844}
845
846fn estimate_content_block_tokens(block: &ContentBlock) -> u64 {
847 match block {
848 ContentBlock::Text(text) => heuristic_text(&text.text),
849 ContentBlock::ToolUse(tool_use) => heuristic_text(&tool_use.name) + heuristic_json(&tool_use.input),
850 ContentBlock::ToolResult(result) => result
851 .content
852 .iter()
853 .map(|item| match item {
854 ToolResultContent::Text(text) => heuristic_text(&text.text),
855 ToolResultContent::Json(json) => heuristic_json(&json.json),
856 _ => 0,
857 })
858 .sum(),
859 ContentBlock::Reasoning(reasoning) => reasoning.text.as_deref().map_or(0, heuristic_text),
860 ContentBlock::GuardContent(guard) => guard.text().map_or(0, |text| heuristic_text(&text.text)),
861 ContentBlock::Citations(citations) => citations.content.iter().map(|item| heuristic_text(&item.text)).sum(),
862 ContentBlock::Injected(injected) => heuristic_text(&injected.text),
863 ContentBlock::Summary(summary) => heuristic_text(&summary.text),
864 _ => 0,
865 }
866}
867
868fn estimate_system_prompt_tokens(system_prompt: &SystemPrompt) -> u64 {
869 match system_prompt {
870 SystemPrompt::Text(text) => heuristic_text(text),
871 SystemPrompt::Blocks(blocks) => blocks
872 .iter()
873 .map(|block| match block {
874 SystemContentBlock::Text(text) => heuristic_text(&text.text),
875 SystemContentBlock::GuardContent(guard) => guard.text().map_or(0, |text| heuristic_text(&text.text)),
876 _ => 0,
877 })
878 .sum(),
879 }
880}
881
882fn estimate_message_tokens(messages: &[Message]) -> u64 {
884 let latest_user = latest_user_index(messages);
885 messages
886 .iter()
887 .enumerate()
888 .flat_map(|(index, message)| {
889 let keep_injected = Some(index) == latest_user;
890 message
891 .content
892 .iter()
893 .filter(move |block| keep_injected || !matches!(block, ContentBlock::Injected(_)))
894 })
895 .map(estimate_content_block_tokens)
896 .sum()
897}
898
899#[must_use]
904pub fn estimate_tokens(messages: &[Message], options: &CountTokensOptions) -> u64 {
905 let system = options.system_prompt.as_ref().map_or(0, estimate_system_prompt_tokens);
906 let tools: u64 = options.tool_specs.iter().map(heuristic_json).sum();
907 system + estimate_message_tokens(messages) + tools
908}
909
910#[cfg(test)]
912mod tests;