agent

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 20 Imported by: ? 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 runs AI agents on top of package aikit: a tool loop with durable threads, human approval that survives restarts, background turns on Quiver, run events fanned out over PubSub, and audit records.

An Agent is built once with New and is safe for concurrent use. Each Run, Stream, or Enqueue is one turn: the user message, the model calls and tool runs that answer it, and, when a tool call needs approval, a pause until Resolve and Resume.

Index

Constants

View Source
const DefaultMaxSteps = 10

DefaultMaxSteps caps the model calls of a turn unless WithMaxSteps is set.

View Source
const RunJobTimeout = 5 * time.Minute

RunJobTimeout bounds one attempt of a RunJob unless the enqueue sets quiver.Timeout.

Variables

View Source
var (
	// ErrNotFound is a thread, turn, or approval the store does not have.
	ErrNotFound = errors.New("agent: not found")
	// ErrConflict is a SaveTurn whose Version is not the stored one: another
	// writer changed the turn first.
	ErrConflict = errors.New("agent: turn changed concurrently")
	// ErrAlreadyResolved is a decision on an approval that has one.
	ErrAlreadyResolved = errors.New("agent: approval already resolved")
	// ErrPendingApprovals is a resume of a turn with undecided approvals.
	ErrPendingApprovals = errors.New("agent: turn has pending approvals")
	// ErrNotResumable is a resume of a turn that has finished.
	ErrNotResumable = errors.New("agent: turn cannot be resumed")
	// ErrNoStore is an operation that needs the agent's ThreadStore when it
	// has none.
	ErrNoStore = errors.New("agent: no ThreadStore")
)

Errors of stores and turns. Match them with errors.Is.

View Source
var ErrNoEvents = errors.New("agent: no event broker or event log")

ErrNoEvents is a Watch or Follow on an agent that neither publishes nor logs its run events.

Functions

func ApprovalID

func ApprovalID(turn TurnID, callID string) string

ApprovalID is the ID of the approval of tool call callID in turn.

func Commands

func Commands(agents ...*Agent) []cli.Command

Commands returns the app commands for agents: `ai chat [agent]`, a terminal chat that streams answers, shows tool calls, asks y/n/e at each approval, and continues a thread with --thread. Add them to the app's command runner.

func JobError

func JobError(err error) error

JobError maps the error of a background turn to what Quiver does with its job, as RunJob does: nil once the turn waits for approval, is finished, or runs elsewhere; quiver.Snooze for a rate limit with a Retry-After; quiver.Discard for a guardrail trip or an invalid request; err itself, retried, otherwise.

func MarshalEvent

func MarshalEvent(e aikit.Event) ([]byte, error)

MarshalEvent encodes e as JSON. A Finish keeps its response's message, steps, usage, and approvals, but not the provider's raw body.

func MarshalMessage

func MarshalMessage(m aikit.Message) ([]byte, error)

MarshalMessage encodes m as JSON.

func Ready

func Ready(ctx context.Context, store ThreadStore, turn TurnID) (bool, error)

Ready reports whether every approval of the turn is decided, so Resume can run it.

func Register

func Register(q quiver.Queue, agents ...*Agent) error

Register handles RunJob on q for agents, matched by name. A turn that waits for approval ends the job; EnqueueResume continues it. A rate limit with a Retry-After snoozes the job; a guardrail trip or an invalid request discards it; another failure is retried, and fails the turn on the last attempt.

func Summarize

func Summarize(after int, m aikit.Model) aikit.Middleware

Summarize compacts long conversations. When a step would send more than after messages, the older ones are summarized by m and replaced by the summary, which is put in front of the first kept user message; the last after/2 or so messages are kept as they are, starting at a user message so no tool call is split from its result. The stored thread is not changed. Add it with WithMiddleware.

func Topic

func Topic(turn TurnID) pubsub.Topic[TurnEvent]

Topic is the PubSub topic that carries a turn's events: "ai.turn.<id>".

func UnmarshalEvent

func UnmarshalEvent(b []byte) (aikit.Event, error)

UnmarshalEvent decodes an event encoded by MarshalEvent. A failover's error comes back as a plain error with the same text.

func UnmarshalMessage

func UnmarshalMessage(b []byte) (aikit.Message, error)

UnmarshalMessage decodes a message encoded by MarshalMessage.

