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