Class: OmniAI::Schema::Format

Inherits:
Object
  • Object
show all
Defined in:
lib/omniai/schema/format.rb

Overview

Examples:

format = OmniAI::Schema::Format.deserialize({
  name: "example",
  schema: {
    type: "object",
    properties: {
      name: { type: "string" },
    },
    required: ["name"],
  }
})
format.serialize # => { name: "example", schema: { ... } }

Constant Summary collapse

BLOCK_REGEX =
/```(?:json)?\s*(?<text>.+)\s*```/m

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, schema:) ⇒ Format

Returns a new instance of Format.

Parameters:



46
47
48
49
# File 'lib/omniai/schema/format.rb', line 46

def initialize(name:, schema:)
  @name = name
  @schema = schema
end

Instance Attribute Details

#nameString

Returns:

  • (String)


22
23
24
# File 'lib/omniai/schema/format.rb', line 22

def name
  @name
end

#schemaOmniAI::Schema::Object



26
27
28
# File 'lib/omniai/schema/format.rb', line 26

def schema
  @schema
end

Class Method Details

.deserialize(data) ⇒ OmniAI::Schema::Format

Examples:

array = OmniAI::Schema::Format.deserialize({
  name: "Contact",
  schema: { ... },
}) # => OmniAI::Schema::Format

Parameters:

  • data (Hash)

Returns:



37
38
39
40
41
42
# File 'lib/omniai/schema/format.rb', line 37

def self.deserialize(data)
  name = data["name"] || data[:name]
  schema = OmniAI::Schema.deserialize(data["schema"] || data[:schema])

  new(name:, schema:)
end

Instance Method Details

#parse(text) ⇒ Hash

Examples:

format.parse("{ "name": "Ringo Starr" }"") # => { name: "Ringo Starr" }

Parameters:

  • text (String)

Returns:

  • (Hash)

Raises:

  • OmniAI::ParseError



72
73
74
75
76
77
78
79
# File 'lib/omniai/schema/format.rb', line 72

def parse(text)
  match = BLOCK_REGEX.match(text)
  text = match[:text] if match

  schema.parse(JSON.parse(text))
rescue JSON::ParserError => e
  raise OmniAI::ParseError, "Unable to parse JSON text=#{text.inspect} message=#{e.message.inspect}."
end

#promptString

A helper used for LLMs that do not support passing in a schema using a dedicated argument.

Examples:

format.prompt #=> "Your response must match the following schema: ..."

Returns:

  • (String)


87
88
89
90
91
92
93
94
95
# File 'lib/omniai/schema/format.rb', line 87

def prompt
  <<~TEXT
    Your must respond with ONLY valid JSON matching this exact schema:

    #{JSON.generate(schema.serialize)}

    Do not include any preamble, explanation, heredocs, etc. Return only the JSON.
  TEXT
end

#serialize(additional_properties: false) ⇒ Hash

Examples:

format.serialize # => { name: "...", schema: { ... } }

Parameters:

  • additional_properties (Boolean, nil) (defaults to: false)

    optional

Returns:

  • (Hash)


57
58
59
60
61
62
# File 'lib/omniai/schema/format.rb', line 57

def serialize(additional_properties: false)
  {
    name:,
    schema: schema.serialize(additional_properties:),
  }
end