merry_runtime/
user_input.rs1use crate::RuntimeError;
4use merry_llm::{ModelContent, ModelImage};
5use std::sync::Arc;
6
7const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
8
9pub const MAX_USER_IMAGES: usize = 20;
11pub const MAX_USER_IMAGE_PNG_BYTES: usize = 10 * 1024 * 1024;
13pub const MAX_USER_IMAGE_TOTAL_PNG_BYTES: usize = 20 * 1024 * 1024;
15pub const MAX_USER_IMAGE_DIMENSION: u32 = 8_000;
17pub const MAX_USER_IMAGE_PIXELS: u64 = 32_000_000;
19
20pub fn user_image_label(index: usize) -> Result<String, RuntimeError> {
22 if index == 0 {
23 return Err(invalid_image("user image label index must start at one"));
24 }
25 Ok(format!("[Image #{index}]"))
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct UserImageInput {
31 label: String,
32 png_bytes: Arc<[u8]>,
33 width: u32,
34 height: u32,
35}
36
37impl UserImageInput {
38 pub fn png(
40 label: &str,
41 png_bytes: impl Into<Arc<[u8]>>,
42 width: u32,
43 height: u32,
44 ) -> Result<Self, RuntimeError> {
45 if label.trim().is_empty() || label.chars().any(char::is_control) {
46 return Err(invalid_image(
47 "user image label must be non-blank and contain no control characters",
48 ));
49 }
50
51 let png_bytes = png_bytes.into();
52 if !png_bytes.starts_with(PNG_SIGNATURE) {
53 return Err(invalid_image(
54 "user image bytes must contain normalized PNG data",
55 ));
56 }
57 if png_bytes.len() > MAX_USER_IMAGE_PNG_BYTES {
58 return Err(invalid_image(
59 "one user image encoded PNG must be at most 10 MiB",
60 ));
61 }
62 if width == 0 || height == 0 {
63 return Err(invalid_image(
64 "user image dimensions must be greater than zero",
65 ));
66 }
67 if width > MAX_USER_IMAGE_DIMENSION || height > MAX_USER_IMAGE_DIMENSION {
68 return Err(invalid_image(
69 "user image dimensions must not exceed 8000 pixels per dimension",
70 ));
71 }
72 let pixels = u64::from(width)
73 .checked_mul(u64::from(height))
74 .ok_or_else(|| invalid_image("user image pixel count overflowed"))?;
75 if pixels > MAX_USER_IMAGE_PIXELS {
76 return Err(invalid_image(
77 "one user image must not exceed 32 million pixels",
78 ));
79 }
80
81 Ok(Self {
82 label: label.to_owned(),
83 png_bytes,
84 width,
85 height,
86 })
87 }
88
89 #[must_use]
91 pub fn label(&self) -> &str {
92 &self.label
93 }
94
95 #[must_use]
97 pub fn png_bytes(&self) -> &[u8] {
98 &self.png_bytes
99 }
100
101 #[must_use]
103 pub fn shared_png_bytes(&self) -> Arc<[u8]> {
104 Arc::clone(&self.png_bytes)
105 }
106
107 #[must_use]
109 pub fn width(&self) -> u32 {
110 self.width
111 }
112
113 #[must_use]
115 pub fn height(&self) -> u32 {
116 self.height
117 }
118
119 fn model_image(&self) -> Result<ModelImage, merry_llm::ModelError> {
120 ModelImage::png(
121 self.label(),
122 self.shared_png_bytes(),
123 self.width(),
124 self.height(),
125 )
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct UserMessageInput {
132 text: String,
133 images: Vec<UserImageInput>,
134}
135
136impl UserMessageInput {
137 pub fn text_only(text: &str) -> Result<Self, RuntimeError> {
139 Self::new(text, Vec::new())
140 }
141
142 pub fn new(text: &str, images: Vec<UserImageInput>) -> Result<Self, RuntimeError> {
144 validate_user_text(text)?;
145 if images.len() > MAX_USER_IMAGES {
146 return Err(invalid_image(
147 "one user message may contain at most 20 images",
148 ));
149 }
150
151 let mut total_png_bytes = 0_usize;
152 for (offset, image) in images.iter().enumerate() {
153 let expected_label = user_image_label(offset + 1)?;
154 if image.label() != expected_label {
155 return Err(invalid_image(format!(
156 "user image {} label must be {expected_label}",
157 offset + 1
158 )));
159 }
160 if !text.contains(image.label()) {
161 return Err(invalid_image(format!(
162 "user message text must contain image label {}",
163 image.label()
164 )));
165 }
166 total_png_bytes = total_png_bytes
167 .checked_add(image.png_bytes().len())
168 .ok_or_else(|| invalid_image("user image total PNG byte count overflowed"))?;
169 }
170 if total_png_bytes > MAX_USER_IMAGE_TOTAL_PNG_BYTES {
171 return Err(invalid_image(
172 "one user message encoded PNG data must total at most 20 MiB",
173 ));
174 }
175
176 Ok(Self {
177 text: text.to_owned(),
178 images,
179 })
180 }
181
182 #[must_use]
184 pub fn text(&self) -> &str {
185 &self.text
186 }
187
188 #[must_use]
190 pub fn images(&self) -> &[UserImageInput] {
191 &self.images
192 }
193
194 pub(crate) fn model_content(&self) -> Result<ModelContent, merry_llm::ModelError> {
195 if self.images.is_empty() {
196 return ModelContent::text(self.text());
197 }
198
199 let images = self
200 .images
201 .iter()
202 .map(UserImageInput::model_image)
203 .collect::<Result<Vec<_>, _>>()?;
204 ModelContent::user_with_images(self.text(), images)
205 }
206}
207
208#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct StepInput {
214 user_messages: Vec<UserMessageInput>,
215 user_texts: Vec<String>,
216 history: StepInputHistory,
217}
218
219impl StepInput {
220 pub fn user_text(text: &str) -> Result<Self, RuntimeError> {
222 Self::user_texts([text])
223 }
224
225 pub fn user_texts<I, S>(texts: I) -> Result<Self, RuntimeError>
227 where
228 I: IntoIterator<Item = S>,
229 S: AsRef<str>,
230 {
231 let messages = texts
232 .into_iter()
233 .map(|text| UserMessageInput::text_only(text.as_ref()))
234 .collect::<Result<Vec<_>, _>>()?;
235 Self::from_user_messages(messages)
236 }
237
238 pub fn from_user_messages<I>(messages: I) -> Result<Self, RuntimeError>
240 where
241 I: IntoIterator<Item = UserMessageInput>,
242 {
243 let user_messages = messages.into_iter().collect::<Vec<_>>();
244 if user_messages.is_empty() {
245 return Err(RuntimeError::InvalidStepInput {
246 reason: "user text burst must contain at least one message",
247 });
248 }
249 let user_texts = user_messages
250 .iter()
251 .map(|message| message.text().to_owned())
252 .collect();
253
254 Ok(Self {
255 user_messages,
256 user_texts,
257 history: StepInputHistory::RecordUser,
258 })
259 }
260
261 #[allow(dead_code)]
262 pub(crate) fn loop_control_text(text: &str) -> Result<Self, RuntimeError> {
263 let message = UserMessageInput::text_only(text)?;
264 Ok(Self {
265 user_texts: vec![message.text().to_owned()],
266 user_messages: vec![message],
267 history: StepInputHistory::ControlOnly,
268 })
269 }
270
271 pub(crate) fn no_new_user_input() -> Self {
272 Self {
273 user_messages: Vec::new(),
274 user_texts: Vec::new(),
275 history: StepInputHistory::ControlOnly,
276 }
277 }
278
279 #[must_use]
281 pub fn text(&self) -> &str {
282 self.user_texts
283 .first()
284 .map(String::as_str)
285 .expect("StepInput::text is available only for user text inputs")
286 }
287
288 #[must_use]
290 pub fn texts(&self) -> &[String] {
291 &self.user_texts
292 }
293
294 #[must_use]
296 pub fn user_messages(&self) -> &[UserMessageInput] {
297 &self.user_messages
298 }
299
300 pub(crate) fn user_messages_for_request(&self) -> &[UserMessageInput] {
301 &self.user_messages
302 }
303
304 pub(crate) fn user_messages_for_history(&self) -> &[UserMessageInput] {
305 if self.history == StepInputHistory::RecordUser {
306 &self.user_messages
307 } else {
308 &[]
309 }
310 }
311
312 pub(crate) fn memory_activation_query(&self) -> Option<String> {
313 (!self.user_texts.is_empty()).then(|| self.user_texts.join("\n\n"))
314 }
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318enum StepInputHistory {
319 RecordUser,
320 ControlOnly,
321}
322
323pub(crate) fn validate_user_text(text: &str) -> Result<(), RuntimeError> {
324 if text.trim().is_empty() {
325 return Err(RuntimeError::InvalidStepInput {
326 reason: "user text must not be blank",
327 });
328 }
329
330 if text
331 .chars()
332 .any(|character| character.is_control() && character != '\n' && character != '\t')
333 {
334 return Err(RuntimeError::InvalidStepInput {
335 reason: "user text must not contain control characters other than newline or tab",
336 });
337 }
338
339 Ok(())
340}
341
342fn invalid_image(reason: impl Into<String>) -> RuntimeError {
343 RuntimeError::InvalidUserImageInput {
344 reason: reason.into(),
345 }
346}