Documentation
¶
Overview ¶
Package runner is the Agent runtime: it loads history by session ID, builds the context of each run, drives the Agent, persists messages, manages queued messages and history compaction, and runs in the background with events any number of receivers can follow.
A Runner holds one Agent and one store and serves any number of sessions: different sessions can run concurrently, and each session has at most one run at a time. That guarantee only holds within one Runner instance: when several processes or instances share a store, the caller must ensure mutual exclusion per session (for example by routing a session to a fixed instance, or with a distributed lock). Who the Agent is (instructions, model, tools) is defined on agent.Agent, what is stored is defined in the session package, and the Runner only runs them.
Index ¶
- Variables
- type CompactInput
- type CompactOptions
- type CompactReason
- type CompactResult
- type Compactor
- type Config
- type ContextInput
- type DefaultConverter
- type Event
- type EventType
- type Input
- type MessageConverter
- type Queue
- type Result
- type Run
- type RunOption
- type Runner
- func (r *Runner) Compact(ctx context.Context, sessionID string, opts CompactOptions) (*session.Message, chat.Usage, error)
- func (r *Runner) Current(sessionID string) *Run
- func (r *Runner) ListTasks(sessionID string) []tool.Task
- func (r *Runner) Start(ctx context.Context, sessionID string, in Input, opts ...RunOption) (*Run, error)
- func (r *Runner) StopTask(ctx context.Context, id string) error
- func (r *Runner) Store() session.Store
- func (r *Runner) Subscribe(ctx context.Context, sessionID string) iter.Seq[Event]
- type SummaryCompactor
- type TaskResultDelivery
Constants ¶
This section is empty.
Variables ¶
var ( // ErrBusy means the session already has a run in progress. ErrBusy = errors.New("runner: session is busy") // ErrNotRunning means the run no longer takes queued messages: it is finishing or has ended, or it does not run the Agent. ErrNotRunning = errors.New("runner: run is not running") // ErrInvalidConfig means the Runner configuration is incomplete. ErrInvalidConfig = errors.New("runner: invalid config") )
Functions ¶
This section is empty.
Types ¶
type CompactInput ¶
type CompactInput struct {
// Messages are the session messages currently in the model context, with earlier summaries applied:
// when there is a summary it comes first, followed by the kept messages and those added since.
// They are shared with the run and read-only: a Compactor must not modify their content.
Messages []session.Message
// Tokens is the estimated context usage, and MaxInputTokens the model's context limit.
Tokens int
MaxInputTokens int
// Reason says how this compaction was triggered.
Reason CompactReason
// Instructions are the caller's extra requirements for the summary in a manual compaction; may be empty.
Instructions string
// Client is the model client of the session, which can be used to generate the summary.
Client chat.Client
// Continue sends the conversation as the model last saw it, followed by extra, as a side call of the Agent (see agent.SideCall):
// the same system prompt, tools, options and messages, through the same middlewares. Summarizing through it reuses the
// conversation's prompt cache. The conversation covers Messages up to and including ContinueThrough, so the kept part must
// start no later than the message after it. Continue is nil when there is no such conversation, for example when no model call
// has succeeded since the last summary.
Continue func(ctx context.Context, extra []chat.Message, opts agent.SideCallOptions) (*chat.Message, error)
ContinueThrough string
}
CompactInput is the input of one compaction decision.
type CompactOptions ¶ added in v0.2.0
type CompactOptions struct {
// Instructions are extra requirements for the summary and may be empty; see CompactInput.Instructions.
Instructions string
// Model generates the summary instead of Agent.Model, typically the model the session currently runs on.
Model chat.Client
}
CompactOptions adjusts a manual compaction.
type CompactReason ¶
type CompactReason string
CompactReason says how a compaction was triggered.
const ( // CompactAuto is the routine check before a run and after each turn; the Compactor decides from the usage whether to compact. CompactAuto CompactReason = "auto" // CompactOverflow means the model already failed because the context was exceeded; compact as much as possible regardless of the estimate. CompactOverflow CompactReason = "overflow" // CompactManual means the caller asked for compaction through Runner.Compact; compact as much as possible regardless of the estimate. // MaxInputTokens is 0 when the model declares no context limit. CompactManual CompactReason = "manual" )
type CompactResult ¶
type CompactResult struct {
Summary string
// FirstKeptID is the ID of the first kept message and must come from CompactInput.Messages.
// It cannot be a tool result message, or its tool call would be summarized away and leave an orphan result.
FirstKeptID string
// Usage is the tokens consumed generating the summary, counted in the run result.
Usage chat.Usage
}
CompactResult describes a compaction: the messages before FirstKeptID are replaced by Summary.
type Compactor ¶
type Compactor interface {
Compact(ctx context.Context, in CompactInput) (*CompactResult, error)
}
Compactor decides when and how to compact session history. Returning nil means no compaction this time.
The Runner calls it automatically at three points: before each run, after each turn of a run, and when the model reports a context overflow; callers can also trigger it manually with Runner.Compact; see CompactInput.Reason. The original messages always stay in the store; compaction only affects what enters the model context.
type Config ¶
type Config struct {
// Agent is the Agent to run. Its Model may be nil when every run passes WithModel.
// Do not modify it after handing it to the Runner: every run of every session reads this one definition without synchronization.
Agent *agent.Agent
// Store is the session store; an in-memory store is used when nil.
Store session.Store
// Converter converts session messages into model-visible messages; DefaultConverter is used when nil.
Converter MessageConverter
// Compactor is the history compaction strategy; SummaryCompactor with defaults is used when nil.
// There is no compaction when the model declares no context limit (ModelInfo.MaxInputTokens is 0).
Compactor Compactor
// DisableCompaction turns compaction off.
DisableCompaction bool
// Middlewares are the runtime middlewares, applied to every run on this Runner, including the sub-agents it spawns.
// Steps every Agent must go through rather than ones belonging to a particular Agent, such as approval, auditing and tracing, go here.
// They wrap the Agent's own middlewares, so an Agent can only add its own behavior inside them; history compaction is innermost.
Middlewares []agent.Middleware
// OnTaskStarted is called after a task starts running, exactly once per task and before the other callbacks.
OnTaskStarted func(ctx context.Context, task tool.Task)
// OnTaskProgressed is called every time a task reports progress, for live display. task is the snapshot with the progress merged;
// for a sub-agent, update.Event is the Event of the run on the child session, the same as Run.Events hands out,
// and for a background command update.Output is the new output.
OnTaskProgressed func(ctx context.Context, task tool.Task, update tool.TaskUpdate)
// OnTaskFinished is called after a task ends and its result has been sent back to the session that spawned it, exactly once per task and last.
// When delivery is ResultSavedToHistory the main Agent has not seen the result yet, and the business layer decides whether to wake it,
// for example with r.Start(ctx, task.SessionID, Input{}).
OnTaskFinished func(ctx context.Context, task tool.Task, delivery TaskResultDelivery)
}
Config is the configuration for creating a Runner.
type ContextInput ¶
type ContextInput struct {
Text string
Content []chat.ContentBlock
// Source and Kind describe where the context comes from and what it is, by the business layer's own convention, and may be empty; when set they become attributes of <app_context> visible to the model.
Source string
Kind string
// Scope defaults to session.ScopePersistent: the context is written to the session and stays visible to later runs,
// so history only grows and earlier runs keep their prompt cache and thinking. session.ScopeRun keeps it to this run,
// for large context that should not pile up in history; later runs are rebuilt without it, which rewrites the prompt
// cache from that point and drops the thinking of the runs that had it.
Scope session.Scope
Details any
Visible bool
}
ContextInput is business context injected with a run, such as the page the user is on. It is merged into the user message as <app_context>, visible to the model but hidden from the user by default.
type DefaultConverter ¶
type DefaultConverter struct{}
DefaultConverter is the default message converter: consecutive user messages and business context are merged into one model message, business context is wrapped in <app_context>, and summaries in <conversation_summary>.
func (DefaultConverter) ToChatMessages ¶
type Event ¶
type Event struct {
Type EventType
SessionID string
RunID string
Message *session.Message
AgentEvent *agent.Event
Queue *Queue
// Result carries the run result on run_end.
Result *Result
}
Event is an event during a run.
func (Event) TextDelta ¶
TextDelta returns the reply text delta of this event, or "" when it is not a text delta event.
func (Event) ThinkingDelta ¶
ThinkingDelta returns the thinking text delta of this event, or "" when it is not a thinking delta event.
type EventType ¶
type EventType string
EventType is the type of an event during a run.
const ( EventRunStart EventType = "run_start" // EventRunEnd is the last event of a run and carries the run result. EventRunEnd EventType = "run_end" // EventMessageSaved is emitted after a message has been stored. EventMessageSaved EventType = "message_saved" // EventQueueUpdate is emitted when the queued messages change. EventQueueUpdate EventType = "queue_update" // EventAgentEvent forwards events of the Agent run (model stream, tool execution and so on). EventAgentEvent EventType = "agent_event" // EventCompaction is emitted after the history was compacted; Message is the stored summary message. EventCompaction EventType = "compaction" )
type Input ¶
type Input struct {
Content []chat.ContentBlock
}
Input is one user input: content blocks in order, which can only be text and media (chat.Media, chat.MediaURL).
func Parts ¶
func Parts(blocks ...chat.ContentBlock) Input
Parts returns an input made of several content blocks, such as some text and a few images.
type MessageConverter ¶
type MessageConverter interface {
ToChatMessages(ctx context.Context, messages []session.Message) ([]chat.Message, error)
}
MessageConverter converts session messages into messages visible to the model.
It also converts queued steer / follow-up messages, which can only become user messages (possibly merged into fewer messages).
type Result ¶
type Result struct {
SessionID string
RunID string
// Status is how the run ended; it is StatusFailed when infrastructure such as the store fails.
Status agent.Status
// Messages are all messages stored by this run, and Final is the last assistant message.
Messages []session.Message
Final *session.Message
// Usage includes the tokens consumed by model calls, inside tools and generating summaries.
Usage chat.Usage
// Pending are the steer / follow-up messages not yet injected when the run ended; they did not enter history.
// Messages taken by Abort are returned by Abort, not here.
Pending Queue
}
Result is the result of a run. It is still valid when Run.Wait returns an error and contains the messages produced so far.
type Run ¶ added in v0.2.0
type Run struct {
// contains filtered or unexported fields
}
Run is one occupation of a session, the handle for everything about it: it runs in the background whether or not anyone watches it, Events replays its events from the start to any number of receivers, Wait waits for its result, and Steer, FollowUp and Abort act on it. Start returns it, and Current finds the one in progress by session ID.
Besides runs of the Agent, manual compaction and writing a background task result to an idle session's history occupy the session too. They are Runs as well, with their own events (run_start, the stored messages, run_end) and Result, so every occupation looks the same. All fields are guarded by Runner.mu; the state private to the run's goroutine is in runState.
func (*Run) Abort ¶ added in v0.2.1
Abort cancels the run and returns the queued messages not yet injected (they do not enter history); it returns an empty queue once the run has ended. It does not wait for the run to end; call Wait for that.
func (*Run) Events ¶ added in v0.2.0
Events returns the events of the run from the first one, then each new one as it happens, ending after run_end or when ctx is done. Any number of receivers can iterate, each at its own pace, and a slow receiver never holds up the run. Call Wait for the run's error.
The events are kept in memory while the Run is referenced. To bound that, a replayed message_update keeps only its delta once a newer message_update exists (AgentEvent.Message is nil); message_end carries the complete message.
func (*Run) FollowUp ¶ added in v0.2.1
FollowUp queues a follow-up message, injected when the model gives its final reply and the run would end; the current task is not affected. It returns ErrNotRunning in the same cases as Steer.
func (*Run) ID ¶ added in v0.2.0
ID returns the run ID, which every message stored by the run carries.
func (*Run) Steer ¶ added in v0.2.1
Steer interjects mid-run: the message is injected after the current turn's tools finish and before the next model call, to correct or add to the task in progress. It never interrupts tools that are executing. It returns ErrNotRunning once the run is finishing, and for occupations that do not run the Agent (compaction, task results).
func (*Run) Wait ¶ added in v0.2.0
Wait waits for the run to end and returns its result. When the model fails, the run is aborted or the turn limit is reached, a non-nil error is returned and Result is still valid: Status gives the end status and Messages the messages produced and stored so far. ctx only bounds the waiting and does not stop the run. Once Wait returns, the session is free for the next run.
type RunOption ¶
type RunOption func(*runOptions)
RunOption adjusts a run.
func WithContext ¶
func WithContext(inputs ...ContextInput) RunOption
WithContext injects business context into this run.
func WithDetails ¶
WithDetails attaches business data to this run's user message (session.Message.Details).
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner runs one Agent and serves many sessions. It is safe for concurrent use.
func (*Runner) Compact ¶
func (r *Runner) Compact(ctx context.Context, sessionID string, opts CompactOptions) (*session.Message, chat.Usage, error)
Compact immediately compacts the history of an idle session, for when the user asks for it, and returns the stored summary message and the tokens consumed generating it; the summary is nil when there is nothing to compact. On error the tokens already consumed are still returned.
Compaction is a run of its own: Current returns it, Events gives run_start, the stored summary and run_end, and Abort cancels it. Meanwhile Start returns ErrBusy, and background task results are written to history after it ends. It returns ErrBusy while the session is running, and an error when compaction is disabled.
func (*Runner) Current ¶ added in v0.2.1
Current returns the session's run in progress, or nil when the session is idle. It suits requests that know only the session, such as a reopened page: follow the run with Events, then call Wait, after which the session is free.
func (*Runner) ListTasks ¶
ListTasks returns the background tasks spawned by the session whose results have not been delivered, ordered by start time.
func (*Runner) Start ¶ added in v0.2.0
func (r *Runner) Start(ctx context.Context, sessionID string, in Input, opts ...RunOption) (*Run, error)
Start processes one user input in a session: it occupies the session, stores the input, loads the history and drives the Agent to the end in the background, returning as soon as the run has started. The session is created if it does not exist; an empty sessionID generates a new one, see Run.SessionID. It returns ErrBusy at once when the session already has a run in progress, and an error when neither WithModel nor Agent.Model gives a model.
The run keeps ctx's values but not its cancellation, so it goes on after the caller returns or a client disconnects; stop it with Abort. Watch it with Run.Events or Subscribe and get its result with Run.Wait.
An empty in (Input{}) appends no new input and continues from the existing history, for example to wake the main Agent after a background task's result was written to history; the history must then end with a user-side message or a tool result.
func (*Runner) StopTask ¶
StopTask stops a background task and waits for it to end. The result is still sent back to the session as a notice, with the stopped status. It returns tool.ErrTaskNotFound when the task does not exist or has already ended. Do not call it synchronously from this task's callbacks: they run on the task's goroutine and would wait on each other.
func (*Runner) Subscribe ¶ added in v0.2.0
Subscribe follows a session: it replays the events of the run in progress, if any, from its start, then hands over the events of that run and of every later run of the session in order, until ctx is done. While the session is idle it waits for the next run. No run is missed, even one that starts and ends while the receiver is still busy with the previous one. It suits views that attach to a session at any time, such as a page reopened in the middle of a reply; earlier runs are read from the store.
type SummaryCompactor ¶
type SummaryCompactor struct {
// TriggerRatio is the context usage ratio that triggers compaction, 0.8 by default.
TriggerRatio float64
// KeepRatio is the share of the context limit kept as recent messages after compaction, 0.2 by default.
KeepRatio float64
// Prompt is the instruction for generating the summary; an empty one uses the built-in prompt.
Prompt string
// Client is the model that generates the summary; empty uses the session's model. A cheaper model can be used.
//
// With the session's model the summary is asked for at the end of the conversation through CompactInput.Continue,
// reusing its prompt cache. Otherwise, or when Continue is nil, the messages are sent as a plain text transcript
// with Prompt as the system prompt, which no cache covers.
Client chat.Client
// Options are the parameters of the summary request. MaxTokens of 0 becomes 4096 and applies to both ways; the other
// fields only apply to the transcript, as the conversation keeps its own. There an empty CacheRetention disables caching,
// since the transcript is used only once.
Options chat.Options
}
SummaryCompactor is the default compaction strategy: when context usage exceeds a threshold, it keeps the most recent messages as they are and has the model summarize the earlier part. The cut prefers user messages and never separates a tool call from its result. The zero value works.
func (SummaryCompactor) Compact ¶
func (c SummaryCompactor) Compact(ctx context.Context, in CompactInput) (*CompactResult, error)
type TaskResultDelivery ¶
type TaskResultDelivery string
TaskResultDelivery says how a background task's result was sent back to the session.
const ( // ResultInjectedIntoRun means the session was running and the result was injected into that run, where the main Agent handles it. ResultInjectedIntoRun TaskResultDelivery = "injected_into_run" // ResultSavedToHistory means the session was idle and the result was only written to history; the main Agent has not seen it yet. ResultSavedToHistory TaskResultDelivery = "saved_to_history" )