Documentation
¶
Overview ¶
Package schema provides helpers to generate JSON Schemas from Go types and shape those schemas for LLM prompting. It is used throughout the project to derive structured parameter definitions and response formats from Go structs.
Core ideas
- Reflect Go structs and produce a jsonschema (draft-07) model.
- Convert reflected schema to a compact “function parameter” schema where top-level properties are flattened and $ref entries are resolved.
- Build OpenAI-style JSON Schema response formats to steer model outputs.
Common usage ¶
Generate a schema from a struct and use it as function parameters:
type Search struct {
Query string `json:"query" jsonschema:"description=Query to search"`
Type string `json:"type" jsonschema:"description=Type of search,enum=web,enum=image,default=web"`
}
s, err := New(reflect.TypeOf(Search{}))
if err != nil { /* handle */ }
_ = s.Parameters // jsonschema.Schema describing parameters
Build a response format (OpenAI style) from a type:
rf, err := NewResponseFormat(reflect.TypeOf(Search{}), true)
if err != nil { /* handle */ }
// rf.Type == "json_schema" and rf.JSONSchema contains the strict schema
You can also construct a schema from an arbitrary map using FromAny/MustFromAny when you want explicit control over the resulting structure.
Recursive types ¶
Schemas are generated without references, so a type that contains itself, such as type Node struct { Children []Node }, has no schema. New and JSONSchema return an error wrapping ErrRecursiveType for it; CheckRecursion runs the same check before reflecting with another reflector:
if _, err := New(reflect.TypeOf(Node{})); errors.Is(err, ErrRecursiveType) {
// break the cycle, for example with an `any` field
}
Index ¶
- Variables
- func CheckRecursion(t reflect.Type) error
- func FromAny(t any) (*jsonschema.Schema, error)
- func JSONSchema(t reflect.Type) (*jsonschema.Schema, error)
- func MustFromAny(t any) *jsonschema.Schema
- func ObjectFields(s *jsonschema.Schema) (properties map[string]any, required []string)
- func ToFunctionSchema(tType reflect.Type, tSchema *jsonschema.Schema) *jsonschema.Schema
- func ValidatePortableJSON(raw json.RawMessage, output string) error
- func ValidatePortableSchema(raw json.RawMessage, strict bool) error
- type Faker
- type ResponseFormat
- type ResponseFormatJSONSchema
- type ResponseFormatJSONSchemaProperty
- type Schema
Constants ¶
This section is empty.
Variables ¶
var ErrRecursiveType = errors.New("recursive type is not supported")
ErrRecursiveType is returned for a type that contains itself, such as type Node struct { Children []Node }. A schema without references cannot describe such a type, and references ($ref) are not used because several providers do not resolve them. Test for it with errors.Is.
Functions ¶
func CheckRecursion ¶ added in v1.0.178
CheckRecursion returns an error wrapping ErrRecursiveType when t contains itself, directly or through other types. Call it before reflecting t with an invopop/jsonschema Reflector that has DoNotReference set: such a reflector inlines every type and, on a recursive one, overflows the stack, a fatal error that recover cannot catch. New and JSONSchema call it for you. The error names the type and the path back to it.
It follows t as that reflector does: through pointers, slice and array elements, map values (not keys), and the struct fields it describes, with embedded structs and fields tagged json:",inline" merged into the parent. It skips unexported fields and fields tagged json:"-" or jsonschema:"-". It stops at interfaces, at types whose value receiver has a JSONSchema method, and at protobuf enums, and it follows the types returned by JSONSchemaAlias and JSONSchemaProperty. A type that only implements json.Marshaler or encoding.TextMarshaler is still reflected field by field, so it is still checked.
A type used more than once without containing itself, such as struct{ A, B Inner }, is not recursive.
func FromAny ¶ added in v0.10.55
func FromAny(t any) (*jsonschema.Schema, error)
FromAny creates a jsonschema.Schema from an arbitrary value, returning an error if the input is invalid.
func JSONSchema ¶
func JSONSchema(t reflect.Type) (*jsonschema.Schema, error)
JSONSchema returns the jsonschema model for a type using invopop/jsonschema. The reflector is configured to produce expanded structs and stable names to avoid collisions across packages with identically-named structs.
The reflector inlines every type instead of referencing definitions, so a recursive type is rejected before reflection with an error wrapping ErrRecursiveType; see CheckRecursion.
func MustFromAny ¶ added in v0.10.55
func MustFromAny(t any) *jsonschema.Schema
MustFromAny creates a jsonschema.Schema from an arbitrary value. It panics if the input cannot be marshaled into a valid schema. Useful in tests or when construction failures should be considered programmer errors.
func ObjectFields ¶ added in v1.0.178
func ObjectFields(s *jsonschema.Schema) (properties map[string]any, required []string)
ObjectFields returns the properties of the object schema s as a map, and the names of its required properties, for provider SDKs that take a tool's input schema in that form. properties is nil when s is nil or has no properties; required is nil when no property is required.
func ToFunctionSchema ¶
func ToFunctionSchema(tType reflect.Type, tSchema *jsonschema.Schema) *jsonschema.Schema
ToFunctionSchema converts a reflected Schema into a simplified, top-level object schema that exposes the first-level properties directly. This structure is more suitable for function/tool parameter documentation.
A $ref to a local definition ("#/$defs/<name>") in a property or array items, at any depth, is replaced by a copy of that definition. A $ref that names no definition, or one already being inlined above it (a recursive type), is kept as is. tSchema and its definitions are not modified. tType is unused.
func ValidatePortableJSON ¶ added in v0.21.160
func ValidatePortableJSON(raw json.RawMessage, output string) error
ValidatePortableJSON checks completed JSON against a previously validated schema. It never repairs output or accepts partial JSON. Call ValidatePortableSchema first.
func ValidatePortableSchema ¶ added in v0.21.160
func ValidatePortableSchema(raw json.RawMessage, strict bool) error
ValidatePortableSchema validates the bounded JSON Schema subset supported by the text router. It rejects unknown keywords instead of weakening caller constraints. Supported keywords: type, title, description, enum, properties, required, additionalProperties (boolean), and items. Strict objects require every property and disallow additional properties. The root must be an object.
Types ¶
type Faker ¶
type Faker interface {
Fake() any
}
Faker is an interface for generating structures with fake data. It can be implemented by custom types to provide exemplar values used in tests or documentation.
type ResponseFormat ¶ added in v0.10.55
type ResponseFormat struct {
Type string `json:"type"`
JSONSchema *ResponseFormatJSONSchema `json:"json_schema,omitempty"`
}
ResponseFormat defines the LLM response format. Currently supports a JSON Schema variant compatible with OpenAI’s response_format.
func NewResponseFormat ¶ added in v0.10.55
func NewResponseFormat(t reflect.Type, strict bool) (*ResponseFormat, error)
NewResponseFormat builds an OpenAI-style JSON Schema response format from the provided Go type. When strict is true, additionalProperties are disabled for objects and only defined fields are allowed.
type ResponseFormatJSONSchema ¶ added in v0.10.55
type ResponseFormatJSONSchema struct {
Name string `json:"name"`
Strict bool `json:"strict"`
Schema *ResponseFormatJSONSchemaProperty `json:"schema"`
}
ResponseFormatJSONSchema is the container for the top-level JSON Schema definition used in prompts, including the schema name and strictness.
type ResponseFormatJSONSchemaProperty ¶ added in v0.10.55
type ResponseFormatJSONSchemaProperty struct {
Type string `json:"type"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Enum []any `json:"enum,omitempty"`
Default any `json:"default,omitempty"`
Examples []any `json:"examples,omitempty"`
Items *ResponseFormatJSONSchemaProperty `json:"items,omitempty"`
Properties map[string]*ResponseFormatJSONSchemaProperty `json:"properties,omitempty"`
AdditionalProperties *bool `json:"additionalProperties,omitempty"`
Required []string `json:"required,omitempty"`
Ref string `json:"$ref,omitempty"`
}
ResponseFormatJSONSchemaProperty represents a property within the flattened JSON Schema used for prompting. Only fields relevant for LLM guidance are retained and rendered.
type Schema ¶
type Schema struct {
RawSchema *jsonschema.Schema
// Parameters represents the Function parameters definition
Parameters *jsonschema.Schema
}
func New ¶
New creates a new Schema from the given Go type. The result contains both the raw reflected jsonschema and a flattened Parameters schema suitable for use as tool/function parameters. Successful results are cached by type. A recursive type is rejected, on every call, with an error wrapping ErrRecursiveType; see CheckRecursion.
func (*Schema) NameFromRef ¶
NameFromRef returns the definition name of a RawSchema that is a local reference ("#/$defs/MyStruct" gives "MyStruct"), or "" when it is not one. Schemas built by New are never references, so it returns "" for them.