Skip to main content

GenerateObject

Generates structured JSON objects that conform to a specified schema using language models with structured output support.

Signature​

func GenerateObject(ctx context.Context, opts GenerateObjectOptions) (*GenerateObjectResult, error)

Parameters​

GenerateObjectOptions​

FieldTypeRequiredDescription
Modelprovider.LanguageModelYesLanguage model to use (must support structured output)
PromptstringNoSimple string prompt (alternative to Messages)
Messages[]types.MessageNoList of conversation messages
SystemstringNoSystem instructions
Schemaschema.SchemaNoSchema for output validation (required for object/array modes)
OutputModeObjectOutputModeNoOutput mode: object, array, enum, or no-schema (default: object)
EnumValues[]stringNoEnum values (required for enum mode)
Temperature*float64NoSampling temperature (0.0 to 2.0)
MaxTokens*intNoMaximum tokens to generate
TopP*float64NoNucleus sampling parameter
FrequencyPenalty*float64NoFrequency penalty (-2.0 to 2.0)
PresencePenalty*float64NoPresence penalty (-2.0 to 2.0)
Seed*intNoRandom seed for reproducibility
OnFinishfuncNoCalled when generation completes
ExperimentalContextinterfaceNoUser-defined context

Return Value​

GenerateObjectResult​

FieldTypeDescription
ObjectinterfaceGenerated object (for object/no-schema modes)
Array[]interfaceGenerated array (for array mode)
EnumValuestringSelected enum value (for enum mode)
TextstringRaw JSON text
FinishReasontypes.FinishReasonWhy generation finished
Usagetypes.UsageToken usage information
Warnings[]types.WarningProvider warnings

Examples​

Basic Object Generation​

package main

import (
"context"
"fmt"
"log"

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

type Person struct {
Name string `json:"name"`
Age int `json:"age"`
City string `json:"city"`
}

func main() {
provider := openai.New(openai.Config{
APIKey: "your-api-key",
})
model, err := provider.LanguageModel("gpt-6-astra")
if err != nil {
log.Fatal(err)
}

// Define schema
personSchema := schema.NewSimpleJSONSchema(map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string"},
"age": map[string]interface{}{"type": "integer"},
"city": map[string]interface{}{"type": "string"},
},
"required": []string{"name", "age", "city"},
})

// Generate object
result, err := ai.GenerateObject(context.Background(), ai.GenerateObjectOptions{
Model: model,
Prompt: "Generate information about a fictional character named Alice",
Schema: personSchema,
})
if err != nil {
log.Fatal(err)
}

fmt.Printf("Result: %+v\n", result.Object)
fmt.Printf("Tokens used: %d\n", result.Usage.GetTotalTokens())
}

Generate Into Struct​

type Recipe struct {
Name string `json:"name"`
Ingredients []string `json:"ingredients"`
Steps []string `json:"steps"`
CookTime int `json:"cookTime"`
}

var recipe Recipe

recipeSchema := schema.NewSimpleJSONSchema(map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string"},
"ingredients": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}},
"steps": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}},
"cookTime": map[string]interface{}{"type": "integer"},
},
"required": []string{"name", "ingredients", "steps", "cookTime"},
})

err := ai.GenerateObjectInto(ctx, ai.GenerateObjectOptions{
Model: model,
Prompt: "Generate a recipe for chocolate chip cookies",
Schema: recipeSchema,
}, &recipe)
if err != nil {
log.Fatal(err)
}

fmt.Printf("Recipe: %s\n", recipe.Name)
fmt.Printf("Ingredients: %v\n", recipe.Ingredients)

Array Mode​

itemSchema := schema.NewSimpleJSONSchema(map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string"},
"price": map[string]interface{}{"type": "number"},
},
"required": []string{"name", "price"},
})

result, err := ai.GenerateObject(ctx, ai.GenerateObjectOptions{
Model: model,
Prompt: "List 5 popular tech gadgets with prices",
Schema: itemSchema,
OutputMode: ai.ObjectModeArray,
})
if err != nil {
log.Fatal(err)
}

for i, item := range result.Array {
fmt.Printf("%d. %+v\n", i+1, item)
}

Enum Mode​

result, err := ai.GenerateObject(ctx, ai.GenerateObjectOptions{
Model: model,
Prompt: "Classify the sentiment: 'This product is amazing!'",
OutputMode: ai.ObjectModeEnum,
EnumValues: []string{"positive", "negative", "neutral"},
})
if err != nil {
log.Fatal(err)
}