Types

type Agent

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

Agent is a model with instructions, tools, and policies. It does not change after New.

func New

func New(name string, m aikit.Model, opts ...Option) (*Agent, error)

New returns an agent named name that runs m.

func (*Agent) Begin

func (a *Agent) Begin(ctx context.Context, threadID string, in aikit.Message) (TurnID, error)

Begin stores in as a new queued turn of the thread without running it, for Resume or a background worker to run. It fails with ErrPendingApprovals while the thread has a turn waiting for approval.

func (*Agent) Enqueue

func (a *Agent) Enqueue(ctx context.Context, q quiver.Queue, threadID string, in aikit.Message, opts ...quiver.EnqueueOption) (TurnID, error)

Enqueue stores in as a new turn of the thread and enqueues a RunJob for it. opts override the job's defaults.

func (*Agent) EnqueueResume

func (a *Agent) EnqueueResume(ctx context.Context, q quiver.Queue, turn TurnID, opts ...quiver.EnqueueOption) error

EnqueueResume enqueues a RunJob that resumes the turn, typically once its approvals are decided.

func (*Agent) EnqueueTx

func (a *Agent) EnqueueTx(ctx context.Context, q quiver.Queue, tx any, threadID string, in aikit.Message, opts ...quiver.EnqueueOption) (TurnID, error)

EnqueueTx is Enqueue with the job enqueued inside tx, so it runs only if tx commits. The turn itself is stored outside tx: when tx rolls back it stays queued and is never run.

func (*Agent) EventLog

func (a *Agent) EventLog() EventLog

EventLog returns the agent's store as an EventLog, or nil when it does not log events.

func (*Agent) Follow

func (a *Agent) Follow(ctx context.Context, turn TurnID, after int64) iter.Seq2[TurnEvent, error]

Follow yields the turn's events with Seq above after: first those in the event log, then new ones as they are published (or, without a broker, as they are logged). It ends with a status event (nil Event) once the turn finishes or waits for a decision, or when ctx is done. A turn whose approvals are all decided is followed until it runs again and stops.

func (*Agent) Name

func (a *Agent) Name() string

Name returns the agent's name.

func (*Agent) Resolve

func (a *Agent) Resolve(ctx context.Context, approvalID string, d Decision) (*Approval, error)

Resolve is Resolve on the agent's store, audited to its recorder.

func (*Agent) Resume

func (a *Agent) Resume(ctx context.Context, turn TurnID) (*Result, error)

Resume runs a turn from its persisted state: a queued turn from its input, and a turn whose approvals are all decided from its waiting step. A turn left running by a crashed process is taken over only by its RunJob (see EnqueueResume). Approved calls run, with edited arguments when the decision has them; rejected ones answer the model {"rejected":true,"reason":...}.

Resume returns ErrPendingApprovals while a decision is missing, ErrNotResumable for a finished turn, and ErrConflict when the turn is running or another process resumed it first.

func (*Agent) ResumeJob

func (a *Agent) ResumeJob(ctx context.Context, turn TurnID) (*Result, error)

ResumeJob is Resume as RunJob runs it, for job handlers of their own such as Converse's: it takes over a turn a crashed worker left running, and a transient failure leaves the turn queued for the job's next attempt. JobError maps its error to the job's outcome.

func (*Agent) ResumeStream

func (a *Agent) ResumeStream(ctx context.Context, turn TurnID) iter.Seq2[aikit.Event, error]

ResumeStream is Resume as an event stream.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, threadID string, in aikit.Message) (*Result, error)

Run answers in on the thread and returns how the turn ended. threadID names the thread, which is created on first use; "" starts a new one. An agent without a store keeps no thread: each Run sees only in.

A turn stopped by a budget or middleware returns StatusStopped and an error matching aikit.ErrStopped; a failed one returns StatusFailed and its error. A turn waiting for approval returns StatusAwaitingApproval and a nil error.

func (*Agent) Store

func (a *Agent) Store() ThreadStore

Store returns the agent's ThreadStore, or nil.

func (*Agent) Stream

func (a *Agent) Stream(ctx context.Context, threadID string, in aikit.Message) iter.Seq2[aikit.Event, error]

