Skip to content

Commit 019fbea

Browse files
committed
feat: add early JSON validation for tool call arguments
1 parent d201070 commit 019fbea

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/cortex-engine/src/streaming.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,18 @@ impl StreamContent {
143143
}
144144
}
145145

146+
/// Complete a tool call and validate its arguments.
147+
/// Returns Ok(()) if the tool call was found and arguments are valid JSON.
148+
/// Returns Err if tool call not found or arguments are invalid JSON.
149+
pub fn complete_tool_call_validated(&mut self, id: &str) -> Result<(), String> {
150+
if let Some(tc) = self.tool_calls.iter_mut().find(|tc| tc.id == id) {
151+
tc.complete = true;
152+
tc.validate_arguments()
153+
} else {
154+
Err(format!("Tool call with id '{}' not found", id))
155+
}
156+
}
157+
146158
/// Check if has content.
147159
pub fn has_content(&self) -> bool {
148160
!self.text.is_empty() || !self.tool_calls.is_empty()
@@ -171,6 +183,23 @@ impl StreamToolCall {
171183
None
172184
}
173185
}
186+
187+
/// Validate that arguments contain valid JSON.
188+
/// Returns Ok(()) if valid, Err with details if invalid.
189+
pub fn validate_arguments(&self) -> Result<(), String> {
190+
if self.arguments.trim().is_empty() {
191+
return Ok(()); // Empty is valid (no arguments)
192+
}
193+
serde_json::from_str::<serde_json::Value>(&self.arguments)
194+
.map(|_| ())
195+
.map_err(|e| format!("Invalid JSON in tool call arguments: {}", e))
196+
}
197+
198+
/// Check if arguments are complete and valid JSON.
199+
/// Returns true only if complete and valid.
200+
pub fn is_valid_complete(&self) -> bool {
201+
self.complete && self.validate_arguments().is_ok()
202+
}
174203
}
175204

176205
/// Token counts.

0 commit comments

Comments
 (0)