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