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}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[non_exhaustive]
70pub struct ImageUrl {
71 pub url: String,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub detail: Option<String>,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[non_exhaustive]
79pub struct InputAudio {
80 pub data: String,
82 pub format: String,
83}
84
85impl ContentPart {
86 pub fn text(text: impl Into<String>) -> Self {
87 ContentPart::Text { text: text.into() }
88 }
89
90 pub fn image(url: impl Into<String>) -> Self {
92 ContentPart::ImageUrl { image_url: ImageUrl { url: url.into(), detail: None } }
93 }
94
95 pub fn audio(data: impl Into<String>, format: impl Into<String>) -> Self {
96 ContentPart::InputAudio { input_audio: InputAudio { data: data.into(), format: format.into() } }
97 }
98
99 pub fn needs(&self) -> Modalities {
101 match self {
102 ContentPart::Text { .. } => Modalities::TEXT,
103 ContentPart::ImageUrl { .. } => Modalities::VISION,
104 ContentPart::InputAudio { .. } => Modalities::AUDIO,
105 }
106 }
107}
108
109impl Content {
110 pub fn text(&self) -> std::borrow::Cow<'_, str> {
112 match self {
113 Content::Text(t) => std::borrow::Cow::Borrowed(t),
114 Content::Parts(parts) => parts
115 .iter()
116 .filter_map(|p| match p {
117 ContentPart::Text { text } => Some(text.as_str()),
118 _ => None,
119 })
120 .collect::<String>()
121 .into(),
122 }
123 }
124
125 pub fn as_text(&self) -> Option<&str> {
127 match self {
128 Content::Text(t) => Some(t),
129 Content::Parts(_) => None,
130 }
131 }
132
133 pub fn into_text(self) -> String {
135 match self {
136 Content::Text(t) => t,
137 other => other.text().into_owned(),
138 }
139 }
140
141 pub fn parts(&self) -> Vec<ContentPart> {
143 match self {
144 Content::Text(t) => vec![ContentPart::text(t.clone())],
145 Content::Parts(p) => p.clone(),
146 }
147 }
148
149 pub fn is_empty(&self) -> bool {
150 match self {
151 Content::Text(t) => t.is_empty(),
152 Content::Parts(p) => p.is_empty(),
153 }
154 }
155
156 pub fn needs(&self) -> Modalities {
158 match self {
159 Content::Text(_) => Modalities::TEXT,
160 Content::Parts(p) => p.iter().fold(Modalities::TEXT, |m, part| m.union(part.needs())),
161 }
162 }
163
164 pub fn normalized(self) -> Self {
167 match self {
168 Content::Parts(p) if p.iter().all(|x| matches!(x, ContentPart::Text { .. })) => Content::Parts(p).into_text().into(),
169 other => other,
170 }
171 }
172
173 pub fn check(&self) -> Result<(), String> {
176 let Content::Parts(parts) = self else { return Ok(()) };
177 for p in parts {
178 match p {
179 ContentPart::ImageUrl { image_url } if !image_url.url.starts_with("data:image/") => {
180 return Err("image_url must be a data:image/... URL; remote image URLs are not fetched".into());
181 }
182 ContentPart::InputAudio { input_audio } if input_audio.format.is_empty() || input_audio.data.is_empty() => {
183 return Err("input_audio needs data and a format".into());
184 }
185 _ => {}
186 }
187 }
188 Ok(())
189 }
190}
191
192impl From<String> for Content {
193 fn from(s: String) -> Self {
194 Content::Text(s)
195 }
196}
197
198impl From<&str> for Content {
199 fn from(s: &str) -> Self {
200 Content::Text(s.to_string())
201 }
202}
203
204impl From<&String> for Content {
205 fn from(s: &String) -> Self {
206 Content::Text(s.clone())
207 }
208}
209
210impl From<Vec<ContentPart>> for Content {
211 fn from(p: Vec<ContentPart>) -> Self {
212 Content::Parts(p)
213 }
214}
215
216impl PartialEq<str> for Content {
217 fn eq(&self, other: &str) -> bool {
218 self.as_text() == Some(other)
219 }
220}
221
222impl PartialEq<&str> for Content {
223 fn eq(&self, other: &&str) -> bool {
224 self.as_text() == Some(*other)
225 }
226}
227
228impl std::fmt::Display for Content {
229 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230 f.write_str(&self.text())
231 }
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
236#[non_exhaustive]
237pub struct Modalities {
238 #[serde(default, skip_serializing_if = "is_false")]
240 pub vision: bool,
241 #[serde(default, skip_serializing_if = "is_false")]
243 pub audio: bool,
244}
245
246fn is_false(b: &bool) -> bool {
247 !*b
248}
249
250impl Modalities {
251 pub const TEXT: Self = Self { vision: false, audio: false };
253 pub const VISION: Self = Self { vision: true, audio: false };
254 pub const AUDIO: Self = Self { vision: false, audio: true };
255
256 pub fn new(vision: bool, audio: bool) -> Self {
257 Self { vision, audio }
258 }
259
260 pub fn is_text(&self) -> bool {
261 !self.vision && !self.audio
262 }
263
264 pub fn union(self, other: Self) -> Self {
265 Self { vision: self.vision || other.vision, audio: self.audio || other.audio }
266 }
267
268 pub fn covers(&self, needed: Modalities) -> bool {
270 (self.vision || !needed.vision) && (self.audio || !needed.audio)
271 }
272
273 pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
275 match (needed.vision && !self.vision, needed.audio && !self.audio) {
276 (true, true) => Some("images and audio"),
277 (true, false) => Some("images"),
278 (false, true) => Some("audio"),
279 (false, false) => None,
280 }
281 }
282}
283
284#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
285pub struct Message {
286 pub role: Role,
287 pub content: Content,
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 pub tool_calls: Vec<ToolCall>,
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub tool_call_id: Option<String>,
292}
293
294impl Message {
295 pub fn system(content: impl Into<Content>) -> Self {
296 Self { role: Role::System, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
297 }
298
299 pub fn user(content: impl Into<Content>) -> Self {
302 Self { role: Role::User, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
303 }
304
305 pub fn assistant(content: impl Into<Content>, tool_calls: Vec<ToolCall>) -> Self {
306 Self { role: Role::Assistant, content: content.into(), tool_calls, tool_call_id: None }
307 }
308
309 pub fn tool(call_id: impl Into<String>, content: impl Into<Content>) -> Self {
310 Self { role: Role::Tool, content: content.into(), tool_calls: Vec::new(), tool_call_id: Some(call_id.into()) }
311 }
312
313 pub fn text(&self) -> std::borrow::Cow<'_, str> {
315 self.content.text()
316 }
317
318 pub fn needs(&self) -> Modalities {
320 self.content.needs()
321 }
322}
323
324pub fn needs(messages: &[Message]) -> Modalities {
326 messages.iter().fold(Modalities::TEXT, |m, msg| m.union(msg.needs()))
327}
328
329#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
331pub struct ModelTurn {
332 pub text: String,
333 #[serde(default)]
334 pub tool_calls: Vec<ToolCall>,
335}
336
337#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
338#[non_exhaustive]
339pub enum ModelError {
340 #[error("model unavailable: {0}")]
341 Unavailable(String),
342 #[error("model failed: {0}")]
343 Failed(String),
344 #[error("cancelled")]
345 Cancelled,
346}
347
348#[derive(Debug, Clone)]
350pub struct DeltaSink {
351 tx: Option<UnboundedSender<AgentEvent>>,
352}
353
354impl DeltaSink {
355 pub fn new(tx: Option<UnboundedSender<AgentEvent>>) -> Self {
356 Self { tx }
357 }
358
359 pub fn discard() -> Self {
361 Self { tx: None }
362 }
363
364 pub fn text(&self, delta: impl Into<String>) {
365 if let Some(tx) = &self.tx {
366 let _ = tx.send(AgentEvent::TextDelta(delta.into()));
367 }
368 }
369
370 pub fn reasoning(&self, delta: impl Into<String>) {
373 if let Some(tx) = &self.tx {
374 let _ = tx.send(AgentEvent::ReasoningDelta(delta.into()));
375 }
376 }
377}
378
379#[async_trait]
382pub trait ModelBackend: Send + Sync {
383 fn name(&self) -> String;
385
386 async fn complete(&self, messages: &[Message], tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError>;
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 const PNG: &str = "data:image/png;base64,iVBORw0KGgo=";
394
395 #[test]
396 fn text_content_keeps_the_plain_string_wire_form() {
397 let m = Message::user("hi");
398 assert_eq!(serde_json::to_value(&m).unwrap(), serde_json::json!({"role": "user", "content": "hi"}));
399 let cbor = crate::remote::to_cbor(&m).unwrap();
400 #[derive(Deserialize)]
401 struct Old {
402 content: String,
403 }
404 assert_eq!(crate::remote::from_cbor::<Old>(&cbor).unwrap().content, "hi", "a 0.4 peer reads it");
405 let old = serde_json::json!({"role": "user", "content": "from 0.4"});
406 assert_eq!(serde_json::from_value::<Message>(old).unwrap().content, "from 0.4");
407 }
408
409 #[test]
410 fn parts_round_trip_in_json_and_cbor() {
411 let m = Message::user(vec![ContentPart::text("what is it?"), ContentPart::image(PNG), ContentPart::audio("UklGRg==", "wav")]);
412 let j = serde_json::to_value(&m).unwrap();
413 assert_eq!(
414 j["content"],
415 serde_json::json!([
416 {"type": "text", "text": "what is it?"},
417 {"type": "image_url", "image_url": {"url": PNG}},
418 {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}
419 ])
420 );
421 assert_eq!(serde_json::from_value::<Message>(j).unwrap(), m);
422 let back: Message = crate::remote::from_cbor(&crate::remote::to_cbor(&m).unwrap()).unwrap();
423 assert_eq!(back, m);
424 assert_eq!(m.needs(), Modalities::new(true, true));
425 assert_eq!(m.text(), "what is it?");
426 }
427
428 #[test]
429 fn needs_covers_and_lacking() {
430 let msgs = [Message::system("s"), Message::user(vec![ContentPart::image(PNG)])];
431 let n = needs(&msgs);
432 assert_eq!(n, Modalities::VISION);
433 assert!(Modalities::VISION.covers(n) && !Modalities::TEXT.covers(n) && !Modalities::AUDIO.covers(n));
434 assert_eq!(Modalities::TEXT.lacking(Modalities::new(true, true)), Some("images and audio"));
435 assert_eq!(Modalities::VISION.lacking(n), None);
436 assert!(needs(&[Message::user("x")]).is_text());
437 }
438
439 #[test]
440 fn check_refuses_remote_images_and_empty_audio() {
441 assert!(Content::from(vec![ContentPart::image(PNG)]).check().is_ok());
442 assert!(Content::from(vec![ContentPart::image("https://example.com/a.png")]).check().is_err());
443 assert!(Content::from(vec![ContentPart::audio("", "wav")]).check().is_err());
444 assert!(Content::from("text").check().is_ok());
445 }
446
447 #[test]
448 fn text_parts_normalize_to_a_string() {
449 let c = Content::from(vec![ContentPart::text("a"), ContentPart::text("b")]).normalized();
450 assert_eq!(c, Content::Text("ab".into()));
451 let img = Content::from(vec![ContentPart::image(PNG)]);
452 assert_eq!(img.clone().normalized(), img);
453 }
454}