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
- Variables
- func ApprovalID(turn TurnID, callID string) string
- func Commands(agents ...*Agent) []cli.Command
- func JobError(err error) error
- func MarshalEvent(e aikit.Event) ([]byte, error)
- func MarshalMessage(m aikit.Message) ([]byte, error)
- func Ready(ctx context.Context, store ThreadStore, turn TurnID) (bool, error)
- func Register(q quiver.Queue, agents ...*Agent) error
- func Summarize(after int, m aikit.Model) aikit.Middleware
- func Topic(turn TurnID) pubsub.Topic[TurnEvent]
- func UnmarshalEvent(b []byte) (aikit.Event, error)
- func UnmarshalMessage(b []byte) (aikit.Message, error)
- type Agent
- func (a *Agent) Begin(ctx context.Context, threadID string, in aikit.Message) (TurnID, error)
- func (a *Agent) Enqueue(ctx context.Context, q quiver.Queue, threadID string, in aikit.Message, ...) (TurnID, error)
- func (a *Agent) EnqueueResume(ctx context.Context, q quiver.Queue, turn TurnID, opts ...quiver.EnqueueOption) error
- func (a *Agent) EnqueueTx(ctx context.Context, q quiver.Queue, tx any, threadID string, in aikit.Message, ...) (TurnID, error)
- func (a *Agent) EventLog() EventLog
- func (a *Agent) Follow(ctx context.Context, turn TurnID, after int64) iter.Seq2[TurnEvent, error]
- func (a *Agent) Name() string
- func (a *Agent) Resolve(ctx context.Context, approvalID string, d Decision) (*Approval, error)
- func (a *Agent) Resume(ctx context.Context, turn TurnID) (*Result, error)
- func (a *Agent) ResumeJob(ctx context.Context, turn TurnID) (*Result, error)
- func (a *Agent) ResumeStream(ctx context.Context, turn TurnID) iter.Seq2[aikit.Event, error]
- func (a *Agent) Run(ctx context.Context, threadID string, in aikit.Message) (*Result, error)
- func (a *Agent) Store() ThreadStore
- func (a *Agent) Stream(ctx context.Context, threadID string, in aikit.Message) iter.Seq2[aikit.Event, error]
- func (a *Agent) Watch(ctx context.Context, turn TurnID, fn func(TurnEvent)) (cancel func(), err error)
- type Approval
- type ApprovalPolicy
- type ApprovalPolicyFunc
- type ApprovalStatus
- type Decision
- type EventLog
- type Memory
- func (m *Memory) AppendEvent(_ context.Context, turn TurnID, seq int64, e aikit.Event) error
- func (m *Memory) AppendMessages(_ context.Context, threadID string, turn TurnID, msgs ...StoredMessage) error
- func (m *Memory) Approval(_ context.Context, id string) (*Approval, error)
- func (m *Memory) CreateThread(_ context.Context, t *Thread) error
- func (m *Memory) Events(_ context.Context, turn TurnID, after int64) iter.Seq2[TurnEvent, error]
- func (m *Memory) Messages(_ context.Context, threadID string, page Page) ([]StoredMessage, error)
- func (m *Memory) PendingApprovals(_ context.Context, threadID string) ([]Approval, error)
- func (m *Memory) ResolveApproval(_ context.Context, id string, d Decision) (*Approval, error)
- func (m *Memory) SaveTurn(_ context.Context, t *Turn) error
- func (m *Memory) Thread(_ context.Context, id string) (*Thread, error)
- func (m *Memory) Turn(_ context.Context, id TurnID) (*Turn, error)
- type Option
- func WithApprovals(p ApprovalPolicy) Option
- func WithAudit(r audit.Recorder) Option
- func WithBudget(l ...aikit.Limit) Option
- func WithEvents(b pubsub.Broker) Option
- func WithGuardrails(g ...aikit.Guardrail) Option
- func WithInstructions(s string) Option
- func WithInstructionsFunc(fn func(ctx context.Context, t *Thread) string) Option
- func WithMaxSteps(n int) Option
- func WithMiddleware(mw ...aikit.Middleware) Option
- func WithObserver(obs aikit.Observer) Option
- func WithStore(s ThreadStore) Option
- func WithSubAgents(as ...*Agent) Option
- func WithTools(ts ...aikit.Tool) Option
- type Page
- type Result
- type RunJob
- type Status
- type StoredMessage
- type Thread
- type ThreadStore
- type Turn
- type TurnEvent
- type TurnID
Constants ¶
const DefaultMaxSteps = 10
DefaultMaxSteps caps the model calls of a turn unless WithMaxSteps is set.
const RunJobTimeout = 5 * time.Minute
RunJobTimeout bounds one attempt of a RunJob unless the enqueue sets quiver.Timeout.
Variables ¶
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.
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 ¶
ApprovalID is the ID of the approval of tool call callID in turn.
func Commands ¶
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 ¶
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 ¶
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 ¶
MarshalMessage encodes m as JSON.
func Register ¶
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 UnmarshalEvent ¶
UnmarshalEvent decodes an event encoded by MarshalEvent. A failover's error comes back as a plain error with the same text.
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 (*Agent) Begin ¶
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 ¶
EventLog returns the agent's store as an EventLog, or nil when it does not log events.
func (*Agent) Follow ¶
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) Resume ¶
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 ¶
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 ¶
ResumeStream is Resume as an event stream.
func (*Agent) Run ¶
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.
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 ¶
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 ¶
ApprovalPolicyFunc adapts a function to ApprovalPolicy.
func (ApprovalPolicyFunc) NeedsApproval ¶
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 Edit ¶
func Edit(args json.RawMessage) Decision
Edit lets the call run with args instead of the model's arguments.
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 ¶
AppendEvent implements EventLog.
func (*Memory) AppendMessages ¶
func (m *Memory) AppendMessages(_ context.Context, threadID string, turn TurnID, msgs ...StoredMessage) error
AppendMessages implements ThreadStore.
func (*Memory) CreateThread ¶
CreateThread implements ThreadStore.
func (*Memory) PendingApprovals ¶
PendingApprovals implements ThreadStore.
func (*Memory) ResolveApproval ¶
ResolveApproval 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 ¶
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 ¶
WithBudget stops a turn before a step that would pass a limit. Step and token limits count the whole turn, across approvals.
func WithEvents ¶
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 ¶
WithGuardrails checks each step's input, output, and tool calls.
func WithInstructions ¶
WithInstructions sets the system prompt.
func WithInstructionsFunc ¶
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 ¶
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 ¶
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 ¶
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.
type Page ¶
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.
type Status ¶
type Status string
Status is the state of a turn.
type StoredMessage ¶
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 ¶
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 ¶
MarshalJSON encodes the event with MarshalEvent.
func (*TurnEvent) UnmarshalJSON ¶
UnmarshalJSON decodes an event encoded by MarshalJSON.
Source Files
¶
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. |