agent

package
v0.2.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package agent provides autonomous tool-calling agent functionality for the gains library.

An agent orchestrates a conversation loop where the model can request tool calls, which are automatically executed and the results fed back to the model until the model produces a final response without tool calls.

Basic Usage

Create a registry, register tools with their handlers, then create an agent:

// Define tool arguments
type WeatherArgs struct {
    Location string `json:"location" desc:"City name" required:"true"`
}

// Create registry and register tool
registry := tool.NewRegistry()
tool.MustRegisterFunc(registry, "get_weather", "Get current weather",
    func(ctx context.Context, args WeatherArgs) (string, error) {
        return fmt.Sprintf(`{"temp": 72, "location": %q}`, args.Location), nil
    },
)

// Create agent
a := agent.New(client, registry)

// Run and get final result (blocking)
result, err := a.Run(ctx, messages, agent.WithMaxSteps(5))

Streaming Events

Use RunStream() to receive events as the agent executes:

import "github.com/spetersoncode/gains/event"

events := a.RunStream(ctx, messages, agent.WithMaxSteps(5))
for e := range events {
    switch e.Type {
    case event.MessageDelta:
        fmt.Print(e.Delta)
    case event.ToolCallStart:
        fmt.Printf("[Tool: %s]\n", e.ToolCall.Name)
    case event.RunEnd:
        fmt.Println("Done!")
    }
}

Human-in-the-Loop Approval

Use WithApprover to require approval before tool execution:

events := a.Run(ctx, messages,
    agent.WithApprover(func(ctx context.Context, call gains.ToolCall) (bool, string) {
        fmt.Printf("Approve %s? (y/n): ", call.Name)
        var input string
        fmt.Scanln(&input)
        return input == "y", "User rejected"
    }),
)

Configuration Options

The agent supports various configuration options:

  • WithMaxSteps(n): Limit iterations to prevent infinite loops (default: 10)
  • WithTimeout(d): Set overall execution timeout
  • WithHandlerTimeout(d): Set per-handler timeout (default: 30s)
  • WithParallelToolCalls(bool): Enable/disable parallel tool execution (default: true)
  • WithApprover(fn): Enable human-in-the-loop approval
  • WithApprovalRequired(tools...): Require approval only for specific tools
  • WithStopPredicate(fn): Custom termination condition
  • WithChatOptions(opts...): Pass options to underlying ChatProvider

Termination Conditions

The agent stops when any of these conditions are met:

  • The model responds without tool calls (TerminationComplete)
  • MaxSteps is reached (TerminationMaxSteps)
  • Timeout is exceeded (TerminationTimeout)
  • Context is cancelled (TerminationCancelled)
  • StopPredicate returns true (TerminationCustom)
  • All tool calls are rejected (TerminationRejected)
  • An error occurs (TerminationError)

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMaxStepsReached indicates the agent hit the step limit.
	ErrMaxStepsReached = errors.New("agent: maximum steps reached")

	// ErrAgentTimeout indicates the overall timeout was exceeded.
	ErrAgentTimeout = errors.New("agent: timeout exceeded")
)

Sentinel errors for agent termination conditions.

Functions

func NewTool added in v0.2.9

func NewTool(name string, a *Agent, opts ...ToolOption) tool.Registration

NewTool creates a tool registration that wraps an agent as a callable tool. This enables sub-agent patterns where one agent can delegate tasks to specialized agents.

By default, the tool accepts ToolArgs (a simple query field) and runs the agent with a user message containing the query. The final response content is returned.

Example:

// Create a specialized research agent
researchAgent := agent.New(client, researchTools)

// Register it as a tool in the main agent's registry
mainRegistry.Add(agent.NewTool("research", researchAgent,
    agent.WithToolDescription("Delegate complex research tasks to a specialized research agent"),
    agent.WithToolMaxSteps(5),
))

func NewToolFunc added in v0.2.9

func NewToolFunc[T any](name string, a *Agent, description string, toMessages func(args T) []ai.Message, opts ...ToolOption) tool.Registration

NewToolFunc creates a tool registration with a custom typed argument handler. This provides type-safe argument handling for agent tools.

Example:

