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    /// 创建字符串输出解析器。
29    pub fn new() -> Self {
30        Self
31    }
32}
33
34impl Default for StrOutputParser {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40#[async_trait]
41impl BaseOutputParser<String> for StrOutputParser {
42    async fn parse(&self, text: &str) -> OutputParserResult<String> {
43        Ok(text.to_string())
44    }
45}
46
47#[async_trait]
48impl Runnable<LLMResult, String> for StrOutputParser {
49    type Error = OutputParserError;
50
51    async fn invoke(
52        &self,
53        input: LLMResult,
54        _config: Option<RunnableConfig>,
55    ) -> Result<String, Self::Error> {
56        self.parse(&input.content).await
57    }
58
59    async fn stream(
60        &self,
61        input: LLMResult,
62        _config: Option<RunnableConfig>,
63    ) -> Result<Pin<Box<dyn Stream<Item = Result<String, Self::Error>> + Send>>, Self::Error> {
64        let result = self.parse(&input.content).await?;
65        let stream = futures_util::stream::once(async move { Ok(result) });
66        Ok(Box::pin(stream))
67    }
68}