agent_chain_core/output_parsers/
string.rs1use 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#[derive(Debug, Clone, Default)]
36pub struct StrOutputParser {
37 _private: (),
38}
39
40impl StrOutputParser {
41 pub fn new() -> Self {
43 Self { _private: () }
44 }
45
46 pub fn is_lc_serializable() -> bool {
48 true
49 }
50
51 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 fn parse(&self, text: &str) -> Result<String> {
64 Ok(text.to_string())
65 }
66
67 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}