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 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 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#[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#[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 Summary {
130 content: String,
131 timestamp: IsoString,
132 messages_compacted: usize,
134 },
135}
136
137impl ChatMessage {
138 pub fn user(text: impl Into<String>) -> Self {
140 ChatMessage::User { content: vec![ContentBlock::text(text)], timestamp: IsoString::now() }
141 }
142
143 pub fn system(content: impl Into<String>) -> Self {
145 ChatMessage::System { content: content.into(), timestamp: IsoString::now() }
146 }
147
148 pub fn is_tool_result(&self) -> bool {
150 matches!(self, ChatMessage::ToolCallResult(_))
151 }
152
153 pub fn is_system(&self) -> bool {
155 matches!(self, ChatMessage::System { .. })
156 }
157
158 pub fn is_summary(&self) -> bool {
160 matches!(self, ChatMessage::Summary { .. })
161 }
162
163 pub fn estimated_bytes(&self) -> usize {
166 match self {
167 ChatMessage::System { content, .. }
168 | ChatMessage::Error { message: content, .. }
169 | ChatMessage::Summary { content, .. } => content.len(),
170 ChatMessage::User { content, .. } => content.iter().map(ContentBlock::estimated_bytes).sum(),
171 ChatMessage::Assistant { content, reasoning, tool_calls, .. } => {
172 content.len()
173 + reasoning.summary_text.as_ref().map_or(0, String::len)
174 + reasoning.encrypted_content.as_ref().map_or(0, |ec| ec.content.len())
175 + tool_calls.iter().map(|tc| tc.name.len() + tc.arguments.len()).sum::<usize>()
176 }
177 ChatMessage::ToolCallResult(Ok(result)) => result.name.len() + result.arguments.len() + result.result.len(),
178 ChatMessage::ToolCallResult(Err(error)) => {
179 error.name.len() + error.arguments.as_ref().map_or(0, String::len) + error.error.len()
180 }
181 }
182 }
183
184 pub fn timestamp(&self) -> Option<&IsoString> {
186 match self {
187 ChatMessage::System { timestamp, .. }
188 | ChatMessage::User { timestamp, .. }
189 | ChatMessage::Assistant { timestamp, .. }
190 | ChatMessage::Error { timestamp, .. }
191 | ChatMessage::Summary { timestamp, .. } => Some(timestamp),
192 ChatMessage::ToolCallResult(_) => None,
193 }
194 }
195}
196
197fn serialize_llm_model<S: serde::Serializer>(model: &LlmModel, s: S) -> Result<S::Ok, S::Error> {
198 s.serialize_str(&model.to_string())
199}
200
201fn deserialize_llm_model<'de, D: serde::Deserializer<'de>>(d: D) -> Result<LlmModel, D::Error> {
202 let s = String::deserialize(d)?;
203 s.parse::<LlmModel>().map_err(serde::de::Error::custom)
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 fn make_model() -> LlmModel {
211 "anthropic:claude-opus-4-6".parse().unwrap()
212 }
213
214 #[test]
215 fn assistant_reasoning_is_empty_when_default() {
216 let r = AssistantReasoning::default();
217 assert!(r.is_empty());
218 }
219
220 #[test]
221 fn assistant_reasoning_not_empty_with_summary() {
222 let r = AssistantReasoning::from_parts("thinking".to_string(), None);
223 assert!(!r.is_empty());
224 }
225
226 #[test]
227 fn assistant_reasoning_not_empty_with_encrypted() {
228 let r = AssistantReasoning {
229 summary_text: None,
230 encrypted_content: Some(EncryptedReasoningContent {
231 id: "r_test".to_string(),
232 model: make_model(),
233 content: "blob".to_string(),
234 }),
235 };
236 assert!(!r.is_empty());
237 }
238
239 #[test]
240 fn from_parts_empty_summary_is_none() {
241 let r = AssistantReasoning::from_parts(String::new(), None);
242 assert!(r.summary_text.is_none());
243 assert!(r.is_empty());
244 }
245
246 #[test]
247 fn first_text_returns_first_non_empty_text_block() {
248 let parts = vec![
249 ContentBlock::Image { data: "a".to_string(), mime_type: "image/png".to_string() },
250 ContentBlock::text(" "),
251 ContentBlock::text("hello"),
252 ];
253
254 assert_eq!(ContentBlock::first_text(&parts), Some("hello"));
255 }
256
257 #[test]
258 fn encrypted_reasoning_content_serde_roundtrip() {
259 let model = make_model();
260 let ec = EncryptedReasoningContent {
261 id: "r_test".to_string(),
262 model: model.clone(),
263 content: "encrypted-data".to_string(),
264 };
265 let json = serde_json::to_string(&ec).unwrap();
266 let parsed: EncryptedReasoningContent = serde_json::from_str(&json).unwrap();
267 assert_eq!(parsed.model, model);
268 assert_eq!(parsed.content, "encrypted-data");
269 }
270
271 #[test]
272 fn assistant_reasoning_serde_roundtrip() {
273 let model = make_model();
274 let r = AssistantReasoning {
275 summary_text: Some("thought".to_string()),
276 encrypted_content: Some(EncryptedReasoningContent {
277 id: "r_test".to_string(),
278 model,
279 content: "blob".to_string(),
280 }),
281 };
282 let json = serde_json::to_string(&r).unwrap();
283 let parsed: AssistantReasoning = serde_json::from_str(&json).unwrap();
284 assert_eq!(parsed, r);
285 }
286
287 #[test]
288 fn assistant_reasoning_serde_empty_roundtrip() {
289 let r = AssistantReasoning::default();
290 let json = serde_json::to_string(&r).unwrap();
291 assert_eq!(json, "{}");
292 let parsed: AssistantReasoning = serde_json::from_str(&json).unwrap();
293 assert_eq!(parsed, r);
294 }
295
296 #[test]
297 fn chat_message_assistant_serde_roundtrip_with_reasoning() {
298 let model = make_model();
299 let msg = ChatMessage::Assistant {
300 content: "response".to_string(),
301 reasoning: AssistantReasoning {
302 summary_text: Some("plan".to_string()),
303 encrypted_content: Some(EncryptedReasoningContent {
304 id: "r_test".to_string(),
305 model,
306 content: "enc".to_string(),
307 }),
308 },
309 timestamp: IsoString::now(),
310 tool_calls: vec![],
311 };
312 let json = serde_json::to_string(&msg).unwrap();
313 let parsed: ChatMessage = serde_json::from_str(&json).unwrap();
314 assert_eq!(parsed, msg);
315 }
316
317 #[test]
318 fn estimated_bytes_includes_encrypted_content() {
319 let model = make_model();
320 let msg_with = ChatMessage::Assistant {
321 content: "hi".to_string(),
322 reasoning: AssistantReasoning {
323 summary_text: Some("think".to_string()),
324 encrypted_content: Some(EncryptedReasoningContent {
325 id: "r_test".to_string(),
326 model,
327 content: "x".repeat(100),
328 }),
329 },
330 timestamp: IsoString::now(),
331 tool_calls: vec![],
332 };
333 let msg_without = ChatMessage::Assistant {
334 content: "hi".to_string(),
335 reasoning: AssistantReasoning { summary_text: Some("think".to_string()), encrypted_content: None },
336 timestamp: IsoString::now(),
337 tool_calls: vec![],
338 };
339 assert!(msg_with.estimated_bytes() > msg_without.estimated_bytes());
340 }
341}