Skip to main content

GenerateText

Generates text using a language model with support for tool calling, streaming, and multi-step conversations.

Signature​

func GenerateText(ctx context.Context, opts GenerateTextOptions) (*GenerateTextResult, error)

Parameters​

GenerateTextOptions​

FieldTypeRequiredDescription
Modelprovider.LanguageModelYesLanguage model to use for generation
PromptstringNoSimple string prompt (alternative to Messages)
Messages[]types.MessageNoList of conversation messages
SystemstringNoSystem instructions
Temperature*float64NoSampling temperature (0.0 to 2.0)
MaxTokens*intNoMaximum tokens to generate
TopP*float64NoNucleus sampling parameter
TopK*intNoTop-K sampling parameter
FrequencyPenalty*float64NoFrequency penalty (-2.0 to 2.0)
PresencePenalty*float64NoPresence penalty (-2.0 to 2.0)
StopSequences[]stringNoSequences that stop generation
Seed*intNoRandom seed for reproducibility
Tools[]types.ToolNoTools available for the model to call
ToolChoicetypes.ToolChoiceNoHow the model should choose tools
StopWhen[]ai.StopConditionNoConditions that stop the tool-calling loop (see IsStepCount, HasToolCall). Default: IsStepCount(1), a single step (tool calls in it still execute). Set e.g. IsStepCount(5) to let the model answer after tool results.
MaxSteps*intNoDeprecated — use StopWhen: []ai.StopCondition{ai.IsStepCount(n)} instead
Timeout*TimeoutConfigNoTimeout configuration
OutputinterfaceNoOutput specification (v6.0+)
ResponseFormat*provider.ResponseFormatNoResponse format (deprecated: use Output)
ExperimentalContextinterfaceNoUser-defined context
ExperimentalRetention*types.RetentionSettingsNoData retention settings
ProviderOptionsmap[string]interfaceNoProvider-specific options
PrepareStepfuncNoCalled before each step
OnStepFinishfuncNoCalled after each step completes
OnFinishfuncNoCalled when generation completes

Return Value​

GenerateTextResult​

FieldTypeDescription
TextstringGenerated text content
ToolCalls[]types.ToolCallTool calls made during generation
ToolResults[]types.ToolResultResults from executed tools
Steps[]types.StepResultSteps taken during generation
FinalSteptypes.StepResultLast step, including Performance statistics
FinishReasontypes.FinishReasonWhy generation finished
StopReasonstringReason string from the StopCondition that stopped the loop; empty if no condition fired
Usagetypes.UsageToken usage information
ContextManagementinterfaceContext management info (Anthropic)
Warnings[]types.WarningProvider warnings
RawRequestinterfaceRaw request for debugging
RawResponseinterfaceRaw response for debugging

Each types.StepResult includes Performance with StepTimeMs, ResponseTimeMs, ToolExecutionMs, EffectiveOutputTokensPerSecond, EffectiveTotalTokensPerSecond, and streaming-only OutputTokensPerSecond, InputTokensPerSecond, TimeToFirstOutputMs, and TimeBetweenOutputChunksMs.

Examples​

Basic Text Generation​

package main

import (
"context"
"fmt"
"log"

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

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

// Generate text
result, err := ai.GenerateText(context.Background(), ai.GenerateTextOptions{
Model: model,
Prompt: "Write a haiku about Go programming",
})
if err != nil {
log.Fatal(err)
}

fmt.Println(result.Text)
fmt.Printf("Tokens used: %d\n", result.Usage.GetTotalTokens())
}

With Generation Parameters​

temperature := 0.7
maxTokens := 500

result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{
Model: model,
Prompt: "Explain quantum computing",
Temperature: &temperature,
MaxTokens: &maxTokens,
})
if err != nil {
log.Fatal(err)
}

fmt.Println(result.Text)

With Multi-turn Conversation​

result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{
Model: model,
Messages: []types.Message{
{
Role: types.RoleUser,
Content: []types.ContentPart{
types.TextContent{Text: "What is the capital of France?"},
},
},
{
Role: types.RoleAssistant,
Content: []types.ContentPart{
types.TextContent{Text: "The capital of France is Paris."},
},
},
{
Role: types.RoleUser,
Content: []types.ContentPart{
types.TextContent{Text: "What is its population?"},
},
},
},
})
if err != nil {
log.Fatal(err)
}

fmt.Println(result.Text)

With Tool Calling​

weatherTool := types.Tool{
Name: "get_weather",
Description: "Get current weather for a location",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"location": map[string]interface{}{
"type": "string",
"description": "City name",
},
},
"required": []string{"location"},
},
Execute: func(ctx context.Context, input map[string]interface{}, opts types.ToolExecutionOptions) (interface{}, error) {
location := input["location"].(string)
return fmt.Sprintf("Weather in %s: Sunny, 72°F", location), nil
},
}

result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{
Model: model,
Prompt: "What's the weather like in San Francisco?",
Tools: []types.Tool{weatherTool},
StopWhen: []ai.StopCondition{ai.IsStepCount(5)},
})
if err != nil {
log.Fatal(err)
}

fmt.Println(result.Text)
fmt.Printf("Tool calls: %d\n", len(result.ToolCalls))

Error Handling​

Common errors and how to handle them:

result, err := ai.GenerateText(ctx, opts)
if err != nil {
switch {
case errors.Is(err, context.DeadlineExceeded):
log.Println("Request timed out")
case errors.Is(err, context.Canceled):
log.Println("Request was canceled")
case strings.Contains(err.Error(), "model is required"):
log.Println("Missing required model parameter")
case strings.Contains(err.Error(), "generation failed"):
log.Println("Generation error:", err)
default:
log.Println("Unknown error:", err)
}
return
}

See Also​