agent

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 18 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agent provides the agent runtime: one streaming-first execution loop, typed tools, provider-neutral models, optional sessions, policy and event seams.

Index

Constants

View Source
const DefaultMaxSteps = 8

DefaultMaxSteps is the step budget used when Budget.MaxSteps is zero.

View Source
const DefaultToolTimeout = 2 * time.Minute

DefaultToolTimeout bounds a single tool execution when RunOptions.ToolTimeout is zero.

Variables

View Source
var (
	// ErrAgentRequired is returned when a nil agent is run.
	ErrAgentRequired = errors.New("agent: agent is required")
	// ErrModelRequired is returned when an agent has no model.
	ErrModelRequired = errors.New("agent: model is required")
	// ErrNameRequired is returned when an agent has no name.
	ErrNameRequired = errors.New("agent: name is required")
	// ErrDuplicateTool is returned when two tools share a name.
	ErrDuplicateTool = errors.New("agent: duplicate tool name")
	// ErrToolNil is returned when a tool list contains a typed nil.
	ErrToolNil = errors.New("agent: tool is nil")
	// ErrToolNameRequired is returned when a tool spec has no name.
	ErrToolNameRequired = errors.New("agent: tool name is required")
	// ErrSessionRequired is returned when a store is configured without a
	// session.
	ErrSessionRequired = errors.New("agent: session is required when a store is configured")
	// ErrSessionIDRequired is returned when a session has no ID.
	ErrSessionIDRequired = errors.New("agent: session id is required")
	// ErrMaxSteps is returned with a partial response when the run uses its
	// full step budget.
	ErrMaxSteps = errors.New("agent: max steps exceeded")
	// ErrBudgetExceeded is returned when a run exceeds its token, call, or
	// time budget.
	ErrBudgetExceeded = errors.New("agent: budget exceeded")
	// ErrTerminated is returned when a policy terminates a run.
	ErrTerminated = errors.New("agent: run terminated by policy")
	// ErrToolDenied marks a call a policy denied or left unresolved. It is
	// reported on ToolEnd.Err and in the tool result message; the run
	// continues.
	ErrToolDenied = errors.New("agent: tool call denied")
	// ErrOutputSchema is returned when a structured output schema cannot be
	// generated from the requested type.
	ErrOutputSchema = errors.New("agent: invalid output schema")
	// ErrResponseRequired is returned when a model or policy produces no
	// response.
	ErrResponseRequired = errors.New("agent: response is required")
	// ErrRunCanceled is returned when a run is canceled without a more
	// specific cause.
	ErrRunCanceled = errors.New("agent: run canceled")
)

Functions

This section is empty.

Types

type Agent

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

Agent is reusable behavior: instructions, a model, tools, and optional defaults for policy, persistence, and run options. It does not own per-run execution state. ApplyAgentOptions layers those defaults over one run's RunOptions.

func New

func New(cfg Config) (*Agent, error)

New creates an immutable Agent.

func (*Agent) ApplyAgentOptions

func (a *Agent) ApplyAgentOptions(opts RunOptions) RunOptions

ApplyAgentOptions fills unset run options from the agent's configuration. Explicit run values win; zero values inherit the agent-level value. Budget and RetryPolicy merge field by field, so a run can change one limit without dropping the others.

The returned options never alias the agent's pointer-valued sampling options: inherited values are cloned before they are applied. Interface values such as Model, Policy, Approver, and Store are shared. A nil agent returns opts unchanged.

func (*Agent) AsTool

func (a *Agent) AsTool() tool.Tool

AsTool exposes the agent as a tool with default configuration so another agent can delegate to it.

func (*Agent) AsToolWith

func (a *Agent) AsToolWith(cfg AsToolConfig) tool.Tool

AsToolWith exposes the agent as a tool so another agent can delegate to it.

func (*Agent) Description

func (a *Agent) Description() string

Description returns the agent description.

func (*Agent) Generate

func (a *Agent) Generate(ctx context.Context, prompt string, opts ...Option) (*Response, error)

Generate runs the agent with a text prompt.

func (*Agent) GenerateMessages

func (a *Agent) GenerateMessages(ctx context.Context, messages []llm.Message, opts ...Option) (*Response, error)

GenerateMessages runs the agent with explicit messages.

func (*Agent) GenerateMessagesWith

func (a *Agent) GenerateMessagesWith(ctx context.Context, messages []llm.Message, opts RunOptions) (*Response, error)

GenerateMessagesWith runs the agent with explicit messages and RunOptions.

func (*Agent) GenerateWith

func (a *Agent) GenerateWith(ctx context.Context, prompt string, opts RunOptions) (*Response, error)

GenerateWith runs the agent with a complete RunOptions value.

func (*Agent) Instructions

func (a *Agent) Instructions() string

Instructions returns the system instructions.

func (*Agent) Name

func (a *Agent) Name() string

Name returns the agent name.

func (*Agent) Stream

func (a *Agent) Stream(ctx context.Context, prompt string, opts ...Option) (*Run, error)

Stream runs the agent asynchronously and returns its Run handle.

func (*Agent) StreamMessages

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

StreamMessages runs the agent asynchronously with explicit messages.

func (*Agent) StreamMessagesWith

func (a *Agent) StreamMessagesWith(ctx context.Context, messages []llm.Message, opts RunOptions) (*Run, error)

StreamMessagesWith runs the agent asynchronously with explicit messages and RunOptions.

func (*Agent) StreamWith

func (a *Agent) StreamWith(ctx context.Context, prompt string, opts RunOptions) (*Run, error)

StreamWith runs the agent asynchronously with a complete RunOptions value.

func (*Agent) Tools

func (a *Agent) Tools() []tool.Tool

Tools returns a copy of the tool list, sorted by name.

type Approver

type Approver interface {
	Approve(ctx context.Context, req ToolRequest) (bool, error)
}

Approver resolves Ask decisions. An approval request contains the same call metadata a policy sees.

type ApproverFunc

type ApproverFunc func(ctx context.Context, req ToolRequest) (bool, error)

ApproverFunc adapts a function to Approver.

func (ApproverFunc) Approve

func (f ApproverFunc) Approve(ctx context.Context, req ToolRequest) (bool, error)

Approve implements Approver.

type AsToolConfig

type AsToolConfig struct {
	// Name overrides the tool name. Defaults to the sanitized agent name.
	Name string
	// Description overrides the tool description. Defaults to the agent
	// description.
	Description string
	// Options configures the subagent run. Defaults to zero-value options.
	Options RunOptions
}

AsToolConfig configures an agent tool.

type Budget

type Budget struct {
	// MaxSteps is the maximum number of model calls. Zero uses
	// DefaultMaxSteps.
	MaxSteps int
	// MaxToolCalls is the maximum number of tool executions. Zero is
	// unlimited.
	MaxToolCalls int
	// MaxTotalTokens is the maximum cumulative token usage. Zero is unlimited.
	MaxTotalTokens int
	// MaxDuration bounds wall-clock execution. Zero is unlimited.
	MaxDuration time.Duration
}

Budget bounds a run. Zero values mean "use the default" for MaxSteps and "unlimited" for the other fields.

type Config

type Config struct {
	// Name uniquely identifies the agent. Required.
	Name string
	// Description explains the agent's purpose, especially when exposed as a
	// tool for subagents.
	Description string
	// Instructions is the system prompt.
	Instructions string
	// Model powers the agent. Required.
	Model llm.Model
	// Tools are the capabilities available to the model.
	Tools []tool.Tool
	// Policy is the agent's default policy. A RunOptions policy may override it.
	Policy Policy
	// Approver resolves Ask decisions. A run approver replaces it.
	Approver Approver
	// Store persists conversations. The session identity remains per-run: a
	// run without a Session fails with ErrSessionRequired.
	Store session.Store
	// Budget bounds each run. Non-zero run budget fields override individual
	// values.
	Budget Budget
	// Retry configures transient model retries. Non-zero run fields override
	// individual values; set MaxAttempts to 1 in RunOptions to disable
	// inherited retries.
	Retry RetryPolicy
	// ToolTimeout bounds each tool execution. Zero uses DefaultToolTimeout; a
	// negative value disables the timeout.
	ToolTimeout time.Duration

	// Reasoning configures reasoning.
	Reasoning *llm.ReasoningConfig
	// ResponseFormat constrains structured output.
	ResponseFormat *llm.ResponseFormat
	// Temperature sets sampling temperature.
	Temperature *float64
	// MaxTokens sets the output token limit.
	MaxTokens *int
	// TopP sets nucleus sampling.
	TopP *float64
	// ToolChoice constrains tool selection.
	ToolChoice llm.ToolChoice
}

Config configures an Agent.

type Decision

type Decision int