Stream is Run as an event stream. A turn that waits for approval emits one ApprovalRequested per call, whose Request.ID is the tool call ID (the approval is ApprovalID(turn, callID)), then a Finish with FinishReason aikit.FinishApproval.

func (*Agent) Watch

func (a *Agent) Watch(ctx context.Context, turn TurnID, fn func(TurnEvent)) (cancel func(), err error)

Watch calls fn with each event published on the turn's topic from now on, until cancel is called or ctx is done. It needs WithEvents.

type Approval

type Approval struct {
	ID       string
	Turn     TurnID
	ThreadID string
	CallID   string
	Tool     string
	Args     json.RawMessage
	Status   ApprovalStatus
	Reason   string
	// EditedArgs replace Args when the call runs.
	EditedArgs json.RawMessage
	Actor      string
	CreatedAt  time.Time
	ResolvedAt time.Time
}

Approval is a tool call that waits for, or got, a person's decision. Its ID is ApprovalID(Turn, CallID).

func Resolve

func Resolve(ctx context.Context, store ThreadStore, approvalID string, d Decision) (*Approval, error)

Resolve records decision d on the approval and audits it as approval.resolved with the context's recorder. Of concurrent decisions on one approval exactly one wins; the others get ErrAlreadyResolved. Resolving does not resume the turn: call Resume or EnqueueResume once the turn's approvals are all decided (see Ready).

type ApprovalPolicy

type ApprovalPolicy interface {
	NeedsApproval(ctx context.Context, call aikit.ToolCall) bool
}

ApprovalPolicy decides which tool calls wait for a person, beyond the tools that ask for approval themselves.

func RequireApprovalFor

func RequireApprovalFor(names ...string) ApprovalPolicy

RequireApprovalFor makes every call to the named tools wait for a decision.

type ApprovalPolicyFunc

type ApprovalPolicyFunc func(ctx context.Context, call aikit.ToolCall) bool

ApprovalPolicyFunc adapts a function to ApprovalPolicy.

func (ApprovalPolicyFunc) NeedsApproval

func (f ApprovalPolicyFunc) NeedsApproval(ctx context.Context, call aikit.ToolCall) bool

NeedsApproval calls f.

type ApprovalStatus

type ApprovalStatus string

ApprovalStatus is the state of an approval.

const (
	ApprovalPending  ApprovalStatus = "pending"
	ApprovalApproved ApprovalStatus = "approved"
	ApprovalRejected ApprovalStatus = "rejected"
)

The approval states.

type Decision

type Decision struct {
	Approved bool
	Reason   string
	// Args, when set, replace the call's arguments.
	Args json.RawMessage
	// Actor is who decided. Empty: the audit actor of the context.
	Actor string
}

Decision is the answer to an approval: build it with Approve, Reject, or Edit.

func Approve

func Approve() Decision

Approve lets the call run as asked.

func Edit

func Edit(args json.RawMessage) Decision

Edit lets the call run with args instead of the model's arguments.

func Reject

func Reject(reason string) Decision

Reject refuses the call; the model reads reason.

func (Decision) By

func (d Decision) By(actor string) Decision

By returns d decided by actor.

type EventLog

type EventLog interface {
	// AppendEvent stores event seq of turn. A seq that is stored already
	// returns ErrConflict.
	AppendEvent(ctx context.Context, turn TurnID, seq int64, e aikit.Event) error
	// Events yields the turn's events with Seq above after, in order.
	Events(ctx context.Context, turn TurnID, after int64) iter.Seq2[TurnEvent, error]
}

EventLog is a ThreadStore that also keeps every event of a turn, so a stream can be replayed after a reload or a reconnect.

type Memory

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

Memory is the store MemoryStore returns.

func MemoryStore

func MemoryStore() *Memory

MemoryStore returns a ThreadStore and EventLog kept in process memory, for tests and development.

func (*Memory) AppendEvent

func (m *Memory) AppendEvent(_ context.Context, turn TurnID, seq int64, e aikit.Event) error

AppendEvent implements EventLog.

func (*Memory) AppendMessages

func (m *Memory) AppendMessages(_ context.Context, threadID string, turn TurnID, msgs ...StoredMessage) error

AppendMessages implements ThreadStore.

func (*Memory) Approval

func (m *Memory) Approval(_ context.Context, id string) (*Approval, error)

Approval implements ThreadStore.

func (*Memory) CreateThread

