runtime

package
v0.0.0-...-b2e70c2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 55 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

Index

Constants

View Source
const (
	ChannelHealthHealthy  = "healthy"
	ChannelHealthDegraded = "degraded"
	ChannelHealthCooling  = "cooling"
	ChannelHealthHalfOpen = "half_open"
)
View Source
const (
	LongContextPromptTokenThreshold = 100_000
	VeryLongContextPromptTokens     = 200_000
)
View Source
const (
	LastMessageTypeNone     = "none"
	LastMessageTypeText     = "text"
	LastMessageTypeTools    = "tools"
	LastMessageTypeThinking = "thinking"
)
View Source
const (
	RouteDecisionProbeNormal     = "normal"
	RouteDecisionProbeLastResort = "last_resort"
	RouteDecisionProbeRateLimit  = "rate_limit_retry"
	RouteDecisionProbeEmergency  = "emergency_retry"
)
View Source
const (
	LocalStreamTimeoutFirstByte        = "first_byte"
	LocalStreamTimeoutIdle             = "idle"
	LocalStreamTimeoutAdaptiveInitial  = "adaptive_initial"
	LocalStreamTimeoutAdaptiveProgress = "adaptive_progress"
	LocalStreamTimeoutMaxDuration      = "max_duration"
)
View Source
const FirstByteTraceContextKey = "gateway_first_byte_trace"

FirstByteTraceContextKey stores the request trace in the Gin context so lower-level HTTP and streaming packages can add timing marks without importing the relay handler package.

View Source
const (
	// GPTInitialFailureRetryWindow bounds retries before a GPT response starts.
	GPTInitialFailureRetryWindow = 30 * time.Second
)
View Source
const (
	RoutePoolNameContextKey = "request_route_pool_name"
)
View Source
const StreamUsageRecoveryTimeout = 2 * time.Minute

Variables

This section is empty.

Functions

func AcquireAllCoolingFallback

func AcquireAllCoolingFallback(c *gin.Context, group, model string, requestTypes ...RequestType) bool

AcquireAllCoolingFallback reserves one bounded process-local slot for a request that must use a still-cooling route because no healthy route remains. It waits at most 200 ms so a genuine upstream outage cannot grow a long queue.

func ActiveChannelRequestLeasesForChannels

func ActiveChannelRequestLeasesForChannels(channelIDs []int) (map[int]int, bool)

ActiveChannelRequestLeasesForChannels returns the live cross-Gateway lease count used by admission. It reports false when Redis cannot provide a shared snapshot so callers can fall back to process telemetry.

func ActiveChannelRequests

func ActiveChannelRequests(channelID int) int

ActiveChannelRequests returns the cross-process in-flight count when shared telemetry is available, otherwise it falls back to this process.

func ActiveChannelRequestsForChannels

func ActiveChannelRequestsForChannels(channelIDs []int) map[int]int

ActiveChannelRequestsForChannels returns one aggregated snapshot for the requested channels without issuing one Redis query per Marketplace group.

func ActiveChannelUserRequests

func ActiveChannelUserRequests(channelID, userID int) int

ActiveChannelUserRequests returns this process's in-flight count for one user on one channel. Hard admission uses this value under the same lock.

func AllowRetryAfterChannelAffinityFailure

func AllowRetryAfterChannelAffinityFailure(c *gin.Context)

AllowRetryAfterChannelAffinityFailure clears only the request-local veto. The successful affinity cache entry remains intact for later requests.

func AppendChannelAffinityAdminInfo

func AppendChannelAffinityAdminInfo(c *gin.Context, adminInfo map[string]interface{})

AppendChannelAffinityAdminInfo appends affinity debug data to error log admin metadata.

func AppendRequestConversionFromRequest

func AppendRequestConversionFromRequest(info *RelayInfo, req any)

AppendRequestConversionFromRequest records a request-format conversion onto relay info.

func ApplyAccountRequestAbuse

func ApplyAccountRequestAbuse(userID int, windowEnd int64, evidence string) (gatewayschema.AccountRequestAbuseState, error)

ApplyAccountRequestAbuse persists one episode and synchronizes authentication caches. WindowEnd identifies the end of the three-minute evidence window.

func ApplyChannelAffinityOverrideTemplate

func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]interface{}) (map[string]interface{}, bool)

ApplyChannelAffinityOverrideTemplate merges per-rule override templates onto the selected channel override config.

func ApplyParamOverride

func ApplyParamOverride(jsonData []byte, paramOverride map[string]interface{}, conditionContext map[string]interface{}) ([]byte, error)

func ApplyParamOverrideWithRelayInfo

func ApplyParamOverrideWithRelayInfo(jsonData []byte, info *RelayInfo) ([]byte, error)

func AttachRouteDecisionProfile

func AttachRouteDecisionProfile(c *gin.Context, profile RequestProfile)

func AttachRouteLogInfo

func AttachRouteLogInfo(c *gin.Context, other map[string]interface{})

AttachRouteLogInfo adds a safe Auto summary for users and the complete route decision under administrator-only metadata.

func AutomaticRouteFirstByteTimeout

func AutomaticRouteFirstByteTimeout(c *gin.Context) time.Duration

AutomaticRouteFirstByteTimeout intentionally disables speculative failover after an Auto request has been dispatched. The upstream may continue billable work after the local connection is cancelled.

func BeginChannelRequest

func BeginChannelRequest(channelID int) func()

BeginChannelRequest tracks one process-local in-flight upstream request.

func BuildBillingExprRequestInputFromRequest

func BuildBillingExprRequestInputFromRequest(request dto.Request, headers map[string]string) (billingexpr.RequestInput, error)

func BuildParamOverrideContext

func BuildParamOverrideContext(info *RelayInfo) map[string]interface{}

BuildParamOverrideContext 提供 ApplyParamOverride 可用的上下文信息。 目前内置以下字段:

  • upstream_model/model:始终为通道映射后的上游模型名。
  • original_model:请求最初指定的模型名。
  • request_path:请求路径
  • user_id/user_group/using_group/token_id:当前路由主体的非 PII 标识。
  • is_channel_test:是否为渠道测试请求(同 is_test)。

func ChannelFaultDomain

func ChannelFaultDomain(channelType int, baseURL string) string

ChannelFaultDomain derives a shared transient-failure boundary without relying on channel names, keys, or user-visible configuration.

func ClearChannelAffinityCacheAll

func ClearChannelAffinityCacheAll() int

func ClearChannelAffinityCacheByRuleName

func ClearChannelAffinityCacheByRuleName(ruleName string) (int, error)

func ClearUserStreamFailureCircuit

func ClearUserStreamFailureCircuit(c *gin.Context, modelName string)

ClearUserStreamFailureCircuit removes failure history after a completed stream.

func ConversationPromptHighWater

func ConversationPromptHighWater(statsCtx ChannelAffinityStatsContext, model string) int

ConversationPromptHighWater returns the observed upstream prompt-token high-water mark for a GPT affinity context. The cache key contains only rule, group, model, and an existing hashed affinity fingerprint.

func ConversationPromptHighWaterFromContext

func ConversationPromptHighWaterFromContext(c *gin.Context, model string) int

func CoolChannelModelForUpstreamFailure

func CoolChannelModelForUpstreamFailure(channelID int, model string, requestTypes ...RequestType) bool

CoolChannelModelForUpstreamFailure immediately isolates one failing model route while leaving the channel available for every other model.

func ExcludeFaultDomain

func ExcludeFaultDomain(c *gin.Context, domain string)

ExcludeFaultDomain records an upstream domain that already failed in this request. Subsequent retries must use a different domain when available.

func ExcludeRouteDecisionCandidate

func ExcludeRouteDecisionCandidate(c *gin.Context, reason string)

func ExpandRequestBudget

func ExpandRequestBudget(budget *RequestBudget, attempts int)

ExpandRequestBudget allows a configured Auto pool to visit its remaining groups while preserving the original request deadline.

func FinalizeRequestAudit

func FinalizeRequestAudit(c *gin.Context, info *RelayInfo, apiErr *types.NewAPIError, upstreamStarted, countedInSuccessRate bool)

FinalizeRequestAudit records exactly one terminal outcome per client request. It deliberately does not write a billing log; billing remains owned by the existing ledger and consume-log path.

func FinishRouteDecisionAttempt

func FinishRouteDecisionAttempt(c *gin.Context, success bool, statusCode int, failureClass, stage string)

func GetAPIVersion

func GetAPIVersion(c *gin.Context) string

func GetEffectiveHeaderOverride

func GetEffectiveHeaderOverride(info *RelayInfo) map[string]interface{}

func GetFullRequestURL

func GetFullRequestURL(baseURL string, requestURL string, channelType int) string

func GetLocalRealtimeID

func GetLocalRealtimeID(c *gin.Context) string

func GetPreferredChannel

func GetPreferredChannel(cacheKey string) (int, bool, error)

func GetPreferredChannelByAffinity

func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool)

GetPreferredChannelByAffinity resolves a preferred cached channel for the current request.

func GuessRelayFormatFromRequest

func GuessRelayFormatFromRequest(req any) (types.RelayFormat, bool)

GuessRelayFormatFromRequest infers the protocol format from a typed request payload.

func HandleGroupRatio

func HandleGroupRatio(ctx *gin.Context, relayInfo *RelayInfo) types.GroupRatioInfo

func HasModelBillingConfig

func HasModelBillingConfig(modelName string) bool

func HasRemainingCrossGroupRoute

func HasRemainingCrossGroupRoute(c *gin.Context) bool

HasRemainingCrossGroupRoute reports whether the current automatic route can still move to a later group before client-visible output is committed.

func IncompleteStreamCooldown

func IncompleteStreamCooldown() time.Duration

IncompleteStreamCooldown gives a transient stream failure a short pause before it becomes eligible for a protected half-open recovery request.

func InvalidateChannelAffinityForChannel

func InvalidateChannelAffinityForChannel(channelID int) int

InvalidateChannelAffinityForChannel clears all affinity entries that currently point to a channel. Redis stores the reverse index so disabled channels are invalidated across gateway replicas.

func InvalidateChannelAffinityForCurrentRequest

func InvalidateChannelAffinityForCurrentRequest(c *gin.Context)

InvalidateChannelAffinityForCurrentRequest removes a stale affinity entry before normal routing resumes.

func InvalidatePreferredChannel

func InvalidatePreferredChannel(cacheKey string)