Decision is a policy's verdict for a tool call.

const (
	// DecisionUnknown is the zero value. It is treated as Deny so a policy
	// that fails to return a decision fails closed.
	DecisionUnknown Decision = iota
	// Allow executes the tool.
	Allow
	// Deny skips the tool and reports the denial to the model.
	Deny
	// Ask requires an approver. Without one, the call is denied.
	Ask
	// Terminate aborts the run.
	Terminate
)

func (Decision) String

func (d Decision) String() string

String renders a decision.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is emitted by a run. Events are observations only; they cannot change execution.

type Hooks

type Hooks struct {
	OnBeforeModel func(ctx context.Context, req *ModelRequest) error
	OnAfterModel  func(ctx context.Context, result *ModelResult)
	OnBeforeTool  func(ctx context.Context, req *ToolRequest) (Decision, error)
	OnAfterTool   func(ctx context.Context, result *ToolResult)
}

Hooks is a function-field Policy. Every field is optional.

func (Hooks) AfterModel

func (h Hooks) AfterModel(ctx context.Context, result *ModelResult) error

AfterModel implements Policy.

func (Hooks) AfterTool

func (h Hooks) AfterTool(ctx context.Context, result *ToolResult) error

AfterTool implements Policy.

func (Hooks) BeforeModel

func (h Hooks) BeforeModel(ctx context.Context, req *ModelRequest) error

BeforeModel implements Policy.

func (Hooks) BeforeTool

func (h Hooks) BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error)

BeforeTool implements Policy.

type MessageEnd

type MessageEnd struct {
	Step    int
	Message *llm.Message
}

MessageEnd is emitted with the completed assistant message.

type MessageStart

type MessageStart struct {
	Step int
}

MessageStart is emitted before streamed assistant output.

type ModelRequest

type ModelRequest struct {
	Step    int
	Request *llm.Request
}

ModelRequest is passed to Policy.BeforeModel.

type ModelResult

type ModelResult struct {
	Step     int
	Request  *llm.Request
	Response *llm.Response
	Err      error
}

ModelResult is passed to Policy.AfterModel.

type Option

type Option func(*RunOptions)

Option customizes one Agent run.

func WithApprover

func WithApprover(approver Approver) Option

WithApprover resolves Ask decisions for one run.

func WithBudget

func WithBudget(budget Budget) Option

WithBudget sets the run budget.

func WithHooks

func WithHooks(hooks Hooks) Option

WithHooks sets a function-field policy, replacing any agent default.

func WithMaxSteps

func WithMaxSteps(steps int) Option

WithMaxSteps sets the step budget for one run.

func WithMaxTokens

func WithMaxTokens(tokens int) Option

WithMaxTokens overrides the output token limit.

func WithMedia

func WithMedia(parts ...llm.Part) Option

WithMedia attaches multimodal parts to the trailing user message.

func WithModel

func WithModel(model llm.Model) Option

WithModel overrides the agent model for one run.

func WithOutputSchema

func WithOutputSchema[T any](opts ...tool.SchemaOption) Option

WithOutputSchema constrains output to a strict schema generated from T.

func WithPolicy

func WithPolicy(policy Policy) Option

WithPolicy sets the run policy, replacing any agent default.

func WithReasoning

func WithReasoning(reasoning llm.ReasoningConfig) Option

WithReasoning overrides reasoning configuration for one run.

func WithResponseFormat

func WithResponseFormat(format *llm.ResponseFormat) Option

WithResponseFormat constrains output for one run.

func WithRetry

func WithRetry(retry RetryPolicy) Option

WithRetry sets the transient-failure retry policy.

func WithSession

func WithSession(id, resourceID string) Option

WithSession configures the conversation identity for one run.

func WithSink

func WithSink(sink Sink) Option

WithSink observes events for one run.

func WithStore

func WithStore(store session.Store) Option

WithStore configures conversation persistence for one run.

func WithTemperature

func WithTemperature(temperature float64) Option

WithTemperature overrides sampling temperature.

func WithToolChoice

func WithToolChoice(choice llm.ToolChoice) Option

WithToolChoice constrains tool selection.

func WithToolTimeout

func WithToolTimeout(timeout time.Duration) Option

WithToolTimeout sets the per-tool execution timeout. A negative duration disables the timeout.

func WithTools

func WithTools(tools ...tool.Tool) Option

WithTools adds or replaces tools for one run.

func WithTopP

func WithTopP(topP float64) Option

