Skip to main content

ToolLoopAgent

ToolLoopAgent is an agent that loops through tool calls until the task completes. It lives in github.com/digitallysavvy/go-ai/pkg/agent (not pkg/ai) and implements the agent.Agent interface.

Signature​

func NewToolLoopAgent(config AgentConfig) *ToolLoopAgent

Parameters​

AgentConfig (selected fields)​

AgentConfig has many fields; these are the ones most commonly used.

FieldTypeDescription
Modelprovider.LanguageModelLanguage model for the agent
SystemstringSystem prompt for the agent
Tools[]types.ToolTools available to the agent
ActiveTools[]stringRestricts the available tools by name before model calls
StopWhen[]ai.StopConditionConditions that terminate the tool-calling loop, e.g. []ai.StopCondition{ai.IsStepCount(20)} (default)
MaxStepsintDeprecated — use StopWhen with ai.IsStepCount instead
Temperature*float64Sampling temperature
MaxTokens*intMaximum tokens per generation
ToolChoicetypes.ToolChoiceControls how the model may call tools
ProviderOptionsmap[string]interfaceProvider-specific options
Skills*SkillRegistryReusable agent behaviors, registered with AddSkill
Subagents*SubagentRegistrySpecialized agents that can be delegated to
PrepareCallfunc(ctx, PrepareCallConfig) PrepareCallConfigCalled before each generation step to adjust settings dynamically
OnStepEndfunc(types.StepResult)Called after each step completes
OnFinishfunc(*AgentResult)Called when agent execution completes
ToolApprovaltypes.ToolApprovalConfigApproval policy for tool calls: a types.GenericToolApprovalFunc or a per-tool map. Tools can also set Tool.ToolApproval
ExperimentalToolApprovalSecret[]byteSigns approval requests and verifies approval responses when a client resumes a conversation
ToolApprovalRequired, ToolApproverbool, funcLegacy blocking callback for CLI-style programs. ToolApprover is called inline and returns true or false

See go doc ./pkg/agent AgentConfig for the complete field list, including telemetry, retry, timeout, and callback-event options.

Methods​

func (a *ToolLoopAgent) Execute(ctx context.Context, prompt string) (*AgentResult, error)
func (a *ToolLoopAgent) ExecuteWithMessages(ctx context.Context, messages []types.Message) (*AgentResult, error)
func (a *ToolLoopAgent) Generate(ctx context.Context, opts AgentGenerateOptions) (*ai.GenerateTextResult, error)
func (a *ToolLoopAgent) GenerateAgent(ctx context.Context, opts AgentGenerateOptions) (*AgentResult, error)
func (a *ToolLoopAgent) Stream(ctx context.Context, opts AgentStreamOptions) (*ai.StreamTextResult, error)
func (a *ToolLoopAgent) AddTool(tool types.Tool)
func (a *ToolLoopAgent) RemoveTool(toolName string)
func (a *ToolLoopAgent) Tools() []types.Tool
func (a *ToolLoopAgent) AddSkill(skill *Skill) error
func (a *ToolLoopAgent) AddSubagent(name string, subagent Agent) error
func (a *ToolLoopAgent) DelegateToSubagent(ctx context.Context, name string, prompt string) (*AgentResult, error)
func (a *ToolLoopAgent) SetMaxSteps(maxSteps int)
func (a *ToolLoopAgent) SetStopConditions(conditions []ai.StopCondition)
func (a *ToolLoopAgent) SetSystem(system string)
func (a *ToolLoopAgent) ID() string
func (a *ToolLoopAgent) Version() string

Return Value​

AgentResult​

FieldTypeDescription
TextstringAgent's final text output
OutputinterfaceParsed/structured output when an output strategy is configured
Steps[]types.StepResultAll steps in the loop
ToolResults[]types.ToolResultAll tool results from execution
FinishReasontypes.FinishReasonFinal finish reason
StopReasonstringWhy the loop stopped
Usagetypes.UsageTotal token usage
Warnings[]types.WarningWarnings from any step

Examples​

Basic Tool Loop Agent​

package main