type ResearchArgs struct {
    Topic     string `json:"topic" desc:"Research topic" required:"true"`
    MaxDepth  int    `json:"maxDepth" desc:"Maximum research depth" default:"2"`
}

mainRegistry.Add(agent.NewToolFunc("research", researchAgent, "Research a topic",
    func(args ResearchArgs) []ai.Message {
        return []ai.Message{
            ai.NewUserMessage(fmt.Sprintf("Research %s with depth %d", args.Topic, args.MaxDepth)),
        }
    },
))

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent orchestrates autonomous tool-calling conversations.

func New

func New(c chat.Client, registry *tool.Registry) *Agent

New creates a new Agent with the given chat client and tool registry.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, messages []ai.Message, opts ...Option) (*Result, error)

Run executes the agent loop and returns the final result. This is a blocking call that runs until the agent completes.

func (*Agent) RunStream

func (a *Agent) RunStream(ctx context.Context, messages []ai.Message, opts ...Option) <-chan Event

RunStream executes the agent loop and returns a channel of events. The channel is closed when the agent completes or encounters a fatal error. Callers should drain the channel to ensure proper cleanup.

type ApprovalBroker added in v0.2.9

type ApprovalBroker struct {
	// contains filtered or unexported fields
}

ApprovalBroker manages async tool approvals for AG-UI integration. It receives approval decisions from the frontend via a channel and routes them to waiting approval requests.

Usage:

broker := agent.NewApprovalBroker()
go func() {
    for decision := range frontendDecisions {
        broker.Decide(decision)
    }
}()
result, err := agent.Run(ctx, messages,
    agent.WithApprover(broker.Approver()),
)

func NewApprovalBroker added in v0.2.9

func NewApprovalBroker() *ApprovalBroker

NewApprovalBroker creates a new ApprovalBroker. The default timeout for waiting on decisions is 5 minutes.

func NewApprovalBrokerWith added in v0.2.9

func NewApprovalBrokerWith(opts ...ApprovalBrokerOption) *ApprovalBroker

NewApprovalBrokerWith creates a new ApprovalBroker with options.

func (*ApprovalBroker) Approve added in v0.2.9

func (b *ApprovalBroker) Approve(toolCallID string) error

Approve is a convenience method to approve a tool call.

func (*ApprovalBroker) Approver added in v0.2.9

func (b *ApprovalBroker) Approver() ApproverFunc

Approver returns an ApproverFunc that can be used with WithApprover. The returned function blocks until a decision is received or the context is cancelled.

func (*ApprovalBroker) Decide added in v0.2.9

func (b *ApprovalBroker) Decide(decision ApprovalDecision) error

Decide sends an approval decision to the broker. The decision will be routed to the waiting approval request for the specified tool call ID.

Returns an error if there is no pending approval for the given tool call ID.

func (*ApprovalBroker) HasPending added in v0.2.9

func (b *ApprovalBroker) HasPending() bool

HasPending returns true if there are any pending approval requests.

func (*ApprovalBroker) PendingCount added in v0.2.9

func (b *ApprovalBroker) PendingCount() int

PendingCount returns the number of pending approval requests.

func (*ApprovalBroker) Reject added in v0.2.9

func (b *ApprovalBroker) Reject(toolCallID, reason string) error

Reject is a convenience method to reject a tool call.

type ApprovalBrokerOption added in v0.2.9

type ApprovalBrokerOption func(*ApprovalBroker)

ApprovalBrokerOption configures an ApprovalBroker.

func WithApprovalTimeout added in v0.2.9

func WithApprovalTimeout(d time.Duration) ApprovalBrokerOption

WithApprovalTimeout sets the timeout for waiting on approval decisions.

func WithOnSubmit added in v0.2.9

func WithOnSubmit(fn func(call ai.ToolCall)) ApprovalBrokerOption

WithOnSubmit sets a callback that's called when an approval request is submitted. This is useful for tracking or logging approval requests.

type ApprovalDecision added in v0.2.9

type ApprovalDecision struct {
	ToolCallID string // ID of the tool call being approved/rejected
	Approved   bool   // Whether the tool call was approved
	Reason     string // Reason for rejection (empty if approved)
}

ApprovalDecision represents a user's decision on a tool call.

