Class: Riffer::StructuredOutput

Inherits:
Object
  • Object
show all
Defined in:
lib/riffer/structured_output.rb

Overview

Riffer::StructuredOutput provides parse/validate for structured JSON responses from LLM providers.

params = Riffer::Params.new
params.required(:sentiment, String)
so = Riffer::StructuredOutput.new(params)
result = so.parse_and_validate('{"sentiment":"positive","score":0.9}')
result.object  #=> {sentiment: "positive", score: 0.9}

Defined Under Namespace

Classes: Result

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ StructuredOutput

– : (Riffer::Params) -> void



20
21
22
# File 'lib/riffer/structured_output.rb', line 20

def initialize(params)
  @params = params
end

Instance Attribute Details

#paramsObject (readonly)

: Riffer::Params



16
17
18
# File 'lib/riffer/structured_output.rb', line 16

def params
  @params
end

Instance Method Details

#json_schema(strict: false) ⇒ Object

Returns the JSON Schema for this structured output.

– : (?strict: bool) -> Hash[Symbol, untyped]



28
29
30
# File 'lib/riffer/structured_output.rb', line 28

def json_schema(strict: false)
  @params.to_json_schema(strict: strict)
end

#parse_and_validate(json_string) ⇒ Object

Parses a JSON string and validates it against the schema.

Returns a Result with the validated object on success, or an error message on failure.

– : (String) -> Riffer::StructuredOutput::Result



38
39
40
41
42
43
44
45
46
# File 'lib/riffer/structured_output.rb', line 38

def parse_and_validate(json_string)
  parsed = JSON.parse(json_string, symbolize_names: true)
  validated = @params.validate(parsed)
  Result.new(object: validated)
rescue JSON::ParserError => e
  Result.new(error: "JSON parse error: #{e.message}")
rescue Riffer::ValidationError => e
  Result.new(error: "Validation error: #{e.message}")
end