routes

package
v0.1.4607 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 7 Imported by: 0 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 routes is the gateway's router strategy point (P3 of docs/subsystems/plugin-runtime.md): how one pool of routes — a provider's accounts or keys, or the heads of a group's members — is ordered for a request. The gateway lists the pool, rests, affinity and failover itself; a Strategy only says the order.

Smart, the default, is the core's. The others a provider or group can be routed by (order, rotate, usage, pace, weight, free, fast, cheap, drain, expiring) are here for a plugin to register: plugins/rotation does, and off, a pool routed by one of them is tried in its listed order, as an unknown routing always was.

Index

Constants

View Source
const (
	LowShare  = 90
	UsedShare = provider.SpentShare
)

Shares of an allowance past which an account is kept for when the others can't take a request: low (in Smart and Use before expiry, of a rate cap: Seat.WeekLow), and all but used up — where the agent signed in to it is signed in to another, too (provider.SpentShare).

View Source
const ProbeEvery = 5

ProbeEvery: of a pool's requests with a seat measured and one not, one in this many gives the turn to one not measured lately.

View Source
const RefTokens = 200

RefTokens is the reply a seat's speed is weighed at: its first token, then this many at its pace. Short, since an agent's turns are mostly tool calls and short answers, where the first token is most of the wait.

Variables

Builtin are the routings besides Smart and their strategies, as plugins/rotation registers them.

View Source
var Cheapest = Strategy{ByPrice: true, Order: func(_ string, seats []Seat) []int {
	idx := identity(len(seats))
	sort.SliceStable(idx, func(a, b int) bool {
		sa, sb := seats[idx[a]], seats[idx[b]]
		if sa.Priced != sb.Priced {
			return sa.Priced
		}
		if !sa.Priced {
			return false
		}
		if !sameCost(sa.Cost, sb.Cost) {
			return sa.Cost < sb.Cost
		}
		return !sameCost(sa.CacheCost, sb.CacheCost) && sa.CacheCost < sb.CacheCost
	})
	return idx
}}

Cheapest sends a request where its model costs least at the request's time: the priced seats by Cost (a million tokens in and a million out), those that cost the same by CacheCost, then the seats whose price isn't known, each kept in its listed order among those alike. A price that changes with the hour (DeepSeek's off-peak half price, a provider's rate window) is read at the request's time, so one model on several providers goes to the one that bills least now: DeepSeek's own API off its peak hours, another provider of the same model in them (liyuanzheng and lam_em on Discord). Prices a hair apart (sameCost) count as the same, so a rate's rounding doesn't reorder providers billing alike.

Like FreeFirst it orders one tier only: a member's allowance, rests and failover are as for every routing, and a provider or group in the group routed its own way keeps it.

View Source
var Drain = Strategy{Exact: true, Order: func(pool string, seats []Seat) []int {
	spent := func(s Seat) bool {
		return s.Spent || !s.First && s.Known && s.Used >= provider.SpentShareOf(provider.Drain)
	}
	drains.Lock()
	defer drains.Unlock()
	on := drains.m[pool]
	at := slices.IndexFunc(seats, func(s Seat) bool { return s.Key != "" && s.Key == on.key })
	if at < 0 {
		at = max(0, slices.IndexFunc(seats, func(s Seat) bool { return !spent(s) }))
	} else if on.past || spent(seats[at]) {
		for k := 1; k < len(seats); k++ {
			if i := (at + k) % len(seats); !spent(seats[i]) {
				at = i
				break
			}
		}
	}
	drains.m[pool] = drainAt{key: seats[at].Key}
	return append(identity(len(seats))[at:], identity(at)...)
}}

Drain stays on one seat until it is used up, then goes on to the next in the listed order, and stays on that one (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back when its quota renews). The one it is on goes first, the others after it in their listed order from there, so failover goes on as Ordered's does. Used up is a window of it used up (provider.SpentShareOf: 100, as In order goes on at, #530), resting out of quota or credit (Seat.Spent), or refused so since the pool's last request (Drained); a rate limit or a failure only rests a seat, which the gateway tries last meanwhile, and the pool stays on it. With every seat used up it stays where it is. A seat it is on that leaves the pool (turned off, removed) leaves it on the first not used up, in the listed order. Asking again with nothing changed gives the same order, so a preview moves nothing.

