Documentation
¶
Overview ¶
Package structuredoutput compiles a JSON Schema and validates a model's final text response against it, backing the provider-neutral llms.WithStructuredOutput contract.
It is kept separate from the base llms package so that package does not depend on an external JSON Schema library: this package imports llms (for the typed llms.ErrStructuredOutputValidation), llms does not import this package, and provider adapters may import both without an import cycle.
Validate compiles a schema (JSON Schema Draft 2020-12, via github.com/santhosh-tekuri/jsonschema/v6) and checks that the response text is exactly one JSON value (trailing text or a second value is rejected) matching it. Numbers decode with json.Number so large integers survive; enum/const stay case-sensitive. Failures are wrapped in *llms.ErrStructuredOutputValidation with the provider, model, choice index and stop reason.
Adapters call it only for a normal-final response; refusals, tool-use turns and truncated/blocked responses are never validated as final JSON.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func RequireClosedObjects ¶
func RequireClosedObjects(schema json.RawMessage) error
RequireClosedObjects verifies that every object node in the schema explicitly sets additionalProperties:false. Anthropic and Amazon Bedrock structured outputs reject an object schema that omits it (a ValidationException 400), and this is reliably detectable locally, so it is turned into a typed configuration error before the request is sent instead of an opaque provider 4xx. It wraps llms.ErrStructuredOutputConfig and does not otherwise constrain the schema.
func Validate ¶
func Validate(schema json.RawMessage, provider, model string, choice int, stopReason, text string) error
Validate compiles schema and validates text, wrapping any failure in a typed *llms.ErrStructuredOutputValidation that carries provider/model/choice/stopReason and unwraps to the concrete cause. Callers pass the ORIGINAL schema so validation reflects exactly what the user asked for, not a provider-transformed variant.
Types ¶
type Compiled ¶
type Compiled struct {
// contains filtered or unexported fields
}
Compiled is a schema compiled once so multiple choices of one response reuse it.
func Compile ¶
func Compile(schema json.RawMessage) (*Compiled, error)
Compile compiles a raw JSON Schema document. Without $schema the document is treated as Draft 2020-12. The schema is used verbatim; no keywords are injected or stripped.
func (*Compiled) ValidateText ¶
ValidateText parses text as exactly one JSON value (trailing text or a second value is rejected) and validates it against the compiled schema. Numbers decode via json.Number so large integers are not degraded to float64 before validation.