InvalidatePreferredChannel removes one affinity entry. Automatic route pools use this when a short-lived sticky route becomes unhealthy or unavailable.

func IsAdaptiveFaultDomainFailureStatus

func IsAdaptiveFaultDomainFailureStatus(statusCode int) bool

IsAdaptiveFaultDomainFailureStatus identifies failures that reliably signal shared upstream admission pressure. A 502 stream close or a 524 may be a request-local transport interruption after the upstream has accepted work; shrinking the shared admission window for those failures creates a 503 wave for otherwise unrelated requests.

func IsAutoRouteRequest

func IsAutoRouteRequest(c *gin.Context) bool

IsAutoRouteRequest reports whether the request selected an Auto route.

func IsChannelCooling

func IsChannelCooling(channelID int, model string, requestTypes ...RequestType) bool

IsChannelCooling reports whether routing must skip the channel/model pair.

func IsChannelCredentialCooling

func IsChannelCredentialCooling(channelID int) bool

IsChannelCredentialCooling reports a short runtime hold for credentials rejected by an upstream. It never changes the channel's configured status.

func IsFaultDomainCooling

func IsFaultDomainCooling(domain, model string, requestTypes ...RequestType) bool

IsFaultDomainCooling reports whether a domain must be excluded from normal routing. Expired cooling states are deliberately left available for one probe.

func IsFaultDomainExcluded

func IsFaultDomainExcluded(c *gin.Context, domain string) bool

IsFaultDomainExcluded reports whether this request has already failed on the given upstream domain.

func IsImageGenerationRequest

func IsImageGenerationRequest(c *gin.Context) bool

func IsLocalStreamMaxDurationExceeded

func IsLocalStreamMaxDurationExceeded(c *gin.Context) bool

func IsLongContextGPTRequest

func IsLongContextGPTRequest(model string, promptTokens int) bool

IsLongContextGPTRequest reports whether a GPT request needs the long-context reliability policy before its upstream response begins streaming.

func IsLongContextRequest

func IsLongContextRequest(c *gin.Context) bool

func IsResponsesConversationRequest

func IsResponsesConversationRequest(request dto.Request) bool

IsResponsesConversationRequest reports whether a parsed Responses request carries a stable conversation/session signal. The raw key value is never retained; only its presence is used for timeout classification.

func IsSingleChannelRoute

func IsSingleChannelRoute(c *gin.Context) bool

func JoinBaseURLPath

func JoinBaseURLPath(baseURL string, requestPath string) string

JoinBaseURLPath accepts provider base URLs with or without a version prefix. It is used by adapters that build provider-specific paths directly.

func LocalStreamTimeoutReason

func LocalStreamTimeoutReason(c *gin.Context) string

func LongContextTimeoutCooldown

func LongContextTimeoutCooldown() time.Duration

LongContextTimeoutCooldown avoids repeated long-context header timeouts while still permitting a prompt half-open recovery attempt.

func MarkAutoRouteRequest

func MarkAutoRouteRequest(c *gin.Context)

MarkAutoRouteRequest preserves Auto routing intent after an internal group binding replaces the token's original group in the request context.

func MarkAutomaticPool

func MarkAutomaticPool(c *gin.Context)

MarkAutomaticPool records that the selected channel came from the cost and health based automatic pool rather than legacy priority/weight selection.

func MarkChannelAffinityUsed

func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int)

MarkChannelAffinityUsed stores audit metadata after a preferred affinity channel is selected.

func MarkImageGenerationRequest

func MarkImageGenerationRequest(c *gin.Context)

MarkImageGenerationRequest disables text-stream first-output deadlines for requests whose output is rendered media rather than tokens.

func MarkLocalStreamMaxDurationExceeded

func MarkLocalStreamMaxDurationExceeded(c *gin.Context)

MarkLocalStreamMaxDurationExceeded identifies a gateway-enforced total stream duration expiry. It is distinct from an idle timeout or an upstream disconnect and must not affect upstream health scoring.

func MarkLocalStreamTimeout

func MarkLocalStreamTimeout(c *gin.Context, reason string)

MarkLocalStreamTimeout distinguishes gateway-enforced deadlines from an upstream EOF so error classification and health accounting remain accurate.

func MarkLongContextRequest

func MarkLongContextRequest(c *gin.Context, model string, promptTokens int)

MarkLongContextRequest records the request classification for route retries and channel health handling. It stores no request content.

func MarkLongContextRequestWithContinuation

func MarkLongContextRequestWithContinuation(c *gin.Context, model string, promptTokens int, hasConversationState bool)

MarkLongContextRequestWithContinuation classifies a GPT Responses session as long-context before a successful upstream usage sample is available. A prompt_cache_key is itself a stable upstream conversation/session signal; previous_response_id is optional in Codex fork/continue flows.

func MarkRemainingCrossGroupRoutes

func MarkRemainingCrossGroupRoutes(c *gin.Context, remaining int)

MarkRemainingCrossGroupRoutes records how many later groups can still be selected without replaying client-visible output.

func MarkSingleChannelRoute

func MarkSingleChannelRoute(c *gin.Context, single bool)

MarkSingleChannelRoute records whether the selected group/model has no alternative channel. Multiple keys on the selected channel do not change this classification.

func ModelMappedHelper

func ModelMappedHelper(c *gin.Context, info *RelayInfo, request dto.Request) error

func ModelPriceHelper

func ModelPriceHelper(c *gin.Context, info *RelayInfo, promptTokens int, meta *types.TokenCountMeta) (types.PriceData, error)

func ModelPriceHelperPerCall

func ModelPriceHelperPerCall(c *gin.Context, info *RelayInfo) (types.PriceData, error)

func NeedsChannelCredentialRecoveryProbe

func NeedsChannelCredentialRecoveryProbe(channelID int) bool

NeedsChannelCredentialRecoveryProbe reports an expired credential hold that still requires half-open validation before ordinary traffic resumes.

func NewAPIErrorFromParamOverride

func NewAPIErrorFromParamOverride(err *ParamOverrideReturnError) *types.NewAPIError

func NewOutboundJSONBody

func NewOutboundJSONBody(data []byte) (body io.Reader, size int64, closer io.Closer, err error)

NewOutboundJSONBody wraps a marshaled upstream payload into replayable body storage.

func ObserveChannelAffinityUsageCache

func ObserveChannelAffinityUsageCache(statsCtx ChannelAffinityStatsContext, usage *dto.Usage, cachedTokenRateMode string)

func ObserveChannelAffinityUsageCacheByRelayFormat

func ObserveChannelAffinityUsageCacheByRelayFormat(statsCtx ChannelAffinityStatsContext, usage *dto.Usage, relayFormat types.RelayFormat)

func ObserveChannelAffinityUsageCacheByRelayFormatFromContext

func ObserveChannelAffinityUsageCacheByRelayFormatFromContext(c *gin.Context, usage *dto.Usage, relayFormat types.RelayFormat)

ObserveChannelAffinityUsageCacheByRelayFormatFromContext records usage cache stats using the current request context.

func ObserveChannelAffinityUsageCacheFromContext

func ObserveChannelAffinityUsageCacheFromContext(c *gin.Context, usage *dto.Usage, cachedTokenRateMode string)

ObserveChannelAffinityUsageCacheFromContext records usage cache stats using the current request context.

func ObserveConversationPromptHighWater

func ObserveConversationPromptHighWater(statsCtx ChannelAffinityStatsContext, model string, usage *dto.Usage)

ObserveConversationPromptHighWater records only the largest upstream prompt token count seen for an affinity-scoped GPT conversation. It intentionally does not retain request or response content.

func ObserveConversationPromptHighWaterFromContext

func ObserveConversationPromptHighWaterFromContext(c *gin.Context, model string, usage *dto.Usage)

ObserveConversationPromptHighWaterFromContext records the upstream prompt high-water mark needed to classify subsequent Responses deltas correctly.

func PrepareResponsesConversationWindow

func PrepareResponsesConversationWindow(c *gin.Context, info *RelayInfo, body []byte) (optimized []byte, fallback []byte, applied bool, err error)

PrepareResponsesConversationWindow replaces a repeated full-history prefix with previous_response_id plus the new input suffix. It only operates on native stored Responses conversations and keeps the original body for a transparent stale-state fallback.

func RecordAccountRequestSample

func RecordAccountRequestSample(userID, channelID int, model string, input, cache int64)

RecordAccountRequestSample runs after settlement, outside the response path. It keeps bounded five-minute Redis counters, never scans the usage log table.

func RecordAutoGroupLiveSignal

func RecordAutoGroupLiveSignal(c *gin.Context, group string, channelID, inflight, limit int, reason string)

func RecordChannelAffinity

func RecordChannelAffinity(c *gin.Context, channelID int)

RecordChannelAffinity persists the successful channel choice into the affinity cache.

func RecordChannelCacheObservation

func RecordChannelCacheObservation(channelID int, model string, promptTokens, cachedTokens int, requestTypes ...RequestType)

RecordChannelCacheObservation updates the short-window cache hit ratio used by weighted route pools.

func RecordChannelCredentialFailure

func RecordChannelCredentialFailure(channelID int)

RecordChannelCredentialFailure temporarily excludes every model on a channel after an explicit upstream authentication or account rejection.

func RecordChannelCredentialSuccess

func RecordChannelCredentialSuccess(channelID int)

RecordChannelCredentialSuccess advances an active credential circuit. Two successful real requests are required before normal traffic resumes.

func RecordChannelGatewayFailure

func RecordChannelGatewayFailure(channelID int, model string, statusCode int, requestTypes ...RequestType)

RecordChannelGatewayFailure rapidly isolates a model route after two consecutive gateway failures. A single transient failure remains degraded so healthy traffic can demonstrate that the route is still usable.

func RecordChannelGatewayFailureForRequest

func RecordChannelGatewayFailureForRequest(channelID int, model, requestID string, statusCode int, requestTypes ...RequestType)

RecordChannelGatewayFailureForRequest applies gateway-failure health accounting once per downstream request while retaining status-specific cooldowns for genuinely separate failures.

func RecordChannelModelUnavailable

func RecordChannelModelUnavailable(channelID int, model string, requestID string, requestTypes ...RequestType) bool

RecordChannelModelUnavailable opens the model circuit only after five distinct request IDs fail consecutively. Repeated retries of one request count once so a single request cannot exhaust the error budget.

func RecordChannelRetryableFailure

