agent_chain_core/output_parsers/
string.rs

1//! String output parser.
2//!
3//! This module contains the `StrOutputParser` which extracts text content
4//! from model outputs as a string.
5//! Mirrors `langchain_core.output_parsers.string`.
6
7use std::fmt::Debug;
8
9use crate::error::Result;
10use crate::load::{Serializable, Serialized, SerializedConstructor};
11use crate::outputs::Generation;
12
13use super::base::BaseOutputParser;
14use super::transform::BaseTransformOutputParser;
15
16/// Extract text content from model outputs as a string.
17///
18/// Converts model outputs (such as `AIMessage` or `AIMessageChunk` objects)
19/// into plain text strings. It's the simplest output parser and is useful
20/// when you need string responses for downstream processing, display, or storage.
21///
22/// Supports streaming, yielding text chunks as they're generated by the model.
23///
24/// # Example
25///
26/// ```ignore
27/// use agent_chain_core::output_parsers::StrOutputParser;
28///
29/// let parser = StrOutputParser::new();
30///
31/// // Parse a simple string
32/// let result = parser.parse("Hello, world!").unwrap();
33/// assert_eq!(result, "Hello, world!");
34/// ```
35#[derive(Debug, Clone, Default)]
36pub struct StrOutputParser {
37    _private: (),
38}
39
40impl StrOutputParser {
41    /// Create a new `StrOutputParser`.
42    pub fn new() -> Self {
43        Self { _private: () }
44    }
45
46    /// Returns `true` as this class is serializable.
47    pub fn is_lc_serializable() -> bool {
48        true
49    }
50
51    /// Get the namespace of the LangChain object.
52    ///
53    /// Returns `["langchain", "schema", "output_parser"]`
54    pub fn get_lc_namespace() -> Vec<&'static str> {
55        vec!["langchain", "schema", "output_parser"]
56    }
57}
58
59impl BaseOutputParser for StrOutputParser {
60    type Output = String;
61
62    /// Returns the input text with no changes.
63    fn parse(&self, text: &str) -> Result<String> {
64        Ok(text.to_string())
65    }
66
67    /// Return the output parser type for serialization.
68    fn parser_type(&self) -> &str {
69        "default"
70    }
71}
72
73impl BaseTransformOutputParser for StrOutputParser {
74    fn parse_generation(&self, generation: &Generation) -> Result<Self::Output> {
75        Ok(generation.text.clone())
76    }
77}
78
79impl Serializable for StrOutputParser {
80    fn is_lc_serializable() -> bool
81    where
82        Self: Sized,
83    {
84        true
85    }
86
87    fn get_lc_namespace() -> Vec<String>
88    where
89        Self: Sized,
90    {
91        vec![
92            "langchain".to_string(),
93            "schema".to_string(),
94            "output_parser".to_string(),
95        ]
96    }
97
98    fn to_json(&self) -> Serialized
99    where
100        Self: Sized + serde::Serialize,
101    {
102        SerializedConstructor::new(Self::lc_id(), std::collections::HashMap::new()).into()
103    }
104}
105
106impl serde::Serialize for StrOutputParser {
107    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
108    where
109        S: serde::Serializer,
110    {
111        use serde::ser::SerializeStruct;
112        let s = serializer.serialize_struct("StrOutputParser", 0)?;
113        s.end()
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn test_str_output_parser() {
123        let parser = StrOutputParser::new();
124        let result = parser.parse("Hello, world!").unwrap();
125        assert_eq!(result, "Hello, world!");
126    }
127
128    #[test]
129    fn test_str_output_parser_empty() {
130        let parser = StrOutputParser::new();
131        let result = parser.parse("").unwrap();
132        assert_eq!(result, "");
133    }
134
135    #[test]
136    fn test_str_output_parser_multiline() {
137        let parser = StrOutputParser::new();
138        let result = parser.parse("line1\nline2\nline3").unwrap();
139        assert_eq!(result, "line1\nline2\nline3");
140    }
141
142    #[test]
143    fn test_parser_type() {
144        let parser = StrOutputParser::new();
145        assert_eq!(parser.parser_type(), "default");
146    }
147}