Skip to main content

lc_core/output_parsers/
base.rs

1use async_trait::async_trait;
2
3/// 输出解析器的统一错误类型
4#[derive(Debug, Clone, thiserror::Error)]
5pub enum OutputParserError {
6    /// 解析失败:输入格式不符合预期
7    #[error("Parse error: {0}")]
8    ParseError(String),
9    /// JSON 格式错误
10    #[error("JSON error: {0}")]
11    JsonError(String),
12    /// 类型转换错误
13    #[error("Type error: {0}")]
14    TypeError(String),
15    /// 自定义错误
16    #[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
26/// 输出解析器的结果类型
27pub type OutputParserResult<T> = Result<T, OutputParserError>;
28
29/// 输出解析器的核心 trait
30///
31/// 所有输出解析器必须实现此 trait。
32/// 与 `Runnable` 不同,`parse` 不接收 config 参数,
33/// 适合在 Runnable 内部调用。
34#[async_trait]
35pub trait BaseOutputParser<Output: Send + Sync + 'static>: Send + Sync {
36    /// 将原始 LLM 输出文本解析为目标类型
37    async fn parse(&self, text: &str) -> OutputParserResult<Output>;
38
39    /// 带重试的解析(默认实现:不重试)
40    async fn parse_with_retry(
41        &self,
42        text: &str,
43        _max_retries: usize,
44    ) -> OutputParserResult<Output> {
45        self.parse(text).await
46    }
47
48    /// 获取格式指令(用于提示 LLM 按指定格式输出)
49    fn get_format_instructions(&self) -> String {
50        String::new()
51    }
52}