func RecordChannelRetryableFailure(channelID int, model string, requestTypes ...RequestType)

RecordChannelRetryableFailure advances the shared circuit for a retryable upstream error.

func RecordChannelRetryableFailureForRequest

func RecordChannelRetryableFailureForRequest(channelID int, model, requestID string, shortCooldown time.Duration, requestTypes ...RequestType)

RecordChannelRetryableFailureForRequest records at most one transient failure for a channel/model pair per downstream request. A gateway retry is not independent evidence that the route became unhealthy.

func RecordChannelRetryableFailureWithCooldown

func RecordChannelRetryableFailureWithCooldown(channelID int, model string, shortCooldown time.Duration, requestTypes ...RequestType)

RecordChannelRetryableFailureWithCooldown applies a short model-level cooldown for a transient failure. Repeated failures in the rolling window still escalate to the longer circuit cooldown.

func RecordChannelSoftFailureForRequest

func RecordChannelSoftFailureForRequest(channelID int, model, requestID string, requestTypes ...RequestType)

RecordChannelSoftFailureForRequest updates shared reliability observations without degrading or cooling the route. Auto routing uses it for short-window scoring while keeping transient circuit state isolated to one user.

func RecordChannelSuccess

func RecordChannelSuccess(channelID int, model string, ttft time.Duration, requestTypes ...RequestType)

RecordChannelSuccess requires two successful half-open probes before restoring normal traffic. Normal healthy routes continue to recover immediately.

func RecordFaultDomainChannelFailure

func RecordFaultDomainChannelFailure(domain, model string, channelID int, requestID string, cooldown time.Duration, requestTypes ...RequestType) bool

RecordFaultDomainChannelFailure promotes a transient failure to provider scope only after the same model fails on three distinct channels in a short window. A single API key or route group therefore cools only itself, while a genuine shared-provider incident still prevents a retry storm.

func RecordFaultDomainRetryableFailure

func RecordFaultDomainRetryableFailure(domain, model, requestID string, cooldown time.Duration, requestTypes ...RequestType)

RecordFaultDomainRetryableFailure opens a domain circuit only after three distinct transient request failures. A failed half-open probe increases the adaptive backoff, while retries of the same request count only once.

func RecordFaultDomainSuccess

func RecordFaultDomainSuccess(domain, model string, requestTypes ...RequestType)

RecordFaultDomainSuccess advances a half-open domain circuit. Two successful probes are required before the domain becomes a normal routing candidate.

func RecordPreferredChannel

func RecordPreferredChannel(cacheKey string, channelID int, ttlSeconds int) error

func RecordResponsesConversationWindow

func RecordResponsesConversationWindow(c *gin.Context, info *RelayInfo, raw []byte)

RecordResponsesConversationWindow advances the short-lived conversation anchor only after a completed upstream response has been observed.

func RecordRouteDecisionCandidate

func RecordRouteDecisionCandidate(c *gin.Context, order int, group, status, reason string, channelID int)

RecordRouteDecisionCandidate records one Auto candidate's preflight state.

func RecordRouteDecisionRetry

func RecordRouteDecisionRetry(c *gin.Context)

func RecordUserChannelGatewayFailureForRequest

func RecordUserChannelGatewayFailureForRequest(c *gin.Context, channelID int, model, requestID string, statusCode int, requestTypes ...RequestType)

RecordUserChannelGatewayFailureForRequest records a fast gateway failure for one user.

func RecordUserChannelRetryableFailureForRequest

func RecordUserChannelRetryableFailureForRequest(c *gin.Context, channelID int, model, requestID string, cooldown time.Duration, requestTypes ...RequestType)

RecordUserChannelRetryableFailureForRequest records a transient channel failure for one user.

func RecordUserChannelSuccess

func RecordUserChannelSuccess(c *gin.Context, channelID int, model string, ttft time.Duration, requestTypes ...RequestType)

RecordUserChannelSuccess advances a user channel circuit without changing other users.

func RecordUserFaultDomainFailure

func RecordUserFaultDomainFailure(c *gin.Context, domain, model, requestID string, cooldown time.Duration, requestTypes ...RequestType)

RecordUserFaultDomainFailure records a transient provider-domain failure for one user.

func RecordUserFaultDomainSuccess

func RecordUserFaultDomainSuccess(c *gin.Context, domain, model string, requestTypes ...RequestType)

RecordUserFaultDomainSuccess advances a user provider-domain circuit.

func ReleaseAllCoolingFallbacks

func ReleaseAllCoolingFallbacks(c *gin.Context)

ReleaseAllCoolingFallbacks releases every fallback slot reserved by a request. It is safe to call from both middleware and a relay cleanup defer.

func ReleaseChannelProbe

func ReleaseChannelProbe(channelID int, model string, requestTypes ...RequestType)

ReleaseChannelProbe returns a slot when a paired fault-domain probe could not be acquired. It prevents partial selection from consuming the retry budget until the lease expires.

func ReleaseFaultDomainProbe

func ReleaseFaultDomainProbe(domain, model string, requestTypes ...RequestType)

ReleaseFaultDomainProbe returns a slot when a paired channel probe cannot be acquired, preventing a partial fault-domain reservation from leaking.

func ReleaseUserChannelProbe

func ReleaseUserChannelProbe(c *gin.Context, channelID int, model string, requestTypes ...RequestType)

ReleaseUserChannelProbe releases a partially acquired channel lease.

func ReleaseUserFaultDomainProbe

func ReleaseUserFaultDomainProbe(c *gin.Context, domain, model string, requestTypes ...RequestType)

ReleaseUserFaultDomainProbe releases a partially acquired domain lease.

func RemainingAutomaticFirstByteWait

func RemainingAutomaticFirstByteWait(c *gin.Context) time.Duration

func RemoveDisabledFields

func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings, channelPassThroughEnabled bool) ([]byte, error)

RemoveDisabledFields 从请求 JSON 数据中移除渠道设置中禁用的字段 service_tier: 服务层级字段,可能导致额外计费(OpenAI、Claude、Responses API 支持) inference_geo: Claude 数据驻留推理区域字段(仅 Claude 支持,默认过滤) speed: Claude 推理速度模式字段(仅 Claude 支持,默认过滤) store: 数据存储授权字段,涉及用户隐私(仅 OpenAI、Responses API 支持,默认允许透传,禁用后可能导致 Codex 无法使用) safety_identifier: 安全标识符,用于向 OpenAI 报告违规用户(仅 OpenAI 支持,涉及用户隐私) stream_options.include_obfuscation: 响应流混淆控制字段(仅 OpenAI Responses API 支持)

func RemoveGeminiDisabledFields

func RemoveGeminiDisabledFields(jsonData []byte) ([]byte, error)

RemoveGeminiDisabledFields removes disabled fields from Gemini request JSON data Currently supports removing functionResponse.id field which Vertex AI does not support

func RequestBudgetStartTime

func RequestBudgetStartTime(requestStartedAt, validatedAt time.Time, bodySize int64) time.Time

RequestBudgetStartTime keeps slow client uploads from consuming the retry budget reserved for upstream processing. Only genuinely large bodies use the post-validation start; small requests retain the original end-to-end deadline semantics.

func ResetChannelAffinityCacheForTest

func ResetChannelAffinityCacheForTest() error

func ResetChannelAffinityUsageCacheStatsForTest

func ResetChannelAffinityUsageCacheStatsForTest() error

func ResetConversationPromptHighWaterForTest

func ResetConversationPromptHighWaterForTest() error

func ResolveIncomingBillingExprRequestInput

func ResolveIncomingBillingExprRequestInput(c *gin.Context, info *RelayInfo) (billingexpr.RequestInput, error)

func RetryableFailureCooldown

func RetryableFailureCooldown(statusCode int) time.Duration

RetryableFailureCooldown selects a short circuit duration without exposing channel-specific rules. Gateway timeouts need a brief pause, while rate limits still recover more slowly than transient upstream failures.

func SelectRouteDecisionCandidate

func SelectRouteDecisionCandidate(c *gin.Context, group string, channelID int, affinityHit bool)

func ServiceTierMultiplier

func ServiceTierMultiplier(tier string) int

Codex sends Fast as priority and UltraFast as ultrafast. Keep the multiplier separate from group pricing so retries and subscription conversion cannot accidentally apply it twice.

func SetRouteDecisionProbeMode

func SetRouteDecisionProbeMode(c *gin.Context, mode string)

SetRouteDecisionProbeMode records the recovery probe path used for this request. It is emitted only in administrator audit metadata.

func ShouldSkipRetryAfterChannelAffinityFailure

func ShouldSkipRetryAfterChannelAffinityFailure(c *gin.Context) bool

ShouldSkipRetryAfterChannelAffinityFailure reports whether affinity policy disables retry for this request.

func SingleUsedChannelID

func SingleUsedChannelID(c *gin.Context) (int, bool)

SingleUsedChannelID returns the channel ID when every recorded attempt used the same channel. Repeated attempts and multi-key selection remain one route.

func StartAutomaticFirstByteWait

func StartAutomaticFirstByteWait(c *gin.Context) time.Duration

StartAutomaticFirstByteWait starts one clock for both response headers and semantic output. Each upstream attempt replaces the previous deadline.

func StartRequestAudit

func StartRequestAudit(c *gin.Context, model, group string)

StartRequestAudit creates the canonical request-level row. It is best effort and asynchronous so the audit path does not add a database round trip to the API hot path. Finalization uses an upsert and remains correct if it wins the race with this initial insert.

func StartRouteDecision

func StartRouteDecision(c *gin.Context, model string, requestedGroup string)

func StartRouteDecisionAttempt

func StartRouteDecisionAttempt(c *gin.Context, retryIndex, channelID int, faultDomain string)

func StreamAdaptiveInitialTimeoutForRequest

func StreamAdaptiveInitialTimeoutForRequest(c *gin.Context, model string, promptTokens int) time.Duration

StreamAdaptiveInitialTimeoutForRequest bounds the wait for the first semantic event on a long-context GPT stream before progress-based renewal becomes active.

func StreamAdaptiveProgressTimeoutForRequest

func StreamAdaptiveProgressTimeoutForRequest(c *gin.Context, model string, promptTokens int) time.Duration

StreamAdaptiveProgressTimeoutForRequest returns the allowed quiet period after a long-context GPT stream has started. A semantic progress signal resets this window; image generation remains on its own long-running policy.

func StreamFirstOutputTimeoutForRequest

func StreamFirstOutputTimeoutForRequest(c *gin.Context, model string, promptTokens int) time.Duration

StreamFirstOutputTimeoutForRequest returns an optional wait for a GPT stream to become useful. It is disabled by default so an upstream that is still restoring conversation state can apply its own timeout and recovery policy.

func StreamMaxDuration

func StreamMaxDuration(model string, promptTokens int) time.Duration

StreamMaxDuration returns the absolute upstream stream budget. GPT requests use a shorter normal budget and a longer budget for large prompts; other protocols retain their existing idle-time behavior until they gain a protocol-specific total-duration policy.

func StreamMaxDurationForRequest

func StreamMaxDurationForRequest(c *gin.Context, model string, promptTokens int) time.Duration

StreamMaxDurationForRequest applies the same tiering as StreamMaxDuration, including an affinity-scoped upstream usage high-water mark for Responses requests that only carry a small delta locally.

func TryBeginChannelRequest

func TryBeginChannelRequest(channelID, limit int) (func(), bool)

TryBeginChannelRequest reserves one process-local channel slot. A positive limit is enforced atomically; zero disables the per-channel gate for legacy and official channels.

func TryStartChannelCredentialRecoveryProbe

func TryStartChannelCredentialRecoveryProbe(channelID int) bool

TryStartChannelCredentialRecoveryProbe permits exactly one request after a credential hold expires. It prevents a recovered channel from receiving a burst before its upstream account state is known again.

func TryStartChannelEmergencyRetryProbe

func TryStartChannelEmergencyRetryProbe(channelID int, model string, requestTypes ...RequestType) bool

TryStartChannelEmergencyRetryProbe admits a second bounded probe slot for a retry after a transient upstream failure. Cooling remains in force for normal route selection; only the already-failing request can use this slot.

func TryStartChannelLastResortProbe

func TryStartChannelLastResortProbe(channelID int, model string, requestTypes ...RequestType) bool

TryStartChannelLastResortProbe reserves a cooling channel for one real request when a route pool has no healthy candidate left. The normal recovery path waits for CoolingUntil; this path retains the same short lease but may probe earlier, preventing an all-cooling pool from becoming a hard outage.

func TryStartChannelRecoveryProbe

func TryStartChannelRecoveryProbe(channelID int, model string, requestTypes ...RequestType) bool

TryStartChannelRecoveryProbe reserves a single expired circuit for a real request. The lease prevents a burst of concurrent callers from reopening it.

func TryStartFaultDomainEmergencyRetryProbe

func TryStartFaultDomainEmergencyRetryProbe(domain, model string, requestTypes ...RequestType) bool

TryStartFaultDomainEmergencyRetryProbe admits one additional bounded probe slot for a transient retry without reopening normal domain traffic.

func TryStartFaultDomainLastResortProbe

func TryStartFaultDomainLastResortProbe(domain, model string, requestTypes ...RequestType) bool

TryStartFaultDomainLastResortProbe reserves one cooling fault domain for a real request when every route-pool candidate is cooling. The lease keeps a shared upstream from receiving a concurrent recovery burst.

func TryStartFaultDomainRecoveryProbe

func TryStartFaultDomainRecoveryProbe(domain, model string, requestTypes ...RequestType) bool

TryStartFaultDomainRecoveryProbe reserves one expired domain circuit for a real request, preventing same-domain channels from probing concurrently.

func TryStartUserChannelEmergencyProbe

func TryStartUserChannelEmergencyProbe(c *gin.Context, channelID int, model string, requestTypes ...RequestType) bool

TryStartUserChannelEmergencyProbe admits one bounded retry probe.

func TryStartUserChannelLastResortProbe

func TryStartUserChannelLastResortProbe(c *gin.Context, channelID int, model string, requestTypes ...RequestType) bool

TryStartUserChannelLastResortProbe keeps one route available during cooling.

func TryStartUserChannelRecoveryProbe

func TryStartUserChannelRecoveryProbe(c *gin.Context, channelID int, model string, requestTypes ...RequestType) bool

TryStartUserChannelRecoveryProbe reserves one expired user channel circuit.

func TryStartUserFaultDomainEmergencyProbe

func TryStartUserFaultDomainEmergencyProbe(c *gin.Context, domain, model string, requestTypes ...RequestType) bool

TryStartUserFaultDomainEmergencyProbe admits one bounded domain retry probe.

func TryStartUserFaultDomainLastResortProbe

func TryStartUserFaultDomainLastResortProbe(c *gin.Context, domain, model string, requestTypes ...RequestType) bool

TryStartUserFaultDomainLastResortProbe keeps one domain available during cooling.

func TryStartUserFaultDomainRecoveryProbe

func TryStartUserFaultDomainRecoveryProbe(c *gin.Context, domain, model string, requestTypes ...RequestType) bool

TryStartUserFaultDomainRecoveryProbe reserves one expired user domain circuit.

func UpdateRouteDecisionBudget

func UpdateRouteDecisionBudget(c *gin.Context, budget *RequestBudget)

func UpdateRouteDecisionCandidates

func UpdateRouteDecisionCandidates(c *gin.Context, count int)

func UserStreamFailureRetryAfter

func UserStreamFailureRetryAfter(c *gin.Context, modelName string) (int, bool)

UserStreamFailureRetryAfter returns a temporary retry delay for repeated, incomplete streams.

func UsesIsolatedRouteHealth

func UsesIsolatedRouteHealth(c *gin.Context) bool

UsesIsolatedRouteHealth reports whether transient route health must avoid shared route state. Direct group requests need the same user isolation as Auto routing: one user's transient upstream failure must not make another user's request unroutable. Anonymous Auto requests retain their previous behavior and do not create shared cooldowns.

func ValidateBasicTaskRequest

func ValidateBasicTaskRequest(c *gin.Context, info *RelayInfo, action string) *dto.TaskError

func ValidateMultipartDirect

func ValidateMultipartDirect(c *gin.Context, info *RelayInfo) *dto.TaskError

func WithOutboundHTTPTrace

func WithOutboundHTTPTrace(req *http.Request, timing *FirstByteTrace, requestBodyBytes int64) *http.Request

WithOutboundHTTPTrace attaches request-level connection and upload timing without recording the upstream address, request content, or credentials.

func WssError

func WssError(c *gin.Context, ws *websocket.Conn, openAIError types.OpenAIError)

func WssObject

func WssObject(c *gin.Context, ws *websocket.Conn, object interface{}) error

Types

type AutoGroupLiveSignal

type AutoGroupLiveSignal struct {
	Group            string `json:"group"`
	ChannelID        int    `json:"channel_id"`
	Inflight         int    `json:"inflight"`
	ConcurrencyLimit int    `json:"concurrency_limit"`
	Reason           string `json:"reason"`
}

type BuildInToolInfo

type BuildInToolInfo struct {
	ToolName          string
	CallCount         int
	SearchContextSize string
}

type ChannelAffinityCacheStats

type ChannelAffinityCacheStats struct {
	Enabled       bool           `json:"enabled"`
	Total         int            `json:"total"`
	Unknown       int            `json:"unknown"`
	ByRuleName    map[string]int `json:"by_rule_name"`
	CacheCapacity int            `json:"cache_capacity"`
	CacheAlgo     string         `json:"cache_algo"`
}

func GetChannelAffinityCacheStats

func GetChannelAffinityCacheStats() ChannelAffinityCacheStats

type ChannelAffinityStatsContext

type ChannelAffinityStatsContext struct {
	RuleName       string
	UsingGroup     string
	KeyFingerprint string
	TTLSeconds     int64
}

func GetChannelAffinityStatsContext

func GetChannelAffinityStatsContext(c *gin.Context) (ChannelAffinityStatsContext, bool)

GetChannelAffinityStatsContext extracts cache observation metadata from a request context.

type ChannelAffinityUsageCacheCounters

type ChannelAffinityUsageCacheCounters struct {
	CachedTokenRateMode  string `json:"cached_token_rate_mode"`
	Hit                  int64  `json:"hit"`
	Total                int64  `json:"total"`
	WindowSeconds        int64  `json:"window_seconds"`
	PromptTokens         int64  `json:"prompt_tokens"`
	CompletionTokens     int64  `json:"completion_tokens"`
	TotalTokens          int64  `json:"total_tokens"`
	CachedTokens         int64  `json:"cached_tokens"`
	PromptCacheHitTokens int64  `json:"prompt_cache_hit_tokens"`
	LastSeenAt           int64  `json:"last_seen_at"`
}

type ChannelAffinityUsageCacheStats

type ChannelAffinityUsageCacheStats struct {
	RuleName             string `json:"rule_name"`
	UsingGroup           string `json:"using_group"`
	KeyFingerprint       string `json:"key_fp"`
	CachedTokenRateMode  string `json:"cached_token_rate_mode"`
	Hit                  int64  `json:"hit"`
	Total                int64  `json:"total"`
	WindowSeconds        int64  `json:"window_seconds"`
	PromptTokens         int64  `json:"prompt_tokens"`
	CompletionTokens     int64  `json:"completion_tokens"`
	TotalTokens          int64  `json:"total_tokens"`
	CachedTokens         int64  `json:"cached_tokens"`
	PromptCacheHitTokens int64  `json:"prompt_cache_hit_tokens"`
	LastSeenAt           int64  `json:"last_seen_at"`
}

func GetChannelAffinityUsageCacheStats

func GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFp string) ChannelAffinityUsageCacheStats

type ChannelConcurrencyAdmission

type ChannelConcurrencyAdmission uint8

ChannelConcurrencyAdmission describes why a channel slot was accepted or rejected. Callers must not treat a Redis dependency failure as real channel capacity exhaustion because it must not affect channel health or cooldowns.

const (
	ChannelConcurrencyAdmitted ChannelConcurrencyAdmission = iota
	ChannelConcurrencyCapacityReached
	ChannelConcurrencyDependencyUnavailable
	AccountRequestRPMReached
	AccountRequestDisabled
)

func TryBeginChannelRequestForUser

func TryBeginChannelRequestForUser(
	channelID, userID, totalLimit, userLimit int,
) (func(), ChannelConcurrencyAdmission)

TryBeginChannelRequestForUser atomically enforces both the channel-wide and per-user Marketplace limits across Gateway instances. Zero disables the corresponding limit.

func TryBeginUserRequest

