Documentation
¶
Overview ¶
Package agentkit is a zero-dependency toolkit for building AI agents and chat sessions: an LLM-agnostic turn loop that drives a model through tool calls, with immutable tool and skill sets, sub-agents (a sub-agent is just a tool), a one-way event stream, and per-turn and per-tree guards (steps, wall-clock, tokens, spawn depth/population).
Immutable is about each set, not about the binding. A session asks for its tools, skills and system prompt once per turn (WithToolsFunc and friends), so a consumer whose available tools change while a conversation is open is answered by the next turn — while the turn already running keeps the set it was handed, because the model plans against the list it was given.
Everything external is a port: the model (LLM), tools (Tool), the logger (Logger) and transcript storage (Store). The core imports nothing outside the standard library; provider adapters (e.g. OpenAI) live in separate modules. See DOCS.md for the full design.
Index ¶
- Constants
- Variables
- func AttachImages(ctx context.Context, images ...Image) bool
- func AudioNote(a Audio) string
- func CallArgs(ctx context.Context) string
- func CallingTool(ctx context.Context) string
- func CanAttachImages(ctx context.Context) bool
- func Diagnose(ctx context.Context, level Level, subject, msg string)
- func Emit(ctx context.Context, e Event)
- func FilterResult(ctx context.Context, name, out string, err error) (string, error)
- func FrameFrom(ctx context.Context) uint64
- func ModelFrom(ctx context.Context) string
- func Once(ctx context.Context, llm LLM, input string, opts ...Option) (string, error)
- func Pause(ctx context.Context) (resume func())
- func Show(ctx context.Context, b Block) bool
- func SinkFrom(ctx context.Context) func(Event)
- func WithCallGuard(ctx context.Context, g CallGuard) context.Context
- func WithDiagnostics(ctx context.Context, d *Diagnostics) context.Context
- func WithPausableBudget(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc)
- func WithResultFilter(ctx context.Context, f ResultFilter) context.Context
- func WithSink(ctx context.Context, sink func(Event)) context.Context
- type Agent
- type Audio
- type Block
- type CallGuard
- type Diagnostic
- type Diagnostics
- func (d *Diagnostics) Add(level Level, subject, msg string)
- func (d *Diagnostics) All() []Diagnostic
- func (d *Diagnostics) Error(subject, msg string)
- func (d *Diagnostics) HasErrors() bool
- func (d *Diagnostics) Info(subject, msg string)
- func (d *Diagnostics) Len() int
- func (d *Diagnostics) Warn(subject, msg string)
- type Effort
- type Event
- type Field
- type Image
- type Input
- type LLM
- type Level
- type LiveAudio
- type LiveCallsCancelled
- type LiveError
- type LiveEvent
- type LiveInterrupted
- type LiveLLM
- type LiveModelText
- type LiveSession
- type LiveToolCall
- type LiveTurnDone
- type LiveUserText
- type Logger
- type MediaLoader
- type MemStore
- type Message
- type Option
- func WithEffort(e Effort) Option
- func WithEffortFunc(fn func() Effort) Option
- func WithLogger(l Logger) Option
- func WithMaxDepth(n int) Option
- func WithMaxSpawns(n int) Option
- func WithMaxSteps(n int) Option
- func WithMedia(load MediaLoader, history int) Option
- func WithModel(name string) Option
- func WithModelFunc(fn func() string) Option
- func WithSkills(sk SkillSet) Option
- func WithSkillsFunc(fn func() SkillSet) Option
- func WithStore(store Store, id string) Option
- func WithSystem(v string) Option
- func WithSystemFunc(fn func() string) Option
- func WithTimeout(d time.Duration) Option
- func WithTokenLimit(n int) Option
- func WithTokenizer(t Tokenizer) Option
- func WithTools(t ToolSet) Option
- func WithToolsFunc(fn func() ToolSet) Option
- type PromptNoter
- type ResultFilter
- type Role
- type Schema
- func Array(items *Schema, description string) *Schema
- func Bool(description string) *Schema
- func Integer(description string) *Schema
- func Number(description string) *Schema
- func Object(props ...Field) *Schema
- func ParseSchema(raw json.RawMessage) (*Schema, error)
- func String(description string) *Schema
- type SchemaType
- type Session
- type Skill
- type SkillSet
- type Step
- type Store
- type Thinking
- type Token
- type TokenCount
- type Tokenizer
- type Tool
- type ToolCall
- type ToolEnd
- type ToolFunc
- type ToolOption
- type ToolResult
- type ToolSet
- type ToolSpec
- type ToolStart
- type TurnEnd
- type TurnStart
Constants ¶
const ( // FormatEmail is the format of a string that is an e-mail address. FormatEmail = "email" // FormatMarkdown is the format of a string that is Markdown: a surface that edits it offers rich // text (bold, italics, lists, links, quotes) and keeps the Markdown. FormatMarkdown = "markdown" // FormatAttachment is the format of an object that names a file a call sends: {"path"} in the // consumer's files, or {"ref"} of a file it keeps by content, with an optional {"name"}. A surface // that edits it shows the file and offers to remove it or add another. FormatAttachment = "attachment" )
The formats a value may have that a surface reads.
const ( MaxSkillNameLen = 64 MaxSkillDescLen = 1024 SkillNamePattern = `^[a-z0-9-]{1,64}$` )
Skill-name / description limits, verified against the Anthropic Agent Skills spec. The name rule is STRICTER than a tool name: lowercase letters, digits and hyphens only (no underscore), and it may not contain the reserved words "anthropic" or "claude". Hard, enforced at construction.
const ( MaxToolNameLen = 64 MaxToolDescLen = 1024 // OpenAI hard-rejects a longer description; Anthropic tolerates it. ToolNamePattern = `^[a-zA-Z0-9_-]{1,64}$` )
Tool-name / description limits, verified against OpenAI function calling and Anthropic tool use (the name regex is identical; both reject a bad name with a 400). These are HARD spec rules enforced at construction — an invalid tool is never created — NOT advisory diagnostics.
const ImageNote = "[an image was attached here; it is not shown]"
ImageNote stands in a message's text for an image the model is not sent: one older than the history it is given (WithMedia), one that could not be loaded, or any image at all for a model that takes none. The model learns that something stood there instead of meeting a gap.
Variables ¶
var ( ErrMaxSteps = errors.New("agentkit: max steps reached") ErrTokenLimit = errors.New("agentkit: token limit reached") ErrMaxDepth = errors.New("agentkit: max sub-agent depth reached") ErrMaxSpawns = errors.New("agentkit: max sub-agent spawns reached") ErrTurnTimeout = errors.New("agentkit: turn timed out") )
Stop reasons a turn can end with, surfaced on TurnEnd.Err and returned by Once. A stop by the turn's wall-clock deadline is ErrTurnTimeout, for a Session, a Once and a sub-agent alike.
var ErrNoAudioInput = errors.New("agentkit: this model takes no audio")
ErrNoAudioInput is what an adapter refuses a turn with when its model hears no audio and the turn's own input is a recording nothing was written down from: the model would answer a note, not what was said.
var ErrNoImageInput = errors.New("agentkit: this model takes no images")
ErrNoImageInput is what an adapter refuses a turn with when its model takes no images and the person sent one. Refusing is the point: dropping the picture would have the model answer a question about something it never saw.
Functions ¶
func AttachImages ¶
AttachImages hands the images a tool made to the call it runs in: they ride on that call's result message and its ToolEnd, and on every call around it up to the turn's own, a script's call to a tool included. A sub-agent's turn keeps its own. Give each image its MIME and its Ref, the name the consumer's MediaLoader loads it by, and no Data: the loop loads it for the model when it is in the budget, as it does every image of the history.
It reports whether anything will keep them: false outside a turn's tool call (a tool called directly, or by a surface that has no conversation), when the images go nowhere. A tool that would make an image at a cost asks CanAttachImages before it does.
func AudioNote ¶
AudioNote stands in a message's text for a recording with no words written down that a model is not sent: "[voice note, 0:12]".
func CallArgs ¶
CallArgs is the raw argument string of the tool call currently executing ("" outside any call): the innermost one, as CallingTool names it. It is what the model wrote, so a consumer shows it as data (an approval's summary of what is being asked), never as text to follow.
func CallingTool ¶
CallingTool is the name of the tool whose call is currently executing ("" outside any call): the innermost one, so a tool a script or a sub-agent calls is named, not the one that started it. ToolSet.Call sets it around the call, so whatever the tool checks while it runs (a permission, a log line) can say which tool asked without each tool passing its own name along.
func CanAttachImages ¶
CanAttachImages reports whether images a tool attaches now are kept: whether the call runs inside a turn's loop, which puts them on its result message.
func Diagnose ¶
Diagnose feeds one finding into the ctx collector; no-op if none is attached (fail-open, like Emit). This is the feed-from-anywhere entry point.
func Emit ¶
Emit delivers e to the ctx sink, first stamping its Frame from the ctx call-frame; no-op if no sink (fail-open). Adapters call it to stream answer/reasoning tokens without knowing the frame.
func FilterResult ¶
FilterResult applies the ctx's ResultFilter to a result, or returns it unchanged when there is none. ToolSet.Call does this itself; a consumer that calls a Tool directly, outside a ToolSet, calls it so the same filter applies there.
func FrameFrom ¶
FrameFrom is the id of the tool call currently executing (0 = top level / main agent) — the same id carried on that call's Tool* events. A consumer reads it to correlate out-of-band work (e.g. an approval request presented mid-call) back to the exact call, without agentkit knowing what that work is.
func ModelFrom ¶
ModelFrom returns the name of the model the turn asked for (Input.Model, or the session's WithModel), or "" if none. agentkit gives the name no meaning, as it gives Effort none: an LLM that routes between several models reads it to pick one, and an adapter bound to one model ignores it.
func Once ¶
Once runs a throwaway session for a single input and returns its final answer — the synchronous convenience over Submit/Subscribe (events still stream to the ctx sink if one is attached). It is the primitive an agent firing or a sub-agent tool builds on. Because the guards on ctx are inherit-if-present and Once keeps the caller's sink, a sub-agent's Once inherits the parent's budget, spawn pool and call-id counter and streams to the parent's event sink. Pass WithStore to persist the transcript.
The input is text: a one-shot's model and effort are its options (WithModel, WithEffort), since it runs exactly once.
func Pause ¶
Pause stops EVERY pausable deadline on ctx while a blocking wait (e.g. an out-of-band approval) is in progress, returning a resume that restarts them all. A tool's Call invokes it so a human deciding never trips a wall-clock cap. No-op if ctx carries none. Token spend is unaffected. The paused span is also banked on the ctx's pausedClock so a tool's reported duration can exclude the out-of-band wait (see activeSince).
func Show ¶
Show hands b to whoever watches the tool call currently executing: ToolSet.Call puts it on that call's ToolEnd. It reports false outside a call, where nobody could see it, so a tool can say so instead of claiming it showed something. A call that fails shows nothing: its blocks are dropped.
func WithCallGuard ¶
WithCallGuard installs g as the CallGuard for every ToolSet.Call under ctx (replacing any earlier one). A nil g removes the guard.
func WithDiagnostics ¶
func WithDiagnostics(ctx context.Context, d *Diagnostics) context.Context
WithDiagnostics attaches a collector to ctx so any corner with the ctx can feed it via Diagnose — the same shape as the event sink. A nil collector leaves ctx unchanged.
func WithPausableBudget ¶
WithPausableBudget adds a pausable wall-clock cap of d (d <= 0 = none) that ALSO pauses (via Pause) while parked on an approval — for a nested budget such as a sandbox guest run, whose real-execution cap must not count out-of-band wait time. Unlike the turn deadline it does NOT inherit; each call adds its own to the set. Returns ctx + a stop func.
func WithResultFilter ¶
func WithResultFilter(ctx context.Context, f ResultFilter) context.Context
WithResultFilter installs f as the ResultFilter for every ToolSet.Call under ctx (replacing any earlier one). A nil f removes the filter.
Types ¶
type Agent ¶
Agent is an agent's declaration: a name, its instructions, the model it asks for and its reasoning effort (both "" = whatever the run that calls it runs on). It carries NO authority type (no policy/cage/capability), NO schedule, and NO tool list — scheduling is the consumer's business, and an agent's tools are chosen where it is wired (the ToolSet passed to AgentTool). Name must satisfy ToolNamePattern, since AgentTool uses it as the tool name.
type Audio ¶
type Audio struct {
MIME string `json:"mime"` // "audio/wav", …
Ref string `json:"ref"`
DurationMs int64 `json:"durationMs,omitempty"`
Data []byte `json:"-"`
}
Audio is the recording a user message was spoken as. Its message's Content is the transcript when one was made, and empty when the recording went to a model that hears it. Ref is the consumer's name for it, as for an Image; Data, the bytes, is loaded for the model per turn (WithMedia) and never serialized.
type Block ¶
type Block struct {
ID string `json:"id,omitempty"`
Kind string `json:"kind"`
Title string `json:"title,omitempty"`
Body string `json:"body"`
Replaces string `json:"replaces,omitempty"`
}
Block is something a tool shows the person instead of telling the model: a chart, a table, a diagram, a page. Kind is the consumer's word for what it is and Body its source in the form that kind names; agentkit gives neither a meaning. A block rides the ToolEnd of the call that showed it and never the model's conversation: the model reads the call's result, the person sees the block.
ID names the block for as long as it is kept, and Replaces is the ID of an earlier block this one is a new version of, empty for a block of its own. agentkit gives them no meaning either: what shows a block sets them, what draws it groups by them.
type CallGuard ¶
CallGuard decides whether a tool call may run, from the tool's name. ToolSet.Call asks the guard on its ctx before every call; a non-nil error refuses the call and becomes its result. The core gives it no meaning: a consumer installs one (agentkit/gate does, from its permission machinery).
It rides the ctx, not the ToolSet, so it cannot be dropped by handing a session a different set: every ToolSet.Call under that ctx — the model's, a script's, a sub-agent's — meets it.
type Diagnostic ¶
type Diagnostic struct {
Level Level
Subject string // what it's about: "tool:http.read", "skill:pdf", "runtime"
Message string
}
Diagnostic is one advisory finding fed into a Diagnostics collector from somewhere in the pipeline — a spec check, a skill loader, a runtime budget/quality hit.
func (Diagnostic) String ¶
func (d Diagnostic) String() string
type Diagnostics ¶
type Diagnostics struct {
// contains filtered or unexported fields
}
Diagnostics is a COLLECTOR — a plain container that different corners of the pipeline feed findings into (tool/skill validation, loaders, runtime checks). It produces nothing itself; it only gathers. The consumer drains it (All) or checks it (HasErrors) and logs as it sees fit. It is safe for concurrent feeders (parallel tool calls).
func DiagnosticsFrom ¶
func DiagnosticsFrom(ctx context.Context) *Diagnostics
DiagnosticsFrom returns the collector attached to ctx, or nil.
func (*Diagnostics) Add ¶
func (d *Diagnostics) Add(level Level, subject, msg string)
Add / Info / Warn / Error feed one finding in (the entry points for a corner holding the collector directly).
func (*Diagnostics) All ¶
func (d *Diagnostics) All() []Diagnostic
All returns a snapshot copy of the collected findings.
func (*Diagnostics) Error ¶
func (d *Diagnostics) Error(subject, msg string)
func (*Diagnostics) HasErrors ¶
func (d *Diagnostics) HasErrors() bool
HasErrors reports whether any finding is Error level.
func (*Diagnostics) Info ¶
func (d *Diagnostics) Info(subject, msg string)
func (*Diagnostics) Warn ¶
func (d *Diagnostics) Warn(subject, msg string)
type Effort ¶
type Effort string
Effort is an opaque reasoning-effort dial the adapter maps to provider knobs.
func EffortFrom ¶
EffortFrom returns the reasoning effort carried in ctx (set by the session), or "" if none. An LLM adapter reads it to override its own default per turn.
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is one item on a session's output stream — raw, time-ordered observations for a UI to render as they happen. The set is sealed (unexported marker method) so a consumer switches exhaustively over the known variants and no foreign type enters the stream. Aggregation (session token totals, latency histograms, cost) is a CONSUMER concern built by draining these.
Every event carries Frame: the enclosing call-frame id — 0 is the top-level (main) agent, non-zero is inside that tool call. A subagent runs inside an AgentTool call, so ALL of its events carry that call's id as Frame. That makes the main and subagent streams fully differentiable: a UI groups events by Frame, renders each non-zero Frame as a nested (collapsible / hideable) card under its tool call, and nests to any depth (a subagent's subagent gets its own Frame). Emit stamps Frame from ctx — emitters do not set it.
type Image ¶
type Image struct {
MIME string `json:"mime"` // "image/jpeg", "image/png", "image/webp"
Ref string `json:"ref"`
Data []byte `json:"-"`
}
Image is a picture a message carries. Ref is the consumer's name for it and, with MIME, the only part a store keeps: Data, the bytes, is loaded for the model when a turn is sent (WithMedia) and is never serialized, so a transcript holds references and not megabytes of base64.
func ConversationImages ¶
ConversationImages is the images of the conversation the calling turn has so far, newest first: those its messages came with and those earlier calls made, without their Data. It is what a tool that works on a picture of this conversation chooses from — "the last one", or one by its Ref — so it can reach no image the model was not shown in this conversation. Empty outside a turn's call.
type Input ¶
type Input struct {
Text string
Images []Image
Audio *Audio
Context string
ContextLabel string
Model string
Effort Effort
}
Input is one user turn: what was said, the images that came with it, the recording it was spoken as (nil when it was written; Text is then its transcript), what the caller gives the model to go with it, and how this turn is to be answered. Context and ContextLabel become the user message's own (Message.Context): Text stays the person's words alone. Model and Effort override the session's own (WithModel, WithEffort) for this turn alone; empty leaves them as they are.
type LLM ¶
LLM is the model port: given the conversation and the available tool specs, produce the next step (a final answer or a batch of tool calls). Streaming deltas are emitted on the ctx event sink by the adapter.
type LiveAudio ¶
type LiveAudio struct{ PCM []byte }
LiveAudio is a chunk of model speech. The adapter documents its sample rate — Gemini Live emits 24 kHz regardless of the input rate, so a consumer targeting a fixed-rate sink resamples.
type LiveCallsCancelled ¶
type LiveCallsCancelled struct{ IDs []string }
LiveCallsCancelled reports that the given tool calls will never be answered — the provider has discarded them and a result for those IDs is no longer wanted.
A consumer must stop whatever those calls are doing, which is more than tidiness when one is blocked on a human: an approval nobody is waiting for any more should not still be sitting on somebody's phone, and it must never grant authority for a call that no longer exists.
type LiveError ¶
type LiveError struct{ Err error }
LiveError is a session-level failure the adapter could not recover from. It is delivered on the stream rather than returned, because it can happen at any point after Open; the stream closes after it.
type LiveEvent ¶
type LiveEvent interface {
// contains filtered or unexported methods
}
LiveEvent is one item on a LiveSession's output stream. Like Event, the set is sealed (unexported marker) so consumers switch exhaustively and no foreign variant enters the stream.
type LiveInterrupted ¶
type LiveInterrupted struct{}
LiveInterrupted reports that the user talked over the model and generation was cut. Any audio the consumer has buffered but not yet played is now stale and must be dropped — otherwise the speaker keeps answering a question the user already abandoned.
type LiveLLM ¶
type LiveLLM interface {
// Open starts a session seeded with conv (a system message and any prior transcript) and the
// tool declarations the model may call. The session runs until Close or ctx cancellation.
Open(ctx context.Context, conv []Message, tools []ToolSpec) (LiveSession, error)
}
LiveLLM is the duplex counterpart of LLM: a model that consumes and produces a CONTINUOUS audio stream rather than answering one turn at a time. It is a separate port on purpose — LLM.Next is request/response and has a turn boundary, a live model has neither, so widening LLM would have meant a turn-shaped API pretending to be a stream. Session drives LLM; a consumer drives LiveLLM (see the driver in nocturn's internal/voice), because what a live stream needs — audio transport, barge-in, wall-clock budget — is the consumer's concern, not the turn loop's.
Tools are unaffected: a LiveSession surfaces ToolCall events and takes ToolResult back, so the SAME ToolSet (and, in a gated deployment, the same gate machinery on ctx) serves both ports.
type LiveModelText ¶
type LiveModelText struct{ Text string }
LiveModelText is a transcript delta of what the MODEL said. Same purpose as LiveUserText: the spoken answer in text, for the transcript and the screen.
type LiveSession ¶
type LiveSession interface {
// SendAudio feeds one chunk of microphone PCM upstream. The adapter documents the wire format
// it expects; nocturn's satellites produce 16 kHz mono little-endian PCM16 end to end.
SendAudio(ctx context.Context, pcm []byte) error
// SendResult answers one ToolCall. Results may arrive in any order and long after the call, so
// the model can keep speaking while a tool waits on an out-of-band approval. A result marked
// Pending may be followed by further results for the same ID.
SendResult(ctx context.Context, r ToolResult) error
// Events is the session's one-way output stream, closed when the session ends. A consumer that
// stops draining it stalls the session — drain it in its own goroutine.
Events() <-chan LiveEvent
// Close ends the session and releases its transport. It is idempotent.
Close() error
}
LiveSession is one open duplex conversation. Send* and Close are safe to call from a goroutine other than the one draining Events — that separation is the point: a tool call that blocks on a human approval must not stall the audio path.
type LiveToolCall ¶
LiveToolCall is a model-issued call. Args is raw JSON, exactly as Tool.Call expects it.
type LiveTurnDone ¶
type LiveTurnDone struct{}
LiveTurnDone marks the model finishing a reply. A live session continues past it; it is a punctuation mark for the consumer (flush the transcript, idle the UI), not an end of session.
type LiveUserText ¶
type LiveUserText struct{ Text string }
LiveUserText is a transcript delta of what the USER said, as the provider heard it. It exists so a consumer can persist and display the conversation without running its own speech recognition.
type Logger ¶
type Logger interface {
Debug(msg string, kv ...any)
Info(msg string, kv ...any)
Warn(msg string, kv ...any)
Error(msg string, kv ...any)
With(kv ...any) Logger
WithContext(ctx context.Context) Logger
}
Logger is the diagnostic logging PORT — a small leveled key/value interface the consumer plugs its own logger into (never a hard-typed *slog.Logger), so any implementation (slog, zap, zerolog, custom) wraps it trivially. kv are alternating key/value pairs (like slog). With derives a logger that stamps the given kv on every line (e.g. component="llm"), so a subsystem tags its own lines without every call site repeating the key. WithContext derives a logger enriched from ctx (request/trace ids) for request-scoped logging.
func NopLogger ¶
func NopLogger() Logger
NopLogger discards everything. It is the default when no logger is configured.
func SlogLogger ¶
SlogLogger adapts a stdlib *slog.Logger to the port. A nil logger yields NopLogger.
type MediaLoader ¶
MediaLoader returns the bytes of the image or recording a consumer named ref (Image.Ref, Audio.Ref). The consumer owns where they live; agentkit only asks, once per turn, for the ones the model is sent (WithMedia).
type MemStore ¶
type MemStore struct {
// contains filtered or unexported fields
}
MemStore is an in-memory Store.
type Message ¶
type Message struct {
Role Role `json:"role"`
Content string `json:"content,omitempty"`
Context string `json:"context,omitempty"` // set on a user message the caller gave the model something to go with
ContextLabel string `json:"contextLabel,omitempty"` // what a surface shows in the context's place
Images []Image `json:"images,omitempty"` // set on a user message that came with pictures, and on a tool result whose call made some
Audio *Audio `json:"audio,omitempty"` // set on a user message that was spoken
ToolCalls []ToolCall `json:"toolCalls,omitempty"` // set on an assistant message that issues calls
ToolCallID string `json:"toolCallID,omitempty"` // set on a tool-result message
DurationMs int64 `json:"durationMs,omitempty"` // wall-clock of the tool call, on a tool-result message
}
Message is one conversation turn. A tool result is a RoleTool message whose ToolCallID links it to the call it answers (native id association, not positional). The optional fields carry omitempty so a persisted transcript stays clean — a plain message serializes to just role + content, without null tool-call clutter.
A message's content is its context, its text, the images it carries and the recording it was spoken as, in that order. That is the whole of the provider-neutral form: each adapter renders them as its own provider's parts, and a model that hears no audio is shown the text alone (Shown).
Context is text the caller attached to a user message for the model: not the person's words, which are Content alone. A surface shows the person's words and, in place of the context, its ContextLabel, a short name for what it is about; the model is shown the context before the words.
func NoAudio ¶
NoAudio is conv for a model that hears no audio: every recording's Data is dropped, so Shown renders its transcript, or its AudioNote where none was made — and a recording without a transcript on the turn's own input refuses the turn with ErrNoAudioInput.
func TextOnly ¶
TextOnly is conv for a model that takes no images: every earlier image becomes an ImageNote (its Data dropped, so Shown renders the note), and an image on the turn's own input — the last user message — refuses the turn with ErrNoImageInput. A conversation that switched to such a model therefore goes on, and only a new picture is refused.
func (Message) Heard ¶
Heard is the recording m carries with its bytes, for an adapter whose model hears audio; nil when it carries none or it was not loaded.
func (Message) Said ¶
Said is m's words as a surface without a player shows them (a list's preview, a terminal): its content, or the AudioNote of a recording nothing was written down from.
func (Message) Shown ¶
Shown is m as a model is shown it: its context, a blank line and its text (the context alone when there is no text), with an ImageNote for every image that has no Data, and the images that do. A recording without Data and without a transcript stands as its AudioNote; one with Data is the adapter's to send (Heard). An adapter renders a message through it, so nothing is sent empty and nothing vanishes without a trace.
type Option ¶
type Option func(*config)
Option configures a Session (or a Once run).
func WithEffort ¶
func WithEffortFunc ¶
WithEffortFunc supplies the reasoning effort through a function evaluated once per turn, for a conversation whose effort is a setting that can change while it is open. The adapter reads the result from the turn's ctx (EffortFrom); "" leaves it to the adapter's default, or to an enclosing run's effort for a sub-agent.
func WithLogger ¶
func WithMaxDepth ¶
WithMaxDepth caps how deep AgentTool spawns may nest (0 = a sensible default). A spawn past it is refused with ErrMaxDepth, surfaced to the model as the tool result.
func WithMaxSpawns ¶
WithMaxSpawns caps the TOTAL number of sub-agents spawned across the whole tree (0 = a sensible default) — the population guard depth cannot provide. Exceeding it refuses with ErrMaxSpawns.
func WithMaxSteps ¶
WithMaxSteps caps model round-trips per turn (0 = a sensible default).
func WithMedia ¶
func WithMedia(load MediaLoader, history int) Option
WithMedia loads the images a conversation carries for the model through load, keyed by each image's Ref. A turn sends every image of its own input and, of the earlier messages, the newest history ones; an older image is not sent, and the model sees an ImageNote where it stood. A loader that fails on an earlier image costs that image the same way and is logged; one that fails on the turn's own input fails the turn, since that is the picture the person is asking about. Recordings are loaded by the same rule, counted apart: the turn's own and the newest history earlier ones, the rest shown as their transcript or an AudioNote (an adapter whose model hears none drops them all, NoAudio). A negative history is 0.
func WithModelFunc ¶
WithModelFunc supplies the name of the model a turn asks for, evaluated once per turn and carried on the turn's ctx (ModelFrom). "" asks for none, which leaves the choice to the LLM, or to an enclosing run's for a sub-agent.
func WithSkills ¶
func WithSkillsFunc ¶
WithSkillsFunc is WithToolsFunc for the skill catalog, evaluated on the same boundary.
func WithStore ¶
WithStore persists this session's transcript under id: history is loaded from the store when the session is built and saved after each turn. Without it a session is in-memory only. Multiplexing many sessions and evicting idle ones is the CONSUMER's concern (its own map[id]*Session + policy) — the library owns no live-session lifecycle.
func WithSystem ¶
func WithSystemFunc ¶
WithSystemFunc supplies the system prompt through a function evaluated once per turn, for a prompt whose content can change over a session's lifetime (a consumer folding in mutable context). Safe because the system message is ephemeral — it is put in front of the durable history for each turn rather than stored — so a changed prompt cannot corrupt a persisted transcript.
All three funcs must be safe for concurrent use only insofar as the caller shares one across sessions; a single session evaluates it on its own turn goroutine.
func WithTimeout ¶
WithTimeout caps wall-clock per turn. It is PAUSABLE — time spent waiting on out-of-band approval does not count (see withTimeout). 0 = none.
func WithTokenLimit ¶
WithTokenLimit caps the turn's cumulative BILLED tokens (sum of every round-trip's prompt + completion). Reactive: the loop checks the running total after each round-trip and stops with ErrTokenLimit before the next. 0 = none. The count comes from the provider response; if the provider omits it, configure WithTokenizer to fall back to an estimate. (max_tokens, the per-response output cap, is a separate adapter option.)
func WithTokenizer ¶
WithTokenizer sets a fallback tokenizer to ESTIMATE a round-trip's tokens at the model boundary (the conversation sent in, the step returned out) when the provider reports no usage — so WithTokenLimit and the [tokens] readout still work against endpoints that omit it. When the provider returns usage, that exact count wins and the tokenizer is unused. Estimation is approximate; exact billing is the provider's usage.
func WithTools ¶
The value forms, sugar over the funcs above: a constant is a function that returns the same thing every turn.
func WithToolsFunc ¶
WithToolsFunc supplies the toolset through a function evaluated once per turn, for a consumer whose available tools change over a session's lifetime — an extension installed or removed while the conversation is open. The turn boundary is what makes it safe: a turn is handed its set once and works with it throughout, so a tool can never vanish between two calls the model already planned together, and the next turn simply sees the new world.
type PromptNoter ¶
PromptNoter is a Tool that brings a note for the system prompt: what a model offered the tool must know beyond the tool's own description, such as how its output fits the answer. The tools of one family return one note. agentkit puts the notes nowhere itself; whoever writes the system prompt collects them with PromptNotes, so a family that is not offered says nothing.
type ResultFilter ¶
ResultFilter rewrites what a tool call produced before it goes back to whoever called the tool (the model, a script, a parent agent) and into the ToolEnd event. ToolSet.Call applies the filter on its ctx after the tool ran. The core gives it no meaning: a consumer installs one, for example to redact secrets from every result in one place instead of trusting each tool to do it.
It rides the ctx like CallGuard, so it applies to every ToolSet.Call under that ctx, whichever set the call came from. A filter must keep an error an error (and should keep it errors.Is-able), unless the error is the consumer's own word that the call did not fail but was set aside (a call parked for later), whose result is then the note that says so.
type Schema ¶
type Schema struct {
Type SchemaType
Description string
Properties map[string]*Schema // for Object
Required []string // for Object
Items *Schema // for Array
Enum []string // for String
// Format names what a value holds beyond its type ("email", "markdown", "date-time" for a
// string; "attachment" for an object), JSON Schema's own word for it. A model reads it as a hint;
// a surface that edits the arguments (a draft's editor) reads it to know an address, rich text or
// a file from any other value.
Format string
}
Schema is agentkit's canonical, provider-agnostic parameter schema. It is the ONE representation of a tool's arguments: build it with the helpers below, or parse a foreign JSON Schema into it with ParseSchema — either way you get a Schema. An adapter renders it to a provider's accepted JSON Schema. There is nothing to "sanitize": the model only expresses supported constructs, so unsupported keywords simply have no field and never reach a provider (allowlist by construction).
func Object ¶
Object builds an object schema from its properties. Chain .Require to mark required ones.
func ParseSchema ¶
func ParseSchema(raw json.RawMessage) (*Schema, error)
ParseSchema maps a foreign JSON Schema into a Schema, keeping the supported constructs (type, description, properties, required, items, string enum and format) and dropping the rest by simply not representing it — so an MCP/plugin tool's hand-written schema goes through the same render path, no blocklist. An empty input yields nil (a no-arg tool). Malformed JSON is an error.
func (*Schema) Render ¶
func (s *Schema) Render(typeName func(SchemaType) string) map[string]any
Render maps the schema to the JSON-Schema-shaped map an LLM API's tool declaration takes, writing each type name with typeName (providers differ: an OpenAI-compatible endpoint wants "object", Gemini "OBJECT"). Because Schema only holds the portable subset shared by OpenAI, Anthropic and Gemini — type, description, properties, required, items, enum, format (Gemini takes any format and acts on few) — there is nothing to strip: the output is the safe lowest common denominator by construction. A nil schema renders as an object with no properties, since a tool without arguments still needs a parameters block.
func (*Schema) Require ¶
Require marks properties as required and returns the schema (for chaining).
func (*Schema) WithEnum ¶
WithEnum restricts a string schema to a set of values and returns it (for chaining).
func (*Schema) WithFormat ¶
WithFormat says what a schema holds (FormatEmail, FormatMarkdown, FormatAttachment) and returns it (for chaining).
type SchemaType ¶
type SchemaType string
SchemaType is a JSON Schema primitive type.
const ( TypeObject SchemaType = "object" TypeString SchemaType = "string" TypeNumber SchemaType = "number" TypeInteger SchemaType = "integer" TypeBoolean SchemaType = "boolean" TypeArray SchemaType = "array" )
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is a live conversation: a serialized turn loop driven by Submit (input in) and observed via Subscribe (event stream out). It owns the lifecycle around the turns: the input queue, the output stream, closing and cancelling. The turns themselves, and the history they grow, are the runner's.
func NewSession ¶
NewSession builds a Session and starts its internal turn loop under ctx. ctx is the session's LIFECYCLE: cancelling it (or Close) stops the loop, cancels any in-flight turn, and closes the Subscribe channel. Each Submit'd turn runs under a child of ctx decorated with the event sink, the per-turn timeout and fresh guards. Without WithLogger it uses NopLogger().
func (*Session) Cancel ¶
func (s *Session) Cancel()
Cancel aborts the in-flight turn (if any) without stopping the session: the turn ends with a context.Canceled error, its partial output is still appended and persisted, and the next Submit runs normally. A no-op when no turn is running.
func (*Session) Close ¶
func (s *Session) Close()
Close stops the session: it cancels the internal loop and any in-flight turn and closes the Subscribe channel. Sugar for cancelling the ctx passed to NewSession; safe to call more than once.
type Skill ¶
Skill is one progressive-disclosure entry: name + description (the catalog the model sees) plus body. Context, zero authority — the skills analog of a tool. WHERE a Skill comes from (disk, embed, network, the moon) is NOT this package's concern; the consumer builds Skill values and hands them in, exactly like tools.
type SkillSet ¶
SkillSet is the skills available to a session, keyed by name — a plain named map (like ToolSet), so index/range/len work; the domain methods sit on top. Select returns a COPY.
func NewSkillSet ¶
NewSkillSet builds a SkillSet keyed by Name, validating each skill. It returns an error if any skill is invalid or two share a name — so a SkillSet never holds an invalid or colliding skill.
func (SkillSet) LoadTool ¶
LoadTool returns the load_skill tool: the model calls it with a skill name to pull that skill's body into the conversation (progressive disclosure), backed by THIS set. Like any tool it is just a Tool value — no authority, only context.
type Step ¶
type Step struct {
Answer string
ToolCalls []ToolCall
Tokens TokenCount
}
Step is the LLM's output for one Next: either a final Answer or a batch of ToolCalls, plus the TokenCount of THIS round-trip (the adapter fills it from the provider response — no tokenizer).
type Store ¶
type Store interface {
Save(id string, msgs []Message) error
Load(id string) ([]Message, error)
List() ([]string, error)
}
Store persists a session's transcript. Session is this package's runtime aggregate, so an unqualified Store (and Manager) unambiguously means "session" — tools and skills are Sets, not stores. The consumer supplies the implementation (file-backed, DB, …); MemStore is the in-memory default for tests and simple use.
type TokenCount ¶
TokenCount is a prompt/completion token count. From a Step it is one round-trip; on TurnEnd it is the turn total (the sum of every round-trip = what you are BILLED, since history is re-sent each call). To gauge context-window fill instead, read the LAST round-trip's Prompt, not the sum.
type Tokenizer ¶
Tokenizer estimates the token count of a piece of text. It is a PORT: exact token counts come from the provider response (Step.Tokens); a Tokenizer is only for ESTIMATION — either proactive pre-send budgeting, or a fallback when an endpoint omits usage so WithTokenLimit still functions. Accurate, model-specific tokenizers (e.g. tiktoken) are separate adapter modules; the core ships only this interface and a rough dependency-free default.
func ApproxTokenizer ¶
func ApproxTokenizer() Tokenizer
ApproxTokenizer returns the built-in rough estimator (~4 chars/token). It never errors.
type Tool ¶
Tool is the port. The consumer builds it; its guard sits in Call, because the consumer is the one who knows what the tool does. A Tool may hold state/deps as fields. The verb is Call because the model issues a ToolCall — calling the tool is the natural act.
func AgentTool ¶
AgentTool exposes an agent as a callable Tool, so a parent agent can DELEGATE to it as a subagent — a subagent is just a tool. The returned tool's Call runs the agent to a final answer (Once) over the input argument, with a.Instructions as system and tools as its toolset. The caller scopes the subagent by what it passes: nil for a leaf, tools.Select(keep) for a subset, the full set otherwise — the same immutable-subset mechanism as everywhere else. Because Call receives the parent's ctx, the subagent's own tool calls nest under this call in the event forest, its tokens/events stream to the same sink, and it inherits the outer budget — nesting is automatic.
Before running, Call passes through enterSpawn: it charges the tree's depth and population caps (WithMaxDepth / WithMaxSpawns) and, if a cap is exceeded, returns ErrMaxDepth / ErrMaxSpawns as the tool result so the model finishes the work directly instead of spawning further. Whether the subagent can spawn its OWN subagents is decided by whether any AgentTools are in tools — omit them and it is a leaf.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Tool string `json:"tool"`
Args string `json:"args"` // JSON
}
ToolCall is one model-issued call, carrying the id used to match its result.
type ToolEnd ¶
type ToolEnd struct {
Frame, ID uint64
Tool, Args, Result string
Images []Image
Err error
Blocks []Block
Duration time.Duration
}
ToolEnd carries the outcome of a tool's Call, including its wall-clock Duration (per-call, a tool-level number — not turn-level), the images it and the calls under it made (AttachImages), by reference and without Data, and the Blocks the call showed the person (Show), which the model never sees; nil when it showed none or failed.
type ToolFunc ¶
ToolFunc is a tool's implementation as a closure: raw JSON args in, a string result out. It is what NewTool wraps and what a Tool's Call ultimately runs.
type ToolOption ¶
type ToolOption func(*toolOptions)
ToolOption configures a Tool built by NewTool.
func WithMaxChars ¶
func WithMaxChars(n int) ToolOption
WithMaxChars truncates the tool's result to n characters (0 = unbounded). The library enforces it around Call so a tool needn't self-truncate.
func WithSchema ¶
func WithSchema(schema *Schema) ToolOption
WithSchema sets the tool's argument schema (omit for a no-arg tool). Build it with Object / Prop / String / Number / … or ParseSchema a foreign JSON Schema; an adapter renders it to the provider's accepted dialect.
type ToolResult ¶
type ToolResult struct {
ID string
Tool string
Result string
Err error
// Late reports that the conversation moved on while this call was outstanding — the speakers
// completed at least one turn between the call and this answer.
//
// It exists because correlation is not the same as timing. A provider matches the answer to its
// call by ID however long it takes, but an answer that arrives two subjects later should not cut
// into whatever is being said now: the person asked about a file, then moved to the weather, and
// having the file contents interrupt the weather is worse than a short wait. An adapter maps
// this onto whatever delivery its provider offers; one with no such control ignores it.
Late bool
// Pending marks this as an INTERIM answer: the call is still running and a final result for the
// same ID will follow.
//
// It exists because a pending call is otherwise opaque from the model's side. It sees that it
// called something and that nothing came back, but not why — waiting on a slow server and
// waiting on a human holding a phone are indistinguishable. An assistant told to explain the
// wait would have to guess, and guessing "check your phone" when nothing is pending there is
// worse than saying nothing.
//
// Answering the call itself is what makes this safe to say. The alternative — injecting the
// reason as conversational input — counts as somebody speaking, which interrupts the model
// mid-sentence and makes it abandon what it was saying. An interim result is data about a call
// the model already made, so it arrives without anyone appearing to talk.
Pending bool
}
ToolResult is the answer to a LiveToolCall. Err is rendered for the model rather than returned to the caller: a failed tool is information the model acts on, not a transport failure.
type ToolSet ¶
ToolSet is the tools available to a session, keyed by name — a plain named map, so index, range, len and delete all work; the domain methods just sit on top. Immutability and agent attenuation are by convention: Select returns a COPY, so an agent's subset simply lacks the tools it may not use (a missing key is unreachable) and cannot widen the parent.
func NewToolSet ¶
NewToolSet builds a ToolSet keyed by each tool's Spec().Name, validating every spec. It returns an error if any tool's spec is invalid or two tools share a name — so a ToolSet never holds an invalid or colliding tool. (Building the map literal directly bypasses this guarantee.)
func (ToolSet) Call ¶
Call looks up name and runs its Tool.Call. It assigns a fresh call-instance id (from a counter carried in ctx, so nested calls form a parent/child forest — the name is tool identity, the id is call identity for the same tool called several times or nested) and emits ToolStart/ToolEnd around the run. The name and the arguments ride the call's ctx (CallingTool, CallArgs), and so does where the call's blocks go (Show): onto its ToolEnd. A CallGuard on ctx is asked first; its refusal is the call's error. A ResultFilter on ctx rewrites what the tool produced, before the caller and the ToolEnd event see it. The images the tool attached (AttachImages) ride on its ToolEnd and go on to the call around it. An unknown tool is a non-fatal error surfaced to the model.
func (ToolSet) PromptNotes ¶
PromptNotes is the notes the tools in t bring, each once, in the order of the tools' names: what a system prompt adds for exactly the tools offered.
type ToolSpec ¶
type ToolSpec struct {
Name string
Description string
Parameters *Schema // argument schema; nil = no-arg tool
}
ToolSpec is a tool's model-facing declaration — only what the model needs to decide to call it. Runtime behavior (result budget, …) is NOT here; it lives on the Tool via options.
func (ToolSpec) Validate ¶
Validate enforces the hard rule a provider rejects with a 400: Name matches ToolNamePattern. Description LENGTH is NOT enforced here (an over-long description is a Warn diagnostic). Parameters need no check: a *Schema is valid by construction and the adapter renders it to the provider's dialect. Call-argument validation is the tool's OWN job inside Call.
type ToolStart ¶
ToolStart is emitted before a tool's Call runs. ID is this call's id; it becomes the Frame of everything the call emits underneath (so a subagent tool's ID is the Frame of the subagent).
type TurnEnd ¶
type TurnEnd struct {
Frame uint64
Err error
Tokens TokenCount
}
type TurnStart ¶
type TurnStart struct{ Frame uint64 }
TurnStart / TurnEnd bracket a whole turn. TurnEnd carries the turn's accumulated TokenCount (summed across every model round-trip) and the stop reason, if any (Err = ErrMaxSteps / ErrTokenLimit / ErrTurnTimeout / context.Canceled). For a subagent turn, Frame is the enclosing AgentTool call.