1use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use tokio::sync::mpsc::UnboundedSender;
8
9use crate::cancel::CancelToken;
10use crate::session::AgentEvent;
11use crate::tool::ToolSpec;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15#[non_exhaustive]
16pub enum Role {
17 System,
18 User,
19 Assistant,
20 Tool,
21}
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub struct ToolCall {
26 pub id: String,
27 pub name: String,
28 #[serde(default)]
29 pub arguments: Value,
30}
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38#[serde(untagged)]
39pub enum Content {
40 Text(String),
41 Parts(Vec<ContentPart>),
42}
43
44impl Default for Content {
45 fn default() -> Self {
46 Content::Text(String::new())
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[serde(tag = "type", rename_all = "snake_case")]
53#[non_exhaustive]
54pub enum ContentPart {
55 Text {
56 text: String,
57 },
58 ImageUrl {
60 image_url: ImageUrl,
61 },
62 InputAudio {
64 input_audio: InputAudio,
65 },
66 VideoUrl {
72 video_url: VideoUrl,
73 },
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[non_exhaustive]
78pub struct ImageUrl {
79 pub url: String,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub detail: Option<String>,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[non_exhaustive]
91pub struct VideoUrl {
92 pub url: String,
94}
95
96impl VideoUrl {
97 pub fn mime_type(&self) -> Option<&str> {
99 let rest = self.url.strip_prefix("data:")?;
100 let end = rest.find([';', ','])?;
101 Some(&rest[..end]).filter(|m| !m.is_empty())
102 }
103
104 pub fn data_len(&self) -> Option<u64> {
109 let (head, data) = self.url.strip_prefix("data:")?.split_once(',')?;
110 if !head.ends_with(";base64") {
111 return None;
112 }
113 let data = data.trim_end();
114 let pad = data.bytes().rev().take_while(|b| *b == b'=').count().min(2);
115 Some((data.len() as u64 * 3 / 4).saturating_sub(pad as u64))
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct InputAudio {
122 pub data: String,
124 pub format: String,
125}
126
127impl ContentPart {
128 pub fn text(text: impl Into<String>) -> Self {
129 ContentPart::Text { text: text.into() }
130 }
131
132 pub fn image(url: impl Into<String>) -> Self {
134 ContentPart::ImageUrl { image_url: ImageUrl { url: url.into(), detail: None } }
135 }
136
137 pub fn audio(data: impl Into<String>, format: impl Into<String>) -> Self {
138 ContentPart::InputAudio { input_audio: InputAudio { data: data.into(), format: format.into() } }
139 }
140
141 pub fn video(url: impl Into<String>) -> Self {
144 ContentPart::VideoUrl { video_url: VideoUrl { url: url.into() } }
145 }
146
147 pub fn video_bytes(bytes: &[u8], mime_type: &str) -> Self {
150 use base64::Engine as _;
151 Self::video(format!("data:{mime_type};base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)))
152 }
153
154 pub fn needs(&self) -> Modalities {
156 match self {
157 ContentPart::Text { .. } => Modalities::TEXT,
158 ContentPart::ImageUrl { .. } => Modalities::VISION,
159 ContentPart::InputAudio { .. } => Modalities::AUDIO,
160 ContentPart::VideoUrl { .. } => Modalities::VIDEO,
161 }
162 }
163}
164
165impl Content {
166 pub fn text(&self) -> std::borrow::Cow<'_, str> {
168 match self {
169 Content::Text(t) => std::borrow::Cow::Borrowed(t),
170 Content::Parts(parts) => parts
171 .iter()
172 .filter_map(|p| match p {
173 ContentPart::Text { text } => Some(text.as_str()),
174 _ => None,
175 })
176 .collect::<String>()
177 .into(),
178 }
179 }
180
181 pub fn as_text(&self) -> Option<&str> {
183 match self {
184 Content::Text(t) => Some(t),
185 Content::Parts(_) => None,
186 }
187 }
188
189 pub fn into_text(self) -> String {
191 match self {
192 Content::Text(t) => t,
193 other => other.text().into_owned(),
194 }
195 }
196
197 pub fn parts(&self) -> Vec<ContentPart> {
199 match self {
200 Content::Text(t) => vec![ContentPart::text(t.clone())],
201 Content::Parts(p) => p.clone(),
202 }
203 }
204
205 pub fn is_empty(&self) -> bool {
206 match self {
207 Content::Text(t) => t.is_empty(),
208 Content::Parts(p) => p.is_empty(),
209 }
210 }
211
212 pub fn needs(&self) -> Modalities {
214 match self {
215 Content::Text(_) => Modalities::TEXT,
216 Content::Parts(p) => p.iter().fold(Modalities::TEXT, |m, part| m.union(part.needs())),
217 }
218 }
219
220 pub fn normalized(self) -> Self {
223 match self {
224 Content::Parts(p) if p.iter().all(|x| matches!(x, ContentPart::Text { .. })) => Content::Parts(p).into_text().into(),
225 other => other,
226 }
227 }
228
229 pub fn check(&self) -> Result<(), String> {
232 let Content::Parts(parts) = self else { return Ok(()) };
233 for p in parts {
234 match p {
235 ContentPart::ImageUrl { image_url } if !image_url.url.starts_with("data:image/") => {
236 return Err("image_url must be a data:image/... URL; remote image URLs are not fetched".into());
237 }
238 ContentPart::InputAudio { input_audio } if input_audio.format.is_empty() || input_audio.data.is_empty() => {
239 return Err("input_audio needs data and a format".into());
240 }
241 ContentPart::VideoUrl { video_url } if !video_url.url.starts_with("data:video/") => {
242 return Err("video_url must be a data:video/... URL; remote video URLs are not fetched".into());
243 }
244 _ => {}
245 }
246 }
247 Ok(())
248 }
249}
250
251impl From<String> for Content {
252 fn from(s: String) -> Self {
253 Content::Text(s)
254 }
255}
256
257impl From<&str> for Content {
258 fn from(s: &str) -> Self {
259 Content::Text(s.to_string())
260 }
261}
262
263impl From<&String> for Content {
264 fn from(s: &String) -> Self {
265 Content::Text(s.clone())
266 }
267}
268
269impl From<Vec<ContentPart>> for Content {
270 fn from(p: Vec<ContentPart>) -> Self {
271 Content::Parts(p)
272 }
273}
274
275impl PartialEq<str> for Content {
276 fn eq(&self, other: &str) -> bool {
277 self.as_text() == Some(other)
278 }
279}
280
281impl PartialEq<&str> for Content {
282 fn eq(&self, other: &&str) -> bool {
283 self.as_text() == Some(*other)
284 }
285}
286
287impl std::fmt::Display for Content {
288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289 f.write_str(&self.text())
290 }
291}
292
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
295#[non_exhaustive]
296pub struct Modalities {
297 #[serde(default, skip_serializing_if = "is_false")]
299 pub vision: bool,
300 #[serde(default, skip_serializing_if = "is_false")]
302 pub audio: bool,
303 #[serde(default, skip_serializing_if = "is_false")]
306 pub video: bool,
307}
308
309fn is_false(b: &bool) -> bool {
310 !*b
311}
312
313impl Modalities {
314 pub const TEXT: Self = Self { vision: false, audio: false, video: false };
316 pub const VISION: Self = Self { vision: true, audio: false, video: false };
317 pub const AUDIO: Self = Self { vision: false, audio: true, video: false };
318 pub const VIDEO: Self = Self { vision: false, audio: false, video: true };
320
321 pub fn new(vision: bool, audio: bool) -> Self {
323 Self { vision, audio, video: false }
324 }
325
326 pub fn with_video(mut self, video: bool) -> Self {
328 self.video = video;
329 self
330 }
331
332 pub fn is_text(&self) -> bool {
333 !self.vision && !self.audio && !self.video
334 }
335
336 pub fn union(self, other: Self) -> Self {
337 Self { vision: self.vision || other.vision, audio: self.audio || other.audio, video: self.video || other.video }
338 }
339
340 pub fn covers(&self, needed: Modalities) -> bool {
342 (self.vision || !needed.vision) && (self.audio || !needed.audio) && (self.video || !needed.video)
343 }
344
345 pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
349 match (needed.vision && !self.vision, needed.audio && !self.audio, needed.video && !self.video) {
350 (true, true, true) => Some("images, audio and video"),
351 (true, true, false) => Some("images and audio"),
352 (true, false, true) => Some("images and video"),
353 (false, true, true) => Some("audio and video"),
354 (true, false, false) => Some("images"),
355 (false, true, false) => Some("audio"),
356 (false, false, true) => Some("video"),
357 (false, false, false) => None,
358 }
359 }
360}
361
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363pub struct Message {
364 pub role: Role,
365 pub content: Content,
366 #[serde(default, skip_serializing_if = "Vec::is_empty")]
367 pub tool_calls: Vec<ToolCall>,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub tool_call_id: Option<String>,
370}
371
372impl Message {
373 pub fn system(content: impl Into<Content>) -> Self {
374 Self { role: Role::System, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
375 }
376
377 pub fn user(content: impl Into<Content>) -> Self {
380 Self { role: Role::User, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
381 }
382
383 pub fn assistant(content: impl Into<Content>, tool_calls: Vec<ToolCall>) -> Self {
384 Self { role: Role::Assistant, content: content.into(), tool_calls, tool_call_id: None }
385 }
386
387 pub fn tool(call_id: impl Into<String>, content: impl Into<Content>) -> Self {
388 Self { role: Role::Tool, content: content.into(), tool_calls: Vec::new(), tool_call_id: Some(call_id.into()) }
389 }
390
391 pub fn text(&self) -> std::borrow::Cow<'_, str> {
393 self.content.text()
394 }
395
396 pub fn needs(&self) -> Modalities {
398 self.content.needs()
399 }
400}
401
402pub fn needs(messages: &[Message]) -> Modalities {
404 messages.iter().fold(Modalities::TEXT, |m, msg| m.union(msg.needs()))
405}
406
407#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
409pub struct ModelTurn {
410 pub text: String,
411 #[serde(default)]
412 pub tool_calls: Vec<ToolCall>,
413}
414
415#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
416#[non_exhaustive]
417pub enum ModelError {
418 #[error("model unavailable: {0}")]
419 Unavailable(String),
420 #[error("model failed: {0}")]
421 Failed(String),
422 #[error("cancelled")]
423 Cancelled,
424 #[error("model pool unreachable: {0}")]
428 PoolUnreachable(String),
429}
430
431#[derive(Debug, Clone, PartialEq, Eq)]
434#[non_exhaustive]
435pub enum ModelNotice {
436 Continued { node: String, offset: u64 },
439 FellBack { reason: String, to: String },
442 Rerouted { from: String, needs: String },
445}
446
447#[derive(Debug, Clone)]
449pub struct DeltaSink {
450 tx: Option<UnboundedSender<AgentEvent>>,
451}
452
453impl DeltaSink {
454 pub fn new(tx: Option<UnboundedSender<AgentEvent>>) -> Self {
455 Self { tx }
456 }
457
458 pub fn discard() -> Self {
460 Self { tx: None }
461 }
462
463 pub fn text(&self, delta: impl Into<String>) {
464 if let Some(tx) = &self.tx {
465 let _ = tx.send(AgentEvent::TextDelta(delta.into()));
466 }
467 }
468
469 pub fn reasoning(&self, delta: impl Into<String>) {
472 if let Some(tx) = &self.tx {
473 let _ = tx.send(AgentEvent::ReasoningDelta(delta.into()));
474 }
475 }
476
477 pub fn notice(&self, notice: ModelNotice) {
479 if let Some(tx) = &self.tx {
480 let _ = tx.send(AgentEvent::ModelNotice(notice));
481 }
482 }
483}
484
485#[async_trait]
488pub trait ModelBackend: Send + Sync {
489 fn name(&self) -> String;
491
492 async fn complete(&self, messages: &[Message], tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError>;
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 const PNG: &str = "data:image/png;base64,iVBORw0KGgo=";
500
501 #[test]
502 fn text_content_keeps_the_plain_string_wire_form() {
503 let m = Message::user("hi");
504 assert_eq!(serde_json::to_value(&m).unwrap(), serde_json::json!({"role": "user", "content": "hi"}));
505 let cbor = crate::remote::to_cbor(&m).unwrap();
506 #[derive(Deserialize)]
507 struct Old {
508 content: String,
509 }
510 assert_eq!(crate::remote::from_cbor::<Old>(&cbor).unwrap().content, "hi", "a 0.4 peer reads it");
511 let old = serde_json::json!({"role": "user", "content": "from 0.4"});
512 assert_eq!(serde_json::from_value::<Message>(old).unwrap().content, "from 0.4");
513 }
514
515 #[test]
516 fn parts_round_trip_in_json_and_cbor() {
517 let m = Message::user(vec![ContentPart::text("what is it?"), ContentPart::image(PNG), ContentPart::audio("UklGRg==", "wav")]);
518 let j = serde_json::to_value(&m).unwrap();
519 assert_eq!(
520 j["content"],
521 serde_json::json!([
522 {"type": "text", "text": "what is it?"},
523 {"type": "image_url", "image_url": {"url": PNG}},
524 {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}
525 ])
526 );
527 assert_eq!(serde_json::from_value::<Message>(j).unwrap(), m);
528 let back: Message = crate::remote::from_cbor(&crate::remote::to_cbor(&m).unwrap()).unwrap();
529 assert_eq!(back, m);
530 assert_eq!(m.needs(), Modalities::new(true, true));
531 assert_eq!(m.text(), "what is it?");
532 }
533
534 #[test]
535 fn needs_covers_and_lacking() {
536 let msgs = [Message::system("s"), Message::user(vec![ContentPart::image(PNG)])];
537 let n = needs(&msgs);
538 assert_eq!(n, Modalities::VISION);
539 assert!(Modalities::VISION.covers(n) && !Modalities::TEXT.covers(n) && !Modalities::AUDIO.covers(n));
540 assert_eq!(Modalities::TEXT.lacking(Modalities::new(true, true)), Some("images and audio"));
541 assert_eq!(Modalities::VISION.lacking(n), None);
542 assert!(needs(&[Message::user("x")]).is_text());
543 }
544
545 #[test]
546 fn check_refuses_remote_images_and_empty_audio() {
547 assert!(Content::from(vec![ContentPart::image(PNG)]).check().is_ok());
548 assert!(Content::from(vec![ContentPart::image("https://example.com/a.png")]).check().is_err());
549 assert!(Content::from(vec![ContentPart::audio("", "wav")]).check().is_err());
550 assert!(Content::from("text").check().is_ok());
551 }
552
553 const MP4: &str = "data:video/mp4;base64,AAAAIGZ0eXBpc29t";
554
555 #[test]
556 fn video_parts_round_trip_in_json_and_cbor() {
557 let m = Message::user(vec![ContentPart::text("what happens?"), ContentPart::video(MP4)]);
558 let j = serde_json::to_value(&m).unwrap();
559 assert_eq!(j["content"], serde_json::json!([{"type": "text", "text": "what happens?"}, {"type": "video_url", "video_url": {"url": MP4}}]));
560 assert_eq!(serde_json::from_value::<Message>(j).unwrap(), m);
561 let cbor = crate::remote::to_cbor(&m).unwrap();
562 assert_eq!(crate::remote::from_cbor::<Message>(&cbor).unwrap(), m);
563 assert_eq!(m.needs(), Modalities::VIDEO);
564 assert_eq!(m.text(), "what happens?");
565 let mixed = Message::user(vec![ContentPart::image(PNG), ContentPart::video(MP4), ContentPart::audio("UklGRg==", "wav")]);
566 assert_eq!(mixed.needs(), Modalities::new(true, true).with_video(true));
567 let newer = serde_json::json!({"role": "user", "content": [{"type": "hologram_url", "hologram_url": {"url": "x"}}]});
570 assert!(serde_json::from_value::<Message>(newer).is_err());
571 }
572
573 #[test]
574 fn video_bytes_mime_and_size() {
575 let clip = b"\x00\x00\x00\x20ftypisom-a-tiny-clip";
576 let ContentPart::VideoUrl { video_url } = ContentPart::video_bytes(clip, "video/mp4") else { panic!("a video part") };
577 assert!(video_url.url.starts_with("data:video/mp4;base64,"));
578 assert_eq!(video_url.mime_type(), Some("video/mp4"));
579 assert_eq!(video_url.data_len(), Some(clip.len() as u64));
580 for n in 0..8usize {
581 let ContentPart::VideoUrl { video_url } = ContentPart::video_bytes(&vec![7u8; n], "video/webm") else { unreachable!() };
582 assert_eq!(video_url.data_len(), Some(n as u64), "{n} bytes");
583 }
584 let remote = VideoUrl { url: "https://example.com/a.mp4".into() };
585 assert_eq!((remote.mime_type(), remote.data_len()), (None, None));
586 assert_eq!(VideoUrl { url: "data:video/mp4,raw".into() }.data_len(), None, "not base64");
587 assert!(Content::from(vec![ContentPart::video(MP4)]).check().is_ok());
588 assert!(Content::from(vec![ContentPart::video("https://example.com/a.mp4")]).check().is_err());
589 assert!(Content::from(vec![ContentPart::video("data:image/png;base64,iVBORw0KGgo=")]).check().is_err());
590 let v = Content::from(vec![ContentPart::video(MP4)]);
591 assert_eq!(v.clone().normalized(), v, "video stays parts");
592 }
593
594 #[test]
595 fn video_modality() {
596 let v = Modalities::VIDEO;
597 assert!(!v.is_text() && v.video && !v.vision && !v.audio);
598 assert_eq!(Modalities::new(true, false).with_video(true), Modalities::VISION.union(Modalities::VIDEO));
599 assert!(Modalities::VIDEO.covers(Modalities::VIDEO) && !Modalities::new(true, true).covers(Modalities::VIDEO));
600 assert!(Modalities::VIDEO.covers(Modalities::TEXT) && !Modalities::VIDEO.covers(Modalities::VISION));
601 let all = Modalities::new(true, true).with_video(true);
602 assert_eq!(Modalities::TEXT.lacking(all), Some("images, audio and video"));
603 assert_eq!(Modalities::AUDIO.lacking(all), Some("images and video"));
604 assert_eq!(Modalities::VISION.lacking(all), Some("audio and video"));
605 assert_eq!(Modalities::VIDEO.lacking(all), Some("images and audio"));
606 assert_eq!(Modalities::new(true, true).lacking(all), Some("video"));
607 assert_eq!(all.lacking(all), None);
608 assert_eq!(serde_json::to_value(Modalities::new(true, true)).unwrap(), serde_json::json!({"vision": true, "audio": true}));
610 assert_eq!(serde_json::to_value(Modalities::VIDEO).unwrap(), serde_json::json!({"video": true}));
611 assert_eq!(serde_json::from_str::<Modalities>(r#"{"vision":true}"#).unwrap(), Modalities::VISION);
612 let back: Modalities = crate::remote::from_cbor(&crate::remote::to_cbor(&all).unwrap()).unwrap();
613 assert_eq!(back, all);
614 #[derive(Deserialize, PartialEq, Debug)]
615 struct Old {
616 #[serde(default)]
617 vision: bool,
618 #[serde(default)]
619 audio: bool,
620 }
621 let old: Old = crate::remote::from_cbor(&crate::remote::to_cbor(&all).unwrap()).unwrap();
622 assert_eq!(old, Old { vision: true, audio: true }, "a 0.5.9 peer reads the rest and ignores video");
623 }
624
625 #[test]
626 fn text_parts_normalize_to_a_string() {
627 let c = Content::from(vec![ContentPart::text("a"), ContentPart::text("b")]).normalized();
628 assert_eq!(c, Content::Text("ab".into()));
629 let img = Content::from(vec![ContentPart::image(PNG)]);
630 assert_eq!(img.clone().normalized(), img);
631 }
632}