WithTopP overrides nucleus sampling.

type PanicError

type PanicError struct {
	Value any
	Stack []byte
}

PanicError converts a recovered panic into an error.

func (*PanicError) Error

func (e *PanicError) Error() string

Error implements the error interface.

type Policy

type Policy interface {
	BeforeModel(ctx context.Context, req *ModelRequest) error
	AfterModel(ctx context.Context, result *ModelResult) error
	BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error)
	AfterTool(ctx context.Context, result *ToolResult) error
}

Policy controls a run. Sinks observe; policies decide.

BeforeModel and AfterModel may mutate the request/response. Returning an error aborts the run. BeforeTool returns a Decision; Deny tells the model, Ask delegates to an Approver, and Terminate aborts.

type PolicyChain

type PolicyChain []Policy

PolicyChain composes policies in order. Before hooks run in order and After hooks run in reverse order.

func (PolicyChain) AfterModel

func (c PolicyChain) AfterModel(ctx context.Context, result *ModelResult) error

AfterModel implements Policy. After hooks run in reverse order.

func (PolicyChain) AfterTool

func (c PolicyChain) AfterTool(ctx context.Context, result *ToolResult) error

AfterTool implements Policy. After hooks run in reverse order.

func (PolicyChain) BeforeModel

func (c PolicyChain) BeforeModel(ctx context.Context, req *ModelRequest) error

BeforeModel implements Policy.

func (PolicyChain) BeforeTool

func (c PolicyChain) BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error)

BeforeTool implements Policy. The most restrictive decision wins: Terminate, then Ask, then Deny (including DecisionUnknown).

type Response

type Response struct {
	// Text is the last assistant message's text.
	Text string `json:"text"`
	// Thinking is the last assistant message's reasoning trace.
	Thinking string `json:"thinking,omitempty"`
	// ToolCalls contains every tool call made during the run.
	ToolCalls []llm.ToolCall `json:"tool_calls,omitempty"`
	// Messages is the full conversation, including system instructions,
	// session history, input, assistant messages, and tool results.
	Messages []llm.Message `json:"messages"`
	// FinishReason explains why the final model call ended.
	FinishReason llm.FinishReason `json:"finish_reason"`
	// Usage is cumulative token usage across all model calls.
	Usage llm.Usage `json:"usage"`
}

Response is the final result of a run.

func GenerateStructured

func GenerateStructured[T any](ctx context.Context, a *Agent, prompt string, opts ...Option) (T, *Response, error)

GenerateStructured runs the agent and decodes its output into T.

func (*Response) Unmarshal

func (r *Response) Unmarshal(target any) error

Unmarshal parses the response text into target, stripping a single Markdown JSON code fence when present.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the total number of attempts, including the first. Zero
	// or one disables retries.
	MaxAttempts int
	// InitialDelay is the first backoff delay. Zero uses 500ms.
	InitialDelay time.Duration
	// MaxDelay caps the backoff delay. Zero uses 8s.
	MaxDelay time.Duration
}

RetryPolicy configures retries of transient model failures.

type Run

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

Run is an asynchronous agent execution.

Consume Events, wait for the final response with Wait, or both. Wait does not drain Events, so a consumer that ignores Events and never cancels the run may leave the event dispatcher blocked; use a buffered consumer or call Cancel when abandoning a run.

func (*Run) Cancel

func (r *Run) Cancel(cause error)

Cancel stops the run with the given cause. A nil cause uses ErrRunCanceled.

func (*Run) Close

func (r *Run) Close() error

Close cancels the run. It implements io.Closer for convenience.

func (*Run) Events

func (r *Run) Events() <-chan Event

Events returns the run's event stream. The channel closes after RunEnd.

func (*Run) Response

func (r *Run) Response() (*Response, error)

Response returns the final response if the run has finished.

func (*Run) Wait

func (r *Run) Wait(ctx context.Context) (*Response, error)

Wait blocks until the run finishes or ctx is done. It does not consume Events.

type RunEnd

type RunEnd struct {
	Response *Response
	Err      error
}

RunEnd is always the final event. Response may be non-nil with an error when a run stops at a budget boundary.

type RunOptions

