causa_kernel/context/model/
conversion.rs1use super::{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)]
9pub enum ModelBlockError {
10 #[error("EndTurn includes {count} tool calls")]
12 EndTurnWithToolCalls {
13 count: usize,
15 },
16 #[error("ToolUse has no tool calls")]
18 ToolUseWithoutToolCalls,
19 #[error("expected {expected} block ids, received {actual}")]
21 BlockIdCountMismatch {
22 expected: usize,
24 actual: usize,
26 },
27 #[error("tool {tool_index} has an empty name")]
29 EmptyToolName {
30 tool_index: usize,
32 },
33 #[error("tool {tool_index} arguments are not an object")]
35 ArgumentsNotObject {
36 tool_index: usize,
38 },
39}
40
41impl ModelResponse {
42 pub fn block_count(&self) -> usize {
44 usize::from(!self.text.0.trim().is_empty()) + self.tool_calls.len()
45 }
46
47 pub fn to_blocks(
55 &self,
56 stop_reason: ModelStopReason,
57 block_ids: &[BlockId],
58 ) -> Result<Vec<ContextBlock>, ModelBlockError> {
59 match stop_reason {
60 ModelStopReason::EndTurn if !self.tool_calls.is_empty() => {
61 return Err(ModelBlockError::EndTurnWithToolCalls {
62 count: self.tool_calls.len(),
63 });
64 }
65 ModelStopReason::ToolUse if self.tool_calls.is_empty() => {
66 return Err(ModelBlockError::ToolUseWithoutToolCalls);
67 }
68 _ => {}
69 }
70 let expected = self.block_count();
71 if expected != block_ids.len() {
72 return Err(ModelBlockError::BlockIdCountMismatch {
73 expected,
74 actual: block_ids.len(),
75 });
76 }
77 for (tool_index, call) in self.tool_calls.iter().enumerate() {
78 if call.tool_name.trim().is_empty() {
79 return Err(ModelBlockError::EmptyToolName { tool_index });
80 }
81 if !call.arguments.is_object() {
82 return Err(ModelBlockError::ArgumentsNotObject { tool_index });
83 }
84 }
85 let mut ids = block_ids.iter().copied();
86 let mut blocks = Vec::with_capacity(expected);
87 if !self.text.0.trim().is_empty() {
88 blocks.push(ContextBlock::new(
89 ids.next().expect("identity count validated"),
90 BlockContent::Parts(vec![ContentPart::Text(self.text.clone())]),
91 BlockMeta::default(),
92 ));
93 }
94 for call in &self.tool_calls {
95 blocks.push(ContextBlock::new(
96 ids.next().expect("identity count validated"),
97 BlockContent::ToolCall(ToolCallPayload {
98 tool_name: call.tool_name.clone(),
99 arguments: call.arguments.clone(),
100 }),
101 BlockMeta {
102 provider_call_id: call.provider_call_id.clone(),
103 ..BlockMeta::default()
104 },
105 ));
106 }
107 Ok(blocks)
108 }
109}