Skip to main content

llm_trait/
message.rs

1//! Message types for LLM conversations.
2//!
3//! These types define the conversation format shared across all LLM providers.
4
5use serde::{Deserialize, Serialize};
6
7/// A tool call embedded in an assistant message.
8#[derive(Clone, Debug, Serialize, Deserialize)]
9pub struct ToolCallMessage {
10    pub id: String,
11    pub name: String,
12    pub arguments: String,
13}
14
15/// Image attachment for multimodal messages.
16#[derive(Clone, Debug, Serialize, Deserialize)]
17pub enum ImageAttachment {
18    Url {
19        url: String,
20        #[serde(default, skip_serializing_if = "Option::is_none")]
21        detail: Option<ImageDetail>,
22    },
23    Base64 {
24        data: String,
25        #[serde(default, skip_serializing_if = "Option::is_none")]
26        media_type: Option<String>,
27        #[serde(default, skip_serializing_if = "Option::is_none")]
28        detail: Option<ImageDetail>,
29    },
30}
31
32/// Image detail level.
33#[derive(Clone, Debug, Serialize, Deserialize)]
34pub enum ImageDetail {
35    Low,
36    High,
37    Auto,
38}
39
40/// `skip_serializing_if` helper for `bool` flags: a message that is not
41/// synthetic serializes exactly as it did before the flag existed.
42fn is_false(value: &bool) -> bool {
43    !*value
44}
45
46/// A chat message in a conversation.
47///
48/// Supports system, user, assistant, tool, and custom message types.
49/// Each variant carries the data needed for LLM API calls.
50#[derive(Clone, Debug, Serialize, Deserialize)]
51pub enum ChatMessage {
52    System {
53        content: String,
54        /// Ephemeral messages are cleaned up after each turn and skipped during persistence.
55        #[serde(default, skip_serializing)]
56        ephemeral: bool,
57    },
58    User {
59        content: String,
60        #[serde(default, skip_serializing_if = "Vec::is_empty")]
61        images: Vec<ImageAttachment>,
62        /// Ephemeral messages are cleaned up after each turn and skipped during persistence.
63        #[serde(default, skip_serializing)]
64        ephemeral: bool,
65        /// Machine-composed input on the user role (tool-failure notices,
66        /// background-task wakes, the window seed): the model sees it like
67        /// any user message, but it is never the user's own words. Context
68        /// rotation skips synthetic messages when carrying the task trail
69        /// into a fresh window. Unlike `ephemeral`, this flag survives
70        /// persistence, so a resumed session keeps the distinction.
71        #[serde(default, skip_serializing_if = "is_false")]
72        synthetic: bool,
73    },
74    Assistant {
75        content: Option<String>,
76        reasoning_content: Option<String>,
77        /// Anthropic requires thinking blocks with signature to be sent back
78        /// in multi-turn conversations. This field stores the signature.
79        #[serde(default, skip_serializing_if = "Option::is_none")]
80        thinking_signature: Option<String>,
81        tool_calls: Option<Vec<ToolCallMessage>>,
82    },
83    /// A tool's result, paired with the assistant's `tool_calls` entry.
84    ///
85    /// `content` is the textual face; `images` carries pictures the tool's
86    /// output wants the model to *look at* (a screenshot, a rendered
87    /// diagram). A provider whose tool-result shape can carry images sends
88    /// them beside the text; one that cannot says so in `content` rather
89    /// than dropping the picture silently.
90    Tool {
91        tool_call_id: String,
92        name: Option<String>,
93        content: String,
94        #[serde(default, skip_serializing_if = "Vec::is_empty")]
95        images: Vec<ImageAttachment>,
96    },
97    /// Application-defined message type for extensibility.
98    ///
99    /// Custom messages are preserved in the transcript but filtered out
100    /// by the default conversion before being sent to the LLM provider.
101    Custom {
102        role: String,
103        data: serde_json::Value,
104    },
105}
106
107impl ChatMessage {
108    pub fn system(content: impl Into<String>) -> Self {
109        Self::System {
110            content: content.into(),
111            ephemeral: false,
112        }
113    }
114
115    /// Create an ephemeral system message: auto-cleaned after turn, not persisted.
116    pub fn system_ephemeral(content: impl Into<String>) -> Self {
117        Self::System {
118            content: content.into(),
119            ephemeral: true,
120        }
121    }
122
123    pub fn user(content: impl Into<String>) -> Self {
124        Self::User {
125            content: content.into(),
126            images: Vec::new(),
127            ephemeral: false,
128            synthetic: false,
129        }
130    }
131
132    /// Create an ephemeral user message: auto-cleaned after turn, not persisted.
133    pub fn user_ephemeral(content: impl Into<String>) -> Self {
134        Self::User {
135            content: content.into(),
136            images: Vec::new(),
137            ephemeral: true,
138            synthetic: false,
139        }
140    }
141
142    /// Create a synthetic user message: machine-composed input on the user
143    /// role (a notice, a wake, a seed) that must never stand in for the
144    /// user's own words — context rotation skips it when collecting the task
145    /// trail. The flag is persisted, so a resumed session keeps the
146    /// distinction.
147    pub fn user_synthetic(content: impl Into<String>) -> Self {
148        Self::User {
149            content: content.into(),
150            images: Vec::new(),
151            ephemeral: false,
152            synthetic: true,
153        }
154    }
155
156    pub fn user_with_images(content: impl Into<String>, images: Vec<ImageAttachment>) -> Self {
157        Self::User {
158            content: content.into(),
159            images,
160            ephemeral: false,
161            synthetic: false,
162        }
163    }
164
165    /// Whether this is an ephemeral message (auto-cleaned after turn, not persisted).
166    pub fn is_ephemeral(&self) -> bool {
167        match self {
168            Self::System { ephemeral, .. } => *ephemeral,
169            Self::User { ephemeral, .. } => *ephemeral,
170            _ => false,
171        }
172    }
173
174    /// Whether this is machine-composed input on the user role (never the
175    /// user's own words).
176    pub fn is_synthetic(&self) -> bool {
177        match self {
178            Self::User { synthetic, .. } => *synthetic,
179            _ => false,
180        }
181    }
182
183    pub fn assistant(content: impl Into<String>) -> Self {
184        Self::Assistant {
185            content: Some(content.into()),
186            reasoning_content: None,
187            thinking_signature: None,
188            tool_calls: None,
189        }
190    }
191
192    pub fn assistant_with_reasoning(
193        content: impl Into<String>,
194        reasoning: impl Into<String>,
195    ) -> Self {
196        Self::Assistant {
197            content: Some(content.into()),
198            reasoning_content: Some(reasoning.into()),
199            thinking_signature: None,
200            tool_calls: None,
201        }
202    }
203
204    pub fn assistant_tool_call(
205        tool_call_id: impl Into<String>,
206        tool_name: impl Into<String>,
207        arguments: impl Into<String>,
208    ) -> Self {
209        Self::Assistant {
210            content: None,
211            reasoning_content: None,
212            thinking_signature: None,
213            tool_calls: Some(vec![ToolCallMessage {
214                id: tool_call_id.into(),
215                name: tool_name.into(),
216                arguments: arguments.into(),
217            }]),
218        }
219    }
220
221    pub fn tool(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
222        Self::Tool {
223            tool_call_id: tool_call_id.into(),
224            name: None,
225            content: content.into(),
226            images: Vec::new(),
227        }
228    }
229
230    /// A tool result that also hands the model pictures to look at.
231    pub fn tool_with_images(
232        tool_call_id: impl Into<String>,
233        content: impl Into<String>,
234        images: Vec<ImageAttachment>,
235    ) -> Self {
236        Self::Tool {
237            tool_call_id: tool_call_id.into(),
238            name: None,
239            content: content.into(),
240            images,
241        }
242    }
243
244    pub fn tool_with_name(
245        tool_call_id: impl Into<String>,
246        name: impl Into<String>,
247        content: impl Into<String>,
248    ) -> Self {
249        Self::Tool {
250            tool_call_id: tool_call_id.into(),
251            name: Some(name.into()),
252            content: content.into(),
253            images: Vec::new(),
254        }
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn chat_message_user() {
264        let msg = ChatMessage::user("hello");
265        match &msg {
266            ChatMessage::User {
267                content,
268                images,
269                ephemeral,
270                synthetic,
271            } => {
272                assert_eq!(content, "hello");
273                assert!(images.is_empty());
274                assert!(!ephemeral);
275                assert!(!synthetic);
276            }
277            _ => panic!("Expected User variant"),
278        }
279    }
280
281    #[test]
282    fn chat_message_user_synthetic() {
283        let msg = ChatMessage::user_synthetic("Background tasks finished");
284        assert!(msg.is_synthetic());
285        assert!(!msg.is_ephemeral());
286        // A plain user message is the user's own words.
287        assert!(!ChatMessage::user("hello").is_synthetic());
288    }
289
290    /// The synthetic flag survives persistence — a resumed session must keep
291    /// the distinction between the user's words and machine notices.
292    #[test]
293    fn a_synthetic_user_message_round_trips_its_flag() {
294        let wire =
295            serde_json::to_string(&ChatMessage::user_synthetic("Tool calls failed")).unwrap();
296        assert!(wire.contains("synthetic"), "flag must persist: {wire}");
297        let back: ChatMessage = serde_json::from_str(&wire).unwrap();
298        assert!(back.is_synthetic());
299    }
300
301    /// An all-real transcript serializes exactly as it did before the flag
302    /// existed, and history written before it still loads as real.
303    #[test]
304    fn a_real_user_message_serializes_without_a_synthetic_key() {
305        let wire = serde_json::to_string(&ChatMessage::user("hello")).unwrap();
306        assert!(
307            !wire.contains("synthetic"),
308            "no empty flag on the wire: {wire}"
309        );
310        let old = r#"{"User":{"content":"hello","images":[]}}"#;
311        let back: ChatMessage = serde_json::from_str(old).unwrap();
312        assert!(!back.is_synthetic());
313    }
314
315    #[test]
316    fn chat_message_system() {
317        let msg = ChatMessage::system("sys");
318        assert!(!msg.is_ephemeral());
319    }
320
321    /// Pictures ride the tool result through a persisted transcript too —
322    /// a session resumed later still hands the model what it was shown.
323    #[test]
324    fn a_tool_result_round_trips_its_pictures() {
325        let msg = ChatMessage::tool_with_images(
326            "tc1",
327            "image: the whole desktop",
328            vec![ImageAttachment::Base64 {
329                data: "aGVsbG8=".to_string(),
330                media_type: Some("image/png".to_string()),
331                detail: None,
332            }],
333        );
334        let wire = serde_json::to_string(&msg).unwrap();
335        let back: ChatMessage = serde_json::from_str(&wire).unwrap();
336        match back {
337            ChatMessage::Tool {
338                tool_call_id,
339                content,
340                images,
341                ..
342            } => {
343                assert_eq!(tool_call_id, "tc1");
344                assert_eq!(content, "image: the whole desktop");
345                assert_eq!(images.len(), 1);
346            }
347            other => panic!("expected a tool result, got {other:?}"),
348        }
349    }
350
351    /// Transcripts written before the image face existed have no `images`
352    /// key at all. They must keep loading — a resume must never fail on
353    /// history the product itself wrote.
354    #[test]
355    fn a_tool_result_written_before_images_still_loads() {
356        let old = r#"{"Tool":{"tool_call_id":"tc1","name":null,"content":"done"}}"#;
357        let msg: ChatMessage = serde_json::from_str(old).unwrap();
358        match msg {
359            ChatMessage::Tool {
360                content, images, ..
361            } => {
362                assert_eq!(content, "done");
363                assert!(images.is_empty());
364            }
365            other => panic!("expected a tool result, got {other:?}"),
366        }
367    }
368
369    /// An empty image list is not written at all: a word-only tool result
370    /// serializes byte-for-byte as it did before this field existed.
371    #[test]
372    fn a_word_only_tool_result_serializes_without_an_images_key() {
373        let wire = serde_json::to_string(&ChatMessage::tool("tc1", "done")).unwrap();
374        assert!(
375            !wire.contains("images"),
376            "no empty field on the wire: {wire}"
377        );
378    }
379
380    #[test]
381    fn chat_message_system_ephemeral() {
382        let msg = ChatMessage::system_ephemeral("sys");
383        assert!(msg.is_ephemeral());
384    }
385
386    #[test]
387    fn chat_message_user_ephemeral() {
388        let msg = ChatMessage::user_ephemeral("hi");
389        assert!(msg.is_ephemeral());
390    }
391
392    #[test]
393    fn chat_message_assistant() {
394        let msg = ChatMessage::assistant("response");
395        match &msg {
396            ChatMessage::Assistant { content, .. } => {
397                assert_eq!(content.as_deref(), Some("response"));
398            }
399            _ => panic!("Expected Assistant variant"),
400        }
401    }
402
403    #[test]
404    fn chat_message_tool_call() {
405        let msg = ChatMessage::assistant_tool_call("id1", "echo", r#"{"x":1}"#);
406        match &msg {
407            ChatMessage::Assistant { tool_calls, .. } => {
408                let tc = tool_calls.as_ref().unwrap();
409                assert_eq!(tc.len(), 1);
410                assert_eq!(tc[0].id, "id1");
411                assert_eq!(tc[0].name, "echo");
412            }
413            _ => panic!("Expected Assistant variant"),
414        }
415    }
416
417    #[test]
418    fn chat_message_tool() {
419        let msg = ChatMessage::tool("id1", "result");
420        match &msg {
421            ChatMessage::Tool {
422                tool_call_id,
423                name,
424                content,
425                images,
426            } => {
427                assert_eq!(tool_call_id, "id1");
428                assert!(name.is_none());
429                assert_eq!(content, "result");
430                assert!(
431                    images.is_empty(),
432                    "the plain constructor carries no pictures"
433                );
434            }
435            _ => panic!("Expected Tool variant"),
436        }
437    }
438
439    #[test]
440    fn chat_message_tool_with_name() {
441        let msg = ChatMessage::tool_with_name("id1", "echo", "result");
442        match &msg {
443            ChatMessage::Tool {
444                tool_call_id,
445                name,
446                content,
447                images,
448            } => {
449                assert_eq!(tool_call_id, "id1");
450                assert_eq!(name.as_deref(), Some("echo"));
451                assert_eq!(content, "result");
452                assert!(
453                    images.is_empty(),
454                    "the plain constructor carries no pictures"
455                );
456            }
457            _ => panic!("Expected Tool variant"),
458        }
459    }
460
461    #[test]
462    fn custom_message_not_ephemeral() {
463        let msg = ChatMessage::Custom {
464            role: "artifact".to_string(),
465            data: serde_json::json!({}),
466        };
467        assert!(!msg.is_ephemeral());
468    }
469
470    #[test]
471    fn serialization_roundtrip() {
472        let msg = ChatMessage::user("hello");
473        let json = serde_json::to_string(&msg).unwrap();
474        let deserialized: ChatMessage = serde_json::from_str(&json).unwrap();
475        match deserialized {
476            ChatMessage::User { content, .. } => assert_eq!(content, "hello"),
477            _ => panic!("Expected User"),
478        }
479    }
480}