Skip to main content

causa_kernel/context/model/
conversion.rs

1//! Pure model response validation and block construction.
2
3use super::{ModelItemContent, 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)]
9#[non_exhaustive]
10pub enum ModelBlockError {
11    /// EndTurn cannot include tool declarations.
12    #[error("EndTurn includes {count} tool calls")]
13    #[non_exhaustive]
14    EndTurnWithToolCalls {
15        /// Number of tool declarations in the response.
16        count: usize,
17    },
18    /// ToolUse requires at least one tool declaration.
19    #[error("ToolUse has no tool calls")]
20    ToolUseWithoutToolCalls,
21    /// The supplied identities do not match the response's material count.
22    #[error("expected {expected} block ids, received {actual}")]
23    #[non_exhaustive]
24    BlockIdCountMismatch {
25        /// Number of identities required by the response.
26        expected: usize,
27        /// Number of supplied identities.
28        actual: usize,
29    },
30    /// A tool declaration's name is blank.
31    #[error("tool {tool_index} has an empty name")]
32    #[non_exhaustive]
33    EmptyToolName {
34        /// Zero-based index in the response's tool declarations.
35        tool_index: usize,
36    },
37    /// A tool declaration's arguments are not a JSON object.
38    #[error("tool {tool_index} arguments are not an object")]
39    #[non_exhaustive]
40    ArgumentsNotObject {
41        /// Zero-based index in the response's tool declarations.
42        tool_index: usize,
43    },
44}
45
46impl ModelResponse {
47    /// Counts the blocks `to_blocks` produces: one per item, except that a
48    /// `Parts` item whose parts are all zero-length text produces none.
49    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    /// Validates and constructs material without changing or consuming inputs.
60    ///
61    /// One item becomes one block, in item order. A `Parts` item becomes a
62    /// `Parts` block and a tool-call item a `ToolCall` block carrying its
63    /// provider identifier. An item's `wire` is copied to the block's
64    /// [`BlockMeta::wire`]. Only zero-length text parts are omitted
65    /// (whitespace-only text is kept verbatim); a `Parts` item left with no
66    /// parts produces no block and its `wire` is dropped. The kernel never
67    /// reads `wire` or sealed items. Duplicate block identities are checked
68    /// on context submission rather than here. MaxTokens and Refusal policy
69    /// belongs to the caller.
70    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            // The runner commits only for EndTurn and ToolUse; the other four
84            // reasons are interruptions, so conversion applies no policy.
85            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
146/// Whether a part from a `Parts` item survives conversion: only text of zero
147/// length is dropped.
148fn keeps_part(part: &ContentPart) -> bool {
149    !matches!(part, ContentPart::Text(t) if t.0.is_empty())
150}