Skip to main content

lc_core/output_parsers/
str_parser.rs

1use async_trait::async_trait;
2use futures_util::Stream;
3use std::pin::Pin;
4
5use super::base::{BaseOutputParser, OutputParserError, OutputParserResult};
6use crate::language_models::LLMResult;
7use crate::runnables::{Runnable, RunnableConfig};
8
9/// 字符串输出解析器
10///
11/// 最简单的解析器,直接将 LLM 输出作为字符串返回。
12/// 相当于 Python LangChain 的 `StrOutputParser`。
13///
14/// 作为 `Runnable` 时接收 `LLMResult`,取其 `content` 字段后原样返回,
15/// 使 `llm.pipe(StrOutputParser)` 成为 LCEL 链的尾段。
16///
17/// # 示例
18/// ```ignore
19/// use langchainrust::output_parsers::StrOutputParser;
20///
21/// let parser = StrOutputParser::new();
22/// let result = parser.parse("Hello, world!").await?;
23/// assert_eq!(result, "Hello, world!");
24/// ```
25pub struct StrOutputParser;
26
27impl StrOutputParser {
28    pub fn new() -> Self {
29        Self
30    }
31}
32
33impl Default for StrOutputParser {
34    fn default() -> Self {
35        Self::new()
36    }
37}
38
39#[async_trait]
40impl BaseOutputParser<String> for StrOutputParser {
41    async fn parse(&self, text: &str) -> OutputParserResult<String> {
42        Ok(text.to_string())
43    }
44}
45
46#[async_trait]
47impl Runnable<LLMResult, String> for StrOutputParser {
48    type Error = OutputParserError;
49
50    async fn invoke(
51        &self,
52        input: LLMResult,
53        _config: Option<RunnableConfig>,
54    ) -> Result<String, Self::Error> {
55        self.parse(&input.content).await
56    }
57
58    async fn stream(
59        &self,
60        input: LLMResult,
61        _config: Option<RunnableConfig>,
62    ) -> Result<Pin<Box<dyn Stream<Item = Result<String, Self::Error>> + Send>>, Self::Error> {
63        let result = self.parse(&input.content).await?;
64        let stream = futures_util::stream::once(async move { Ok(result) });
65        Ok(Box::pin(stream))
66    }
67}