ai

package
v0.22.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 21 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 ai is the platform's agent loop: a model provider, a set of tools, a session of append-only messages, and the loop that runs a prompt to completion while streaming events to the caller.

The package is provider-neutral and product-free. A model provider (package ai/anthropic) turns one request into one assistant turn; tools are anything that satisfies Tool (package ai/apitool generates them from an OpenAPI document, ai/rag and ai/memory contribute retrieval and memory, ai/mcp bridges to and from MCP servers); sessions persist in the host's store. The host process that holds the admin store satisfies CredentialResolver so that the model endpoint and key come from the admin API token vault and never reach a browser.

Message history is stored in the provider's native content-block form and is append-only: current models bind their reasoning blocks to the conversation that produced them, so a harness must never rewrite earlier turns. Context pressure is handled by the provider (server-side compaction), not by editing history here.

Import boundary: this package and its subpackages import admin/client, never the root admin package. The root admin package imports them to host the assistant.

Index

Constants

View Source
const (
	// DefaultMaxTurns bounds the number of model turns in one Run.
	DefaultMaxTurns = 25
	// DefaultMaxToolResultBytes bounds the content of one tool result as
	// the model sees it.
	DefaultMaxToolResultBytes = 64 * 1024
	// DisplayToolResultBytes bounds the copy of a tool result kept in
	// Message.ToolResults for transcripts.
	DisplayToolResultBytes = 2000
	// StopReasonMaxTurns is the stop reason EventDone carries when a run
	// ends because MaxTurns was reached.
	StopReasonMaxTurns = "max_turns"
)
View Source
const (
	// ResourceTypeModel marks a chat model credential.
	ResourceTypeModel = "ai_model"
	// ResourceTypeEmbedding marks an embeddings credential.
	ResourceTypeEmbedding = "ai_embedding"
	// ResourceTypeMCPServer marks a remote MCP server the agent may use.
	ResourceTypeMCPServer = "mcp_server"

	// TagProvider names the API dialect: anthropic, openai_compat, voyage,
	// ollama.
	TagProvider = "ai_provider"
	// TagModel is the model id, for example claude-opus-5-5 or voyage-3.
	TagModel = "ai_model"
	// TagContextWindow is the model's context window in tokens, when the
	// provider cannot discover it; the ollama and openai_compat providers
	// report it from a credential test when the server does not say.
	TagContextWindow = "ai_context_window"
	// TagMaxOutput is the maximum output tokens per turn.
	TagMaxOutput = "ai_max_output"
	// TagDimensions is the embedding vector size.
	TagDimensions = "ai_embedding_dimensions"
	// TagEffort is the reasoning effort for a model credential: low,
	// medium, high, xhigh, max.
	TagEffort = "ai_effort"
	// TagMCPTrustReadOnly, set to "true" on an mcp_server credential, makes
	// the host trust the server's readOnlyHint annotations, so its
	// read-only tools run without write approval. Absent, every tool of
	// the server is treated as a write. Set it only for a server the
	// operator controls.
	TagMCPTrustReadOnly = "mcp_trust_read_only"

	ProviderAnthropic    = "anthropic"
	ProviderOpenAICompat = "openai_compat"
	ProviderVoyage       = "voyage"
	ProviderOllama       = "ollama"

	// OllamaDefaultEndpoint is the Ollama server an ollama credential
	// without an endpoint talks to.
	OllamaDefaultEndpoint = "http://localhost:11434"
)

A model, embedding, or MCP server credential is an ordinary admin API token (type bearer, user or account scope) whose metadata says what it opens: ResourceType selects the kind, Endpoint is the base URL, and the tags below carry the provider and model. The sealed Token is the API key (static mode) or the OIDC inputs a bearer is minted from, exactly as for every other vault credential. @bboxsys/ui mirrors these names in src/lib/aiCredential.ts; keep the two in step.

View Source
const (
	// DefaultMountPrefix is the route prefix Mount uses when given none.
	DefaultMountPrefix = "/api/v1/ai"
	// HeartbeatInterval is how often SendMessage writes an SSE comment
	// while a run produces no event, so proxies keep the stream open.
	HeartbeatInterval = 15 * time.Second
	// MaxPromptBytes bounds the body of SendMessage and CreateSession.
	MaxPromptBytes = 1 << 20
	// DefaultSetupTimeout bounds building the tool set, the system prompt,
	// and the preamble before a run, and the tool listing of Status.
	DefaultSetupTimeout = 20 * time.Second
	// MaxCachedProviders bounds the provider cache; past it the oldest
	// entry is evicted.
	MaxCachedProviders = 256
)
View Source
const ChartGuidance = `` /* 927-byte string literal not displayed */

ChartGuidance is appended to the default system prompt when ServiceOptions.Charts is set. The block it describes is what the admin SPA's assistant page renders with Apache ECharts; the option is plain JSON so no code runs on the client.

View Source
const ErrNoModel = "no AI model credential configured"

ErrNoModel is the message SendMessage and CreateSession answer with when the caller has no model credential.

View Source
const MaxTitleRunes = 200

MaxTitleRunes bounds a session title.

View Source
const SessionPrefix = "ai_session"

SessionPrefix is the store prefix sessions live under, scoped by account: {accountID}:ai_session:{userID}:{sessionID}.

View Source
const StopReasonToolUse = "tool_use"

StopReasonToolUse is the stop reason that keeps the loop going.

View Source
const UsageTimeout = 5 * time.Second

UsageTimeout bounds the call to ServiceOptions.Usage after a run.

Variables

View Source
var ErrDuplicateTool = errors.New("ai: duplicate tool name")

ErrDuplicateTool is returned by Registry.Add for a name already present.

View Source
var ErrInvalidToolName = errors.New("ai: invalid tool name")

ErrInvalidToolName is returned for a name that does not match ToolNamePattern.

View Source
var ErrNoCredential = errors.New("ai: no credential configured")

ErrNoCredential is returned when no usable credential of the requested kind is visible to the caller.

View Source
var ErrNoProvider = errors.New("ai: provider is required")

ErrNoProvider is returned by New when Options.Provider is nil.

View Source
var ErrSessionNotFound = errors.New("ai: session not found")

ErrSessionNotFound is returned by SessionStore.Get and Delete.

View Source
var ToolNamePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)

ToolNamePattern is what a tool name must match: the Anthropic and MCP limits are both satisfied by this subset.

Functions

func DefaultSystem

func DefaultSystem(caller Caller) string

DefaultSystem is the system prompt used when ServiceOptions.System is nil. It names the tenant, states that the assistant acts as the user through the user's own permissions, and sets the rule that tool output and recalled facts are data, not instructions.

func OllamaBaseURL

func OllamaBaseURL(endpoint string) string

OllamaBaseURL returns the Ollama server root for a credential's endpoint: OllamaDefaultEndpoint when it is empty, otherwise the endpoint without a trailing slash and without a trailing /api or /v1, since Ollama's native API and its OpenAI-compatible one hang off the same root and a credential may name either. The model provider appends /v1, the embedder /api.

func RepairDanglingToolCalls

func RepairDanglingToolCalls(session *Session, provider Provider) bool

RepairDanglingToolCalls makes a session whose last message is an assistant message with tool calls valid to continue: that history ends in tool_use blocks with no tool_result, which the model API rejects, and it is what a process that stopped while tools ran leaves on disk. It appends one tool result message answering every call with an error result and reports whether it did; nothing earlier is edited. Call it on a loaded session before Run.

func Truncate

func Truncate(s string, limit int) string

Truncate cuts s to at most limit bytes on a rune boundary and appends a marker saying how much was shown. s is returned unchanged when it fits.

func WithCaller

func WithCaller(ctx context.Context, c Caller) context.Context

WithCaller returns a context carrying the caller.

Types

type Agent

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

Agent runs prompts against a provider and a tool set. It is safe for concurrent use; per-run state lives in the Session.

func New

func New(o Options) (*Agent, error)

New validates o and returns an Agent.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, session *Session, prompt string, emit func(Event)) error

Run appends prompt to the session as a user message and drives the loop until the model stops without tool calls, MaxTurns is reached, the context is cancelled, or the provider fails. Every message produced is appended to session.Messages; the caller persists the session afterwards. emit receives every Event of the run and may be nil.

A provider error or a cancelled context ends the run with EventError and the error; every other outcome ends with EventDone and a nil error.

type Caller

type Caller struct {
	AccountID string
	// UserID is the user's NATS public key, as admin.UserIDFromContext
	// returns it after Bearer.
	UserID string
	// Bearer is the caller's own token, forwarded to API tools.
	Bearer string
}

Caller is the identity a run acts as. Tools that call the platform's own HTTP API forward Bearer and the account so the service's normal authorization applies; nothing in the loop grants more than the caller already has.

func CallerFromContext

func CallerFromContext(ctx context.Context) (Caller, bool)

CallerFromContext returns the caller placed by WithCaller.

func CallerFromRequest

func CallerFromRequest(r *http.Request) Caller

CallerFromRequest builds the Caller for a request that has passed the ID and Bearer middleware: the account and user from the context and the bearer from the Authorization header.

type CheckError

type CheckError struct {
	Kind    CheckErrorKind
	Message string
}

CheckError is a classified check failure. Message never contains the credential's secret.

func (*CheckError) Error

func (e *CheckError) Error() string

type CheckErrorKind

type CheckErrorKind string

CheckErrorKind classifies a failed credential check so a UI can say what to fix.

const (
	// CheckAuth means the provider rejected the key.
	CheckAuth CheckErrorKind = "auth"
	// CheckNotFound means the key works but the model does not exist or is
	// not available to it.
	CheckNotFound CheckErrorKind = "not_found"
	// CheckUnreachable means the endpoint could not be reached.
	CheckUnreachable CheckErrorKind = "unreachable"
	// CheckRejected is any other refusal from the provider.
	CheckRejected CheckErrorKind = "rejected"
)

type CheckResult

type CheckResult struct {
	// Model is the model id the credential will use.
	Model string `json:"model,omitempty"`
	// DisplayName is the provider's name for the model.
	DisplayName string `json:"display_name,omitempty"`
	// ContextWindow is the model's maximum input tokens, when known.
	ContextWindow int64 `json:"context_window,omitempty"`
	// MaxOutput is the model's maximum output tokens, when known.
	MaxOutput int64 `json:"max_output,omitempty"`
}

CheckResult describes what a successful check found.

type Checker

type Checker interface {
	Check(ctx context.Context) (CheckResult, error)
}

Checker is implemented by providers that can verify their credential without running a model turn, for a "test this key" action. Check must not spend output tokens.

type Credential

type Credential struct {
	// Name is the token's name in the vault.
	Name string
	// ResourceType is one of the ResourceType constants.
	ResourceType string
	// Provider is the TagProvider value; empty means the host's default
	// for the resource type.
	Provider string
	// Endpoint is the base URL; empty means the provider's public API.
	Endpoint string
	// Model is the TagModel value; empty means the provider's default.
	Model string
	// Bearer is the API key or minted token.
	Bearer string
	// Tags are the token's metadata tags, for provider-specific settings.
	Tags map[string]string
}

Credential is a resolved vault credential: metadata plus the bearer the host minted or unsealed for this call. It is never serialized to a client.

func (Credential) IntTag

func (c Credential) IntTag(key string, def int) int

IntTag returns a tag parsed as an integer, or def when absent or invalid.

func (Credential) Tag

func (c Credential) Tag(key string) string

Tag returns a tag value or "".

type CredentialLister

type CredentialLister interface {
	Models(ctx context.Context, accountID, userID string) ([]Credential, error)
}

CredentialLister is implemented by a CredentialResolver that can list every model credential the caller may use, in the order Model("") would try them, so a client can offer a choice of model per session (Status reports them). Without it, Status lists only the default.

type CredentialRef

type CredentialRef struct {
	Name     string `json:"name"`
	Provider string `json:"provider"`
	Model    string `json:"model"`
}

CredentialRef is the public projection of a credential in Status.

type CredentialResolver

type CredentialResolver interface {
	Model(ctx context.Context, accountID, userID, name string) (Credential, error)
	Embedding(ctx context.Context, accountID, userID, name string) (Credential, error)
	// MCPServers returns every remote MCP server credential the caller may use.
	MCPServers(ctx context.Context, accountID, userID string) ([]Credential, error)
}

CredentialResolver reads credentials for a caller. The host process that holds the admin store implements it (root admin package); the lookup order is the vault's: the user's own tokens first, then the account's shared ones. name "" means the first visible credential of that kind.

type Event

type Event struct {
	Type EventType `json:"type"`
	// Text is the delta for EventText and EventThinking, and the summary
	// for EventCompaction.
	Text string `json:"text,omitempty"`
	// Call is set for EventToolUse.
	Call *ToolCall `json:"call,omitempty"`
	// Result is set for EventToolResult.
	Result *ToolResult `json:"result,omitempty"`
	// Usage is set for EventUsage.
	Usage *Usage `json:"usage,omitempty"`
	// StopReason is set for EventDone: end_turn, max_tokens, refusal,
	// max_turns, or a provider-specific reason.
	StopReason string `json:"stop_reason,omitempty"`
	// Error is set for EventError.
	Error string `json:"error,omitempty"`
}

Event is one item of the stream a run emits. Only the fields relevant to Type are set.

type EventType

type EventType string

EventType names what an Event carries.

const (
	// EventText is a delta of the assistant's visible text.
	EventText EventType = "text"
	// EventThinking is a delta of the assistant's summarized reasoning.
	EventThinking EventType = "thinking"
	// EventToolUse announces a complete tool call before it runs.
	EventToolUse EventType = "tool_use"
	// EventToolResult reports a finished (or denied) tool call.
	EventToolResult EventType = "tool_result"
	// EventUsage reports the token usage of one model turn.
	EventUsage EventType = "usage"
	// EventCompaction reports that the provider compacted earlier context.
	EventCompaction EventType = "compaction"
	// EventDone ends a run; StopReason says why.
	EventDone EventType = "done"
	// EventError ends a run with a failure.
	EventError EventType = "error"
)

type FuncTool

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

FuncTool is a Tool built from a function.

func NewTool

func NewTool(name, description string, schema json.RawMessage, readOnly bool, fn func(ctx context.Context, input json.RawMessage) (Result, error)) *FuncTool

NewTool builds a Tool from a function. schema must be a JSON Schema object; nil means an object with no properties.

func (*FuncTool) Description

func (t *FuncTool) Description() string

func (*FuncTool) Execute

func (t *FuncTool) Execute(ctx context.Context, input json.RawMessage) (Result, error)

func (*FuncTool) InputSchema

func (t *FuncTool) InputSchema() json.RawMessage

func (*FuncTool) Name

func (t *FuncTool) Name() string

func (*FuncTool) ReadOnly

func (t *FuncTool) ReadOnly() bool

type Message

type Message struct {
	Role    Role            `json:"role"`
	Content json.RawMessage `json:"content"`
	// Text is the user's prompt or the assistant's visible text.
	Text string `json:"text,omitempty"`
	// ToolCalls are the calls an assistant message requested.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	// ToolResults are the results a user message carries back, with
	// Content truncated for display.
	ToolResults []ToolResult `json:"tool_results,omitempty"`
	CreatedAt   time.Time    `json:"created_at"`
}

Message is one entry of a session's history.

Content is the provider's native content-block JSON and is what goes back to the model verbatim; it is never edited after it is appended. The remaining fields are a display projection filled when the message is created, so a transcript can be rendered without parsing Content.

type MessageInput

type MessageInput struct {
	Content string `json:"content"`
}

MessageInput is the body of SendMessage.

type ModelInfo

type ModelInfo struct {
	// ID is the id to put in a credential's model tag.
	ID string `json:"id"`
	// DisplayName is the provider's name for it, when it has one.
	DisplayName string `json:"display_name,omitempty"`
	// ContextWindow is the context size in tokens, when the listing says.
	ContextWindow int64 `json:"context_window,omitempty"`
}

ModelInfo is one model a provider's endpoint offers.

type ModelLister

type ModelLister interface {
	ListModels(ctx context.Context) ([]ModelInfo, error)
}

ModelLister is implemented by providers that can list the models their endpoint serves, so a form can offer them instead of asking for an id. ListModels must not spend output tokens; a failure is an *CheckError when it can be classified.

type Options

type Options struct {
	// Provider runs each model turn. Required.
	Provider Provider
	// Tools are offered to the model, in this order. Names must be unique
	// and match ToolNamePattern.
	Tools []Tool
	// System is the system prompt. Keep it stable within a session so the
	// provider can cache it.
	System string
	// MaxTurns bounds the model turns of one Run; zero means DefaultMaxTurns.
	MaxTurns int
	// Approve decides whether a requested call runs. nil allows read-only
	// tools and denies everything else.
	Approve func(ctx context.Context, call ToolCall, t Tool) bool
	// MaxToolResultBytes truncates a tool result's content before the model
	// sees it; zero means DefaultMaxToolResultBytes.
	MaxToolResultBytes int
	// Logger receives debug lines about the loop; nil is silent.
	Logger *logger.Logger
}

Options configures an Agent.

type Provider

type Provider interface {
	// Name is the provider id, for example "anthropic".
	Name() string
	// Model is the model the provider will use when TurnInput.Model is empty.
	Model() string
	// UserMessage builds a user message from plain text.
	UserMessage(text string) Message
	// ToolResultMessage builds the user message that returns tool results
	// to the model. All results of one turn go in one message.
	ToolResultMessage(results []ToolResult) Message
	// Turn sends the history and tools to the model and returns the
	// assistant message to append. It calls emit for every streamed event
	// it can report (text, thinking, tool_use, usage, compaction); it must
	// not emit done or error, which belong to the loop. emit may be nil.
	Turn(ctx context.Context, in TurnInput, emit func(Event)) (*Turn, error)
}

Provider runs one model turn. Implementations own the wire format of Message.Content, so a session is bound to the provider that created it (Session.Provider).

type ProviderFactory

type ProviderFactory func(cred Credential) (Provider, error)

ProviderFactory builds a provider from a resolved credential. Hosts keep one factory per Credential.Provider value.

type Registry

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

Registry is a named set of tools in registration order.

func NewRegistry

func NewRegistry(tools ...Tool) *Registry

NewRegistry returns a registry holding tools. It panics on a duplicate or invalid name, which is a programming error at startup; use Add for tools discovered at runtime.

func (*Registry) Add

func (r *Registry) Add(tools ...Tool) error

Add registers tools. On error nothing is added.

func (*Registry) Get

func (r *Registry) Get(name string) (Tool, bool)

Get returns the tool by name.

func (*Registry) List

func (r *Registry) List() []Tool

List returns the tools in registration order.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns the registered names sorted.

type Result

type Result struct {
	// Content is the text the model reads.
	Content string `json:"content"`
	// JSON is optional structured content for callers that can use it
	// (MCP structuredContent). The model sees Content.
	JSON json.RawMessage `json:"json,omitempty"`
	// IsError marks a failed call so the model can recover.
	IsError bool `json:"is_error,omitempty"`
}

Result is what a tool returns to the model.

func ErrorResult

func ErrorResult(format string, args ...any) Result

ErrorResult builds a failed Result from a message.

type Role

type Role string

Role is who a message is from. Tool results travel in a user message, as the model APIs require.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type RunRecord

type RunRecord struct {
	AccountID string `json:"account_id"`
	UserID    string `json:"user_id"`
	SessionID string `json:"session_id"`
	Provider  string `json:"provider"`
	Model     string `json:"model"`
	// Credential is the vault name of the model credential, never its secret.
	Credential string `json:"credential,omitempty"`
	// Turns is the number of model turns; ToolCalls the tools run in them.
	Turns     int   `json:"turns"`
	ToolCalls int   `json:"tool_calls"`
	Usage     Usage `json:"usage"`
	// StopReason is the final stop reason (end_turn, max_turns, refusal,
	// ...); Error is set when the run failed instead, with no secret in it.
	StopReason string        `json:"stop_reason,omitempty"`
	Error      string        `json:"error,omitempty"`
	Started    time.Time     `json:"started"`
	Duration   time.Duration `json:"duration"`
}

RunRecord describes one run, one user message driven to completion, for usage accounting. Service fills it after every run, successful or not, and hands it to ServiceOptions.Usage. Package ai/usage stores and reports it; any other sink works too.

type Service

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

Service is the HTTP surface of the assistant: status, sessions, and the streamed message route. A host mounts it on its router behind its own bearer middleware (Mount); the handlers read the caller from the request context the way every other handler on the platform does.

func NewService

func NewService(o ServiceOptions) (*Service, error)

NewService validates o and returns a Service.

func (*Service) CreateSession

func (s *Service) CreateSession(w http.ResponseWriter, r *http.Request)

CreateSession starts a session against the caller's model credential.

func (*Service) DeleteSession

func (s *Service) DeleteSession(w http.ResponseWriter, r *http.Request)

DeleteSession removes one of the caller's sessions.

func (*Service) GetSession

func (s *Service) GetSession(w http.ResponseWriter, r *http.Request)

GetSession returns one of the caller's sessions with its messages.

func (*Service) ListSessions

func (s *Service) ListSessions(w http.ResponseWriter, r *http.Request)

ListSessions returns the caller's sessions, newest first.

func (*Service) Mount

func (s *Service) Mount(router *mux.Router, prefix string, wrap func(http.HandlerFunc) http.HandlerFunc)

Mount registers the handlers on router under prefix (DefaultMountPrefix when empty), each wrapped with wrap, which is the host's bearer middleware; a nil wrap registers them unwrapped.

func (*Service) Options

func (s *Service) Options() ServiceOptions

Options returns the options the service was built with.

func (*Service) SendMessage

func (s *Service) SendMessage(w http.ResponseWriter, r *http.Request)

SendMessage runs one prompt against a session and streams the run as server-sent events: one frame per Event ("event: {type}" and "data: {json}"), a ": ping" comment every HeartbeatInterval while the model is quiet, ending with done or error. The session is persisted after the run and on every usage event. A second run on a session that is already running answers 409. If the client goes away the run is cancelled and what it produced so far is still persisted. Tool calls an interrupted earlier run left unanswered are answered with error results first (RepairDanglingToolCalls). Building the tool set and the preamble is bounded by SetupTimeout (504 when it fires). A panic in the run ends it with an error event; the session is still persisted and unlocked. Every run that got past resolving the model credential is reported to ServiceOptions.Usage.

func (*Service) Status

func (s *Service) Status(w http.ResponseWriter, r *http.Request)

Status reports whether the caller can use the assistant and with what.

func (*Service) UpdateSession

func (s *Service) UpdateSession(w http.ResponseWriter, r *http.Request)

UpdateSession renames one of the caller's sessions. It takes the session's run lock, so it answers 409 while a run is in progress instead of overwriting what the run persists.

type ServiceOptions

type ServiceOptions struct {
	// Credentials resolves the caller's model, embedding, and MCP server
	// credentials. Required.
	Credentials CredentialResolver
	// Providers builds a Provider per Credential.Provider value; a
	// credential with no provider tag uses ProviderAnthropic. Required.
	Providers map[string]ProviderFactory
	// Sessions persists sessions. Required.
	Sessions SessionStore
	// Tools returns the tools for one caller (API tools, search, memory,
	// remote MCP servers). It is called once per run and once per Status
	// request. A returned tool that implements io.Closer is closed when the
	// run ends, which is how a tool set holding remote connections releases
	// them. ctx is bounded by SetupTimeout and ends when Tools returns, so
	// a tool must not keep it; Execute receives the run's own context.
	// nil offers no tools.
	Tools func(ctx context.Context, c Caller) ([]Tool, error)
	// System returns the system prompt for a caller; it must be stable
	// within a session so the provider can cache it. nil uses
	// DefaultSystem.
	System func(ctx context.Context, c Caller) string
	// Preamble returns text prepended to the user's prompt for this turn
	// (recalled memory, for example); nil or "" prepends nothing. The
	// stored message keeps the user's own text for display.
	Preamble func(ctx context.Context, c Caller, prompt string) string
	// MaxTurns bounds the model turns of one run; zero means
	// DefaultMaxTurns.
	MaxTurns int
	// SetupTimeout bounds Tools, System, and Preamble before a run (and
	// Tools in Status), all of which may reach remote MCP servers or an
	// embedding endpoint while the session is locked. When it fires, or
	// the client goes away first, SendMessage releases the lock and gives
	// up without running. Zero means DefaultSetupTimeout.
	SetupTimeout time.Duration
	// Charts reports that the client renders a fenced code block tagged
	// echarts as an Apache ECharts chart. The default system prompt then
	// tells the model how to draw one (ChartGuidance); a client that shows
	// such a block as code should leave it off.
	Charts bool
	// AllowWrites lets the model run tools that are not read-only. Off by
	// default: the approval policy then denies every write except the
	// tools named in AllowTools.
	AllowWrites bool
	// AllowTools names tools the model may run even when AllowWrites is
	// off. Hosts list the tools whose writes stay inside the caller's own
	// scope, such as the memory tools, so the assistant keeps memory
	// without being allowed to change the tenant's records.
	AllowTools []string
	// Usage receives one RunRecord after every run SendMessage starts,
	// however it ends (done, error, cancellation, a setup failure after the
	// model credential resolved, a panic). Requests rejected before a run
	// (validation, 404, 409, 412) are not recorded. nil records nothing.
	Usage UsageSink
	// Logger receives operational lines; nil is silent.
	Logger *logger.Logger
}

ServiceOptions configures a Service.

type Session

type Session struct {
	ID        string `json:"id"`
	AccountID string `json:"account_id"`
	// UserID is the owner's NATS public key.
	UserID string `json:"user_id"`
	Title  string `json:"title,omitempty"`
	// Provider and Model record what produced Messages; a session is not
	// moved between providers.
	Provider string `json:"provider"`
	Model    string `json:"model"`
	// Credential is the vault name of the model credential in use.
	Credential string    `json:"credential,omitempty"`
	Messages   []Message `json:"messages"`
	// Usage is cumulative over every turn.
	Usage     Usage     `json:"usage"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Session is one conversation. Messages are append-only.

func (*Session) Summary

func (s *Session) Summary() SessionSummary

Summary projects a session for lists.

type SessionInput

type SessionInput struct {
	Title string `json:"title,omitempty"`
	// Credential is the vault name of the model credential; empty picks
	// the first visible one.
	Credential string `json:"credential,omitempty"`
}

SessionInput is the body of CreateSession.

type SessionStore

type SessionStore interface {
	Put(ctx context.Context, s *Session) error
	Get(ctx context.Context, accountID, userID, id string) (*Session, error)
	// List returns the owner's sessions, newest first.
	List(ctx context.Context, accountID, userID string) ([]SessionSummary, error)
	Delete(ctx context.Context, accountID, userID, id string) error
}

SessionStore persists sessions scoped by account and owner.

func NewMemorySessions

func NewMemorySessions() SessionStore

NewMemorySessions returns an in-memory SessionStore for tests. Values are deep-copied on the way in and out so callers cannot share state through the store.

func NewStoreSessions

func NewStoreSessions(st *store.Store) SessionStore

NewStoreSessions returns a SessionStore on a bboxsys store. Sessions are account-scoped records keyed by owner and id, so a user's list is one prefix scan and nothing crosses an account.

type SessionSummary

type SessionSummary struct {
	ID           string    `json:"id"`
	Title        string    `json:"title,omitempty"`
	Provider     string    `json:"provider"`
	Model        string    `json:"model"`
	MessageCount int       `json:"message_count"`
	Usage        Usage     `json:"usage"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

SessionSummary is a session without its messages.

type SessionUpdate

type SessionUpdate struct {
	Title *string `json:"title"`
}

SessionUpdate is the body of UpdateSession. Title is required; an empty one clears the title.

type StaticCredentials

type StaticCredentials struct {
	ModelCredential      *Credential
	EmbeddingCredential  *Credential
	MCPServerCredentials []Credential
}

StaticCredentials is a CredentialResolver for a host without the admin vault: a host agent or a product service that reads an API key from its own configuration. Every caller gets the same credentials. A nil ModelCredential or EmbeddingCredential answers ErrNoCredential, which turns the assistant (or retrieval) off rather than failing.

The fields carry a Credential suffix because a Go type cannot have a field and a method of the same name, and the methods are the CredentialResolver interface.

A name passed to Model or Embedding must match the credential's Name when both are set; an empty name always selects the configured one.

func (StaticCredentials) Embedding

func (s StaticCredentials) Embedding(_ context.Context, _, _, name string) (Credential, error)

Embedding returns the configured embedding credential.

func (StaticCredentials) MCPServers

MCPServers returns a copy of the configured MCP server credentials.

func (StaticCredentials) Model

func (s StaticCredentials) Model(_ context.Context, _, _, name string) (Credential, error)

Model returns the configured model credential.

func (StaticCredentials) Models

Models returns the configured model credential as a list of one, or an empty list.

type Status

type Status struct {
	Enabled bool `json:"enabled"`
	// Model is the credential a session gets when none is named.
	Model *CredentialRef `json:"model"`
	// Models is every model credential the caller may name when creating
	// a session, Model first; just Model when the resolver cannot list.
	Models      []CredentialRef `json:"models"`
	Embedding   *CredentialRef  `json:"embedding"`
	Tools       []string        `json:"tools"`
	MCPServers  []string        `json:"mcp_servers"`
	AllowWrites bool            `json:"allow_writes"`
}

Status is the response of the status route.

type Tool

type Tool interface {
	// Name is the identifier the model calls. It must match ToolNamePattern.
	Name() string
	// Description tells the model what the tool does and when to use it.
	Description() string
	// InputSchema is a JSON Schema object describing the input.
	InputSchema() json.RawMessage
	// ReadOnly reports that the tool observes without changing anything.
	// Read-only calls in one turn may run concurrently and are allowed by
	// the default approval policy; everything else is treated as a write.
	ReadOnly() bool
	// Execute runs the tool. The context carries the Caller (WithCaller)
	// so a tool can act with the user's own identity. An error is reported
	// to the model as a failed tool result, not returned to the caller of
	// the loop; return a Result with IsError for a failure the model should
	// read verbatim.
	Execute(ctx context.Context, input json.RawMessage) (Result, error)
}

Tool is one action the model may request. The loop decides whether to run it (Options.Approve), runs it, and returns Result to the model.

type ToolCall

type ToolCall struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

ToolCall is one tool request from the model.

type ToolResult

type ToolResult struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Result Result `json:"result"`
	// Denied is set when the approval policy refused the call; Result then
	// carries the message the model was given.
	Denied bool `json:"denied,omitempty"`
}

ToolResult is the outcome of one ToolCall.

func DisplayToolResults

func DisplayToolResults(results []ToolResult) []ToolResult

DisplayToolResults returns copies of results with Content cut to DisplayToolResultBytes and JSON dropped, for Message.ToolResults.

type Turn

