causa_kernel/context/model/
conversion.rs1use super::{ModelItemContent, ModelResponse, ModelStopReason};
4use crate::context::block::{BlockContent, BlockMeta, ContentPart, ContextBlock, ToolCallPayload};
5use crate::context::ids::BlockId;
6
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9#[non_exhaustive]
10pub enum ModelBlockError {
11 #[error("EndTurn includes {count} tool calls")]
13 EndTurnWithToolCalls {
14 count: usize,
16 },
17 #[error("ToolUse has no tool calls")]
19 ToolUseWithoutToolCalls,
20 #[error("expected {expected} block ids, received {actual}")]
22 BlockIdCountMismatch {
23 expected: usize,
25 actual: usize,
27 },
28 #[error("tool {tool_index} has an empty name")]
30 EmptyToolName {
31 tool_index: usize,
33 },
34 #[error("tool {tool_index} arguments are not an object")]
36 ArgumentsNotObject {
37 tool_index: usize,
39 },
40}
41
42impl ModelResponse {
43 pub fn block_count(&self) -> usize {
46 self.items
47 .iter()
48 .filter(|item| match &item.content {
49 ModelItemContent::Parts(parts) => parts.iter().any(keeps_part),
50 ModelItemContent::ToolCall(_) => true,
51 })
52 .count()
53 }
54
55 pub fn to_blocks(
67 &self,
68 stop_reason: ModelStopReason,
69 block_ids: &[BlockId],
70 ) -> Result<Vec<ContextBlock>, ModelBlockError> {
71 let tool_count = self.tool_calls().count();
72 match stop_reason {
73 ModelStopReason::EndTurn if tool_count > 0 => {
74 return Err(ModelBlockError::EndTurnWithToolCalls { count: tool_count });
75 }
76 ModelStopReason::ToolUse if tool_count == 0 => {
77 return Err(ModelBlockError::ToolUseWithoutToolCalls);
78 }
79 ModelStopReason::EndTurn
82 | ModelStopReason::ToolUse
83 | ModelStopReason::MaxTokens
84 | ModelStopReason::Refusal
85 | ModelStopReason::ContextWindowExceeded
86 | ModelStopReason::Unrecognized => {}
87 }
88 let expected = self.block_count();
89 if expected != block_ids.len() {
90 return Err(ModelBlockError::BlockIdCountMismatch {
91 expected,
92 actual: block_ids.len(),
93 });
94 }
95 for (tool_index, call) in self.tool_calls().enumerate() {
96 if call.tool_name.trim().is_empty() {
97 return Err(ModelBlockError::EmptyToolName { tool_index });
98 }
99 if !call.arguments.is_object() {
100 return Err(ModelBlockError::ArgumentsNotObject { tool_index });
101 }
102 }
103 let mut ids = block_ids.iter().copied();
104 let mut blocks = Vec::with_capacity(expected);
105 for item in &self.items {
106 match &item.content {
107 ModelItemContent::Parts(parts) => {
108 let parts: Vec<ContentPart> =
109 parts.iter().filter(|p| keeps_part(p)).cloned().collect();
110 if parts.is_empty() {
111 continue;
112 }
113 blocks.push(ContextBlock::new(
114 ids.next().expect("identity count validated"),
115 BlockContent::Parts(parts),
116 BlockMeta {
117 wire: item.wire.clone(),
118 ..BlockMeta::default()
119 },
120 ));
121 }
122 ModelItemContent::ToolCall(call) => {
123 blocks.push(ContextBlock::new(
124 ids.next().expect("identity count validated"),
125 BlockContent::ToolCall(ToolCallPayload {
126 tool_name: call.tool_name.clone(),
127 arguments: call.arguments.clone(),
128 }),
129 BlockMeta {
130 provider_call_id: call.provider_call_id.clone(),
131 wire: item.wire.clone(),
132 ..BlockMeta::default()
133 },
134 ));
135 }
136 }
137 }
138 Ok(blocks)
139 }
140}
141
142fn keeps_part(part: &ContentPart) -> bool {
145 !matches!(part, ContentPart::Text(t) if t.0.is_empty())
146}