structured_output

command
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 7 Imported by: 0

README

Structured (JSON) output

Ask an LLM for strict JSON and decode it into a typed Go struct.

model.ChatRequest.ResponseFormat controls the output format:

  • "json_object" — the model returns valid JSON (no schema enforcement).
  • "json_schema" — the model returns JSON conforming to the schema in Metadata["json_schema"]. Enforced as a native request parameter by OpenAI, Azure OpenAI, OpenAI-compatible providers (Ollama, Mistral, ...), Gemini, and the Responses API. Anthropic has no equivalent parameter, so it falls back to whatever the system prompt asks for.

Going through sdk/agent's WithOutputSchema/output_schema: instead of a bare Provider.Chat call (as this example does) additionally validates the reply against the schema after the fact, on every provider — see Structured (JSON) Output in the Agents guide.

This example requests a Recipe as JSON, then decodes the reply into the Recipe struct (tolerating stray Markdown code fences).

Run

Needs a real LLM provider (one network call). Configure any provider from examples/internal/providers:

OPENAI_API_KEY=sk-... go run ./examples/structured_output/

With no provider set, it prints the required env vars and exits.

Test

The test covers the pure JSON parsing helpers only — no network, no provider:

go test ./examples/structured_output/

Documentation

Overview

Example: structured_output — asking an LLM for strict JSON and decoding it.

What you'll learn:

  • How to request JSON output with model.ChatRequest.ResponseFormat
  • The difference between "json_object" (valid JSON) and "json_schema" (JSON conforming to a schema in Metadata["json_schema"])
  • How to decode the model's reply into a typed Go struct

This example needs a real LLM provider (it makes one network call). Configure one via the environment (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, …); see examples/internal/providers for the full list. With no provider set it prints the required env vars and exits cleanly.

Run:

OPENAI_API_KEY=sk-... go run ./examples/structured_output/

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL