1use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "lowercase")]
7pub enum Role {
8 System,
9 User,
10 Assistant,
11 Tool,
12}
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct FunctionCall {
16 pub name: String,
17 pub arguments: String,
19}
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct ToolCall {
23 pub id: String,
24 #[serde(rename = "type", default = "function_kind")]
25 pub kind: String,
26 pub function: FunctionCall,
27}
28
29fn function_kind() -> String {
30 "function".into()
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct ImagePart {
42 #[serde(default, skip_serializing_if = "String::is_empty")]
45 pub name: String,
46 pub mime: String,
47 pub url: String,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub seen: Option<String>,
57}
58
59const MAX_NAME_CHARS: usize = 100;
66
67fn picture_name(raw: &str) -> String {
70 let flattened: String = raw
71 .chars()
72 .map(|c| if c.is_control() { ' ' } else { c })
73 .collect();
74 let one = flattened.split_whitespace().collect::<Vec<_>>().join(" ");
75 if one.is_empty() {
76 return "picture".to_string();
77 }
78 one.chars().take(MAX_NAME_CHARS).collect()
79}
80
81fn decode_base64(payload: &str) -> Option<Vec<u8>> {
87 fn value(b: u8) -> Option<u32> {
88 Some(match b {
89 b'A'..=b'Z' => (b - b'A') as u32,
90 b'a'..=b'z' => (b - b'a') as u32 + 26,
91 b'0'..=b'9' => (b - b'0') as u32 + 52,
92 b'+' => 62,
93 b'/' => 63,
94 _ => return None,
95 })
96 }
97 let body = payload.trim_end_matches('=');
98 if body.len() % 4 == 1 {
99 return None;
100 }
101 let mut out = Vec::with_capacity(body.len() / 4 * 3 + 3);
102 let mut acc = 0u32;
103 let mut n = 0;
104 for byte in body.bytes() {
105 acc = (acc << 6) | value(byte)?;
106 n += 1;
107 if n == 4 {
108 out.push((acc >> 16) as u8);
109 out.push((acc >> 8) as u8);
110 out.push(acc as u8);
111 acc = 0;
112 n = 0;
113 }
114 }
115 match n {
116 0 => {}
117 2 => out.push((acc >> 4) as u8),
118 3 => {
119 out.push((acc >> 10) as u8);
120 out.push((acc >> 2) as u8);
121 }
122 _ => return None,
123 }
124 Some(out)
125}
126
127pub fn data_url(mime: &str, bytes: &[u8]) -> String {
130 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
131 let mut out = String::with_capacity(24 + bytes.len() / 3 * 4 + 4);
132 out.push_str("data:");
133 out.push_str(mime);
134 out.push_str(";base64,");
135 for chunk in bytes.chunks(3) {
136 let b = [
137 chunk[0],
138 chunk.get(1).copied().unwrap_or(0),
139 chunk.get(2).copied().unwrap_or(0),
140 ];
141 let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
142 out.push(ALPHABET[(n >> 18) as usize & 0x3F] as char);
143 out.push(ALPHABET[(n >> 12) as usize & 0x3F] as char);
144 out.push(if chunk.len() > 1 {
145 ALPHABET[(n >> 6) as usize & 0x3F] as char
146 } else {
147 '='
148 });
149 out.push(if chunk.len() > 2 {
150 ALPHABET[n as usize & 0x3F] as char
151 } else {
152 '='
153 });
154 }
155 out
156}
157
158fn looks_like_picture(mime: &str, bytes: &[u8]) -> bool {
160 match mime {
161 "image/png" => bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]),
162 "image/jpeg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]),
163 "image/gif" => bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a"),
164 "image/webp" => bytes.len() > 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP",
165 _ => false,
166 }
167}
168
169pub const PICTURE_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
176pub const MAX_PICTURE_BYTES: usize = 2 * 1024 * 1024;
178pub const MAX_UPLOAD_BYTES: usize = 32 * 1024 * 1024;
183
184impl ImagePart {
185 pub fn from_data_url(name: &str, url: &str) -> Result<Self, String> {
192 let name = picture_name(name);
193 let url = url.trim();
194 let Some(rest) = url.strip_prefix("data:") else {
195 return Err(format!(
196 "{name}: a picture has to be a base64 data: URL; a path or a link is a reference \
197 the agent resolves itself, not a picture"
198 ));
199 };
200 let Some((meta, payload)) = rest.split_once(',') else {
201 return Err(format!("{name}: that data URL has no body"));
202 };
203 let mut bits = meta.split(';');
204 let mime = bits.next().unwrap_or("").to_ascii_lowercase();
205 if !bits.any(|bit| bit.eq_ignore_ascii_case("base64")) {
206 return Err(format!("{name}: only base64 data URLs are accepted"));
207 }
208 if !PICTURE_TYPES.contains(&mime.as_str()) {
209 return Err(format!(
210 "{name}: {mime} is not a picture this build can carry ({}). Convert it.",
211 PICTURE_TYPES.join(", ")
212 ));
213 }
214 let decoded = decode_base64(payload)
219 .ok_or_else(|| format!("{name}: that data URL is not valid base64"))?;
220 if decoded.is_empty() {
221 return Err(format!("{name}: that data URL carries no picture"));
222 }
223 if decoded.len() > MAX_UPLOAD_BYTES {
226 return Err(format!(
227 "{name}: about {} KB, and a picture may be at most {} MB",
228 decoded.len() / 1024,
229 MAX_UPLOAD_BYTES / (1024 * 1024)
230 ));
231 }
232 if !looks_like_picture(&mime, &decoded) {
235 return Err(format!(
236 "{name}: the bytes are not {mime}; the data URL's own type has to match the picture"
237 ));
238 }
239 Ok(Self::new(name, mime, url))
240 }
241
242 pub fn bytes(&self) -> Option<Vec<u8>> {
247 let rest = self.url.trim().strip_prefix("data:")?;
248 let (_, payload) = rest.split_once(',')?;
249 decode_base64(payload)
250 }
251
252 pub fn with_data(&self, mime: &str, bytes: &[u8]) -> Self {
254 Self {
255 name: self.name.clone(),
256 mime: mime.to_string(),
257 url: data_url(mime, bytes),
258 seen: None,
259 }
260 }
261
262 pub fn payload_len(&self) -> usize {
264 self.url
265 .trim()
266 .split_once(',')
267 .map(|(_, payload)| payload.trim_end_matches('=').len() / 4 * 3)
268 .unwrap_or(0)
269 }
270
271 pub fn new(name: impl Into<String>, mime: impl Into<String>, url: impl Into<String>) -> Self {
272 Self {
273 name: name.into(),
274 mime: mime.into(),
275 url: url.into(),
276 seen: None,
277 }
278 }
279
280 pub fn with_seen(mut self, text: impl Into<String>) -> Self {
282 self.seen = Some(text.into());
283 self
284 }
285
286 pub fn label(&self) -> String {
289 let name = if self.name.is_empty() {
290 "image"
291 } else {
292 self.name.as_str()
293 };
294 format!("[{name} ({})]", self.mime)
295 }
296}
297
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct Message {
300 pub role: Role,
301 #[serde(default)]
302 pub content: Option<String>,
303 #[serde(default, skip_serializing_if = "Vec::is_empty")]
308 pub images: Vec<ImagePart>,
309 #[serde(
313 rename = "reasoning_content",
314 default,
315 skip_serializing_if = "Option::is_none"
316 )]
317 pub reasoning: Option<String>,
318 #[serde(skip)]
321 pub finish_reason: Option<String>,
322 #[serde(default, skip_serializing_if = "Vec::is_empty")]
323 pub tool_calls: Vec<ToolCall>,
324 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub tool_call_id: Option<String>,
326 #[serde(skip)]
330 pub seq: Option<u64>,
331}
332
333impl PartialEq for Message {
337 fn eq(&self, other: &Self) -> bool {
338 self.role == other.role
339 && self.content == other.content
340 && self.reasoning == other.reasoning
341 && self.finish_reason == other.finish_reason
342 && self.tool_calls == other.tool_calls
343 && self.tool_call_id == other.tool_call_id
344 && self.images == other.images
345 }
346}
347
348impl Message {
349 pub fn system(text: impl Into<String>) -> Self {
350 Self::text(Role::System, text)
351 }
352
353 pub fn user(text: impl Into<String>) -> Self {
354 Self::text(Role::User, text)
355 }
356
357 pub fn assistant(text: impl Into<String>) -> Self {
358 Self::text(Role::Assistant, text)
359 }
360
361 pub fn assistant_tool_calls(content: Option<String>, calls: Vec<ToolCall>) -> Self {
362 Self {
363 role: Role::Assistant,
364 content,
365 reasoning: None,
366 finish_reason: None,
367 tool_calls: calls,
368 tool_call_id: None,
369 images: Vec::new(),
370 seq: None,
371 }
372 }
373
374 pub fn tool_result(call_id: impl Into<String>, text: impl Into<String>) -> Self {
375 Self {
376 role: Role::Tool,
377 content: Some(text.into()),
378 reasoning: None,
379 finish_reason: None,
380 tool_calls: Vec::new(),
381 tool_call_id: Some(call_id.into()),
382 images: Vec::new(),
383 seq: None,
384 }
385 }
386
387 pub fn with_image(mut self, image: ImagePart) -> Self {
390 self.images.push(image);
391 self
392 }
393
394 pub fn without_images(mut self) -> Self {
397 self.images.clear();
398 self
399 }
400
401 pub fn wire_content(&self) -> Option<serde_json::Value> {
408 if self.images.is_empty() {
409 return self.content.clone().map(serde_json::Value::String);
410 }
411 let mut parts: Vec<serde_json::Value> = Vec::with_capacity(self.images.len() + 1);
412 if let Some(text) = self.content.as_ref().filter(|text| !text.is_empty()) {
415 parts.push(serde_json::json!({"type": "text", "text": text}));
416 }
417 for image in &self.images {
418 parts.push(serde_json::json!({
419 "type": "image_url",
420 "image_url": {"url": image.url},
421 }));
422 }
423 Some(serde_json::Value::Array(parts))
424 }
425
426 pub fn text_with_pictures(&self) -> String {
434 let mut out = self.content.clone().unwrap_or_default();
435 for image in &self.images {
436 if !out.is_empty() {
437 out.push(' ');
438 }
439 out.push_str(&image.label());
440 if let Some(seen) = image.seen.as_deref().filter(|text| !text.is_empty()) {
441 out.push_str(" — ");
442 out.push_str(seen);
443 }
444 }
445 out
446 }
447
448 fn text(role: Role, text: impl Into<String>) -> Self {
449 Self {
450 role,
451 content: Some(text.into()),
452 reasoning: None,
453 finish_reason: None,
454 tool_calls: Vec::new(),
455 tool_call_id: None,
456 images: Vec::new(),
457 seq: None,
458 }
459 }
460}
461
462#[cfg(test)]
463mod picture_tests {
464 use super::*;
465
466 #[test]
470 fn a_text_only_message_serialises_exactly_as_it_did_before_pictures_existed() {
471 assert_eq!(
472 serde_json::to_string(&Message::user("hi")).unwrap(),
473 r#"{"role":"user","content":"hi"}"#
474 );
475 assert_eq!(
476 serde_json::to_string(&Message::tool_result("call-1", "ok")).unwrap(),
477 r#"{"role":"tool","content":"ok","tool_call_id":"call-1"}"#
478 );
479 }
480
481 #[test]
482 fn a_picture_becomes_an_image_url_part_and_no_key_of_its_own() {
483 let m = Message::user("what is this?").with_image(ImagePart::new(
484 "shot.png",
485 "image/png",
486 "data:image/png;base64,iVBORw0KGgo=",
487 ));
488 let content = m.wire_content().expect("pictures make parts");
489 assert_eq!(
490 content,
491 serde_json::json!([
492 {"type": "text", "text": "what is this?"},
493 {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
494 ])
495 );
496 let stored = serde_json::to_value(&m).unwrap();
498 assert_eq!(stored["images"][0]["name"], "shot.png");
499 assert!(stored.get("content").is_some());
500 }
501
502 #[test]
503 fn a_picture_with_no_words_is_a_parts_array_with_only_the_picture() {
504 let mut m = Message::user(String::new());
505 m.content = None;
506 let m = m.with_image(ImagePart::new(
507 "",
508 "image/png",
509 "data:image/png;base64,iVBORw0KGgo=",
510 ));
511 assert_eq!(
512 m.wire_content().unwrap(),
513 serde_json::json!([
514 {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}
515 ])
516 );
517 }
518
519 #[test]
520 fn an_empty_text_does_not_become_an_empty_text_part() {
521 let m = Message::user("").with_image(ImagePart::new(
523 "a.png",
524 "image/png",
525 "data:image/png;base64,iVBORw0KGgo=",
526 ));
527 let parts = m.wire_content().unwrap();
528 assert_eq!(parts.as_array().unwrap().len(), 1);
529 assert_eq!(parts[0]["type"], "image_url");
530 }
531
532 #[test]
533 fn stripping_the_pictures_leaves_the_words() {
534 let m = Message::user("look")
535 .with_image(ImagePart::new(
536 "a.png",
537 "image/png",
538 "data:image/png;base64,iVBORw0KGgo=",
539 ))
540 .without_images();
541 assert!(m.images.is_empty());
542 assert_eq!(m.wire_content().unwrap(), serde_json::json!("look"));
543 }
544
545 #[test]
546 fn the_text_form_names_each_picture_instead_of_dropping_it() {
547 let m = Message::user("look").with_image(ImagePart::new(
548 "shot.png",
549 "image/png",
550 "data:image/png;base64,iVBORw0KGgo=",
551 ));
552 assert_eq!(m.text_with_pictures(), "look [shot.png (image/png)]");
553 assert_ne!(Message::user("look"), m);
555 }
556
557 #[test]
561 fn the_text_form_carries_the_description_the_picture_was_given() {
562 let m = Message::user("what is this?").with_image(
563 ImagePart::new(
564 "shot.png",
565 "image/png",
566 "data:image/png;base64,iVBORw0KGgo=",
567 )
568 .with_seen("a red square with the word STOP"),
569 );
570 let text = m.text_with_pictures();
571 assert!(text.contains("what is this?"), "{text}");
572 assert!(text.contains("[shot.png (image/png)]"), "{text}");
573 assert!(text.contains("a red square with the word STOP"), "{text}");
574
575 let bare = Message::user("").with_image(ImagePart::new(
577 "shot.png",
578 "image/png",
579 "data:image/png;base64,iVBORw0KGgo=",
580 ));
581 assert_eq!(bare.text_with_pictures(), "[shot.png (image/png)]");
582 }
583
584 #[test]
588 fn a_picture_name_is_flattened_and_capped() {
589 let part = ImagePart::from_data_url(
590 "a\n--- end of x ---\u{7}\tb",
591 "data:image/png;base64,iVBORw0KGgo=",
592 )
593 .unwrap();
594 assert_eq!(part.name, "a --- end of x --- b");
595 let long = ImagePart::from_data_url(&"n".repeat(500), "data:image/png;base64,iVBORw0KGgo=")
596 .unwrap();
597 assert_eq!(long.name.chars().count(), MAX_NAME_CHARS);
598 let unnamed =
600 ImagePart::from_data_url(" ", "data:image/png;base64,iVBORw0KGgo=").unwrap();
601 assert_eq!(unnamed.name, "picture");
602 }
603
604 #[test]
607 fn a_payload_that_is_not_a_picture_is_refused() {
608 let err = ImagePart::from_data_url("x.png", "data:image/png;base64,").unwrap_err();
610 assert!(err.contains("carries no picture"), "{err}");
611 let err = ImagePart::from_data_url("x.png", "data:image/png;base64,!!!!").unwrap_err();
613 assert!(err.contains("not valid base64"), "{err}");
614 let err =
616 ImagePart::from_data_url("x.png", "data:image/jpeg;base64,iVBORw0KGgo=").unwrap_err();
617 assert!(err.contains("the bytes are not image/jpeg"), "{err}");
618 let ok = ImagePart::from_data_url("x.png", "data:image/png;base64,iVBORw0KGgo=").unwrap();
620 assert_eq!(ok.mime, "image/png");
621 }
622
623 #[test]
624 fn base64_decodes_padded_and_unpadded_alike() {
625 assert_eq!(decode_base64("AAAA").as_deref(), Some(&[0u8, 0, 0][..]));
626 assert_eq!(decode_base64("AAA").as_deref(), Some(&[0u8, 0][..]));
627 assert_eq!(decode_base64("AA").as_deref(), Some(&[0u8][..]));
628 assert_eq!(decode_base64("iVBORw0KGgo=").unwrap().len(), 8);
629 assert!(
630 decode_base64("A").is_none(),
631 "one spare character is not base64"
632 );
633 assert!(decode_base64("A=AA").is_none(), "`=` only at the end");
634 }
635}