View Source
var Fastest = Strategy{BySpeed: true, Order: func(pool string, seats []Seat) []int {
	var fast, unmeasured, resting, spent []int
	for i, s := range seats {
		switch {
		case s.Resting:
			resting = append(resting, i)
		case seatTier(s) == 2:
			spent = append(spent, i)
		case s.TTFT > 0:
			fast = append(fast, i)
		default:
			unmeasured = append(unmeasured, i)
		}
	}
	// a seat that told no pace counts at the middle pace of those that
	// did, so lacking it neither helps nor hurts; none told, the first
	// token alone decides
	var paces []float64
	for _, i := range fast {
		if seats[i].TPS > 0 {
			paces = append(paces, seats[i].TPS)
		}
	}
	mid := 0.0
	if len(paces) > 0 {
		sort.Float64s(paces)
		mid = paces[len(paces)/2]
	}
	est := make(map[int]float64, len(fast))
	for _, i := range fast {
		est[i] = Estimate(seats[i].TTFT, seats[i].TPS, mid)
	}
	sort.SliceStable(fast, func(a, b int) bool { return est[fast[a]] < est[fast[b]] })

	band := make(map[int]int, len(fast))
	top := 0.0
	for k, i := range fast {
		if k == 0 {
			top = est[i]
		} else if band[i] = band[fast[k-1]]; est[i] > alike*top {
			band[i]++
			top = est[i]
		}
	}
	sort.SliceStable(fast, func(a, b int) bool {
		if band[fast[a]] != band[fast[b]] {
			return band[fast[a]] < band[fast[b]]
		}
		return fast[a] < fast[b]
	})
	awake := append(fast, unmeasured...)
	if len(fast) > 0 && len(unmeasured) > 0 {
		probes.Lock()
		p := probes.m[pool]
		p.n++
		if p.n >= ProbeEvery {
			k := unmeasured[p.turns%len(unmeasured)]
			p.n, p.turns = 0, p.turns+1
			awake = append([]int{k}, deleted(awake, k)...)
		}
		probes.m[pool] = p
		probes.Unlock()
	}
	return append(append(awake, resting...), spent...)
}}

Fastest orders a pool by speed lately, as above.

View Source
var FreeExpiring = Strategy{ByFree: true, ByPlan: true, Order: func(pool string, seats []Seat) []int {
	var free, paid, spent []int
	for i, s := range seats {
		switch {
		case s.Spent || seatTier(s) == 2:
			spent = append(spent, i)
		case s.Free || s.FreePlan:
			free = append(free, i)
		default:
			paid = append(paid, i)
		}
	}
	sort.SliceStable(free, func(i, j int) bool {
		x, y := Expires(seats[free[i]]).Truncate(time.Hour), Expires(seats[free[j]]).Truncate(time.Hour)
		if x.Equal(y) {
			return false
		}
		if x.IsZero() || y.IsZero() {
			return y.IsZero()
		}
		return x.Before(y)
	})
	if len(paid) > 1 {
		sub := make([]Seat, len(paid))
		for k, i := range paid {
			sub[k] = seats[i]
		}
		by := Smart.Order(pool, sub)
		ordered := make([]int, len(paid))
		for k, i := range by {
			ordered[k] = paid[i]
		}
		paid = ordered
	}
	sort.SliceStable(spent, func(i, j int) bool { return spentBefore(seats[spent[i]], seats[spent[j]]) })
	return append(append(free, paid...), spent...)
}}

FreeExpiring spends free quota before paid, and of the free, what is lost soonest first (wowbbs on Discord: check-in accounts of WorkBuddy, MiniMax, Trae and Qoder in one group, each given quota that lapses on its own day). A seat is free when its model costs nothing there (Free) or its account's plan is a free one (FreePlan). The order is:

  • the free seats with quota left, by when it is lost first, to the hour (Expires: the soonest of its windows' renewals and of its credits' lapse); one that tells neither after those that do, those alike in their listed order;
  • the paid seats with quota left, as Smart orders them;
  • the used up, free or paid (a known window all but used up, or resting out of quota or credit), as Smart orders its used up.

