lc_core/output_parsers/
base.rs1use async_trait::async_trait;
2
3#[derive(Debug, Clone, thiserror::Error)]
5pub enum OutputParserError {
6 #[error("Parse error: {0}")]
8 ParseError(String),
9 #[error("JSON error: {0}")]
11 JsonError(String),
12 #[error("Type error: {0}")]
14 TypeError(String),
15 #[error("{0}")]
17 Custom(String),
18}
19
20impl From<serde_json::Error> for OutputParserError {
21 fn from(e: serde_json::Error) -> Self {
22 OutputParserError::JsonError(e.to_string())
23 }
24}
25
26pub type OutputParserResult<T> = Result<T, OutputParserError>;
28
29#[async_trait]
35pub trait BaseOutputParser<Output: Send + Sync + 'static>: Send + Sync {
36 async fn parse(&self, text: &str) -> OutputParserResult<Output>;
38
39 async fn parse_with_retry(&self, text: &str, max_retries: usize) -> OutputParserResult<Output> {
47 let mut last_err = None;
48 for _ in 0..=max_retries {
49 match self.parse(text).await {
50 Ok(output) => return Ok(output),
51 Err(e) => last_err = Some(e),
52 }
53 }
54 Err(last_err.unwrap_or_else(|| {
55 OutputParserError::ParseError("parse_with_retry made no parse attempts".to_string())
56 }))
57 }
58
59 fn get_format_instructions(&self) -> String {
61 String::new()
62 }
63}