func (m *Memory) CreateThread(_ context.Context, t *Thread) error

CreateThread implements ThreadStore.

func (*Memory) Events

func (m *Memory) Events(_ context.Context, turn TurnID, after int64) iter.Seq2[TurnEvent, error]

Events implements EventLog.

func (*Memory) Messages

func (m *Memory) Messages(_ context.Context, threadID string, page Page) ([]StoredMessage, error)

Messages implements ThreadStore.

func (*Memory) PendingApprovals

func (m *Memory) PendingApprovals(_ context.Context, threadID string) ([]Approval, error)

PendingApprovals implements ThreadStore.

func (*Memory) ResolveApproval

func (m *Memory) ResolveApproval(_ context.Context, id string, d Decision) (*Approval, error)

ResolveApproval implements ThreadStore.

func (*Memory) SaveTurn

func (m *Memory) SaveTurn(_ context.Context, t *Turn) error

SaveTurn implements ThreadStore.

func (*Memory) Thread

func (m *Memory) Thread(_ context.Context, id string) (*Thread, error)

Thread implements ThreadStore.

func (*Memory) Turn

func (m *Memory) Turn(_ context.Context, id TurnID) (*Turn, error)

Turn implements ThreadStore.

type Option

type Option func(*options)

Option configures New.

func WithApprovals

func WithApprovals(p ApprovalPolicy) Option

WithApprovals makes tool calls that p selects wait for a decision, on top of tools that ask for approval themselves. New fails without WithStore, because a paused turn must be persisted to resume.

func WithAudit

func WithAudit(r audit.Recorder) Option

WithAudit records tool calls, approvals, guardrail trips, and budget stops to r. Without it they go to the recorder in the context, if any.

func WithBudget

func WithBudget(l ...aikit.Limit) Option

WithBudget stops a turn before a step that would pass a limit. Step and token limits count the whole turn, across approvals.

func WithEvents

func WithEvents(b pubsub.Broker) Option

WithEvents publishes every run event on the PubSub topic of its turn (see Topic), so any replica can follow a turn another one runs.

func WithGuardrails

func WithGuardrails(g ...aikit.Guardrail) Option

WithGuardrails checks each step's input, output, and tool calls.

func WithInstructions

func WithInstructions(s string) Option

WithInstructions sets the system prompt.

func WithInstructionsFunc

func WithInstructionsFunc(fn func(ctx context.Context, t *Thread) string) Option

WithInstructionsFunc builds the system prompt for each turn from its thread. The thread is nil for an agent without a store. It replaces WithInstructions.

func WithMaxSteps

func WithMaxSteps(n int) Option

WithMaxSteps caps the model calls of one turn. Default DefaultMaxSteps.

func WithMiddleware

func WithMiddleware(mw ...aikit.Middleware) Option

WithMiddleware wraps each model call. The first is the outermost, inside the budget and guardrails.

func WithObserver

func WithObserver(obs aikit.Observer) Option

WithObserver reports each model call and tool run to obs.

func WithStore

func WithStore(s ThreadStore) Option

WithStore keeps threads and turns in s. When s is also an EventLog, every run event is logged for replay.

func WithSubAgents

func WithSubAgents(as ...*Agent) Option

WithSubAgents offers each agent to the model as a tool named after it, which takes a prompt and returns the sub-agent's answer. Sub-agents run without a thread, so a sub-agent tool call that needs approval fails.

func WithTools

func WithTools(ts ...aikit.Tool) Option

WithTools offers tools to the model.

type Page

type Page struct {
	After int64
	Limit int
}

Page selects messages: those with Seq above After, at most Limit of them (0 means all), oldest first.

type Result

type Result struct {
	Status Status
	// Response is the last model answer, with usage summed over the steps
	// of this run.
	Response *aikit.Response
	// Approvals are the decisions the turn waits for when Status is
	// StatusAwaitingApproval.
	Approvals []Approval
	Turn      TurnID
}

Result is how a turn ended.

type RunJob

type RunJob struct {
	Agent    string `json:"agent"`
	ThreadID string `json:"thread_id"`
	Turn     TurnID `json:"turn"`
}

RunJob runs, or resumes, one turn in the background. Register installs its handler.

func (RunJob) Defaults

func (j RunJob) Defaults() quiver.JobDefaults

