use std::collections::HashMap;
use serde_json::Value;
use causa_kernel::{
BlockContent, ContentPart, ContextFrame, MediaRef, ModelInvokeError, ModelInvokeErrorKind,
ToolResultStatus, ToolSurface,
};
use super::media::MediaSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Role {
System,
User,
Assistant,
}
pub(crate) fn text_role(source: Option<&str>) -> Role {
match source {
None | Some("assistant") => Role::Assistant,
Some("system") => Role::System,
Some(_) => Role::User,
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ResolvedMedia {
Image {
media_type: String,
data_base64: String,
},
Placeholder(String),
}
fn placeholder_text(r: &MediaRef) -> String {
format!("[media: {} {}]", r.media_type, r.reference)
}
fn resolve_media(r: &MediaRef, role: Role, media: &MediaSet) -> ResolvedMedia {
if role != Role::User {
return ResolvedMedia::Placeholder(placeholder_text(r));
}
match media.get(r) {
Some(p) if p.media_type.starts_with("image/") && !p.data_base64.is_empty() => {
ResolvedMedia::Image {
media_type: p.media_type.clone(),
data_base64: p.data_base64.clone(),
}
}
_ => ResolvedMedia::Placeholder(placeholder_text(r)),
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PreparedCall {
pub wire_id: String,
pub name: String,
pub arguments: Value,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Segment {
Text {
role: Role,
text: String,
},
Media {
role: Role,
media: ResolvedMedia,
},
ToolCall(PreparedCall),
ToolResult {
wire_id: String,
status: ToolResultStatus,
content: String,
notes: Vec<String>,
media: Vec<ResolvedMedia>,
},
}
pub(crate) struct NormalizedFrame {
pub segments: Vec<Segment>,
}
pub(crate) fn result_text_with_notes(content: &str, notes: &[String]) -> String {
if notes.is_empty() {
return content.to_owned();
}
let mut text = format!("{content}\n\nNotes:");
for note in notes {
text.push_str("\n- ");
text.push_str(note);
}
text
}
pub(crate) fn normalize(frame: &ContextFrame, media: &MediaSet) -> NormalizedFrame {
let blocks = &frame.blocks;
let mut provider_ids: HashMap<causa_kernel::BlockId, String> = HashMap::new();
for block in blocks {
if let BlockContent::ToolCall(_) = block.content() {
provider_ids.insert(
block.id(),
block
.meta()
.provider_call_id
.clone()
.unwrap_or_else(|| block.id().0.to_string()),
);
}
}
let mut segments: Vec<Segment> = Vec::new();
for block in blocks {
let mut block_emitted = false;
match block.content() {
BlockContent::Parts(parts) => {
let role = text_role(block.meta().source.as_deref());
for part in parts {
match part {
ContentPart::Text(t) => {
if t.0.is_empty() {
continue;
}
if !block_emitted
&& let Some(Segment::Text {
role: last_role,
text: last_text,
}) = segments.last_mut()
&& *last_role == role
{
last_text.push('\n');
last_text.push_str(&t.0);
} else {
segments.push(Segment::Text {
role,
text: t.0.clone(),
});
}
block_emitted = true;
}
ContentPart::Media(r) => {
segments.push(Segment::Media {
role,
media: resolve_media(r, role, media),
});
block_emitted = true;
}
}
}
}
BlockContent::ToolCall(call) => {
segments.push(Segment::ToolCall(PreparedCall {
wire_id: block
.meta()
.provider_call_id
.clone()
.unwrap_or_else(|| block.id().0.to_string()),
name: call.tool_name.clone(),
arguments: call.arguments.clone(),
}));
}
BlockContent::ToolResult(result) => {
let content = match &result.output.content {
Value::String(s) => s.clone(),
other => other.to_string(),
};
let resolved = result
.media
.iter()
.map(|r| resolve_media(r, Role::User, media))
.collect();
segments.push(Segment::ToolResult {
wire_id: provider_ids
.get(&result.call_block_id)
.cloned()
.expect("renderer validated tool declaration"),
status: result.status.clone(),
content,
notes: result.notes.iter().map(|note| note.0.clone()).collect(),
media: resolved,
});
}
}
}
NormalizedFrame { segments }
}
pub(crate) fn decode_wire_arguments(raw: Option<&Value>) -> Result<Value, ModelInvokeError> {
match raw {
None | Some(Value::Null) => Ok(serde_json::json!({})),
Some(Value::String(s)) if s.trim().is_empty() => Ok(serde_json::json!({})),
Some(Value::String(s)) => serde_json::from_str(s).map_err(|e| {
ModelInvokeError::new(
ModelInvokeErrorKind::Permanent,
format!("function arguments: {e}"),
)
}),
Some(other) => Ok(other.clone()),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolShape {
Anthropic,
OpenAiChat,
OpenAiResponses,
}
pub(crate) fn tool_definitions(tool_surface: &ToolSurface, shape: ToolShape) -> Vec<Value> {
tool_surface
.definitions
.iter()
.map(|d| match shape {
ToolShape::Anthropic => serde_json::json!({
"name": d.name,
"description": d.description,
"input_schema": d.parameters,
}),
ToolShape::OpenAiChat => serde_json::json!({
"type": "function",
"function": {
"name": d.name,
"description": d.description,
"parameters": d.parameters,
},
}),
ToolShape::OpenAiResponses => serde_json::json!({
"type": "function",
"name": d.name,
"description": d.description,
"parameters": d.parameters,
}),
})
.collect()
}