Skip to main content

langsmith_rust/strategies/
serialization_strategy.rs

1use serde::Serialize;
2use serde_json::Value;
3
4/// Strategy for serialization approaches
5pub trait SerializationStrategy: Send + Sync {
6    /// Serialize inputs ensuring they're always an object
7    fn serialize_inputs<T: Serialize>(&self, value: &T) -> Result<Value, serde_json::Error>;
8    
9    /// Serialize outputs ensuring they're always an object
10    fn serialize_outputs<T: Serialize>(&self, value: &T) -> Result<Value, serde_json::Error>;
11}
12
13/// Default serialization strategy (wraps primitives in objects)
14pub struct DefaultSerializationStrategy {
15    input_key: String,
16    output_key: String,
17}
18
19impl DefaultSerializationStrategy {
20    pub fn new() -> Self {
21        Self {
22            input_key: "input".to_string(),
23            output_key: "output".to_string(),
24        }
25    }
26
27    pub fn with_keys(input_key: String, output_key: String) -> Self {
28        Self {
29            input_key,
30            output_key,
31        }
32    }
33}
34
35impl Default for DefaultSerializationStrategy {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl SerializationStrategy for DefaultSerializationStrategy {
42    fn serialize_inputs<T: Serialize>(&self, value: &T) -> Result<Value, serde_json::Error> {
43        let mut json_value = serde_json::to_value(value)?;
44        if !json_value.is_object() {
45            let key = self.input_key.clone();
46            json_value = serde_json::json!({ key: json_value });
47        }
48        Ok(json_value)
49    }
50
51    fn serialize_outputs<T: Serialize>(&self, value: &T) -> Result<Value, serde_json::Error> {
52        let mut json_value = serde_json::to_value(value)?;
53        if !json_value.is_object() {
54            let key = self.output_key.clone();
55            json_value = serde_json::json!({ key: json_value });
56        }
57        Ok(json_value)
58    }
59}
60