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 {
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}