use super::{ModelItemContent, ModelResponse, ModelStopReason};
use crate::context::block::{BlockContent, BlockMeta, ContentPart, ContextBlock, ToolCallPayload};
use crate::context::ids::BlockId;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ModelBlockError {
#[error("EndTurn includes {count} tool calls")]
#[non_exhaustive]
EndTurnWithToolCalls {
count: usize,
},
#[error("ToolUse has no tool calls")]
ToolUseWithoutToolCalls,
#[error("expected {expected} block ids, received {actual}")]
#[non_exhaustive]
BlockIdCountMismatch {
expected: usize,
actual: usize,
},
#[error("tool {tool_index} has an empty name")]
#[non_exhaustive]
EmptyToolName {
tool_index: usize,
},
#[error("tool {tool_index} arguments are not an object")]
#[non_exhaustive]
ArgumentsNotObject {
tool_index: usize,
},
}
impl ModelResponse {
pub fn block_count(&self) -> usize {
self.items
.iter()
.filter(|item| match &item.content {
ModelItemContent::Parts(parts) => parts.iter().any(keeps_part),
ModelItemContent::ToolCall(_) => true,
})
.count()
}
pub fn to_blocks(
&self,
stop_reason: ModelStopReason,
block_ids: &[BlockId],
) -> Result<Vec<ContextBlock>, ModelBlockError> {
let tool_count = self.tool_calls().count();
match stop_reason {
ModelStopReason::EndTurn if tool_count > 0 => {
return Err(ModelBlockError::EndTurnWithToolCalls { count: tool_count });
}
ModelStopReason::ToolUse if tool_count == 0 => {
return Err(ModelBlockError::ToolUseWithoutToolCalls);
}
ModelStopReason::EndTurn
| ModelStopReason::ToolUse
| ModelStopReason::MaxTokens
| ModelStopReason::Refusal
| ModelStopReason::ContextWindowExceeded
| ModelStopReason::Unrecognized => {}
}
let expected = self.block_count();
if expected != block_ids.len() {
return Err(ModelBlockError::BlockIdCountMismatch {
expected,
actual: block_ids.len(),
});
}
for (tool_index, call) in self.tool_calls().enumerate() {
if call.tool_name.trim().is_empty() {
return Err(ModelBlockError::EmptyToolName { tool_index });
}
if !call.arguments.is_object() {
return Err(ModelBlockError::ArgumentsNotObject { tool_index });
}
}
let mut ids = block_ids.iter().copied();
let mut blocks = Vec::with_capacity(expected);
for item in &self.items {
match &item.content {
ModelItemContent::Parts(parts) => {
let parts: Vec<ContentPart> =
parts.iter().filter(|p| keeps_part(p)).cloned().collect();
if parts.is_empty() {
continue;
}
blocks.push(ContextBlock::new(
ids.next().expect("identity count validated"),
BlockContent::Parts(parts),
BlockMeta {
wire: item.wire.clone(),
..BlockMeta::default()
},
));
}
ModelItemContent::ToolCall(call) => {
blocks.push(ContextBlock::new(
ids.next().expect("identity count validated"),
BlockContent::ToolCall(ToolCallPayload {
tool_name: call.tool_name.clone(),
arguments: call.arguments.clone(),
}),
BlockMeta {
provider_call_id: call.provider_call_id.clone(),
wire: item.wire.clone(),
..BlockMeta::default()
},
));
}
}
}
Ok(blocks)
}
}
fn keeps_part(part: &ContentPart) -> bool {
!matches!(part, ContentPart::Text(t) if t.0.is_empty())
}