use std::{borrow::Cow, collections::BTreeMap};
use serde::{Deserialize, Serialize};
use super::{ToolResult, ToolUse};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum ContentPart {
Text(String),
Image(Attachment),
Document(Attachment),
Thinking {
text: String,
signature: Option<String>,
},
RedactedThinking {
data: String,
},
ToolUse(ToolUse),
ToolResult(ToolResult),
}
impl ContentPart {
pub fn is_reasoning(&self) -> bool {
matches!(self, ContentPart::Thinking { .. } | ContentPart::RedactedThinking { .. })
}
pub fn text(text: String) -> Self {
Self::Text(text)
}
pub fn as_tool_use(&self) -> Option<&ToolUse> {
match self {
Self::ToolUse(tool_use) => Some(tool_use),
_ => None,
}
}
pub fn image(media_type: String, data: String) -> Self {
Self::Image(Attachment::Base64 { media_type, data })
}
pub fn document(media_type: String, data: String) -> Self {
Self::Document(Attachment::Base64 { media_type, data })
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum Attachment {
Base64 {
media_type: String,
data: String,
},
Url {
url: String,
},
}
impl Attachment {
pub(crate) fn to_uri(&self) -> String {
match self {
Attachment::Base64 { media_type, data } => format!("data:{media_type};base64,{data}"),
Attachment::Url { url } => url.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum Content {
Text(String),
Parts(Vec<ContentPart>),
}
impl Content {
pub fn text(text: String) -> Self {
Self::Text(text)
}
pub fn as_text(&self) -> String {
match self {
Content::Text(text) => text.clone(),
Content::Parts(parts) => parts
.iter()
.filter_map(|part| match part {
ContentPart::Text(text) => Some(text.as_str()),
_ => None,
})
.collect::<Vec<&str>>()
.join("\n"),
}
}
pub fn as_parts(&self) -> Cow<'_, [ContentPart]> {
match self {
Content::Parts(parts) => Cow::Borrowed(parts),
Content::Text(text) => Cow::Owned(vec![ContentPart::Text(text.clone())]),
}
}
pub fn parts(&self) -> &[ContentPart] {
match self {
Content::Parts(parts) => parts,
Content::Text(_) => &[],
}
}
pub fn add_part(&mut self, part: ContentPart) {
match self {
Content::Parts(parts) => parts.push(part),
Content::Text(text) => {
*self = Content::Parts(vec![ContentPart::Text(text.clone()), part])
}
}
}
pub fn add_parts(&mut self, other_parts: Vec<ContentPart>) {
match self {
Content::Parts(parts) => parts.extend(other_parts),
Content::Text(text) => {
*self = Content::Parts(vec![ContentPart::Text(text.clone())]);
self.add_parts(other_parts);
}
}
}
pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUse> + '_ {
self.parts().iter().filter_map(ContentPart::as_tool_use)
}
pub fn images(&self) -> impl Iterator<Item = &Attachment> {
self.parts().iter().filter_map(|part| match part {
ContentPart::Image(image) => Some(image),
_ => None,
})
}
pub fn documents(&self) -> impl Iterator<Item = &Attachment> {
self.parts().iter().filter_map(|part| match part {
ContentPart::Document(document) => Some(document),
_ => None,
})
}
pub fn is_empty(&self) -> bool {
match self {
Content::Text(text) => text.is_empty(),
Content::Parts(parts) => {
parts.is_empty()
|| parts.len() == 1
&& match parts.first() {
Some(ContentPart::Text(text)) => text.is_empty(),
_ => false,
}
}
}
}
pub fn trim_thinkings(&mut self) -> usize {
if let Content::Parts(parts) = self {
let previous_len = parts.len();
parts.retain(|part| !part.is_reasoning());
return previous_len - parts.len();
}
0
}
pub fn add_reminder(&mut self, text: String) {
self.add_part(ContentPart::reminder(text));
}
pub(crate) fn reminder(text: String) -> Content {
Self::Text(reminder(text))
}
}
impl ContentPart {
pub fn reminder(text: String) -> Self {
Self::Text(reminder(text))
}
}
fn reminder(text: String) -> String {
format!("<system-reminder>\n{text}\n</system-reminder>")
}
impl std::fmt::Display for Content {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Content::Text(text) => write!(f, "{text}"),
Content::Parts(parts) => write!(f, "{parts:?}"),
}
}
}
#[cfg(test)]
mod tests {
use super::{Content, ContentPart, Message};
#[test]
fn tags_are_saved_only_when_set() {
let mut message = Message::model("answer".to_string());
let saved = serde_json::to_value(&message).unwrap();
assert!(saved.get("tags").is_none());
assert!(serde_json::from_value::<Message>(saved).unwrap().tags.is_empty());
message.tags.insert("phase".to_string(), "final_answer".to_string());
let saved = serde_json::to_value(&message).unwrap();
assert_eq!(saved["tags"]["phase"], "final_answer");
assert_eq!(serde_json::from_value::<Message>(saved).unwrap().tags, message.tags);
}
#[test]
fn a_reminder_is_the_text_on_its_own_lines_between_the_tags() {
assert_eq!(
ContentPart::reminder("runtime rule".to_string()),
ContentPart::Text("<system-reminder>\nruntime rule\n</system-reminder>".to_string())
);
}
#[test]
fn content_trim_thinkings() {
let mut c = Content::Parts(vec![
ContentPart::Text("hello".to_string()),
ContentPart::Thinking { text: "thinking".to_string(), signature: None },
]);
let trimmed = c.trim_thinkings();
assert_eq!(trimmed, 1);
assert!(
matches!(&c, Content::Parts(parts) if parts.len() == 1 && matches!(&parts[0], ContentPart::Text(t) if t == "hello"))
);
let mut c = Content::Parts(vec![
ContentPart::Thinking { text: "thinking".to_string(), signature: None },
ContentPart::Thinking { text: "thinking".to_string(), signature: None },
]);
let trimmed = c.trim_thinkings();
assert_eq!(trimmed, 2);
assert!(c.is_empty());
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Message {
pub role: Role,
pub content: Content,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub tags: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum Role {
User,
Model,
System,
Custom(String),
}
impl Message {
pub fn new(role: Role, content: Content) -> Self {
Self { role, content, tags: BTreeMap::new() }
}
pub fn system(text: String) -> Self {
Self::new(Role::System, Content::text(text))
}
pub fn user(content: Content) -> Self {
Self::new(Role::User, content)
}
pub fn user_text(text: String) -> Self {
Self::new(Role::User, Content::text(text))
}
pub fn model(text: String) -> Self {
Self::new(Role::Model, Content::text(text))
}
pub fn model_content(content: Content) -> Self {
Self::new(Role::Model, content)
}
pub fn is_user(&self) -> bool {
self.role == Role::User
}
pub fn is_model(&self) -> bool {
self.role == Role::Model
}
pub fn is_system(&self) -> bool {
self.role == Role::System
}
pub fn is_empty(&self) -> bool {
self.content.is_empty()
}
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}: {}", self.role, self.content)
}
}