ai_json_template/
ai_json_template_for_vec.rs

1// ---------------- [ File: ai-json-template/src/ai_json_template_for_vec.rs ]
2crate::ix!();
3
4/// Blanket impl for `Vec<T>` if `T: AiJsonTemplate`.
5///
6/// This treats the field as `"array_of"` in the JSON schema, referencing
7/// `T::to_template()` for the item template. We add disclaimers saying we
8/// expect a top-level JSON array, not item-level justification.
9impl<T> AiJsonTemplate for Vec<T>
10where
11    T: Send + Sync + AiJsonTemplate + 'static,
12{
13    fn to_template() -> JsonValue {
14        trace!(
15            "AiJsonTemplate::to_template for Vec<{}>",
16            type_name::<T>()
17        );
18
19        let mut obj = serde_json::Map::new();
20        obj.insert(
21            "type".to_string(),
22            JsonValue::String("array_of".to_string())
23        );
24
25        obj.insert(
26            "generation_instructions".to_string(),
27            JsonValue::String(format!("Provide a JSON array of items, each conforming to {}.", type_name::<T>()))
28        );
29
30        // Typically marked required, but the parent can override or interpret it
31        obj.insert("required".to_string(), JsonValue::Bool(true));
32
33        // The item template comes from T::to_template
34        let item_schema = T::to_template();
35        obj.insert("item_template".to_string(), item_schema);
36
37        JsonValue::Object(obj)
38    }
39}
40
41/// Blanket impl for `Vec<T>` if `T: AiJsonTemplateWithJustification`.
42///
43/// We add `"has_justification": true` at the array level, but again, we do
44/// not require or encourage justifying each element individually. Instead,
45/// we have a single top-level justification/confidence for the entire vector.
46impl<T> AiJsonTemplateWithJustification for Vec<T>
47where
48    T: Send + Sync + AiJsonTemplateWithJustification + 'static,
49{
50    fn to_template_with_justification() -> JsonValue {
51        trace!(
52            "AiJsonTemplateWithJustification::to_template_with_justification for Vec<{}>",
53            type_name::<T>()
54        );
55
56        let mut obj = serde_json::Map::new();
57
58        obj.insert(
59            "type".to_string(),
60            JsonValue::String("array_of".to_string())
61        );
62
63        obj.insert("required".to_string(), JsonValue::Bool(true));
64
65        // Indicate that top-level justification might exist for this entire array
66        obj.insert("has_justification".to_string(), JsonValue::Bool(true));
67
68        obj.insert(
69            "generation_instructions".to_string(),
70            JsonValue::String(format!("Provide a JSON array of items, each conforming to {}. We do not want you to justify each individual element.", type_name::<T>()))
71        );
72
73        // The item schema for nested types
74        let item_schema = T::to_template_with_justification();
75        obj.insert("item_template".to_string(), item_schema);
76
77        JsonValue::Object(obj)
78    }
79}