fmt.Printf("Sentiment: %s\n", result.EnumValue)

No-Schema Mode​

result, err := ai.GenerateObject(ctx, ai.GenerateObjectOptions{
Model: model,
Prompt: "Generate a JSON object with user profile data",
OutputMode: ai.ObjectModeNoSchema,
})
if err != nil {
log.Fatal(err)
}

// Object is returned as map[string]interface{}
fmt.Printf("Generated: %+v\n", result.Object)

Error Handling​

result, err := ai.GenerateObject(ctx, opts)
if err != nil {
switch {
case strings.Contains(err.Error(), "model is required"):
log.Println("Missing required model parameter")
case strings.Contains(err.Error(), "schema is required"):
log.Println("Schema required for this output mode")
case strings.Contains(err.Error(), "does not support structured output"):
log.Println("Model doesn't support structured output")
case strings.Contains(err.Error(), "validation failed"):
log.Println("Output validation error:", err)
case strings.Contains(err.Error(), "failed to parse JSON"):
log.Println("Invalid JSON output:", err)
default:
log.Println("Unknown error:", err)
}
return
}

Option fields (generated)​

This table is generated from the ai.GenerateObjectOptions source and lists every exported field.

FieldTypeDescription
Modelprovider.LanguageModelModel to use for generation
PromptstringPrompt can be a simple string or a list of messages
Messages[]types.Message
Systemstring
Schemaschema.SchemaSchema for the output object (not required for no-schema mode)
OutputModeObjectOutputModeOutput mode - object, array, enum, or no-schema
EnumValues[]stringEnum values (required for enum mode)
Temperature*float64Generation parameters
MaxTokens*int
TopP*float64
TopK*int
FrequencyPenalty*float64
PresencePenalty*float64
Seed*int
MaxRetriesint
RepairTextRepairTextFuncRepairText repairs invalid JSON or schema-invalid object output. Return nil when the output cannot be repaired. Takes precedence over ExperimentalRepairText when both are set (audit row 09a52cb).
ExperimentalRepairTextRepairTextFuncExperimentalRepairText repairs invalid JSON or schema-invalid object output. Return nil when the output cannot be repaired. Deprecated: use RepairText.
Headersmap[string]stringAdditional HTTP headers sent with the request.
ProviderOptionsmap[string]interface{}Additional provider-specific options.
SchemaNamestringSchemaName is an optional name for the output schema.
SchemaDescriptionstringSchemaDescription is an optional description for the output schema.
Telemetry*TelemetrySettingsTelemetry configures observability for this operation. When both Telemetry and ExperimentalTelemetry are set, Telemetry wins.
ExperimentalTelemetry*TelemetrySettingsTelemetry configuration for observability. Deprecated: use Telemetry.
OnStartfunc(ctx context.Context, e ObjectOnStartEvent)OnStart is called once before any LLM call is made.
ExperimentalOnStartfunc(ctx context.Context, e ObjectOnStartEvent)ExperimentalOnStart is a deprecated alias for OnStart. Deprecated: use OnStart.
OnStepStartfunc(ctx context.Context, e ObjectOnStepStartEvent)OnStepStart is called just before the provider is called.
ExperimentalOnStepStartfunc(ctx context.Context, e ObjectOnStepStartEvent)ExperimentalOnStepStart is a deprecated alias for OnStepStart. Deprecated: use OnStepStart.
OnStepEndfunc(ctx context.Context, e ObjectOnStepFinishEvent)OnStepEnd is called after the provider returns, before JSON parsing.
OnStepFinishfunc(ctx context.Context, e ObjectOnStepFinishEvent)OnStepFinish is called after the provider returns, before JSON parsing. Deprecated: use OnStepEnd.
OnEndfunc(ctx context.Context, e ObjectOnFinishEvent)OnEnd is called when the operation completes with a typed event. For GenerateObject, the event Error field is always nil.
OnFinishEventfunc(ctx context.Context, e ObjectOnFinishEvent)OnFinishEvent is a deprecated alias for OnEnd. Deprecated: use OnEnd.
OnFinishfunc(ctx context.Context, result *GenerateObjectResult, userContext interface{})Legacy callback — kept for backward compatibility. Prefer OnEnd for structured access.
ExperimentalContextinterface{}ExperimentalContext allows passing custom context through generation lifecycle

See Also​