use std::collections::HashMap;
use super::ContentBlockType;
#[derive(Debug, Clone, PartialEq)]
pub enum ContentBlock {
Text(TextBlock),
ToolUse(ToolUseBlock),
ToolResult(ToolResultBlock),
}
impl ContentBlock {
pub fn block_type(&self) -> ContentBlockType {
match self {
Self::Text(_) => ContentBlockType::Text,
Self::ToolUse(_) => ContentBlockType::ToolUse,
Self::ToolResult(_) => ContentBlockType::ToolResult,
}
}
pub fn text(text: impl Into<String>) -> Self {
Self::Text(TextBlock { text: text.into() })
}
pub fn tool_use(
id: impl Into<String>,
name: impl Into<String>,
input: HashMap<String, serde_json::Value>,
) -> Self {
Self::ToolUse(ToolUseBlock {
id: id.into(),
name: name.into(),
input,
})
}
pub fn tool_result(
tool_use_id: impl Into<String>,
content: impl Into<String>,
is_error: bool,
) -> Self {
Self::ToolResult(ToolResultBlock {
tool_use_id: tool_use_id.into(),
content: content.into(),
is_error,
compact_summary: None,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextBlock {
pub text: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolUseBlock {
pub id: String,
pub name: String,
pub input: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolResultBlock {
pub tool_use_id: String,
pub content: String,
pub is_error: bool,
pub compact_summary: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_text_block() {
let block = ContentBlock::text("Hello, world!");
assert_eq!(block.block_type(), ContentBlockType::Text);
if let ContentBlock::Text(text_block) = block {
assert_eq!(text_block.text, "Hello, world!");
} else {
panic!("Expected text block");
}
}
#[test]
fn test_tool_use_block() {
let mut input = HashMap::new();
input.insert("query".to_string(), serde_json::json!("test"));
let block = ContentBlock::tool_use("tool_123", "search", input);
assert_eq!(block.block_type(), ContentBlockType::ToolUse);
if let ContentBlock::ToolUse(tool_block) = block {
assert_eq!(tool_block.id, "tool_123");
assert_eq!(tool_block.name, "search");
} else {
panic!("Expected tool use block");
}
}
#[test]
fn test_tool_result_block() {
let block = ContentBlock::tool_result("tool_123", "{\"result\": \"success\"}", false);
assert_eq!(block.block_type(), ContentBlockType::ToolResult);
if let ContentBlock::ToolResult(result_block) = block {
assert_eq!(result_block.tool_use_id, "tool_123");
assert!(!result_block.is_error);
} else {
panic!("Expected tool result block");
}
}
}