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 #[non_exhaustive]
14 EndTurnWithToolCalls {
15 count: usize,
17 },
18 #[error("ToolUse has no tool calls")]
20 ToolUseWithoutToolCalls,
21 #[error("expected {expected} block ids, received {actual}")]
23 #[non_exhaustive]
24 BlockIdCountMismatch {
25 expected: usize,
27 actual: usize,
29 },
30 #[error("tool {tool_index} has an empty name")]
32 #[non_exhaustive]
33 EmptyToolName {
34 tool_index: usize,
36 },
37 #[error("tool {tool_index} arguments are not an object")]
39 #[non_exhaustive]
40 ArgumentsNotObject {
41 tool_index: usize,
43 },
44}
45
46impl ModelResponse {
47 pub fn block_count(&self) -> usize {
50 self.items
51 .iter()
52 .filter(|item| match &item.content {
53 ModelItemContent::Parts(parts) => parts.iter().any(keeps_part),
54 ModelItemContent::ToolCall(_) => true,
55 })
56 .count()
57 }
58
59 pub fn to_blocks(
71 &self,
72 stop_reason: ModelStopReason,
73 block_ids: &[BlockId],
74 ) -> Result<Vec<ContextBlock>, ModelBlockError> {
75 let tool_count = self.tool_calls().count();
76 match stop_reason {
77 ModelStopReason::EndTurn if tool_count > 0 => {
78 return Err(ModelBlockError::EndTurnWithToolCalls { count: tool_count });
79 }
80 ModelStopReason::ToolUse if tool_count == 0 => {
81 return Err(ModelBlockError::ToolUseWithoutToolCalls);
82 }
83 ModelStopReason::EndTurn
86 | ModelStopReason::ToolUse
87 | ModelStopReason::MaxTokens
88 | ModelStopReason::Refusal
89 | ModelStopReason::ContextWindowExceeded
90 | ModelStopReason::Unrecognized => {}
91 }
92 let expected = self.block_count();
93 if expected != block_ids.len() {
94 return Err(ModelBlockError::BlockIdCountMismatch {
95 expected,
96 actual: block_ids.len(),
97 });
98 }
99 for (tool_index, call) in self.tool_calls().enumerate() {
100 if call.tool_name.trim().is_empty() {
101 return Err(ModelBlockError::EmptyToolName { tool_index });
102 }
103 if !call.arguments.is_object() {
104 return Err(ModelBlockError::ArgumentsNotObject { tool_index });
105 }
106 }
107 let mut ids = block_ids.iter().copied();
108 let mut blocks = Vec::with_capacity(expected);
109 for item in &self.items {
110 match &item.content {
111 ModelItemContent::Parts(parts) => {
112 let parts: Vec<ContentPart> =
113 parts.iter().filter(|p| keeps_part(p)).cloned().collect();
114 if parts.is_empty() {
115 continue;
116 }
117 blocks.push(ContextBlock::new(
118 ids.next().expect("identity count validated"),
119 BlockContent::Parts(parts),
120 BlockMeta {
121 wire: item.wire.clone(),
122 ..BlockMeta::default()
123 },
124 ));
125 }
126 ModelItemContent::ToolCall(call) => {
127 blocks.push(ContextBlock::new(
128 ids.next().expect("identity count validated"),
129 BlockContent::ToolCall(ToolCallPayload {
130 tool_name: call.tool_name.clone(),
131 arguments: call.arguments.clone(),
132 }),
133 BlockMeta {
134 provider_call_id: call.provider_call_id.clone(),
135 wire: item.wire.clone(),
136 ..BlockMeta::default()
137 },
138 ));
139 }
140 }
141 }
142 Ok(blocks)
143 }
144}
145
146fn keeps_part(part: &ContentPart) -> bool {
149 !matches!(part, ContentPart::Text(t) if t.0.is_empty())
150}