use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ContentBlock {
Text {
text: String,
},
Thinking {
thinking: String,
},
ToolCall {
id: String,
name: String,
arguments: serde_json::Value,
},
ToolResult {
tool_call_id: String,
content: String,
#[serde(default)]
is_error: bool,
},
}
impl ContentBlock {
pub fn text(text: impl Into<String>) -> Self {
ContentBlock::Text { text: text.into() }
}
pub fn tool_result(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
ContentBlock::ToolResult {
tool_call_id: tool_call_id.into(),
content: content.into(),
is_error: false,
}
}
pub fn tool_error(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
ContentBlock::ToolResult {
tool_call_id: tool_call_id.into(),
content: content.into(),
is_error: true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Assistant,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Message {
pub role: Role,
pub content: Vec<ContentBlock>,
}
impl Message {
pub fn user(text: impl Into<String>) -> Self {
Message {
role: Role::User,
content: vec![ContentBlock::text(text)],
}
}
pub fn assistant(text: impl Into<String>) -> Self {
Message {
role: Role::Assistant,
content: vec![ContentBlock::text(text)],
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
Stop,
Length,
ToolUse,
Refusal,
Error,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Usage {
pub input: u32,
pub output: u32,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn content_block_round_trips_through_json() {
let blocks = vec![
ContentBlock::text("hello"),
ContentBlock::Thinking {
thinking: "hmm".into(),
},
ContentBlock::ToolCall {
id: "call_1".into(),
name: "get_weather".into(),
arguments: serde_json::json!({ "city": "Paris" }),
},
ContentBlock::ToolResult {
tool_call_id: "call_1".into(),
content: "sunny".into(),
is_error: false,
},
];
let json = serde_json::to_string(&blocks).unwrap();
let back: Vec<ContentBlock> = serde_json::from_str(&json).unwrap();
assert_eq!(blocks, back);
}
#[test]
fn tool_call_block_uses_camel_case_tag_fields() {
let json = serde_json::to_value(ContentBlock::ToolResult {
tool_call_id: "x".into(),
content: "y".into(),
is_error: true,
})
.unwrap();
assert_eq!(json["type"], "toolResult");
assert_eq!(json["tool_call_id"], "x");
assert_eq!(json["is_error"], true);
}
}