type ApproverFunc

type ApproverFunc func(ctx context.Context, call ai.ToolCall) (approved bool, reason string)

ApproverFunc is called when a tool call requires approval. It returns true to approve the call, or false with a reason to reject it. The rejection reason is sent back to the model as an error result.

type Event

type Event = event.Event

Event is an alias to the unified event type. Agent events use these event.Type values:

  • event.RunStart, event.RunEnd, event.RunError
  • event.StepStart, event.StepEnd
  • event.MessageStart, event.MessageDelta, event.MessageEnd
  • event.ToolCallStart, event.ToolCallArgs, event.ToolCallEnd, event.ToolCallResult
  • event.ToolCallApproved, event.ToolCallRejected, event.ToolCallExecuting

type InputType added in v0.2.9

type InputType string

InputType specifies the kind of user input expected.

const (
	// InputTypeConfirm requests a yes/no confirmation.
	InputTypeConfirm InputType = "confirm"

	// InputTypeText requests free-form text input.
	InputTypeText InputType = "text"

	// InputTypeChoice requests selection from a list of options.
	InputTypeChoice InputType = "choice"
)

type Option

type Option func(*Options)

Option is a functional option for configuring agent execution.

func WithApprovalRequired

func WithApprovalRequired(tools ...string) Option

WithApprovalRequired specifies which tools require approval. If not called but WithApprover is used, all tools require approval. Call with specific tool names to only require approval for those tools.

func WithApprover

func WithApprover(fn ApproverFunc) Option

WithApprover sets the human-in-the-loop approval function. The function is called before each tool execution and must return an approval decision.

func WithChatOptions

func WithChatOptions(opts ...ai.Option) Option

WithChatOptions passes options through to the ChatProvider. These options are applied to every chat call made by the agent.

func WithHandlerTimeout

func WithHandlerTimeout(d time.Duration) Option

WithHandlerTimeout sets the timeout for each individual tool handler. Default is 30 seconds. Set to 0 for no per-handler timeout.

func WithMaxSteps

func WithMaxSteps(n int) Option

WithMaxSteps sets the maximum number of agent iterations. Default is 10. Set to 0 for unlimited (not recommended).

func WithMaxTokens

func WithMaxTokens(n int) Option

WithMaxTokens is a convenience option to set max tokens for chat calls.

func WithModel

func WithModel(model ai.Model) Option

WithModel is a convenience option to set the model for chat calls.

func WithParallelToolCalls

func WithParallelToolCalls(enabled bool) Option

WithParallelToolCalls enables or disables concurrent tool execution. Default is true.

func WithStopPredicate

func WithStopPredicate(fn StopFunc) Option

WithStopPredicate sets a custom termination condition. The predicate is called after each step with the step number and response. Return true to stop the agent.

func WithTemperature

func WithTemperature(t float64) Option

WithTemperature is a convenience option to set temperature for chat calls.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets a deadline for the entire agent execution.

type Options

type Options struct {
	// MaxSteps limits the number of agent iterations.
	// Set to 0 for unlimited (not recommended). Default is 10.
	MaxSteps int

	// Timeout sets a deadline for the entire agent execution.
	// A value of 0 means no timeout (context deadline applies).
	Timeout time.Duration

	// HandlerTimeout sets the timeout for each individual tool handler.
	// A value of 0 means no per-handler timeout. Default is 30 seconds.
	HandlerTimeout time.Duration

	// ParallelToolCalls enables concurrent execution of multiple tool calls.
	// Default is true.
	ParallelToolCalls bool

	// Approver enables human-in-the-loop approval for tool calls.
	// If nil, all tool calls are automatically approved.
	Approver ApproverFunc

	// ApprovalRequired specifies which tool names require approval.
	// If empty and Approver is set, all tools require approval.
	// If non-empty, only the listed tools require approval.
	ApprovalRequired []string

	// StopPredicate is a custom termination condition.
	// Called after each step; return true to stop the agent.
	StopPredicate StopFunc

	// ChatOptions are passed through to the underlying ChatProvider.
	ChatOptions []ai.Option
}

Options contains configuration for agent execution.

func ApplyOptions

func ApplyOptions(opts ...Option) *Options