func TryBeginUserRequest(ctx context.Context, userID int) (context.Context, func(), ChannelConcurrencyAdmission)

TryBeginUserRequest enforces an operator account restriction independently of the token's group, route and bypass flag. The existing atomic lease scripts are reused with a separate namespace; no channel telemetry is affected.

type ChannelHealth

type ChannelHealth struct {
	ChannelID                    int                  `json:"channel_id"`
	Model                        string               `json:"model"`
	RequestType                  RequestType          `json:"request_type"`
	State                        string               `json:"state"`
	ConsecutiveRetryableFailures int                  `json:"consecutive_retryable_failures"`
	RecoveryProbeSuccesses       int                  `json:"recovery_probe_successes"`
	RecoveryProbeUntil           time.Time            `json:"recovery_probe_until"`
	RecoveryProbeSlots           int                  `json:"recovery_probe_slots,omitempty"`
	CoolingUntil                 time.Time            `json:"cooling_until"`
	SuccessRate2m                float64              `json:"success_rate_2m"`
	SuccessRate5m                float64              `json:"success_rate_5m"`
	SuccessRate15m               float64              `json:"success_rate_15m"`
	TTFTEWMAMilliseconds         float64              `json:"ttft_ewma_ms"`
	TTFTSamples                  int                  `json:"ttft_samples"`
	TTFTP50Milliseconds          float64              `json:"ttft_p50_ms"`
	TTFTP95Milliseconds          float64              `json:"ttft_p95_ms"`
	CacheHitRate5m               float64              `json:"cache_hit_rate_5m"`
	TTFTRecentMilliseconds       []int64              `json:"ttft_recent_ms"`
	LastSuccessAt                time.Time            `json:"last_success_at"`
	LastFailureAt                time.Time            `json:"last_failure_at"`
	LastFailureRequestID         string               `json:"last_failure_request_id"`
	FaultDomainFailures          []FaultDomainFailure `json:"fault_domain_failures,omitempty"`

	Window2StartedAt  time.Time `json:"window_2_started_at"`
	Window2Requests   int       `json:"window_2_requests"`
	Window2Successes  int       `json:"window_2_successes"`
	Window5StartedAt  time.Time `json:"window_5_started_at"`
	Window5Requests   int       `json:"window_5_requests"`
	Window5Successes  int       `json:"window_5_successes"`
	Window15StartedAt time.Time `json:"window_15_started_at"`
	Window15Requests  int       `json:"window_15_requests"`
	Window15Successes int       `json:"window_15_successes"`
}

ChannelHealth captures the shared routing health for one channel/model pair. It deliberately excludes provider credentials and other user-visible details.

func GetChannelHealth

func GetChannelHealth(channelID int, model string, requestTypes ...RequestType) (ChannelHealth, bool)

GetChannelHealth returns the last shared health state for a channel/model pair.

func GetFaultDomainHealth

func GetFaultDomainHealth(domain, model string, requestTypes ...RequestType) (ChannelHealth, bool)

GetFaultDomainHealth returns transient health shared by channels using the same provider type and upstream host for one model.

func GetUserChannelHealth

func GetUserChannelHealth(c *gin.Context, channelID int, model string, requestTypes ...RequestType) (ChannelHealth, bool)

GetUserChannelHealth returns transient channel health isolated to one user.

func GetUserFaultDomainHealth

func GetUserFaultDomainHealth(c *gin.Context, domain, model string, requestTypes ...RequestType) (ChannelHealth, bool)

GetUserFaultDomainHealth returns transient provider-domain health isolated to one user.

type ChannelMeta

type ChannelMeta struct {
	ChannelType               int
	ChannelId                 int
	ChannelScope              string
	MarketplaceEgress         bool
	ChannelIsMultiKey         bool
	ChannelMultiKeyIndex      int
	ChannelBaseUrl            string
	ApiType                   int
	ApiVersion                string
	ApiKey                    string
	Organization              string
	ChannelCreateTime         int64
	ParamOverride             map[string]interface{}
	HeadersOverride           map[string]interface{}
	ChannelSetting            dto.ChannelSettings
	ChannelOtherSettings      dto.ChannelOtherSettings
	UpstreamModelName         string
	IsModelMapped             bool
	SupportStreamOptions      bool // 是否支持流式选项
	ResponsesCapabilities     gatewayschema.ResponsesCapabilities
	MultiplierCardSupported   bool
	CreditPackSupported       bool
	MultiplierCardUserEnabled bool
}

type ClaudeConvertInfo

type ClaudeConvertInfo struct {
	LastMessagesType string
	Index            int
	Usage            *dto.Usage
	FinishReason     string
	Done             bool

	ToolCallBaseIndex      int
	ToolCallMaxIndexOffset int
}

type ConditionOperation

type ConditionOperation struct {
	Path           string      `json:"path"`             // JSON路径
	Mode           string      `json:"mode"`             // full, prefix, suffix, contains, gt, gte, lt, lte
	Value          interface{} `json:"value"`            // 匹配的值
	Invert         bool        `json:"invert"`           // 反选功能,true表示取反结果
	PassMissingKey bool        `json:"pass_missing_key"` // 未获取到json key时的行为
}

type FaultDomainConcurrencySnapshot

type FaultDomainConcurrencySnapshot struct {
	Domain     string
	Scope      string
	Model      string
	Active     int
	Limit      int // deprecated shared limit; always zero because admission is per user
	UserActive int
	UserLimit  int
}

FaultDomainConcurrencySnapshot is internal telemetry for route audits and tests.

func TryAcquireFaultDomainSlot

func TryAcquireFaultDomainSlot(domain, model string, requestTypes ...RequestType) (release func(success bool, statusCode int), acquired bool, snapshot FaultDomainConcurrencySnapshot)

TryAcquireFaultDomainSlot reserves one in-flight upstream request. The lease must be released after the upstream attempt completes. This legacy wrapper uses one shared anonymous user key; relay requests should call TryAcquireFaultDomainSlotForUser instead.

func TryAcquireFaultDomainSlotForUser

func TryAcquireFaultDomainSlotForUser(domain, scope, model string, userID int, requestTypes ...RequestType) (release func(success bool, statusCode int), acquired bool, snapshot FaultDomainConcurrencySnapshot)

TryAcquireFaultDomainSlotForUser reserves one in-flight upstream request. Admission and adaptive capacity are tracked per user. A provider fault domain is still used for health/cooldown scope, but never as a shared concurrency ceiling.

type FaultDomainFailure

type FaultDomainFailure struct {
	ChannelID  int       `json:"channel_id"`
	OccurredAt time.Time `json:"occurred_at"`
}

FaultDomainFailure records the last transient failure observed for one channel inside a provider fault domain. It is only used for scope detection.

type FirstByteTrace

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

FirstByteTrace separates gateway work from the wait for the first upstream stream event. It deliberately stores no request content or upstream identity.

func NewFirstByteTrace

func NewFirstByteTrace(startedAt time.Time) *FirstByteTrace

func (*FirstByteTrace) AddWalletQueueWaitDuration

func (t *FirstByteTrace) AddWalletQueueWaitDuration(duration time.Duration)

AddWalletQueueWaitDuration records only initial relay wallet reservation queue waits, including cancellation. SQL, settlement and refund are excluded.

func (*FirstByteTrace) BodyReadDoneTime

func (t *FirstByteTrace) BodyReadDoneTime() time.Time

BodyReadDoneTime returns the instant the client request body was fully materialized by the gateway. It is used as the origin for latency metrics that should exclude downstream upload time.

func (*FirstByteTrace) MarkAdmitted

func (t *FirstByteTrace) MarkAdmitted()

func (*FirstByteTrace) MarkBillingReserveDone

func (t *FirstByteTrace) MarkBillingReserveDone()

func (*FirstByteTrace) MarkBillingReserveStarted

func (t *FirstByteTrace) MarkBillingReserveStarted()

func (*FirstByteTrace) MarkBodyReadDone

func (t *FirstByteTrace) MarkBodyReadDone()

func (*FirstByteTrace) MarkBodyReadStarted

func (t *FirstByteTrace) MarkBodyReadStarted()

func (*FirstByteTrace) MarkChannelAdmissionDone

func (t *FirstByteTrace) MarkChannelAdmissionDone()

func (*FirstByteTrace) MarkChannelAdmissionStarted

func (t *FirstByteTrace) MarkChannelAdmissionStarted()

func (*FirstByteTrace) MarkChannelMetaDone

func (t *FirstByteTrace) MarkChannelMetaDone()

func (*FirstByteTrace) MarkChannelMetaStarted

func (t *FirstByteTrace) MarkChannelMetaStarted()

func (*FirstByteTrace) MarkFaultDomainAdmissionDone

func (t *FirstByteTrace) MarkFaultDomainAdmissionDone()

func (*FirstByteTrace) MarkFaultDomainAdmissionStarted

func (t *FirstByteTrace) MarkFaultDomainAdmissionStarted()

func (*FirstByteTrace) MarkFirstEvent

func (t *FirstByteTrace) MarkFirstEvent()

func (*FirstByteTrace) MarkFirstFlush

func (t *FirstByteTrace) MarkFirstFlush()

func (*FirstByteTrace) MarkFirstSemanticEvent

func (t *FirstByteTrace) MarkFirstSemanticEvent()

func (*FirstByteTrace) MarkFirstSemanticReadAt

func (t *FirstByteTrace) MarkFirstSemanticReadAt(receivedAt time.Time, isText bool)

MarkFirstSemanticReadAt records when the scanner received the first model-visible SSE frame, before handler scheduling and JSON decoding.

func (*FirstByteTrace) MarkFirstTextEvent

func (t *FirstByteTrace) MarkFirstTextEvent()

func (*FirstByteTrace) MarkFirstTextReadAt

func (t *FirstByteTrace) MarkFirstTextReadAt(receivedAt time.Time)

MarkFirstTextReadAt records when the scanner received the first visible output-text delta, excluding reasoning and lifecycle frames.

func (*FirstByteTrace) MarkHeadersFlush

func (t *FirstByteTrace) MarkHeadersFlush()

func (*FirstByteTrace) MarkJSONDecodeDone

func (t *FirstByteTrace) MarkJSONDecodeDone()

func (*FirstByteTrace) MarkJSONDecodeStarted

func (t *FirstByteTrace) MarkJSONDecodeStarted()

func (*FirstByteTrace) MarkModelPriceDone

func (t *FirstByteTrace) MarkModelPriceDone()

