1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4use crate::catalog::LlmModel;
5use crate::types::IsoString;
6
7use super::{AssistantReply, MessageId, ToolCallError, 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#[doc = include_str!("docs/chat_message.md")]
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
69#[serde(tag = "type", rename_all = "camelCase")]
70pub enum ChatMessage {
71 System {
72 content: String,
73 timestamp: IsoString,
74 },
75 User {
76 message_id: MessageId,
77 content: Vec<ContentBlock>,
78 timestamp: IsoString,
79 },
80 Assistant {
81 message_id: MessageId,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 model: Option<LlmModel>,
84 content: AssistantReply,
85 timestamp: IsoString,
86 },
87 ToolCallResult(Result<ToolCallResult, ToolCallError>),
88 Error {
89 message_id: MessageId,
90 message: String,
91 timestamp: IsoString,
92 },
93 Summary {
96 message_id: MessageId,
97 content: String,
98 timestamp: IsoString,
99 messages_compacted: usize,
101 },
102}
103
104impl ChatMessage {
105 pub fn user(text: impl Into<String>) -> Self {
107 Self::user_with_id(MessageId::new(), vec![ContentBlock::text(text)])
108 }
109
110 pub fn system(content: impl Into<String>) -> Self {
112 ChatMessage::System { content: content.into(), timestamp: IsoString::now() }
113 }
114
115 pub fn user_with_id(message_id: MessageId, content: Vec<ContentBlock>) -> Self {
116 Self::User { message_id, content, timestamp: IsoString::now() }
117 }
118
119 pub fn assistant_reply(
120 message_id: MessageId,
121 model: Option<LlmModel>,
122 mut content: AssistantReply,
123 results: &[Result<ToolCallResult, ToolCallError>],
124 ) -> Self {
125 content.pair_tool_calls(results);
126 Self::Assistant { message_id, model, content, timestamp: IsoString::now() }
127 }
128
129 pub fn message_id(&self) -> Option<MessageId> {
131 match self {
132 Self::User { message_id, .. }
133 | Self::Assistant { message_id, .. }
134 | Self::Error { message_id, .. }
135 | Self::Summary { message_id, .. } => Some(message_id.clone()),
136 Self::ToolCallResult(Ok(result)) => Some(MessageId::tool_result(&result.id)),
137 Self::ToolCallResult(Err(error)) => Some(MessageId::tool_result(&error.id)),
138 Self::System { .. } => None,
139 }
140 }
141
142 pub fn is_tool_result(&self) -> bool {
144 matches!(self, ChatMessage::ToolCallResult(_))
145 }
146
147 pub fn is_system(&self) -> bool {
149 matches!(self, ChatMessage::System { .. })
150 }
151
152 pub fn is_summary(&self) -> bool {
154 matches!(self, ChatMessage::Summary { .. })
155 }
156
157 pub fn estimated_bytes(&self) -> usize {
160 match self {
161 ChatMessage::System { content, .. }
162 | ChatMessage::Error { message: content, .. }
163 | ChatMessage::Summary { content, .. } => content.len(),
164 ChatMessage::User { content, .. } => content.iter().map(ContentBlock::estimated_bytes).sum(),
165 ChatMessage::Assistant { content, .. } => content.estimated_bytes(),
166 ChatMessage::ToolCallResult(Ok(result)) => result.name.len() + result.arguments.len() + result.result.len(),
167 ChatMessage::ToolCallResult(Err(error)) => {
168 error.name.len() + error.arguments.as_ref().map_or(0, String::len) + error.error.len()
169 }
170 }
171 }
172
173 pub fn timestamp(&self) -> Option<&IsoString> {
175 match self {
176 ChatMessage::System { timestamp, .. }
177 | ChatMessage::User { timestamp, .. }
178 | ChatMessage::Assistant { timestamp, .. }
179 | ChatMessage::Error { timestamp, .. }
180 | ChatMessage::Summary { timestamp, .. } => Some(timestamp),
181 ChatMessage::ToolCallResult(_) => None,
182 }
183 }
184
185 pub(crate) fn as_user_note(&self) -> Option<String> {
186 match self {
187 ChatMessage::Summary { content, .. } => Some(format!("[Previous conversation handoff]\n\n{content}")),
188 ChatMessage::Error { message, .. } => Some(format!("Error: {message}")),
189 _ => None,
190 }
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn assistant_reply_pairs_every_tool_call_with_a_result() {
200 let model: LlmModel = "anthropic:claude-opus-4-6".parse().unwrap();
201 let content = crate::testing::assistant_message()
202 .tool_call("call_1", "read", "{}")
203 .tool_call("call_cancelled", "read", "{}")
204 .build_reply();
205 let result = ToolCallResult {
206 id: "call_1".to_string(),
207 name: "read".to_string(),
208 arguments: "{}".to_string(),
209 result: "ok".to_string(),
210 };
211 let error = ToolCallError {
212 id: "call_retried".to_string(),
213 name: "bash".to_string(),
214 arguments: None,
215 error: "failed".to_string(),
216 };
217
218 let reply =
219 ChatMessage::assistant_reply(MessageId::new(), Some(model.clone()), content, &[Ok(result), Err(error)]);
220
221 let ChatMessage::Assistant { model: author, content, .. } = reply else { panic!("expected assistant message") };
222 let ids: Vec<_> = content.tool_calls().map(|call| call.id.as_str()).collect();
223 assert_eq!(ids, ["call_1", "call_retried"]);
224 assert_eq!(author, Some(model));
225 }
226
227 #[test]
228 fn first_text_returns_first_non_empty_text_block() {
229 let parts = vec![
230 ContentBlock::Image { data: "a".to_string(), mime_type: "image/png".to_string() },
231 ContentBlock::text(" "),
232 ContentBlock::text("hello"),
233 ];
234
235 assert_eq!(ContentBlock::first_text(&parts), Some("hello"));
236 }
237
238 #[test]
239 fn estimated_bytes_counts_reasoning_in_the_form_it_is_sent_back() {
240 let summary = "s".repeat(10);
241 let encrypted = "e".repeat(100);
242 let assistant = crate::testing::assistant_message().text("hi");
243
244 assert_eq!(assistant.clone().reasoning(&summary).build().estimated_bytes(), 12);
245 assert_eq!(assistant.reasoning(&summary).encrypted_reasoning("r_1", &encrypted).build().estimated_bytes(), 102);
246 }
247
248 #[test]
249 fn assistant_messages_roundtrip_with_their_author() {
250 let message = crate::testing::assistant_message()
251 .model("anthropic:claude-opus-4-6")
252 .reasoning("plan")
253 .encrypted_reasoning("r_1", "blob")
254 .text("answer")
255 .build();
256
257 let json = serde_json::to_value(&message).unwrap();
258
259 assert_eq!(json["model"], "anthropic:claude-opus-4-6");
260 assert_eq!(serde_json::from_value::<ChatMessage>(json).unwrap(), message);
261 }
262}