Skip to main content

lc_core/output_parsers/
base.rs

1use async_trait::async_trait;
2
3/// 输出解析器的统一错误类型
4#[derive(Debug, Clone, thiserror::Error)]
5#[non_exhaustive]
6pub enum OutputParserError {
7    /// 解析失败:输入格式不符合预期
8    #[error("Parse error: {0}")]
9    ParseError(String),
10    /// JSON 格式错误
11    #[error("JSON error: {0}")]
12    JsonError(String),
13    /// 类型转换错误
14    #[error("Type error: {0}")]
15    TypeError(String),
16    /// 自定义错误
17    #[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
27/// 输出解析器的结果类型
28pub type OutputParserResult<T> = Result<T, OutputParserError>;
29
30/// 输出解析器的核心 trait
31///
32/// 所有输出解析器必须实现此 trait。
33/// 与 `Runnable` 不同,`parse` 不接收 config 参数,
34/// 适合在 Runnable 内部调用。
35#[async_trait]
36pub trait BaseOutputParser<Output: Send + Sync + 'static>: Send + Sync {
37    /// 将原始 LLM 输出文本解析为目标类型
38    async fn parse(&self, text: &str) -> OutputParserResult<Output>;
39
40    /// 带重试的解析(默认实现:真正重试 `max_retries` 次)
41    ///
42    /// 对同一份文本反复调用 [`parse`](Self::parse),最多尝试
43    /// `max_retries + 1` 次。重试同一份文本只对非确定性解析(例如内部
44    /// 依赖网络/外部服务的解析器)有意义;确定性解析器首次失败后必然
45    /// 重复失败,最终返回最后一次错误。需要基于失败原因修正输入的
46    /// 解析器应覆写此方法。
47    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    /// 获取格式指令(用于提示 LLM 按指定格式输出)
61    fn get_format_instructions(&self) -> String {
62        String::new()
63    }
64}