Documentation
¶
Index ¶
- Constants
- func ApplyModelContextDefaults(ctx context.Context, store ModelContextStore, req *translate.ChatRequest, ...) error
- func ApplyPinnedProviderFilter(pool *Pool, providerFilter, publicModel, prefer string) string
- func CanonicalModelID(model string) string
- func ClassifyUpstreamBody(status int, body string) error
- func IsInvalidRequestText(text string) bool
- func IsPromptLimitText(text string) bool
- func ItemCouldServeModel(item Item, publicModel string) bool
- func ItemHasModel(item Item, publicModel string) bool
- func NativeModelID(item Item, publicModel string) string
- func NativeSessionKeyFor(req *translate.NativeResponsesRequest, identity auth.Identity) string
- func NextLocalMidnightCooldown() time.Duration
- func NextLocalMidnightCooldownAt(now time.Time) time.Duration
- func NormalizeModelName(model string) string
- func NormalizeProviderFamily(provider string) string
- func NormalizeRegion(region string) string
- func NormalizeRoutingStrategy(strategy string) string
- func NormalizeWeight(priority int) int
- func ParseRetryAfter(raw string, fallback time.Duration) time.Duration
- func ParseRetryAfterHint(body, header string, fallback time.Duration) time.Duration
- func ProviderAllowed(provider string, allowed []string) bool
- func ProviderPrefix(model string) string
- func ProviderRegionAllowed(provider, region string, allowed []string) bool
- func RejectsBareModel(model string, crossProviderPool bool) bool
- func RequestIDFromContext(ctx context.Context) string
- func RequestedReasoningLevel(req translate.ChatRequest) string
- func ResolveProviderFilter(req *translate.ChatRequest, crossProviderPool bool) string
- func SessionKeyFor(header string, identity auth.Identity, req translate.ChatRequest) string
- func StreamIncompleteError() error
- func StreamReadError(err error) error
- func WithAllowedProviders(ctx context.Context, providers []string) context.Context
- func WithRequestID(ctx context.Context, id string) context.Context
- func WithSessionKey(ctx context.Context, key string) context.Context
- type AttemptHook
- type CatalogPreparer
- type ChatExecutor
- func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (result ChatResult, returnErr error)
- func (e ChatExecutor) ChatStreamProxy(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (result StreamResult, returnErr error)
- func (e ChatExecutor) ChatStreamProxyNativeResponses(ctx context.Context, req translate.ChatRequest, ...) (result StreamResult, returnErr error)
- func (e ChatExecutor) CommitSession(ctx context.Context, req translate.ChatRequest, routing, accountID string)
- func (e ChatExecutor) HasNativeResponsesRoute(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) bool
- func (e ChatExecutor) NativeResponsesNonStream(ctx context.Context, req translate.ChatRequest, ...) (result NativeResponseResult, returnErr error)
- func (e ChatExecutor) ObserveStreamFailure(accountID string, err error, model string)
- func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error)
- type ChatResult
- type Classified
- type ExecutionError
- type Item
- type ModelContextStore
- type NativeResponseResult
- type Pool
- func (p *Pool) ByID(id string) (Item, bool)
- func (p *Pool) CooldownScope(item Item, publicModel string) string
- func (p *Pool) First() (Item, bool)
- func (p *Pool) Items() []Item
- func (p *Pool) Len() int
- func (p *Pool) LenRoute(q RouteQuery) int
- func (p *Pool) MarkClassified(id string, c Classified)
- func (p *Pool) MarkDown(id string, d time.Duration, err string)
- func (p *Pool) MarkOK(id, model string)
- func (p *Pool) MergeHealth(id string, ready, hot bool, inFlight, restarts int, lastError string)
- func (p *Pool) MergeModels(id string, models []string)
- func (p *Pool) MergeQuota(id string, quota *QuotaSnapshot)
- func (p *Pool) Observer() PoolObserver
- func (p *Pool) Pick(prefer string, excluded map[string]struct{}) (Item, bool)
- func (p *Pool) PickRoute(q RouteQuery) (Item, bool)
- func (p *Pool) Remove(id string)
- func (p *Pool) RemoveModel(id, model string)
- func (p *Pool) RetryAfter(item Item, publicModel string) time.Duration
- func (p *Pool) RoutingStrategy() string
- func (p *Pool) SetDropSystemPrompt(id string, drop bool)
- func (p *Pool) SetObserver(observer PoolObserver)
- func (p *Pool) SetRoutingStrategy(strategy string)
- func (p *Pool) SetRuntimeState(id, state string, nextRestartAt time.Time, backoffLevel int, lastError string)
- func (p *Pool) SetWeight(id string, weight int)
- func (p *Pool) Snapshot() []map[string]any
- func (p *Pool) Upsert(item Item)
- type PoolObserver
- type PrepareError
- type PrepareInput
- type PreparedRequest
- type QuotaSnapshot
- type RequestStarter
- type RouteQuery
- type SessionAffinity
- type SessionAffinityStats
- type StreamResult
Constants ¶
const ( KindQuota = accounts.KindQuota KindRateLimit = accounts.KindRateLimit KindAuth = accounts.KindAuth KindNotReady = accounts.KindNotReady KindInvalidRequest = accounts.KindInvalidRequest KindModelNotAvailable = accounts.KindModelNotAvailable KindCanceled = accounts.KindCanceled BackoffMaxLevel = accounts.BackoffMaxLevel RoutingStrategyRoundRobin = accounts.RoutingStrategyRoundRobin RoutingStrategyWeightedRoundRobin = accounts.RoutingStrategyWeightedRoundRobin RoutingStrategyFillFirst = accounts.RoutingStrategyFillFirst )
Variables ¶
This section is empty.
Functions ¶
func ApplyModelContextDefaults ¶ added in v0.6.0
func ApplyModelContextDefaults(ctx context.Context, store ModelContextStore, req *translate.ChatRequest, providerFilter string) error
func ApplyPinnedProviderFilter ¶ added in v0.6.0
func CanonicalModelID ¶ added in v0.6.0
func ClassifyUpstreamBody ¶ added in v0.6.0
ClassifyUpstreamBody classifies an upstream HTTP/SSE error body once.
func IsInvalidRequestText ¶ added in v0.6.0
func IsPromptLimitText ¶ added in v0.6.0
func ItemCouldServeModel ¶ added in v0.6.0
ItemCouldServeModel reports whether this account belongs on a model route at all, including cooling unknown-catalog accounts. Sticky routing uses this so a bound cooling account still pins provider/region before PickRoute escapes.
func ItemHasModel ¶ added in v0.6.0
ItemHasModel reports whether this account can serve publicModel on a live pick. Cooling empty-catalog accounts fail closed here so they do not occupy the route just because a catalog fetch failed.
func NativeModelID ¶ added in v0.6.0
NativeModelID returns the provider-native catalog spelling for a public model. Trae config_name is case-sensitive; routing matches on the canonical form, but the upstream request must keep the original ID.
func NativeSessionKeyFor ¶ added in v0.6.7
func NativeSessionKeyFor(req *translate.NativeResponsesRequest, identity auth.Identity) string
func NextLocalMidnightCooldown ¶ added in v0.6.0
func NextLocalMidnightCooldownAt ¶ added in v0.6.0
func NormalizeModelName ¶ added in v0.6.0
func NormalizeProviderFamily ¶ added in v0.6.0
func NormalizeRegion ¶ added in v0.6.0
func NormalizeRoutingStrategy ¶ added in v0.6.0
func NormalizeWeight ¶ added in v0.6.0
func ParseRetryAfter ¶ added in v0.6.0
func ParseRetryAfterHint ¶ added in v0.6.0
func ProviderAllowed ¶ added in v0.6.0
func ProviderPrefix ¶ added in v0.6.0
func ProviderRegionAllowed ¶ added in v0.6.0
func RejectsBareModel ¶ added in v0.6.0
func RequestIDFromContext ¶ added in v0.2.6
func RequestedReasoningLevel ¶ added in v0.6.1
func RequestedReasoningLevel(req translate.ChatRequest) string
RequestedReasoningLevel surfaces the reasoning level the client asked for, normalized to the provider-neutral vocabulary. Empty when the request did not specify one.
func ResolveProviderFilter ¶ added in v0.6.0
func ResolveProviderFilter(req *translate.ChatRequest, crossProviderPool bool) string
func SessionKeyFor ¶ added in v0.6.0
func StreamIncompleteError ¶ added in v0.6.0
func StreamIncompleteError() error
StreamIncompleteError is a mid-body stream that ended without [DONE].
func StreamReadError ¶ added in v0.6.0
StreamReadError wraps a mid-body stream read failure.
func WithAllowedProviders ¶ added in v0.2.21
func WithRequestID ¶ added in v0.2.6
Types ¶
type AttemptHook ¶ added in v0.2.6
type AttemptHook func(accounts.RequestAttempt)
type CatalogPreparer ¶ added in v0.6.0
type ChatExecutor ¶
type ChatExecutor struct {
Pool *Pool
WorkerKey string
// WorkerKeySource, when set, supplies the live key shared by executor copies.
WorkerKeySource func() string
HTTPClient *http.Client
Providers *providerRegistry
OnAttempt AttemptHook
MaxAttempts int
SessionAffinity *SessionAffinity
}
func NewChatExecutor ¶
func NewChatExecutor(pool *Pool, workerKey string) ChatExecutor
func (ChatExecutor) ChatNonStream ¶
func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (result ChatResult, returnErr error)
func (ChatExecutor) ChatStreamProxy ¶
func (e ChatExecutor) ChatStreamProxy(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (result StreamResult, returnErr error)
func (ChatExecutor) ChatStreamProxyNativeResponses ¶ added in v0.6.7
func (e ChatExecutor) ChatStreamProxyNativeResponses(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string) (result StreamResult, returnErr error)
ChatStreamProxyNativeResponses sends the original Responses request to a native-capable adapter. Once this path starts, retries remain native-only.
func (ChatExecutor) CommitSession ¶ added in v0.2.42
func (e ChatExecutor) CommitSession(ctx context.Context, req translate.ChatRequest, routing, accountID string)
CommitSession binds a successfully completed stream. The executor cannot know whether an SSE response reached [DONE], so the relay calls this only after it has finished without an upstream or client error.
func (ChatExecutor) HasNativeResponsesRoute ¶ added in v0.6.7
func (e ChatExecutor) HasNativeResponsesRoute(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) bool
func (ChatExecutor) NativeResponsesNonStream ¶ added in v0.6.7
func (e ChatExecutor) NativeResponsesNonStream(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string) (result NativeResponseResult, returnErr error)
func (ChatExecutor) ObserveStreamFailure ¶ added in v0.2.28
func (e ChatExecutor) ObserveStreamFailure(accountID string, err error, model string)
ObserveStreamFailure applies a post-headers streaming failure to the pool. Upstream can answer 200 and then fail inside the SSE body, which happens after the executor already returned a successful StreamResult; the relay error is the first place the failure is observable. Same-account retry is impossible at that point (bytes are on the wire), so this only records the classified state for the next request's scheduling.
func (ChatExecutor) Prepare ¶ added in v0.6.0
func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error)
type ChatResult ¶
type ChatResult struct {
Model string
Content string
Reasoning string
ToolCalls json.RawMessage
FinishReason string
PromptTokens int
CompletionTokens int
CacheReadTokens *int
CacheWriteTokens *int
CachedTokens *int
UsageSource string
Credits *float64
ConsumedCredits *float64
AccountID string
Provider string
AttemptCount int
RawNote string
Routing string
ReasoningLevel string
}
type Classified ¶ added in v0.6.0
type Classified struct {
Kind string
Status int
Failover bool
Cooldown time.Duration
Code string
Type string
Message string
RetryAfter time.Duration
// Model scopes the cooldown to one public model. When set, only that
// model is cooled; the account keeps serving everything else.
Model string
}
func Classify ¶ added in v0.6.0
func Classify(status int, body, retryAfter, kindHint, failoverHint string) Classified
func ClassifyError ¶ added in v0.6.0
func ClassifyError(err error) Classified
ClassifyError is the single adapter-error policy used by execution and HTTP reporting.
type ExecutionError ¶ added in v0.6.0
type ExecutionError struct {
Classified Classified
Err error
}
ExecutionError is the executor's final classified result. HTTP layers format it; they must not re-run Classify or invent failover/cooldown policy.
func NewExecutionError ¶ added in v0.6.0
func NewExecutionError(classified Classified, err error) *ExecutionError
func (*ExecutionError) Error ¶ added in v0.6.0
func (e *ExecutionError) Error() string
func (*ExecutionError) Unwrap ¶ added in v0.6.0
func (e *ExecutionError) Unwrap() error
type Item ¶ added in v0.6.0
type Item struct {
ID string
URL string
Provider string
Region string
Runtime string
// Weight is the per-account scheduling weight (1..100). Accounts share
// the default, so the pool stays a plain round-robin until an operator
// differentiates them.
Weight int
DownUntil time.Time
LastError string
LastKind string
Ready *bool
Hot *bool
InFlight int
// MaxInFlight caps concurrent requests routed to this account. Zero
// means unknown and does not block routing.
MaxInFlight int
Restarts int
RuntimeState string
NextRestartAt time.Time
RestartBackoffLevel int
Quota *QuotaSnapshot
// Models is the last successful per-account catalog snapshot. A nil
// slice means unknown (fail open); a non-nil slice, including empty,
// is used to filter PublicModel. Entries keep the provider-native
// spelling so Trae config_name case is preserved.
Models []string
ModelsAt time.Time
// ProvenModels are public IDs this account has actually served. A
// later catalog refresh must not drop a model that just succeeded:
// WorkBuddy CLI snapshots can omit a live ID and would otherwise
// leave only quota-cooled empty-catalog accounts on that route.
ProvenModels []string
// ModelDownUntil is per-model cooldown. One model hitting a limit must
// not take the whole account offline for other models.
ModelDownUntil map[string]time.Time
// ModelBackoff is the per-model backoff ladder, mirroring
// ModelDownUntil. One model's repeated failures must not inflate the
// ladder for a different model. The account-wide BackoffLevel covers
// non-model-scoped failures.
ModelBackoff map[string]int
// ModelLastKind is the per-model previous failure kind, mirroring
// ModelBackoff. The backoff ladder only climbs on a repeat of the same
// kind, and that comparison must be scoped per model: a rate_limit on
// model-A followed by auth on model-B must not make a later auth on
// model-A look like a repeat. The account-wide LastKind covers
// non-model-scoped failures.
ModelLastKind map[string]string
// BackoffLevel climbs on repeated failures of the same kind and resets
// on success, so a persistently failing account backs off instead of
// being retried at a fixed interval.
BackoffLevel int
// DropSystemPrompt mirrors the stored account flag so the executor can
// sanitize requests per account without a store lookup per chat.
DropSystemPrompt bool
// StateVersion is a process-local monotonic stamp assigned under p.mu
// whenever a persistable mutation lands. The persistence observer runs
// after p.mu is released, so concurrent observers can enqueue snapshots
// out of production order; the version lets the drainer discard a stale
// snapshot that arrives after a newer one for the same account. Not
// persisted: it only orders in-memory snapshots.
StateVersion uint64
}
type ModelContextStore ¶ added in v0.6.0
type NativeResponseResult ¶ added in v0.6.7
type Pool ¶ added in v0.6.0
type Pool struct {
// contains filtered or unexported fields
}
func (*Pool) CooldownScope ¶ added in v0.6.0
CooldownScope identifies whether the retry hint is caused by the whole account or only by the requested model.
func (*Pool) LenRoute ¶ added in v0.6.0
func (p *Pool) LenRoute(q RouteQuery) int
LenRoute counts the candidate set for one route query, so retry attempts match the current pool instead of every registered account.
func (*Pool) MarkClassified ¶ added in v0.6.0
func (p *Pool) MarkClassified(id string, c Classified)
func (*Pool) MarkOK ¶ added in v0.6.0
MarkOK records a success. When model is non-empty, only that model's cooldown and backoff ladder are cleared: a success on model-B must not un-cool a still-rate-limited model-A, and a streaming 200 (headers only) must not discard a mid-stream failure recorded for another model. When model is empty the account is treated as fully healthy: account-wide cooldown, backoff, and all model-scoped state are cleared.
func (*Pool) MergeHealth ¶ added in v0.6.0
func (*Pool) MergeModels ¶ added in v0.6.0
func (*Pool) MergeQuota ¶ added in v0.6.0
func (p *Pool) MergeQuota(id string, quota *QuotaSnapshot)
func (*Pool) Observer ¶ added in v0.6.0
func (p *Pool) Observer() PoolObserver
func (*Pool) PickRoute ¶ added in v0.6.0
func (p *Pool) PickRoute(q RouteQuery) (Item, bool)
PickRoute picks one item. Provider filtering, cooldown, pin, exclusion, and round-robin are applied in that order. The fallback path returns the item with the earliest cooldown so callers can surface a classified error.
func (*Pool) RemoveModel ¶ added in v0.6.0
RemoveModel drops one public ID from a cached catalog so a stale snapshot cannot keep sending traffic to an account that no longer serves the model.
func (*Pool) RetryAfter ¶ added in v0.6.0
RetryAfter reports how long the selected item remains unavailable for a route. PickRoute may return a cooling item as a retry hint; callers must check this value before dispatching the request.
func (*Pool) RoutingStrategy ¶ added in v0.6.0
func (*Pool) SetDropSystemPrompt ¶ added in v0.6.0
SetDropSystemPrompt updates only the request-sanitization flag on a live item. Routing and runtime state stay untouched so the change applies to the next request without disturbing cooldowns or health.
func (*Pool) SetObserver ¶ added in v0.6.0
func (p *Pool) SetObserver(observer PoolObserver)
func (*Pool) SetRoutingStrategy ¶ added in v0.6.0
func (*Pool) SetRuntimeState ¶ added in v0.6.0
type PoolObserver ¶ added in v0.6.0
type PoolObserver func(Item)
PoolObserver receives a cloned Item after a persistable mutation (MarkClassified / MarkOK). The callback is data-only: Pool never accepts *Store, and the Manager persist goroutine is the writer.
type PrepareError ¶ added in v0.6.0
func (*PrepareError) Error ¶ added in v0.6.0
func (e *PrepareError) Error() string
type PrepareInput ¶ added in v0.6.0
type PrepareInput struct {
Context context.Context
Request translate.ChatRequest
NativeRequest *translate.NativeResponsesRequest
Identity auth.Identity
PreferAccount string
SessionHeader string
CrossProviderPool bool
Now time.Time
NewRequestID func() string
ModelContexts ModelContextStore
Catalogs CatalogPreparer
Logs RequestStarter
}
type PreparedRequest ¶ added in v0.6.0
type QuotaSnapshot ¶ added in v0.6.0
type QuotaSnapshot = accounts.QuotaSnapshot
QuotaSnapshot stays an accounts type so store and Account can share it without importing executor. The alias keeps pool field types local.
type RequestStarter ¶ added in v0.6.0
type RequestStarter interface {
Start(entry accounts.RequestLog)
}
type RouteQuery ¶ added in v0.6.0
type RouteQuery struct {
PublicModel string
PreferAccount string
ProviderFilter string
RegionFilter string
AllowedProviders []string
Excluded map[string]struct{}
// Eligible, when set, admits only items that can serve the request's
// protocol (for example native Responses input the chat form cannot
// carry). Nil admits every item.
Eligible func(Item) bool
}
RouteQuery selects candidates for one public model request. Empty fields are not filtered; excluded account IDs are honored before anything else.
type SessionAffinity ¶ added in v0.2.42
type SessionAffinity struct {
// contains filtered or unexported fields
}
SessionAffinity is a bounded process-local LRU. Session bindings are a routing cache, not durable account state: process restarts intentionally clear them.
func NewSessionAffinity ¶ added in v0.2.42
func NewSessionAffinity(ttl time.Duration, capacity int) *SessionAffinity
func (*SessionAffinity) Bind ¶ added in v0.2.42
func (a *SessionAffinity) Bind(key, accountID string)
func (*SessionAffinity) Forget ¶ added in v0.2.42
func (a *SessionAffinity) Forget(key string)
func (*SessionAffinity) Get ¶ added in v0.2.42
func (a *SessionAffinity) Get(key string) (string, bool)
func (*SessionAffinity) RecordEscape ¶ added in v0.2.45
func (a *SessionAffinity) RecordEscape(reason string)
func (*SessionAffinity) Stats ¶ added in v0.2.45
func (a *SessionAffinity) Stats() SessionAffinityStats
type SessionAffinityStats ¶ added in v0.2.45
type SessionAffinityStats struct {
TTLSeconds int64 `json:"ttl_seconds"`
Capacity int `json:"capacity"`
Bindings int `json:"bindings"`
Hits uint64 `json:"hits"`
Misses uint64 `json:"misses"`
Escapes uint64 `json:"escapes"`
Rebindings uint64 `json:"rebindings"`
LastEscapeAt string `json:"last_escape_at,omitempty"`
LastEscapeReason string `json:"last_escape_reason,omitempty"`
LastMissReason string `json:"last_miss_reason,omitempty"`
}
type StreamResult ¶ added in v0.2.6
type StreamResult struct {
Response *http.Response
AccountID string
Provider string
AttemptCount int
TTFBMs int
Routing string
ReasoningLevel string
// NativeResponses marks the body as an upstream OpenAI Responses SSE stream
// that /v1/responses can relay verbatim instead of translating.
NativeResponses bool
}