use super::{Content, Role};
use crate::{Image, api::ToolCall, prelude::*, utils};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Visibility {
#[default]
Public,
Internal,
Debug,
}
impl Visibility {
pub fn is_public(&self) -> bool {
matches!(self, Self::Public)
}
pub fn is_internal(&self) -> bool {
matches!(self, Self::Internal)
}
pub fn is_debug(&self) -> bool {
matches!(self, Self::Debug)
}
}
#[derive(Default, From, Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[from(Bytes, expr = Message::user(vec![String::from_utf8_lossy(&value).into()]))]
#[from(String, expr = Message::user(vec![value.into()]))]
#[from(&str, expr = Message::user(vec![value.into()]))]
pub struct Message {
pub role: Role,
pub content: Vec<Content>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tool_calls: Vec<ToolCall>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub tool_call_id: String,
#[serde(default)]
pub tokens_count: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<DateTime<Utc>>,
#[serde(default)]
pub visibility: Visibility,
}
impl Message {
pub fn new(role: Role, content: Vec<Content>) -> Self {
let tokens_count = utils::content_tokens(&content);
Self {
role,
content,
tokens_count,
timestamp: Some(Utc::now()),
..Default::default()
}
}
pub fn system(content: Vec<Content>) -> Self {
Self::new(Role::System, content)
}
pub fn user(content: Vec<Content>) -> Self {
Self::new(Role::User, content)
}
pub fn assistant(content: Vec<Content>, tool_calls: Vec<ToolCall>) -> Self {
Self {
tool_calls,
..Self::new(Role::Assistant, content)
}
}
pub fn tool(content: Vec<Content>, tool_call_id: String) -> Self {
Self {
tool_call_id,
..Self::new(Role::Tool, content)
}
}
pub fn map_content(&mut self, f: impl FnOnce(&mut Vec<Content>)) {
f(&mut self.content);
self.count_tokens();
}
pub fn extract_texts(&self) -> Vec<&str> {
self.content
.iter()
.filter_map(|c| match c {
Content::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
}
pub fn extract_images(&self) -> Vec<&Image> {
self.content
.iter()
.filter_map(|c| match c {
Content::Image { image, .. } => Some(image),
_ => None,
})
.collect::<Vec<_>>()
}
pub fn count_tokens(&mut self) -> usize {
let count = utils::content_tokens(&self.content);
self.tokens_count = count;
count
}
pub fn visibility(mut self, visibility: Visibility) -> Self {
self.visibility = visibility;
self
}
}