Class: Rails::Llm::Structured::Schema
- Inherits:
-
Object
- Object
- Rails::Llm::Structured::Schema
- Defined in:
- lib/rails/llm/structured/schema.rb
Instance Attribute Summary collapse
-
#fields ⇒ Object
readonly
Returns the value of attribute fields.
Instance Method Summary collapse
- #field(name, type:, **options) ⇒ Object
-
#initialize(&block) ⇒ Schema
constructor
A new instance of Schema.
- #to_json_schema ⇒ Object
- #validate!(data) ⇒ Object
Constructor Details
#initialize(&block) ⇒ Schema
Returns a new instance of Schema.
9 10 11 12 |
# File 'lib/rails/llm/structured/schema.rb', line 9 def initialize(&block) @fields = {} instance_eval(&block) if block_given? end |
Instance Attribute Details
#fields ⇒ Object (readonly)
Returns the value of attribute fields.
7 8 9 |
# File 'lib/rails/llm/structured/schema.rb', line 7 def fields @fields end |
Instance Method Details
#field(name, type:, **options) ⇒ Object
14 15 16 |
# File 'lib/rails/llm/structured/schema.rb', line 14 def field(name, type:, **) @fields[name] = Field.new(name, type, ) end |
#to_json_schema ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/rails/llm/structured/schema.rb', line 18 def to_json_schema { type: "json_schema", json_schema: { name: "response", strict: true, schema: { type: "object", properties: fields_to_properties, required: required_fields, additionalProperties: false } } } end |
#validate!(data) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/rails/llm/structured/schema.rb', line 34 def validate!(data) @fields.each do |name, field| value = data[name.to_s] || data[name.to_sym] field.validate!(value) end # Create struct with validated data struct_class = Struct.new(*@fields.keys) values = @fields.keys.map { |key| data[key.to_s] || data[key.to_sym] } struct_class.new(*values) end |