use std::collections::HashMap;
use serde_json::Value;
use causa_kernel::{
BlockContent, ContentPart, ContextFrame, MediaRef, ModelInvokeError, ModelInvokeErrorKind,
ModelItem, ModelItemContent, SealedPart, ToolChange, ToolDefinition, ToolResultStatus,
WireMeta, current_tools,
};
pub(crate) use causa_kernel::Role;
use super::media::{MediaKind, MediaSet, MediaSource};
use crate::Protocol;
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ResolvedMedia {
Image {
media_type: String,
source: MediaSource,
},
Document {
media_type: String,
source: MediaSource,
name: Option<String>,
},
Placeholder(String),
}
fn placeholder_text(r: &MediaRef) -> String {
match &r.name {
Some(name) => format!("[media: {} {} {}]", r.media_type, name, r.reference),
None => format!("[media: {} {}]", r.media_type, r.reference),
}
}
fn is_supported_http_url(url: &str) -> bool {
if let Some(prefix) = url.get(..7)
&& prefix.eq_ignore_ascii_case("http://")
{
return url.len() > 7;
}
if let Some(prefix) = url.get(..8)
&& prefix.eq_ignore_ascii_case("https://")
{
return url.len() > 8;
}
false
}
fn emits(protocol: Protocol, kind: MediaKind, source: &MediaSource) -> bool {
match (protocol, kind, source) {
(
Protocol::AnthropicMessages,
MediaKind::Image | MediaKind::Document,
MediaSource::Inline { .. } | MediaSource::Url(_),
) => true,
(
Protocol::OpenAiChatCompletions | Protocol::OpenAiResponses,
MediaKind::Image,
MediaSource::Inline { .. } | MediaSource::Url(_),
) => true,
(Protocol::OpenAiChatCompletions | Protocol::OpenAiResponses, MediaKind::Document, _) => {
false
}
}
}
fn resolve_media(r: &MediaRef, role: Role, media: &MediaSet, protocol: Protocol) -> ResolvedMedia {
if role != Role::User {
return ResolvedMedia::Placeholder(placeholder_text(r));
}
let Some(payload) = media.get(r) else {
return ResolvedMedia::Placeholder(placeholder_text(r));
};
let Some(kind) = MediaKind::of(&payload.media_type) else {
return ResolvedMedia::Placeholder(placeholder_text(r));
};
if !emits(protocol, kind, &payload.source) {
return ResolvedMedia::Placeholder(placeholder_text(r));
}
let usable = match &payload.source {
MediaSource::Inline { data_base64 } => !data_base64.is_empty(),
MediaSource::Url(u) => is_supported_http_url(u),
};
if !usable {
return ResolvedMedia::Placeholder(placeholder_text(r));
}
match kind {
MediaKind::Image => ResolvedMedia::Image {
media_type: payload.media_type.clone(),
source: payload.source.clone(),
},
MediaKind::Document => ResolvedMedia::Document {
media_type: payload.media_type.clone(),
source: payload.source.clone(),
name: r.name.clone(),
},
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PreparedCall {
pub wire_id: String,
pub name: String,
pub arguments: Value,
pub wire: Option<Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Origin {
pub block: usize,
pub parts: usize,
pub wire: Option<Value>,
}
pub(crate) fn leading_system_len(segments: &[Segment]) -> usize {
segments
.iter()
.take_while(|segment| {
matches!(
segment,
Segment::Text {
role: Role::System,
..
} | Segment::Media {
role: Role::System,
media: ResolvedMedia::Placeholder(_),
..
}
)
})
.count()
}
pub(crate) fn is_blank_text(text: &str) -> bool {
text.trim().is_empty()
}
pub(crate) fn same_block_run(segments: &[Segment], from: usize) -> usize {
let Some(Segment::Text { origin, .. }) = segments.get(from) else {
return 0;
};
segments[from..]
.iter()
.take_while(|segment| {
matches!(
segment,
Segment::Text { role: Role::Assistant, origin: o, .. } if o.block == origin.block
)
})
.count()
}
fn user_part_block(segment: &Segment) -> Option<usize> {
match segment {
Segment::Text {
role: Role::User,
origin,
..
} => Some(origin.block),
Segment::Media {
role: Role::User,
block,
..
} => Some(*block),
_ => None,
}
}
pub(crate) fn user_block_run(segments: &[Segment], from: usize) -> usize {
let Some(block) = segments.get(from).and_then(user_part_block) else {
return 0;
};
segments[from..]
.iter()
.take_while(|segment| user_part_block(segment) == Some(block))
.count()
}
pub(crate) fn without_keys(value: &Value, keys: &[&str]) -> Value {
let mut copy = value.clone();
if let Value::Object(map) = &mut copy {
for key in keys {
map.remove(*key);
}
}
copy
}
pub(crate) fn wire_meta(protocol: Protocol, fields: Value) -> WireMeta {
WireMeta::new(protocol.as_str().to_owned(), fields)
}
pub(crate) fn sealed_item(protocol: Protocol, item: Value) -> ModelItem {
ModelItem::new(ModelItemContent::Parts(vec![ContentPart::Sealed(
SealedPart::new(protocol.as_str().to_owned(), item),
)]))
}
pub(crate) fn residue_object(fields: Option<&Value>) -> serde_json::Map<String, Value> {
match fields {
Some(Value::Object(map)) => map.clone(),
_ => serde_json::Map::new(),
}
}
pub(crate) fn wire_arguments_string(raw: Option<&Value>, facts: &Value) -> String {
if let Some(raw) = raw.and_then(Value::as_str)
&& serde_json::from_str::<Value>(raw).is_ok_and(|parsed| parsed == *facts)
{
return raw.to_owned();
}
facts.to_string()
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Segment {
Text {
role: Role,
text: String,
origin: Origin,
},
Sealed(Value),
Media {
role: Role,
media: ResolvedMedia,
block: usize,
},
ToolCall(PreparedCall),
ToolResult {
wire_id: String,
status: ToolResultStatus,
content: String,
notes: Vec<String>,
media: Vec<ResolvedMedia>,
},
ToolChange(ToolChange),
}
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,
protocol: Protocol,
in_place_changes: bool,
) -> 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();
let mut declared = false;
for (block_index, block) in blocks.iter().enumerate() {
let own_wire = || {
block
.meta()
.wire
.as_ref()
.filter(|wire| wire.format == protocol.as_str())
.map(|wire| wire.fields.clone())
};
match block.content() {
BlockContent::Message { role, parts } => {
let role = *role;
for part in parts {
match part {
ContentPart::Text(t) => {
if t.0.is_empty() {
continue;
}
segments.push(Segment::Text {
role,
text: t.0.clone(),
origin: Origin {
block: block_index,
parts: parts.len(),
wire: if role == Role::Assistant {
own_wire()
} else {
None
},
},
});
}
ContentPart::Media(r) => {
segments.push(Segment::Media {
role,
media: resolve_media(r, role, media, protocol),
block: block_index,
});
}
ContentPart::Sealed(sealed) => {
if role == Role::Assistant && sealed.format == protocol.as_str() {
segments.push(Segment::Sealed(sealed.item.clone()));
}
}
}
}
}
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(),
wire: own_wire(),
}));
}
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, protocol))
.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,
});
}
BlockContent::ToolChange(change) => {
if declared && in_place_changes {
segments.push(Segment::ToolChange(change.clone()));
}
declared = true;
}
}
}
NormalizedFrame { segments }
}
pub(crate) fn decode_wire_arguments(
raw: Option<&Value>,
cut_off: bool,
) -> Result<Option<Value>, ModelInvokeError> {
let parsed = raw
.and_then(Value::as_str)
.ok_or("function arguments: expected a JSON string")
.and_then(|raw| {
serde_json::from_str(raw).map_err(|_| "function arguments: invalid or incomplete JSON")
});
match parsed {
Ok(arguments) => Ok(Some(arguments)),
Err(_) if cut_off => Ok(None),
Err(message) => Err(ModelInvokeError::new(
ModelInvokeErrorKind::Undecodable,
message,
)),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolShape {
Anthropic,
OpenAiChat,
OpenAiResponses,
}
pub(crate) fn tool_definitions(definitions: &[ToolDefinition], shape: ToolShape) -> Vec<Value> {
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()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolPlacement {
Fold,
AnthropicInPlace,
ResponsesAdditive,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ToolPlan {
pub tools: Vec<ToolDefinition>,
pub in_place: bool,
}
pub(crate) fn plan_tools(frame: &ContextFrame, placement: ToolPlacement) -> ToolPlan {
let fold = || ToolPlan {
tools: current_tools(&frame.blocks),
in_place: false,
};
let mut changes = frame
.blocks
.iter()
.filter_map(|block| match block.content() {
BlockContent::ToolChange(change) => Some(change),
_ => None,
});
let Some(first) = changes.next() else {
return fold();
};
let mut declaration = Vec::new();
first.apply_to(&mut declaration);
let expressible = match placement {
ToolPlacement::Fold => false,
ToolPlacement::AnthropicInPlace => !declaration.is_empty(),
ToolPlacement::ResponsesAdditive => {
let mut names: Vec<&str> = declaration.iter().map(|d| d.name.as_str()).collect();
changes.all(|change| {
change.removed.is_empty()
&& change.added.iter().all(|definition| {
let new = !names.contains(&definition.name.as_str());
names.push(&definition.name);
new
})
})
}
};
if expressible {
ToolPlan {
tools: declaration,
in_place: true,
}
} else {
fold()
}
}