lc_core/output_parsers/
str_parser.rs1use 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
9pub 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}