Use Structured Outputs with the Responses API
mainThe Responses API supports structured outputs by passing a class inheriting from OpenAI::BaseModel to the text parameter. The model is instructed to output JSON matching your schema, and the SDK automatically parses the content into instances of your class. Parsed objects are accessible via event.parsed on ResponseTextDoneEvent.
Example schema definition:
class Haiku < OpenAI::BaseModel
field :first_line, String
field :second_line, String
field :third_line, String
endclass Haiku < OpenAI::BaseModel
field :first_line, String
field :second_line, String
field :third_line, String
end
stream = client.responses.stream(
input: "Write a haiku about Ruby",
model: "gpt-4o",
text: Haiku
)
stream.each do |event|
case event
when OpenAI::Streaming::ResponseTextDoneEvent
haiku = event.parsed
puts(haiku.first_line)
end
end