use std::fmt;
use serde_json::Value;
use crate::error::VldError;
use crate::schema::{VldParse, VldSchema};
use super::LlmFeedbackOptions;
#[derive(Debug, Clone)]
pub enum LlmParseError {
NoJson,
Invalid(VldError),
}
impl LlmParseError {
pub fn llm_feedback(&self) -> String {
self.llm_feedback_with(&LlmFeedbackOptions::default())
}
pub fn llm_feedback_with(&self, options: &LlmFeedbackOptions) -> String {
match self {
Self::Invalid(e) => e.llm_feedback_with(options),
Self::NoJson if options.retry_prompt => {
"Your previous output contained no JSON. Return the JSON only.".into()
}
Self::NoJson => "no JSON object or array found".into(),
}
}
}
impl fmt::Display for LlmParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoJson => f.write_str("no JSON object or array found in the reply"),
Self::Invalid(e) => e.fmt(f),
}
}
}
impl std::error::Error for LlmParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::NoJson => None,
Self::Invalid(e) => Some(e),
}
}
}
impl From<VldError> for LlmParseError {
fn from(e: VldError) -> Self {
Self::Invalid(e)
}
}
pub fn extract_json(text: &str) -> Option<Value> {
let mut rest = text;
while let Some(start) = rest.find("```") {
let after = &rest[start + 3..];
let body_start = after.find('\n').map_or(0, |i| i + 1);
let Some(len) = after[body_start..].find("```") else {
break;
};
if let Some(v) = first_value(&after[body_start..body_start + len]) {
return Some(v);
}
rest = &after[body_start + len + 3..];
}
first_value(text)
}
fn first_value(s: &str) -> Option<Value> {
let mut first_array = None;
let mut i = 0;
while let Some(off) = s[i..].find(['{', '[']) {
let start = i + off;
let parsed = balanced_end(&s[start..]).and_then(|end| {
let v: Value = serde_json::from_str(&s[start..start + end]).ok()?;
Some((v, end))
});
match parsed {
Some((v @ Value::Object(_), _)) => return Some(v),
Some((v, end)) => {
first_array.get_or_insert(v);
i = start + end;
}
None => i = start + 1,
}
}
first_array
}
fn balanced_end(s: &str) -> Option<usize> {
let (mut depth, mut in_str, mut escaped) = (0usize, false, false);
for (i, b) in s.bytes().enumerate() {
if in_str {
match b {
_ if escaped => escaped = false,
b'\\' => escaped = true,
b'"' => in_str = false,
_ => {}
}
continue;
}
match b {
b'"' => in_str = true,
b'{' | b'[' => depth += 1,
b'}' | b']' => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(i + 1);
}
}
_ => {}
}
}
None
}
pub fn parse_llm<T: VldParse>(text: &str) -> Result<T, LlmParseError> {
let value = extract_json(text).ok_or(LlmParseError::NoJson)?;
Ok(T::vld_parse_value(&value)?)
}
pub fn parse_llm_with<S: VldSchema>(schema: &S, text: &str) -> Result<S::Output, LlmParseError> {
let value = extract_json(text).ok_or(LlmParseError::NoJson)?;
Ok(schema.parse_value(&value)?)
}