liteforge 0.2.3

Rust SDK for LiteForge - LLM completions via OpenAI-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! JSON Schema validation for tool arguments.

use serde_json::Value;
use std::fmt;

/// Error returned when JSON schema validation fails.
#[derive(Debug, Clone)]
pub struct SchemaValidationError {
    pub path: String,
    pub message: String,
}

impl fmt::Display for SchemaValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(f, "at '{}': {}", self.path, self.message)
        }
    }
}

impl std::error::Error for SchemaValidationError {}

/// Validate a JSON value against a JSON schema.
///
/// This is a simplified validator that handles common cases:
/// - type validation (string, number, integer, boolean, array, object, null)
/// - required properties
/// - enum validation
/// - minimum/maximum for numbers
/// - minLength/maxLength for strings
/// - minItems/maxItems for arrays
///
/// # Example
///
/// ```
/// use liteforge::tools::validate_json_schema;
/// use serde_json::json;
///
/// let schema = json!({
///     "type": "object",
///     "properties": {
///         "name": { "type": "string" },
///         "age": { "type": "integer", "minimum": 0 }
///     },
///     "required": ["name"]
/// });
///
/// let valid = json!({"name": "Alice", "age": 30});
/// assert!(validate_json_schema(&valid, &schema).is_ok());
///
/// let invalid = json!({"age": -5});  // missing required "name"
/// assert!(validate_json_schema(&invalid, &schema).is_err());
/// ```
pub fn validate_json_schema(
    value: &Value,
    schema: &Value,
) -> Result<(), Vec<SchemaValidationError>> {
    let mut errors = Vec::new();
    validate_value(value, schema, "", &mut errors);

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn validate_value(
    value: &Value,
    schema: &Value,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    // Handle anyOf, oneOf, allOf
    if let Some(any_of) = schema.get("anyOf") {
        if let Some(schemas) = any_of.as_array() {
            let mut any_valid = false;
            for s in schemas {
                let mut sub_errors = Vec::new();
                validate_value(value, s, path, &mut sub_errors);
                if sub_errors.is_empty() {
                    any_valid = true;
                    break;
                }
            }
            if !any_valid {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: "value does not match any of the schemas".to_string(),
                });
            }
        }
        return;
    }

    // Check type
    if let Some(type_value) = schema.get("type") {
        let type_valid = match type_value.as_str() {
            Some("string") => value.is_string(),
            Some("number") => value.is_number(),
            Some("integer") => value.is_i64() || value.is_u64(),
            Some("boolean") => value.is_boolean(),
            Some("array") => value.is_array(),
            Some("object") => value.is_object(),
            Some("null") => value.is_null(),
            _ => true, // Unknown type, skip validation
        };

        if !type_valid {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!(
                    "expected type '{}', got '{}'",
                    type_value.as_str().unwrap_or("unknown"),
                    json_type_name(value)
                ),
            });
            return; // Don't continue validation if type is wrong
        }
    }

    // Validate based on type
    if value.is_string() {
        validate_string(value.as_str().unwrap(), schema, path, errors);
    } else if value.is_number() {
        validate_number(value, schema, path, errors);
    } else if value.is_array() {
        validate_array(value.as_array().unwrap(), schema, path, errors);
    } else if value.is_object() {
        validate_object(value.as_object().unwrap(), schema, path, errors);
    }

    // Check enum
    if let Some(enum_values) = schema.get("enum") {
        if let Some(variants) = enum_values.as_array() {
            if !variants.contains(value) {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: format!("value must be one of {:?}", variants),
                });
            }
        }
    }

    // Check const
    if let Some(const_value) = schema.get("const") {
        if value != const_value {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!("value must be {:?}", const_value),
            });
        }
    }
}

fn validate_string(
    value: &str,
    schema: &Value,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    if let Some(min_length) = schema.get("minLength").and_then(|v| v.as_u64()) {
        if (value.len() as u64) < min_length {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!(
                    "string length {} is less than minimum {}",
                    value.len(),
                    min_length
                ),
            });
        }
    }

    if let Some(max_length) = schema.get("maxLength").and_then(|v| v.as_u64()) {
        if (value.len() as u64) > max_length {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!(
                    "string length {} is greater than maximum {}",
                    value.len(),
                    max_length
                ),
            });
        }
    }

    if let Some(pattern) = schema.get("pattern").and_then(|v| v.as_str()) {
        if let Ok(re) = regex::Regex::new(pattern) {
            if !re.is_match(value) {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: format!("string does not match pattern '{}'", pattern),
                });
            }
        }
    }
}

fn validate_number(
    value: &Value,
    schema: &Value,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    let num = value.as_f64().unwrap_or(0.0);

    if let Some(minimum) = schema.get("minimum").and_then(|v| v.as_f64()) {
        if num < minimum {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!("value {} is less than minimum {}", num, minimum),
            });
        }
    }

    if let Some(maximum) = schema.get("maximum").and_then(|v| v.as_f64()) {
        if num > maximum {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!("value {} is greater than maximum {}", num, maximum),
            });
        }
    }

    if let Some(exclusive_minimum) = schema.get("exclusiveMinimum").and_then(|v| v.as_f64()) {
        if num <= exclusive_minimum {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!("value {} must be greater than {}", num, exclusive_minimum),
            });
        }
    }

    if let Some(exclusive_maximum) = schema.get("exclusiveMaximum").and_then(|v| v.as_f64()) {
        if num >= exclusive_maximum {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!("value {} must be less than {}", num, exclusive_maximum),
            });
        }
    }
}