ApplyOptions applies functional options to an Options struct with defaults.

type Result

type Result struct {
	// Response is the final response from the model.
	Response *ai.Response

	// Steps is the number of iterations completed.
	Steps int

	// Termination indicates why execution stopped.
	Termination TerminationReason

	// TotalUsage aggregates token usage across all steps.
	TotalUsage ai.Usage

	// Error contains any error that caused termination (if applicable).
	Error error

	// PendingClientToolCalls contains tool calls awaiting client execution.
	// These are set when Termination is TerminationClientToolCall.
	PendingClientToolCalls []ai.ToolCall
	// contains filtered or unexported fields
}

Result represents the final outcome of an agent execution.

func (*Result) LastMessages

func (r *Result) LastMessages(n int) []ai.Message

LastMessages returns the last n messages from the conversation history. If n exceeds the total message count, all messages are returned.

func (*Result) MessageCount

func (r *Result) MessageCount() int

MessageCount returns the number of messages in the conversation history.

func (*Result) Messages

func (r *Result) Messages() []ai.Message

Messages returns the conversation history as a slice.

type Specialist added in v0.2.9

type Specialist struct {
	Name         string   // Unique identifier
	Description  string   // Description for tool registration
	Agent        *Agent   // The underlying agent
	Capabilities []string // Optional: capabilities this specialist provides
}

Specialist represents a specialized agent with metadata.

type SpecialistOption added in v0.2.9

type SpecialistOption func(*Specialist)

SpecialistOption configures a Specialist.

func WithCapabilities added in v0.2.9

func WithCapabilities(caps ...string) SpecialistOption

WithCapabilities sets capabilities for the specialist. Capabilities are used for capability-based routing.

type SpecialistRegistry added in v0.2.9

type SpecialistRegistry struct {
	// contains filtered or unexported fields
}

SpecialistRegistry manages a collection of specialized agents. It provides named lookup and easy tool registration for sub-agent patterns.

Example:

registry := agent.NewSpecialistRegistry()
registry.Register("research", "Research and gather information", researchAgent)
registry.Register("code", "Write and analyze code", codeAgent)

// Add all specialists as tools to a tool registry
toolRegistry := tool.NewRegistry()
for _, t := range registry.AsTools() {
    toolRegistry.Add(t)
}

func NewSpecialistRegistry added in v0.2.9

func NewSpecialistRegistry() *SpecialistRegistry

NewSpecialistRegistry creates an empty specialist registry.

func (*SpecialistRegistry) All added in v0.2.9

func (r *SpecialistRegistry) All() []*Specialist

All returns all registered specialists.

func (*SpecialistRegistry) AsTools added in v0.2.9

func (r *SpecialistRegistry) AsTools(opts ...ToolOption) []tool.Registration

AsTools converts all specialists to tool registrations. Use this to add all specialists as callable tools to a tool.Registry.

Example:

toolRegistry := tool.NewRegistry()
for _, t := range specialists.AsTools() {
    toolRegistry.Add(t)
}

func (*SpecialistRegistry) AsToolsWith added in v0.2.9

func (r *SpecialistRegistry) AsToolsWith(optsFunc func(*Specialist) []ToolOption) []tool.Registration

AsToolsWith converts specialists to tools with per-specialist options. The optsFunc receives the specialist and returns tool options for it.

func (*SpecialistRegistry) ByCapability added in v0.2.9

func (r *SpecialistRegistry) ByCapability(capability string) []*Specialist

ByCapability returns all specialists that have the given capability.

func (*SpecialistRegistry) Get added in v0.2.9

func (r *SpecialistRegistry) Get(name string) *Specialist

Get retrieves a specialist by name. Returns nil if not found.

func (*SpecialistRegistry) GetAgent added in v0.2.9

func (r *SpecialistRegistry) GetAgent(name string) *Agent

GetAgent retrieves an agent by specialist name. Returns nil if not found.

func (*SpecialistRegistry) Has added in v0.2.9

func (r *SpecialistRegistry) Has(name string) bool

Has returns true if a specialist with the given name exists.

func (*SpecialistRegistry) Len added in v0.2.9

func (r *SpecialistRegistry) Len() int

Len returns the number of registered specialists.