func (*FirstByteTrace) MarkModelPriceStarted

func (t *FirstByteTrace) MarkModelPriceStarted()

func (*FirstByteTrace) MarkOutboundHTTPVersion

func (t *FirstByteTrace) MarkOutboundHTTPVersion(major, minor int)

MarkOutboundHTTPVersion records the protocol selected for the upstream hop.

func (*FirstByteTrace) MarkPreflightDone

func (t *FirstByteTrace) MarkPreflightDone()

func (*FirstByteTrace) MarkPromptAuditDone

func (t *FirstByteTrace) MarkPromptAuditDone()

func (*FirstByteTrace) MarkPromptAuditStarted

func (t *FirstByteTrace) MarkPromptAuditStarted()

func (*FirstByteTrace) MarkPromptSensitiveDone

func (t *FirstByteTrace) MarkPromptSensitiveDone()

func (*FirstByteTrace) MarkPromptSensitiveStarted

func (t *FirstByteTrace) MarkPromptSensitiveStarted()

func (*FirstByteTrace) MarkRelayInfoGenerationDone

func (t *FirstByteTrace) MarkRelayInfoGenerationDone()

func (*FirstByteTrace) MarkRelayInfoGenerationStarted

func (t *FirstByteTrace) MarkRelayInfoGenerationStarted()

func (*FirstByteTrace) MarkRelayInfoReady

func (t *FirstByteTrace) MarkRelayInfoReady()

func (*FirstByteTrace) MarkRequestBodyFastPath

func (t *FirstByteTrace) MarkRequestBodyFastPath()

MarkRequestBodyFastPath records that the validated request body was reused without protocol conversion or JSON re-marshalling.

func (*FirstByteTrace) MarkRequestBodyRestoreDone

func (t *FirstByteTrace) MarkRequestBodyRestoreDone()

func (*FirstByteTrace) MarkRequestBodyRestoreStarted

func (t *FirstByteTrace) MarkRequestBodyRestoreStarted()

func (*FirstByteTrace) MarkRequestConversionDone

func (t *FirstByteTrace) MarkRequestConversionDone()

func (*FirstByteTrace) MarkRequestValidated

func (t *FirstByteTrace) MarkRequestValidated()

func (*FirstByteTrace) MarkRouteSelected

func (t *FirstByteTrace) MarkRouteSelected()

func (*FirstByteTrace) MarkUpstreamRequestReady

func (t *FirstByteTrace) MarkUpstreamRequestReady()

func (*FirstByteTrace) MarkUpstreamResponseHeaders

func (t *FirstByteTrace) MarkUpstreamResponseHeaders()

func (*FirstByteTrace) MarkUpstreamStart

func (t *FirstByteTrace) MarkUpstreamStart()

func (*FirstByteTrace) ProgressSnapshot

func (t *FirstByteTrace) ProgressSnapshot(now time.Time) map[string]int64

ProgressSnapshot returns completed stages even when a request failed before semantic output. The current elapsed values make no-output failures diagnosable without recording request content or credentials.

func (*FirstByteTrace) Snapshot

func (t *FirstByteTrace) Snapshot() map[string]int64

Snapshot returns millisecond durations suitable for operational logs.

type HasImage

type HasImage interface {
	HasImage() bool
}

type HasPrompt

type HasPrompt interface {
	GetPrompt() string
}

type MigrationCapability

type MigrationCapability string
const (
	MigrationUnbound            MigrationCapability = "unbound"
	MigrationCacheAffinity      MigrationCapability = "cache_affinity"
	MigrationUpstreamStateBound MigrationCapability = "upstream_state_bound"
)

type OpenRouterRequestReasoning

type OpenRouterRequestReasoning struct {
	Enabled   bool   `json:"enabled"`
	Effort    string `json:"effort,omitempty"`
	MaxTokens int    `json:"max_tokens,omitempty"`
	Exclude   bool   `json:"exclude,omitempty"`
}

type ParamOperation

type ParamOperation struct {
	Path       string               `json:"path"`
	Mode       string               `json:"mode"` // delete, set, move, copy, prepend, append, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, regex_replace, return_error, prune_objects, set_header, delete_header, copy_header, move_header, pass_headers, sync_fields
	Value      interface{}          `json:"value"`
	KeepOrigin bool                 `json:"keep_origin"`
	From       string               `json:"from,omitempty"`
	To         string               `json:"to,omitempty"`
	Conditions []ConditionOperation `json:"conditions,omitempty"` // 条件列表
	Logic      string               `json:"logic,omitempty"`      // AND, OR (默认OR)
}

type ParamOverrideReturnError

type ParamOverrideReturnError struct {
	Message    string
	StatusCode int
	Code       string
	Type       string
	SkipRetry  bool
}

func AsParamOverrideReturnError

func AsParamOverrideReturnError(err error) (*ParamOverrideReturnError, bool)

func (*ParamOverrideReturnError) Error

func (e *ParamOverrideReturnError) Error() string

type PromptSizeBucket

type PromptSizeBucket string
const (
	PromptSizeSmall     PromptSizeBucket = "small"
	PromptSizeMedium    PromptSizeBucket = "medium"
	PromptSizeLarge     PromptSizeBucket = "large"
	PromptSizeVeryLarge PromptSizeBucket = "very_large"
)

type RelayInfo

type RelayInfo struct {
	TokenId                 int
	TokenKey                string
	TokenGroup              string
	MarketplaceGroupID      string
	MarketplaceOwnerID      int
	MarketplaceSourceType   string
	MarketplaceCreditPolicy string
	MarketplaceMultiplier   float64
	UserId                  int
	UsingGroup              string // 使用的分组,当auto跨分组重试时,会变动
	UserGroup               string // 用户所在分组
	TokenUnlimited          bool
	StartTime               time.Time
	AttemptStartTime        time.Time
	FirstResponseTime       time.Time
	ResponseCompletedAt     time.Time
	FirstByteTrace          *FirstByteTrace

	StreamPacer         *StreamPacer
	StreamUsageRecovery *StreamUsageRecovery
	//SendLastReasoningResponse bool
	IsStream               bool
	IsGeminiBatchEmbedding bool
	IsPlayground           bool
	UsePrice               bool
	RelayMode              int
	OriginModelName        string
	RequestURLPath         string
	RequestHeaders         map[string]string
	ShouldIncludeUsage     bool
	DisablePing            bool // 是否禁止向下游发送自定义 Ping
	ClientWs               *websocket.Conn
	TargetWs               *websocket.Conn
	InputAudioFormat       string
	OutputAudioFormat      string
	RealtimeTools          []dto.RealTimeTool
	IsFirstRequest         bool
	AudioUsage             bool
	ReasoningEffort        string
	ServiceTier            string
	UserSetting            dto.UserSetting
	UserEmail              string
	UserQuota              int
	RelayFormat            types.RelayFormat
	SendResponseCount      int
	ReceivedResponseCount  int
	FinalPreConsumedQuota  int // 最终预消耗的配额
	// BillingSettledQuota is the amount the authoritative ledger actually
	// accepted. It can be lower than provider usage when no extra balance is
	// available at final settlement.
	BillingSettledQuota int
	BillingSettled      bool
	// ForcePreConsume 为 true 时禁用 BillingSession 的信任额度旁路,
	// 强制预扣全额。用于异步任务(视频/音乐生成等),因为请求返回后任务仍在运行,
	// 必须在提交前锁定全额。
	ForcePreConsume bool
	// Billing 是计费会话,封装了预扣费/结算/退款的统一生命周期。
	// 免费模型时为 nil。
	Billing gatewaycontract.BillingSettler
	// BillingSource indicates whether this request is billed from wallet quota or subscription.
	// "" or "wallet" => wallet; "subscription" => subscription
	BillingSource string
	// SubscriptionId is the user_subscriptions.id used when BillingSource == "subscription"
	SubscriptionId int
	// SubscriptionPreConsumed is the amount pre-consumed on subscription item (quota units or 1)
	SubscriptionPreConsumed int64
	// SubscriptionPostDelta is the post-consume delta applied to amount_used (quota units; can be negative).
	SubscriptionPostDelta int64
	// SubscriptionPlanId / SubscriptionPlanTitle are used for logging/UI display.
	SubscriptionPlanId    int
	SubscriptionPlanTitle string
	// RoutePoolID and ProcurementCostMultiplier are internal-only settlement
	// snapshots. They are never sent to users or upstream providers.
	RoutePoolID               int64
	ProcurementCostMultiplier float64
	// RequestId is used for idempotent pre-consume/refund
	RequestId string
	// SubscriptionAmountTotal / SubscriptionAmountUsedAfterPreConsume are used to compute remaining in logs.
	SubscriptionAmountTotal               int64
	SubscriptionAmountUsedAfterPreConsume int64
	// SubscriptionGroupMultiplier is the configured subscription multiplier
	// for the selected billing group. SubscriptionQuotaScale is the resulting
	// scale applied to the normal group-priced quota.
	SubscriptionGroupMultiplier   float64
	SubscriptionPackageMultiplier float64
	SubscriptionQuotaScale        float64
	SubscriptionGroupRatio        float64
	CreditPackGrantedQuota        int64
	CreditPackPaidQuota           int64
	CreditPackChannelShareBPS     int64
	BlindBoxRequestId             string
	IsClaudeBetaQuery             bool // /v1/messages?beta=true
	IsChannelTest                 bool // channel test request
	RetryIndex                    int
	LastError                     *types.NewAPIError
	RuntimeHeadersOverride        map[string]interface{}
	UseRuntimeHeadersOverride     bool
	ParamOverrideAudit            []string

	// UpstreamRequestBodySize is the byte size of the marshaled upstream request
	// body. It is set when the body is wrapped in a BodyStorage (see
	// internal/gateway/runtime/outbound_body.go), so that DoApiRequest can populate
	// http.Request.ContentLength manually (net/http only auto-detects it for
	// *bytes.Reader/Buffer/strings.Reader). 0 means "let net/http decide".
	UpstreamRequestBodySize int64

	PriceData types.PriceData

	// TieredBillingSnapshot is a frozen snapshot of tiered billing rules
	// captured at pre-consume time. Non-nil only when billing mode is "tiered_expr".
	TieredBillingSnapshot *billingexpr.BillingSnapshot
	BillingRequestInput   *billingexpr.RequestInput

	Request                  dto.Request
	ConversationResponseText string

	// RequestConversionChain records request format conversions in order, e.g.
	// ["openai", "openai_responses"] or ["openai", "claude"].
	RequestConversionChain []types.RelayFormat
	// 最终请求到上游的格式。可由 adaptor 显式设置;
	// 若为空,调用 GetFinalRequestRelayFormat 会回退到 RequestConversionChain 的最后一项或 RelayFormat。
	FinalRequestRelayFormat types.RelayFormat

	StreamStatus *gatewaycontract.StreamStatus

	ThinkingContentInfo
	TokenCountMeta
	*ClaudeConvertInfo
	*RerankerInfo
	*ResponsesUsageInfo
	*ChannelMeta
	*TaskRelayInfo
	// contains filtered or unexported fields
}

