Module: Whoosh::AI::StructuredOutput

Defined in:
lib/whoosh/ai/structured_output.rb

Overview

Validates LLM output against a Whoosh::Schema

Class Method Summary collapse

Class Method Details

.prompt_for(schema) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/whoosh/ai/structured_output.rb', line 13

def self.prompt_for(schema)
  return "" unless schema.respond_to?(:fields)

  lines = schema.fields.map do |name, opts|
    type = OpenAPI::SchemaConverter.type_for(opts[:type])
    parts = ["#{name}: #{type}"]
    parts << "(required)" if opts[:required]
    parts << "#{opts[:desc]}" if opts[:desc]
    parts << "[min: #{opts[:min]}]" if opts[:min]
    parts << "[max: #{opts[:max]}]" if opts[:max]
    parts << "[default: #{opts[:default]}]" if opts.key?(:default)
    "  #{parts.join(" ")}"
  end

  "Return ONLY valid JSON matching this schema:\n{\n#{lines.join(",\n")}\n}"
end

.validate(data, schema:) ⇒ Object



7
8
9
10
11
# File 'lib/whoosh/ai/structured_output.rb', line 7

def self.validate(data, schema:)
  result = schema.validate(data)
  return result.data if result.success?
  raise Errors::ValidationError.new(result.errors)
end