Documentation
¶
Overview ¶
Package router picks a rule for a request and walks its model chain.
Index ¶
- Constants
- Variables
- func ApplyPlacement(chain []*proxydb.Model, placement string) ([]*proxydb.Model, error)
- func CanaryKey(attrs map[string]string) string
- func Execute(ctx context.Context, th Throttle, r Request) (*llm.Response, *proxydb.Model, error)
- func ExecuteMedia(ctx context.Context, th Throttle, r MediaRequest) (*proxydb.Model, error)
- func ExecuteStream(ctx context.Context, th Throttle, r Request, ...) (*proxydb.Model, error)
- func FilterChain(snap *registry.Snapshot, use []string, apiKeyID, effort string, ...) ([]*proxydb.Model, error)
- func IsNodeModel(m *proxydb.Model) bool
- func Kept(cands []Candidate) ([]*proxydb.Model, error)
- func Match(snap *registry.Snapshot, effort string, attrs map[string]string) *proxydb.Rule
- func MatchModality(snap *registry.Snapshot, effort, modalityKey, modality string, ...) *proxydb.Rule
- func NormalizePlacement(p string) string
- func ResolveBatchModel(ctx context.Context, snap *registry.Snapshot, th Throttle, use []string, ...) (*proxydb.Model, error)
- func ResolveChain(rule *proxydb.Rule, hashKey string) []string
- func SanitizeAttributes(attrs map[string]string) map[string]string
- func ToStatus(err error) error
- func UserID(attributes map[string]string, keyName string) string
- type Candidate
- type ChainExhausted
- type CircuitBreaker
- type Cooldown
- type CoolingDown
- type MediaRequest
- type NoopThrottle
- func (NoopThrottle) AllowRPM(context.Context, string, string, *proxydb.Model) bool
- func (NoopThrottle) ChargeDailyBudget(context.Context, *proxydb.Model, string, string, string, llm.TokensUsage)
- func (NoopThrottle) CheckDailyBudget(context.Context, *proxydb.Model, string, string, string) string
- func (NoopThrottle) Reserve(context.Context, *proxydb.Model, string, string, string, int64, int64) (*Reservation, string)
- func (NoopThrottle) Settle(*Reservation, llm.TokensUsage)
- type Request
- type Reservation
- type SchemaFailure
- type SpendHold
- type Throttle
Constants ¶
const ( DropNotFound = "not_found" DropEffort = "effort" DropCapability = "capability" DropNoVendorKey = "no_vendor_key" )
Why ExplainChain drops a model of a rule's chain.
const ( PlacementNodesFirst = "nodes_first" PlacementNodesOnly = "nodes_only" PlacementCloudFirst = "cloud_first" PlacementCloudOnly = "cloud_only" // Route modes returned in GenerateTextResponse.RouteMode. RouteModeDirect = "direct" RouteModeOverride = "override" RouteModeAutoJudge = "auto-judge" RouteModeAutoDefault = "auto-default" RouteModeAutoEffort = "auto-effort" )
Placement policy constants defining infrastructure locality preferences.
const InsufficientQuota = "insufficient_quota"
InsufficientQuota is the OpenAI-compatible code for an exhausted spend limit.
Variables ¶
var ( ErrNotConfigured = errors.New("not_configured") ErrNoCapableModel = errors.New("no_capable_model") ErrNoVendorKey = errors.New("no_vendor_key") ErrModelAccessDenied = errors.New("model_access_denied") )
Sentinels for the documented error contract (see proto/ktms/v1/gateway.proto).
Functions ¶
func ApplyPlacement ¶
ApplyPlacement reorders or prunes candidates according to the placement policy.
func CanaryKey ¶
CanaryKey extracts the stickiness key for canary routing from request attributes. When canary_mode is "random", stickiness is disabled. Otherwise, it checks for an explicit "canary_key", falling back to "user_id".
func Execute ¶
Execute walks the chain: throttle-admit, call with per-model retries on retryable errors, settle budgets. Terminal vendor errors stop the chain — a schema rejection would fail identically on every model.
func ExecuteMedia ¶
ExecuteMedia walks the chain for a non-text call. A retryable failure — which includes a TTS reply that carried no audio — moves to the next model, so a vendor that answers without speech degrades to another rather than failing.
func ExecuteStream ¶
func ExecuteStream(ctx context.Context, th Throttle, r Request, onChunk func(*proxydb.Model, llm.StreamChunk) error) (*proxydb.Model, error)
ExecuteStream walks the model chain for streaming requests. Pre-stream failures fallback to the next model; once the first chunk is emitted, the stream locks.
func FilterChain ¶
func FilterChain(snap *registry.Snapshot, use []string, apiKeyID, effort string, needsGoogleSearch bool, requireCapabilities ...string) ([]*proxydb.Model, error)
FilterChain narrows a rule's chain to models that can serve this request: right effort, google_search capability when asked for, a vendor key where the vendor needs one, and all required capabilities.
func IsNodeModel ¶
IsNodeModel reports whether the model runs on self-hosted or local compute nodes.
func Kept ¶ added in v1.2.0
Kept returns the models ExplainChain kept, or the error a call would get when none is left.
func Match ¶
Match returns the first rule (priority desc) whose predicates all hold: effort equal (or rule matches any) and every rule attribute pair equal to the request's. Returns nil only on an unconfigured or invalid snapshot — validation guarantees a catch-all per effort otherwise.
func MatchModality ¶
func MatchModality(snap *registry.Snapshot, effort, modalityKey, modality string, attrs map[string]string) *proxydb.Rule
MatchModality picks a rule for a non-text call. Unlike Match it considers only rules that name the modality themselves, so a text rule can never capture speech or image traffic just because its other predicates happen to hold — that would hand back a chain FilterChain then strips to nothing. nil means no rule is configured for this modality.
func NormalizePlacement ¶
NormalizePlacement standardizes placement aliases into canonical names. Supports aliases: nodes, node, private, private_only, self, self_hosted.
func ResolveBatchModel ¶
func ResolveBatchModel(ctx context.Context, snap *registry.Snapshot, th Throttle, use []string, apiKeyID, keyName, userID, teamID string, canAccess func(string) bool) (*proxydb.Model, error)
ResolveBatchModel resolves the route once for a batch submission: picks the first model in the rule's chain that has the batch capability, a vendor key for the client, and daily budget left.
func ResolveChain ¶
ResolveChain returns the model chain for a rule, selecting the primary candidate via weights when defined while retaining remaining fallbacks in order. If a non-empty hashKey is provided, canary distribution is deterministic per key.
func SanitizeAttributes ¶
SanitizeAttributes strips reserved internal attributes (shadow, is_shadow, shadow_eval, org_id, team_id) to prevent client forgery of billing exemption, automated evaluation, or tenant impersonation.
Types ¶
type Candidate ¶ added in v1.2.0
Candidate is one model of a chain and why it was dropped ("" if kept). Model is nil when the chain names a model the snapshot lacks.
type ChainExhausted ¶
type ChainExhausted struct {
Last error // last vendor error, nil when every model was skipped
AllThrottled bool // every model skipped by a throttle
ThrottleKind string // "rpm" | "budget_key" | "budget_user" | spendlimit reasons
AllCircuitBroken bool // every model skipped because circuit breaker is open
AnyCircuitBroken bool // observed at least one open circuit in chain; retained for telemetry and tests
// RetryAfter is when the first model frees up if every one was paused, else zero.
RetryAfter time.Duration
}
ChainExhausted reports a chain walked to the end without a response.
func (*ChainExhausted) Error ¶
func (e *ChainExhausted) Error() string
func (*ChainExhausted) Unwrap ¶
func (e *ChainExhausted) Unwrap() error
type CircuitBreaker ¶
type CircuitBreaker interface {
Allow(vendor, model string) bool
Report(ctx context.Context, vendor, model string, err error)
Release(vendor, model string)
IsClosed(vendor, model string) bool
}
CircuitBreaker fails fast on degraded upstream models without network IO.
type Cooldown ¶ added in v0.13.1
type Cooldown interface {
Remaining(m *proxydb.Model) time.Duration
Pause(m *proxydb.Model, d time.Duration) time.Duration
}
Cooldown holds back models whose vendor answered with Retry-After. It is bound to the calling client, so one client's quota does not stall others.
type CoolingDown ¶ added in v0.13.1
type CoolingDown struct {
Model string
Remaining time.Duration
Err error // the vendor reply that started the pause; nil on a skip
}
CoolingDown is a model skipped, or just answered, inside its vendor's Retry-After window. It advances the chain rather than ending it.
func (*CoolingDown) Error ¶ added in v0.13.1
func (e *CoolingDown) Error() string
func (*CoolingDown) SkipToNextModel ¶ added in v0.13.1
func (e *CoolingDown) SkipToNextModel() bool
func (*CoolingDown) Unwrap ¶ added in v0.13.1
func (e *CoolingDown) Unwrap() error
type MediaRequest ¶
type MediaRequest struct {
Chain []*proxydb.Model
KeyName string
UserID string
TeamID string
Estimate int64
CircuitBreaker CircuitBreaker
// Cooldown skips models paused by a vendor Retry-After; nil disables it.
Cooldown Cooldown
// UpstreamTimeout bounds each attempt against an upstream vendor.
UpstreamTimeout time.Duration
// Call runs one model and reports what the vendor billed. The adapter is
// resolved for the calling client, exactly as on the text path.
Call func(ctx context.Context, m *proxydb.Model, adapter llm.ClientAdapter) (llm.TokensUsage, error)
// Adapter resolves the vendor adapter for a chain model.
Adapter func(m *proxydb.Model) (llm.ClientAdapter, error)
}
MediaRequest is the chain walk for the speech and image RPCs. They share the text path's throttling and chain semantics but not its schema handling: there is no shape to verify, only bytes to get back.
type NoopThrottle ¶
type NoopThrottle struct{}
NoopThrottle admits everything; used when Redis is not configured.
func (NoopThrottle) ChargeDailyBudget ¶
func (NoopThrottle) ChargeDailyBudget(context.Context, *proxydb.Model, string, string, string, llm.TokensUsage)
func (NoopThrottle) CheckDailyBudget ¶
func (NoopThrottle) Settle ¶
func (NoopThrottle) Settle(*Reservation, llm.TokensUsage)
type Request ¶
type Request struct {
Chain []*proxydb.Model // pre-filtered candidates, in fallback order
KeyName string // api_key name: throttle keys, logs
UserID string // attributes["user_id"] or svc:<keyName> fallback
TeamID string // team identity for team budget enforcement
Estimate int64 // estimated input tokens to reserve
Chat *llm.ChatContext
CircuitBreaker CircuitBreaker
// Cooldown skips models paused by a vendor Retry-After; nil disables it.
Cooldown Cooldown
// UpstreamTimeout bounds each attempt against an upstream vendor.
UpstreamTimeout time.Duration
// Adapter resolves the vendor adapter for a chain model — a closure over
// the snapshot and the calling client, so the router stays testable.
Adapter func(m *proxydb.Model) (llm.ClientAdapter, error)
// SoftSchema reports models whose reply has to be checked here because
// their API cannot enforce a schema.
SoftSchema func(m *proxydb.Model) bool
// ShadowModel is an optional candidate for asynchronous request mirroring.
ShadowModel *proxydb.Model
// ShadowPercentage is the traffic percentage (0.0 - 100.0) to mirror.
ShadowPercentage float64
// ShadowEvaluator is called asynchronously when both primary and shadow responses are ready.
ShadowEvaluator func(ctx context.Context, primaryModel, shadowModel *proxydb.Model, primaryResp, shadowResp *llm.Response)
}
Request is one admission-controlled generation attempt over a model chain.
type Reservation ¶
Reservation is the throttle's bookkeeping handle for one admitted call.
type SchemaFailure ¶
SchemaFailure reports a model that answered but could not produce the requested shape, even given a second try. It advances the chain rather than ending it: another model may well comply.
func (*SchemaFailure) Error ¶
func (e *SchemaFailure) Error() string
func (*SchemaFailure) Unwrap ¶
func (e *SchemaFailure) Unwrap() error
type SpendHold ¶
type SpendHold struct {
Keys []string
TTLs []int64 // seconds, per key
Reserved int64
Model *proxydb.Model
Mode pricing.Mode
}
SpendHold is the monetary side of a reservation: counters booked with Reserved nano-USD, settled to the actual usage priced in Mode.
type Throttle ¶
type Throttle interface {
// AllowRPM takes an RPM slot, or reports the model saturated this minute.
AllowRPM(ctx context.Context, keyName, userID string, m *proxydb.Model) bool
// Reserve books the token estimate against daily budgets and the priced worst
// case (estimate in, maxOutput out) against spend limits. tripped names the
// refusing limit (budget_*, spend_*); empty means reserved, res may be nil.
Reserve(ctx context.Context, m *proxydb.Model, keyName, userID, teamID string, estimate, maxOutput int64) (res *Reservation, tripped string)
// Settle adjusts reserved budgets to actual usage; usage zero = release.
Settle(res *Reservation, usage llm.TokensUsage)
// CheckDailyBudget reports if daily budget is already exhausted ("budget_key" | "budget_user"), or "" if OK.
CheckDailyBudget(ctx context.Context, m *proxydb.Model, keyName, userID, teamID string) string
// ChargeDailyBudget books actual batch usage against daily token budgets
// and, priced at the batch rate, against spend limits.
ChargeDailyBudget(ctx context.Context, m *proxydb.Model, keyName, userID, teamID string, usage llm.TokensUsage)
}
Throttle is what Execute needs from the limiter. The Redis implementation lives in internal/throttle; NoopThrottle allows everything.