func GenRelayInfo

func GenRelayInfo(c *gin.Context, relayFormat types.RelayFormat, request dto.Request, ws *websocket.Conn) (*RelayInfo, error)

func GenRelayInfoAlphaSearch

func GenRelayInfoAlphaSearch(c *gin.Context, request *dto.AlphaSearchRequest) *RelayInfo

func GenRelayInfoClaude

func GenRelayInfoClaude(c *gin.Context, request dto.Request) *RelayInfo

func GenRelayInfoEmbedding

func GenRelayInfoEmbedding(c *gin.Context, request dto.Request) *RelayInfo

func GenRelayInfoGemini

func GenRelayInfoGemini(c *gin.Context, request dto.Request) *RelayInfo

func GenRelayInfoImage

func GenRelayInfoImage(c *gin.Context, request dto.Request) *RelayInfo

func GenRelayInfoOpenAI

func GenRelayInfoOpenAI(c *gin.Context, request dto.Request) *RelayInfo

func GenRelayInfoOpenAIAudio

func GenRelayInfoOpenAIAudio(c *gin.Context, request dto.Request) *RelayInfo

func GenRelayInfoRerank

func GenRelayInfoRerank(c *gin.Context, request *dto.RerankRequest) *RelayInfo

func GenRelayInfoResponses

func GenRelayInfoResponses(c *gin.Context, request *dto.OpenAIResponsesRequest) *RelayInfo

func GenRelayInfoResponsesCompaction

func GenRelayInfoResponsesCompaction(c *gin.Context, request *dto.OpenAIResponsesCompactionRequest) *RelayInfo

func GenRelayInfoWs

func GenRelayInfoWs(c *gin.Context, ws *websocket.Conn) *RelayInfo

func (*RelayInfo) AppendRequestConversion

func (info *RelayInfo) AppendRequestConversion(format types.RelayFormat)

func (*RelayInfo) AttemptTTFT

func (info *RelayInfo) AttemptTTFT() (time.Duration, bool)

AttemptTTFT reports latency attributable to the final upstream attempt.

func (*RelayInfo) BeginAttempt

func (info *RelayInfo) BeginAttempt(startedAt time.Time)

BeginAttempt resets the channel-local latency origin immediately before an upstream attempt starts. Request-scoped StartTime intentionally stays fixed.

func (*RelayInfo) EndToEndTTFT

func (info *RelayInfo) EndToEndTTFT() (time.Duration, bool)

EndToEndTTFT reports request latency after the client upload has completed. This keeps the metric comparable with upstream provider TTFT while retaining local validation, routing, billing and retry time after body reception.

func (*RelayInfo) GenerationDuration

func (info *RelayInfo) GenerationDuration() (time.Duration, bool)

GenerationDuration is observed streaming output time, including reasoning and tool output. It does not describe the provider's internal generation rate. Missing observations and non-streaming responses deliberately remain unknown.

func (*RelayInfo) GetEstimatePromptTokens

func (info *RelayInfo) GetEstimatePromptTokens() int

func (*RelayInfo) GetFinalRequestRelayFormat

func (info *RelayInfo) GetFinalRequestRelayFormat() types.RelayFormat

func (*RelayInfo) HasSemanticResponse

func (info *RelayInfo) HasSemanticResponse() bool

HasSemanticResponse excludes protocol lifecycle and role-only events.

func (*RelayInfo) HasSendResponse

func (info *RelayInfo) HasSendResponse() bool

func (*RelayInfo) InitChannelMeta

func (info *RelayInfo) InitChannelMeta(c *gin.Context)

func (*RelayInfo) InitRequestConversionChain

func (info *RelayInfo) InitRequestConversionChain()

func (*RelayInfo) MarkResponseCompleted

func (info *RelayInfo) MarkResponseCompleted()

MarkResponseCompleted freezes the response interval before billing and audit work. Call it after the response handler has finished, including final frames.

func (*RelayInfo) MarkResponseCompletedAt

func (info *RelayInfo) MarkResponseCompletedAt(completedAt time.Time)

func (*RelayInfo) ObserveChatStreamOutput

func (info *RelayInfo) ObserveChatStreamOutput(response dto.ChatCompletionsStreamResponse, receivedAt time.Time)

ObserveChatStreamOutput ignores assistant roles, usage and stop-only chunks.

func (*RelayInfo) ObserveClaudeStreamOutput

func (info *RelayInfo) ObserveClaudeStreamOutput(response dto.ClaudeResponse, receivedAt time.Time)

ObserveClaudeStreamOutput excludes message setup, empty block starts and signatures. Thinking and tool calls count as output, separately from text.

func (*RelayInfo) ObserveResponsesStreamOutput

func (info *RelayInfo) ObserveResponsesStreamOutput(response dto.ResponsesStreamResponse, receivedAt time.Time)

ObserveResponsesStreamOutput is used by Responses-to-Chat bridges. Native Responses uses its own full protocol classification before forwarding events.

func (*RelayInfo) ObserveStreamOutput

func (info *RelayInfo) ObserveStreamOutput(receivedAt time.Time, isText bool)

ObserveStreamOutput records model output after decoding, separately from raw SSE receipt. Text excludes reasoning, tool arguments and lifecycle events.

func (*RelayInfo) ResponseDuration

func (info *RelayInfo) ResponseDuration() (time.Duration, bool)

func (*RelayInfo) ServiceTierQuota

func (info *RelayInfo) ServiceTierQuota(quota int) int

func (*RelayInfo) SetEstimatePromptTokens

func (info *RelayInfo) SetEstimatePromptTokens(promptTokens int)

func (*RelayInfo) SetFirstResponseTime

func (info *RelayInfo) SetFirstResponseTime()

func (*RelayInfo) SetFirstSemanticResponseTime

func (info *RelayInfo) SetFirstSemanticResponseTime()

SetFirstSemanticResponseTime records the first model-visible output. SSE lifecycle events such as response.created are intentionally excluded.

func (*RelayInfo) ToString

func (info *RelayInfo) ToString() string

func (*RelayInfo) UsesMarketplaceEgress

func (info *RelayInfo) UsesMarketplaceEgress() bool

UsesMarketplaceEgress relies on server-resolved routing metadata, never client headers. Administrator-owned upstreams retain their existing policy.

type RequestBudget

type RequestBudget struct {
	StartedAt        time.Time `json:"started_at"`
	Deadline         time.Time `json:"deadline"`
	MaxAttempts      int       `json:"max_attempts"`
	AttemptsUsed     int       `json:"attempts_used"`
	MaxFaultDomains  int       `json:"max_fault_domains"`
	FaultDomainsUsed int       `json:"fault_domains_used"`
	// contains filtered or unexported fields
}

func RequestBudgetFromContext

func RequestBudgetFromContext(c *gin.Context) *RequestBudget

func StartRequestBudget

func StartRequestBudget(c *gin.Context, profile RequestProfile, startedAt time.Time) *RequestBudget

StartRequestBudget creates the request-level retry budget once. Repeated calls return the existing budget so retries never reset the deadline.

func (*RequestBudget) CanRetry

func (b *RequestBudget) CanRetry(now time.Time) bool

func (*RequestBudget) Remaining

func (b *RequestBudget) Remaining(now time.Time) time.Duration

func (*RequestBudget) TryBeginAttempt

func (b *RequestBudget) TryBeginAttempt(now time.Time, faultDomain string) bool

type RequestProfile

type RequestProfile struct {
	RequestType          RequestType         `json:"request_type"`
	Protocol             string              `json:"protocol"`
	ModelFamily          string              `json:"model_family"`
	PromptSizeBucket     PromptSizeBucket    `json:"prompt_size_bucket"`
	HasTools             bool                `json:"has_tools"`
	HasConversationState bool                `json:"has_conversation_state"`
	IsStream             bool                `json:"is_stream"`
	MigrationCapability  MigrationCapability `json:"migration_capability"`
}

RequestProfile is the immutable routing classification shared by selection, health, retry, and audit code. Refinement replaces the complete value.

func InitializeRequestProfile

func InitializeRequestProfile(c *gin.Context, model, path string, hint RequestProfileHint) RequestProfile

func RefineRequestProfile

func RefineRequestProfile(c *gin.Context, format types.RelayFormat, request dto.Request, promptTokens int) RequestProfile

func RequestProfileFromContext

func RequestProfileFromContext(c *gin.Context) (RequestProfile, bool)

type RequestProfileHint

type RequestProfileHint struct {
	IsStream         bool
	HasTools         bool
	HasCacheAffinity bool
	HasUpstreamState bool
}

RequestProfileHint contains body fields that are cheap to parse before the distributor performs the first channel selection.

type RequestType

type RequestType string
const (
	RequestTypeChatShortStream RequestType = "chat_short_stream"
	RequestTypeChatLongStream  RequestType = "chat_long_stream"
	RequestTypeToolCallStream  RequestType = "tool_call_stream"
	RequestTypeChatNonStream   RequestType = "chat_non_stream"
	RequestTypeImageNonStream  RequestType = "image_non_stream"
	RequestTypeImageStream     RequestType = "image_stream"
	RequestTypeOther           RequestType = "embedding_or_other"
)

func RequestTypeFromContext

func RequestTypeFromContext(c *gin.Context) RequestType

type RerankerInfo

type RerankerInfo struct {
	Documents       []any
	ReturnDocuments bool
}

type ResponsesUsageInfo

type ResponsesUsageInfo struct {
	BuiltInTools map[string]*BuildInToolInfo
}

type RouteAttempt

