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
- Variables
- type Agent
- func (a *Agent) ApplyAgentOptions(opts RunOptions) RunOptions
- func (a *Agent) AsTool() tool.Tool
- func (a *Agent) AsToolWith(cfg AsToolConfig) tool.Tool
- func (a *Agent) Description() string
- func (a *Agent) Generate(ctx context.Context, prompt string, opts ...Option) (*Response, error)
- func (a *Agent) GenerateMessages(ctx context.Context, messages []llm.Message, opts ...Option) (*Response, error)
- func (a *Agent) GenerateMessagesWith(ctx context.Context, messages []llm.Message, opts RunOptions) (*Response, error)
- func (a *Agent) GenerateWith(ctx context.Context, prompt string, opts RunOptions) (*Response, error)
- func (a *Agent) Instructions() string
- func (a *Agent) Name() string
- func (a *Agent) Stream(ctx context.Context, prompt string, opts ...Option) (*Run, error)
- func (a *Agent) StreamMessages(ctx context.Context, messages []llm.Message, opts ...Option) (*Run, error)
- func (a *Agent) StreamMessagesWith(ctx context.Context, messages []llm.Message, opts RunOptions) (*Run, error)
- func (a *Agent) StreamWith(ctx context.Context, prompt string, opts RunOptions) (*Run, error)
- func (a *Agent) Tools() []tool.Tool
- type Approver
- type ApproverFunc
- type AsToolConfig
- type Budget
- type Config
- type Decision
- type Event
- type Hooks
- func (h Hooks) AfterModel(ctx context.Context, result *ModelResult) error
- func (h Hooks) AfterTool(ctx context.Context, result *ToolResult) error
- func (h Hooks) BeforeModel(ctx context.Context, req *ModelRequest) error
- func (h Hooks) BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error)
- type MessageEnd
- type MessageStart
- type ModelRequest
- type ModelResult
- type Option
- func WithApprover(approver Approver) Option
- func WithBudget(budget Budget) Option
- func WithHooks(hooks Hooks) Option
- func WithMaxSteps(steps int) Option
- func WithMaxTokens(tokens int) Option
- func WithMedia(parts ...llm.Part) Option
- func WithModel(model llm.Model) Option
- func WithOutputSchema[T any](opts ...tool.SchemaOption) Option
- func WithPolicy(policy Policy) Option
- func WithReasoning(reasoning llm.ReasoningConfig) Option
- func WithResponseFormat(format *llm.ResponseFormat) Option
- func WithRetry(retry RetryPolicy) Option
- func WithSession(id, resourceID string) Option
- func WithSink(sink Sink) Option
- func WithStore(store session.Store) Option
- func WithTemperature(temperature float64) Option
- func WithToolChoice(choice llm.ToolChoice) Option
- func WithToolTimeout(timeout time.Duration) Option
- func WithTools(tools ...tool.Tool) Option
- func WithTopP(topP float64) Option
- type PanicError
- type Policy
- type PolicyChain
- func (c PolicyChain) AfterModel(ctx context.Context, result *ModelResult) error
- func (c PolicyChain) AfterTool(ctx context.Context, result *ToolResult) error
- func (c PolicyChain) BeforeModel(ctx context.Context, req *ModelRequest) error
- func (c PolicyChain) BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error)
- type Response
- type RetryPolicy
- type Run
- type RunEnd
- type RunOptions
- type RunStart
- type Sink
- type SinkFunc
- type StepEnd
- type StepStart
- type SubagentInput
- type TextDelta
- type ThinkingDelta
- type ToolCallDelta
- type ToolEnd
- type ToolRequest
- type ToolResult
- type ToolStart
- type ToolUpdate
Constants ¶
const DefaultMaxSteps = 8
DefaultMaxSteps is the step budget used when Budget.MaxSteps is zero.
const DefaultToolTimeout = 2 * time.Minute
DefaultToolTimeout bounds a single tool execution when RunOptions.ToolTimeout is zero.
Variables ¶
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 (*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 ¶
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 ¶
Description returns the agent description.
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 ¶
Instructions returns the system instructions.
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 ¶
StreamWith runs the agent asynchronously with a complete RunOptions value.
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 )
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 ¶
BeforeTool implements Policy.
type MessageEnd ¶
MessageEnd is emitted with the completed assistant message.
type MessageStart ¶
type MessageStart struct {
Step int
}
MessageStart is emitted before streamed assistant output.
type ModelRequest ¶
ModelRequest is passed to Policy.BeforeModel.
type ModelResult ¶
ModelResult is passed to Policy.AfterModel.
type Option ¶
type Option func(*RunOptions)
Option customizes one Agent run.
func WithApprover ¶
WithApprover resolves Ask decisions for one run.
func WithMaxSteps ¶
WithMaxSteps sets the step budget for one run.
func WithMaxTokens ¶
WithMaxTokens overrides the output token limit.
func WithOutputSchema ¶
func WithOutputSchema[T any](opts ...tool.SchemaOption) Option
WithOutputSchema constrains output to a strict schema generated from T.
func WithPolicy ¶
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 ¶
WithSession configures the conversation identity for one run.
func WithTemperature ¶
WithTemperature overrides sampling temperature.
func WithToolChoice ¶
func WithToolChoice(choice llm.ToolChoice) Option
WithToolChoice constrains tool selection.
func WithToolTimeout ¶
WithToolTimeout sets the per-tool execution timeout. A negative duration disables the timeout.
type PanicError ¶
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.
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.
type RunEnd ¶
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 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 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 ¶
TextDelta is emitted for each text fragment. Replace means Text is a full snapshot of the part, not an increment.
type ThinkingDelta ¶
ThinkingDelta is emitted for each reasoning fragment. Replace means Text is a full snapshot of the part, not an increment.
type ToolCallDelta ¶
ToolCallDelta is emitted for each tool-call fragment.
type ToolEnd ¶
ToolEnd is emitted exactly once for every ToolStart, including denied, failed, or policy-aborted calls.
type ToolRequest ¶
ToolRequest is passed to Policy.BeforeTool.
type ToolResult ¶
ToolResult is passed to Policy.AfterTool.
type ToolUpdate ¶
ToolUpdate reports tool progress. The current runner does not emit it; it is reserved for tools and schedulers that surface progress events.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
eventstream
Package eventstream provides a non-blocking event queue.
|
Package eventstream provides a non-blocking event queue. |