type Turn struct {
	// Message is the assistant message to append verbatim.
	Message Message
	// Text is the visible text of the message.
	Text string
	// ToolCalls are the calls requested, in order. They normally come with
	// StopReason "tool_use"; a turn cut off by another stop reason
	// (max_tokens, refusal) can still carry calls, which the loop answers
	// with error results instead of running so the history stays valid.
	ToolCalls []ToolCall
	// StopReason is the provider's stop reason: end_turn, tool_use,
	// max_tokens, refusal, or pause_turn.
	StopReason string
	// Usage is this turn's token usage.
	Usage Usage
}

Turn is the result of one model request.

type TurnInput

type TurnInput struct {
	// System is the system prompt. Keep it stable across turns of a
	// session so the provider can cache it.
	System string
	// Messages is the whole history, oldest first, ending with a user
	// message.
	Messages []Message
	// Tools are offered in this order.
	Tools []Tool
	// Model overrides the provider's default when set.
	Model string
	// MaxTokens bounds the output; zero means the provider's default.
	MaxTokens int
}

TurnInput is one model request.

type Usage

type Usage struct {
	InputTokens      int64 `json:"input_tokens"`
	OutputTokens     int64 `json:"output_tokens"`
	CacheReadTokens  int64 `json:"cache_read_tokens"`
	CacheWriteTokens int64 `json:"cache_write_tokens"`
}

Usage counts tokens. Fields are cumulative when read from a Session and per turn when read from an EventUsage.

func (*Usage) Add

func (u *Usage) Add(o Usage)

Add accumulates u into the receiver.

type UsageSink

type UsageSink interface {
	RecordRun(ctx context.Context, r RunRecord)
}

UsageSink receives a RunRecord after every run. RecordRun must not block for long: it is called on the request path after the stream has ended.

Directories

Path Synopsis
Package anthropic is the ai.Provider on the official Anthropic SDK.
Package anthropic is the ai.Provider on the official Anthropic SDK.
Package apitool turns a service's OpenAPI document into ai.Tools that call the service's own http.Handler.
Package apitool turns a service's OpenAPI document into ai.Tools that call the service's own http.Handler.
Package docsearch gives an assistant the product's documentation: the sections of a docsite.Site as two read-only tools, {prefix}docs_search and {prefix}docs_read, and the system prompt guidance that tells the model to look there first and cite what it used.
Package docsearch gives an assistant the product's documentation: the sections of a docsite.Site as two read-only tools, {prefix}docs_search and {prefix}docs_read, and the system prompt guidance that tells the model to look there first and cite what it used.
Package instance hosts one AI assistant with reasonable defaults: its own store, its own retrieval index, memory, tools generated from the host's OpenAPI document, remote MCP servers, the credential test, the documents routes, the MCP endpoint, and usage reporting.
Package instance hosts one AI assistant with reasonable defaults: its own store, its own retrieval index, memory, tools generated from the host's OpenAPI document, remote MCP servers, the credential test, the documents routes, the MCP endpoint, and usage reporting.
natshost
Package natshost serves an AI instance's conversation API over NATS (package natsapi) instead of a listener, for a product service whose assistant is reached through the admin console's gateway (admin.AssistantGateway) rather than by the browser directly.
Package natshost serves an AI instance's conversation API over NATS (package natsapi) instead of a listener, for a product service whose assistant is reached through the admin console's gateway (admin.AssistantGateway) rather than by the browser directly.
serverhost
Package serverhost builds an AI instance for a service on package server.
Package serverhost builds an AI instance for a service on package server.
Package mcp serves ai.Tools to MCP clients over streamable HTTP and consumes remote MCP servers as ai.Tools, on the official Go MCP SDK.
Package mcp serves ai.Tools to MCP clients over streamable HTTP and consumes remote MCP servers as ai.Tools, on the official Go MCP SDK.
Package memory is the assistant's persistent memory, in two layers that are both scoped by account and user.
Package memory is the assistant's persistent memory, in two layers that are both scoped by account and user.
Package openai is the ai.Provider for servers that speak the OpenAI chat completions API: Ollama's /v1 endpoints, llama.cpp's llama-server, vLLM, LM Studio, and gateways in front of them.
Package openai is the ai.Provider for servers that speak the OpenAI chat completions API: Ollama's /v1 endpoints, llama.cpp's llama-server, vLLM, LM Studio, and gateways in front of them.
Package rag is retrieval over an embedded vector store.
Package rag is retrieval over an embedded vector store.
Package usage records what an AI instance spends and reports it to the admin server.
Package usage records what an AI instance spends and reports it to the admin server.

Jump to

Keyboard shortcuts

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