# Get typed data from a model

> Generate a validated Go struct with GenerateText and ObjectOutput.

Canonical URL: https://goaisdk.com/docs/recipes/structured-output
Documentation index: https://goaisdk.com/llms.txt

Get a Go struct back from a model, not free text.

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/digitallysavvy/go-ai/pkg/ai"
	"github.com/digitallysavvy/go-ai/pkg/providers/openai"
)

// The schema comes from the struct's JSON tags.
type Recipe struct {
	Name        string   `json:"name"`
	Ingredients []string `json:"ingredients"`
	Steps       []string `json:"steps"`
}

func main() {
	model, err := openai.New(openai.Config{APIKey: os.Getenv("OPENAI_API_KEY")}).
		LanguageModel(openai.ModelGPT6Astra)
	if err != nil {
		log.Fatal(err)
	}

	result, err := ai.GenerateText(context.Background(), ai.GenerateTextOptions{
		Model:  model,
		Prompt: "Give me a lasagna recipe.",
		Output: ai.ObjectOutput[Recipe](ai.ObjectOutputOptions{
			Schema:      ai.SchemaFor[Recipe](),
			Name:        "recipe",
			Description: "A recipe with a name, ingredients and steps",
		}),
	})
	if err != nil {
		log.Fatal(err)
	}

	recipe := result.Output.(Recipe)
	fmt.Println(recipe.Name)
	for i, step := range recipe.Steps {
		fmt.Printf("%d. %s\n", i+1, step)
	}
}
```

Run it:

```bash
OPENAI_API_KEY=... go run ./examples/recipes/structured-output
```

## Notes

- `ai.SchemaFor[T]()` builds the JSON Schema from the struct's `json` tags.
- `result.Output` holds the parsed value. Type-assert it to your struct.
- Other output types: `ArrayOutput[T]` for a list, `ChoiceOutput[T]` for a classification and `JSONOutput()` for untyped JSON.
- `ai.GenerateObject` still works but is deprecated. Prefer `GenerateText` with `Output`.

## Go deeper

- [Guide: Generating structured data](https://goaisdk.com/docs/ai-sdk-core/generating-structured-data.md)
- [Reference: Generate text](https://goaisdk.com/docs/reference/ai/generate-text.md)
- [Reference: Generate object](https://goaisdk.com/docs/reference/ai/generate-object.md)

The full program is at [`examples/recipes/structured-output/main.go`](https://github.com/digitallysavvy/go-ai/blob/main/examples/recipes/structured-output/main.go).
