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