func (*SpecialistRegistry) Names added in v0.2.9

func (r *SpecialistRegistry) Names() []string

Names returns all registered specialist names.

func (*SpecialistRegistry) Register added in v0.2.9

func (r *SpecialistRegistry) Register(name, description string, agent *Agent, opts ...SpecialistOption) *SpecialistRegistry

Register adds a specialist agent to the registry. If a specialist with the same name already exists, it is replaced.

func (*SpecialistRegistry) RegisterTo added in v0.2.9

func (r *SpecialistRegistry) RegisterTo(toolRegistry *tool.Registry, opts ...ToolOption)

RegisterTo adds all specialists as tools to the given tool registry. This is a convenience method combining AsTools and registry.Add.

func (*SpecialistRegistry) Unregister added in v0.2.9

func (r *SpecialistRegistry) Unregister(name string)

Unregister removes a specialist from the registry. It is a no-op if the specialist does not exist.

type StopFunc

type StopFunc func(step int, response *ai.Response) bool

StopFunc is a custom predicate to determine if the agent should stop. It receives the current step number and the latest response. Return true to stop the agent.

type TerminationReason

type TerminationReason string

TerminationReason indicates why the agent stopped execution.

const (
	// TerminationComplete indicates normal completion (no more tool calls).
	TerminationComplete TerminationReason = "complete"

	// TerminationMaxSteps indicates the step limit was reached.
	TerminationMaxSteps TerminationReason = "max_steps"

	// TerminationTimeout indicates the context deadline was exceeded.
	TerminationTimeout TerminationReason = "timeout"

	// TerminationCustom indicates a custom stop predicate returned true.
	TerminationCustom TerminationReason = "custom"

	// TerminationRejected indicates all tool calls were rejected.
	TerminationRejected TerminationReason = "rejected"

	// TerminationError indicates an unrecoverable error occurred.
	TerminationError TerminationReason = "error"

	// TerminationCancelled indicates context cancellation.
	TerminationCancelled TerminationReason = "cancelled"

	// TerminationClientToolCall indicates the model called a client-side tool.
	// The frontend should execute the tool and resume with the result.
	TerminationClientToolCall TerminationReason = "client_tool_call"
)

type ToolArgs added in v0.2.9

type ToolArgs struct {
	Query string `json:"query" desc:"The query or task for the agent" required:"true"`
}

ToolArgs is the default argument type for agent tools. It provides a simple query-based interface for invoking sub-agents.

type ToolOption added in v0.2.9

type ToolOption func(*toolConfig)

ToolOption configures an agent tool.

func WithToolAgentOptions added in v0.2.9

func WithToolAgentOptions(opts ...Option) ToolOption

WithToolAgentOptions passes options through to the agent.

func WithToolArgsMapper added in v0.2.9

func WithToolArgsMapper(mapper func(call ai.ToolCall) ([]ai.Message, error)) ToolOption

WithToolArgsMapper sets a custom function to convert tool arguments to messages. The function receives the raw tool call and should return the messages to send to the agent.

func WithToolDescription added in v0.2.9

func WithToolDescription(desc string) ToolOption

WithToolDescription sets a custom description for the agent tool.

func WithToolEventForwarding added in v0.2.9

func WithToolEventForwarding() ToolOption

WithToolEventForwarding enables event forwarding from the sub-agent to the parent. When enabled and a forwarding channel is available in the context, all sub-agent events are forwarded to the parent event stream for observability.

This allows the parent agent (or AG-UI frontend) to observe sub-agent progress: - Streaming message deltas from the sub-agent - Tool calls made by the sub-agent - Step progress within the sub-agent

Example:

mainRegistry.Add(agent.NewTool("research", researchAgent,
    agent.WithToolEventForwarding(),
    agent.WithToolDescription("Research a topic with observable progress"),
))

func WithToolMaxSteps added in v0.2.9

func WithToolMaxSteps(n int) ToolOption

WithToolMaxSteps sets the maximum steps for the sub-agent.

func WithToolSchema added in v0.2.9

func WithToolSchema(schema json.RawMessage) ToolOption

WithToolSchema sets a custom parameter schema for the agent tool. Use this when you want different arguments than the default ToolArgs.