So a free account is spent until it is used up or expires, then the next free one, and a paid one only once no free one has quota left. Rests and failover are as for every routing.

View Source
var FreeFirst = Strategy{ByFree: true, Order: func(_ string, seats []Seat) []int {
	free, paid := make([]int, 0, len(seats)), make([]int, 0, len(seats))
	for i, s := range seats {
		if s.Free {
			free = append(free, i)
		} else {
			paid = append(paid, i)
		}
	}
	return append(free, paid...)
}}

FreeFirst spends what costs nothing before what is paid for: the seats whose model its vendor serves at no cost to the subscription's allowance or credits go first, in their listed order, and the rest after them, also in their listed order. So a request whose model is free somewhere on the pool uses that first, and only when those can't answer does it go to one that spends credits or quota — nothing is left unused that cost nothing.

It orders one tier only, unlike Smart: a free seat is not pushed behind a paid one for running low, since the free one spends nothing by running out of. Among the paid, the listed order stands rather than Smart's renewal-weighted one, because what this routing is for is the free tier; set a provider's own routing (Smart, in order, weekly pace) if the paid seats should be spent smartly among themselves — a provider or group in this group keeps its own routing either way.

A seat whose model costs nothing nowhere is not free: it goes with the paid ones, so a routing set on a pool without free models behaves as In order.

View Source
var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
	left := byLeft(seats, fewerTokens)

	shared := func(s Seat) bool {
		if !s.Known {
			return false
		}
		if s.Used > 0 {
			return true
		}
		for _, at := range s.Soon {
			if !at.IsZero() {
				return true
			}
		}
		return false
	}

	place := func(s Seat) int {
		switch t := tier(s.Used); {
		case s.Learns:
			return 0
		case t == 0 && shared(s):
			return 1
		case t == 0:
			return 2
		default:
			return t + 2
		}
	}
	idx := identity(len(seats))
	sort.SliceStable(idx, func(a, b int) bool {
		sa, sb := seats[idx[a]], seats[idx[b]]
		if pa, pb := place(sa), place(sb); pa != pb {
			return pa < pb
		}
		if ta, tb := tier(sa.Used), tier(sb.Used); ta == 2 && tb == 2 && sa.Credits != sb.Credits {
			return sa.Credits
		}

		if ua, ub := urgent(sa), urgent(sb); ua != ub {
			return ua
		} else if ua && !sa.Lapse.Truncate(time.Hour).Equal(sb.Lapse.Truncate(time.Hour)) {
			return sa.Lapse.Before(sb.Lapse)
		}
		if sa.Used != sb.Used {
			return sa.Used < sb.Used
		}
		if left != nil {
			if c := left(idx[a], idx[b]); c != 0 {
				return c < 0
			}
		}
		return sa.Tokens < sb.Tokens
	})
	return idx
}}

LeastUsed puts a subscription, or a key that reads its own windows, by the share of its allowance used, as the vendor says; then, and for other keys, by what magpie sent it lately; prepaid wallets, which have no share, by what they have left first (Seat.Left). Of those all but used up, one that goes on on its credits goes first (spentBefore). A seat that tells no share — a pay-as-you-go key, a wallet, an account whose use wasn't read — has Used read 0, and by that 0 alone it went first, burning paid balance while subscription quota sat idle (#4535): it goes after those whose share was told and has room, and before those running low or spent, as Smart and Pace keep the unknown. One not known that tells what it has left as it answers goes first, once, as in Smart and Pace. The share used is taken less what lapses soon unspent (Seat.Lapsing): WorkBuddy's account with half of a year-long pack used but check-in credits ending tomorrow ranks by what it can really lose, not by the pool's share (kudi3699 on X): one with room whose credits lapse soon goes ahead of the rest, the soonest first.

View Source
var Ordered = Strategy{Exact: true, Order: func(_ string, seats []Seat) []int { return identity(len(seats)) }}

Ordered tries a pool in its order: the first until it can't answer.

