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-4")
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
}

See Also​