Every LLM feature I've built in Go eventually needs the same thing: a typed value, not a string. A triage bot needs Severity to be one of four values. An invoice parser needs Total to be a number. A scheduler needs End to come after Start.
The usual approach looks like this:
resp, _ := client.Chat(ctx, prompt+"\nRespond ONLY with JSON like {...}")
var t Ticket
if err := json.Unmarshal([]byte(resp), &t); err != nil {
// retry? log? give up?
}
It works in the demo and fails in production in boring, predictable ways:
- The model wraps the JSON in prose or Markdown fences.
- It returns
"severity": "URGENT"when you only handlelow|medium|high|critical. - It adds fields you didn't ask for, or leaves out ones you need.
-
json.Unmarshalhappily accepts all of that, so the bad value flows into your system.
"Respond with EXACTLY this format" is a hope, not a guarantee. I wanted the guarantee to live in code, so I wrote go-structllm.
The idea: the struct is the contract
type Ticket struct {
Severity string `json:"severity" enum:"low,medium,high,critical" desc:"How urgent it is"`
Summary string `json:"summary" minLen:"1" maxLen:"200"`
Tags []string `json:"tags" maxItems:"5" pattern:"^[a-z-]+$"`
Owner *string `json:"owner"` // pointer = optional and nullable
}
client := openai.New(os.Getenv("OPENAI_API_KEY"), "gpt-4o-mini")
t, err := structllm.Extract[Ticket](ctx, client, "Triage this alert: "+alert)
You get back a Ticket that passed validation, or an error. Never a half-parsed value.
Under the hood, Extract does four things.
1. Build a JSON Schema from the struct
structllm.SchemaFor[Ticket]() reads the field types and tags and produces a JSON Schema: types, required fields, enums, lengths, item counts, numeric bounds, patterns, and date-time for time.Time. Properties keep their declaration order, so the prompt is the same on every run.
The schema goes to the model twice: in the system prompt, and as response_format: json_schema for providers that support constrained decoding.
2. Never trust the reply
The reply is parsed leniently, so JSON inside code fences or prose is found. Then it is validated strictly against the schema, including fields the model invented.
If your type needs rules a schema can't express, add a method:
type Window struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
}
func (w Window) Validate() error {
if !w.End.After(w.Start) {
return errors.New("end must be after start")
}
return nil
}
3. Let the model fix its own mistakes
This is the part that makes the difference. When validation fails, go-structllm doesn't just retry. It sends the model exactly what was wrong, with JSON paths:
Your previous response was not valid. Fix these problems and reply with only the corrected JSON:
- $.eta: is not an allowed field
- $.severity: must be one of [low, medium, high, critical]
- $.tags[0]: must match pattern ^[a-z-]+$
- $.tags[1]: must match pattern ^[a-z-]+$
Models are very good at fixing a specific list of problems. This repair loop runs at most MaxRepairs times (default 2), so the cost is bounded.
4. Return a T, or a precise error
If the reply is still invalid after the repairs, you get an *ExhaustedError that wraps the last *ValidationError, with every issue and the raw reply for debugging.
structllm.Extract[Ticket](ctx, client, prompt,
structllm.System("You are a precise incident triage assistant."),
structllm.MaxRepairs(3),
structllm.OnAttempt(func(a structllm.Attempt) {
metrics.Observe("llm_attempt", a.Number, len(a.Issues))
}),
)
Any model, one interface
The model is a one-method interface:
type Client interface {
Complete(ctx context.Context, req Request) (string, error)
}
The included openai package speaks the OpenAI chat-completions protocol. That protocol is also spoken by Gemini, Azure OpenAI, Ollama, vLLM, LM Studio and Groq, so switching providers is one struct literal:
// Local model, no API key
c := &openai.Client{BaseURL: "http://localhost:11434/v1", Model: "llama3.1"}
// Google Gemini (free tier key from AI Studio)
c := &openai.Client{
BaseURL: "https://generativelanguage.googleapis.com/v1beta/openai",
APIKey: os.Getenv("GEMINI_API_KEY"),
Model: "gemini-3.5-flash",
}
For anything else, wrap your SDK in a structllm.ClientFunc. It also makes testing easy: a scripted fake client is a few lines, and the whole library has no dependencies outside the standard library.
What broke when I tested against a real model
The unit tests covered everything against a fake server. They passed, and they still weren't enough. A fake server proves your code matches your understanding of the API, not the API itself. So before announcing anything, I ran the library against real Gemini.
The good news: with the default schema mode, Gemini returned a valid Ticket on the first attempt: a correct enum value, a summary under the length limit, and three tags matching ^[a-z-]+$.
The less good news came from the error paths:
-
The first model name I tried had been retired. Gemini answered with a 404, but my error said only
HTTP 404: Not Found. The useful message, "This model … is no longer available to new users. Please update your code to use …", was lost. - The next model was overloaded. A 503, "currently experiencing high demand … try again later", failed the whole call on the first try.
The root cause of the first was a small surprise. OpenAI returns errors as {"error": {...}}, but Gemini's OpenAI-compatible endpoint returns them wrapped in an array: [{"error": {...}}]. My client only understood the first shape.
Both are fixed in v0.2.0:
- Errors keep the provider's real message in both shapes. The exact Gemini messages are pinned as regression tests, so this can't quietly come back.
- Rate limits (429), server errors (5xx) and network failures are retried with exponential backoff and jitter. A
Retry-Afterheader is honoured, but the client won't wait absurdly long (30 s by default). Everything is configurable, or you can turn it off withDisableRetries.
The lesson I keep re-learning: "compatible" APIs are compatible on the happy path. Test the error paths against the real thing before you ship.
Honest comparison
I'm not the first to do this in Go. instructor-go brings the Instructor approach to Go too, and it's worth a look. Choose based on what you need:
-
go-structllm: zero dependencies, any model behind a one-method interface (including local models),
Validate()business rules fed back to the model, exact JSON-path errors. - instructor-go: built-in clients for OpenAI, Anthropic, Gemini and Cohere, and streaming of partial objects, which go-structllm doesn't do yet.
Part of a small toolkit
go-structllm is one of a few dependency-free Go libraries I've published for building LLM-backed services:
- go-ssekit: stream LLM tokens to the browser with Server-Sent Events, with a broker that replays missed events on reconnect.
-
go-redact: a
log/sloghandler that scrubs API keys, JWTs, card numbers and emails from your logs, including from prompts and error messages. - go-resilience, go-httpkit and go-outbox: retries and circuit breakers, idempotent HTTP APIs, and a transactional outbox.
- go-microservices-kit: a reference project that wires several of them together.
Try it
go get github.com/shani8615/go-structllm@latest
git clone https://github.com/shani8615/go-structllm && cd go-structllm
go run ./examples/demo # no API key needed: watch the repair loop
Issues, ideas and pull requests are very welcome, especially reports from providers I haven't tested yet (Groq, vLLM, LM Studio). If you've built LLM features in Go, I'd love to hear how you handle structured output today.

Top comments (1)
The path-based repair message is the right design, models fix a specific list far better than a generic retry. Two edge cases to watch: with constrained decoding some providers only support a subset of JSON Schema (pattern, minLength and similar keywords can be ignored or rejected), so keep the local validator as the source of truth. And pointer fields for optional values: make sure an explicit null from the model and a missing key are treated the same, otherwise the repair loop can burn an attempt on a harmless difference.