Skip to main content

causa_kernel/context/model/
conversion.rs

1//! Pure model response validation and block construction.
2
3use super::{ModelResponse, ModelStopReason};
4use crate::context::block::{BlockContent, BlockMeta, ContentPart, ContextBlock, ToolCallPayload};
5use crate::context::ids::BlockId;
6
7/// Why a model response cannot be converted into blocks.
8#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9pub enum ModelBlockError {
10    /// EndTurn cannot include tool declarations.
11    #[error("EndTurn includes {count} tool calls")]
12    EndTurnWithToolCalls {
13        /// Number of tool declarations in the response.
14        count: usize,
15    },
16    /// ToolUse requires at least one tool declaration.
17    #[error("ToolUse has no tool calls")]
18    ToolUseWithoutToolCalls,
19    /// The supplied identities do not match the response's material count.
20    #[error("expected {expected} block ids, received {actual}")]
21    BlockIdCountMismatch {
22        /// Number of identities required by the response.
23        expected: usize,
24        /// Number of supplied identities.
25        actual: usize,
26    },
27    /// A tool declaration's name is blank.
28    #[error("tool {tool_index} has an empty name")]
29    EmptyToolName {
30        /// Zero-based index in the response's tool declarations.
31        tool_index: usize,
32    },
33    /// A tool declaration's arguments are not a JSON object.
34    #[error("tool {tool_index} arguments are not an object")]
35    ArgumentsNotObject {
36        /// Zero-based index in the response's tool declarations.
37        tool_index: usize,
38    },
39}
40
41impl ModelResponse {
42    /// Counts one block for nonblank text, plus one per tool declaration.
43    pub fn block_count(&self) -> usize {
44        usize::from(!self.text.0.trim().is_empty()) + self.tool_calls.len()
45    }
46
47    /// Validates and constructs material without changing or consuming inputs.
48    ///
49    /// Text precedes declarations, which retain their original order, arguments,
50    /// names and provider identifiers. Blank text is omitted; other text is
51    /// preserved verbatim. Duplicate block identities are checked on context
52    /// submission rather than here. MaxTokens and Refusal policy belongs to the
53    /// caller.
54    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}