Skip to main content

modular_agent_core/
value.rs

1use std::sync::Arc;
2
3#[cfg(feature = "image")]
4use photon_rs::PhotonImage;
5
6use im::{HashMap, Vector};
7use serde::{
8    Deserialize, Deserializer, Serialize, Serializer,
9    ser::{SerializeMap, SerializeSeq},
10};
11
12use crate::error::AgentError;
13use crate::llm::Message;
14
15#[cfg(feature = "image")]
16const IMAGE_BASE64_PREFIX: &str = "data:image/png;base64,";
17
18#[derive(Debug, Clone)]
19pub enum AgentValue {
20    // Primitive types stored directly
21    Unit,
22    Boolean(bool),
23    Integer(i64),
24    Number(f64),
25
26    // Larger data structures use reference counting
27    String(Arc<String>),
28
29    #[cfg(feature = "image")]
30    Image(Arc<PhotonImage>),
31
32    // Recursive data structures
33    Array(Vector<AgentValue>),
34    Object(HashMap<String, AgentValue>),
35
36    // Tensor Data (Embeddings, etc.)
37    Tensor(Arc<Vec<f32>>),
38
39    // LLM Message
40    Message(Arc<Message>),
41
42    // Error
43    // special type to represent errors
44    Error(Arc<AgentError>),
45}
46
47pub type AgentValueMap<S, T> = HashMap<S, T>;
48
49impl AgentValue {
50    pub fn unit() -> Self {
51        AgentValue::Unit
52    }
53
54    pub fn boolean(value: bool) -> Self {
55        AgentValue::Boolean(value)
56    }
57
58    pub fn integer(value: i64) -> Self {
59        AgentValue::Integer(value)
60    }
61
62    pub fn number(value: f64) -> Self {
63        AgentValue::Number(value)
64    }
65
66    pub fn string(value: impl Into<String>) -> Self {
67        AgentValue::String(Arc::new(value.into()))
68    }
69
70    #[cfg(feature = "image")]
71    pub fn image(value: PhotonImage) -> Self {
72        AgentValue::Image(Arc::new(value))
73    }
74
75    #[cfg(feature = "image")]
76    pub fn image_arc(value: Arc<PhotonImage>) -> Self {
77        AgentValue::Image(value)
78    }
79
80    pub fn array(value: Vector<AgentValue>) -> Self {
81        AgentValue::Array(value)
82    }
83
84    pub fn object(value: AgentValueMap<String, AgentValue>) -> Self {
85        AgentValue::Object(value)
86    }
87
88    pub fn tensor(value: Vec<f32>) -> Self {
89        AgentValue::Tensor(Arc::new(value))
90    }
91
92    pub fn message(value: Message) -> Self {
93        AgentValue::Message(Arc::new(value))
94    }
95
96    pub fn boolean_default() -> Self {
97        AgentValue::Boolean(false)
98    }
99
100    pub fn integer_default() -> Self {
101        AgentValue::Integer(0)
102    }
103
104    pub fn number_default() -> Self {
105        AgentValue::Number(0.0)
106    }
107
108    pub fn string_default() -> Self {
109        AgentValue::String(Arc::new(String::new()))
110    }
111
112    #[cfg(feature = "image")]
113    pub fn image_default() -> Self {
114        AgentValue::Image(Arc::new(PhotonImage::new(vec![0u8, 0u8, 0u8, 0u8], 1, 1)))
115    }
116
117    pub fn array_default() -> Self {
118        AgentValue::Array(Vector::new())
119    }
120
121    pub fn object_default() -> Self {
122        AgentValue::Object(HashMap::new())
123    }
124
125    pub fn tensor_default() -> Self {
126        AgentValue::Tensor(Arc::new(Vec::new()))
127    }
128
129    pub fn from_json(value: serde_json::Value) -> Result<Self, AgentError> {
130        match value {
131            serde_json::Value::Null => Ok(AgentValue::Unit),
132            serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
133            serde_json::Value::Number(n) => {
134                if let Some(i) = n.as_i64() {
135                    Ok(AgentValue::Integer(i))
136                } else if let Some(f) = n.as_f64() {
137                    Ok(AgentValue::Number(f))
138                } else {
139                    Err(AgentError::InvalidValue(
140                        "Invalid numeric value for AgentValue".into(),
141                    ))
142                }
143            }
144            serde_json::Value::String(s) => {
145                #[cfg(feature = "image")]
146                if s.starts_with(IMAGE_BASE64_PREFIX) {
147                    let img =
148                        PhotonImage::new_from_base64(&s.trim_start_matches(IMAGE_BASE64_PREFIX));
149                    Ok(AgentValue::Image(Arc::new(img)))
150                } else {
151                    Ok(AgentValue::String(Arc::new(s)))
152                }
153                #[cfg(not(feature = "image"))]
154                Ok(AgentValue::String(Arc::new(s)))
155            }
156            serde_json::Value::Array(arr) => {
157                let agent_arr: Vector<AgentValue> = arr
158                    .into_iter()
159                    .map(AgentValue::from_json)
160                    .collect::<Result<_, _>>()?;
161                Ok(AgentValue::Array(agent_arr))
162            }
163            serde_json::Value::Object(obj) => {
164                let map: HashMap<String, AgentValue> = obj
165                    .into_iter()
166                    .map(|(k, v)| Ok((k, AgentValue::from_json(v)?)))
167                    .collect::<Result<_, AgentError>>()?;
168                Ok(AgentValue::Object(map))
169            }
170        }
171    }
172
173    pub fn to_json(&self) -> serde_json::Value {
174        match self {
175            AgentValue::Unit => serde_json::Value::Null,
176            AgentValue::Boolean(b) => (*b).into(),
177            AgentValue::Integer(i) => (*i).into(),
178            AgentValue::Number(n) => (*n).into(),
179            AgentValue::String(s) => s.as_str().into(),
180            #[cfg(feature = "image")]
181            AgentValue::Image(img) => img.get_base64().into(),
182            AgentValue::Array(a) => {
183                let arr: Vec<serde_json::Value> = a.iter().map(|v| v.to_json()).collect();
184                serde_json::Value::Array(arr)
185            }
186            AgentValue::Object(o) => {
187                let mut map = serde_json::Map::new();
188                let mut entries: Vec<_> = o.iter().collect();
189                entries.sort_by(|a, b| a.0.cmp(b.0));
190
191                for (k, v) in entries {
192                    map.insert(k.clone(), v.to_json());
193                }
194                serde_json::Value::Object(map)
195            }
196            AgentValue::Tensor(t) => {
197                let arr: Vec<serde_json::Value> = t
198                    .iter()
199                    .map(|&v| {
200                        serde_json::Value::Number(
201                            serde_json::Number::from_f64(v as f64)
202                                .unwrap_or_else(|| serde_json::Number::from(0)),
203                        )
204                    })
205                    .collect();
206                serde_json::Value::Array(arr)
207            }
208            AgentValue::Message(m) => serde_json::to_value(&**m).unwrap_or(serde_json::Value::Null),
209            AgentValue::Error(_) => serde_json::Value::Null, // Errors are not serializable
210        }
211    }
212
213    /// Create AgentValue from Serialize
214    pub fn from_serialize<T: Serialize>(value: &T) -> Result<Self, AgentError> {
215        let json_value = serde_json::to_value(value)
216            .map_err(|e| AgentError::InvalidValue(format!("Failed to serialize: {}", e)))?;
217        Self::from_json(json_value)
218    }
219
220    /// Convert AgentValue to a Deserialize
221    pub fn to_deserialize<T: for<'de> Deserialize<'de>>(&self) -> Result<T, AgentError> {
222        let json_value = self.to_json();
223        serde_json::from_value(json_value)
224            .map_err(|e| AgentError::InvalidValue(format!("Failed to deserialize: {}", e)))
225    }
226
227    // Type check helpers
228
229    pub fn is_unit(&self) -> bool {
230        matches!(self, AgentValue::Unit)
231    }
232
233    pub fn is_boolean(&self) -> bool {
234        matches!(self, AgentValue::Boolean(_))
235    }
236
237    pub fn is_integer(&self) -> bool {
238        matches!(self, AgentValue::Integer(_))
239    }
240
241    pub fn is_number(&self) -> bool {
242        matches!(self, AgentValue::Number(_))
243    }
244
245    pub fn is_string(&self) -> bool {
246        matches!(self, AgentValue::String(_))
247    }
248
249    #[cfg(feature = "image")]
250    pub fn is_image(&self) -> bool {
251        matches!(self, AgentValue::Image(_))
252    }
253
254    pub fn is_array(&self) -> bool {
255        matches!(self, AgentValue::Array(_))
256    }
257
258    pub fn is_object(&self) -> bool {
259        matches!(self, AgentValue::Object(_))
260    }
261
262    pub fn is_tensor(&self) -> bool {
263        matches!(self, AgentValue::Tensor(_))
264    }
265
266    pub fn is_message(&self) -> bool {
267        matches!(self, AgentValue::Message(_))
268    }
269
270    // Cast helpers
271
272    pub fn as_bool(&self) -> Option<bool> {
273        match self {
274            AgentValue::Boolean(b) => Some(*b),
275            _ => None,
276        }
277    }
278
279    pub fn as_i64(&self) -> Option<i64> {
280        match self {
281            AgentValue::Integer(i) => Some(*i),
282            AgentValue::Number(n) => Some(*n as i64),
283            _ => None,
284        }
285    }
286
287    pub fn as_f64(&self) -> Option<f64> {
288        match self {
289            AgentValue::Integer(i) => Some(*i as f64),
290            AgentValue::Number(n) => Some(*n),
291            _ => None,
292        }
293    }
294
295    pub fn as_str(&self) -> Option<&str> {
296        match self {
297            AgentValue::String(s) => Some(s),
298            _ => None,
299        }
300    }
301
302    #[cfg(feature = "image")]
303    pub fn as_image(&self) -> Option<&PhotonImage> {
304        match self {
305            AgentValue::Image(img) => Some(img),
306            _ => None,
307        }
308    }
309
310    #[cfg(feature = "image")]
311    /// If self is an Image, get a mutable reference to the inner PhotonImage.
312    pub fn as_image_mut(&mut self) -> Option<&mut PhotonImage> {
313        match self {
314            AgentValue::Image(img) => Some(Arc::make_mut(img)),
315            _ => None,
316        }
317    }
318
319    #[cfg(feature = "image")]
320    /// If self is an Image, extract the inner PhotonImage; otherwise, return None.
321    /// This consumes self.
322    pub fn into_image(self) -> Option<Arc<PhotonImage>> {
323        match self {
324            AgentValue::Image(img) => Some(img),
325            _ => None,
326        }
327    }
328
329    pub fn as_message(&self) -> Option<&Message> {
330        match self {
331            AgentValue::Message(m) => Some(m),
332            _ => None,
333        }
334    }
335
336    pub fn as_message_mut(&mut self) -> Option<&mut Message> {
337        match self {
338            AgentValue::Message(m) => Some(Arc::make_mut(m)),
339            _ => None,
340        }
341    }
342
343    pub fn into_message(self) -> Option<Arc<Message>> {
344        match self {
345            AgentValue::Message(m) => Some(m),
346            _ => None,
347        }
348    }
349
350    /// Convert to Boolean.
351    pub fn to_boolean(&self) -> Option<bool> {
352        match self {
353            AgentValue::Boolean(b) => Some(*b),
354            AgentValue::Integer(i) => Some(*i != 0),
355            AgentValue::Number(n) => Some(*n != 0.0),
356            AgentValue::String(s) => s.parse().ok(),
357            _ => None,
358        }
359    }
360
361    /// Convert to AgentValue::Boolean or AgentValue::Array of booleans.
362    pub fn to_boolean_value(&self) -> Option<AgentValue> {
363        match self {
364            AgentValue::Boolean(_) => Some(self.clone()),
365            AgentValue::Array(arr) => {
366                if arr.iter().all(|v| v.is_boolean()) {
367                    return Some(self.clone());
368                }
369                let mut new_arr = Vector::new();
370                for item in arr {
371                    new_arr.push_back(item.to_boolean_value()?);
372                }
373                Some(AgentValue::Array(new_arr))
374            }
375            _ => self.to_boolean().map(AgentValue::boolean),
376        }
377    }
378
379    /// Convert to Integer (i64).
380    pub fn to_integer(&self) -> Option<i64> {
381        match self {
382            AgentValue::Integer(i) => Some(*i),
383            AgentValue::Boolean(b) => Some(if *b { 1 } else { 0 }),
384            AgentValue::Number(n) => Some(*n as i64),
385            AgentValue::String(s) => s.parse().ok(),
386            _ => None,
387        }
388    }
389
390    /// Convert to AgentValue::Integer or AgentValue::Array of integers.
391    pub fn to_integer_value(&self) -> Option<AgentValue> {
392        match self {
393            AgentValue::Integer(_) => Some(self.clone()),
394            AgentValue::Array(arr) => {
395                if arr.iter().all(|v| v.is_integer()) {
396                    return Some(self.clone());
397                }
398                let mut new_arr = Vector::new();
399                for item in arr {
400                    new_arr.push_back(item.to_integer_value()?);
401                }
402                Some(AgentValue::Array(new_arr))
403            }
404            _ => self.to_integer().map(AgentValue::integer),
405        }
406    }
407
408    /// Convert to Number (f64).
409    pub fn to_number(&self) -> Option<f64> {
410        match self {
411            AgentValue::Number(n) => Some(*n),
412            AgentValue::Boolean(b) => Some(if *b { 1.0 } else { 0.0 }),
413            AgentValue::Integer(i) => Some(*i as f64),
414            AgentValue::String(s) => s.parse().ok(),
415            _ => None,
416        }
417    }
418
419    /// Convert to AgentValue::Number or AgentValue::Array of numbers.
420    pub fn to_number_value(&self) -> Option<AgentValue> {
421        match self {
422            AgentValue::Number(_) => Some(self.clone()),
423            AgentValue::Array(arr) => {
424                if arr.iter().all(|v| v.is_number()) {
425                    return Some(self.clone());
426                }
427                let mut new_arr = Vector::new();
428                for item in arr {
429                    new_arr.push_back(item.to_number_value()?);
430                }
431                Some(AgentValue::Array(new_arr))
432            }
433            _ => self.to_number().map(AgentValue::number),
434        }
435    }
436
437    /// Convert to String.
438    pub fn to_string(&self) -> Option<String> {
439        match self {
440            AgentValue::String(s) => Some(s.as_ref().clone()),
441            AgentValue::Boolean(b) => Some(b.to_string()),
442            AgentValue::Integer(i) => Some(i.to_string()),
443            AgentValue::Number(n) => Some(n.to_string()),
444            AgentValue::Message(m) => Some(m.content.clone()),
445            _ => None,
446        }
447    }
448
449    /// Convert to AgentValue::String or AgentValue::Array of strings.
450    pub fn to_string_value(&self) -> Option<AgentValue> {
451        match self {
452            AgentValue::String(_) => Some(self.clone()),
453            AgentValue::Array(arr) => {
454                if arr.iter().all(|v| v.is_string()) {
455                    return Some(self.clone());
456                }
457                let mut new_arr = Vector::new();
458                for item in arr {
459                    new_arr.push_back(item.to_string_value()?);
460                }
461                Some(AgentValue::Array(new_arr))
462            }
463            _ => self.to_string().map(AgentValue::string),
464        }
465    }
466
467    /// Convert to Message.
468    pub fn to_message(&self) -> Option<Message> {
469        Message::try_from(self.clone()).ok()
470    }
471
472    /// Convert to AgentValue::Message or AgentValue::Array of messages.
473    /// If the value is an array, it recursively converts its elements.
474    pub fn to_message_value(&self) -> Option<AgentValue> {
475        match self {
476            AgentValue::Message(_) => Some(self.clone()),
477            AgentValue::Array(arr) => {
478                if arr.iter().all(|v| v.is_message()) {
479                    return Some(self.clone());
480                }
481                let mut new_arr = Vector::new();
482                for item in arr {
483                    new_arr.push_back(item.to_message_value()?);
484                }
485                Some(AgentValue::Array(new_arr))
486            }
487            _ => Message::try_from(self.clone())
488                .ok()
489                .map(|m| AgentValue::message(m)),
490        }
491    }
492
493    pub fn as_object(&self) -> Option<&AgentValueMap<String, AgentValue>> {
494        match self {
495            AgentValue::Object(o) => Some(o),
496            _ => None,
497        }
498    }
499
500    pub fn as_object_mut(&mut self) -> Option<&mut AgentValueMap<String, AgentValue>> {
501        match self {
502            AgentValue::Object(o) => Some(o),
503            _ => None,
504        }
505    }
506
507    /// If self is an Object, extract the inner HashMap; otherwise, return None.
508    /// This consumes self.
509    pub fn into_object(self) -> Option<AgentValueMap<String, AgentValue>> {
510        match self {
511            AgentValue::Object(o) => Some(o),
512            _ => None,
513        }
514    }
515
516    pub fn as_array(&self) -> Option<&Vector<AgentValue>> {
517        match self {
518            AgentValue::Array(a) => Some(a),
519            _ => None,
520        }
521    }
522
523    pub fn as_array_mut(&mut self) -> Option<&mut Vector<AgentValue>> {
524        match self {
525            AgentValue::Array(a) => Some(a),
526            _ => None,
527        }
528    }
529
530    /// If self is an Array, extract the inner Vector; otherwise, return None.
531    /// This consumes self.
532    pub fn into_array(self) -> Option<Vector<AgentValue>> {
533        match self {
534            AgentValue::Array(a) => Some(a),
535            _ => None,
536        }
537    }
538
539    pub fn as_tensor(&self) -> Option<&Vec<f32>> {
540        match self {
541            AgentValue::Tensor(t) => Some(t),
542            _ => None,
543        }
544    }
545
546    pub fn as_tensor_mut(&mut self) -> Option<&mut Vec<f32>> {
547        match self {
548            AgentValue::Tensor(t) => Some(Arc::make_mut(t)),
549            _ => None,
550        }
551    }
552
553    /// If self is a Tensor, extract the inner Vec; otherwise, return None.
554    /// This consumes self.
555    pub fn into_tensor(self) -> Option<Arc<Vec<f32>>> {
556        match self {
557            AgentValue::Tensor(t) => Some(t),
558            _ => None,
559        }
560    }
561
562    /// If self is a Tensor, extract the inner Vec; otherwise, return None.
563    ///
564    /// This consumes self.
565    /// Possibly O(n) copy.
566    pub fn into_tensor_vec(self) -> Option<Vec<f32>> {
567        match self {
568            AgentValue::Tensor(t) => Some(Arc::unwrap_or_clone(t)),
569            _ => None,
570        }
571    }
572
573    // Getters by key
574
575    pub fn get(&self, key: &str) -> Option<&AgentValue> {
576        self.as_object().and_then(|o| o.get(key))
577    }
578
579    pub fn get_mut(&mut self, key: &str) -> Option<&mut AgentValue> {
580        self.as_object_mut().and_then(|o| o.get_mut(key))
581    }
582
583    pub fn get_bool(&self, key: &str) -> Option<bool> {
584        self.get(key).and_then(|v| v.as_bool())
585    }
586
587    pub fn get_i64(&self, key: &str) -> Option<i64> {
588        self.get(key).and_then(|v| v.as_i64())
589    }
590
591    pub fn get_f64(&self, key: &str) -> Option<f64> {
592        self.get(key).and_then(|v| v.as_f64())
593    }
594
595    pub fn get_str(&self, key: &str) -> Option<&str> {
596        self.get(key).and_then(|v| v.as_str())
597    }
598
599    #[cfg(feature = "image")]
600    pub fn get_image(&self, key: &str) -> Option<&PhotonImage> {
601        self.get(key).and_then(|v| v.as_image())
602    }
603
604    #[cfg(feature = "image")]
605    pub fn get_image_mut(&mut self, key: &str) -> Option<&mut PhotonImage> {
606        self.get_mut(key).and_then(|v| v.as_image_mut())
607    }
608
609    pub fn get_object(&self, key: &str) -> Option<&AgentValueMap<String, AgentValue>> {
610        self.get(key).and_then(|v| v.as_object())
611    }
612
613    pub fn get_object_mut(&mut self, key: &str) -> Option<&mut AgentValueMap<String, AgentValue>> {
614        self.get_mut(key).and_then(|v| v.as_object_mut())
615    }
616
617    pub fn get_array(&self, key: &str) -> Option<&Vector<AgentValue>> {
618        self.get(key).and_then(|v| v.as_array())
619    }
620
621    pub fn get_array_mut(&mut self, key: &str) -> Option<&mut Vector<AgentValue>> {
622        self.get_mut(key).and_then(|v| v.as_array_mut())
623    }
624
625    pub fn get_tensor(&self, key: &str) -> Option<&Vec<f32>> {
626        self.get(key).and_then(|v| v.as_tensor())
627    }
628
629    pub fn get_tensor_mut(&mut self, key: &str) -> Option<&mut Vec<f32>> {
630        self.get_mut(key).and_then(|v| v.as_tensor_mut())
631    }
632
633    pub fn get_message(&self, key: &str) -> Option<&Message> {
634        self.get(key).and_then(|v| v.as_message())
635    }
636
637    pub fn get_message_mut(&mut self, key: &str) -> Option<&mut Message> {
638        self.get_mut(key).and_then(|v| v.as_message_mut())
639    }
640
641    // Setter by key
642
643    pub fn set(&mut self, key: String, value: AgentValue) -> Result<(), AgentError> {
644        if let Some(obj) = self.as_object_mut() {
645            obj.insert(key, value);
646            Ok(())
647        } else {
648            Err(AgentError::InvalidValue(
649                "set can only be called on Object AgentValue".into(),
650            ))
651        }
652    }
653}
654
655impl Default for AgentValue {
656    fn default() -> Self {
657        AgentValue::Unit
658    }
659}
660
661impl PartialEq for AgentValue {
662    fn eq(&self, other: &Self) -> bool {
663        match (self, other) {
664            (AgentValue::Unit, AgentValue::Unit) => true,
665            (AgentValue::Boolean(b1), AgentValue::Boolean(b2)) => b1 == b2,
666            (AgentValue::Integer(i1), AgentValue::Integer(i2)) => i1 == i2,
667            (AgentValue::Number(n1), AgentValue::Number(n2)) => n1 == n2,
668            (AgentValue::String(s1), AgentValue::String(s2)) => s1 == s2,
669            #[cfg(feature = "image")]
670            (AgentValue::Image(i1), AgentValue::Image(i2)) => {
671                i1.get_width() == i2.get_width()
672                    && i1.get_height() == i2.get_height()
673                    && i1.get_raw_pixels() == i2.get_raw_pixels()
674            }
675            (AgentValue::Array(a1), AgentValue::Array(a2)) => a1 == a2,
676            (AgentValue::Object(o1), AgentValue::Object(o2)) => o1 == o2,
677            (AgentValue::Tensor(t1), AgentValue::Tensor(t2)) => t1 == t2,
678            (AgentValue::Message(m1), AgentValue::Message(m2)) => m1 == m2,
679            _ => false,
680        }
681    }
682}
683
684impl Serialize for AgentValue {
685    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
686    where
687        S: Serializer,
688    {
689        match self {
690            AgentValue::Unit => serializer.serialize_none(),
691            AgentValue::Boolean(b) => serializer.serialize_bool(*b),
692            AgentValue::Integer(i) => serializer.serialize_i64(*i),
693            AgentValue::Number(n) => serializer.serialize_f64(*n),
694            AgentValue::String(s) => serializer.serialize_str(s),
695            #[cfg(feature = "image")]
696            AgentValue::Image(img) => serializer.serialize_str(&img.get_base64()),
697            AgentValue::Array(a) => {
698                let mut seq = serializer.serialize_seq(Some(a.len()))?;
699                for e in a.iter() {
700                    seq.serialize_element(e)?;
701                }
702                seq.end()
703            }
704            AgentValue::Object(o) => {
705                let mut map = serializer.serialize_map(Some(o.len()))?;
706                // Sort the entries to ensure stable JSON output.
707                let mut entries: Vec<_> = o.iter().collect();
708                entries.sort_by(|a, b| a.0.cmp(b.0));
709
710                for (k, v) in entries {
711                    map.serialize_entry(k, v)?;
712                }
713                map.end()
714            }
715            AgentValue::Tensor(t) => {
716                let mut seq = serializer.serialize_seq(Some(t.len()))?;
717                for e in t.iter() {
718                    seq.serialize_element(e)?;
719                }
720                seq.end()
721            }
722            AgentValue::Message(m) => m.serialize(serializer),
723            AgentValue::Error(_) => serializer.serialize_none(), // Errors are not serializable
724        }
725    }
726}
727
728impl<'de> Deserialize<'de> for AgentValue {
729    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
730    where
731        D: Deserializer<'de>,
732    {
733        let value = serde_json::Value::deserialize(deserializer)?;
734        AgentValue::from_json(value).map_err(|e| {
735            serde::de::Error::custom(format!("Failed to deserialize AgentValue: {}", e))
736        })
737    }
738}
739
740impl From<()> for AgentValue {
741    fn from(_: ()) -> Self {
742        AgentValue::unit()
743    }
744}
745
746impl From<bool> for AgentValue {
747    fn from(value: bool) -> Self {
748        AgentValue::boolean(value)
749    }
750}
751
752impl From<i32> for AgentValue {
753    fn from(value: i32) -> Self {
754        AgentValue::integer(value as i64)
755    }
756}
757
758impl From<i64> for AgentValue {
759    fn from(value: i64) -> Self {
760        AgentValue::integer(value)
761    }
762}
763
764impl From<usize> for AgentValue {
765    fn from(value: usize) -> Self {
766        AgentValue::Integer(value as i64)
767    }
768}
769
770impl From<u64> for AgentValue {
771    fn from(value: u64) -> Self {
772        AgentValue::Integer(value as i64)
773    }
774}
775
776impl From<f32> for AgentValue {
777    fn from(value: f32) -> Self {
778        AgentValue::Number(value as f64)
779    }
780}
781
782impl From<f64> for AgentValue {
783    fn from(value: f64) -> Self {
784        AgentValue::number(value)
785    }
786}
787
788impl From<String> for AgentValue {
789    fn from(value: String) -> Self {
790        AgentValue::string(value)
791    }
792}
793
794impl From<&str> for AgentValue {
795    fn from(value: &str) -> Self {
796        AgentValue::string(value)
797    }
798}
799
800impl From<Vector<AgentValue>> for AgentValue {
801    fn from(value: Vector<AgentValue>) -> Self {
802        AgentValue::Array(value)
803    }
804}
805
806impl From<HashMap<String, AgentValue>> for AgentValue {
807    fn from(value: HashMap<String, AgentValue>) -> Self {
808        AgentValue::Object(value)
809    }
810}
811
812// Tensor support
813impl From<Vec<f32>> for AgentValue {
814    fn from(value: Vec<f32>) -> Self {
815        AgentValue::Tensor(Arc::new(value))
816    }
817}
818impl From<Arc<Vec<f32>>> for AgentValue {
819    fn from(value: Arc<Vec<f32>>) -> Self {
820        AgentValue::Tensor(value)
821    }
822}
823
824// Standard Collections support
825impl From<Vec<AgentValue>> for AgentValue {
826    fn from(value: Vec<AgentValue>) -> Self {
827        AgentValue::Array(Vector::from(value))
828    }
829}
830impl From<std::collections::HashMap<String, AgentValue>> for AgentValue {
831    fn from(value: std::collections::HashMap<String, AgentValue>) -> Self {
832        AgentValue::Object(HashMap::from(value))
833    }
834}
835
836// Error support
837impl From<AgentError> for AgentValue {
838    fn from(value: AgentError) -> Self {
839        AgentValue::Error(Arc::new(value))
840    }
841}
842
843// Option support
844impl From<Option<AgentValue>> for AgentValue {
845    fn from(value: Option<AgentValue>) -> Self {
846        value.unwrap_or(AgentValue::Unit)
847    }
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853    use im::{hashmap, vector};
854    use serde_json::json;
855
856    #[test]
857    fn test_partial_eq() {
858        // Test PartialEq implementation
859        let unit1 = AgentValue::unit();
860        let unit2 = AgentValue::unit();
861        assert_eq!(unit1, unit2);
862
863        let boolean1 = AgentValue::boolean(true);
864        let boolean2 = AgentValue::boolean(true);
865        assert_eq!(boolean1, boolean2);
866
867        let integer1 = AgentValue::integer(42);
868        let integer2 = AgentValue::integer(42);
869        assert_eq!(integer1, integer2);
870        let different = AgentValue::integer(100);
871        assert_ne!(integer1, different);
872
873        let number1 = AgentValue::number(3.14);
874        let number2 = AgentValue::number(3.14);
875        assert_eq!(number1, number2);
876
877        let string1 = AgentValue::string("hello");
878        let string2 = AgentValue::string("hello");
879        assert_eq!(string1, string2);
880
881        #[cfg(feature = "image")]
882        {
883            let image1 = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
884            let image2 = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
885            assert_eq!(image1, image2);
886        }
887
888        let obj1 = AgentValue::object(hashmap! {
889                "key1".into() => AgentValue::string("value1"),
890                "key2".into() => AgentValue::integer(2),
891        });
892        let obj2 = AgentValue::object(hashmap! {
893                "key1".to_string() => AgentValue::string("value1"),
894                "key2".to_string() => AgentValue::integer(2),
895        });
896        assert_eq!(obj1, obj2);
897
898        let arr1 = AgentValue::array(vector![
899            AgentValue::integer(1),
900            AgentValue::string("two"),
901            AgentValue::boolean(true),
902        ]);
903        let arr2 = AgentValue::array(vector![
904            AgentValue::integer(1),
905            AgentValue::string("two"),
906            AgentValue::boolean(true),
907        ]);
908        assert_eq!(arr1, arr2);
909
910        let mixed_types_1 = AgentValue::boolean(true);
911        let mixed_types_2 = AgentValue::integer(1);
912        assert_ne!(mixed_types_1, mixed_types_2);
913
914        let msg1 = AgentValue::message(Message::user("hello".to_string()));
915        let msg2 = AgentValue::message(Message::user("hello".to_string()));
916        assert_eq!(msg1, msg2);
917    }
918
919    #[test]
920    fn test_agent_value_constructors() {
921        // Test AgentValue constructors
922        let unit = AgentValue::unit();
923        assert_eq!(unit, AgentValue::Unit);
924
925        let boolean = AgentValue::boolean(true);
926        assert_eq!(boolean, AgentValue::Boolean(true));
927
928        let integer = AgentValue::integer(42);
929        assert_eq!(integer, AgentValue::Integer(42));
930
931        let number = AgentValue::number(3.14);
932        assert!(matches!(number, AgentValue::Number(_)));
933        if let AgentValue::Number(num) = number {
934            assert!((num - 3.14).abs() < f64::EPSILON);
935        }
936
937        let string = AgentValue::string("hello");
938        assert!(matches!(string, AgentValue::String(_)));
939        assert_eq!(string.as_str().unwrap(), "hello");
940
941        let text = AgentValue::string("multiline\ntext");
942        assert!(matches!(text, AgentValue::String(_)));
943        assert_eq!(text.as_str().unwrap(), "multiline\ntext");
944
945        let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
946        assert!(matches!(array, AgentValue::Array(_)));
947        if let AgentValue::Array(arr) = array {
948            assert_eq!(arr.len(), 2);
949            assert_eq!(arr[0].as_i64().unwrap(), 1);
950            assert_eq!(arr[1].as_i64().unwrap(), 2);
951        }
952
953        let obj = AgentValue::object(hashmap! {
954                "key1".to_string() => AgentValue::string("string1"),
955                "key2".to_string() => AgentValue::integer(2),
956        });
957        assert!(matches!(obj, AgentValue::Object(_)));
958        if let AgentValue::Object(obj) = obj {
959            assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
960            assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
961        } else {
962            panic!("Object was not deserialized correctly");
963        }
964
965        let msg = AgentValue::message(Message::user("hello".to_string()));
966        assert!(matches!(msg, AgentValue::Message(_)));
967    }
968
969    #[test]
970    fn test_agent_value_from_json_value() {
971        // Test converting from JSON value to AgentValue
972        let null = AgentValue::from_json(json!(null)).unwrap();
973        assert_eq!(null, AgentValue::Unit);
974
975        let boolean = AgentValue::from_json(json!(true)).unwrap();
976        assert_eq!(boolean, AgentValue::Boolean(true));
977
978        let integer = AgentValue::from_json(json!(42)).unwrap();
979        assert_eq!(integer, AgentValue::Integer(42));
980
981        let number = AgentValue::from_json(json!(3.14)).unwrap();
982        assert!(matches!(number, AgentValue::Number(_)));
983        if let AgentValue::Number(num) = number {
984            assert!((num - 3.14).abs() < f64::EPSILON);
985        }
986
987        let string = AgentValue::from_json(json!("hello")).unwrap();
988        assert!(matches!(string, AgentValue::String(_)));
989        if let AgentValue::String(s) = string {
990            assert_eq!(*s, "hello");
991        } else {
992            panic!("Expected string value");
993        }
994
995        let array = AgentValue::from_json(json!([1, "test", true])).unwrap();
996        assert!(matches!(array, AgentValue::Array(_)));
997        if let AgentValue::Array(arr) = array {
998            assert_eq!(arr.len(), 3);
999            assert_eq!(arr[0], AgentValue::Integer(1));
1000            assert!(matches!(&arr[1], AgentValue::String(_)));
1001            if let AgentValue::String(s) = &arr[1] {
1002                assert_eq!(**s, "test");
1003            } else {
1004                panic!("Expected string value");
1005            }
1006            assert_eq!(arr[2], AgentValue::Boolean(true));
1007        }
1008
1009        let object = AgentValue::from_json(json!({"key1": "string1", "key2": 2})).unwrap();
1010        assert!(matches!(object, AgentValue::Object(_)));
1011        if let AgentValue::Object(obj) = object {
1012            assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
1013            assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
1014        } else {
1015            panic!("Object was not deserialized correctly");
1016        }
1017    }
1018
1019    #[test]
1020    fn test_agent_value_test_methods() {
1021        // Test test methods on AgentValue
1022        let unit = AgentValue::unit();
1023        assert_eq!(unit.is_unit(), true);
1024        assert_eq!(unit.is_boolean(), false);
1025        assert_eq!(unit.is_integer(), false);
1026        assert_eq!(unit.is_number(), false);
1027        assert_eq!(unit.is_string(), false);
1028        assert_eq!(unit.is_array(), false);
1029        assert_eq!(unit.is_object(), false);
1030        #[cfg(feature = "image")]
1031        assert_eq!(unit.is_image(), false);
1032
1033        let boolean = AgentValue::boolean(true);
1034        assert_eq!(boolean.is_unit(), false);
1035        assert_eq!(boolean.is_boolean(), true);
1036        assert_eq!(boolean.is_integer(), false);
1037        assert_eq!(boolean.is_number(), false);
1038        assert_eq!(boolean.is_string(), false);
1039        assert_eq!(boolean.is_array(), false);
1040        assert_eq!(boolean.is_object(), false);
1041        #[cfg(feature = "image")]
1042        assert_eq!(boolean.is_image(), false);
1043
1044        let integer = AgentValue::integer(42);
1045        assert_eq!(integer.is_unit(), false);
1046        assert_eq!(integer.is_boolean(), false);
1047        assert_eq!(integer.is_integer(), true);
1048        assert_eq!(integer.is_number(), false);
1049        assert_eq!(integer.is_string(), false);
1050        assert_eq!(integer.is_array(), false);
1051        assert_eq!(integer.is_object(), false);
1052        #[cfg(feature = "image")]
1053        assert_eq!(integer.is_image(), false);
1054
1055        let number = AgentValue::number(3.14);
1056        assert_eq!(number.is_unit(), false);
1057        assert_eq!(number.is_boolean(), false);
1058        assert_eq!(number.is_integer(), false);
1059        assert_eq!(number.is_number(), true);
1060        assert_eq!(number.is_string(), false);
1061        assert_eq!(number.is_array(), false);
1062        assert_eq!(number.is_object(), false);
1063        #[cfg(feature = "image")]
1064        assert_eq!(number.is_image(), false);
1065
1066        let string = AgentValue::string("hello");
1067        assert_eq!(string.is_unit(), false);
1068        assert_eq!(string.is_boolean(), false);
1069        assert_eq!(string.is_integer(), false);
1070        assert_eq!(string.is_number(), false);
1071        assert_eq!(string.is_string(), true);
1072        assert_eq!(string.is_array(), false);
1073        assert_eq!(string.is_object(), false);
1074        #[cfg(feature = "image")]
1075        assert_eq!(string.is_image(), false);
1076
1077        let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1078        assert_eq!(array.is_unit(), false);
1079        assert_eq!(array.is_boolean(), false);
1080        assert_eq!(array.is_integer(), false);
1081        assert_eq!(array.is_number(), false);
1082        assert_eq!(array.is_string(), false);
1083        assert_eq!(array.is_array(), true);
1084        assert_eq!(array.is_object(), false);
1085        #[cfg(feature = "image")]
1086        assert_eq!(array.is_image(), false);
1087
1088        let obj = AgentValue::object(hashmap! {
1089                "key1".to_string() => AgentValue::string("string1"),
1090                "key2".to_string() => AgentValue::integer(2),
1091        });
1092        assert_eq!(obj.is_unit(), false);
1093        assert_eq!(obj.is_boolean(), false);
1094        assert_eq!(obj.is_integer(), false);
1095        assert_eq!(obj.is_number(), false);
1096        assert_eq!(obj.is_string(), false);
1097        assert_eq!(obj.is_array(), false);
1098        assert_eq!(obj.is_object(), true);
1099        #[cfg(feature = "image")]
1100        assert_eq!(obj.is_image(), false);
1101
1102        #[cfg(feature = "image")]
1103        {
1104            let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1105            assert_eq!(img.is_unit(), false);
1106            assert_eq!(img.is_boolean(), false);
1107            assert_eq!(img.is_integer(), false);
1108            assert_eq!(img.is_number(), false);
1109            assert_eq!(img.is_string(), false);
1110            assert_eq!(img.is_array(), false);
1111            assert_eq!(img.is_object(), false);
1112            assert_eq!(img.is_image(), true);
1113        }
1114
1115        let msg = AgentValue::message(Message::user("hello".to_string()));
1116        assert_eq!(msg.is_unit(), false);
1117        assert_eq!(msg.is_boolean(), false);
1118        assert_eq!(msg.is_integer(), false);
1119        assert_eq!(msg.is_number(), false);
1120        assert_eq!(msg.is_string(), false);
1121        assert_eq!(msg.is_array(), false);
1122        assert_eq!(msg.is_object(), false);
1123        #[cfg(feature = "image")]
1124        assert_eq!(msg.is_image(), false);
1125        assert_eq!(msg.is_message(), true);
1126    }
1127
1128    #[test]
1129    fn test_agent_value_as_methods() {
1130        // Test accessor methods on AgentValue
1131        let boolean = AgentValue::boolean(true);
1132        assert_eq!(boolean.as_bool(), Some(true));
1133        assert_eq!(boolean.as_i64(), None);
1134        assert_eq!(boolean.as_f64(), None);
1135        assert_eq!(boolean.as_str(), None);
1136        assert!(boolean.as_array().is_none());
1137        assert_eq!(boolean.as_object(), None);
1138        #[cfg(feature = "image")]
1139        assert!(boolean.as_image().is_none());
1140
1141        let integer = AgentValue::integer(42);
1142        assert_eq!(integer.as_bool(), None);
1143        assert_eq!(integer.as_i64(), Some(42));
1144        assert_eq!(integer.as_f64(), Some(42.0));
1145        assert_eq!(integer.as_str(), None);
1146        assert!(integer.as_array().is_none());
1147        assert_eq!(integer.as_object(), None);
1148        #[cfg(feature = "image")]
1149        assert!(integer.as_image().is_none());
1150
1151        let number = AgentValue::number(3.14);
1152        assert_eq!(number.as_bool(), None);
1153        assert_eq!(number.as_i64(), Some(3)); // truncated
1154        assert_eq!(number.as_f64().unwrap(), 3.14);
1155        assert_eq!(number.as_str(), None);
1156        assert!(number.as_array().is_none());
1157        assert_eq!(number.as_object(), None);
1158        #[cfg(feature = "image")]
1159        assert!(number.as_image().is_none());
1160
1161        let string = AgentValue::string("hello");
1162        assert_eq!(string.as_bool(), None);
1163        assert_eq!(string.as_i64(), None);
1164        assert_eq!(string.as_f64(), None);
1165        assert_eq!(string.as_str(), Some("hello"));
1166        assert!(string.as_array().is_none());
1167        assert_eq!(string.as_object(), None);
1168        #[cfg(feature = "image")]
1169        assert!(string.as_image().is_none());
1170
1171        let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1172        assert_eq!(array.as_bool(), None);
1173        assert_eq!(array.as_i64(), None);
1174        assert_eq!(array.as_f64(), None);
1175        assert_eq!(array.as_str(), None);
1176        assert!(array.as_array().is_some());
1177        if let Some(arr) = array.as_array() {
1178            assert_eq!(arr.len(), 2);
1179            assert_eq!(arr[0].as_i64().unwrap(), 1);
1180            assert_eq!(arr[1].as_i64().unwrap(), 2);
1181        }
1182        assert_eq!(array.as_object(), None);
1183        #[cfg(feature = "image")]
1184        assert!(array.as_image().is_none());
1185
1186        let mut array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1187        if let Some(arr) = array.as_array_mut() {
1188            arr.push_back(AgentValue::integer(3));
1189        }
1190
1191        let obj = AgentValue::object(hashmap! {
1192                "key1".to_string() => AgentValue::string("string1"),
1193                "key2".to_string() => AgentValue::integer(2),
1194        });
1195        assert_eq!(obj.as_bool(), None);
1196        assert_eq!(obj.as_i64(), None);
1197        assert_eq!(obj.as_f64(), None);
1198        assert_eq!(obj.as_str(), None);
1199        assert!(obj.as_array().is_none());
1200        assert!(obj.as_object().is_some());
1201        if let Some(value) = obj.as_object() {
1202            assert_eq!(value.get("key1").and_then(|v| v.as_str()), Some("string1"));
1203            assert_eq!(value.get("key2").and_then(|v| v.as_i64()), Some(2));
1204        }
1205        #[cfg(feature = "image")]
1206        assert!(obj.as_image().is_none());
1207
1208        let mut obj = AgentValue::object(hashmap! {
1209                "key1".to_string() => AgentValue::string("string1"),
1210                "key2".to_string() => AgentValue::integer(2),
1211        });
1212        if let Some(value) = obj.as_object_mut() {
1213            value.insert("key3".to_string(), AgentValue::boolean(true));
1214        }
1215
1216        #[cfg(feature = "image")]
1217        {
1218            let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1219            assert_eq!(img.as_bool(), None);
1220            assert_eq!(img.as_i64(), None);
1221            assert_eq!(img.as_f64(), None);
1222            assert_eq!(img.as_str(), None);
1223            assert!(img.as_array().is_none());
1224            assert_eq!(img.as_object(), None);
1225            assert!(img.as_image().is_some());
1226        }
1227
1228        let mut msg = AgentValue::message(Message::user("hello".to_string()));
1229        assert!(msg.as_message().is_some());
1230        assert_eq!(msg.as_message().unwrap().content, "hello");
1231        assert!(msg.as_message_mut().is_some());
1232        if let Some(m) = msg.as_message_mut() {
1233            m.content = "world".to_string();
1234        }
1235        assert_eq!(msg.as_message().unwrap().content, "world");
1236        assert!(msg.into_message().is_some());
1237    }
1238
1239    #[test]
1240    fn test_agent_value_get_methods() {
1241        // Test get methods on AgentValue
1242        const KEY: &str = "key";
1243
1244        let boolean = AgentValue::boolean(true);
1245        assert_eq!(boolean.get(KEY), None);
1246
1247        let integer = AgentValue::integer(42);
1248        assert_eq!(integer.get(KEY), None);
1249
1250        let number = AgentValue::number(3.14);
1251        assert_eq!(number.get(KEY), None);
1252
1253        let string = AgentValue::string("hello");
1254        assert_eq!(string.get(KEY), None);
1255
1256        let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1257        assert_eq!(array.get(KEY), None);
1258
1259        let mut array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1260        assert_eq!(array.get_mut(KEY), None);
1261
1262        let mut obj = AgentValue::object(hashmap! {
1263                "k_boolean".to_string() => AgentValue::boolean(true),
1264                "k_integer".to_string() => AgentValue::integer(42),
1265                "k_number".to_string() => AgentValue::number(3.14),
1266                "k_string".to_string() => AgentValue::string("string1"),
1267                "k_array".to_string() => AgentValue::array(vector![AgentValue::integer(1)]),
1268                "k_object".to_string() => AgentValue::object(hashmap! {
1269                        "inner_key".to_string() => AgentValue::integer(100),
1270                }),
1271                #[cfg(feature = "image")]
1272                "k_image".to_string() => AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1)),
1273                "k_message".to_string() => AgentValue::message(Message::user("hello".to_string())),
1274        });
1275        assert_eq!(obj.get(KEY), None);
1276        assert_eq!(obj.get_bool("k_boolean"), Some(true));
1277        assert_eq!(obj.get_i64("k_integer"), Some(42));
1278        assert_eq!(obj.get_f64("k_number"), Some(3.14));
1279        assert_eq!(obj.get_str("k_string"), Some("string1"));
1280        assert!(obj.get_array("k_array").is_some());
1281        assert!(obj.get_array_mut("k_array").is_some());
1282        assert!(obj.get_object("k_object").is_some());
1283        assert!(obj.get_object_mut("k_object").is_some());
1284        #[cfg(feature = "image")]
1285        assert!(obj.get_image("k_image").is_some());
1286        assert!(obj.get_message("k_message").is_some());
1287        assert!(obj.get_message_mut("k_message").is_some());
1288
1289        #[cfg(feature = "image")]
1290        {
1291            let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1292            assert_eq!(img.get(KEY), None);
1293        }
1294    }
1295
1296    #[test]
1297    fn test_agent_value_set() {
1298        // Test set method on AgentValue
1299        let mut obj = AgentValue::object(AgentValueMap::new());
1300        assert!(obj.set("key1".to_string(), AgentValue::integer(42)).is_ok());
1301        assert_eq!(obj.get_i64("key1"), Some(42));
1302
1303        let mut not_obj = AgentValue::integer(10);
1304        assert!(
1305            not_obj
1306                .set("key1".to_string(), AgentValue::integer(42))
1307                .is_err()
1308        );
1309    }
1310
1311    #[test]
1312    fn test_agent_value_default() {
1313        assert_eq!(AgentValue::default(), AgentValue::Unit);
1314
1315        assert_eq!(AgentValue::boolean_default(), AgentValue::Boolean(false));
1316        assert_eq!(AgentValue::integer_default(), AgentValue::Integer(0));
1317        assert_eq!(AgentValue::number_default(), AgentValue::Number(0.0));
1318        assert_eq!(
1319            AgentValue::string_default(),
1320            AgentValue::String(Arc::new(String::new()))
1321        );
1322        assert_eq!(
1323            AgentValue::array_default(),
1324            AgentValue::Array(Vector::new())
1325        );
1326        assert_eq!(
1327            AgentValue::object_default(),
1328            AgentValue::Object(AgentValueMap::new())
1329        );
1330
1331        #[cfg(feature = "image")]
1332        {
1333            assert_eq!(
1334                AgentValue::image_default(),
1335                AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1))
1336            );
1337        }
1338    }
1339
1340    #[test]
1341    fn test_to_json() {
1342        // Test to_json
1343        let unit = AgentValue::unit();
1344        assert_eq!(unit.to_json(), json!(null));
1345
1346        let boolean = AgentValue::boolean(true);
1347        assert_eq!(boolean.to_json(), json!(true));
1348
1349        let integer = AgentValue::integer(42);
1350        assert_eq!(integer.to_json(), json!(42));
1351
1352        let number = AgentValue::number(3.14);
1353        assert_eq!(number.to_json(), json!(3.14));
1354
1355        let string = AgentValue::string("hello");
1356        assert_eq!(string.to_json(), json!("hello"));
1357
1358        let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::string("test")]);
1359        assert_eq!(array.to_json(), json!([1, "test"]));
1360
1361        let obj = AgentValue::object(hashmap! {
1362                "key1".to_string() => AgentValue::string("string1"),
1363                "key2".to_string() => AgentValue::integer(2),
1364        });
1365        assert_eq!(obj.to_json(), json!({"key1": "string1", "key2": 2}));
1366
1367        #[cfg(feature = "image")]
1368        {
1369            let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1370            assert_eq!(
1371                img.to_json(),
1372                json!(
1373                    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg=="
1374                )
1375            );
1376        }
1377
1378        let msg = AgentValue::message(Message::user("hello".to_string()));
1379        assert_eq!(
1380            msg.to_json(),
1381            json!({
1382                "role": "user",
1383                "content": "hello",
1384            })
1385        );
1386    }
1387
1388    #[test]
1389    fn test_agent_value_serialization() {
1390        // Test Null serialization
1391        {
1392            let null = AgentValue::Unit;
1393            assert_eq!(serde_json::to_string(&null).unwrap(), "null");
1394        }
1395
1396        // Test Boolean serialization
1397        {
1398            let boolean_t = AgentValue::boolean(true);
1399            assert_eq!(serde_json::to_string(&boolean_t).unwrap(), "true");
1400
1401            let boolean_f = AgentValue::boolean(false);
1402            assert_eq!(serde_json::to_string(&boolean_f).unwrap(), "false");
1403        }
1404
1405        // Test Integer serialization
1406        {
1407            let integer = AgentValue::integer(42);
1408            assert_eq!(serde_json::to_string(&integer).unwrap(), "42");
1409        }
1410
1411        // Test Number serialization
1412        {
1413            let num = AgentValue::number(3.14);
1414            assert_eq!(serde_json::to_string(&num).unwrap(), "3.14");
1415
1416            let num = AgentValue::number(3.0);
1417            assert_eq!(serde_json::to_string(&num).unwrap(), "3.0");
1418        }
1419
1420        // Test String serialization
1421        {
1422            let s = AgentValue::string("Hello, world!");
1423            assert_eq!(serde_json::to_string(&s).unwrap(), "\"Hello, world!\"");
1424
1425            let s = AgentValue::string("hello\nworld\n\n");
1426            assert_eq!(serde_json::to_string(&s).unwrap(), r#""hello\nworld\n\n""#);
1427        }
1428
1429        // Test Image serialization
1430        #[cfg(feature = "image")]
1431        {
1432            let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1433            assert_eq!(
1434                serde_json::to_string(&img).unwrap(),
1435                r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#
1436            );
1437        }
1438
1439        // Test Arc Image serialization
1440        #[cfg(feature = "image")]
1441        {
1442            let img = AgentValue::image_arc(Arc::new(PhotonImage::new(vec![0u8; 4], 1, 1)));
1443            assert_eq!(
1444                serde_json::to_string(&img).unwrap(),
1445                r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#
1446            );
1447        }
1448
1449        // Test Array serialization
1450        {
1451            let array = AgentValue::array(vector![
1452                AgentValue::integer(1),
1453                AgentValue::string("test"),
1454                AgentValue::object(hashmap! {
1455                        "key1".to_string() => AgentValue::string("test"),
1456                        "key2".to_string() => AgentValue::integer(2),
1457                }),
1458            ]);
1459            assert_eq!(
1460                serde_json::to_string(&array).unwrap(),
1461                r#"[1,"test",{"key1":"test","key2":2}]"#
1462            );
1463        }
1464
1465        // Test Object serialization
1466        {
1467            let obj = AgentValue::object(hashmap! {
1468                    "key1".to_string() => AgentValue::string("test"),
1469                    "key2".to_string() => AgentValue::integer(3),
1470            });
1471            assert_eq!(
1472                serde_json::to_string(&obj).unwrap(),
1473                r#"{"key1":"test","key2":3}"#
1474            );
1475        }
1476    }
1477
1478    #[test]
1479    fn test_agent_value_deserialization() {
1480        // Test Null deserialization
1481        {
1482            let deserialized: AgentValue = serde_json::from_str("null").unwrap();
1483            assert_eq!(deserialized, AgentValue::Unit);
1484        }
1485
1486        // Test Boolean deserialization
1487        {
1488            let deserialized: AgentValue = serde_json::from_str("false").unwrap();
1489            assert_eq!(deserialized, AgentValue::boolean(false));
1490
1491            let deserialized: AgentValue = serde_json::from_str("true").unwrap();
1492            assert_eq!(deserialized, AgentValue::boolean(true));
1493        }
1494
1495        // Test Integer deserialization
1496        {
1497            let deserialized: AgentValue = serde_json::from_str("123").unwrap();
1498            assert_eq!(deserialized, AgentValue::integer(123));
1499        }
1500
1501        // Test Number deserialization
1502        {
1503            let deserialized: AgentValue = serde_json::from_str("3.14").unwrap();
1504            assert_eq!(deserialized, AgentValue::number(3.14));
1505
1506            let deserialized: AgentValue = serde_json::from_str("3.0").unwrap();
1507            assert_eq!(deserialized, AgentValue::number(3.0));
1508        }
1509
1510        // Test String deserialization
1511        {
1512            let deserialized: AgentValue = serde_json::from_str("\"Hello, world!\"").unwrap();
1513            assert_eq!(deserialized, AgentValue::string("Hello, world!"));
1514
1515            let deserialized: AgentValue = serde_json::from_str(r#""hello\nworld\n\n""#).unwrap();
1516            assert_eq!(deserialized, AgentValue::string("hello\nworld\n\n"));
1517        }
1518
1519        // Test Image deserialization
1520        #[cfg(feature = "image")]
1521        {
1522            let deserialized: AgentValue = serde_json::from_str(
1523                r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#,
1524            )
1525            .unwrap();
1526            assert!(matches!(deserialized, AgentValue::Image(_)));
1527        }
1528
1529        // Test Array deserialization
1530        {
1531            let deserialized: AgentValue =
1532                serde_json::from_str(r#"[1,"test",{"key1":"test","key2":2}]"#).unwrap();
1533            assert!(matches!(deserialized, AgentValue::Array(_)));
1534            if let AgentValue::Array(arr) = deserialized {
1535                assert_eq!(arr.len(), 3, "Array length mismatch after serialization");
1536                assert_eq!(arr[0], AgentValue::integer(1));
1537                assert_eq!(arr[1], AgentValue::string("test"));
1538                assert_eq!(
1539                    arr[2],
1540                    AgentValue::object(hashmap! {
1541                            "key1".to_string() => AgentValue::string("test"),
1542                            "key2".to_string() => AgentValue::integer(2),
1543                    })
1544                );
1545            }
1546        }
1547
1548        // Test Object deserialization
1549        {
1550            let deserialized: AgentValue =
1551                serde_json::from_str(r#"{"key1":"test","key2":3}"#).unwrap();
1552            assert_eq!(
1553                deserialized,
1554                AgentValue::object(hashmap! {
1555                        "key1".to_string() => AgentValue::string("test"),
1556                        "key2".to_string() => AgentValue::integer(3),
1557                })
1558            );
1559        }
1560    }
1561
1562    #[test]
1563    fn test_agent_value_into() {
1564        // Test From implementations for AgentValue
1565        let from_unit: AgentValue = ().into();
1566        assert_eq!(from_unit, AgentValue::Unit);
1567
1568        let from_bool: AgentValue = true.into();
1569        assert_eq!(from_bool, AgentValue::Boolean(true));
1570
1571        let from_i32: AgentValue = 42i32.into();
1572        assert_eq!(from_i32, AgentValue::Integer(42));
1573
1574        let from_i64: AgentValue = 100i64.into();
1575        assert_eq!(from_i64, AgentValue::Integer(100));
1576
1577        let from_f64: AgentValue = 3.14f64.into();
1578        assert_eq!(from_f64, AgentValue::Number(3.14));
1579
1580        let from_string: AgentValue = "hello".to_string().into();
1581        assert_eq!(
1582            from_string,
1583            AgentValue::String(Arc::new("hello".to_string()))
1584        );
1585
1586        let from_str: AgentValue = "world".into();
1587        assert_eq!(from_str, AgentValue::String(Arc::new("world".to_string())));
1588    }
1589
1590    #[test]
1591    fn test_serialize_deserialize_roundtrip() {
1592        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1593        struct TestStruct {
1594            name: String,
1595            age: i64,
1596            active: bool,
1597        }
1598
1599        let test_data = TestStruct {
1600            name: "Alice".to_string(),
1601            age: 30,
1602            active: true,
1603        };
1604
1605        // Test AgentData roundtrip
1606        let agent_data = AgentValue::from_serialize(&test_data).unwrap();
1607        assert_eq!(agent_data.get_str("name"), Some("Alice"));
1608        assert_eq!(agent_data.get_i64("age"), Some(30));
1609        assert_eq!(agent_data.get_bool("active"), Some(true));
1610
1611        let restored: TestStruct = agent_data.to_deserialize().unwrap();
1612        assert_eq!(restored, test_data);
1613    }
1614
1615    #[test]
1616    fn test_serialize_deserialize_nested() {
1617        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1618        struct Address {
1619            street: String,
1620            city: String,
1621            zip: String,
1622        }
1623
1624        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1625        struct Person {
1626            name: String,
1627            age: i64,
1628            address: Address,
1629            tags: Vec<String>,
1630        }
1631
1632        let person = Person {
1633            name: "Bob".to_string(),
1634            age: 25,
1635            address: Address {
1636                street: "123 Main St".to_string(),
1637                city: "Springfield".to_string(),
1638                zip: "12345".to_string(),
1639            },
1640            tags: vec!["developer".to_string(), "rust".to_string()],
1641        };
1642
1643        // Test AgentData roundtrip with nested structures
1644        let agent_data = AgentValue::from_serialize(&person).unwrap();
1645        assert_eq!(agent_data.get_str("name"), Some("Bob"));
1646
1647        let address = agent_data.get_object("address").unwrap();
1648        assert_eq!(
1649            address.get("city").and_then(|v| v.as_str()),
1650            Some("Springfield")
1651        );
1652
1653        let tags = agent_data.get_array("tags").unwrap();
1654        assert_eq!(tags.len(), 2);
1655        assert_eq!(tags[0].as_str(), Some("developer"));
1656
1657        let restored: Person = agent_data.to_deserialize().unwrap();
1658        assert_eq!(restored, person);
1659    }
1660
1661    #[test]
1662    fn test_agent_value_conversions() {
1663        // Boolean
1664        assert_eq!(AgentValue::boolean(true).to_boolean(), Some(true));
1665        assert_eq!(AgentValue::integer(1).to_boolean(), Some(true));
1666        assert_eq!(AgentValue::integer(0).to_boolean(), Some(false));
1667        assert_eq!(AgentValue::number(1.0).to_boolean(), Some(true));
1668        assert_eq!(AgentValue::number(0.0).to_boolean(), Some(false));
1669        assert_eq!(AgentValue::string("true").to_boolean(), Some(true));
1670        assert_eq!(AgentValue::string("false").to_boolean(), Some(false));
1671        assert_eq!(AgentValue::unit().to_boolean(), None);
1672
1673        let bool_arr = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(0)]);
1674        let converted = bool_arr.to_boolean_value().unwrap();
1675        assert!(converted.is_array());
1676        let arr = converted.as_array().unwrap();
1677        assert_eq!(arr[0], AgentValue::boolean(true));
1678        assert_eq!(arr[1], AgentValue::boolean(false));
1679
1680        // Integer
1681        assert_eq!(AgentValue::integer(42).to_integer(), Some(42));
1682        assert_eq!(AgentValue::boolean(true).to_integer(), Some(1));
1683        assert_eq!(AgentValue::boolean(false).to_integer(), Some(0));
1684        assert_eq!(AgentValue::number(42.9).to_integer(), Some(42));
1685        assert_eq!(AgentValue::string("42").to_integer(), Some(42));
1686        assert_eq!(AgentValue::unit().to_integer(), None);
1687
1688        let int_arr =
1689            AgentValue::array(vector![AgentValue::string("10"), AgentValue::boolean(true)]);
1690        let converted = int_arr.to_integer_value().unwrap();
1691        assert!(converted.is_array());
1692        let arr = converted.as_array().unwrap();
1693        assert_eq!(arr[0], AgentValue::integer(10));
1694        assert_eq!(arr[1], AgentValue::integer(1));
1695
1696        // Number
1697        assert_eq!(AgentValue::number(3.14).to_number(), Some(3.14));
1698        assert_eq!(AgentValue::integer(42).to_number(), Some(42.0));
1699        assert_eq!(AgentValue::boolean(true).to_number(), Some(1.0));
1700        assert_eq!(AgentValue::string("3.14").to_number(), Some(3.14));
1701        assert_eq!(AgentValue::unit().to_number(), None);
1702
1703        let num_arr =
1704            AgentValue::array(vector![AgentValue::integer(10), AgentValue::string("0.5")]);
1705        let converted = num_arr.to_number_value().unwrap();
1706        assert!(converted.is_array());
1707        let arr = converted.as_array().unwrap();
1708        assert_eq!(arr[0], AgentValue::number(10.0));
1709        assert_eq!(arr[1], AgentValue::number(0.5));
1710
1711        // String
1712        assert_eq!(
1713            AgentValue::string("hello").to_string(),
1714            Some("hello".to_string())
1715        );
1716        assert_eq!(AgentValue::integer(42).to_string(), Some("42".to_string()));
1717        assert_eq!(
1718            AgentValue::boolean(true).to_string(),
1719            Some("true".to_string())
1720        );
1721        assert_eq!(
1722            AgentValue::number(3.14).to_string(),
1723            Some("3.14".to_string())
1724        );
1725        assert_eq!(
1726            AgentValue::message(Message::user("content".to_string())).to_string(),
1727            Some("content".to_string())
1728        );
1729        assert_eq!(AgentValue::unit().to_string(), None);
1730
1731        let str_arr =
1732            AgentValue::array(vector![AgentValue::integer(42), AgentValue::boolean(false)]);
1733        let converted = str_arr.to_string_value().unwrap();
1734        assert!(converted.is_array());
1735        let arr = converted.as_array().unwrap();
1736        assert_eq!(arr[0], AgentValue::string("42"));
1737        assert_eq!(arr[1], AgentValue::string("false"));
1738    }
1739}