fn validate_array(
    value: &[Value],
    schema: &Value,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    if let Some(min_items) = schema.get("minItems").and_then(|v| v.as_u64()) {
        if (value.len() as u64) < min_items {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!(
                    "array length {} is less than minimum {}",
                    value.len(),
                    min_items
                ),
            });
        }
    }

    if let Some(max_items) = schema.get("maxItems").and_then(|v| v.as_u64()) {
        if (value.len() as u64) > max_items {
            errors.push(SchemaValidationError {
                path: path.to_string(),
                message: format!(
                    "array length {} is greater than maximum {}",
                    value.len(),
                    max_items
                ),
            });
        }
    }

    // Validate items
    if let Some(items_schema) = schema.get("items") {
        for (i, item) in value.iter().enumerate() {
            let item_path = format!("{}[{}]", path, i);
            validate_value(item, items_schema, &item_path, errors);
        }
    }
}

fn validate_object(
    value: &serde_json::Map<String, Value>,
    schema: &Value,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    // Check required properties
    if let Some(required) = schema.get("required").and_then(|v| v.as_array()) {
        for req in required {
            if let Some(prop_name) = req.as_str() {
                if !value.contains_key(prop_name) {
                    errors.push(SchemaValidationError {
                        path: path.to_string(),
                        message: format!("missing required property '{}'", prop_name),
                    });
                }
            }
        }
    }

    // Validate properties
    if let Some(properties) = schema.get("properties").and_then(|v| v.as_object()) {
        for (prop_name, prop_schema) in properties {
            if let Some(prop_value) = value.get(prop_name) {
                let prop_path = if path.is_empty() {
                    prop_name.clone()
                } else {
                    format!("{}.{}", path, prop_name)
                };
                validate_value(prop_value, prop_schema, &prop_path, errors);
            }
        }
    }

    // Check additional properties
    if let Some(additional) = schema.get("additionalProperties") {
        if additional.as_bool() == Some(false) {
            if let Some(properties) = schema.get("properties").and_then(|v| v.as_object()) {
                for key in value.keys() {
                    if !properties.contains_key(key) {
                        errors.push(SchemaValidationError {
                            path: path.to_string(),
                            message: format!("additional property '{}' is not allowed", key),
                        });
                    }
                }
            }
        }
    }
}

fn json_type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(n) if n.is_i64() || n.is_u64() => "integer",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_validate_type_string() {
        let schema = json!({"type": "string"});

        assert!(validate_json_schema(&json!("hello"), &schema).is_ok());
        assert!(validate_json_schema(&json!(123), &schema).is_err());
    }

    #[test]
    fn test_validate_type_number() {
        let schema = json!({"type": "number"});

        assert!(validate_json_schema(&json!(123), &schema).is_ok());
        assert!(validate_json_schema(&json!(12.5), &schema).is_ok());
        assert!(validate_json_schema(&json!("hello"), &schema).is_err());
    }

    #[test]
    fn test_validate_type_integer() {
        let schema = json!({"type": "integer"});

        assert!(validate_json_schema(&json!(123), &schema).is_ok());
        // Note: 12.0 is stored as integer in serde_json
        assert!(validate_json_schema(&json!("hello"), &schema).is_err());
    }

    #[test]
    fn test_validate_required() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"}
            },
            "required": ["name"]
        });

        assert!(validate_json_schema(&json!({"name": "Alice"}), &schema).is_ok());
        assert!(validate_json_schema(&json!({"age": 30}), &schema).is_err());
    }

    #[test]
    fn test_validate_enum() {
        let schema = json!({
            "type": "string",
            "enum": ["red", "green", "blue"]
        });

        assert!(validate_json_schema(&json!("red"), &schema).is_ok());
        assert!(validate_json_schema(&json!("yellow"), &schema).is_err());
    }

    #[test]
    fn test_validate_minimum_maximum() {
        let schema = json!({
            "type": "number",
            "minimum": 0,
            "maximum": 100
        });

        assert!(validate_json_schema(&json!(50), &schema).is_ok());
        assert!(validate_json_schema(&json!(-1), &schema).is_err());
        assert!(validate_json_schema(&json!(101), &schema).is_err());
    }

    #[test]
    fn test_validate_string_length() {
        let schema = json!({
            "type": "string",
            "minLength": 2,
            "maxLength": 10
        });

        assert!(validate_json_schema(&json!("hello"), &schema).is_ok());
        assert!(validate_json_schema(&json!("a"), &schema).is_err());
        assert!(validate_json_schema(&json!("this is too long"), &schema).is_err());
    }

    #[test]
    fn test_validate_array_items() {
        let schema = json!({
            "type": "array",
            "items": {"type": "integer"},
            "minItems": 1,
            "maxItems": 3
        });

        assert!(validate_json_schema(&json!([1, 2, 3]), &schema).is_ok());
        assert!(validate_json_schema(&json!([]), &schema).is_err()); // too few
        assert!(validate_json_schema(&json!([1, 2, 3, 4]), &schema).is_err()); // too many
        assert!(validate_json_schema(&json!([1, "two", 3]), &schema).is_err()); // wrong type
    }

    #[test]
    fn test_validate_nested_object() {
        let schema = json!({
            "type": "object",
            "properties": {
                "person": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"}
                    },
                    "required": ["name"]
                }
            },
            "required": ["person"]
        });

        assert!(validate_json_schema(&json!({"person": {"name": "Alice"}}), &schema).is_ok());
        assert!(validate_json_schema(&json!({"person": {}}), &schema).is_err());
    }
}