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/// A chat message in a conversation.
41///
42/// Supports system, user, assistant, tool, and custom message types.
43/// Each variant carries the data needed for LLM API calls.
44#[derive(Clone, Debug, Serialize, Deserialize)]
45pub enum ChatMessage {
46    System {
47        content: String,
48        /// Ephemeral messages are cleaned up after each turn and skipped during persistence.
49        #[serde(default, skip_serializing)]
50        ephemeral: bool,
51    },
52    User {
53        content: String,
54        #[serde(default, skip_serializing_if = "Vec::is_empty")]
55        images: Vec<ImageAttachment>,
56        /// Ephemeral messages are cleaned up after each turn and skipped during persistence.
57        #[serde(default, skip_serializing)]
58        ephemeral: bool,
59    },
60    Assistant {
61        content: Option<String>,
62        reasoning_content: Option<String>,
63        /// Anthropic requires thinking blocks with signature to be sent back
64        /// in multi-turn conversations. This field stores the signature.
65        #[serde(default, skip_serializing_if = "Option::is_none")]
66        thinking_signature: Option<String>,
67        tool_calls: Option<Vec<ToolCallMessage>>,
68    },
69    /// A tool's result, paired with the assistant's `tool_calls` entry.
70    ///
71    /// `content` is the textual face; `images` carries pictures the tool's
72    /// output wants the model to *look at* (a screenshot, a rendered
73    /// diagram). A provider whose tool-result shape can carry images sends
74    /// them beside the text; one that cannot says so in `content` rather
75    /// than dropping the picture silently.
76    Tool {
77        tool_call_id: String,
78        name: Option<String>,
79        content: String,
80        #[serde(default, skip_serializing_if = "Vec::is_empty")]
81        images: Vec<ImageAttachment>,
82    },
83    /// Application-defined message type for extensibility.
84    ///
85    /// Custom messages are preserved in the transcript but filtered out
86    /// by the default conversion before being sent to the LLM provider.
87    Custom {
88        role: String,
89        data: serde_json::Value,
90    },
91}
92
93impl ChatMessage {
94    pub fn system(content: impl Into<String>) -> Self {
95        Self::System {
96            content: content.into(),
97            ephemeral: false,
98        }
99    }
100
101    /// Create an ephemeral system message: auto-cleaned after turn, not persisted.
102    pub fn system_ephemeral(content: impl Into<String>) -> Self {
103        Self::System {
104            content: content.into(),
105            ephemeral: true,
106        }
107    }
108
109    pub fn user(content: impl Into<String>) -> Self {
110        Self::User {
111            content: content.into(),
112            images: Vec::new(),
113            ephemeral: false,
114        }
115    }
116
117    /// Create an ephemeral user message: auto-cleaned after turn, not persisted.
118    pub fn user_ephemeral(content: impl Into<String>) -> Self {
119        Self::User {
120            content: content.into(),
121            images: Vec::new(),
122            ephemeral: true,
123        }
124    }
125
126    pub fn user_with_images(content: impl Into<String>, images: Vec<ImageAttachment>) -> Self {
127        Self::User {
128            content: content.into(),
129            images,
130            ephemeral: false,
131        }
132    }
133
134    /// Whether this is an ephemeral message (auto-cleaned after turn, not persisted).
135    pub fn is_ephemeral(&self) -> bool {
136        match self {
137            Self::System { ephemeral, .. } => *ephemeral,
138            Self::User { ephemeral, .. } => *ephemeral,
139            _ => false,
140        }
141    }
142
143    pub fn assistant(content: impl Into<String>) -> Self {
144        Self::Assistant {
145            content: Some(content.into()),
146            reasoning_content: None,
147            thinking_signature: None,
148            tool_calls: None,
149        }
150    }
151
152    pub fn assistant_with_reasoning(
153        content: impl Into<String>,
154        reasoning: impl Into<String>,
155    ) -> Self {
156        Self::Assistant {
157            content: Some(content.into()),
158            reasoning_content: Some(reasoning.into()),
159            thinking_signature: None,
160            tool_calls: None,
161        }
162    }
163
164    pub fn assistant_tool_call(
165        tool_call_id: impl Into<String>,
166        tool_name: impl Into<String>,
167        arguments: impl Into<String>,
168    ) -> Self {
169        Self::Assistant {
170            content: None,
171            reasoning_content: None,
172            thinking_signature: None,
173            tool_calls: Some(vec![ToolCallMessage {
174                id: tool_call_id.into(),
175                name: tool_name.into(),
176                arguments: arguments.into(),
177            }]),
178        }
179    }
180
181    pub fn tool(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
182        Self::Tool {
183            tool_call_id: tool_call_id.into(),
184            name: None,
185            content: content.into(),
186            images: Vec::new(),
187        }
188    }
189
190    /// A tool result that also hands the model pictures to look at.
191    pub fn tool_with_images(
192        tool_call_id: impl Into<String>,
193        content: impl Into<String>,
194        images: Vec<ImageAttachment>,
195    ) -> Self {
196        Self::Tool {
197            tool_call_id: tool_call_id.into(),
198            name: None,
199            content: content.into(),
200            images,
201        }
202    }
203
204    pub fn tool_with_name(
205        tool_call_id: impl Into<String>,
206        name: impl Into<String>,
207        content: impl Into<String>,
208    ) -> Self {
209        Self::Tool {
210            tool_call_id: tool_call_id.into(),
211            name: Some(name.into()),
212            content: content.into(),
213            images: Vec::new(),
214        }
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn chat_message_user() {
224        let msg = ChatMessage::user("hello");
225        match &msg {
226            ChatMessage::User {
227                content,
228                images,
229                ephemeral,
230            } => {
231                assert_eq!(content, "hello");
232                assert!(images.is_empty());
233                assert!(!ephemeral);
234            }
235            _ => panic!("Expected User variant"),
236        }
237    }
238
239    #[test]
240    fn chat_message_system() {
241        let msg = ChatMessage::system("sys");
242        assert!(!msg.is_ephemeral());
243    }
244
245    /// Pictures ride the tool result through a persisted transcript too —
246    /// a session resumed later still hands the model what it was shown.
247    #[test]
248    fn a_tool_result_round_trips_its_pictures() {
249        let msg = ChatMessage::tool_with_images(
250            "tc1",
251            "image: the whole desktop",
252            vec![ImageAttachment::Base64 {
253                data: "aGVsbG8=".to_string(),
254                media_type: Some("image/png".to_string()),
255                detail: None,
256            }],
257        );
258        let wire = serde_json::to_string(&msg).unwrap();
259        let back: ChatMessage = serde_json::from_str(&wire).unwrap();
260        match back {
261            ChatMessage::Tool {
262                tool_call_id,
263                content,
264                images,
265                ..
266            } => {
267                assert_eq!(tool_call_id, "tc1");
268                assert_eq!(content, "image: the whole desktop");
269                assert_eq!(images.len(), 1);
270            }
271            other => panic!("expected a tool result, got {other:?}"),
272        }
273    }
274
275    /// Transcripts written before the image face existed have no `images`
276    /// key at all. They must keep loading — a resume must never fail on
277    /// history the product itself wrote.
278    #[test]
279    fn a_tool_result_written_before_images_still_loads() {
280        let old = r#"{"Tool":{"tool_call_id":"tc1","name":null,"content":"done"}}"#;
281        let msg: ChatMessage = serde_json::from_str(old).unwrap();
282        match msg {
283            ChatMessage::Tool {
284                content, images, ..
285            } => {
286                assert_eq!(content, "done");
287                assert!(images.is_empty());
288            }
289            other => panic!("expected a tool result, got {other:?}"),
290        }
291    }
292
293    /// An empty image list is not written at all: a word-only tool result
294    /// serializes byte-for-byte as it did before this field existed.
295    #[test]
296    fn a_word_only_tool_result_serializes_without_an_images_key() {
297        let wire = serde_json::to_string(&ChatMessage::tool("tc1", "done")).unwrap();
298        assert!(
299            !wire.contains("images"),
300            "no empty field on the wire: {wire}"
301        );
302    }
303
304    #[test]
305    fn chat_message_system_ephemeral() {
306        let msg = ChatMessage::system_ephemeral("sys");
307        assert!(msg.is_ephemeral());
308    }
309
310    #[test]
311    fn chat_message_user_ephemeral() {
312        let msg = ChatMessage::user_ephemeral("hi");
313        assert!(msg.is_ephemeral());
314    }
315
316    #[test]
317    fn chat_message_assistant() {
318        let msg = ChatMessage::assistant("response");
319        match &msg {
320            ChatMessage::Assistant { content, .. } => {
321                assert_eq!(content.as_deref(), Some("response"));
322            }
323            _ => panic!("Expected Assistant variant"),
324        }
325    }
326
327    #[test]
328    fn chat_message_tool_call() {
329        let msg = ChatMessage::assistant_tool_call("id1", "echo", r#"{"x":1}"#);
330        match &msg {
331            ChatMessage::Assistant { tool_calls, .. } => {
332                let tc = tool_calls.as_ref().unwrap();
333                assert_eq!(tc.len(), 1);
334                assert_eq!(tc[0].id, "id1");
335                assert_eq!(tc[0].name, "echo");
336            }
337            _ => panic!("Expected Assistant variant"),
338        }
339    }
340
341    #[test]
342    fn chat_message_tool() {
343        let msg = ChatMessage::tool("id1", "result");
344        match &msg {
345            ChatMessage::Tool {
346                tool_call_id,
347                name,
348                content,
349                images,
350            } => {
351                assert_eq!(tool_call_id, "id1");
352                assert!(name.is_none());
353                assert_eq!(content, "result");
354                assert!(
355                    images.is_empty(),
356                    "the plain constructor carries no pictures"
357                );
358            }
359            _ => panic!("Expected Tool variant"),
360        }
361    }
362
363    #[test]
364    fn chat_message_tool_with_name() {
365        let msg = ChatMessage::tool_with_name("id1", "echo", "result");
366        match &msg {
367            ChatMessage::Tool {
368                tool_call_id,
369                name,
370                content,
371                images,
372            } => {
373                assert_eq!(tool_call_id, "id1");
374                assert_eq!(name.as_deref(), Some("echo"));
375                assert_eq!(content, "result");
376                assert!(
377                    images.is_empty(),
378                    "the plain constructor carries no pictures"
379                );
380            }
381            _ => panic!("Expected Tool variant"),
382        }
383    }
384
385    #[test]
386    fn custom_message_not_ephemeral() {
387        let msg = ChatMessage::Custom {
388            role: "artifact".to_string(),
389            data: serde_json::json!({}),
390        };
391        assert!(!msg.is_ephemeral());
392    }
393
394    #[test]
395    fn serialization_roundtrip() {
396        let msg = ChatMessage::user("hello");
397        let json = serde_json::to_string(&msg).unwrap();
398        let deserialized: ChatMessage = serde_json::from_str(&json).unwrap();
399        match deserialized {
400            ChatMessage::User { content, .. } => assert_eq!(content, "hello"),
401            _ => panic!("Expected User"),
402        }
403    }
404}