import (
"context"
"fmt"
"log"

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

func main() {
p := openai.New(openai.Config{
APIKey: "your-api-key",
})
model, _ := p.LanguageModel("gpt-6-astra")

searchTool := types.Tool{Name: "search"}
priceCompareTool := types.Tool{Name: "price_compare"}

a := agent.NewToolLoopAgent(agent.AgentConfig{
Model: model,
Tools: []types.Tool{searchTool, priceCompareTool},
})

result, err := a.Execute(context.Background(), "Find and compare prices of three popular smartphones")
if err != nil {
log.Fatal(err)
}

fmt.Printf("Answer: %s\n", result.Text)
fmt.Printf("Tool calls: %d\n", len(result.ToolResults))
}

With a Custom Stop Condition​

a := agent.NewToolLoopAgent(agent.AgentConfig{
Model: model,
Tools: tools,
StopWhen: []ai.StopCondition{
ai.HasToolCall("final_answer"),
ai.IsStepCount(5),
},
})

result, err := a.Execute(ctx, "Research topic and gather 3 key facts")

With Step and Tool Callbacks​

a := agent.NewToolLoopAgent(agent.AgentConfig{
Model: model,
Tools: tools,
OnStepEnd: func(step types.StepResult) {
fmt.Printf("Step finished, %d tool calls\n", len(step.ToolCalls))
},
OnToolResult: func(result types.ToolResult) {
fmt.Printf("Tool result: %+v\n", result.Result)
if result.Error != nil {
fmt.Printf("Tool error: %v\n", result.Error)
}
},
})

result, err := a.Execute(ctx, "Complex multi-step research task")

Configuration fields (generated)​

These tables are generated from the agent.AgentConfig and agent.PrepareCallConfig source and list every exported field.

AgentConfig​

agent.DefaultAgentConfig() returns an AgentConfig with default values.

FieldTypeDescription
IDstringID is a unique identifier for the agent Useful for tracking and logging which agent performed actions
VersionstringVersion is the version of the agent (e.g., "agent-v1", "1.0.0") Useful for versioning agent behavior and configurations
Modelprovider.LanguageModelModel to use for the agent
SystemstringSystem prompt for the agent
PromptstringPrompt is a TypeScript-compatible alias for System/instructions. When System is empty, Prompt is used as the system prompt for each step.
Instructions*stringInstructions is the canonical TypeScript-compatible name for System. When set, Instructions takes precedence over System.
AllowSystemInMessagesboolAllowSystemInMessages mirrors TypeScript ToolLoopAgentSettings.allowSystemInMessages.
Tools[]types.ToolTools available to the agent
ActiveTools[]stringActiveTools restricts the available tools by name before model calls.
ToolOrder[]stringToolOrder controls the order tools are sent to providers.
ExperimentalToolCallersai.ExperimentalToolCallersExperimentalToolCallers configures which tools may call which other tools, and which tools stay hidden until discovered via ai.ToolSearch. Forwarded to the underlying GenerateText/StreamText call. Mirrors the TypeScript SDK's ToolLoopAgentSettings.experimental_toolCallers.
Skills*SkillRegistrySkills are reusable agent behaviors Skills can be registered and executed by the agent
Subagents*SubagentRegistrySubagents are specialized agents that can be delegated to The main agent can delegate tasks to subagents for specialized processing
MaxStepsintMaximum number of steps (iterations) the agent can take. If both MaxSteps and StopWhen are set, StopWhen takes precedence. Deprecated: use StopWhen with ai.IsStepCount instead.
StopWhen[]ai.StopConditionStopWhen defines conditions that terminate the agent's tool-calling loop. Conditions are evaluated OR -- first non-empty string stops the loop. If neither StopWhen nor MaxSteps is set, defaults to []ai.StopCondition{ai.IsStepCount(20)}.
Temperature*float64Temperature for generation
MaxTokens*intMaxTokens per generation
TopP*float64TopP controls nucleus sampling.
TopK*intTopK controls top-k sampling for providers that support it.
FrequencyPenalty*float64FrequencyPenalty reduces repetition.
PresencePenalty*float64PresencePenalty encourages topic diversity.
StopSequences[]stringStopSequences halt generation when encountered.
ToolChoicetypes.ToolChoiceToolChoice controls how the model may call tools.
Seed*intSeed enables deterministic generation when supported by the provider.
Headersmap[string]stringHeaders are custom request headers forwarded to the provider.
Reasoning*types.ReasoningLevelReasoning configures provider reasoning effort.
SendReasoning*boolSendReasoning controls whether reasoning stream/content parts are exposed.
ProviderOptionsmap[string]interface{}ProviderOptions are provider-specific options keyed by provider name.
Outputinterface{}Output specifies how to handle and parse model output during streaming.
Telemetry*ai.TelemetrySettingsTelemetry configures observability for this agent.
ExperimentalTelemetry*ai.TelemetrySettingsExperimentalTelemetry is a deprecated alias for Telemetry, included for parity with TypeScript prepareCall.
SensitiveRuntimeContextboolSensitiveRuntimeContext omits runtime context from telemetry payloads.
Include*ai.IncludeOptionsInclude forwards stable include options to core stream/generate behavior.
Internal*ai.InternalOptionsInternal contains test-only ID generators matching TypeScript _internal.
Timeout*ai.TimeoutConfigTimeout provides granular timeout controls Supports total timeout, per-step timeout, and per-chunk timeout
MaxRetries*intMaxRetries controls transient provider call retries, forwarded to ai.GenerateTextOptions.MaxRetries / ai.StreamTextOptions.MaxRetries. nil uses the default retry count (2), matching TS WorkflowAgent's mergedGenerationSettings.maxRetries ?? 2.
PrepareCallfunc(ctx context.Context, config PrepareCallConfig) PrepareCallConfigPrepareCall is called before each generation step Allows dynamic modification of the agent's configuration per step This is useful for: - Adjusting system prompts based on context - Changing temperature/parameters dynamically - Modifying available tools based on state - Adding contextual information Example: PrepareCall: func(ctx context.Context, config PrepareCallConfig) PrepareCallConfig { // Adjust system prompt based on step number if config.StepNumber > 5 { config.System = "Be more concise." } return config }
ExperimentalContextinterface{}ExperimentalContext is user-defined context that flows through all structured callback events (OnStartEvent, OnStepStartEvent, etc.). It is passed as-is to every event — useful for correlating events with application-level state (e.g. request IDs, session objects).
RuntimeContextinterface{}RuntimeContext is user-defined context that flows through callbacks, approval hooks, and tool execution. ExperimentalContext is a deprecated alias and is used only when RuntimeContext is nil.
ToolsContextmap[string]interface{}ToolsContext contains per-tool context keyed by tool name. Each value is validated against the matching tool's ContextSchema before approval callbacks and execution.
ExperimentalSandboxinterface{}ExperimentalSandbox is passed to tool execution and prepare-step hooks.
ExperimentalRefineToolInputmap[string]ai.ToolInputRefinerExperimentalRefineToolInput refines parsed tool input before execution.
CallOptionsinterface{}CallOptions contains agent-level call options passed through PrepareCall. When CallOptionsSchema is set, this value is validated before model calls.
CallOptionsSchemaschema.SchemaCallOptionsSchema validates CallOptions before any generate/stream call.
FilterActiveToolsfunc(ctx context.Context, stepNumber int, tools []types.Tool) []types.ToolFilterActiveTools can restrict the available tools for each step. It mirrors the TypeScript filterActiveTools/activeTools behavior.
ExperimentalDownloadai.DownloadFunctionExperimentalDownload customizes remote file URL downloads before model calls. When nil, the core default downloader is used for unsupported URLs.
InstructionMessages[]types.MessageInstructionMessages supplies the agent's instructions as system messages (ai.GenerateTextOptions.InstructionMessages / StreamTextOptions equivalent), preserving per-message ProviderOptions. Takes precedence over Instructions/System/Prompt when non-empty.
PrepareStepfunc(ctx context.Context, step ai.PrepareStepOptions) ai.PrepareStepOptionsPrepareStep lets you provide different settings for a step. Forwarded to ai.GenerateText/StreamText for Generate/Stream (TS ToolLoopAgentSettings.prepareStep).
RepairToolCallai.ToolCallRepairFunctionRepairToolCall attempts to repair tool calls that fail to parse because the tool does not exist or its input is invalid. Forwarded to ai.GenerateText/StreamText for Generate/Stream.
ExperimentalRepairToolCallai.ToolCallRepairFunctionExperimentalRepairToolCall is a deprecated alias for RepairToolCall. Deprecated: use RepairToolCall.
OnLanguageModelCallStartai.OnLanguageModelCallStartCallbackOnLanguageModelCallStart is called immediately before each provider model call begins.
ExperimentalOnLanguageModelCallStartai.OnLanguageModelCallStartCallbackExperimentalOnLanguageModelCallStart is a deprecated alias for OnLanguageModelCallStart. Deprecated: use OnLanguageModelCallStart.
OnLanguageModelCallEndai.OnLanguageModelCallEndCallbackOnLanguageModelCallEnd is called after each provider model response is normalized and parsed, before client-side tool execution.
ExperimentalOnLanguageModelCallEndai.OnLanguageModelCallEndCallbackExperimentalOnLanguageModelCallEnd is a deprecated alias for OnLanguageModelCallEnd. Deprecated: use OnLanguageModelCallEnd.
OnStepStartfunc(stepNum int)Legacy/Basic Callbacks
OnStepEndfunc(step types.StepResult)
OnStepFinishfunc(step types.StepResult)Deprecated: use OnStepEnd.
OnToolCallfunc(toolCall types.ToolCall)
OnToolResultfunc(toolResult types.ToolResult)
OnFinishfunc(result *AgentResult)
OnStartfunc(ctx context.Context, e ai.OnStartEvent)OnStart is called once when agent execution begins.
OnStepStartEventfunc(ctx context.Context, e ai.OnStepStartEvent)OnStepStart is called at the beginning of each LLM step.
OnToolExecutionStartfunc(ctx context.Context, e ai.OnToolCallStartEvent)OnToolExecutionStart is called just before each tool's Execute function runs.
OnToolExecutionEndfunc(ctx context.Context, e ai.OnToolCallFinishEvent)OnToolExecutionEnd is called after each tool's Execute function returns.
OnToolCallStartfunc(ctx context.Context, e ai.OnToolCallStartEvent)OnToolCallStart is the previous Go name for OnToolExecutionStart. Deprecated: use OnToolExecutionStart.
OnToolCallFinishfunc(ctx context.Context, e ai.OnToolCallFinishEvent)OnToolCallFinish is the previous Go name for OnToolExecutionEnd. Deprecated: use OnToolExecutionEnd.
OnStepEndEventfunc(ctx context.Context, e ai.OnStepFinishEvent)OnStepEndEvent is called at the end of each LLM step.
OnStepFinishEventfunc(ctx context.Context, e ai.OnStepFinishEvent)OnStepFinishEvent is called at the end of each LLM step. Deprecated: use OnStepEndEvent.
OnEndEventfunc(ctx context.Context, e ai.OnFinishEvent)OnEndEvent is called once when agent execution completes.
OnFinishEventfunc(ctx context.Context, e ai.OnFinishEvent)OnFinishEvent is a deprecated alias for OnEndEvent. Deprecated: use OnEndEvent.
OnChainStartfunc(input string, messages []types.Message)OnChainStart is called when the agent begins execution Use this to initialize resources, start timers, or log the beginning of a chain
OnChainEndfunc(result *AgentResult)OnChainEnd is called when the agent completes successfully Use this to clean up resources, log completion, or process final results
OnChainErrorfunc(err error)OnChainError is called when the agent encounters an error during execution Use this for error logging, cleanup, or triggering fallback mechanisms
OnAgentActionfunc(action AgentAction)OnAgentAction is called when the agent decides to take an action (e.g., call a tool) This is invoked before tool execution begins Use this to log agent decisions or implement custom action approval logic
OnAgentFinishfunc(finish AgentFinish)OnAgentFinish is called when the agent reaches a final answer (no more tool calls) This differs from OnChainEnd as it's called when the agent decides it's done, even if more processing remains
OnToolStartfunc(toolCall types.ToolCall)OnToolStart is called immediately before a tool begins execution Use this to log tool invocations or start performance timers
OnToolEndfunc(toolResult types.ToolResult)OnToolEnd is called after a tool successfully completes execution Use this to log successful tool completions or process tool outputs
OnToolErrorfunc(toolCall types.ToolCall, err error)OnToolError is called when a tool execution fails Use this for error logging, retry logic, or fallback mechanisms
ToolApprovalRequiredboolToolApprovalRequired determines if tools require approval before execution
ToolApproverfunc(toolCall types.ToolCall) boolToolApprover is called when a tool needs approval (if ToolApprovalRequired is true) Should return true to approve, false to reject
ToolApprovaltypes.ToolApprovalConfigToolApproval configures automatic approval handling. Supported values are types.ToolApprovalFunc and maps keyed by tool name. Nil or zero-valued results are treated as not-applicable.
ExperimentalToolApprovalSecret[]byteExperimentalToolApprovalSecret signs issued tool approval requests and verifies resumed approval responses before tools execute (TS experimental_toolApprovalSecret). Nil disables signing/verification.

PrepareCallConfig​

PrepareCall returns a PrepareCallConfig to override settings for one call.

FieldTypeDescription
StepNumberintStepNumber is the current step number
Modelprovider.LanguageModelModel is the language model for this call.
SystemstringSystem prompt for this call
AllowSystemInMessagesboolAllowSystemInMessages controls whether system-role messages are accepted in this call's message list.
PromptstringPrompt is the per-call user prompt when the caller used Prompt instead of Messages.
Messages[]types.MessageMessages for this call
Tools[]types.ToolTools available for this call
ActiveTools[]stringActiveTools restricts Tools by name before calling the model.
ToolChoicetypes.ToolChoiceToolChoice controls how the model may call tools for this call.
ToolOrder[]stringToolOrder controls the order tools are sent to providers for this call.
ExperimentalToolCallersai.ExperimentalToolCallersExperimentalToolCallers configures which tools may call which other tools for this call.
ToolApprovaltypes.ToolApprovalConfigToolApproval configures automatic approval handling for this call.
ExperimentalToolApprovalSecret[]byteExperimentalToolApprovalSecret overrides the approval signing secret for this call.
SensitiveRuntimeContextboolSensitiveRuntimeContext omits runtime context from telemetry payloads.
CallOptionsinterface{}CallOptions are validated and passed through from AgentConfig.
Temperature*float64Temperature for this call
MaxTokens*intMaxTokens for this call
TopP*float64TopP controls nucleus sampling.
TopK*intTopK controls top-k sampling for providers that support it.
FrequencyPenalty*float64FrequencyPenalty reduces repetition.
PresencePenalty*float64PresencePenalty encourages topic diversity.
StopSequences[]stringStopSequences halt generation when encountered.
Seed*intSeed enables deterministic generation when supported by the provider.
Headersmap[string]stringHeaders are custom request headers forwarded to the provider.
Reasoning*types.ReasoningLevelReasoning configures provider reasoning effort.
SendReasoning*boolSendReasoning controls whether reasoning stream/content parts are exposed.
ProviderOptionsmap[string]interface{}ProviderOptions are provider-specific options keyed by provider name.
StopWhen[]ai.StopConditionStopWhen defines conditions that can terminate the tool loop.
Outputinterface{}Output specifies how to handle and parse model output.
Telemetry*ai.TelemetrySettingsTelemetry configures observability for this call.
ExperimentalTelemetry*ai.TelemetrySettingsExperimentalTelemetry is a deprecated alias for Telemetry.
Include*ai.IncludeOptionsInclude controls retained request/response details.
Internal*ai.InternalOptionsInternal contains test-only ID generators matching TypeScript _internal.
ExperimentalSandboxinterface{}ExperimentalSandbox is the sandbox environment for this step.
ExperimentalRefineToolInputmap[string]ai.ToolInputRefinerExperimentalRefineToolInput refines parsed tool input before execution.
ExperimentalDownloadai.DownloadFunctionExperimentalDownload customizes prompt URL download handling.
InstructionMessages[]types.MessageInstructionMessages supplies this step's instructions as system messages. See AgentConfig.InstructionMessages.
PrepareStepfunc(ctx context.Context, step ai.PrepareStepOptions) ai.PrepareStepOptionsPrepareStep lets you provide different settings for a step. See AgentConfig.PrepareStep.
RepairToolCallai.ToolCallRepairFunctionRepairToolCall attempts to repair tool calls that fail to parse for this step.
OnLanguageModelCallStartai.OnLanguageModelCallStartCallbackOnLanguageModelCallStart is called immediately before this step's provider model call begins.
OnLanguageModelCallEndai.OnLanguageModelCallEndCallbackOnLanguageModelCallEnd is called after this step's provider model response is normalized and parsed, before client-side tool execution.
RuntimeContextinterface{}RuntimeContext is user-defined runtime data for this call.
ToolsContextmap[string]interface{}ToolsContext contains per-tool execution context keyed by tool name.
PreviousSteps[]types.StepResultPreviousSteps contains completed step results before this call.
AccumulatedUsagetypes.UsageAccumulatedUsage is the total usage so far
CustomDatainterface{}CustomData allows passing custom data between PrepareCall invocations
MaxRetries*intMaxRetries controls transient provider call retries for this call.
Timeout*ai.TimeoutConfigTimeout provides granular timeout controls for this call, the Go stand-in for TS's per-call abortSignal.

Tool approval signing​

ExperimentalToolApprovalSecret is a byte slice. When it is set, the SDK signs every approval request it issues with HMAC-SHA256 and verifies the signature on the approval response before it runs the tool. A client that edits the tool name, the tool call ID or the tool input between the request and the response fails verification. When it is nil, requests are not signed and responses are not verified. The signing functions are ai.SignToolApproval and ai.VerifyToolApprovalSignature; see Tool approval helpers.

See Also​