-
-
Notifications
You must be signed in to change notification settings - Fork 235
Add Schema builder for Structured Outputs #90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c81af10
Add structured output class and tests for the class
danielfriis 5f670ea
Focus on schema building only
danielfriis 3802eb5
Use .json_schema instead of .to_hash
danielfriis a135389
Clean up specs
danielfriis 59b84a9
Merge branch 'main' into feature/structured_output
danielfriis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
# frozen_string_literal: true | ||
|
||
module RubyLLM | ||
module StructuredOutput | ||
class Schema | ||
MAX_OBJECT_PROPERTIES = 100 | ||
MAX_NESTING_DEPTH = 5 | ||
|
||
class << self | ||
def string(name = nil, enum: nil, description: nil) | ||
schema = { type: 'string', enum: enum, description: description }.compact | ||
name ? add_property(name, schema) : schema | ||
end | ||
|
||
def number(name = nil, description: nil) | ||
schema = { type: 'number', description: description }.compact | ||
name ? add_property(name, schema) : schema | ||
end | ||
|
||
def boolean(name = nil, description: nil) | ||
schema = { type: 'boolean', description: description }.compact | ||
name ? add_property(name, schema) : schema | ||
end | ||
|
||
def null(name = nil, description: nil) | ||
schema = { type: 'null', description: description }.compact | ||
name ? add_property(name, schema) : schema | ||
end | ||
|
||
def object(name = nil, description: nil, &block) | ||
sub_schema = Class.new(Schema) | ||
sub_schema.class_eval(&block) | ||
|
||
schema = { | ||
type: 'object', | ||
properties: sub_schema.properties, | ||
required: sub_schema.required, | ||
additionalProperties: false, | ||
description: description | ||
}.compact | ||
|
||
name ? add_property(name, schema) : schema | ||
end | ||
|
||
def array(name, type = nil, description: nil, &block) | ||
items = if block_given? | ||
collector = SchemaCollector.new | ||
collector.instance_eval(&block) | ||
collector.schemas.first | ||
elsif type.is_a?(Symbol) | ||
case type | ||
when :string, :number, :boolean, :null | ||
send(type) | ||
else | ||
ref(type) | ||
end | ||
else | ||
raise ArgumentError, "Invalid array type: #{type}" | ||
end | ||
|
||
add_property(name, { | ||
type: 'array', | ||
description: description, | ||
items: items | ||
}.compact) | ||
end | ||
|
||
def any_of(name, description: nil, &block) | ||
collector = SchemaCollector.new | ||
collector.instance_eval(&block) | ||
|
||
add_property(name, { | ||
description: description, | ||
anyOf: collector.schemas | ||
}.compact) | ||
end | ||
|
||
def ref(schema_name) | ||
{ '$ref' => "#/$defs/#{schema_name}" } | ||
end | ||
|
||
def properties | ||
@properties ||= {} | ||
end | ||
|
||
def required | ||
@required ||= [] | ||
end | ||
|
||
def definitions | ||
@definitions ||= {} | ||
end | ||
|
||
def define(name, &) | ||
sub_schema = Class.new(Schema) | ||
sub_schema.class_eval(&) | ||
|
||
definitions[name] = { | ||
type: 'object', | ||
properties: sub_schema.properties, | ||
required: sub_schema.required | ||
} | ||
end | ||
|
||
private | ||
|
||
def add_property(name, definition) | ||
properties[name.to_sym] = definition | ||
required << name.to_sym | ||
end | ||
end | ||
|
||
# Simple collector that just stores schemas | ||
class SchemaCollector | ||
attr_reader :schemas | ||
|
||
def initialize | ||
@schemas = [] | ||
end | ||
|
||
def method_missing(method_name, ...) | ||
if Schema.respond_to?(method_name) | ||
@schemas << Schema.send(method_name, ...) | ||
else | ||
super | ||
end | ||
end | ||
|
||
def respond_to_missing?(method_name, include_private = false) | ||
Schema.respond_to?(method_name) || super | ||
end | ||
end | ||
|
||
def initialize(name = nil) | ||
@name = name || self.class.name | ||
validate_schema | ||
end | ||
|
||
def to_hash | ||
{ | ||
name: @name, | ||
description: 'Schema for the structured response', | ||
schema: { | ||
type: 'object', | ||
properties: self.class.properties, | ||
required: self.class.required, | ||
additionalProperties: false, | ||
strict: true, | ||
'$defs' => self.class.definitions | ||
} | ||
} | ||
end | ||
|
||
private | ||
|
||
# Validate the schema against defined limits | ||
def validate_schema | ||
properties_count = count_properties(self.class.properties) | ||
raise 'Exceeded maximum number of object properties' if properties_count > MAX_OBJECT_PROPERTIES | ||
|
||
max_depth = calculate_max_depth(self.class.properties) | ||
raise 'Exceeded maximum nesting depth' if max_depth > MAX_NESTING_DEPTH | ||
end | ||
|
||
# Count the total number of properties in the schema | ||
def count_properties(schema) | ||
return 0 unless schema.is_a?(Hash) && schema[:properties] | ||
|
||
count = schema[:properties].size | ||
schema[:properties].each_value do |prop| | ||
count += count_properties(prop) | ||
end | ||
count | ||
end | ||
|
||
# Calculate the maximum nesting depth of the schema | ||
def calculate_max_depth(schema, current_depth = 1) | ||
return current_depth unless schema.is_a?(Hash) | ||
|
||
if schema[:type] == 'object' && schema[:properties] | ||
child_depths = schema[:properties].values.map do |prop| | ||
calculate_max_depth(prop, current_depth + 1) | ||
end | ||
[current_depth, child_depths.max].compact.max | ||
elsif schema[:items] # For arrays | ||
calculate_max_depth(schema[:items], current_depth + 1) | ||
else | ||
current_depth | ||
end | ||
end | ||
|
||
def method_missing(method_name, ...) | ||
if respond_to_missing?(method_name) | ||
send(method_name, ...) | ||
else | ||
super | ||
end | ||
end | ||
|
||
def respond_to_missing?(method_name, include_private = false) | ||
%i[string number boolean array object any_of null].include?(method_name) || super | ||
end | ||
end | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.