Defaults makes the job unique per turn, so a turn never runs twice at once, and gives it RunJobTimeout.

func (RunJob) Kind

func (RunJob) Kind() string

Kind implements quiver.JobArgs.

type Status

type Status string

Status is the state of a turn.

const (
	StatusQueued           Status = "queued"
	StatusRunning          Status = "running"
	StatusAwaitingApproval Status = "awaiting_approval"
	StatusCompleted        Status = "completed"
	StatusStopped          Status = "stopped"
	StatusFailed           Status = "failed"
)

The turn states. Completed, Stopped, and Failed are final.

func (Status) Final

func (s Status) Final() bool

Final reports whether no more work happens on a turn in state s.

type StoredMessage

type StoredMessage struct {
	Seq       int64
	Turn      TurnID
	Message   aikit.Message
	CreatedAt time.Time
}

StoredMessage is a message of a thread. Seq orders a thread's messages from 1; the store assigns it.

type Thread

type Thread struct {
	ID string
	// Agent is the name of the agent that created it.
	Agent     string
	Meta      map[string]string
	CreatedAt time.Time
}

Thread is one conversation.

type ThreadStore

type ThreadStore interface {
	CreateThread(ctx context.Context, t *Thread) error
	// Thread returns ErrNotFound for an unknown id.
	Thread(ctx context.Context, id string) (*Thread, error)
	// AppendMessages adds msgs to the thread in order, assigning their Seq
	// and Turn.
	AppendMessages(ctx context.Context, threadID string, turn TurnID, msgs ...StoredMessage) error
	Messages(ctx context.Context, threadID string, page Page) ([]StoredMessage, error)
	// SaveTurn stores t when t.Version is the stored version (0 for a new
	// turn) and increments t.Version; otherwise it returns ErrConflict. It
	// inserts approvals it has not seen as pending.
	SaveTurn(ctx context.Context, t *Turn) error
	// Turn returns the turn with its approvals, or ErrNotFound.
	Turn(ctx context.Context, id TurnID) (*Turn, error)
	// Approval returns one approval, or ErrNotFound.
	Approval(ctx context.Context, id string) (*Approval, error)
	// PendingApprovals lists a thread's undecided approvals, oldest first.
	PendingApprovals(ctx context.Context, threadID string) ([]Approval, error)
	// ResolveApproval records d on a pending approval and returns it. Of
	// concurrent calls on one approval exactly one succeeds; the others get
	// ErrAlreadyResolved.
	ResolveApproval(ctx context.Context, id string, d Decision) (*Approval, error)
}

ThreadStore persists threads, their messages, and turns. Implementations must be safe for concurrent use.

type Turn

type Turn struct {
	ID       TurnID
	ThreadID string
	Agent    string
	Status   Status
	// Step counts the model calls the turn has made.
	Step int
	// Seq is the sequence number of the turn's last event.
	Seq   int64
	Usage aikit.Usage
	// Approvals are the decisions the waiting step needs. SaveTurn adds
	// new ones as pending; only ResolveApproval changes them.
	Approvals []Approval
	Error     string
	// Version is 0 for a turn never saved. SaveTurn stores the turn only
	// when Version is the stored one, then increments it.
	Version   int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

Turn is the persisted state of one turn.

type TurnEvent

type TurnEvent struct {
	Turn   TurnID
	Seq    int64
	Event  aikit.Event
	Status Status
	Error  string
}

TurnEvent is one event of a turn as event logs and pubsub carry it. The last one published for a run has a nil Event and the turn's Status (and Error, for a failed turn) instead.

func (TurnEvent) MarshalJSON

func (e TurnEvent) MarshalJSON() ([]byte, error)

MarshalJSON encodes the event with MarshalEvent.

func (*TurnEvent) UnmarshalJSON

func (e *TurnEvent) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes an event encoded by MarshalJSON.

type TurnID

type TurnID string

TurnID names one turn: a user message and the steps that answer it.

Directories

Path Synopsis
Package web serves an agent to browser frontends over server-sent events: the Vercel AI SDK UI message stream (useChat) by default, or the AG-UI protocol.
Package web serves an agent to browser frontends over server-sent events: the Vercel AI SDK UI message stream (useChat) by default, or the AG-UI protocol.

Jump to

Keyboard shortcuts

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