View Source
var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {
	// the bands of pace alike within a tenth, the highest first: drawn
	// before sorting, from each band's highest down, so that sorting by
	// them is consistent — "within a tenth of each other" alone is not,
	// three paces a twelfth apart each going round in a circle. Drawn among
	// those the pace orders alone — one running low would otherwise set a
	// band's top and part two alike behind it
	var byPace []int
	for i, s := range seats {
		if seatTier(s) == 0 && !s.Learns {
			byPace = append(byPace, i)
		}
	}
	sort.SliceStable(byPace, func(a, b int) bool { return seats[byPace[a]].Pace > seats[byPace[b]].Pace })
	band, top := make([]int, len(seats)), 0.0
	for k, i := range byPace {
		if p := seats[i].Pace; k == 0 || p < 0.9*top {
			top = p
			if k > 0 {
				band[i] = band[byPace[k-1]] + 1
				continue
			}
		} else {
			band[i] = band[byPace[k-1]]
		}
	}
	left := byLeft(seats, fewerTokens)
	idx := identity(len(seats))
	sort.SliceStable(idx, func(a, b int) bool {
		sa, sb := seats[idx[a]], seats[idx[b]]
		if ta, tb := seatTier(sa), seatTier(sb); ta != tb {
			return ta < tb
		} else if ta == 2 && sa.Credits != sb.Credits {
			return sa.Credits
		} else if ta > 0 {
			if sa.Used != sb.Used {
				return sa.Used < sb.Used
			}
		} else if sa.Learns != sb.Learns {
			return sa.Learns
		} else if band[idx[a]] != band[idx[b]] {
			return band[idx[a]] < band[idx[b]]
		} else if left != nil {

			if c := left(idx[a], idx[b]); c != 0 {
				return c < 0
			}
		}
		return sa.Tokens < sb.Tokens
	})
	return idx
}}

Pace puts a subscription by what it has left of its week per hour until that renews, the most first: it has the most to lose at the reset, where the most left alone (least used) sends a fresh account ahead of one with 80% left and an hour to go, and the soonest reset alone (smart) sends one with 3% left and an hour to go ahead of one with 90% and two. The tiers are Smart's: one at 90% or more of a rate cap that counts the model — the five hours, which it would be sent into before its allowance was read again — waits until the others can't answer (a week at 90% alone doesn't: what it has left is lost at its reset, Seat.WeekLow), one all but used up until nothing else can; each tier by the share used, one all but used up that goes on on its credits first (spentBefore). Among the rest, one not known that tells what it has left as it answers goes first while it isn't, as in Smart, else it would never be known; then the pace, those alike within a tenth by what a wallet has left (Seat.Left), then by what magpie sent them lately, then in their order, keeping the vendor's prompt cache warm. An account not known counts as a whole week ahead of it; a key has no week, unless it reads its own windows (a sub2api key's limits). A Codex account that spends a reset about to run out by itself goes by the hours until then when that is sooner (Allowance.Pace, #717).

View Source
var Rotate = Strategy{Order: func(pool string, seats []Seat) []int {
	turns.Lock()
	n := turns.m[pool] % len(seats)
	turns.m[pool]++
	turns.Unlock()
	return append(identity(len(seats))[n:], identity(n)...)
}}

Rotate starts each request one further along the pool.

View Source
var SmallFirst = Strategy{ByWindow: true, Order: func(pool string, seats []Seat) []int {
	idx := Smart.Order(pool, seats)
	rank := func(s Seat) (int, int) {
		g := 1
		switch {
		case seatTier(s) == 2:
			g = 2
		case s.Lead:
			g = 0
		}
		return g, s.Window
	}
	sort.SliceStable(idx, func(a, b int) bool {
		ga, wa := rank(seats[idx[a]])
		gb, wb := rank(seats[idx[b]])
		if ga != gb {
			return ga < gb
		}
		if wa == wb {
			return false
		}
		if wa == 0 || wb == 0 {
			return wb == 0
		}
		return wa < wb
	})
	return idx
}}

SmallFirst sends a request to the member whose model has the smallest context window, so the big ones are kept for the requests only they hold: the gateway leaves out, before asking, every member whose window the request is longer than (roomy), so the first left is the smallest that holds it. In Smart's order otherwise: a seat all but used up still goes after those with room, one set to be used first still first, and members of one window in Smart's order among themselves; a window not known goes after every known one.

View Source
var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
	left := byLeft(seats, nil)
	var fine, low, spent []int
	for i, s := range seats {
		switch seatTier(s) {
		case 2:
			spent = append(spent, i)
		case 1:
			low = append(low, i)
		default:
			fine = append(fine, i)
		}
	}
	sort.SliceStable(fine, func(i, j int) bool {
		a, b := seats[fine[i]], seats[fine[j]]
		if a.Learns != b.Learns {
			return a.Learns
		}

		ri, rj := a.Soon[min(a.Unreached, len(a.Soon)):], b.Soon[min(b.Unreached, len(b.Soon)):]
		for k := 0; k < len(ri) || k < len(rj); k++ {
			var x, y time.Time // to the hour, so a few minutes don't reorder
			if k < len(ri) {
				x = ri[k].Truncate(time.Hour)
			}
			if k < len(rj) {
				y = rj[k].Truncate(time.Hour)
			}
			switch {
			case x.Equal(y):
				continue
			case x.IsZero() || y.IsZero():
				return y.IsZero()
			}
			return x.Before(y)
		}

		x, y := a.Lapse.Truncate(time.Hour), b.Lapse.Truncate(time.Hour)
		if x.Equal(y) {

			return left != nil && left(fine[i], fine[j]) < 0
		}
		if x.IsZero() || y.IsZero() {
			return y.IsZero()
		}
		return x.Before(y)
	})
	sort.SliceStable(low, func(i, j int) bool { return seats[low[i]].Used < seats[low[j]].Used })
	sort.SliceStable(spent, func(i, j int) bool { return spentBefore(seats[spent[i]], seats[spent[j]]) })
	return leadFirst(seats, append(append(fine, low...), spent...))
}}

