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 Unit,
22 Boolean(bool),
23 Integer(i64),
24 Number(f64),
25
26 String(Arc<String>),
28
29 #[cfg(feature = "image")]
30 Image(Arc<PhotonImage>),
31
32 Array(Vector<AgentValue>),
34 Object(HashMap<String, AgentValue>),
35
36 Tensor(Arc<Vec<f32>>),
38
39 Message(Arc<Message>),
41
42 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, }
211 }
212
213 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 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 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 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 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 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 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 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 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 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 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 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 #[allow(clippy::inherent_to_string)]
439 pub fn to_string(&self) -> Option<String> {
440 match self {
441 AgentValue::String(s) => Some(s.as_ref().clone()),
442 AgentValue::Boolean(b) => Some(b.to_string()),
443 AgentValue::Integer(i) => Some(i.to_string()),
444 AgentValue::Number(n) => Some(n.to_string()),
445 AgentValue::Message(m) => Some(m.content.clone()),
446 _ => None,
447 }
448 }
449
450 pub fn to_string_value(&self) -> Option<AgentValue> {
452 match self {
453 AgentValue::String(_) => Some(self.clone()),
454 AgentValue::Array(arr) => {
455 if arr.iter().all(|v| v.is_string()) {
456 return Some(self.clone());
457 }
458 let mut new_arr = Vector::new();
459 for item in arr {
460 new_arr.push_back(item.to_string_value()?);
461 }
462 Some(AgentValue::Array(new_arr))
463 }
464 _ => self.to_string().map(AgentValue::string),
465 }
466 }
467
468 pub fn to_message(&self) -> Option<Message> {
470 Message::try_from(self.clone()).ok()
471 }
472
473 pub fn to_message_value(&self) -> Option<AgentValue> {
476 match self {
477 AgentValue::Message(_) => Some(self.clone()),
478 AgentValue::Array(arr) => {
479 if arr.iter().all(|v| v.is_message()) {
480 return Some(self.clone());
481 }
482 let mut new_arr = Vector::new();
483 for item in arr {
484 new_arr.push_back(item.to_message_value()?);
485 }
486 Some(AgentValue::Array(new_arr))
487 }
488 _ => Message::try_from(self.clone())
489 .ok()
490 .map(|m| AgentValue::message(m)),
491 }
492 }
493
494 pub fn as_object(&self) -> Option<&AgentValueMap<String, AgentValue>> {
495 match self {
496 AgentValue::Object(o) => Some(o),
497 _ => None,
498 }
499 }
500
501 pub fn as_object_mut(&mut self) -> Option<&mut AgentValueMap<String, AgentValue>> {
502 match self {
503 AgentValue::Object(o) => Some(o),
504 _ => None,
505 }
506 }
507
508 pub fn into_object(self) -> Option<AgentValueMap<String, AgentValue>> {
511 match self {
512 AgentValue::Object(o) => Some(o),
513 _ => None,
514 }
515 }
516
517 pub fn as_array(&self) -> Option<&Vector<AgentValue>> {
518 match self {
519 AgentValue::Array(a) => Some(a),
520 _ => None,
521 }
522 }
523
524 pub fn as_array_mut(&mut self) -> Option<&mut Vector<AgentValue>> {
525 match self {
526 AgentValue::Array(a) => Some(a),
527 _ => None,
528 }
529 }
530
531 pub fn into_array(self) -> Option<Vector<AgentValue>> {
534 match self {
535 AgentValue::Array(a) => Some(a),
536 _ => None,
537 }
538 }
539
540 pub fn as_tensor(&self) -> Option<&Vec<f32>> {
541 match self {
542 AgentValue::Tensor(t) => Some(t),
543 _ => None,
544 }
545 }
546
547 pub fn as_tensor_mut(&mut self) -> Option<&mut Vec<f32>> {
548 match self {
549 AgentValue::Tensor(t) => Some(Arc::make_mut(t)),
550 _ => None,
551 }
552 }
553
554 pub fn into_tensor(self) -> Option<Arc<Vec<f32>>> {
557 match self {
558 AgentValue::Tensor(t) => Some(t),
559 _ => None,
560 }
561 }
562
563 pub fn into_tensor_vec(self) -> Option<Vec<f32>> {
568 match self {
569 AgentValue::Tensor(t) => Some(Arc::unwrap_or_clone(t)),
570 _ => None,
571 }
572 }
573
574 pub fn get(&self, key: &str) -> Option<&AgentValue> {
577 self.as_object().and_then(|o| o.get(key))
578 }
579
580 pub fn get_mut(&mut self, key: &str) -> Option<&mut AgentValue> {
581 self.as_object_mut().and_then(|o| o.get_mut(key))
582 }
583
584 pub fn get_bool(&self, key: &str) -> Option<bool> {
585 self.get(key).and_then(|v| v.as_bool())
586 }
587
588 pub fn get_i64(&self, key: &str) -> Option<i64> {
589 self.get(key).and_then(|v| v.as_i64())
590 }
591
592 pub fn get_f64(&self, key: &str) -> Option<f64> {
593 self.get(key).and_then(|v| v.as_f64())
594 }
595
596 pub fn get_str(&self, key: &str) -> Option<&str> {
597 self.get(key).and_then(|v| v.as_str())
598 }
599
600 #[cfg(feature = "image")]
601 pub fn get_image(&self, key: &str) -> Option<&PhotonImage> {
602 self.get(key).and_then(|v| v.as_image())
603 }
604
605 #[cfg(feature = "image")]
606 pub fn get_image_mut(&mut self, key: &str) -> Option<&mut PhotonImage> {
607 self.get_mut(key).and_then(|v| v.as_image_mut())
608 }
609
610 pub fn get_object(&self, key: &str) -> Option<&AgentValueMap<String, AgentValue>> {
611 self.get(key).and_then(|v| v.as_object())
612 }
613
614 pub fn get_object_mut(&mut self, key: &str) -> Option<&mut AgentValueMap<String, AgentValue>> {
615 self.get_mut(key).and_then(|v| v.as_object_mut())
616 }
617
618 pub fn get_array(&self, key: &str) -> Option<&Vector<AgentValue>> {
619 self.get(key).and_then(|v| v.as_array())
620 }
621
622 pub fn get_array_mut(&mut self, key: &str) -> Option<&mut Vector<AgentValue>> {
623 self.get_mut(key).and_then(|v| v.as_array_mut())
624 }
625
626 pub fn get_tensor(&self, key: &str) -> Option<&Vec<f32>> {
627 self.get(key).and_then(|v| v.as_tensor())
628 }
629
630 pub fn get_tensor_mut(&mut self, key: &str) -> Option<&mut Vec<f32>> {
631 self.get_mut(key).and_then(|v| v.as_tensor_mut())
632 }
633
634 pub fn get_message(&self, key: &str) -> Option<&Message> {
635 self.get(key).and_then(|v| v.as_message())
636 }
637
638 pub fn get_message_mut(&mut self, key: &str) -> Option<&mut Message> {
639 self.get_mut(key).and_then(|v| v.as_message_mut())
640 }
641
642 pub fn set(&mut self, key: String, value: AgentValue) -> Result<(), AgentError> {
645 if let Some(obj) = self.as_object_mut() {
646 obj.insert(key, value);
647 Ok(())
648 } else {
649 Err(AgentError::InvalidValue(
650 "set can only be called on Object AgentValue".into(),
651 ))
652 }
653 }
654}
655
656impl Default for AgentValue {
657 fn default() -> Self {
658 AgentValue::Unit
659 }
660}
661
662impl PartialEq for AgentValue {
663 fn eq(&self, other: &Self) -> bool {
664 match (self, other) {
665 (AgentValue::Unit, AgentValue::Unit) => true,
666 (AgentValue::Boolean(b1), AgentValue::Boolean(b2)) => b1 == b2,
667 (AgentValue::Integer(i1), AgentValue::Integer(i2)) => i1 == i2,
668 (AgentValue::Number(n1), AgentValue::Number(n2)) => n1 == n2,
669 (AgentValue::String(s1), AgentValue::String(s2)) => s1 == s2,
670 #[cfg(feature = "image")]
671 (AgentValue::Image(i1), AgentValue::Image(i2)) => {
672 i1.get_width() == i2.get_width()
673 && i1.get_height() == i2.get_height()
674 && i1.get_raw_pixels() == i2.get_raw_pixels()
675 }
676 (AgentValue::Array(a1), AgentValue::Array(a2)) => a1 == a2,
677 (AgentValue::Object(o1), AgentValue::Object(o2)) => o1 == o2,
678 (AgentValue::Tensor(t1), AgentValue::Tensor(t2)) => t1 == t2,
679 (AgentValue::Message(m1), AgentValue::Message(m2)) => m1 == m2,
680 _ => false,
681 }
682 }
683}
684
685impl Serialize for AgentValue {
686 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
687 where
688 S: Serializer,
689 {
690 match self {
691 AgentValue::Unit => serializer.serialize_none(),
692 AgentValue::Boolean(b) => serializer.serialize_bool(*b),
693 AgentValue::Integer(i) => serializer.serialize_i64(*i),
694 AgentValue::Number(n) => serializer.serialize_f64(*n),
695 AgentValue::String(s) => serializer.serialize_str(s),
696 #[cfg(feature = "image")]
697 AgentValue::Image(img) => serializer.serialize_str(&img.get_base64()),
698 AgentValue::Array(a) => {
699 let mut seq = serializer.serialize_seq(Some(a.len()))?;
700 for e in a.iter() {
701 seq.serialize_element(e)?;
702 }
703 seq.end()
704 }
705 AgentValue::Object(o) => {
706 let mut map = serializer.serialize_map(Some(o.len()))?;
707 let mut entries: Vec<_> = o.iter().collect();
709 entries.sort_by(|a, b| a.0.cmp(b.0));
710
711 for (k, v) in entries {
712 map.serialize_entry(k, v)?;
713 }
714 map.end()
715 }
716 AgentValue::Tensor(t) => {
717 let mut seq = serializer.serialize_seq(Some(t.len()))?;
718 for e in t.iter() {
719 seq.serialize_element(e)?;
720 }
721 seq.end()
722 }
723 AgentValue::Message(m) => m.serialize(serializer),
724 AgentValue::Error(_) => serializer.serialize_none(), }
726 }
727}
728
729impl<'de> Deserialize<'de> for AgentValue {
730 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
731 where
732 D: Deserializer<'de>,
733 {
734 let value = serde_json::Value::deserialize(deserializer)?;
735 AgentValue::from_json(value).map_err(|e| {
736 serde::de::Error::custom(format!("Failed to deserialize AgentValue: {}", e))
737 })
738 }
739}
740
741impl From<()> for AgentValue {
742 fn from(_: ()) -> Self {
743 AgentValue::unit()
744 }
745}
746
747impl From<bool> for AgentValue {
748 fn from(value: bool) -> Self {
749 AgentValue::boolean(value)
750 }
751}
752
753impl From<i32> for AgentValue {
754 fn from(value: i32) -> Self {
755 AgentValue::integer(value as i64)
756 }
757}
758
759impl From<i64> for AgentValue {
760 fn from(value: i64) -> Self {
761 AgentValue::integer(value)
762 }
763}
764
765impl From<usize> for AgentValue {
766 fn from(value: usize) -> Self {
767 AgentValue::Integer(value as i64)
768 }
769}
770
771impl From<u64> for AgentValue {
772 fn from(value: u64) -> Self {
773 AgentValue::Integer(value as i64)
774 }
775}
776
777impl From<f32> for AgentValue {
778 fn from(value: f32) -> Self {
779 AgentValue::Number(value as f64)
780 }
781}
782
783impl From<f64> for AgentValue {
784 fn from(value: f64) -> Self {
785 AgentValue::number(value)
786 }
787}
788
789impl From<String> for AgentValue {
790 fn from(value: String) -> Self {
791 AgentValue::string(value)
792 }
793}
794
795impl From<&str> for AgentValue {
796 fn from(value: &str) -> Self {
797 AgentValue::string(value)
798 }
799}
800
801impl From<Vector<AgentValue>> for AgentValue {
802 fn from(value: Vector<AgentValue>) -> Self {
803 AgentValue::Array(value)
804 }
805}
806
807impl From<HashMap<String, AgentValue>> for AgentValue {
808 fn from(value: HashMap<String, AgentValue>) -> Self {
809 AgentValue::Object(value)
810 }
811}
812
813impl From<Vec<f32>> for AgentValue {
815 fn from(value: Vec<f32>) -> Self {
816 AgentValue::Tensor(Arc::new(value))
817 }
818}
819impl From<Arc<Vec<f32>>> for AgentValue {
820 fn from(value: Arc<Vec<f32>>) -> Self {
821 AgentValue::Tensor(value)
822 }
823}
824
825impl From<Vec<AgentValue>> for AgentValue {
827 fn from(value: Vec<AgentValue>) -> Self {
828 AgentValue::Array(Vector::from(value))
829 }
830}
831impl From<std::collections::HashMap<String, AgentValue>> for AgentValue {
832 fn from(value: std::collections::HashMap<String, AgentValue>) -> Self {
833 AgentValue::Object(HashMap::from(value))
834 }
835}
836
837impl From<AgentError> for AgentValue {
839 fn from(value: AgentError) -> Self {
840 AgentValue::Error(Arc::new(value))
841 }
842}
843
844impl From<Option<AgentValue>> for AgentValue {
846 fn from(value: Option<AgentValue>) -> Self {
847 value.unwrap_or(AgentValue::Unit)
848 }
849}
850
851#[cfg(test)]
852mod tests {
853 use super::*;
854 use im::{hashmap, vector};
855 use serde_json::json;
856
857 #[test]
858 fn test_partial_eq() {
859 let unit1 = AgentValue::unit();
861 let unit2 = AgentValue::unit();
862 assert_eq!(unit1, unit2);
863
864 let boolean1 = AgentValue::boolean(true);
865 let boolean2 = AgentValue::boolean(true);
866 assert_eq!(boolean1, boolean2);
867
868 let integer1 = AgentValue::integer(42);
869 let integer2 = AgentValue::integer(42);
870 assert_eq!(integer1, integer2);
871 let different = AgentValue::integer(100);
872 assert_ne!(integer1, different);
873
874 let number1 = AgentValue::number(3.14);
875 let number2 = AgentValue::number(3.14);
876 assert_eq!(number1, number2);
877
878 let string1 = AgentValue::string("hello");
879 let string2 = AgentValue::string("hello");
880 assert_eq!(string1, string2);
881
882 #[cfg(feature = "image")]
883 {
884 let image1 = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
885 let image2 = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
886 assert_eq!(image1, image2);
887 }
888
889 let obj1 = AgentValue::object(hashmap! {
890 "key1".into() => AgentValue::string("value1"),
891 "key2".into() => AgentValue::integer(2),
892 });
893 let obj2 = AgentValue::object(hashmap! {
894 "key1".to_string() => AgentValue::string("value1"),
895 "key2".to_string() => AgentValue::integer(2),
896 });
897 assert_eq!(obj1, obj2);
898
899 let arr1 = AgentValue::array(vector![
900 AgentValue::integer(1),
901 AgentValue::string("two"),
902 AgentValue::boolean(true),
903 ]);
904 let arr2 = AgentValue::array(vector![
905 AgentValue::integer(1),
906 AgentValue::string("two"),
907 AgentValue::boolean(true),
908 ]);
909 assert_eq!(arr1, arr2);
910
911 let mixed_types_1 = AgentValue::boolean(true);
912 let mixed_types_2 = AgentValue::integer(1);
913 assert_ne!(mixed_types_1, mixed_types_2);
914
915 let msg1 = AgentValue::message(Message::user("hello".to_string()));
916 let msg2 = AgentValue::message(Message::user("hello".to_string()));
917 assert_eq!(msg1, msg2);
918 }
919
920 #[test]
921 fn test_agent_value_constructors() {
922 let unit = AgentValue::unit();
924 assert_eq!(unit, AgentValue::Unit);
925
926 let boolean = AgentValue::boolean(true);
927 assert_eq!(boolean, AgentValue::Boolean(true));
928
929 let integer = AgentValue::integer(42);
930 assert_eq!(integer, AgentValue::Integer(42));
931
932 let number = AgentValue::number(3.14);
933 assert!(matches!(number, AgentValue::Number(_)));
934 if let AgentValue::Number(num) = number {
935 assert!((num - 3.14).abs() < f64::EPSILON);
936 }
937
938 let string = AgentValue::string("hello");
939 assert!(matches!(string, AgentValue::String(_)));
940 assert_eq!(string.as_str().unwrap(), "hello");
941
942 let text = AgentValue::string("multiline\ntext");
943 assert!(matches!(text, AgentValue::String(_)));
944 assert_eq!(text.as_str().unwrap(), "multiline\ntext");
945
946 let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
947 assert!(matches!(array, AgentValue::Array(_)));
948 if let AgentValue::Array(arr) = array {
949 assert_eq!(arr.len(), 2);
950 assert_eq!(arr[0].as_i64().unwrap(), 1);
951 assert_eq!(arr[1].as_i64().unwrap(), 2);
952 }
953
954 let obj = AgentValue::object(hashmap! {
955 "key1".to_string() => AgentValue::string("string1"),
956 "key2".to_string() => AgentValue::integer(2),
957 });
958 assert!(matches!(obj, AgentValue::Object(_)));
959 if let AgentValue::Object(obj) = obj {
960 assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
961 assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
962 } else {
963 panic!("Object was not deserialized correctly");
964 }
965
966 let msg = AgentValue::message(Message::user("hello".to_string()));
967 assert!(matches!(msg, AgentValue::Message(_)));
968 }
969
970 #[test]
971 fn test_agent_value_from_json_value() {
972 let null = AgentValue::from_json(json!(null)).unwrap();
974 assert_eq!(null, AgentValue::Unit);
975
976 let boolean = AgentValue::from_json(json!(true)).unwrap();
977 assert_eq!(boolean, AgentValue::Boolean(true));
978
979 let integer = AgentValue::from_json(json!(42)).unwrap();
980 assert_eq!(integer, AgentValue::Integer(42));
981
982 let number = AgentValue::from_json(json!(3.14)).unwrap();
983 assert!(matches!(number, AgentValue::Number(_)));
984 if let AgentValue::Number(num) = number {
985 assert!((num - 3.14).abs() < f64::EPSILON);
986 }
987
988 let string = AgentValue::from_json(json!("hello")).unwrap();
989 assert!(matches!(string, AgentValue::String(_)));
990 if let AgentValue::String(s) = string {
991 assert_eq!(*s, "hello");
992 } else {
993 panic!("Expected string value");
994 }
995
996 let array = AgentValue::from_json(json!([1, "test", true])).unwrap();
997 assert!(matches!(array, AgentValue::Array(_)));
998 if let AgentValue::Array(arr) = array {
999 assert_eq!(arr.len(), 3);
1000 assert_eq!(arr[0], AgentValue::Integer(1));
1001 assert!(matches!(&arr[1], AgentValue::String(_)));
1002 if let AgentValue::String(s) = &arr[1] {
1003 assert_eq!(**s, "test");
1004 } else {
1005 panic!("Expected string value");
1006 }
1007 assert_eq!(arr[2], AgentValue::Boolean(true));
1008 }
1009
1010 let object = AgentValue::from_json(json!({"key1": "string1", "key2": 2})).unwrap();
1011 assert!(matches!(object, AgentValue::Object(_)));
1012 if let AgentValue::Object(obj) = object {
1013 assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
1014 assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
1015 } else {
1016 panic!("Object was not deserialized correctly");
1017 }
1018 }
1019
1020 #[test]
1021 fn test_agent_value_test_methods() {
1022 let unit = AgentValue::unit();
1024 assert_eq!(unit.is_unit(), true);
1025 assert_eq!(unit.is_boolean(), false);
1026 assert_eq!(unit.is_integer(), false);
1027 assert_eq!(unit.is_number(), false);
1028 assert_eq!(unit.is_string(), false);
1029 assert_eq!(unit.is_array(), false);
1030 assert_eq!(unit.is_object(), false);
1031 #[cfg(feature = "image")]
1032 assert_eq!(unit.is_image(), false);
1033
1034 let boolean = AgentValue::boolean(true);
1035 assert_eq!(boolean.is_unit(), false);
1036 assert_eq!(boolean.is_boolean(), true);
1037 assert_eq!(boolean.is_integer(), false);
1038 assert_eq!(boolean.is_number(), false);
1039 assert_eq!(boolean.is_string(), false);
1040 assert_eq!(boolean.is_array(), false);
1041 assert_eq!(boolean.is_object(), false);
1042 #[cfg(feature = "image")]
1043 assert_eq!(boolean.is_image(), false);
1044
1045 let integer = AgentValue::integer(42);
1046 assert_eq!(integer.is_unit(), false);
1047 assert_eq!(integer.is_boolean(), false);
1048 assert_eq!(integer.is_integer(), true);
1049 assert_eq!(integer.is_number(), false);
1050 assert_eq!(integer.is_string(), false);
1051 assert_eq!(integer.is_array(), false);
1052 assert_eq!(integer.is_object(), false);
1053 #[cfg(feature = "image")]
1054 assert_eq!(integer.is_image(), false);
1055
1056 let number = AgentValue::number(3.14);
1057 assert_eq!(number.is_unit(), false);
1058 assert_eq!(number.is_boolean(), false);
1059 assert_eq!(number.is_integer(), false);
1060 assert_eq!(number.is_number(), true);
1061 assert_eq!(number.is_string(), false);
1062 assert_eq!(number.is_array(), false);
1063 assert_eq!(number.is_object(), false);
1064 #[cfg(feature = "image")]
1065 assert_eq!(number.is_image(), false);
1066
1067 let string = AgentValue::string("hello");
1068 assert_eq!(string.is_unit(), false);
1069 assert_eq!(string.is_boolean(), false);
1070 assert_eq!(string.is_integer(), false);
1071 assert_eq!(string.is_number(), false);
1072 assert_eq!(string.is_string(), true);
1073 assert_eq!(string.is_array(), false);
1074 assert_eq!(string.is_object(), false);
1075 #[cfg(feature = "image")]
1076 assert_eq!(string.is_image(), false);
1077
1078 let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1079 assert_eq!(array.is_unit(), false);
1080 assert_eq!(array.is_boolean(), false);
1081 assert_eq!(array.is_integer(), false);
1082 assert_eq!(array.is_number(), false);
1083 assert_eq!(array.is_string(), false);
1084 assert_eq!(array.is_array(), true);
1085 assert_eq!(array.is_object(), false);
1086 #[cfg(feature = "image")]
1087 assert_eq!(array.is_image(), false);
1088
1089 let obj = AgentValue::object(hashmap! {
1090 "key1".to_string() => AgentValue::string("string1"),
1091 "key2".to_string() => AgentValue::integer(2),
1092 });
1093 assert_eq!(obj.is_unit(), false);
1094 assert_eq!(obj.is_boolean(), false);
1095 assert_eq!(obj.is_integer(), false);
1096 assert_eq!(obj.is_number(), false);
1097 assert_eq!(obj.is_string(), false);
1098 assert_eq!(obj.is_array(), false);
1099 assert_eq!(obj.is_object(), true);
1100 #[cfg(feature = "image")]
1101 assert_eq!(obj.is_image(), false);
1102
1103 #[cfg(feature = "image")]
1104 {
1105 let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1106 assert_eq!(img.is_unit(), false);
1107 assert_eq!(img.is_boolean(), false);
1108 assert_eq!(img.is_integer(), false);
1109 assert_eq!(img.is_number(), false);
1110 assert_eq!(img.is_string(), false);
1111 assert_eq!(img.is_array(), false);
1112 assert_eq!(img.is_object(), false);
1113 assert_eq!(img.is_image(), true);
1114 }
1115
1116 let msg = AgentValue::message(Message::user("hello".to_string()));
1117 assert_eq!(msg.is_unit(), false);
1118 assert_eq!(msg.is_boolean(), false);
1119 assert_eq!(msg.is_integer(), false);
1120 assert_eq!(msg.is_number(), false);
1121 assert_eq!(msg.is_string(), false);
1122 assert_eq!(msg.is_array(), false);
1123 assert_eq!(msg.is_object(), false);
1124 #[cfg(feature = "image")]
1125 assert_eq!(msg.is_image(), false);
1126 assert_eq!(msg.is_message(), true);
1127 }
1128
1129 #[test]
1130 fn test_agent_value_as_methods() {
1131 let boolean = AgentValue::boolean(true);
1133 assert_eq!(boolean.as_bool(), Some(true));
1134 assert_eq!(boolean.as_i64(), None);
1135 assert_eq!(boolean.as_f64(), None);
1136 assert_eq!(boolean.as_str(), None);
1137 assert!(boolean.as_array().is_none());
1138 assert_eq!(boolean.as_object(), None);
1139 #[cfg(feature = "image")]
1140 assert!(boolean.as_image().is_none());
1141
1142 let integer = AgentValue::integer(42);
1143 assert_eq!(integer.as_bool(), None);
1144 assert_eq!(integer.as_i64(), Some(42));
1145 assert_eq!(integer.as_f64(), Some(42.0));
1146 assert_eq!(integer.as_str(), None);
1147 assert!(integer.as_array().is_none());
1148 assert_eq!(integer.as_object(), None);
1149 #[cfg(feature = "image")]
1150 assert!(integer.as_image().is_none());
1151
1152 let number = AgentValue::number(3.14);
1153 assert_eq!(number.as_bool(), None);
1154 assert_eq!(number.as_i64(), Some(3)); assert_eq!(number.as_f64().unwrap(), 3.14);
1156 assert_eq!(number.as_str(), None);
1157 assert!(number.as_array().is_none());
1158 assert_eq!(number.as_object(), None);
1159 #[cfg(feature = "image")]
1160 assert!(number.as_image().is_none());
1161
1162 let string = AgentValue::string("hello");
1163 assert_eq!(string.as_bool(), None);
1164 assert_eq!(string.as_i64(), None);
1165 assert_eq!(string.as_f64(), None);
1166 assert_eq!(string.as_str(), Some("hello"));
1167 assert!(string.as_array().is_none());
1168 assert_eq!(string.as_object(), None);
1169 #[cfg(feature = "image")]
1170 assert!(string.as_image().is_none());
1171
1172 let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1173 assert_eq!(array.as_bool(), None);
1174 assert_eq!(array.as_i64(), None);
1175 assert_eq!(array.as_f64(), None);
1176 assert_eq!(array.as_str(), None);
1177 assert!(array.as_array().is_some());
1178 if let Some(arr) = array.as_array() {
1179 assert_eq!(arr.len(), 2);
1180 assert_eq!(arr[0].as_i64().unwrap(), 1);
1181 assert_eq!(arr[1].as_i64().unwrap(), 2);
1182 }
1183 assert_eq!(array.as_object(), None);
1184 #[cfg(feature = "image")]
1185 assert!(array.as_image().is_none());
1186
1187 let mut array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1188 if let Some(arr) = array.as_array_mut() {
1189 arr.push_back(AgentValue::integer(3));
1190 }
1191
1192 let obj = AgentValue::object(hashmap! {
1193 "key1".to_string() => AgentValue::string("string1"),
1194 "key2".to_string() => AgentValue::integer(2),
1195 });
1196 assert_eq!(obj.as_bool(), None);
1197 assert_eq!(obj.as_i64(), None);
1198 assert_eq!(obj.as_f64(), None);
1199 assert_eq!(obj.as_str(), None);
1200 assert!(obj.as_array().is_none());
1201 assert!(obj.as_object().is_some());
1202 if let Some(value) = obj.as_object() {
1203 assert_eq!(value.get("key1").and_then(|v| v.as_str()), Some("string1"));
1204 assert_eq!(value.get("key2").and_then(|v| v.as_i64()), Some(2));
1205 }
1206 #[cfg(feature = "image")]
1207 assert!(obj.as_image().is_none());
1208
1209 let mut obj = AgentValue::object(hashmap! {
1210 "key1".to_string() => AgentValue::string("string1"),
1211 "key2".to_string() => AgentValue::integer(2),
1212 });
1213 if let Some(value) = obj.as_object_mut() {
1214 value.insert("key3".to_string(), AgentValue::boolean(true));
1215 }
1216
1217 #[cfg(feature = "image")]
1218 {
1219 let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1220 assert_eq!(img.as_bool(), None);
1221 assert_eq!(img.as_i64(), None);
1222 assert_eq!(img.as_f64(), None);
1223 assert_eq!(img.as_str(), None);
1224 assert!(img.as_array().is_none());
1225 assert_eq!(img.as_object(), None);
1226 assert!(img.as_image().is_some());
1227 }
1228
1229 let mut msg = AgentValue::message(Message::user("hello".to_string()));
1230 assert!(msg.as_message().is_some());
1231 assert_eq!(msg.as_message().unwrap().content, "hello");
1232 assert!(msg.as_message_mut().is_some());
1233 if let Some(m) = msg.as_message_mut() {
1234 m.content = "world".to_string();
1235 }
1236 assert_eq!(msg.as_message().unwrap().content, "world");
1237 assert!(msg.into_message().is_some());
1238 }
1239
1240 #[test]
1241 fn test_agent_value_get_methods() {
1242 const KEY: &str = "key";
1244
1245 let boolean = AgentValue::boolean(true);
1246 assert_eq!(boolean.get(KEY), None);
1247
1248 let integer = AgentValue::integer(42);
1249 assert_eq!(integer.get(KEY), None);
1250
1251 let number = AgentValue::number(3.14);
1252 assert_eq!(number.get(KEY), None);
1253
1254 let string = AgentValue::string("hello");
1255 assert_eq!(string.get(KEY), None);
1256
1257 let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1258 assert_eq!(array.get(KEY), None);
1259
1260 let mut array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(2)]);
1261 assert_eq!(array.get_mut(KEY), None);
1262
1263 let mut obj = AgentValue::object(hashmap! {
1264 "k_boolean".to_string() => AgentValue::boolean(true),
1265 "k_integer".to_string() => AgentValue::integer(42),
1266 "k_number".to_string() => AgentValue::number(3.14),
1267 "k_string".to_string() => AgentValue::string("string1"),
1268 "k_array".to_string() => AgentValue::array(vector![AgentValue::integer(1)]),
1269 "k_object".to_string() => AgentValue::object(hashmap! {
1270 "inner_key".to_string() => AgentValue::integer(100),
1271 }),
1272 #[cfg(feature = "image")]
1273 "k_image".to_string() => AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1)),
1274 "k_message".to_string() => AgentValue::message(Message::user("hello".to_string())),
1275 });
1276 assert_eq!(obj.get(KEY), None);
1277 assert_eq!(obj.get_bool("k_boolean"), Some(true));
1278 assert_eq!(obj.get_i64("k_integer"), Some(42));
1279 assert_eq!(obj.get_f64("k_number"), Some(3.14));
1280 assert_eq!(obj.get_str("k_string"), Some("string1"));
1281 assert!(obj.get_array("k_array").is_some());
1282 assert!(obj.get_array_mut("k_array").is_some());
1283 assert!(obj.get_object("k_object").is_some());
1284 assert!(obj.get_object_mut("k_object").is_some());
1285 #[cfg(feature = "image")]
1286 assert!(obj.get_image("k_image").is_some());
1287 assert!(obj.get_message("k_message").is_some());
1288 assert!(obj.get_message_mut("k_message").is_some());
1289
1290 #[cfg(feature = "image")]
1291 {
1292 let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1293 assert_eq!(img.get(KEY), None);
1294 }
1295 }
1296
1297 #[test]
1298 fn test_agent_value_set() {
1299 let mut obj = AgentValue::object(AgentValueMap::new());
1301 assert!(obj.set("key1".to_string(), AgentValue::integer(42)).is_ok());
1302 assert_eq!(obj.get_i64("key1"), Some(42));
1303
1304 let mut not_obj = AgentValue::integer(10);
1305 assert!(
1306 not_obj
1307 .set("key1".to_string(), AgentValue::integer(42))
1308 .is_err()
1309 );
1310 }
1311
1312 #[test]
1313 fn test_agent_value_default() {
1314 assert_eq!(AgentValue::default(), AgentValue::Unit);
1315
1316 assert_eq!(AgentValue::boolean_default(), AgentValue::Boolean(false));
1317 assert_eq!(AgentValue::integer_default(), AgentValue::Integer(0));
1318 assert_eq!(AgentValue::number_default(), AgentValue::Number(0.0));
1319 assert_eq!(
1320 AgentValue::string_default(),
1321 AgentValue::String(Arc::new(String::new()))
1322 );
1323 assert_eq!(
1324 AgentValue::array_default(),
1325 AgentValue::Array(Vector::new())
1326 );
1327 assert_eq!(
1328 AgentValue::object_default(),
1329 AgentValue::Object(AgentValueMap::new())
1330 );
1331
1332 #[cfg(feature = "image")]
1333 {
1334 assert_eq!(
1335 AgentValue::image_default(),
1336 AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1))
1337 );
1338 }
1339 }
1340
1341 #[test]
1342 fn test_to_json() {
1343 let unit = AgentValue::unit();
1345 assert_eq!(unit.to_json(), json!(null));
1346
1347 let boolean = AgentValue::boolean(true);
1348 assert_eq!(boolean.to_json(), json!(true));
1349
1350 let integer = AgentValue::integer(42);
1351 assert_eq!(integer.to_json(), json!(42));
1352
1353 let number = AgentValue::number(3.14);
1354 assert_eq!(number.to_json(), json!(3.14));
1355
1356 let string = AgentValue::string("hello");
1357 assert_eq!(string.to_json(), json!("hello"));
1358
1359 let array = AgentValue::array(vector![AgentValue::integer(1), AgentValue::string("test")]);
1360 assert_eq!(array.to_json(), json!([1, "test"]));
1361
1362 let obj = AgentValue::object(hashmap! {
1363 "key1".to_string() => AgentValue::string("string1"),
1364 "key2".to_string() => AgentValue::integer(2),
1365 });
1366 assert_eq!(obj.to_json(), json!({"key1": "string1", "key2": 2}));
1367
1368 #[cfg(feature = "image")]
1369 {
1370 let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1371 assert_eq!(
1372 img.to_json(),
1373 json!(
1374 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg=="
1375 )
1376 );
1377 }
1378
1379 let msg = AgentValue::message(Message::user("hello".to_string()));
1380 assert_eq!(
1381 msg.to_json(),
1382 json!({
1383 "role": "user",
1384 "content": "hello",
1385 })
1386 );
1387 }
1388
1389 #[test]
1390 fn test_agent_value_serialization() {
1391 {
1393 let null = AgentValue::Unit;
1394 assert_eq!(serde_json::to_string(&null).unwrap(), "null");
1395 }
1396
1397 {
1399 let boolean_t = AgentValue::boolean(true);
1400 assert_eq!(serde_json::to_string(&boolean_t).unwrap(), "true");
1401
1402 let boolean_f = AgentValue::boolean(false);
1403 assert_eq!(serde_json::to_string(&boolean_f).unwrap(), "false");
1404 }
1405
1406 {
1408 let integer = AgentValue::integer(42);
1409 assert_eq!(serde_json::to_string(&integer).unwrap(), "42");
1410 }
1411
1412 {
1414 let num = AgentValue::number(3.14);
1415 assert_eq!(serde_json::to_string(&num).unwrap(), "3.14");
1416
1417 let num = AgentValue::number(3.0);
1418 assert_eq!(serde_json::to_string(&num).unwrap(), "3.0");
1419 }
1420
1421 {
1423 let s = AgentValue::string("Hello, world!");
1424 assert_eq!(serde_json::to_string(&s).unwrap(), "\"Hello, world!\"");
1425
1426 let s = AgentValue::string("hello\nworld\n\n");
1427 assert_eq!(serde_json::to_string(&s).unwrap(), r#""hello\nworld\n\n""#);
1428 }
1429
1430 #[cfg(feature = "image")]
1432 {
1433 let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1434 assert_eq!(
1435 serde_json::to_string(&img).unwrap(),
1436 r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#
1437 );
1438 }
1439
1440 #[cfg(feature = "image")]
1442 {
1443 let img = AgentValue::image_arc(Arc::new(PhotonImage::new(vec![0u8; 4], 1, 1)));
1444 assert_eq!(
1445 serde_json::to_string(&img).unwrap(),
1446 r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#
1447 );
1448 }
1449
1450 {
1452 let array = AgentValue::array(vector![
1453 AgentValue::integer(1),
1454 AgentValue::string("test"),
1455 AgentValue::object(hashmap! {
1456 "key1".to_string() => AgentValue::string("test"),
1457 "key2".to_string() => AgentValue::integer(2),
1458 }),
1459 ]);
1460 assert_eq!(
1461 serde_json::to_string(&array).unwrap(),
1462 r#"[1,"test",{"key1":"test","key2":2}]"#
1463 );
1464 }
1465
1466 {
1468 let obj = AgentValue::object(hashmap! {
1469 "key1".to_string() => AgentValue::string("test"),
1470 "key2".to_string() => AgentValue::integer(3),
1471 });
1472 assert_eq!(
1473 serde_json::to_string(&obj).unwrap(),
1474 r#"{"key1":"test","key2":3}"#
1475 );
1476 }
1477 }
1478
1479 #[test]
1480 fn test_agent_value_deserialization() {
1481 {
1483 let deserialized: AgentValue = serde_json::from_str("null").unwrap();
1484 assert_eq!(deserialized, AgentValue::Unit);
1485 }
1486
1487 {
1489 let deserialized: AgentValue = serde_json::from_str("false").unwrap();
1490 assert_eq!(deserialized, AgentValue::boolean(false));
1491
1492 let deserialized: AgentValue = serde_json::from_str("true").unwrap();
1493 assert_eq!(deserialized, AgentValue::boolean(true));
1494 }
1495
1496 {
1498 let deserialized: AgentValue = serde_json::from_str("123").unwrap();
1499 assert_eq!(deserialized, AgentValue::integer(123));
1500 }
1501
1502 {
1504 let deserialized: AgentValue = serde_json::from_str("3.14").unwrap();
1505 assert_eq!(deserialized, AgentValue::number(3.14));
1506
1507 let deserialized: AgentValue = serde_json::from_str("3.0").unwrap();
1508 assert_eq!(deserialized, AgentValue::number(3.0));
1509 }
1510
1511 {
1513 let deserialized: AgentValue = serde_json::from_str("\"Hello, world!\"").unwrap();
1514 assert_eq!(deserialized, AgentValue::string("Hello, world!"));
1515
1516 let deserialized: AgentValue = serde_json::from_str(r#""hello\nworld\n\n""#).unwrap();
1517 assert_eq!(deserialized, AgentValue::string("hello\nworld\n\n"));
1518 }
1519
1520 #[cfg(feature = "image")]
1522 {
1523 let deserialized: AgentValue = serde_json::from_str(
1524 r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#,
1525 )
1526 .unwrap();
1527 assert!(matches!(deserialized, AgentValue::Image(_)));
1528 }
1529
1530 {
1532 let deserialized: AgentValue =
1533 serde_json::from_str(r#"[1,"test",{"key1":"test","key2":2}]"#).unwrap();
1534 assert!(matches!(deserialized, AgentValue::Array(_)));
1535 if let AgentValue::Array(arr) = deserialized {
1536 assert_eq!(arr.len(), 3, "Array length mismatch after serialization");
1537 assert_eq!(arr[0], AgentValue::integer(1));
1538 assert_eq!(arr[1], AgentValue::string("test"));
1539 assert_eq!(
1540 arr[2],
1541 AgentValue::object(hashmap! {
1542 "key1".to_string() => AgentValue::string("test"),
1543 "key2".to_string() => AgentValue::integer(2),
1544 })
1545 );
1546 }
1547 }
1548
1549 {
1551 let deserialized: AgentValue =
1552 serde_json::from_str(r#"{"key1":"test","key2":3}"#).unwrap();
1553 assert_eq!(
1554 deserialized,
1555 AgentValue::object(hashmap! {
1556 "key1".to_string() => AgentValue::string("test"),
1557 "key2".to_string() => AgentValue::integer(3),
1558 })
1559 );
1560 }
1561 }
1562
1563 #[test]
1564 fn test_agent_value_into() {
1565 let from_unit: AgentValue = ().into();
1567 assert_eq!(from_unit, AgentValue::Unit);
1568
1569 let from_bool: AgentValue = true.into();
1570 assert_eq!(from_bool, AgentValue::Boolean(true));
1571
1572 let from_i32: AgentValue = 42i32.into();
1573 assert_eq!(from_i32, AgentValue::Integer(42));
1574
1575 let from_i64: AgentValue = 100i64.into();
1576 assert_eq!(from_i64, AgentValue::Integer(100));
1577
1578 let from_f64: AgentValue = 3.14f64.into();
1579 assert_eq!(from_f64, AgentValue::Number(3.14));
1580
1581 let from_string: AgentValue = "hello".to_string().into();
1582 assert_eq!(
1583 from_string,
1584 AgentValue::String(Arc::new("hello".to_string()))
1585 );
1586
1587 let from_str: AgentValue = "world".into();
1588 assert_eq!(from_str, AgentValue::String(Arc::new("world".to_string())));
1589 }
1590
1591 #[test]
1592 fn test_serialize_deserialize_roundtrip() {
1593 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1594 struct TestStruct {
1595 name: String,
1596 age: i64,
1597 active: bool,
1598 }
1599
1600 let test_data = TestStruct {
1601 name: "Alice".to_string(),
1602 age: 30,
1603 active: true,
1604 };
1605
1606 let agent_data = AgentValue::from_serialize(&test_data).unwrap();
1608 assert_eq!(agent_data.get_str("name"), Some("Alice"));
1609 assert_eq!(agent_data.get_i64("age"), Some(30));
1610 assert_eq!(agent_data.get_bool("active"), Some(true));
1611
1612 let restored: TestStruct = agent_data.to_deserialize().unwrap();
1613 assert_eq!(restored, test_data);
1614 }
1615
1616 #[test]
1617 fn test_serialize_deserialize_nested() {
1618 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1619 struct Address {
1620 street: String,
1621 city: String,
1622 zip: String,
1623 }
1624
1625 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1626 struct Person {
1627 name: String,
1628 age: i64,
1629 address: Address,
1630 tags: Vec<String>,
1631 }
1632
1633 let person = Person {
1634 name: "Bob".to_string(),
1635 age: 25,
1636 address: Address {
1637 street: "123 Main St".to_string(),
1638 city: "Springfield".to_string(),
1639 zip: "12345".to_string(),
1640 },
1641 tags: vec!["developer".to_string(), "rust".to_string()],
1642 };
1643
1644 let agent_data = AgentValue::from_serialize(&person).unwrap();
1646 assert_eq!(agent_data.get_str("name"), Some("Bob"));
1647
1648 let address = agent_data.get_object("address").unwrap();
1649 assert_eq!(
1650 address.get("city").and_then(|v| v.as_str()),
1651 Some("Springfield")
1652 );
1653
1654 let tags = agent_data.get_array("tags").unwrap();
1655 assert_eq!(tags.len(), 2);
1656 assert_eq!(tags[0].as_str(), Some("developer"));
1657
1658 let restored: Person = agent_data.to_deserialize().unwrap();
1659 assert_eq!(restored, person);
1660 }
1661
1662 #[test]
1663 fn test_agent_value_conversions() {
1664 assert_eq!(AgentValue::boolean(true).to_boolean(), Some(true));
1666 assert_eq!(AgentValue::integer(1).to_boolean(), Some(true));
1667 assert_eq!(AgentValue::integer(0).to_boolean(), Some(false));
1668 assert_eq!(AgentValue::number(1.0).to_boolean(), Some(true));
1669 assert_eq!(AgentValue::number(0.0).to_boolean(), Some(false));
1670 assert_eq!(AgentValue::string("true").to_boolean(), Some(true));
1671 assert_eq!(AgentValue::string("false").to_boolean(), Some(false));
1672 assert_eq!(AgentValue::unit().to_boolean(), None);
1673
1674 let bool_arr = AgentValue::array(vector![AgentValue::integer(1), AgentValue::integer(0)]);
1675 let converted = bool_arr.to_boolean_value().unwrap();
1676 assert!(converted.is_array());
1677 let arr = converted.as_array().unwrap();
1678 assert_eq!(arr[0], AgentValue::boolean(true));
1679 assert_eq!(arr[1], AgentValue::boolean(false));
1680
1681 assert_eq!(AgentValue::integer(42).to_integer(), Some(42));
1683 assert_eq!(AgentValue::boolean(true).to_integer(), Some(1));
1684 assert_eq!(AgentValue::boolean(false).to_integer(), Some(0));
1685 assert_eq!(AgentValue::number(42.9).to_integer(), Some(42));
1686 assert_eq!(AgentValue::string("42").to_integer(), Some(42));
1687 assert_eq!(AgentValue::unit().to_integer(), None);
1688
1689 let int_arr =
1690 AgentValue::array(vector![AgentValue::string("10"), AgentValue::boolean(true)]);
1691 let converted = int_arr.to_integer_value().unwrap();
1692 assert!(converted.is_array());
1693 let arr = converted.as_array().unwrap();
1694 assert_eq!(arr[0], AgentValue::integer(10));
1695 assert_eq!(arr[1], AgentValue::integer(1));
1696
1697 assert_eq!(AgentValue::number(3.14).to_number(), Some(3.14));
1699 assert_eq!(AgentValue::integer(42).to_number(), Some(42.0));
1700 assert_eq!(AgentValue::boolean(true).to_number(), Some(1.0));
1701 assert_eq!(AgentValue::string("3.14").to_number(), Some(3.14));
1702 assert_eq!(AgentValue::unit().to_number(), None);
1703
1704 let num_arr =
1705 AgentValue::array(vector![AgentValue::integer(10), AgentValue::string("0.5")]);
1706 let converted = num_arr.to_number_value().unwrap();
1707 assert!(converted.is_array());
1708 let arr = converted.as_array().unwrap();
1709 assert_eq!(arr[0], AgentValue::number(10.0));
1710 assert_eq!(arr[1], AgentValue::number(0.5));
1711
1712 assert_eq!(
1714 AgentValue::string("hello").to_string(),
1715 Some("hello".to_string())
1716 );
1717 assert_eq!(AgentValue::integer(42).to_string(), Some("42".to_string()));
1718 assert_eq!(
1719 AgentValue::boolean(true).to_string(),
1720 Some("true".to_string())
1721 );
1722 assert_eq!(
1723 AgentValue::number(3.14).to_string(),
1724 Some("3.14".to_string())
1725 );
1726 assert_eq!(
1727 AgentValue::message(Message::user("content".to_string())).to_string(),
1728 Some("content".to_string())
1729 );
1730 assert_eq!(AgentValue::unit().to_string(), None);
1731
1732 let str_arr =
1733 AgentValue::array(vector![AgentValue::integer(42), AgentValue::boolean(false)]);
1734 let converted = str_arr.to_string_value().unwrap();
1735 assert!(converted.is_array());
1736 let arr = converted.as_array().unwrap();
1737 assert_eq!(arr[0], AgentValue::string("42"));
1738 assert_eq!(arr[1], AgentValue::string("false"));
1739 }
1740}