type UserInputBroker added in v0.2.9

type UserInputBroker struct {
	// contains filtered or unexported fields
}

UserInputBroker manages async user input requests for AG-UI integration. It receives responses from the frontend and routes them to waiting requests.

Usage:

broker := agent.NewUserInputBroker()

// In your HTTP handler, route frontend responses to the broker
go func() {
    for response := range frontendResponses {
        broker.Respond(response)
    }
}()

// Agents can request input using the broker
response, err := broker.RequestConfirm(ctx, "Delete file?", "This cannot be undone.")

func NewUserInputBroker added in v0.2.9

func NewUserInputBroker() *UserInputBroker

NewUserInputBroker creates a new UserInputBroker. The default timeout for waiting on responses is 5 minutes.

func NewUserInputBrokerWith added in v0.2.9

func NewUserInputBrokerWith(opts ...UserInputBrokerOption) *UserInputBroker

NewUserInputBrokerWith creates a new UserInputBroker with options.

func (*UserInputBroker) HasPending added in v0.2.9

func (b *UserInputBroker) HasPending() bool

HasPending returns true if there are any pending input requests.

func (*UserInputBroker) PendingCount added in v0.2.9

func (b *UserInputBroker) PendingCount() int

PendingCount returns the number of pending input requests.

func (*UserInputBroker) Request added in v0.2.9

Request sends a user input request and waits for a response. This is the low-level method; prefer the typed methods like RequestConfirm.

func (*UserInputBroker) RequestChoice added in v0.2.9

func (b *UserInputBroker) RequestChoice(ctx context.Context, title, message string, choices []string, defaultChoice string) (string, error)

RequestChoice requests the user to select from a list of choices. Returns the selected choice, or empty string if cancelled.

func (*UserInputBroker) RequestConfirm added in v0.2.9

func (b *UserInputBroker) RequestConfirm(ctx context.Context, title, message string) (bool, error)

RequestConfirm requests a yes/no confirmation from the user. Returns true if confirmed, false if rejected or cancelled.

func (*UserInputBroker) RequestText added in v0.2.9

func (b *UserInputBroker) RequestText(ctx context.Context, title, message, placeholder, defaultValue string) (string, error)

RequestText requests text input from the user. Returns the entered text, or empty string if cancelled.

func (*UserInputBroker) Respond added in v0.2.9

func (b *UserInputBroker) Respond(response UserInputResponse) error

Respond sends a user response to the broker. The response will be routed to the waiting input request. Returns an error if there is no pending request for the given ID.

type UserInputBrokerOption added in v0.2.9

type UserInputBrokerOption func(*UserInputBroker)

UserInputBrokerOption configures a UserInputBroker.

func WithInputTimeout added in v0.2.9

func WithInputTimeout(d time.Duration) UserInputBrokerOption

WithInputTimeout sets the timeout for waiting on user responses.

func WithOnInputSubmit added in v0.2.9

func WithOnInputSubmit(fn func(req UserInputRequest)) UserInputBrokerOption

WithOnInputSubmit sets a callback that's called when an input request is submitted. This is useful for emitting AG-UI activity events.

type UserInputRequest added in v0.2.9

type UserInputRequest struct {
	ID          string    `json:"id"`                    // Unique identifier for this request
	Type        InputType `json:"type"`                  // Type of input expected
	Title       string    `json:"title,omitempty"`       // Optional title for the dialog
	Message     string    `json:"message"`               // The prompt message
	Choices     []string  `json:"choices,omitempty"`     // Options for InputTypeChoice
	Default     string    `json:"default,omitempty"`     // Default value
	Placeholder string    `json:"placeholder,omitempty"` // Placeholder for text input
}

UserInputRequest represents a request for user input. This is used for confirmation dialogs, text prompts, and choice selections.

type UserInputResponse added in v0.2.9

type UserInputResponse struct {
	RequestID string `json:"requestId"` // ID of the request being responded to
	Value     string `json:"value"`     // The user's input value
	Confirmed bool   `json:"confirmed"` // For confirm type: true if confirmed
	Cancelled bool   `json:"cancelled"` // True if user cancelled/dismissed
}

UserInputResponse represents the user's response to an input request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL