Documentation
¶
Overview ¶
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. Every host of package ai (the admin server, a product service, a host agent, an app) goes through it, so adding an assistant is one call:
inst, err := instance.New(instance.Options{
Name: "inventory_service",
Dir: filepath.Join(root, "ai"),
Credentials: resolver,
OpenAPI: spec,
Handler: srv.Srv.Handler,
ToolPrefix: "inventory_",
Publisher: srv.MessengerClient,
})
inst.Mount(srv.Router, "/api/v1/ai", bearer, requireAdmin)
defer inst.Close()
A service built on package server can use serverhost.New (package ai/instance/serverhost), which fills Name, Handler, Publisher, and Logger from the server. It is a separate package so this one does not link package server into hosts that do not run it (a host agent, a CLI).
Store layout ¶
Everything an instance keeps lives under Dir: {Dir}/ai.db is its own Badger store (sessions, memory notes, usage records and their outbox) and {Dir}/index is its retrieval index (documents and remembered facts). No instance writes into another store, so sessions never land in the host's main database (for the admin, never in admin.db). Collections of the earlier layout, where the index was Dir itself, are moved into {Dir}/index the first time New finds no index there.
Credentials ¶
Credentials resolves the caller's model, embedding, and MCP server credentials. The admin server reads them from its vault (admin.NewAICredentialResolver). A host without the vault, a host agent or a product that reads a key from its own configuration, uses ai.StaticCredentials, or a resolver that asks the admin server over natsapi (GET /api/v1/apitokens with the agent's own JWT as the bearer).
Usage reporting ¶
Every instance records each run in its own store for 30 days (usage.DefaultRetention) and, when a Publisher is set (normally the host's *messenger.Client), publishes it on sys.ai.usage.{Name} and a heartbeat with running totals every 60 s on sys.ai.heartbeat.{Name}. Records that could not be published wait in an outbox and are retried with each heartbeat. The admin server's collectors subscribe to sys.ai.> in every account; the admin's own instance hands its records to the collector store in-process through Local instead.
Index ¶
- Constants
- Variables
- func CloseTools(tools []ai.Tool)
- func ExcludePathSegments(segments ...string) func(path string) bool
- func PathHasPrefix(path, prefix string) bool
- func PathMatches(path, template string) bool
- func PlatformVersion() string
- func Redact(msg, secret string) string
- func RouteTools(o RouteToolsOptions) (spec []byte, include func(method, path string) bool, err error)
- type CheckInput
- type CheckResult
- type Document
- type Instance
- func (i *Instance) APITools() []ai.Tool
- func (i *Instance) AddDocuments(w http.ResponseWriter, r *http.Request)
- func (i *Instance) Close() error
- func (i *Instance) Index() *rag.Index
- func (i *Instance) ListModels(w http.ResponseWriter, r *http.Request)
- func (i *Instance) Mount(r *mux.Router, prefix string, ...)
- func (i *Instance) Options() Options
- func (i *Instance) RequestTool() ai.Tool
- func (i *Instance) SearchDocuments(w http.ResponseWriter, r *http.Request)
- func (i *Instance) ServeMCP(w http.ResponseWriter, r *http.Request)
- func (i *Instance) Service() *ai.Service
- func (i *Instance) Store() *store.Store
- func (i *Instance) TestCredential(w http.ResponseWriter, r *http.Request)
- func (i *Instance) Tools(ctx context.Context, c ai.Caller) ([]ai.Tool, error)
- func (i *Instance) Usage() *usage.Recorder
- type ModelsInput
- type ModelsResult
- type Options
- type RouteOperation
- type RouteToolsOptions
- type SearchResult
Constants ¶
const ( // StoreName is the instance store's directory under Dir. StoreName = "ai.db" // IndexName is the retrieval index's directory under Dir. IndexName = "index" // MCPPath is where Mount serves the MCP endpoint. Clients send the // account as the accountID query parameter (the ID middleware reads it // there) and the user's bearer in the Authorization header. MCPPath = "/mcp" // DocumentsPurpose is the rag collection purpose documents are // ingested into. DocumentsPurpose = "documents" // MaxDocumentsBody bounds one ingestion request. MaxDocumentsBody = 16 << 20 // MCPConnectTimeout bounds connecting to one remote MCP server and // listing its tools while a tool set is built. MCPConnectTimeout = 15 * time.Second // CheckTimeout bounds one credential test, so a dead endpoint answers // in seconds instead of holding the request. CheckTimeout = 20 * time.Second // PlatformModule is the module whose version is reported by default. PlatformModule = "github.com/bboxsys/platform" )
Variables ¶
var DefaultExcludedSegments = []string{"events", "stream", "realtime", "upload", "grpc"}
DefaultExcludedSegments are the path segments RouteTools leaves out of the tool surface when Exclude is nil: streams never end, and uploads and raw protocol proxies are not something a model should drive. A product extends the list with its own (credential exports, arbitrary proxies) through ExcludePathSegments.
Functions ¶
func CloseTools ¶
CloseTools closes every tool that implements io.Closer.
func ExcludePathSegments ¶
ExcludePathSegments returns an Exclude function that rejects every path containing one of the segments.
func PathHasPrefix ¶
PathHasPrefix reports whether path (a template or a concrete path) starts with every segment of prefix, where a "*" or "{name}" segment of prefix matches any one segment. It is the building block of a ToolFilter deny list.
func PathMatches ¶
PathMatches reports whether path matches the template exactly.
func PlatformVersion ¶
func PlatformVersion() string
PlatformVersion is the platform module's version in this binary's build information ("(devel)" in a workspace build), or "".
func Redact ¶
Redact removes the secret from a message in case an upstream library echoed it, so a failure can be shown in the browser safely. Secrets shorter than eight bytes are left alone (they would match too much).
func RouteTools ¶
func RouteTools(o RouteToolsOptions) (spec []byte, include func(method, path string) bool, err error)
RouteTools derives an OpenAPI document and an Include filter from the routes a router has registered under Root, so a service exposes its API to the assistant without maintaining a second description of it. Pass the document as Options.OpenAPI and the filter as Options.ToolFilter; the filter is what keeps the generic request tool on the same surface as the generated tools. Streaming routes, uploads and wildcard templates (gorilla patterns such as {path:.*}) are left out; the service admits the specific operations behind a wildcard with Admit.
Types ¶
type CheckInput ¶
CheckInput is the body of POST {prefix}/credentials/test. Kind is the credential's resource type; the name is resolved like every other use of a credential (for the vault resolver, the caller's own first and then the account's).
type CheckResult ¶
type CheckResult struct {
OK bool `json:"ok"`
Name string `json:"name"`
Kind string `json:"kind"`
LatencyMS int64 `json:"latency_ms"`
// Message is a one-line summary for a toast.
Message string `json:"message"`
// ErrorKind is set on failure: auth, not_found, unreachable, rejected,
// or unsupported.
ErrorKind string `json:"error_kind,omitempty"`
ai.CheckResult
// Dimensions is the embedding vector size, for an embedding credential.
Dimensions int `json:"dimensions,omitempty"`
// Tools is the number of tools a remote MCP server lists.
Tools int `json:"tools,omitempty"`
}
CheckResult is the answer. A failed test is a 200 with OK false: the request succeeded, the credential did not.
type Document ¶
type Document struct {
ID string `json:"id"`
Content string `json:"content"`
Metadata map[string]string `json:"metadata"`
}
Document is one document to ingest.
type Instance ¶
type Instance struct {
// contains filtered or unexported fields
}
Instance is one hosted assistant.
func New ¶
New opens the instance's store and index and builds its service, tools, and usage recorder, which it starts.
func (*Instance) AddDocuments ¶
func (i *Instance) AddDocuments(w http.ResponseWriter, r *http.Request)
AddDocuments ingests documents into the account's collection: POST {prefix}/documents {documents: [{id, content, metadata}]}. Answers 413 when the body exceeds MaxDocumentsBody and 412 when the caller has no embedding credential.
func (*Instance) Close ¶
Close stops the usage recorder (sending a final heartbeat) and closes the index and the store. It is idempotent.
func (*Instance) ListModels ¶
func (i *Instance) ListModels(w http.ResponseWriter, r *http.Request)
ListModels answers the models a provider's endpoint offers, for the credential form to pick from instead of asking for an id. It builds the provider the way a session would, from the body or the saved credential, and needs a provider that implements ai.ModelLister; the secret never appears in the answer.
func (*Instance) Mount ¶
func (i *Instance) Mount(r *mux.Router, prefix string, bearer, requireAdmin func(http.HandlerFunc) http.HandlerFunc)
Mount registers the instance's routes on r:
{prefix}/status, /sessions, ... ai.Service routes, bearer
POST {prefix}/documents AddDocuments, requireAdmin
GET {prefix}/documents/search SearchDocuments, bearer
POST {prefix}/credentials/test TestCredential, bearer
POST {prefix}/credentials/models ListModels, bearer
MCPPath ServeMCP, bearer
prefix "" means ai.DefaultMountPrefix. bearer is the host's bearer middleware (it must put the caller's account and user in the context the way the platform's auth does); requireAdmin wraps the administrator-only route and defaults to bearer when nil. A nil bearer registers the routes unwrapped, which only suits tests. Every route also gets a fresh apitool.WithRunState, so the API tools' failure guard is scoped to the request that starts the run. Mount once per instance.
func (*Instance) RequestTool ¶
RequestTool returns the generic api_request tool, or nil without an OpenAPI document.
func (*Instance) SearchDocuments ¶
func (i *Instance) SearchDocuments(w http.ResponseWriter, r *http.Request)
SearchDocuments queries the account's collection: GET {prefix}/documents/search?q=&n=. Answers 412 when the caller has no embedding credential.
func (*Instance) ServeMCP ¶
func (i *Instance) ServeMCP(w http.ResponseWriter, r *http.Request)
ServeMCP serves the MCP endpoint: the caller's tool set is built from the request, placed in the context with the caller, served, and closed when the request ends. An MCP client applies its own approval, so the assistant's write policy is applied here instead: without AllowWrites only read-only tools and the memory tools are served.
func (*Instance) TestCredential ¶
func (i *Instance) TestCredential(w http.ResponseWriter, r *http.Request)
TestCredential checks that a credential works, without running the assistant: a model credential reads its model from the provider (no tokens spent), an embedding credential embeds one short string, and an MCP server is connected and its tools listed. The secret never appears in the answer.
func (*Instance) Tools ¶
Tools builds the caller's tool set: the generated API tools, the generic request tool, the host's own tools (Options.Tools) and the documentation tools (Options.Docs), the memory notes tool, and, when the caller has an embedding credential, document search plus remember and recall over the index. Every remote MCP server credential visible to the caller is connected and its tools added; a server that cannot be reached within MCPConnectTimeout is logged and skipped. Credentials repeating a name already seen are skipped (a vault resolver lists the user's own before the account's, so the user's wins), as is any remote tool whose name is already taken, so one misconfigured server cannot break the whole set. A server's readOnlyHint is trusted only when its credential carries ai.TagMCPTrustReadOnly = "true". The returned remote tools implement io.Closer; CloseTools releases them.
type ModelsInput ¶
type ModelsInput struct {
Provider string `json:"provider"`
Endpoint string `json:"endpoint"`
Token string `json:"token"`
Name string `json:"name"`
}
ModelsInput is the body of POST {prefix}/credentials/models: the provider and endpoint a form holds, with either the key typed into it (Token) or the name of a saved credential whose stored key, and endpoint when Endpoint is empty, are used instead. Nothing typed is stored.
type ModelsResult ¶
type ModelsResult struct {
OK bool `json:"ok"`
Provider string `json:"provider"`
Models []ai.ModelInfo `json:"models"`
Message string `json:"message,omitempty"`
ErrorKind string `json:"error_kind,omitempty"`
}
ModelsResult is the answer: the models the endpoint serves, or why it could not say (a 200 with OK false, as for a credential test).
type Options ¶
type Options struct {
// Name names the instance; it is the last token of the usage subjects
// and the MCP server name, so it must match [A-Za-z0-9_-]+. Required,
// for example "admin_service".
Name string
// Service is the component shown in usage; default Name.
Service string
// Dir holds the instance's own store ({Dir}/ai.db) and index
// ({Dir}/index). Required.
Dir string
// Credentials resolves the caller's credentials. Required.
Credentials ai.CredentialResolver
// Providers maps ai.Credential.Provider values to factories. Default:
// anthropic (with Effort and server-side fallbacks), ollama, and
// openai_compat (both ai/openai, with Effort).
Providers map[string]ai.ProviderFactory
// Effort is passed to the default factories only; "" lets each
// credential's ai_effort tag apply.
Effort string
// System overrides the default system prompt when set.
System string
// Instructions are appended to the system prompt (the default or
// System), one block each: a host's standing guidance that does not
// replace the platform rules. Optional.
Instructions []string
// Docs are the documentation corpora the assistant can search and
// cite: each adds its {ToolPrefix}docs_search and docs_read tools and
// its guidance to the system prompt. The host builds, starts and
// closes them (after the instance). Optional.
Docs []*docsearch.Corpus
// Charts reports that the client renders echarts fenced blocks as
// charts; the default system prompt then says how to draw one. See
// ai.ServiceOptions.Charts.
Charts bool
// MaxTurns bounds the model turns of one run; zero means the loop's
// default.
MaxTurns int
// SetupTimeout bounds building a run's tool set and preamble; zero
// means ai.DefaultSetupTimeout.
SetupTimeout time.Duration
// AllowWrites lets the model run tools that are not read-only. Off by
// default; the memory tools, which write only to the caller's own notes
// and facts, are allowed either way. It also governs MCPPath, whose
// client applies its own approval: without it only read-only tools and
// the memory tools are served there.
AllowWrites bool
// OpenAPI is the host's OpenAPI document; with Handler it yields one
// tool per operation plus a generic {ToolPrefix}api_request tool, each
// dispatching through Handler with the caller's bearer. Optional.
OpenAPI []byte
// Handler is the host's full handler chain (ID middleware included).
Handler http.Handler
// ToolPrefix prefixes every generated tool name, for example "admin_".
ToolPrefix string
// ToolFilter rejects operations (method upper case, path template or
// concrete path) that must never be tools. The instance's own routes
// (the mount prefix, ai.DefaultMountPrefix, and MCPPath) are always
// rejected on top of it.
ToolFilter func(method, path string) bool
// MaxToolResponseBytes is the response budget of every API tool call
// (apitool.Bounded): a larger response is replaced by a complete
// problem document naming a compact query, never a truncated object
// list. Zero means apitool.DefaultMaxResponseBytes (32 KiB), which
// stays below the agent's tool-result limit with the envelope added.
MaxToolResponseBytes int
// ToolGuidance returns, for a request path, the compact or paginated
// query the model should use when a response overflowed or an
// identical read keeps failing. Nil means apitool.DefaultGuidance; a
// product names its own summary routes here.
ToolGuidance func(path string) string
// Tools returns additional tools for one caller, built per run after
// the generated API tools and before memory, search and the remote MCP
// servers: a host whose tools are not an HTTP API (the admin's "All"
// assistant delegating to the service assistants, for example) supplies
// them here. A tool whose name is already taken is skipped and logged.
// Optional.
Tools func(ctx context.Context, c ai.Caller) ([]ai.Tool, error)
// Publisher sends usage records and heartbeats over NATS, usually the
// host's *messenger.Client. Optional; without it records stay in the
// instance's outbox.
Publisher usage.Publisher
// Local receives usage in-process, for a host that is itself the
// collector (the admin's AIUsageStore). Optional.
Local usage.Local
// UsageRetention is how long the instance keeps its own records; zero
// means usage.DefaultRetention (30 days).
UsageRetention time.Duration
// HeartbeatInterval is the usage heartbeat period; zero means
// usage.DefaultHeartbeatInterval (60 s).
HeartbeatInterval time.Duration
// Version is reported in heartbeats; empty means the platform module's
// build version.
Version string
// Logger receives operational lines; nil logs as ai/{Name}.
Logger *logger.Logger
}
Options configures an Instance.
type RouteOperation ¶
RouteOperation names operations admitted explicitly: routes the router serves behind a wildcard template (a proxy), which the walk skips because a wildcard is never offered to the model as a whole.
type RouteToolsOptions ¶
type RouteToolsOptions struct {
// Router is the service's router after every route is registered.
// Required.
Router *mux.Router
// Root is the API root the tools are derived from, for example
// "/api/v1/inventory"; only routes under it are considered. Required.
Root string
// Title is the document's info.title; default Root.
Title string
// Exclude rejects a path template from the tool surface. Nil means
// ExcludePathSegments(DefaultExcludedSegments...). It applies to the
// generated tools and the generic request tool alike.
Exclude func(path string) bool
// Queries names the query parameters an operation accepts when no
// contract describes it (the walk cannot see them). Optional; a
// contract's declared parameters always win.
Queries func(path string) []string
// SideEffectGET marks GET operations that change state (a refresh, a
// parse, a redirect that creates something), which are then published
// with x-ai-read-only: false so they need write approval. Optional.
SideEffectGET func(path string) bool
// Admit adds operations the walk does not produce. Optional.
Admit []RouteOperation
// Contracts are OpenAPI documents whose operations replace the
// inferred ones: declared parameters, schemas and descriptions. A
// contract naming an operation that is neither registered under Root
// nor admitted is an error, so a document cannot widen the surface.
Contracts [][]byte
}
RouteToolsOptions configures RouteTools.
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |
|
Package serverhost builds an AI instance for a service on package server.
|
Package serverhost builds an AI instance for a service on package server. |