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