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    EndTurnWithToolCalls {
14        /// Number of tool declarations in the response.
15        count: usize,
16    },
17    /// ToolUse requires at least one tool declaration.
18    #[error("ToolUse has no tool calls")]
19    ToolUseWithoutToolCalls,
20    /// The supplied identities do not match the response's material count.
21    #[error("expected {expected} block ids, received {actual}")]
22    BlockIdCountMismatch {
23        /// Number of identities required by the response.
24        expected: usize,
25        /// Number of supplied identities.
26        actual: usize,
27    },
28    /// A tool declaration's name is blank.
29    #[error("tool {tool_index} has an empty name")]
30    EmptyToolName {
31        /// Zero-based index in the response's tool declarations.
32        tool_index: usize,
33    },
34    /// A tool declaration's arguments are not a JSON object.
35    #[error("tool {tool_index} arguments are not an object")]
36    ArgumentsNotObject {
37        /// Zero-based index in the response's tool declarations.
38        tool_index: usize,
39    },
40}
41
42impl ModelResponse {
43    /// Counts the blocks `to_blocks` produces: one per item, except that a
44    /// `Parts` item whose parts are all zero-length text produces none.
45    pub fn block_count(&self) -> usize {
46        self.items
47            .iter()
48            .filter(|item| match &item.content {
49                ModelItemContent::Parts(parts) => parts.iter().any(keeps_part),
50                ModelItemContent::ToolCall(_) => true,
51            })
52            .count()
53    }
54
55    /// Validates and constructs material without changing or consuming inputs.
56    ///
57    /// One item becomes one block, in item order. A `Parts` item becomes a
58    /// `Parts` block and a tool-call item a `ToolCall` block carrying its
59    /// provider identifier. An item's `wire` is copied to the block's
60    /// [`BlockMeta::wire`]. Only zero-length text parts are omitted
61    /// (whitespace-only text is kept verbatim); a `Parts` item left with no
62    /// parts produces no block and its `wire` is dropped. The kernel never
63    /// reads `wire` or sealed items. Duplicate block identities are checked
64    /// on context submission rather than here. MaxTokens and Refusal policy
65    /// belongs to the caller.
66    pub fn to_blocks(
67        &self,
68        stop_reason: ModelStopReason,
69        block_ids: &[BlockId],
70    ) -> Result<Vec<ContextBlock>, ModelBlockError> {
71        let tool_count = self.tool_calls().count();
72        match stop_reason {
73            ModelStopReason::EndTurn if tool_count > 0 => {
74                return Err(ModelBlockError::EndTurnWithToolCalls { count: tool_count });
75            }
76            ModelStopReason::ToolUse if tool_count == 0 => {
77                return Err(ModelBlockError::ToolUseWithoutToolCalls);
78            }
79            // The runner commits only for EndTurn and ToolUse; the other four
80            // reasons are interruptions, so conversion applies no policy.
81            ModelStopReason::EndTurn
82            | ModelStopReason::ToolUse
83            | ModelStopReason::MaxTokens
84            | ModelStopReason::Refusal
85            | ModelStopReason::ContextWindowExceeded
86            | ModelStopReason::Unrecognized => {}
87        }
88        let expected = self.block_count();
89        if expected != block_ids.len() {
90            return Err(ModelBlockError::BlockIdCountMismatch {
91                expected,
92                actual: block_ids.len(),
93            });
94        }
95        for (tool_index, call) in self.tool_calls().enumerate() {
96            if call.tool_name.trim().is_empty() {
97                return Err(ModelBlockError::EmptyToolName { tool_index });
98            }
99            if !call.arguments.is_object() {
100                return Err(ModelBlockError::ArgumentsNotObject { tool_index });
101            }
102        }
103        let mut ids = block_ids.iter().copied();
104        let mut blocks = Vec::with_capacity(expected);
105        for item in &self.items {
106            match &item.content {
107                ModelItemContent::Parts(parts) => {
108                    let parts: Vec<ContentPart> =
109                        parts.iter().filter(|p| keeps_part(p)).cloned().collect();
110                    if parts.is_empty() {
111                        continue;
112                    }
113                    blocks.push(ContextBlock::new(
114                        ids.next().expect("identity count validated"),
115                        BlockContent::Parts(parts),
116                        BlockMeta {
117                            wire: item.wire.clone(),
118                            ..BlockMeta::default()
119                        },
120                    ));
121                }
122                ModelItemContent::ToolCall(call) => {
123                    blocks.push(ContextBlock::new(
124                        ids.next().expect("identity count validated"),
125                        BlockContent::ToolCall(ToolCallPayload {
126                            tool_name: call.tool_name.clone(),
127                            arguments: call.arguments.clone(),
128                        }),
129                        BlockMeta {
130                            provider_call_id: call.provider_call_id.clone(),
131                            wire: item.wire.clone(),
132                            ..BlockMeta::default()
133                        },
134                    ));
135                }
136            }
137        }
138        Ok(blocks)
139    }
140}
141
142/// Whether a part from a `Parts` item survives conversion: only text of zero
143/// length is dropped.
144fn keeps_part(part: &ContentPart) -> bool {
145    !matches!(part, ContentPart::Text(t) if t.0.is_empty())
146}