type RunOptions struct {
	// Session identifies the conversation. It is required when Store is set.
	Session *session.Session
	// Store persists the conversation. It is optional; the agent Store is used
	// when nil.
	Store session.Store
	// Policy controls model and tool calls. The agent policy is used when nil.
	Policy Policy
	// Approver resolves Ask decisions. The agent default Approver is used when
	// nil. Without an approver, Ask is treated as Deny.
	Approver Approver
	// Sink observes run events.
	Sink Sink
	// Budget bounds the run. Non-zero fields override the agent budget.
	Budget Budget
	// Retry configures transient model retries. Non-zero fields override the
	// agent retry policy.
	Retry RetryPolicy
	// ToolTimeout bounds each tool execution. Zero inherits the agent default,
	// then DefaultToolTimeout. A negative value disables the timeout.
	ToolTimeout time.Duration

	// Model overrides the agent model.
	Model llm.Model
	// Tools adds or replaces agent tools by name.
	Tools []tool.Tool
	// Reasoning overrides reasoning configuration. The agent default is used
	// when nil.
	Reasoning *llm.ReasoningConfig
	// ResponseFormat constrains structured output. The agent default is used
	// when nil.
	ResponseFormat *llm.ResponseFormat
	// Temperature overrides sampling temperature. The agent default is used
	// when nil.
	Temperature *float64
	// MaxTokens overrides the output token limit. The agent default is used
	// when nil.
	MaxTokens *int
	// TopP overrides nucleus sampling. The agent default is used when nil.
	TopP *float64
	// Media attaches parts to the trailing user message.
	Media []llm.Part
	// ToolChoice constrains tool selection. The agent default is used when
	// empty.
	ToolChoice llm.ToolChoice
	// contains filtered or unexported fields
}

RunOptions configures one agent run. Unset values inherit the agent's configuration; remaining zero values fall back to package defaults. It is the single public per-run configuration type.

type RunStart

type RunStart struct {
	RunID   string
	Agent   string
	Session *session.Session
	At      time.Time
}

RunStart is emitted once at the beginning of a run.

type Sink

type Sink interface {
	Emit(Event)
}

Sink observes run events. Emit must not block indefinitely; use a buffered channel or queue when forwarding events elsewhere.

type SinkFunc

type SinkFunc func(Event)

SinkFunc adapts a function to Sink.

func (SinkFunc) Emit

func (f SinkFunc) Emit(event Event)

Emit implements Sink.

type StepEnd

type StepEnd struct {
	Step  int
	Usage llm.Usage
	Err   error
}

StepEnd is emitted after a step's model call and tool execution.

type StepStart

type StepStart struct {
	Step int
}

StepStart is emitted before each model call.

type SubagentInput

type SubagentInput struct {
	Prompt string `json:"prompt" description:"The task or question to delegate to the subagent"`
}

SubagentInput is the input schema for an agent exposed as a tool.

type TextDelta

type TextDelta struct {
	Step    int
	Index   int
	Text    string
	Replace bool
}

TextDelta is emitted for each text fragment. Replace means Text is a full snapshot of the part, not an increment.

type ThinkingDelta

type ThinkingDelta struct {
	Step    int
	Index   int
	Text    string
	Replace bool
}

ThinkingDelta is emitted for each reasoning fragment. Replace means Text is a full snapshot of the part, not an increment.

type ToolCallDelta

type ToolCallDelta struct {
	Step      int
	Index     int
	ID        string
	Name      string
	Arguments string
}

ToolCallDelta is emitted for each tool-call fragment.

type ToolEnd

type ToolEnd struct {
	Step    int
	Call    tool.Call
	Result  *tool.Result
	Message *llm.Message
	Err     error
}

ToolEnd is emitted exactly once for every ToolStart, including denied, failed, or policy-aborted calls.

type ToolRequest

type ToolRequest struct {
	Step int
	Call tool.Call
	Spec tool.Spec
}

ToolRequest is passed to Policy.BeforeTool.

type ToolResult

type ToolResult struct {
	Step   int
	Call   tool.Call
	Result *tool.Result
	Err    error
}

ToolResult is passed to Policy.AfterTool.

type ToolStart

type ToolStart struct {
	Step int
	Call tool.Call
	Spec tool.Spec
}

ToolStart is emitted before a tool call is evaluated.

type ToolUpdate

type ToolUpdate struct {
	CallID   string
	Progress string
}

ToolUpdate reports tool progress. The current runner does not emit it; it is reserved for tools and schedulers that surface progress events.

Directories

Path Synopsis
internal
eventstream
Package eventstream provides a non-blocking event queue.
Package eventstream provides a non-blocking event queue.

Jump to

Keyboard shortcuts

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