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/// String output parser
10///
11/// The simplest parser: returns the LLM output as a string verbatim.
12/// Equivalent to Python LangChain's `StrOutputParser`.
13///
14/// As a `Runnable` it receives an `LLMResult`, returns its `content` field unchanged,
15/// making `llm.pipe(StrOutputParser)` the tail of an LCEL chain.
16///
17/// # Example
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    /// Creates a string output parser.
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}