mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(router): smart routers and per-member rate limits (#9)
Add smart routers: virtual models that score each request and route it to admin-defined model tiers. A retryable failure moves the request to a higher tier. The classifier v2 extracts prose, finds the original ask in long tool loops, adds an uncertainty margin and reads tool-output failures. Sessions, outcome signals, bounded calibration, adaptive selection within a tier, gated saturation downgrade, a first-byte timeout and an opt-in timeout fallback are included. Every new feature is off by default. Add per-member group limits, a tokensPerMinute window that counts uncached input and output, rate-limit headers in three dialects, soft pacing before the hard limit, and a limitExemptKinds list so embedding and reranking traffic never counts toward or hits a limit. Fix yaegi named-result state that made smartContentSize grow between calls.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLatencyMs, formatModelCostHover, formatPercentAxis, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
|
||||
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLimits, formatLatencyMs, formatModelCostHover, formatPercentAxis, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
|
||||
|
||||
describe('refreshLabel', () => {
|
||||
it('reads "discovery off" when discovery is disabled, regardless of lastRefresh', () => {
|
||||
@@ -300,3 +300,29 @@ describe('formatPercentAxis', () => {
|
||||
expect(formatPercentAxis(rate)).toBe(want)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatLimits', () => {
|
||||
it('returns none when unset or empty', () => {
|
||||
expect(formatLimits(undefined)).toBe('none')
|
||||
expect(formatLimits({})).toBe('none')
|
||||
})
|
||||
|
||||
it('renders tokens per minute', () => {
|
||||
expect(formatLimits({ tokensPerMinute: 500 })).toBe('tok/min 500')
|
||||
})
|
||||
|
||||
it('renders pacing with its source', () => {
|
||||
expect(formatLimits({ pacing: { startPct: 80, maxDelay: '10s' } }, { pacing: 'memberLimits:friends' })).toBe(
|
||||
'pace from 80% up to 10s (memberLimits:friends)',
|
||||
)
|
||||
})
|
||||
|
||||
it('appends each field source when given', () => {
|
||||
expect(
|
||||
formatLimits(
|
||||
{ requestsPerMinute: 9, tokensPerMinute: 100 },
|
||||
{ requestsPerMinute: 'user', tokensPerMinute: 'memberLimits:friends' },
|
||||
),
|
||||
).toBe('req/min 9 (user), tok/min 100 (memberLimits:friends)')
|
||||
})
|
||||
})
|
||||
|
||||
+15
-8
@@ -1,4 +1,4 @@
|
||||
import type { HistoryWindow, LimitsConfig } from '@/types/api'
|
||||
import type { HistoryWindow, LimitSources, LimitsConfig } from '@/types/api'
|
||||
|
||||
/** ZERO_TIME is Go's zero time.Time value in its default JSON (RFC 3339) encoding — the unset-timestamp sentinel every admin API "never happened yet" field marshals as, and every formatter/test below treats as absent. */
|
||||
export const ZERO_TIME = '0001-01-01T00:00:00Z'
|
||||
@@ -368,15 +368,22 @@ export function refreshDetailLabel(discoveryEnabled: boolean, lastRefresh: strin
|
||||
}
|
||||
|
||||
/** formatLimits renders a LimitsConfig as a short comma-joined summary, or "none" when unset. */
|
||||
export function formatLimits(limits: LimitsConfig | undefined): string {
|
||||
export function formatLimits(limits: LimitsConfig | undefined, sources?: LimitSources): string {
|
||||
if (!limits) return 'none'
|
||||
const parts: string[] = []
|
||||
if (limits.requestsPerMinute) parts.push(`req/min ${limits.requestsPerMinute}`)
|
||||
if (limits.requestsPerDay) parts.push(`req/day ${limits.requestsPerDay}`)
|
||||
if (limits.tokensPerDay) parts.push(`tok/day ${limits.tokensPerDay}`)
|
||||
if (limits.tokensPerMonth) parts.push(`tok/month ${limits.tokensPerMonth}`)
|
||||
if (limits.costPerDayUSD) parts.push(`cost/day $${limits.costPerDayUSD}`)
|
||||
if (limits.costPerMonthUSD) parts.push(`cost/month $${limits.costPerMonthUSD}`)
|
||||
const add = (key: keyof LimitsConfig, text: string) => {
|
||||
if (!limits[key]) return
|
||||
const source = sources?.[key]
|
||||
parts.push(source ? `${text} (${source})` : text)
|
||||
}
|
||||
add('requestsPerMinute', `req/min ${limits.requestsPerMinute}`)
|
||||
add('requestsPerDay', `req/day ${limits.requestsPerDay}`)
|
||||
add('tokensPerMinute', `tok/min ${limits.tokensPerMinute}`)
|
||||
add('tokensPerDay', `tok/day ${limits.tokensPerDay}`)
|
||||
add('tokensPerMonth', `tok/month ${limits.tokensPerMonth}`)
|
||||
add('costPerDayUSD', `cost/day $${limits.costPerDayUSD}`)
|
||||
add('costPerMonthUSD', `cost/month $${limits.costPerMonthUSD}`)
|
||||
if (limits.pacing) add('pacing', `pace from ${limits.pacing.startPct}% up to ${limits.pacing.maxDelay}`)
|
||||
return parts.length ? parts.join(', ') : 'none'
|
||||
}
|
||||
|
||||
|
||||
@@ -256,3 +256,28 @@ describe('modelCatalogColumns: p50/p95/error rate columns', () => {
|
||||
expect(accessor(testRow({ attempts: 10, failures: 0 }), 0)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildModelCatalogRows: router targets', () => {
|
||||
it('carries a model routers list and defaults to empty', () => {
|
||||
const catalog = {
|
||||
providers: [
|
||||
{
|
||||
name: 'openai',
|
||||
type: 'openai',
|
||||
lastRefresh: '',
|
||||
openUntil: '',
|
||||
healthState: 'closed',
|
||||
discoveryEnabled: false,
|
||||
models: [
|
||||
{ id: 'openai/a', model: 'a', priceSource: 'unpriced', routers: ['auto'] },
|
||||
{ id: 'openai/b', model: 'b', priceSource: 'unpriced' },
|
||||
],
|
||||
},
|
||||
],
|
||||
aliases: [],
|
||||
routers: [],
|
||||
} as unknown as AdminCatalogResponse
|
||||
const rows = buildModelCatalogRows(catalog, { models: [] } as unknown as AdminUsageModelsResponse, { rows: [] } as unknown as AdminPerfResponse)
|
||||
expect(rows.map((r) => r.routers)).toEqual([['auto'], []])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -43,6 +43,8 @@ export interface ModelCatalogRow {
|
||||
/** True for a ':free' suffix model — display-only; priceSource carries the real billing truth regardless (types/api.ts's own AdminCatalogModel doc comment). */
|
||||
displayFree?: boolean
|
||||
aliases: string[]
|
||||
/** Smart routers that target this model. */
|
||||
routers?: string[]
|
||||
requests: number
|
||||
tokensIn: number
|
||||
tokensOut: number
|
||||
@@ -83,6 +85,7 @@ export function buildModelCatalogRows(
|
||||
priceSource: m.priceSource,
|
||||
displayFree: m.displayFree,
|
||||
aliases: m.aliases ?? [],
|
||||
routers: m.routers ?? [],
|
||||
requests: usage?.requests ?? 0,
|
||||
tokensIn: usage?.tokensIn ?? 0,
|
||||
tokensOut: usage?.tokensOut ?? 0,
|
||||
@@ -194,6 +197,21 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'routers',
|
||||
header: 'Routers',
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => (r.routers ?? []).join(', '),
|
||||
cell: ({ row }) => {
|
||||
const routers = row.original.routers ?? []
|
||||
if (routers.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'flex flex-wrap gap-1' },
|
||||
routers.map((r) => h(Badge, { key: r, as: 'span', variant: 'secondary', class: 'font-mono font-normal', title: 'Smart router target' }, () => r)),
|
||||
)
|
||||
},
|
||||
},
|
||||
// reuse-audit.md F9: requests/tokensIn/tokensOut share the shared
|
||||
// usageMetricColumns factory; 'cost' stays hand-written below since
|
||||
// this table's cost cell has an extra free-priced-model badge case
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { routerSnippet, validateRouter } from './snippets'
|
||||
import type { RouterInput } from './snippets'
|
||||
|
||||
const base: RouterInput = {
|
||||
tiers: [
|
||||
{ name: 'small', minScore: 0, models: ['openai/gpt-5-mini'] },
|
||||
{ name: 'big', minScore: 400, models: ['anthropic/claude-opus', 'openai/gpt-5'] },
|
||||
],
|
||||
keywordRules: [],
|
||||
selection: 'ordered',
|
||||
maxAttempts: 0,
|
||||
contextEscalation: true,
|
||||
}
|
||||
|
||||
describe('routerSnippet: golden YAML, spec.plugin.llmgateway.smartRouters.<name>', () => {
|
||||
it('omits every default', () => {
|
||||
expect(routerSnippet('auto', base)).toBe(
|
||||
[
|
||||
'spec:',
|
||||
' plugin:',
|
||||
' llmgateway:',
|
||||
' smartRouters:',
|
||||
' auto:',
|
||||
' tiers:',
|
||||
' - {"name":"small","minScore":0,"models":["openai/gpt-5-mini"]}',
|
||||
' - {"name":"big","minScore":400,"models":["anthropic/claude-opus","openai/gpt-5"]}',
|
||||
].join('\n'),
|
||||
)
|
||||
})
|
||||
|
||||
it('states non-default selection, attempts, escalation and keyword rules', () => {
|
||||
const out = routerSnippet('auto', {
|
||||
...base,
|
||||
selection: 'hash',
|
||||
maxAttempts: 3,
|
||||
contextEscalation: false,
|
||||
keywordRules: [{ tier: 'big', keywords: ['prove'] }],
|
||||
})
|
||||
expect(out).toContain('keywordRules:')
|
||||
expect(out).toContain('selection: hash')
|
||||
expect(out).toContain('maxAttempts: 3')
|
||||
expect(out).toContain('contextEscalation: false')
|
||||
expect(out).toContain('"keywords":["prove"]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateRouter', () => {
|
||||
it('accepts a valid router', () => {
|
||||
expect(validateRouter(base)).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects no tiers', () => {
|
||||
expect(validateRouter({ ...base, tiers: [] })).toEqual(['Add at least one tier.'])
|
||||
})
|
||||
|
||||
it('requires first minScore 0 and rising scores', () => {
|
||||
const errs = validateRouter({
|
||||
...base,
|
||||
tiers: [
|
||||
{ name: 'a', minScore: 100, models: ['m1'] },
|
||||
{ name: 'b', minScore: 100, models: ['m2'] },
|
||||
],
|
||||
})
|
||||
expect(errs.join(' ')).toContain('must have minScore 0')
|
||||
expect(errs.join(' ')).toContain('greater than the previous')
|
||||
})
|
||||
|
||||
it('rejects overlapping models, duplicate tiers and empty tiers', () => {
|
||||
const errs = validateRouter({
|
||||
...base,
|
||||
tiers: [
|
||||
{ name: 'a', minScore: 0, models: ['m1'] },
|
||||
{ name: 'a', minScore: 10, models: ['m1'] },
|
||||
{ name: 'c', minScore: 20, models: [] },
|
||||
],
|
||||
})
|
||||
expect(errs.join(' ')).toContain('used twice')
|
||||
expect(errs.join(' ')).toContain('must be disjoint')
|
||||
expect(errs.join(' ')).toContain('needs at least one model')
|
||||
})
|
||||
|
||||
it('rejects a keyword rule for an unknown tier', () => {
|
||||
expect(validateRouter({ ...base, keywordRules: [{ tier: 'nope', keywords: ['x'] }] }).join(' ')).toContain('is not a tier')
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
generateApiKey,
|
||||
groupGrantSnippet,
|
||||
groupLimitsSnippet,
|
||||
groupMemberLimitsSnippet,
|
||||
isValidName,
|
||||
isValidNonNegative,
|
||||
isValidNonNegativeInt,
|
||||
@@ -337,3 +338,24 @@ describe('generateApiKey / API_KEY_PLACEHOLDER', () => {
|
||||
expect(generateApiKey()).not.toBe(generateApiKey())
|
||||
})
|
||||
})
|
||||
|
||||
describe('groupMemberLimitsSnippet: golden YAML, spec.plugin.llmgateway.groups.<name>.memberLimits', () => {
|
||||
it('renders memberLimits with tokensPerMinute in field order', () => {
|
||||
expect(groupMemberLimitsSnippet('friends', { tokensPerMinute: 1000, requestsPerMinute: 2 })).toBe(
|
||||
[
|
||||
'spec:',
|
||||
' plugin:',
|
||||
' llmgateway:',
|
||||
' groups:',
|
||||
' friends:',
|
||||
' memberLimits:',
|
||||
' requestsPerMinute: 2',
|
||||
' tokensPerMinute: 1000',
|
||||
].join('\n'),
|
||||
)
|
||||
})
|
||||
|
||||
it('emits tokensPerMinute in a user limits fragment', () => {
|
||||
expect(userLimitsJsonFragment({ tokensPerMinute: 50 })).toBe('"limits": {"tokensPerMinute": 50}')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
// authorizedProviders is computed first and gates model resolution).
|
||||
import { emitConfigSnippet, emitYamlFlowMap, emitYamlKey, emitYamlScalar } from '@/lib/yaml-emit'
|
||||
import type { YamlValue } from '@/lib/yaml-emit'
|
||||
import type { LimitsConfig } from '@/types/api'
|
||||
import type { LimitKey, LimitsConfig } from '@/types/api'
|
||||
|
||||
/** NAME_PATTERN is the operator-facing name rule every provider/group id must satisfy — letters, digits, dot, underscore, hyphen, matching every real name in middleware.yaml (anthropic, gx10-embed, macstudio-rerank, friends, ...) and mirroring the plugin's own path.Match glob-safe charset. */
|
||||
export const NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
|
||||
@@ -109,9 +109,10 @@ export function validatePersonalGrant(providers: string[], models: string[]): st
|
||||
}
|
||||
|
||||
/** LIMITS_FIELD_ORDER is LimitsConfig's own field order (types/api.ts) — the single source of truth every limits snippet (YAML block or JSON fragment) below renders in, so the two never drift relative to each other. */
|
||||
const LIMITS_FIELD_ORDER: (keyof LimitsConfig)[] = [
|
||||
const LIMITS_FIELD_ORDER: (LimitKey)[] = [
|
||||
'requestsPerMinute',
|
||||
'requestsPerDay',
|
||||
'tokensPerMinute',
|
||||
'tokensPerDay',
|
||||
'tokensPerMonth',
|
||||
'costPerDayUSD',
|
||||
@@ -135,6 +136,13 @@ export function groupLimitsSnippet(groupName: string, limits: LimitsConfig): str
|
||||
return emitConfigSnippet(['groups', groupName], { limits: body })
|
||||
}
|
||||
|
||||
/** groupMemberLimitsSnippet builds a group's per-member YAML block at spec.plugin.llmgateway.groups.<name>.memberLimits — each member user gets their own counter with these values. */
|
||||
export function groupMemberLimitsSnippet(groupName: string, limits: LimitsConfig): string {
|
||||
const body: { [key: string]: YamlValue | undefined } = {}
|
||||
for (const [key, value] of limitsEntries(limits)) body[key] = value
|
||||
return emitConfigSnippet(['groups', groupName], { memberLimits: body })
|
||||
}
|
||||
|
||||
function jsonString(s: string): string {
|
||||
return JSON.stringify(s)
|
||||
}
|
||||
@@ -305,3 +313,81 @@ export function userJsonLine(user: UserSnippetInput): string {
|
||||
if (user.admin) parts.push(`"admin": ${emitYamlScalar(true)}`)
|
||||
return `{${parts.join(', ')}}`
|
||||
}
|
||||
|
||||
/** ROUTER_MAX_MIN_SCORE mirrors smart_router.go's maxSmartMinScore: tier scores are per-mille. */
|
||||
export const ROUTER_MAX_MIN_SCORE = 1000
|
||||
|
||||
export interface RouterTierInput {
|
||||
name: string
|
||||
minScore: number
|
||||
models: string[]
|
||||
}
|
||||
|
||||
export interface RouterKeywordRuleInput {
|
||||
tier: string
|
||||
keywords: string[]
|
||||
}
|
||||
|
||||
export interface RouterInput {
|
||||
tiers: RouterTierInput[]
|
||||
keywordRules: RouterKeywordRuleInput[]
|
||||
selection: 'ordered' | 'hash'
|
||||
/** 0 means the gateway default. */
|
||||
maxAttempts: number
|
||||
contextEscalation: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* validateRouter mirrors smart_router.go's validateSmartRouters rules: at
|
||||
* least one tier, unique tier names, first minScore 0, strictly rising
|
||||
* scores, models required and disjoint across tiers, keyword rules naming a
|
||||
* real tier. Returns every problem, empty when the router is valid.
|
||||
*/
|
||||
export function validateRouter(router: RouterInput): string[] {
|
||||
const errors: string[] = []
|
||||
if (router.tiers.length === 0) errors.push('Add at least one tier.')
|
||||
const names = new Set<string>()
|
||||
const modelTier = new Map<string, string>()
|
||||
let prev = -1
|
||||
router.tiers.forEach((tier, i) => {
|
||||
if (names.has(tier.name)) errors.push(`Tier name "${tier.name}" is used twice.`)
|
||||
names.add(tier.name)
|
||||
if (!Number.isInteger(tier.minScore) || tier.minScore < 0 || tier.minScore > ROUTER_MAX_MIN_SCORE) {
|
||||
errors.push(`Tier "${tier.name}" minScore must be a whole number from 0 to ${ROUTER_MAX_MIN_SCORE}.`)
|
||||
} else if (i === 0 && tier.minScore !== 0) {
|
||||
errors.push(`First tier "${tier.name}" must have minScore 0.`)
|
||||
} else if (i > 0 && tier.minScore <= prev) {
|
||||
errors.push(`Tier "${tier.name}" minScore must be greater than the previous tier's.`)
|
||||
}
|
||||
prev = tier.minScore
|
||||
if (tier.models.length === 0) errors.push(`Tier "${tier.name}" needs at least one model.`)
|
||||
for (const model of tier.models) {
|
||||
const other = modelTier.get(model)
|
||||
if (other !== undefined) errors.push(`Model "${model}" is in tier "${other}" and tier "${tier.name}"; tiers must be disjoint.`)
|
||||
else modelTier.set(model, tier.name)
|
||||
}
|
||||
})
|
||||
for (const rule of router.keywordRules) {
|
||||
if (!names.has(rule.tier)) errors.push(`Keyword rule tier "${rule.tier}" is not a tier of this router.`)
|
||||
if (rule.keywords.length === 0) errors.push(`Keyword rule for tier "${rule.tier}" needs at least one keyword.`)
|
||||
}
|
||||
if (!Number.isInteger(router.maxAttempts) || router.maxAttempts < 0) errors.push('Max attempts must be a non-negative whole number.')
|
||||
return errors
|
||||
}
|
||||
|
||||
/**
|
||||
* routerSnippet builds one `smartRouters.<name>` YAML entry
|
||||
* (SmartRouterConfig, smart_router.go). Defaults stay out: selection
|
||||
* "ordered", maxAttempts 0 and contextEscalation true are omitted, so the
|
||||
* snippet only states what differs from the gateway.
|
||||
*/
|
||||
export function routerSnippet(name: string, router: RouterInput): string {
|
||||
const body: { [key: string]: YamlValue | undefined } = {
|
||||
tiers: router.tiers.map((t) => ({ name: t.name, minScore: t.minScore, models: t.models })),
|
||||
}
|
||||
if (router.keywordRules.length > 0) body.keywordRules = router.keywordRules.map((r) => ({ tier: r.tier, keywords: r.keywords }))
|
||||
if (router.selection !== 'ordered') body.selection = router.selection
|
||||
if (router.maxAttempts > 0) body.maxAttempts = router.maxAttempts
|
||||
if (!router.contextEscalation) body.contextEscalation = false
|
||||
return emitConfigSnippet(['smartRouters', name], body)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user