Skip to content

Produce a JSON schema through the composition of simple Ruby objects

Notifications You must be signed in to change notification settings

llmrb/json-schema

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

About

llmrb-json_schema is a small, dependency-free library that can produce a JSON Schema through the composition of simple Ruby objects. It is an optional dependency of llmrb/llm where it is used to describe the response a Large Language Model (LLM) is expected to produce.

Examples

Object

The following example demonstrates how to produce a schema that describes a theoretical object with three properties: name, age, and salary. Some properties are required, others have a default, and some have a range of values:

#!/usr/bin/env ruby
require "json"
require "json/schema"

schema = JSON::Schema.new
schema.object({
  name: schema.string.required,
  age: schema.number.default(18),
  salary: schema.number.min(65_000).max(120_000)
})

print JSON.pretty_generate(schema.to_h), "\n"

Array

The following example demonstrates how to produce a schema that describes an array of objects. It builds on the previous example by allowing an array of objects with the same properties, and it also allows the array to include "null" values:

#!/usr/bin/env ruby
require "json"
require "json/schema"

schema = JSON::Schema.new
schema.array(
  schema.object({
    name: schema.string.required,
    age: schema.number.default(18),
    salary: schema.number.min(65_000).max(120_000)
  }),
  schema.null
)

print JSON.pretty_generate(schema.to_h), "\n"

Constraints

Generally each JSON value can have certain constraints, such as a minimum or maximum value, whether or not it is a required item in an object, or has a default value. We have seen some of these in the previous examples. The following example demonstrates a few more. See the API reference for a complete list of constraints on a per-value basis:

#!/usr/bin/env ruby
require "json"
require "json/schema"

schema = JSON::Schema.new
schema.object({
  name: schema.string.required,
  age: schema.number.default(18),
  salary: schema.number.min(65_000).max(120_000).multiple_of(5_000),
  is_employee: schema.boolean.default(true)
})

API reference

The README tries to provide a high-level overview of the library. For everything else there's the API reference. It covers classes and methods that the README glances over or doesn't cover at all. The API reference is available at 0x1eef.github.io/x/llmrb-json_schema.

See also

Install

llmrb-json_schema is available via RubyGems

gem install llmrb-json_schema

License

BSD Zero Clause
See LICENSE

About

Produce a JSON schema through the composition of simple Ruby objects

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages