Expand description
§JSON Schema Builder
This module provides functionality for building JSON schemas that can be used with OpenAI’s structured output features. JSON schemas define the expected structure and format of data, allowing AI models to generate responses that conform to specific formats.
§Features
- Type Safety: Strongly typed schema construction
- Flexible Properties: Support for various JSON types (string, number, boolean, array, object)
- Nested Structures: Support for complex nested objects and arrays
- Validation: Built-in validation through required fields and type constraints
- Serialization: Direct serialization to JSON for API consumption
§Common Use Cases
- Data Extraction: Extract structured information from unstructured text
- Form Generation: Generate forms with specific field requirements
- API Responses: Ensure consistent response formats
- Configuration: Define configuration schema for applications
§Example
use openai_tools::structured_output::Schema;
// Create a schema for a person object
let mut schema = Schema::chat_json_schema("person".to_string());
// Add basic properties
schema.add_property(
"name".to_string(),
"string".to_string(),
Some("The person's full name".to_string())
);
schema.add_property(
"age".to_string(),
"number".to_string(),
Some("The person's age in years".to_string())
);
// Add an array property
schema.add_array(
"hobbies".to_string(),
vec![
("name".to_string(), "The name of the hobby".to_string()),
("level".to_string(), "Skill level (beginner, intermediate, advanced)".to_string()),
]
);
// Convert to JSON for use with OpenAI API
let json_string = serde_json::to_string(&schema).unwrap();
println!("{}", json_string);