inference

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 66 Imported by: 1 module, 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 inference is the data-plane HTTP API: /v1/* and /healthz.

Mount(r, deps) wires huma+chi onto an existing chi router and returns the huma.API. The package owns its huma.Config; main.go constructs Deps and calls Mount.

Index

Constants

View Source
const (
	// HeaderOrigin is "relay" when relay minted the response (auth,
	// routing, rate limit, admission — or a relay verdict about an upstream
	// failure), "upstream" when the provider's bytes passed through.
	HeaderOrigin = "X-Wr-Origin"
	// HeaderUpstreamStatus carries the provider's HTTP status on
	// relay-minted errors that report an upstream failure, so the two
	// layers' statuses are never conflated.
	HeaderUpstreamStatus = "X-Wr-Upstream-Status"
)

Error-attribution headers. Relay's error envelope and an OpenAI-shaped upstream's envelope are indistinguishable by body alone, so every response declares which side produced it: a 401 with origin "relay" means your relay key; origin "upstream" means the provider rejected the upstream key.

View Source
const (
	CredentialKey   = "key"
	CredentialToken = "token"
)

Credential kinds a Principal can be authenticated by.

View Source
const MaxAttributionValueBytes = 256

MaxAttributionValueBytes caps one recorded attribution value. The values ride into every usage event, so a caller cannot inflate the record.

Variables

View Source
var (
	ErrInvalidProxyMode   = errors.New("inference: invalid X-WR-Proxy-Mode value")
	ErrMissingUpstreamKey = errors.New("inference: proxy mode requires Authorization: Bearer <upstream-key>")
)

Sentinel errors returned by Classify. The middleware maps these to 400.

View Source
var ErrTokensDisabled = errors.New("inference: tokens are not enabled")

ErrTokensDisabled means no signing key is configured, so no token can be trusted.

Functions

func AdmitCaller added in v0.20.0

func AdmitCaller(ctx context.Context, w http.ResponseWriter) *plan.Refusal

AdmitCaller refuses the authenticated caller of ctx exactly when its lane refuses an inference request: a closed account, a lane its credential may not use, a disabled policy, account, team, project or principal on any rung. For endpoints behind AuthenticateMiddleware, which route nothing but must not take a refused caller's report either. Returns the refusal after writing the answer inference gives it; nil for an admitted or anonymous caller.

func AuthenticateMiddleware added in v0.10.3

func AuthenticateMiddleware(a *Auth) func(http.Handler) http.Handler

AuthenticateMiddleware resolves who the caller is exactly as PrincipalMiddleware does, but refuses nothing its caller ladder would: for endpoints that record what a caller reports and route nothing, where any valid credential is a valid reporter. A credential is always required.

func ClassifyMiddleware

func ClassifyMiddleware() func(http.Handler) http.Handler

ClassifyMiddleware runs Classify once per request and stashes the result on ctx. Shape-invalid requests get a 400 envelope; everything else falls through to the next handler. Gating (Settings.ProxyMode flags in PrincipalMiddleware, unknown-slug rejection in the proxy handler) lives downstream so this middleware stays snapshot-free.

func CountRenameDrops added in v0.21.0

func CountRenameDrops(modelName string, dropped []string)

CountRenameDrops records the drop metric for the keys a hop's renames dropped from the body it was sent (pipeline.Result.BodyDropped).

func Dispatch

func Dispatch(d Deps, w http.ResponseWriter, r *http.Request, in DispatchInput)

Dispatch runs the shape-agnostic flow. Called from route handlers after a minimal parse to extract ModelName + Stream.

func ForwardUpstreamHeaders

func ForwardUpstreamHeaders(dst, src http.Header)

ForwardUpstreamHeaders copies src → dst, dropping hop-by-hop, and stamps the response origin as "upstream" (Set, not Add — an upstream must not be able to spoof a relay-origin claim). The caller is responsible for any further adjustments (e.g. clearing Content-Length when the body size will change between upstream and client). Exported so adapter packages can use it from their own cross-shape handlers.

func HopBody added in v0.21.0

func HopBody(hop *plan.RouteHop, shape adapters.Name, body []byte) ([]byte, []string)

HopBody is pipeline.Request.HopBody for every inference path: body renamed by hop's host for shape, with the keys dropped because the caller also sent their new name; body itself, untouched and without allocating, when the host renames nothing in shape.

func KeyFromContext added in v0.10.0

func KeyFromContext(ctx context.Context) *key.Key

KeyFromContext returns the authenticated relay key from ctx, or nil if no key middleware fired.

func LaneMiddleware added in v0.20.0

func LaneMiddleware(domain string) func(http.Handler) http.Handler

LaneMiddleware reads the account a request asks to run in, by precedence the X-WR-Account header, a /a/{account}/ path prefix, then the host's first label under domain (RELAY_ACCOUNT_DOMAIN; empty turns host selection off). The prefix is cut before routing, so every inference route serves under it unchanged. The credential middleware resolves the account against the caller's plans.

func Mount

func Mount(r chi.Router, d Deps) huma.API

Mount installs the data-plane huma API on r and registers all operations. Returns the huma.API so the caller can attach test-only operations.

func PayloadLoggingOf added in v0.20.0

func PayloadLoggingOf(ctx context.Context) account.PayloadLogging

PayloadLoggingOf returns the payload-logging say of the request's lane: the nearest account on its ladder that sets one, "" when none does or no credential was presented.

func PrincipalMiddleware added in v0.10.0

func PrincipalMiddleware(a *Auth) func(http.Handler) http.Handler

PrincipalMiddleware authenticates the inbound credential according to the request's Mode classification (set by ClassifyMiddleware upstream) and resolves who it acts as:

  • ModeNormal — credential is required; lookup must succeed.
  • ModeProxyAuthed — credential is required; lookup must succeed and the principal must be allowed to bring its own upstream key.
  • ModeProxyAnonymous — no credential; neither a *Key nor a *Principal is stashed on ctx.

Both proxy modes are also refused here when the proxy-mode setting does not admit them, so a refused request never has its body read, takes an admission slot or leaves a usage record.

The bearer is either a key or a relay-minted token, told apart by shape (looksLikeToken); both resolve to the same Principal and only the lookup differs. Every read is against the published plans and the in-memory revoked-token set, re-read per request so admin edits take effect within the NOTIFY debounce window.

func ReadinessMiddleware

func ReadinessMiddleware(cat *appcatalog.Catalog) func(http.Handler) http.Handler

ReadinessMiddleware short-circuits inbound /v1/* requests with 503 until the catalog has built its first snapshot. Until then, lookups against the empty zero-value snapshot would look identical to a legitimately empty catalog — better to refuse traffic explicitly so the caller retries instead of seeing a misleading 404. /healthz is mounted outside this middleware so liveness/readiness probes can still report. The refusal closes the connection so a keep-alive client re-dials a ready pod, and is logged sampled rather than per request.

func SnapshotFrom added in v0.10.0

func SnapshotFrom(ctx context.Context) *appcatalog.Snapshot

SnapshotFrom returns the catalog view this request was authenticated against, or nil when no credential middleware ran (anonymous proxy). Downstream phases read it rather than cat.Current() so a reload landing mid-request cannot split one request across two snapshots.

func SplitSSEChunks

func SplitSSEChunks(data []byte, atEOF bool) (advance int, token []byte, err error)

SplitSSEChunks is exported so adapter packages can use the same SSE chunking logic in their cross-shape stream handlers.

func StampPrincipal added in v0.10.3

func StampPrincipal(ctx context.Context, lc *lifecycle.Context)

StampPrincipal copies the authenticated caller's key hash, principal and tenancy onto lc, for handlers outside Dispatch that record events against the caller. A request with no principal leaves lc untouched.

func UpstreamBody added in v0.11.7

func UpstreamBody(req *ParsedRequest, upstreamModel string, m *model.Model, paramPaths map[string]string) ([]byte, []string)

UpstreamBody returns req's body with its model set to upstreamModel and the params m declares unsupported removed at their paramPaths locations, recording the per-param drop metric, so capability gating holds on every path to Pipeline.Run. Host renames are per hop: set HopBody on the request.

func WithClassification

func WithClassification(ctx context.Context, c Classification) context.Context

WithClassification returns a child ctx carrying c.

func WithSnapshot added in v0.10.0

func WithSnapshot(ctx context.Context, snap *appcatalog.Snapshot) context.Context

WithSnapshot pins snap as the catalog view for everything downstream of ctx, for callers outside the middleware chain; the chain and the WebSocket per-frame path set it on the request state directly.

func WriteAPIError

func WriteAPIError(w http.ResponseWriter, status int, errType, code, msg string, attrs ...any)

WriteAPIError emits relay's error envelope. Exported so per-shape route packages (app/adapters/<name>/routes.go) can use it without depending on shape-specific helpers. Extra slog attrs are attached to the warning log only — never to the client envelope.

Types

type Auth added in v0.20.0

type Auth struct {
	Catalog *appcatalog.Catalog
	Plans   PlanSource
	Revoked *revocation.Set
	Tokens  *TokenVerifier
	// Lifecycle receives the usage row of a request refused once its credential is known; nil records none.
	Lifecycle *lifecycle.Registry
}

Auth is what the credential middleware reads: the published plans, the revoked-token set, the token verifier, and the catalog for the proxy-mode setting.

func (*Auth) Recheck added in v0.20.0

func (a *Auth) Recheck(keyHash, userID, projectID, jti string, tokenVer int, tokenExp int64, laneID string, now time.Time) (*Principal, error)

Recheck resolves a credential admitted earlier (the submitter of a queued batch item) against the current plans: a key by the hash it presented, a token by its user's version, its expiry, the revoked set and the project it acts in. laneID is the account the submission switched into, empty for the credential's default. The error says why it no longer authenticates; the caller ladder's own refusal (a disabled team among them) is the caller's to check.

type Classification

type Classification struct {
	Mode Mode
	// Key is the raw inbound key token. Empty in
	// ModeProxyAnonymous. In ModeNormal pulled from X-WR-API-Key first,
	// then Authorization (Bearer). In ModeProxyAuthed pulled from
	// X-WR-API-Key only.
	Key string
	// UpstreamAuth is the verbatim Authorization header value (including
	// the "Bearer " prefix when present) supplied by the caller for proxy
	// mode. The proxy forwarder re-attaches it on the outbound request.
	// Empty in ModeNormal.
	UpstreamAuth string
	// UpstreamHost is the X-WR-Upstream-Host slug naming a configured
	// Host row. Empty in ModeNormal. Required in proxy mode; the proxy
	// dispatcher rejects missing/unknown values.
	UpstreamHost string
	// ClientIP is the resolved client address — XFF-walked when the peer
	// matches RELAY_TRUSTED_PROXIES, RemoteAddr otherwise.
	ClientIP string
}

Classification carries the result of Classify. Stashed on ctx by the classifier middleware and read by downstream handlers / pipeline / proxy. The classifier is pure — it does not touch the catalog snapshot or any settings; gating decisions happen later.

func ClassificationFrom

func ClassificationFrom(ctx context.Context) Classification

ClassificationFrom returns the mode classification from ctx. The zero Classification (Mode == ModeUnknown) is returned if no classifier ran.

func Classify

func Classify(r *http.Request) (Classification, error)

Classify extracts the mode, credentials, and client IP from r. Pure; no ctx writes, no snapshot reads. Returns an error only for shape- invalid inputs (bad header value, missing upstream key in proxy mode); the caller maps errors to HTTP responses.

type Deps

type Deps struct {
	// Pinger reports backend health for /healthz. Storage satisfies
	// this; tests can pass a stub.
	Pinger Pinger

	// Catalog is the in-memory snapshot used for key auth lookup
	// and the /v1/models listing.
	Catalog *appcatalog.Catalog

	// Tokens verifies relay-minted inference tokens. nil rejects every
	// token bearer, which is the posture when tokens are disabled.
	Tokens *TokenVerifier

	// Plans are the published key, caller and route plans authentication and routing read.
	Plans PlanSource

	// Revoked is the in-memory set of revoked relay-minted tokens. Nil revokes nothing.
	Revoked *revocation.Set

	// Pipeline orchestrates one normal-mode inference request.
	Pipeline *pipeline.Pipeline

	// Proxy orchestrates a proxy-mode (BYO upstream key) request.
	Proxy *proxy.Pipeline

	// Lifecycle is the observer registry. Dispatch uses it to fire a
	// failure post-flight event for requests rejected before a runner is
	// reached (routing / proxy gating / translate errors) — runner-stage
	// failures are fired by the runner. Same registry the runners hold.
	Lifecycle *lifecycle.Registry

	// Adapters keys the wire-protocol implementation by adapters.Name.
	// Handlers look up the binding's Adapter Name here at request time;
	// proxy mode looks up the extractor by inbound endpoint shape.
	Adapters map[adapters.Name]pipeline.Adapter

	// Specs is the generic adapter registry. Dispatch uses it to look up
	// inbound and upstream translators and to determine routing strategy
	// (byte-pass vs canonical cross-shape). Built once at boot and
	// populated from cmd/relay/main.go.
	Specs *adapter.Registry

	// RouteMounters are per-adapter route registration functions. Each
	// adapter (or the generic framework) exposes a MountRoutes function
	// that satisfies RouteMounter; cmd/relay/main.go wires them in.
	RouteMounters []RouteMounter

	// Admission is the in-flight cap. When set, the RouteMounters' routes
	// refuse new requests with their shape's overload answer before reading
	// the body while the cap is reached. Nil installs no such check.
	Admission *httpapi.Admission

	// KVPoolBusy reports whether the shared kv store's connection wait queue is at its bound, where the admission reserve would be refused unsent. When set, the same routes refuse new requests with their shape's overload answer before reading the body while it holds. Nil installs no such check.
	KVPoolBusy func() bool

	// Profiles are the client profiles this deployment serves, registered
	// at the composition root. Nil means none: no /{profile}/ routes, no
	// profile on the request context, behaviour unchanged.
	Profiles *clientprofile.Registry

	// PublicURL is the externally reachable base of this data plane
	// (RELAY_INFERENCE_API_URL). A client document that has to print the
	// endpoint its reader should call needs it; empty means derive it per
	// request from the origin the caller arrived on.
	PublicURL string

	// TokenCalibrator answers the count-tokens endpoint from the ratio relay measured on completed requests, for upstreams with no counter of their own. Nil is safe: those requests fall through to a byte estimate.
	TokenCalibrator *tokencount.Calibrator

	// StreamKeepAlive is how long a streamed response may go without bytes before relay emits the inbound shape's no-op frame itself (RELAY_STREAM_KEEPALIVE_S). Upstreams stay silent through long prompt processing or thinking, and coding-agent clients abort a stream after a few minutes of silence. 0 disables the keepalive.
	StreamKeepAlive time.Duration

	// RequestStreamUsage makes byte-pass ask a streamed upstream for its token usage when the wire shape reports it only on request and the caller did not ask (RELAY_STREAM_USAGE). The extra usage frame is removed before the caller sees it. Without it such streams leave token budgets and usage records at zero.
	RequestStreamUsage bool

	// MaxRequestBytes is the inference body limit the listener enforces (RELAY_MAX_REQUEST_BYTES); a declared Content-Length within it sizes the read buffer (see readRequestBody). 0 means httpmw.DefaultMaxRequestBytes.
	MaxRequestBytes int64

	// ProxyBodyIdle bounds the wait for each read of a proxy-mode request body (RELAY_PROXY_BODY_IDLE_S); a client silent that long gets 408. 0 disables it.
	ProxyBodyIdle time.Duration

	// AccountDomain is the parent domain of the per-account hosts (RELAY_ACCOUNT_DOMAIN): a request to <account-name>.<AccountDomain> runs in that account. Empty turns host selection off; the header and the /a/{account}/ prefix work regardless.
	AccountDomain string

	// TrustEventTime makes Dispatch honor the X-WR-Event-Time header as
	// the usage Event timestamp (RELAY_DEV_TRUST_EVENT_TIME). Dev/replay
	// tooling only; off by default.
	TrustEventTime bool
}

Deps is the typed dependency bundle for the data plane.

func (Deps) Auth added in v0.20.0

func (d Deps) Auth() *Auth

Auth is the credential middleware's view of d.

type DispatchInput

type DispatchInput struct {
	// Inbound is the wire shape the caller spoke (the route's Name).
	Inbound adapters.Name

	// Body is the raw inbound request body, already consumed from r.Body.
	// In proxy mode with ProxyBody set it is only the part held before the
	// forward starts.
	Body []byte

	// Request is Body parsed once by the route, read by every later step
	// instead of the body. Nil when the caller holds only bytes; byte-pass
	// then parses Body itself.
	Request *ParsedRequest

	// ProxyBody forwards a proxy-mode body: Body, then the rest as it
	// streams from the client. Nil means Body is the whole body.
	ProxyBody *scannedBody

	// ModelName is the caller-supplied model identifier extracted by the
	// per-shape minimal parse. Routing resolution uses this.
	ModelName string

	// Stream is the caller-supplied stream flag from the minimal parse.
	// Determines whether the response leg streams chunks or buffers + emits.
	Stream bool
}

DispatchInput is what a per-shape route passes to Dispatch after its own minimal parse. The route knows the inbound shape Name (because it owns the URL); Dispatch handles everything from routing onward.

type Mode

type Mode int

Mode classifies the proxy mode of an inbound inference request.

const (
	ModeUnknown Mode = iota
	// ModeNormal — default; no X-WR-Proxy-Mode; relay key authenticates
	// against a Policy and the upstream key comes from the keypool.
	ModeNormal
	// ModeProxyAuthed — X-WR-Proxy-Mode: Proxy + relay key in X-WR-API-Key
	// + caller-supplied upstream key in Authorization. Logged against the
	// relay key; metered by its policy's rate limit as in ModeNormal, with
	// the inference-api-proxy system rate limit as a further ceiling.
	ModeProxyAuthed
	// ModeProxyAnonymous — X-WR-Proxy-Mode: Proxy + caller-supplied
	// upstream key in Authorization, no relay key. Subject to the
	// inference-api-proxy-anonymous per-IP rate limit. Gated by
	// Settings.ProxyMode.AllowUnauthenticated in PrincipalMiddleware.
	ModeProxyAnonymous
)

type ParsedRequest added in v0.11.7

type ParsedRequest struct {
	// Model is the top-level model, matched case-insensitively as encoding/json does; "" when absent or null.
	Model string

	// Stream reports whether the request selects streaming through the member its shape's RequestKeys name.
	Stream bool
	// contains filtered or unexported fields
}

ParsedRequest is a request body read in one pass: the values relay acts on, and the byte offsets of every top-level member, so a body sent upstream with edits is assembled from the original bytes instead of being decoded and re-encoded. It holds no copy of the body; typical bodies fit the inline member array, about 1 KB.

func ParseRequest added in v0.11.7

func ParseRequest(body []byte) (*ParsedRequest, error)

ParseRequest parses a request body once, refusing what the realtime routes refuse. Its Model may be empty; the caller decides what that means.

func (*ParsedRequest) Body added in v0.11.7

func (p *ParsedRequest) Body() []byte

Body returns the body the request was parsed from.

func (*ParsedRequest) Member added in v0.11.7

func (p *ParsedRequest) Member(key string) []byte

Member returns the raw value of the last top-level member whose key is exactly key (escapes decoded), nil when there is none: what a decode into map[string]json.RawMessage would hold for key.

type Pinger

type Pinger interface {
	Ping(ctx context.Context) error
}

Pinger reports backend health for /healthz. Storage satisfies this via its own Ping method; tests can supply a stub.

type PlanSource added in v0.20.0

type PlanSource interface{ Load() *plan.Root }

PlanSource is where the request path loads the published plans; *plan.Holder implements it.

type Principal added in v0.10.0

type Principal struct {
	UserID, ServiceAccountID     string // exactly one set
	ProjectID, TeamID            string // the lane's scope; empty for a personal or provider account
	CredentialKind, CredentialID string // CredentialKey/CredentialToken; key id or jti
	KeyHash                      string // hash presented; empty for tokens
	Key                          *key.Key
	// Caller is the request's lane with its ladder folded: what it may reach and the counters it must fit.
	Caller *plan.CallerPlan
	// SwitchedLaneID is the account the request asked to run in, by id, so a WebSocket frame or a queued batch item resolves the same lane again; empty when it runs in the credential's default.
	SwitchedLaneID     string
	PassthroughAllowed bool
	PayloadLogging     bool // the credential's own flag; read through CapturesPayload

	// TokenExp/TokenVer are the claims a token credential was admitted
	// under, kept so a long-lived connection can re-check them without the
	// bearer. Zero for a key.
	TokenExp int64
	TokenVer int
	// contains filtered or unexported fields
}

Principal is who the request is acting as, resolved once at the edge so nothing downstream re-derives it. Credential-specific fields (CredentialKind, CredentialID) name the credential presented, not the subject.

func PrincipalFrom added in v0.10.0

func PrincipalFrom(ctx context.Context) *Principal

PrincipalFrom returns the resolved principal from ctx, or nil when the request carried no credential (anonymous proxy mode).

func (*Principal) CapturesPayload added in v0.10.3

func (p *Principal) CapturesPayload() bool

CapturesPayload reports whether this principal's requests have their bodies captured, the same answer on every runner: the nearest account on the lane's ladder that sets payloadLogging decides, else the credential's own opt-in. Nil (anonymous proxy traffic) carries no opt-in and captures nothing.

func (*Principal) Policy added in v0.10.0

func (p *Principal) Policy() *policy.Policy

Policy returns the innermost caller policy, nil when no caller rung binds one. Nil-safe so error paths can call it unguarded.

func (*Principal) PolicyID added in v0.10.0

func (p *Principal) PolicyID() string

PolicyID returns the innermost caller policy's id, or "".

type RouteMounter

type RouteMounter = func(api huma.API, d Deps, mw huma.Middlewares)

RouteMounter is what an adapter package exposes to mount its own inbound HTTP surface. Each adapter (openai, anthropic, ...) provides a MountRoutes(api, deps, mw) function matching this signature.

func MountRegistry

func MountRegistry(reg *adapter.Registry) RouteMounter

MountRegistry returns a RouteMounter that registers one POST route per InboundPath across all specs in reg. Each route performs a minimal JSON parse (model + stream), then calls Dispatch with the spec's Name as the inbound shape.

This is the generic route mounter that replaces per-shape MountRoutes functions. The composition root calls it once with the populated registry.

type TokenVerifier added in v0.10.0

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

TokenVerifier holds the public half of the token signing key, plus the one rotated out, so a rotation is not a global logout. The composition root swaps the keys in when the auth:tokens section changes; a nil verifier (or one with no key) rejects every token, which is what a deployment with tokens disabled wants.

func (*TokenVerifier) PreviousPublicKey added in v0.10.0

func (v *TokenVerifier) PreviousPublicKey() ed25519.PublicKey

PreviousPublicKey returns the key a rotation retired, or nil.

func (*TokenVerifier) PublicKey added in v0.10.0

func (v *TokenVerifier) PublicKey() ed25519.PublicKey

PublicKey returns the key tokens are currently minted under, or nil.

func (*TokenVerifier) SetCacheSize added in v0.10.0

func (v *TokenVerifier) SetCacheSize(n int)

SetCacheSize bounds the verified-claims cache. 0 turns it off.

func (*TokenVerifier) SetKey added in v0.10.0

func (v *TokenVerifier) SetKey(pub ed25519.PublicKey)

SetKey installs the verification key, demoting the one it replaces so tokens already minted under it keep verifying. A nil key disables tokens and drops both.

func (*TokenVerifier) SetKeys added in v0.10.0

func (v *TokenVerifier) SetKeys(current, previous ed25519.PublicKey)

SetKeys installs the current key alongside the one rotation replaced, so a pod that did not perform the rotation still verifies tokens minted before it. A nil current key disables tokens and drops both.

func (*TokenVerifier) Verify added in v0.10.0

func (v *TokenVerifier) Verify(token string) (crypto.TokenClaims, error)

Verify checks the signature and returns the claims. Claim policy (expiry, issuer, version) is the caller's.

Jump to

Keyboard shortcuts

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