type RouteAttempt struct {
	AttemptID          string      `json:"attempt_id"`
	RetryIndex         int         `json:"retry_index"`
	ChannelID          int         `json:"channel_id"`
	FaultDomain        string      `json:"fault_domain,omitempty"`
	RequestType        RequestType `json:"request_type"`
	StartedAt          time.Time   `json:"started_at"`
	DurationMS         int64       `json:"duration_ms,omitempty"`
	Stage              string      `json:"stage,omitempty"`
	StatusCode         int         `json:"status_code,omitempty"`
	FailureClass       string      `json:"failure_class,omitempty"`
	Success            bool        `json:"success"`
	FirstByteTimeoutMS int64       `json:"first_byte_timeout_ms,omitempty"`
}

type RouteCandidate

type RouteCandidate struct {
	Order     int    `json:"order"`
	Group     string `json:"group"`
	Status    string `json:"status"`
	Reason    string `json:"reason,omitempty"`
	ChannelID int    `json:"channel_id,omitempty"`
}

RouteCandidate records the request-local Auto candidate preflight result. It is emitted only inside administrator route metadata.

type RouteDecision

type RouteDecision struct {
	RequestID           string                `json:"request_id"`
	Model               string                `json:"model"`
	RequestedGroup      string                `json:"requested_group"`
	SelectedGroup       string                `json:"selected_group,omitempty"`
	Mode                string                `json:"mode,omitempty"`
	ChannelID           int                   `json:"channel_id,omitempty"`
	CandidateGroups     int                   `json:"candidate_groups"`
	Excluded            []string              `json:"excluded,omitempty"`
	RetryCount          int                   `json:"retry_count"`
	AffinityHit         bool                  `json:"affinity_hit"`
	Fallback            bool                  `json:"fallback"`
	HealthState         string                `json:"health_state,omitempty"`
	ProbeMode           string                `json:"probe_mode,omitempty"`
	RequestType         RequestType           `json:"request_type,omitempty"`
	Protocol            string                `json:"protocol,omitempty"`
	MigrationCapability MigrationCapability   `json:"migration_capability,omitempty"`
	FirstByteTimeoutMS  int64                 `json:"first_byte_timeout_ms,omitempty"`
	AttemptsUsed        int                   `json:"attempts_used,omitempty"`
	MaxAttempts         int                   `json:"max_attempts,omitempty"`
	BudgetRemaining     int64                 `json:"budget_remaining_ms,omitempty"`
	Attempts            []RouteAttempt        `json:"attempts,omitempty"`
	Candidates          []RouteCandidate      `json:"candidates,omitempty"`
	LiveGroupSignals    []AutoGroupLiveSignal `json:"live_group_signals,omitempty"`
}

RouteDecision is an internal-only record attached to the existing request audit log. It contains identifiers, not provider credentials or channel names.

func GetRouteDecision

func GetRouteDecision(c *gin.Context) (RouteDecision, bool)

GetRouteDecision returns a copy suitable for administrators' log metadata.

type RouteHealthSnapshot

type RouteHealthSnapshot struct {
	Channels    map[int]ChannelHealth
	Domains     map[string]ChannelHealth
	Credentials map[int]ChannelHealth
}

func LoadRouteHealthSnapshot

func LoadRouteHealthSnapshot(c *gin.Context, channelIDs []int, domains []string, model string, requestType RequestType) (RouteHealthSnapshot, error)

LoadRouteHealthSnapshot bounds advisory reads by one Redis round trip per routing round, irrespective of the number of pool members. Admission leases remain live reads and are never taken from this snapshot.

type RouteLogSummary

type RouteLogSummary struct {
	Mode           string   `json:"mode"`
	CandidateCount int      `json:"candidate_count"`
	SelectedOrder  int      `json:"selected_order,omitempty"`
	SkippedCount   int      `json:"skipped_count,omitempty"`
	RetryCount     int      `json:"retry_count,omitempty"`
	Fallback       bool     `json:"fallback"`
	SkipReasons    []string `json:"skip_reasons,omitempty"`
}

RouteLogSummary is the user-visible, identifier-free Auto routing audit.

type StreamPacer

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

StreamPacer splits large GPT deltas into protocol-safe fragments and tracks visible output. It never delays fragments: upstream flow control is the only pacing source.

func NewStreamPacer

func NewStreamPacer(modelName string) *StreamPacer

func (*StreamPacer) OutputDuration

func (p *StreamPacer) OutputDuration() (time.Duration, bool)

OutputDuration measures the interval from the first visible text fragment through the final fragment released to the client.

func (*StreamPacer) OutputTokens

func (p *StreamPacer) OutputTokens() int

OutputTokens returns the estimated visible text tokens released to the client.

func (*StreamPacer) Pace

func (p *StreamPacer) Pace(ctx context.Context, text string) error

func (*StreamPacer) SplitText

func (p *StreamPacer) SplitText(text string) []string

SplitText breaks oversized text deltas into small, protocol-safe fragments. Every fragment is emitted immediately.

type StreamUsageRecovery

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

StreamUsageRecovery keeps an accepted HTTP stream alive briefly after its downstream disappears. Before acceptance, cancellation still stops the dial or request immediately. Close must be called with the response body.

func NewStreamUsageRecovery

func NewStreamUsageRecovery(parent context.Context, maxDuration, grace time.Duration) *StreamUsageRecovery

func (*StreamUsageRecovery) Accept

func (r *StreamUsageRecovery) Accept()

func (*StreamUsageRecovery) BeginDrain

func (r *StreamUsageRecovery) BeginDrain() bool

func (*StreamUsageRecovery) Close

func (r *StreamUsageRecovery) Close()

func (*StreamUsageRecovery) Context

func (r *StreamUsageRecovery) Context() context.Context

func (*StreamUsageRecovery) Done

func (r *StreamUsageRecovery) Done()

func (*StreamUsageRecovery) Failure

func (r *StreamUsageRecovery) Failure() *types.OpenAIError

func (*StreamUsageRecovery) IsDraining

func (r *StreamUsageRecovery) IsDraining() bool

func (*StreamUsageRecovery) Observe

func (r *StreamUsageRecovery) Observe(data string)

Observe runs in the scanner before downstream delivery. Never retain model content in logs; bounded text is used only if final provider usage is missing.

func (*StreamUsageRecovery) Snapshot

func (r *StreamUsageRecovery) Snapshot() (*dto.Usage, string, map[string]interface{})

func (*StreamUsageRecovery) Terminal

func (r *StreamUsageRecovery) Terminal() bool

type TaskInfo

type TaskInfo struct {
	Code             int    `json:"code"`
	TaskID           string `json:"task_id"`
	Status           string `json:"status"`
	Reason           string `json:"reason,omitempty"`
	Url              string `json:"url,omitempty"`
	RemoteUrl        string `json:"remote_url,omitempty"`
	Progress         string `json:"progress,omitempty"`
	CompletionTokens int    `json:"completion_tokens,omitempty"` // 用于按倍率计费
	TotalTokens      int    `json:"total_tokens,omitempty"`      // 用于按倍率计费
}

func FailTaskInfo

func FailTaskInfo(reason string) *TaskInfo

type TaskRelayInfo

type TaskRelayInfo struct {
	Action       string
	OriginTaskID string
	// PublicTaskID 是提交时预生成的 task_xxxx 格式公开 ID,
	// 供 DoResponse 在返回给客户端时使用(避免暴露上游真实 ID)。
	PublicTaskID string

	ConsumeQuota bool

	// LockedChannel holds the full channel object when the request is bound to
	// a specific channel (e.g., remix on origin task's channel). Stored as any
	// to avoid an import cycle with the gateway schema; callers type-assert to *schema.Channel.
	LockedChannel any
}

type TaskSubmitReq

type TaskSubmitReq struct {
	Prompt         string                 `json:"prompt"`
	Model          string                 `json:"model,omitempty"`
	Mode           string                 `json:"mode,omitempty"`
	Image          string                 `json:"image,omitempty"`
	Images         []string               `json:"images,omitempty"`
	Size           string                 `json:"size,omitempty"`
	Duration       int                    `json:"duration,omitempty"`
	Seconds        string                 `json:"seconds,omitempty"`
	InputReference string                 `json:"input_reference,omitempty"`
	Metadata       map[string]interface{} `json:"metadata,omitempty"`
}

func GetTaskRequest

func GetTaskRequest(c *gin.Context) (TaskSubmitReq, error)

func (*TaskSubmitReq) GetPrompt

func (t *TaskSubmitReq) GetPrompt() string

func (*TaskSubmitReq) HasImage

func (t *TaskSubmitReq) HasImage() bool

func (*TaskSubmitReq) UnmarshalJSON

func (t *TaskSubmitReq) UnmarshalJSON(data []byte) error

func (*TaskSubmitReq) UnmarshalMetadata

func (t *TaskSubmitReq) UnmarshalMetadata(v any) error

type ThinkingContentInfo

type ThinkingContentInfo struct {
	IsFirstThinkingContent  bool
	SendLastThinkingContent bool
	HasSentThinkingContent  bool
}

type TokenCountMeta

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

type UserStreamFailureCircuit

type UserStreamFailureCircuit struct {
	Fingerprint         string    `json:"fingerprint"`
	ConsecutiveFailures int       `json:"consecutive_failures"`
	CoolingUntil        time.Time `json:"cooling_until"`
	LastFailureAt       time.Time `json:"last_failure_at"`
	LastFailureRequest  string    `json:"last_failure_request"`
}

UserStreamFailureCircuit is a user-scoped guard for repeated incomplete streams. Its fingerprint is always a one-way hash and never stores request content.

type UserStreamFailureCircuitAudit

type UserStreamFailureCircuitAudit struct {
	Fingerprint         string `json:"fingerprint"`
	ConsecutiveFailures int    `json:"consecutive_failures"`
	Opened              bool   `json:"opened"`
	RetryAfterSeconds   int    `json:"retry_after_seconds,omitempty"`
}

UserStreamFailureCircuitAudit contains the non-sensitive state recorded with an error log.

func RecordUserIncompleteStreamFailure

func RecordUserIncompleteStreamFailure(c *gin.Context, modelName string) UserStreamFailureCircuitAudit

RecordUserIncompleteStreamFailure updates the circuit after an upstream stream misses its terminal event.

func UserStreamFailureCircuitAuditFromContext

func UserStreamFailureCircuitAuditFromContext(c *gin.Context) (UserStreamFailureCircuitAudit, bool)

UserStreamFailureCircuitAuditFromContext returns guard diagnostics for internal error logs.

Jump to

Keyboard shortcuts

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