Smart is the default: of those with quota to spare, the one whose allowance renews soonest, since what it has left is lost then, while one renewing later keeps: the biggest window decides — the week, not the five hours in it — and the next one only when that renews in the same hour. A biggest window whose left the next can no longer let through before it renews (Seat.Unreached: a Volcengine Agent Plan's month two weeks out, with more left than two weeks hold) is passed over: what the week leaves is lost at its reset then, so the week decides (#5639). An account with no week (Claude Enterprise's five hours alone) goes by its five hours, so ahead of every week but one renewing sooner; a window not started renews its whole span from now (#576). A Codex account that spends a reset about to run out by itself (auto-use on, its windows used) renews when that is spent, if sooner: what it has left is lost there just the same (#718). Only holding one, or one that runs out after the week renews, changes nothing. Renewing in the same hours, the one whose credits left lapse first (Seat.Lapse) goes first: WorkBuddy's free accounts all renew at the month's end, but the credits each was given end on their own days (zhaocai_83020 on Discord). Then, of prepaid wallets (Seat.Left), the one with more left (#3950). Those alike stay in their order, keeping the vendor's prompt cache warm. Past that, whichever has the most left, and one all but used up only when nothing else can take it, one that goes on on its credits first of those (spentBefore). Only the windows that count the model do: Opus's own weekly allowance being used up leaves Sonnet alone.

One not known that tells what it has left as it answers goes first, once: else, kept after those known, it would never answer and never be known (Anthropic's usage endpoint can turn magpie away for hours).

View Source
var Weighted = Strategy{Order: func(pool string, seats []Seat) []int {
	keys, weights, rests := make([]string, len(seats)), make([]int, len(seats)), make([]bool, len(seats))
	for i, s := range seats {
		keys[i], weights[i], rests[i] = s.Key, max(s.Weight, 1), s.Resting
	}
	return First(Round(pool, keys, weights, rests), len(seats))
}}

Weighted spreads a pool's requests over its seats by each one's weight, smoothly (Round): the one the pool's round picks now first, the others after it in their order, for failover.

Functions

func Apply

func Apply(s Strategy, pool string, seats []Seat) (order []int)

Apply is the order s gives seats, checked: an order that isn't a permutation of them, or a strategy that panics, leaves them in their listed order, logged. A strategy only orders, so failing it fails open: every route is still tried.

func Drained added in v0.1.2517

func Drained(key string)

Drained says key was refused for its quota or its credit: every pool routed Until used up that is on it goes on to the next at its next request, though key renews before then. The gateway's failover has already tried the next for the request refused; without this, a pool asked again only after key renewed went back to it.

func Estimate added in v0.1.1627

func Estimate(ttft, tps, mid float64) float64

Estimate is the ms to a reply of RefTokens at ttft and tps; a tps of 0 counts as mid, and with mid 0 too the first token alone counts.

func Expires added in v0.1.2921

func Expires(s Seat) time.Time

Expires is when the soonest of what a seat has left is lost: the first of its windows' renewals (Soon) and its credits' lapse (Lapse), zero when it tells neither.

func First

func First(best, n int) []int

First is the order of n with best first and the others after it in their order; best below 1 leaves it as it is.

func Forget

func Forget(pools ...string)

Forget drops what pool's round, turn and drain hold, every pool's with none named: a test starts each anew.

func MoveRound

func MoveRound(pool, picked, kept string)

MoveRound charges pool's last pick to kept rather than picked, when affinity kept a conversation with kept: the round counts the requests each really took, so new conversations make up the share.

func Register

func Register(routing string, s Strategy) (remove func())

Register serves routing by s until remove is called. Registering one already served stacks: the last serves until it is removed.

func Round

func Round(pool string, keys []string, weights []int, rests []bool) int

Round is which of keys pool's round picks now, each weighing its weight, those resting left out of the round; -1 when every one rests. The pick is charged the round's total.

func Served

func Served(routing string) bool

Served says whether routing is served now.

Types

type Seat

type Seat struct {
	// Key is who it is: the account or key's rest key, the same for the
	// same route from request to request
	Key string
	// Account is a subscription's account, not an API key
	Account bool
	// Known: its allowance is known. Used, Soon and Pace are read from it
	Known bool
	// Learns: an account not known yet, of an agent that tells what it has
	// left as it answers (Claude Code's rate_limit_event, Codex's x-codex-*
	// headers)
	Learns bool
	// Used is the share of its allowance used that counts the model, 0–100
	Used float64
	// WeekLow: Used is at LowShare or more for its budget windows alone
	// (a day or longer: the week), no rate cap of it near full
	// (provider.Allowance.CapUsed). Smart and Use before expiry keep it
	// with those that have room: what the week has left is lost at its
	// reset, and kept for last a week at 90% renewing today went unused
	// (ysicing_01858 on Discord).
	WeekLow bool
	// Soon is when its windows renew, the biggest first (Allowance.Renewal)
	Soon []time.Time
	// Unreached is how many of Soon's windows, the biggest first, can no
	// longer be used up before they renew unless the next one's left is
	// used before that renews (provider.Allowance.Unreached): Smart ranks
	// it by the next one, as what that leaves at its reset is lost
	// (#5639). 0 for every account whose windows don't tell their counts.
	Unreached int
	// Lapse is when the soonest of what it has left is lost, apart from
	// its windows' renewals (Allowance.Lapse): zero when not told. Smart
	// goes by it when Soon ties.
	Lapse time.Time
	// Lapsing is the share of its allowance, in points of Used, that is
	// lost soon unspent (Allowance.Lapsing): zero when not told. Least
	// used first sends a seat with room and some ahead, as credits lost
	// anyway cost nothing to spend.
	Lapsing float64
	// Pace is its week left per hour until that renews; an account not
	// known has a whole week (provider.FreshPace), a key none
	Pace float64
	// Weight is its key's weight, at least 1
	Weight int
	// Resting: it rests after a failure now
	Resting bool
	// Spent: it rests because it is out of quota or credit, not for a
	// rate limit or a failure. Drain goes on from it.
	Spent bool
	// Tokens is what magpie sent it lately, decayed by an hour's half-life
	Tokens float64
	// Free: the model this seat would be asked for costs nothing on it —
	// its vendor serves that model at no cost to the subscription's
	// allowance or credits (catalog.Model's Free). FreeFirst goes by it.
	Free bool
	// FreePlan: an account whose plan is a free one (provider.FreePlan:
	// "Free", "Free plan", a trial), as its vendor or plugin names it.
	// FreeExpiring spends it, as it does Free, before a paid one.
	FreePlan bool
	// Credits: an account that goes on past its allowance on its credits:
	// a Codex account let spend them, or a plugin's whose plugin says so
	// (a Kiro trial's). All but used up, it goes before those used up with
	// nothing to go on with.
	Credits bool
	// First: such an account the user set to spend its credits before
	// another account (provider.CodexCreditsFirst): its windows running
	// out never put it behind the others (seatTier), so it keeps the
	// place an account with room has.
	First bool
	// Lead: its provider is set to be used first (provider.Provider.
	// UseFirst). Smart puts such seats ahead of the others while they have
	// quota (seatTier below 2), in Smart's own order among themselves.
	Lead bool
	// TTFT is how long it took lately to the first of its reply, in ms,
	// for the model this seat would be asked for: a decayed average of its
	// recent streamed answers, 0 when it hasn't answered one lately.
	// TPS is how fast it wrote them, output tokens a second, 0 when not
	// told (a reply let go in a burst tells none). Fastest goes by them.
	TTFT, TPS float64
	// Left is a prepaid wallet's balance, what it has left in its unit
	// (provider.Allowance.Left, #3950), and LeftIn whose wallet that is:
	// its provider and unit, empty when no balance was told. A wallet has
	// no share and no renewal, so Used and Soon tie; Smart, Pace and
	// LeastUsed then put the one with more left first, only among seats
	// whose LeftIn is the same (byLeft): points are never weighed against
	// another provider's, or another unit.
	Left   float64
	LeftIn string
	// Priced: what its model costs on it now is known. Cost is then what
	// a million tokens in and a million out cost at the request's time —
	// the user's own price, else the list's, at its provider's rate and
	// rate window, doubled in its vendor's peak hours (catalog.Price.In) —
	// and CacheCost a million read from the cache. Its model free there
	// costs 0. Cheapest goes by them.
	Priced          bool
	Cost, CacheCost float64
	// Window is its model's context window there, in tokens, 0 when not
	// known. SmallFirst goes by it.
	Window int
}

Seat is one route of a pool, as a strategy weighs it.

type Strategy

type Strategy struct {
	// Order is the order to try seats in: a permutation of their indexes.
	// pool names the pool (a provider's id, or "group/<id>"), for a
	// strategy that keeps a round per pool. It is asked with two seats or
	// more.
	Order func(pool string, seats []Seat) []int
	// Exact: its order stands as it says. Otherwise, of a provider's API
	// keys, those that fit the request better go first, each kept in its
	// order among those alike.
	Exact bool
	// ByUse: it weighs by Tokens, which the routing trace then shows
	ByUse bool
	// ByFree: it weighs by Free, so the gateway works out which seat's
	// model costs nothing there, and the routing trace then shows it.
	// Only when set: working it out reads each provider's model list.
	ByFree bool
	// ByPlan: it weighs by FreePlan, so the gateway reads each account's
	// plan, and the routing trace then shows a free one as free.
	ByPlan bool
	// BySpeed: it weighs by TTFT and TPS, so the gateway reads each seat's
	// recent speed, and the routing trace then shows it.
	BySpeed bool
	// ByPrice: it weighs by Priced, Cost and CacheCost, so the gateway
	// prices each seat's model at the request's time, and the routing
	// trace then shows it. Only when set: pricing reads each provider's
	// model list and the user's prices.
	ByPrice bool
	// ByWindow: it weighs by Window, so the gateway reads each seat's
	// model's context window, and the routing trace then shows it.
	ByWindow bool
}

Strategy orders a pool.

func Find

func Find(routing string) (Strategy, bool)

Find is the strategy serving routing: Smart for "", else the last one registered; ok is false when none is.

Jump to

Keyboard shortcuts

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