use serde::Deserialize;
use serde_json::{Value, json};
use super::{AgentIssue, Judgment, MAX_RESPONSE_BYTES, Priority, Verdict, bounded, bounded_result};
use crate::error::{Code, Failure};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Answer {
issues: Vec<AgentIssue>,
}
pub fn verdict(issues: &[AgentIssue], red_at: Option<Priority>) -> Verdict {
if issues
.iter()
.any(|issue| red_at.is_none_or(|bar| issue.priority <= bar))
{
Verdict::Red
} else {
Verdict::Green
}
}
pub(crate) struct Issues {
pub schema: Value,
red_at: Option<Priority>,
}
#[derive(Debug, thiserror::Error)]
#[error("{message}")]
pub(crate) struct ModelError {
message: &'static str,
detail: Option<String>,
}
impl From<&'static str> for ModelError {
fn from(message: &'static str) -> Self {
Self {
message,
detail: None,
}
}
}
impl Issues {
pub fn new(red_at: Option<Priority>) -> Self {
let priorities: Vec<_> = Priority::ALL.iter().map(|p| p.as_str()).collect();
Self {
schema: json!({
"type":"object",
"properties":{
"issues":{
"type":"array",
"description":"Every issue the review found; empty when there is none.",
"items":{
"type":"object",
"properties":{
"priority":{
"type":"string",
"enum":priorities,
"description":"P0 is the most important, P3 the least.",
},
"reason":{"type":"string"},
},
"required":["priority","reason"],
"additionalProperties":false,
},
},
},
"required":["issues"],
"additionalProperties":false,
}),
red_at,
}
}
pub fn parse_model(&self, text: &str) -> Result<Judgment, ModelError> {
if text.len() > MAX_RESPONSE_BYTES {
return Err("over_size: final JSON exceeds 1 MiB".into());
}
if text.trim().is_empty() {
return Err("empty: return one JSON object".into());
}
let value: Value = serde_json::from_str(text).map_err(
|_| "not_json: return exactly one JSON object, without prose or code fences",
)?;
let answer = Answer::deserialize(&value).map_err(|error| ModelError {
message: "schema_mismatch: result must be an object with an issues list, each issue a priority P0 to P3 and a reason",
detail: Some(bounded(error.to_string())),
})?;
if answer
.issues
.iter()
.any(|issue| issue.reason.trim().is_empty())
{
return Err("schema_mismatch: every issue needs a reason".into());
}
bounded_result(&value)?;
Ok(Judgment {
verdict: verdict(&answer.issues, self.red_at),
issues: answer.issues,
})
}
pub fn repair_prompt(error: ModelError) -> String {
format!(
"Your final response did not match the required schema: {}\nReturn only one JSON object matching the schema.",
Self::repair_detail(error),
)
}
pub fn repair_failed(error: ModelError) -> Failure {
Failure::new(
Code::InvalidResult,
format!("Invalid final Agent result after one format repair: {error}."),
)
}
pub fn repair_tools_disabled() -> Failure {
Failure::new(
Code::InvalidResult,
"Invalid final Agent result after one format repair: tools are disabled.",
)
}
pub fn repair_detail(error: ModelError) -> String {
match error.detail {
Some(detail) => format!("{}\n- {detail}", error.message),
None => error.message.into(),
}
}
}
#[cfg(test)]
mod tests;