use serde::{Deserialize, Serialize};
use std::time::SystemTime;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Assistant,
}
impl Role {
pub fn is_user(&self) -> bool {
matches!(self, Role::User)
}
pub fn is_assistant(&self) -> bool {
matches!(self, Role::Assistant)
}
}
pub type ToolCallId = String;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolCall {
pub id: ToolCallId,
pub name: String,
pub arguments: serde_json::Value,
}
impl ToolCall {
pub fn new(
id: impl Into<String>,
name: impl Into<String>,
arguments: serde_json::Value,
) -> Self {
Self {
id: id.into(),
name: name.into(),
arguments,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolResult {
pub call_id: ToolCallId,
pub output: Option<String>,
pub error: Option<String>,
}
impl ToolResult {
pub fn success(call_id: impl Into<String>, output: impl Into<String>) -> Self {
Self {
call_id: call_id.into(),
output: Some(output.into()),
error: None,
}
}
pub fn failure(call_id: impl Into<String>, error: impl Into<String>) -> Self {
Self {
call_id: call_id.into(),
output: None,
error: Some(error.into()),
}
}
pub fn is_success(&self) -> bool {
self.error.is_none()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
Text {
text: String,
},
ToolCall(ToolCall),
ToolResult(ToolResult),
}
impl ContentPart {
pub fn text(text: impl Into<String>) -> Self {
Self::Text { text: text.into() }
}
pub fn tool_call(
id: impl Into<String>,
name: impl Into<String>,
arguments: serde_json::Value,
) -> Self {
Self::ToolCall(ToolCall::new(id, name, arguments))
}
pub fn tool_result_success(call_id: impl Into<String>, output: impl Into<String>) -> Self {
Self::ToolResult(ToolResult::success(call_id, output))
}
pub fn tool_result_failure(call_id: impl Into<String>, error: impl Into<String>) -> Self {
Self::ToolResult(ToolResult::failure(call_id, error))
}
pub fn is_text(&self) -> bool {
matches!(self, ContentPart::Text { .. })
}
pub fn is_tool_call(&self) -> bool {
matches!(self, ContentPart::ToolCall(_))
}
pub fn is_tool_result(&self) -> bool {
matches!(self, ContentPart::ToolResult(_))
}
pub fn as_text(&self) -> Option<&str> {
match self {
ContentPart::Text { text } => Some(text),
_ => None,
}
}
pub fn as_tool_call(&self) -> Option<&ToolCall> {
match self {
ContentPart::ToolCall(call) => Some(call),
_ => None,
}
}
pub fn as_tool_result(&self) -> Option<&ToolResult> {
match self {
ContentPart::ToolResult(result) => Some(result),
_ => None,
}
}
}
pub type MessageId = String;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {
pub id: MessageId,
pub role: Role,
pub content: Vec<ContentPart>,
#[serde(with = "system_time_serde")]
pub created_at: SystemTime,
}
impl Message {
pub fn new(role: Role, content: Vec<ContentPart>) -> Self {
Self {
id: generate_message_id(),
role,
content,
created_at: SystemTime::now(),
}
}
pub fn user(text: impl Into<String>) -> Self {
Self::new(Role::User, vec![ContentPart::text(text)])
}
pub fn assistant(content: Vec<ContentPart>) -> Self {
Self::new(Role::Assistant, content)
}
pub fn assistant_text(text: impl Into<String>) -> Self {
Self::assistant(vec![ContentPart::text(text)])
}
pub fn tool_results(results: Vec<ToolResult>) -> Self {
Self::new(
Role::User,
results.into_iter().map(ContentPart::ToolResult).collect(),
)
}
pub fn text_content(&self) -> String {
self.content
.iter()
.filter_map(|part| part.as_text())
.collect::<Vec<_>>()
.join("")
}
pub fn tool_calls(&self) -> Vec<&ToolCall> {
self.content
.iter()
.filter_map(|part| part.as_tool_call())
.collect()
}
pub fn has_tool_calls(&self) -> bool {
self.content.iter().any(|part| part.is_tool_call())
}
pub fn is_user(&self) -> bool {
self.role.is_user()
}
pub fn is_assistant(&self) -> bool {
self.role.is_assistant()
}
}
fn generate_message_id() -> MessageId {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("msg_{}_{}", timestamp, counter)
}
mod system_time_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let millis = time
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
millis.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
where
D: Deserializer<'de>,
{
let millis = u64::deserialize(deserializer)?;
Ok(UNIX_EPOCH + Duration::from_millis(millis))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_role_serialization() {
assert_eq!(serde_json::to_string(&Role::User).unwrap(), "\"user\"");
assert_eq!(
serde_json::to_string(&Role::Assistant).unwrap(),
"\"assistant\""
);
}
#[test]
fn test_role_deserialization() {
let user: Role = serde_json::from_str("\"user\"").unwrap();
let assistant: Role = serde_json::from_str("\"assistant\"").unwrap();
assert_eq!(user, Role::User);
assert_eq!(assistant, Role::Assistant);
}
#[test]
fn test_role_helpers() {
assert!(Role::User.is_user());
assert!(!Role::User.is_assistant());
assert!(Role::Assistant.is_assistant());
assert!(!Role::Assistant.is_user());
}
#[test]
fn test_content_part_text() {
let part = ContentPart::text("Hello, world!");
assert!(part.is_text());
assert_eq!(part.as_text(), Some("Hello, world!"));
assert!(!part.is_tool_call());
assert!(!part.is_tool_result());
}
#[test]
fn test_content_part_tool_call() {
let part = ContentPart::tool_call(
"call_1",
"read_file",
serde_json::json!({"path": "/tmp/test.txt"}),
);
assert!(part.is_tool_call());
assert!(!part.is_text());
let call = part.as_tool_call().unwrap();
assert_eq!(call.name, "read_file");
assert_eq!(call.id, "call_1");
}
#[test]
fn test_content_part_tool_result() {
let success = ContentPart::tool_result_success("call_1", "file contents here");
assert!(success.is_tool_result());
assert!(success.as_tool_result().unwrap().is_success());
let failure = ContentPart::tool_result_failure("call_2", "file not found");
assert!(failure.is_tool_result());
assert!(!failure.as_tool_result().unwrap().is_success());
}
#[test]
fn test_message_user() {
let msg = Message::user("Hello, agent!");
assert!(msg.is_user());
assert!(!msg.is_assistant());
assert_eq!(msg.text_content(), "Hello, agent!");
assert!(!msg.has_tool_calls());
}
#[test]
fn test_message_assistant_text() {
let msg = Message::assistant_text("I can help with that.");
assert!(msg.is_assistant());
assert_eq!(msg.text_content(), "I can help with that.");
}
#[test]
fn test_message_with_tool_calls() {
let msg = Message::assistant(vec![
ContentPart::text("Let me read that file."),
ContentPart::tool_call(
"call_1",
"read_file",
serde_json::json!({"path": "/tmp/test.txt"}),
),
]);
assert!(msg.has_tool_calls());
assert_eq!(msg.tool_calls().len(), 1);
assert_eq!(msg.tool_calls()[0].name, "read_file");
assert_eq!(msg.text_content(), "Let me read that file.");
}
#[test]
fn test_message_serialization_roundtrip() {
let original = Message::user("Test message");
let json = serde_json::to_string(&original).unwrap();
let restored: Message = serde_json::from_str(&json).unwrap();
assert_eq!(original.id, restored.id);
assert_eq!(original.role, restored.role);
assert_eq!(original.text_content(), restored.text_content());
}
#[test]
fn test_tool_call_serialization() {
let call = ToolCall::new("call_123", "bash", serde_json::json!({"command": "ls -la"}));
let json = serde_json::to_string(&call).unwrap();
let restored: ToolCall = serde_json::from_str(&json).unwrap();
assert_eq!(call.id, restored.id);
assert_eq!(call.name, restored.name);
assert_eq!(call.arguments, restored.arguments);
}
#[test]
fn test_tool_result_success() {
let result = ToolResult::success("call_1", "output text");
assert!(result.is_success());
assert_eq!(result.output, Some("output text".to_string()));
assert_eq!(result.error, None);
}
#[test]
fn test_tool_result_failure() {
let result = ToolResult::failure("call_1", "something went wrong");
assert!(!result.is_success());
assert_eq!(result.output, None);
assert_eq!(result.error, Some("something went wrong".to_string()));
}
#[test]
fn test_content_part_serde_tagged() {
let text = ContentPart::text("hello");
let json = serde_json::to_string(&text).unwrap();
assert!(json.contains("\"type\":\"text\""));
let call = ContentPart::tool_call("id", "name", serde_json::json!({}));
let json = serde_json::to_string(&call).unwrap();
assert!(json.contains("\"type\":\"tool_call\""));
}
#[test]
fn test_message_id_generation() {
let msg1 = Message::user("first");
let msg2 = Message::user("second");
assert_ne!(msg1.id, msg2.id);
assert!(msg1.id.starts_with("msg_"));
}
}