use crate::error::AgentError;
use crate::types::{BlockAssistantMessage, Message, RunResult, UserMessage};
use jsonschema::Validator;
use serde_json::{Value, json};
use super::{Agent, AgentLlmClient, AgentSessionStore, AgentToolDispatcher};
impl<C, T, S> Agent<C, T, S>
where
C: AgentLlmClient + ?Sized + 'static,
T: AgentToolDispatcher + ?Sized + 'static,
S: AgentSessionStore + ?Sized + 'static,
{
pub(super) async fn perform_extraction_turn(
&mut self,
turn_count: u32,
tool_call_count: u32,
) -> Result<RunResult, AgentError> {
let output_schema = self.config.output_schema.as_ref().ok_or_else(|| {
AgentError::InternalError("perform_extraction_turn called without output_schema".into())
})?;
let compiled = self
.client
.compile_schema(output_schema)
.map_err(|e| AgentError::InvalidOutputSchema(e.to_string()))?;
let validator = Validator::new(&compiled.schema)
.map_err(|e| AgentError::InvalidOutputSchema(e.to_string()))?;
let max_attempts = self.config.structured_output_retries + 1;
let mut last_error = String::new();
let schema_warnings = if compiled.warnings.is_empty() {
None
} else {
Some(compiled.warnings.clone())
};
for attempt in 0..max_attempts {
let prompt = if attempt == 0 {
"Based on our conversation, provide the final output as valid JSON matching the required schema. Output ONLY the JSON, no additional text or markdown formatting.".to_string()
} else {
format!(
"The previous output was invalid: {}. Please provide valid JSON matching the schema. Output ONLY the JSON, no additional text.",
last_error
)
};
self.session
.push(Message::User(UserMessage { content: prompt }));
let mut params = self
.config
.provider_params
.clone()
.unwrap_or_else(|| json!({}));
if let Some(obj) = params.as_object_mut() {
obj.insert("structured_output".to_string(), output_schema.to_value());
}
let result = self
.client
.stream_response(
self.session.messages(),
&[], self.config.max_tokens_per_turn,
Some(0.0), Some(¶ms),
)
.await?;
self.budget.record_usage(&result.usage);
self.session.record_usage(result.usage.clone());
let (blocks, stop_reason, _usage) = result.into_parts();
let assistant_msg = BlockAssistantMessage {
blocks,
stop_reason,
};
let content = assistant_msg.to_string();
self.session.push(Message::BlockAssistant(assistant_msg));
let content = content.trim();
let json_content = strip_code_fences(content);
match serde_json::from_str::<Value>(json_content) {
Ok(parsed) => {
match validator.validate(&parsed) {
Ok(()) => {
return Ok(RunResult {
text: self.session.last_assistant_text().unwrap_or_default(),
session_id: self.session.id().clone(),
usage: self.session.total_usage(),
turns: turn_count + 1 + attempt + 1, tool_calls: tool_call_count,
structured_output: Some(parsed),
schema_warnings: schema_warnings.clone(),
skill_diagnostics: None,
});
}
Err(error) => {
last_error = format!("Schema validation failed: {}", error);
}
}
}
Err(e) => {
last_error = format!("Invalid JSON: {}", e);
}
}
}
Err(AgentError::StructuredOutputValidationFailed {
attempts: max_attempts,
reason: last_error,
last_output: self.session.last_assistant_text().unwrap_or_default(),
})
}
}
fn strip_code_fences(content: &str) -> &str {
let trimmed = content.trim();
let without_prefix = if let Some(stripped) = trimmed.strip_prefix("```json") {
stripped
} else if let Some(stripped) = trimmed.strip_prefix("```") {
stripped
} else {
return trimmed;
};
let without_suffix = without_prefix.trim();
if let Some(stripped) = without_suffix.strip_suffix("```") {
stripped.trim()
} else {
without_suffix.trim()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_strip_code_fences_no_fences() {
assert_eq!(
strip_code_fences(r#"{"name": "test"}"#),
r#"{"name": "test"}"#
);
}
#[test]
fn test_strip_code_fences_json_fence() {
let input = r#"```json
{"name": "test"}
```"#;
assert_eq!(strip_code_fences(input), r#"{"name": "test"}"#);
}
#[test]
fn test_strip_code_fences_plain_fence() {
let input = r#"```
{"name": "test"}
```"#;
assert_eq!(strip_code_fences(input), r#"{"name": "test"}"#);
}
#[test]
fn test_strip_code_fences_with_whitespace() {
let input = r#"
```json
{"name": "test"}
```
"#;
assert_eq!(strip_code_fences(input), r#"{"name": "test"}"#);
}
}