Skip to main content

llm/
chat_message.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4use crate::catalog::LlmModel;
5use crate::types::IsoString;
6
7use super::{ToolCallError, ToolCallRequest, ToolCallResult};
8
9#[doc = include_str!("docs/content_block.md")]
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
11#[serde(tag = "type", rename_all = "camelCase")]
12pub enum ContentBlock {
13    Text { text: String },
14    Image { data: String, mime_type: String },
15    Audio { data: String, mime_type: String },
16}
17
18impl ContentBlock {
19    pub fn text(s: impl Into<String>) -> Self {
20        ContentBlock::Text { text: s.into() }
21    }
22
23    pub fn estimated_bytes(&self) -> usize {
24        match self {
25            ContentBlock::Text { text } => text.len(),
26            ContentBlock::Image { data, .. } | ContentBlock::Audio { data, .. } => data.len(),
27        }
28    }
29
30    pub fn is_image(&self) -> bool {
31        matches!(self, ContentBlock::Image { .. })
32    }
33
34    pub fn first_text(parts: &[ContentBlock]) -> Option<&str> {
35        parts.iter().find_map(|part| match part {
36            ContentBlock::Text { text } => {
37                let trimmed = text.trim();
38                (!trimmed.is_empty()).then_some(trimmed)
39            }
40            _ => None,
41        })
42    }
43
44    /// Joins all text blocks with newlines, ignoring non-text content.
45    pub fn join_text(parts: &[ContentBlock]) -> String {
46        parts
47            .iter()
48            .filter_map(|p| match p {
49                ContentBlock::Text { text } => Some(text.as_str()),
50                _ => None,
51            })
52            .collect::<Vec<_>>()
53            .join("\n")
54    }
55
56    /// Returns a `data:{mime};base64,{data}` URI for image/audio blocks, `None` for text.
57    pub fn as_data_uri(&self) -> Option<String> {
58        match self {
59            ContentBlock::Image { data, mime_type } | ContentBlock::Audio { data, mime_type } => {
60                Some(format!("data:{mime_type};base64,{data}"))
61            }
62            ContentBlock::Text { .. } => None,
63        }
64    }
65}
66
67/// Opaque encrypted reasoning content from an LLM response.
68///
69/// This is model-specific: encrypted content from one model cannot be replayed
70/// to a different model. Use [`Context::filter_encrypted_reasoning`](crate::Context::filter_encrypted_reasoning)
71/// to strip content that doesn't match the target model.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct EncryptedReasoningContent {
74    pub id: String,
75    #[serde(serialize_with = "serialize_llm_model", deserialize_with = "deserialize_llm_model")]
76    pub model: LlmModel,
77    pub content: String,
78}
79
80/// Reasoning metadata from an assistant response.
81///
82/// Contains an optional human-readable summary and optional encrypted content
83/// that can be replayed to the same model in future turns.
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
85pub struct AssistantReasoning {
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub summary_text: Option<String>,
88
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub encrypted_content: Option<EncryptedReasoningContent>,
91}
92
93impl AssistantReasoning {
94    pub fn from_parts(summary_text: String, encrypted: Option<EncryptedReasoningContent>) -> Self {
95        Self { summary_text: (!summary_text.is_empty()).then_some(summary_text), encrypted_content: encrypted }
96    }
97
98    pub fn is_empty(&self) -> bool {
99        self.summary_text.is_none() && self.encrypted_content.is_none()
100    }
101}
102
103#[doc = include_str!("docs/chat_message.md")]
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(tag = "type", rename_all = "camelCase")]
106pub enum ChatMessage {
107    System {
108        content: String,
109        timestamp: IsoString,
110    },
111    User {
112        content: Vec<ContentBlock>,
113        timestamp: IsoString,
114    },
115    Assistant {
116        content: String,
117        #[serde(default)]
118        reasoning: AssistantReasoning,
119        timestamp: IsoString,
120        tool_calls: Vec<ToolCallRequest>,
121    },
122    ToolCallResult(Result<ToolCallResult, ToolCallError>),
123    Error {
124        message: String,
125        timestamp: IsoString,
126    },
127    /// A compacted summary of previous conversation history.
128    /// This replaces multiple messages with a structured summary to reduce context usage.
129    Summary {
130        content: String,
131        timestamp: IsoString,
132        /// Number of messages that were compacted into this summary
133        messages_compacted: usize,
134    },
135}
136
137impl ChatMessage {
138    /// Returns true if this message is a tool call result
139    pub fn is_tool_result(&self) -> bool {
140        matches!(self, ChatMessage::ToolCallResult(_))
141    }
142
143    /// Returns true if this message is a system prompt
144    pub fn is_system(&self) -> bool {
145        matches!(self, ChatMessage::System { .. })
146    }
147
148    /// Returns true if this message is a compacted summary
149    pub fn is_summary(&self) -> bool {
150        matches!(self, ChatMessage::Summary { .. })
151    }
152
153    /// Rough byte-size estimate of the message content for pre-flight context checks.
154    /// Not meant to be exact — just close enough to detect overflow before calling the LLM.
155    pub fn estimated_bytes(&self) -> usize {
156        match self {
157            ChatMessage::System { content, .. }
158            | ChatMessage::Error { message: content, .. }
159            | ChatMessage::Summary { content, .. } => content.len(),
160            ChatMessage::User { content, .. } => content.iter().map(ContentBlock::estimated_bytes).sum(),
161            ChatMessage::Assistant { content, reasoning, tool_calls, .. } => {
162                content.len()
163                    + reasoning.summary_text.as_ref().map_or(0, String::len)
164                    + reasoning.encrypted_content.as_ref().map_or(0, |ec| ec.content.len())
165                    + tool_calls.iter().map(|tc| tc.name.len() + tc.arguments.len()).sum::<usize>()
166            }
167            ChatMessage::ToolCallResult(Ok(result)) => result.name.len() + result.arguments.len() + result.result.len(),
168            ChatMessage::ToolCallResult(Err(error)) => {
169                error.name.len() + error.arguments.as_ref().map_or(0, String::len) + error.error.len()
170            }
171        }
172    }
173
174    /// Returns the timestamp of this message, if it has one
175    pub fn timestamp(&self) -> Option<&IsoString> {
176        match self {
177            ChatMessage::System { timestamp, .. }
178            | ChatMessage::User { timestamp, .. }
179            | ChatMessage::Assistant { timestamp, .. }
180            | ChatMessage::Error { timestamp, .. }
181            | ChatMessage::Summary { timestamp, .. } => Some(timestamp),
182            ChatMessage::ToolCallResult(_) => None,
183        }
184    }
185}
186
187fn serialize_llm_model<S: serde::Serializer>(model: &LlmModel, s: S) -> Result<S::Ok, S::Error> {
188    s.serialize_str(&model.to_string())
189}
190
191fn deserialize_llm_model<'de, D: serde::Deserializer<'de>>(d: D) -> Result<LlmModel, D::Error> {
192    let s = String::deserialize(d)?;
193    s.parse::<LlmModel>().map_err(serde::de::Error::custom)
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    fn make_model() -> LlmModel {
201        "anthropic:claude-opus-4-6".parse().unwrap()
202    }
203
204    #[test]
205    fn assistant_reasoning_is_empty_when_default() {
206        let r = AssistantReasoning::default();
207        assert!(r.is_empty());
208    }
209
210    #[test]
211    fn assistant_reasoning_not_empty_with_summary() {
212        let r = AssistantReasoning::from_parts("thinking".to_string(), None);
213        assert!(!r.is_empty());
214    }
215
216    #[test]
217    fn assistant_reasoning_not_empty_with_encrypted() {
218        let r = AssistantReasoning {
219            summary_text: None,
220            encrypted_content: Some(EncryptedReasoningContent {
221                id: "r_test".to_string(),
222                model: make_model(),
223                content: "blob".to_string(),
224            }),
225        };
226        assert!(!r.is_empty());
227    }
228
229    #[test]
230    fn from_parts_empty_summary_is_none() {
231        let r = AssistantReasoning::from_parts(String::new(), None);
232        assert!(r.summary_text.is_none());
233        assert!(r.is_empty());
234    }
235
236    #[test]
237    fn first_text_returns_first_non_empty_text_block() {
238        let parts = vec![
239            ContentBlock::Image { data: "a".to_string(), mime_type: "image/png".to_string() },
240            ContentBlock::text(" "),
241            ContentBlock::text("hello"),
242        ];
243
244        assert_eq!(ContentBlock::first_text(&parts), Some("hello"));
245    }
246
247    #[test]
248    fn encrypted_reasoning_content_serde_roundtrip() {
249        let model = make_model();
250        let ec = EncryptedReasoningContent {
251            id: "r_test".to_string(),
252            model: model.clone(),
253            content: "encrypted-data".to_string(),
254        };
255        let json = serde_json::to_string(&ec).unwrap();
256        let parsed: EncryptedReasoningContent = serde_json::from_str(&json).unwrap();
257        assert_eq!(parsed.model, model);
258        assert_eq!(parsed.content, "encrypted-data");
259    }
260
261    #[test]
262    fn assistant_reasoning_serde_roundtrip() {
263        let model = make_model();
264        let r = AssistantReasoning {
265            summary_text: Some("thought".to_string()),
266            encrypted_content: Some(EncryptedReasoningContent {
267                id: "r_test".to_string(),
268                model,
269                content: "blob".to_string(),
270            }),
271        };
272        let json = serde_json::to_string(&r).unwrap();
273        let parsed: AssistantReasoning = serde_json::from_str(&json).unwrap();
274        assert_eq!(parsed, r);
275    }
276
277    #[test]
278    fn assistant_reasoning_serde_empty_roundtrip() {
279        let r = AssistantReasoning::default();
280        let json = serde_json::to_string(&r).unwrap();
281        assert_eq!(json, "{}");
282        let parsed: AssistantReasoning = serde_json::from_str(&json).unwrap();
283        assert_eq!(parsed, r);
284    }
285
286    #[test]
287    fn chat_message_assistant_serde_roundtrip_with_reasoning() {
288        let model = make_model();
289        let msg = ChatMessage::Assistant {
290            content: "response".to_string(),
291            reasoning: AssistantReasoning {
292                summary_text: Some("plan".to_string()),
293                encrypted_content: Some(EncryptedReasoningContent {
294                    id: "r_test".to_string(),
295                    model,
296                    content: "enc".to_string(),
297                }),
298            },
299            timestamp: IsoString::now(),
300            tool_calls: vec![],
301        };
302        let json = serde_json::to_string(&msg).unwrap();
303        let parsed: ChatMessage = serde_json::from_str(&json).unwrap();
304        assert_eq!(parsed, msg);
305    }
306
307    #[test]
308    fn estimated_bytes_includes_encrypted_content() {
309        let model = make_model();
310        let msg_with = ChatMessage::Assistant {
311            content: "hi".to_string(),
312            reasoning: AssistantReasoning {
313                summary_text: Some("think".to_string()),
314                encrypted_content: Some(EncryptedReasoningContent {
315                    id: "r_test".to_string(),
316                    model,
317                    content: "x".repeat(100),
318                }),
319            },
320            timestamp: IsoString::now(),
321            tool_calls: vec![],
322        };
323        let msg_without = ChatMessage::Assistant {
324            content: "hi".to_string(),
325            reasoning: AssistantReasoning { summary_text: Some("think".to_string()), encrypted_content: None },
326            timestamp: IsoString::now(),
327            tool_calls: vec![],
328        };
329        assert!(msg_with.estimated_bytes() > msg_without.estimated_bytes());
330    }
331}