| 1 | use crate::{ContentBlock, Message}; |
| 2 | |
| 3 | /// Split a `data:<media-type>;base64,<payload>` URL. |
| 4 | /// |
| 5 | /// Anthropic's Messages API models an image as a tagged `source` rather than a |
| 6 | /// URL, so the native route has to take the data URL back apart. Returns |
| 7 | /// `None` for `http(s)` URLs and for anything malformed, which the caller |
| 8 | /// renders as a remote source or a visible degradation respectively. |
| 9 | #[must_use] |
| 10 | pub fn parse_data_url(url: &str) -> Option<(&str, &str)> { |
| 11 | let rest = url.strip_prefix("data:")?; |
| 12 | let (header, payload) = rest.split_once(',')?; |
| 13 | let media_type = header.strip_suffix(";base64")?; |
| 14 | if media_type.is_empty() || payload.is_empty() { |
| 15 | return None; |
| 16 | } |
| 17 | Some((media_type, payload)) |
| 18 | } |
| 19 | |
| 20 | /// Whether a URL is one a provider can fetch for itself. |
| 21 | #[must_use] |
| 22 | pub fn is_remote_image_url(url: &str) -> bool { |
| 23 | url.starts_with("https://") || url.starts_with("http://") |
| 24 | } |
| 25 | |
| 26 | pub const ELIDED_IMAGE_NOTE: &str = "[Image not attached to this request: this model accepts only a limited number of images per request, so the oldest are left out. It remains in the session; do not guess what it showed.]"; |
| 27 | |
| 28 | pub const ELIDED_TOOL_IMAGE_NOTE: &str = "[Tool image not attached to this request: this model accepts only a limited number of images per request, so the oldest are left out; do not guess what it showed. Take a fresh observation (for example a new screenshot) if you need the current state; do not repeat an action to recover its image.]"; |
| 29 | |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 31 | pub struct ImageWindow { |
| 32 | pub total: usize, |
| 33 | pub elided: usize, |
| 34 | pub cap: usize, |
| 35 | } |
| 36 | |
| 37 | fn block_carries_image(block: &ContentBlock) -> bool { |
| 38 | match block { |
| 39 | ContentBlock::ImageUrl { .. } => true, |
| 40 | ContentBlock::ToolResult { content_blocks, .. } => { |
| 41 | content_blocks.as_ref().is_some_and(|blocks| { |
| 42 | blocks.iter().any(|value| { |
| 43 | value.get("type").and_then(serde_json::Value::as_str) == Some("image") |
| 44 | }) |
| 45 | }) |
| 46 | } |
| 47 | _ => false, |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | #[must_use] |
| 52 | pub fn count_request_images(messages: &[Message]) -> usize { |
| 53 | messages |
| 54 | .iter() |
| 55 | .flat_map(|message| &message.content) |
| 56 | .filter(|block| block_carries_image(block)) |
| 57 | .count() |
| 58 | } |
| 59 | |
| 60 | #[must_use] |
| 61 | pub fn images_to_elide(total: usize, cap: usize) -> usize { |
| 62 | if total <= cap { |
| 63 | return 0; |
| 64 | } |
| 65 | let chunk = (cap / 4).max(1); |
| 66 | ((total - cap).div_ceil(chunk) * chunk).min(total) |
| 67 | } |
| 68 | |
| 69 | pub fn cap_request_images(messages: &mut [Message], cap: usize) -> ImageWindow { |
| 70 | let total = count_request_images(messages); |
| 71 | let mut window = cap_request_images_with_notes( |
| 72 | messages, |
| 73 | total - images_to_elide(total, cap), |
| 74 | ELIDED_IMAGE_NOTE, |
| 75 | ELIDED_TOOL_IMAGE_NOTE, |
| 76 | ); |
| 77 | window.cap = cap; |
| 78 | window |
| 79 | } |
| 80 | |
| 81 | pub fn cap_request_images_with_notes( |
| 82 | messages: &mut [Message], |
| 83 | cap: usize, |
| 84 | image_note: &str, |
| 85 | tool_note: &str, |
| 86 | ) -> ImageWindow { |
| 87 | let total = count_request_images(messages); |
| 88 | let elided = total.saturating_sub(cap); |
| 89 | let mut remaining = elided; |
| 90 | for block in messages.iter_mut().flat_map(|message| &mut message.content) { |
| 91 | if remaining == 0 { |
| 92 | break; |
| 93 | } |
| 94 | if !block_carries_image(block) { |
| 95 | continue; |
| 96 | } |
| 97 | match block { |
| 98 | ContentBlock::ImageUrl { .. } => { |
| 99 | *block = ContentBlock::Text { |
| 100 | text: image_note.to_string(), |
| 101 | cache_control: None, |
| 102 | }; |
| 103 | } |
| 104 | ContentBlock::ToolResult { |
| 105 | content, |
| 106 | content_blocks, |
| 107 | .. |
| 108 | } => { |
| 109 | if let Some(blocks) = content_blocks.as_mut() { |
| 110 | blocks.retain(|value| { |
| 111 | value.get("type").and_then(serde_json::Value::as_str) != Some("image") |
| 112 | }); |
| 113 | if blocks.is_empty() { |
| 114 | *content_blocks = None; |
| 115 | } |
| 116 | } |
| 117 | *content = format!("{content}\n{tool_note}"); |
| 118 | } |
| 119 | _ => continue, |
| 120 | } |
| 121 | remaining -= 1; |
| 122 | } |
| 123 | ImageWindow { total, elided, cap } |
| 124 | } |
| 125 | |
| 126 | #[must_use] |
| 127 | pub fn tool_result_text_with_omission(content: &str, omitted: usize) -> String { |
| 128 | if omitted == 0 { |
| 129 | return content.to_string(); |
| 130 | } |
| 131 | format!( |
| 132 | "{content}\n[{omitted} tool-result image block(s) omitted: invalid, unsupported, oversized, or additional.]" |
| 133 | ) |
| 134 | } |
| 135 |