Documentation
¶
Index ¶
- Constants
- Variables
- func AiIntentThreshold(question string) float64
- func BatchAffinityKey(cluster, id string) string
- func BatchPathBatchId(path string) string
- func BatchPathFileId(path string) string
- func ClassifyBatchOp(method string, path string) string
- func CreateForbiddenResp(request *Request) *bfe_http.Response
- func CreateInternalResp(request *Request, code int) *bfe_http.Response
- func CreateInternalSrvErrResp(request *Request) *bfe_http.Response
- func CreateSpecifiedContentResp(request *Request, responseCode int, contentType string, content string) *bfe_http.Response
- func DetectAuthStyle(req *Request) string
- func DetectModeFromPath(path string) string
- func ErrorTypeForCode(code string) string
- func ExtractBatchInputFileId(req *Request) string
- func GetApiKey(req *Request) string
- func IsOpenAIEndpoint(path string) bool
- func SetAiIntentResolver(fn func(*Request) *AiIntent)
- func SetAiIntentThreshold(fn func(question string) float64)
- func StripV1Prefix(path string) string
- type AiAuthInfo
- type AiBasicInfo
- func (aiinfo *AiBasicInfo) AppendClusterKeyName(clusterName, keyName string)
- func (aiinfo *AiBasicInfo) GetTokenUsage() *TokenUsage
- func (aiinfo *AiBasicInfo) IncrementRetryCount()
- func (aiinfo *AiBasicInfo) IsAllowEstimateToken() bool
- func (aiinfo *AiBasicInfo) IsFinalUsageSeen() bool
- func (aiinfo *AiBasicInfo) IsPriceMiss() bool
- func (aiinfo *AiBasicInfo) IsResponseCompleted() bool
- func (aiinfo *AiBasicInfo) MarkFinalUsageSeen()
- func (aiinfo *AiBasicInfo) MarkPriceMiss()
- func (aiinfo *AiBasicInfo) MarkResponseCompleted()
- func (aiinfo *AiBasicInfo) SetAllowEstimateToken(allow bool)
- func (aiinfo *AiBasicInfo) SetUsageDisposition(disposition string)
- func (aiinfo *AiBasicInfo) SetUsageSource(source string)
- func (aiinfo *AiBasicInfo) SetZeroCostReason(reason string)
- func (aiinfo *AiBasicInfo) UsageDisposition() string
- func (aiinfo *AiBasicInfo) UsageSource() string
- func (aiinfo *AiBasicInfo) ZeroCostReason() string
- type AiBatchRouteHint
- type AiError
- type AiErrorBody
- type AiErrorDetail
- type AiIntent
- type AiRateLimitHitInfo
- type AiRouteFallback
- type AiRouteResult
- type AiRouteTarget
- type ApikeyTag
- type BackendInfo
- type ClusterKeyName
- type HitPolicyInfo
- type IntentAnswer
- type OperationStage
- type RedirectInfo
- type Request
- func (req *Request) AddTags(name string, ntags []string)
- func (req *Request) CachedCookie() bfe_http.CookieMap
- func (req *Request) CachedQuery() url.Values
- func (req *Request) Cookie(name string) (*bfe_http.Cookie, bool)
- func (r *Request) GetAiBasicInfo() *AiBasicInfo
- func (req *Request) GetAiBatchRouteHint() *AiBatchRouteHint
- func (r *Request) GetAiRateLimitHitInfo() *AiRateLimitHitInfo
- func (r *Request) GetAiRouteResult() *AiRouteResult
- func (r *Request) GetApikeyTags() []ApikeyTag
- func (req *Request) GetContext(key interface{}) interface{}
- func (req *Request) GetTags(name string) []string
- func (r *Request) InitAiBasicInfo() *AiBasicInfo
- func (r *Request) InitAiRateLimitHitInfo() *AiRateLimitHitInfo
- func (req *Request) Protocol() string
- func (req *Request) SetAiBatchRouteHint(hint *AiBatchRouteHint)
- func (r *Request) SetAiIntent(v *AiIntent)
- func (r *Request) SetAiRouteResult(result *AiRouteResult)
- func (req *Request) SetContext(key, val interface{})
- func (req *Request) SetRequestTransport(backend *backend.BfeBackend, transport bfe_http.RoundTripper)
- type RequestRoute
- type RequestStat
- type RequestTags
- type RequestTransport
- type ServerDataConfInterface
- type Session
- func (s *Session) ClearContext()
- func (s *Session) Finish()
- func (s *Session) GetContext(key interface{}) interface{}
- func (s *Session) GetError() (string, error)
- func (s *Session) GetVip() net.IP
- func (s *Session) IncReqNum(count int) int64
- func (s *Session) IncReqNumActive(count int) int64
- func (s *Session) ReadTotal() int
- func (s *Session) ReqNum() int64
- func (s *Session) ReqNumActive() int64
- func (s *Session) SetContext(key, val interface{})
- func (s *Session) SetError(errCode error, errMsg string)
- func (s *Session) SetReqNum(count int)
- func (s *Session) SetReqNumActive(count int)
- func (s *Session) SetTrustSource(isTrustSource bool)
- func (s *Session) String() string
- func (s *Session) TrustSource() bool
- func (s *Session) UpdateReadTotal(total int) int
- func (s *Session) UpdateWriteTotal(total int) int
- func (s *Session) WriteTotal() int
- type SessionStickyBackend
- type TokenTimeInfo
- type TokenUsage
- type WafInfo
Constants ¶
const ( HeaderBfeIP = "X-Bfe-Ip" HeaderBfeLogId = "X-Bfe-Log-Id" HeaderForwardedHost = "X-Forwarded-Host" HeaderForwardedFor = "X-Forwarded-For" HeaderForwardedPort = "X-Forwarded-Port" HeaderRealIP = "X-Real-Ip" HeaderRealPort = "X-Real-Port" )
const ( REQ_AI_BASIC_CONTEXT = "__REQ_AI_BASIC_CONTEXT" REQ_AI_RATE_LIMIT_HIT = "__REQ_AI_RATE_LIMIT_HIT" )
const ( ModeChat = "chat" ModeCompletion = "completion" ModeImageGeneration = "image_generation" ModeImageEdit = "image_edit" ModeEmbedding = "embedding" ModeAudioSpeech = "audio_speech" ModeAudioTranscription = "audio_transcription" ModeRerank = "rerank" ModeVideoGeneration = "video_generation" ModeOcr = "ocr" ModeSearch = "search" ModeRealtime = "realtime" ModeResponses = "responses" ModeFile = "file" ModeBatch = "batch" )
AI request modes, inferred from request path.
const ( BatchOpUpload = "upload" BatchOpCreate = "create" BatchOpGet = "get" BatchOpList = "list" BatchOpCancel = "cancel" BatchOpDownload = "download" )
Batch operation types (mod_ai_batch), classified from (method, path).
const ( BatchSettleNone = "none" BatchSettleSettle = "settle" // settled by result-file usage at download BatchSettleRelease = "release" // reserve released without settlement )
Batch quota settlement markers written by mod_ai_batch into AiBasicInfo; consumed by mod_ai_token_auth at HandleRequestFinish.
const ( AuthStyleOpenAI = "openai" AuthStyleAnthropic = "anthropic" AuthStyleGemini = "gemini" AuthStyleUnknown = "unknown" )
AI protocol/auth styles.
const ( // UsageDispositionUnset is the zero value: no disposition was judged // (the request did not go through token authentication, or the module // was not loaded). The access-log fields keep their legacy behaviour. UsageDispositionUnset = "" // UsageDispositionNone means the request never successfully called the // upstream (non-2xx response), so no model usage can exist: the access // log must not report ai_input_tokens / ai_output_tokens / // ai_total_tokens, and any auth-time or response-time estimate is // residue, not usage. UsageDispositionNone = "none" // UsageDispositionObserved means the upstream was successfully called // and the shared TokenUsage holds the real parsed usage or the // EstimateToken estimate of this request (issue #1398 keeps that view // observable); the access log reports it as-is. UsageDispositionObserved = "observed" )
Token-usage dispositions for the access log (issue #1409).
const ( // UsageSourceParsed means a final usage was parsed from the upstream // response, decided by the presence of the usage object rather than by // its values (issue #1414): an upstream that explicitly reports all-zero // usage also lands here and is billed at 0, instead of being estimated. UsageSourceParsed = "parsed" // UsageSourceEstimated means the upstream returned no usage at all but the // request is billable by EstimateToken (estimate allowed and response // completed); the approved estimate is mirrored into the shared usage // (issue #1398). UsageSourceEstimated = "estimated" // UsageSourceAborted means the client disconnected (RST/close/write // failure) before the final usage was seen: billing is skipped per the // issue #1352 yardstick, and the reported token fields are either // auth-time seeding residue or the initial usage of the stream // (issue #1414). UsageSourceAborted = "aborted" // UsageSourceUnrecognized means no final usage was parsed and the // request is not estimatable: billing was skipped and the reported // token fields are auth-time seeding residue. UsageSourceUnrecognized = "unrecognized" )
Usage sources for the access log (issue #1410): where the reported token usage came from. Orthogonal to UsageDisposition, which decides whether usage is reported at all; the source is set at the same decision point as the billing-yardstick guard so the signal can never diverge from the billing call.
const ( // ZeroCostReasonUnrecognized: upstream usage was neither recognized nor // estimatable. ZeroCostReasonUnrecognized = "unrecognized" // ZeroCostReasonAborted: the client disconnected before the final usage. ZeroCostReasonAborted = "aborted" // ZeroCostReasonCacheHit: AI cache hit, the upstream was never called. ZeroCostReasonCacheHit = "cache_hit" // ZeroCostReasonBatchRelease: batch contract released without billing. ZeroCostReasonBatchRelease = "batch_release" // ZeroCostReasonPriceMiss: no price entry and no fallback price. ZeroCostReasonPriceMiss = "price_miss" // ZeroCostReasonPriceZero: the price entry exists but the billed // dimensions are priced 0. ZeroCostReasonPriceZero = "price_zero" // ZeroCostReasonModelTableMissing: the cluster model table is missing or // unlookupable. ZeroCostReasonModelTableMissing = "model_table_missing" // ZeroCostReasonConfigMissing: pricing configuration (server data conf / // cluster / target model) is unavailable at billing time. ZeroCostReasonConfigMissing = "config_missing" // ZeroCostReasonNoUsageTokens: no billable token count, although no usage // problem was detected (e.g. a genuine zero-usage response, or image / // video modes with a zero generated count). ZeroCostReasonNoUsageTokens = "no_usage_tokens" // ZeroCostReasonCostZero: fallback for a zero cost with no classified // cause. ZeroCostReasonCostZero = "cost_zero" )
Zero-cost reasons for the access log (issue #1414): why a 2xx request that holds an RMB quota plan was charged 0. Reported as ai_zero_cost_reason and counted by the BillingZeroCost module counter (AI cache hits are marked but not counted: they never call the upstream, so their zero cost is by design).
const ( CodeInvalidRequest = "INVALID_REQUEST" CodeNoApiKey = "NO_API_KEY" CodeInvalidApiKey = "INVALID_API_KEY" CodeKeyDisabled = "KEY_DISABLED" CodeKeyExpired = "KEY_EXPIRED" CodeSubnetNotAllowed = "SUBNET_NOT_ALLOWED" CodeModelNotAllowed = "MODEL_NOT_ALLOWED" CodeRpmLimitExceeded = "RPM_LIMIT_EXCEEDED" CodeTpmLimitExceeded = "TPM_LIMIT_EXCEEDED" CodeConcurrencyLimitExceeded = "CONCURRENCY_LIMIT_EXCEEDED" CodeRateLimitRedisError = "RATE_LIMIT_REDIS_ERROR" CodeQuotaExhausted = "QUOTA_EXHAUSTED" CodeQuotaExpired = "QUOTA_EXPIRED" CodeQuotaPackageDisabled = "QUOTA_PACKAGE_DISABLED" CodeQuotaModelMismatch = "QUOTA_MODEL_MISMATCH" CodeQuotaPlanFailed = "QUOTA_PLAN_FAILED" CodeInternalQuotaError = "INTERNAL_QUOTA_ERROR" CodeContextLengthExceeded = "CONTEXT_LENGTH_EXCEEDED" CodeContentFiltered = "CONTENT_FILTERED" CodeModelInternalError = "MODEL_INTERNAL_ERROR" CodeBackendTimeout = "BACKEND_TIMEOUT" // Batch (mod_ai_batch) limits: file size/line hard ceilings, resolved // from min(bound policies' batch_limits, mod_ai_batch.data global caps) CodeBatchFileTooLarge = "BATCH_FILE_TOO_LARGE" // Batch file ownership check failed (file_id bound to another apikey) CodeBatchFileForbidden = "BATCH_FILE_FORBIDDEN" CodeProviderProtocolMismatch = "PROVIDER_PROTOCOL_MISMATCH" // Upstream error normalization catalog (AIConf.NormalizeUpstreamError). // Values are single-sourced in bfe_model_protocol/utils and shared with // the protocol adapters' mapping tables. CodeUpstreamInvalidRequest = bfe_model_protocol.CodeUpstreamInvalidRequest CodeUpstreamRateLimited = bfe_model_protocol.CodeUpstreamRateLimited CodeUpstreamQuotaExhausted = bfe_model_protocol.CodeUpstreamQuotaExhausted CodeUpstreamAuthError = bfe_model_protocol.CodeUpstreamAuthError CodeUpstreamModelNotFound = bfe_model_protocol.CodeUpstreamModelNotFound CodeUpstreamOverloaded = bfe_model_protocol.CodeUpstreamOverloaded CodeUpstreamUnknown = bfe_model_protocol.CodeUpstreamUnknown CodeConfigLoadError = "CONFIG_LOAD_ERROR" CodeInvalidRequestBody = "INVALID_REQUEST_BODY" CodeModelParamMissing = "MODEL_PARAM_MISSING" CodeUserQuotaExhausted = "USER_QUOTA_EXHAUSTED" CodeSessionQuotaExhausted = "SESSION_QUOTA_EXHAUSTED" CodeFunctionQuotaExhausted = "FUNCTION_QUOTA_EXHAUSTED" CodeCostBudgetExhausted = "COST_BUDGET_EXHAUSTED" CodeGeoRestricted = "GEO_RESTRICTED" CodeTimeWindowRestricted = "TIME_WINDOW_RESTRICTED" )
const ( TypeAuthenticationError = "authentication_error" TypeInvalidRequestError = "invalid_request_error" TypeRateLimitError = "rate_limit_error" TypeQuotaError = "quota_error" TypeInternalError = "internal_error" )
const ( LimitTypeApiKeyQuota = "api_key_quota" LimitTypeRpm = "rpm" LimitTypeTpm = "tpm" LimitTypeConcurrency = "concurrency" LimitTypeErrRedis = "redis_access_error" // Batch limits (mod_ai_batch): file bytes/line ceilings LimitTypeBatchFile = "batch_file" )
const ( IntentQTypeChoice = "choice" IntentQTypeScore = "score" )
intent question types
const ( IntentSourceHeader = "header" // explicitly declared by client request header IntentSourceModel = "model" // classified by decision service IntentSourceCache = "cache" // served from in-process cache )
intent answer sources
const ( SessionNotTrustSource int32 = 0 SessionTrustSource int32 = 1 )
const ( REQ_CHECK_ONLY = "CheckOnly" REQ_NO_CHECK = "NoCheck" REQ_FORBIDDEN = "Forbidden" REQ_OK = "WaitResponse.Pass.Ok" REQ_TIMEOUT = "WaitResponse.Pass.Timeout" REQ_OTHER = "WaitResponse.Pass.Other" NET_ERR = "Net.Error" // net error between go-bfe and waf-server )
const ( WAF_NO_CHECK = 0 // no check for request WAF_CHECKONLY = 1 // check only; from mod_waf_client, not used now WAF_FORBIDDEN = 2 // check and forbidden WAF_PASS = 3 // check and pass WAF_DEGRADE = 4 // check, but pass with degraded WAF_TIMEOUT = 5 // check, but pass with timeout WAF_ERROR = 6 // check and pass with error happened )
const AIKeyAffinityBatchPrefix = "bfe:ai:key_affinity:batch"
AIKeyAffinityBatchPrefix is the Redis namespace of batch-level key affinity bindings, written by mod_ai_batch and read by chooseAIKeyWithAffinity (bfe_server). It intentionally does not follow the configurable [AIKeyAffinity] prefix: batch bindings are an independent namespace so the two mechanisms cannot shadow each other.
const (
COMPLETION_TOKENS_UNKNOWN = -1
)
const CtxAiIntent = "__REQ_AI_INTENT"
const CtxAiRouteResult = "__REQ_AI_ROUTE_RESULT"
const (
GlobalProduct = "global"
)
const HeaderBfeGwError = "X-Bfe-Gw-Error"
HeaderBfeGwError marks gateway-generated error responses. Upstream error normalization skips responses carrying this marker (they are already in the unified AiError format).
const (
REQ_CTX_WAF_INFO = "waf_client.waf_info"
)
const (
SessionStickyBackendKey = "SessionStickyBackendKey"
)
Variables ¶
var ( // client error ErrClientTlsHandshake = errors.New("CLIENT_TLS_HANDSHAKE") // tls handshake error ErrClientWrite = errors.New("CLIENT_WRITE") // write client error ErrClientClose = errors.New("CLIENT_CLOSE") // close by peer ErrClientLongHeader = errors.New("CLIENT_LONG_HEADER") // req too long header ErrClientLongUrl = errors.New("CLIENT_LONG_URL") // req too long url ErrClientTimeout = errors.New("CLIENT_TIMEOUT") // timeout ErrClientBadRequest = errors.New("CLIENT_BAD_REQUEST") // bad request ErrClientZeroContentlen = errors.New("CLIENT_ZERO_CONTENTLEN") // zero content length ErrClientExpectFail = errors.New("CLIENT_EXPECT_FAIL") // expect fail ErrClientReset = errors.New("CLIENT_RESET") // client reset connection ErrClientFrame = errors.New("CLIENT_LONG_FRAME") // only used for spdy/http2 // backend error ErrBkFindProduct = errors.New("BK_FIND_PRODUCT") // fail to find product ErrBkFindLocation = errors.New("BK_FIND_LOCATION") // fail to find location ErrBkNoCluster = errors.New("BK_NO_CLUSTER") // no cluster found ErrBkNoSubCluster = errors.New("BK_NO_SUB_CLUSTER") // no sub-cluster found ErrBkNoBackend = errors.New("BK_NO_BACKEND") // no backend found ErrBkRequestBackend = errors.New("BK_REQUEST_BACKEND") // forward request to backend error ErrBkConnectBackend = errors.New("BK_CONNECT_BACKEND") // connect backend error ErrBkWriteRequest = errors.New("BK_WRITE_REQUEST") // write request error (caused by bk or client) ErrBkReadRespHeader = errors.New("BK_READ_RESP_HEADER") // read response error ErrBkRespHeaderTimeout = errors.New("BK_RESP_HEADER_TIMEOUT") // read response timeout ErrBkTransportBroken = errors.New("BK_TRANSPORT_BROKEN") // conn broken ErrBkRetryTooMany = errors.New("BK_RETRY_TOOMANY") // reach retry max ErrBkNoSubClusterCross = errors.New("BK_NO_SUB_CLUSTER_CROSS") // no sub-cluster found ErrBkCrossRetryBalance = errors.New("BK_CROSS_RETRY_BALANCE") // cross retry balance failed ErrBkBodyProcess = errors.New("BK_BODY_PROCESS") // body process error // GSLB error ErrGslbBlackhole = errors.New("GSLB_BLACKHOLE") // deny by blackhole // AI rate limit deny (mod_ai_rate_limit); global sentinel so that the // server core can distinguish a local policy rejection from an upstream // 429 without importing the module package. ErrAiRateLimit = errors.New("AI_RATE_LIMIT") // deny by mod_ai_rate_limit )
var ErrorCodeToErrorType = map[string]string{ CodeInvalidRequest: TypeInvalidRequestError, CodeNoApiKey: TypeAuthenticationError, CodeInvalidApiKey: TypeAuthenticationError, CodeKeyDisabled: TypeAuthenticationError, CodeKeyExpired: TypeAuthenticationError, CodeSubnetNotAllowed: TypeAuthenticationError, CodeModelNotAllowed: TypeInvalidRequestError, CodeRpmLimitExceeded: TypeRateLimitError, CodeTpmLimitExceeded: TypeRateLimitError, CodeConcurrencyLimitExceeded: TypeRateLimitError, CodeRateLimitRedisError: TypeRateLimitError, CodeQuotaExhausted: TypeQuotaError, CodeQuotaExpired: TypeQuotaError, CodeQuotaPackageDisabled: TypeQuotaError, CodeQuotaModelMismatch: TypeQuotaError, CodeQuotaPlanFailed: TypeQuotaError, CodeInternalQuotaError: TypeInternalError, CodeContextLengthExceeded: TypeInvalidRequestError, CodeContentFiltered: TypeInvalidRequestError, CodeModelInternalError: TypeInternalError, CodeBackendTimeout: TypeInternalError, CodeBatchFileTooLarge: TypeRateLimitError, CodeBatchFileForbidden: TypeAuthenticationError, CodeConfigLoadError: TypeInternalError, CodeBackendUnavailable: TypeInternalError, CodeInvalidRequestBody: TypeInvalidRequestError, CodeModelParamMissing: TypeInvalidRequestError, CodeUserQuotaExhausted: TypeQuotaError, CodeSessionQuotaExhausted: TypeQuotaError, CodeFunctionQuotaExhausted: TypeQuotaError, CodeCostBudgetExhausted: TypeQuotaError, CodeGeoRestricted: TypeAuthenticationError, CodeTimeWindowRestricted: TypeAuthenticationError, CodeProviderProtocolMismatch: TypeInvalidRequestError, CodeUpstreamInvalidRequest: TypeInvalidRequestError, CodeUpstreamRateLimited: TypeRateLimitError, CodeUpstreamQuotaExhausted: TypeQuotaError, CodeUpstreamAuthError: TypeInternalError, CodeUpstreamModelNotFound: TypeInvalidRequestError, CodeUpstreamOverloaded: TypeInternalError, CodeUpstreamUnknown: TypeInternalError, }
ErrorCodeToErrorType maps every catalog code to its error.type.
var ErrorCodeToStatusCode = map[string]int{ CodeInvalidRequest: 400, CodeNoApiKey: 401, CodeInvalidApiKey: 401, CodeKeyDisabled: 403, CodeKeyExpired: 403, CodeSubnetNotAllowed: 403, CodeModelNotAllowed: 400, CodeRpmLimitExceeded: 429, CodeTpmLimitExceeded: 429, CodeConcurrencyLimitExceeded: 429, CodeRateLimitRedisError: 500, CodeQuotaExhausted: 429, CodeQuotaExpired: 429, CodeQuotaPackageDisabled: 429, CodeQuotaModelMismatch: 429, CodeQuotaPlanFailed: 429, CodeInternalQuotaError: 500, CodeContextLengthExceeded: 400, CodeContentFiltered: 400, CodeModelInternalError: 500, CodeBackendTimeout: 504, CodeBatchFileTooLarge: 413, CodeBatchFileForbidden: 404, CodeConfigLoadError: 500, CodeBackendUnavailable: 502, CodeInvalidRequestBody: 400, CodeModelParamMissing: 400, CodeUserQuotaExhausted: 429, CodeSessionQuotaExhausted: 429, CodeFunctionQuotaExhausted: 429, CodeCostBudgetExhausted: 429, CodeGeoRestricted: 403, CodeTimeWindowRestricted: 403, CodeProviderProtocolMismatch: 400, CodeUpstreamInvalidRequest: 400, CodeUpstreamRateLimited: 429, CodeUpstreamQuotaExhausted: 429, CodeUpstreamAuthError: 502, CodeUpstreamModelNotFound: 404, CodeUpstreamOverloaded: 503, CodeUpstreamUnknown: 502, }
var HopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te",
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
HopHeaders are Hop-by-hop headers. These are removed when sent to the backend. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
Functions ¶
func AiIntentThreshold ¶ added in v1.8.9
AiIntentThreshold returns the current effective confidence gate of a question. Without an injected threshold (module not loaded) it is 0, i.e. only the presence of an answer is required.
func BatchAffinityKey ¶ added in v1.8.9
BatchAffinityKey builds the binding key for a batch or file identifier.
func BatchPathBatchId ¶ added in v1.8.9
BatchPathBatchId extracts the {id} segment of /batches/{id}[/cancel].
func BatchPathFileId ¶ added in v1.8.9
BatchPathFileId extracts the {id} segment of /files/{id}[/content].
func ClassifyBatchOp ¶ added in v1.8.9
ClassifyBatchOp maps (method, request path) to a batch operation type. It mirrors the endpoint coverage of openAIEndpointModes: the /files and /batches entries match their sub-paths by prefix, so /files/{id} and /files/{id}/content arrive here with ModeFile, and /batches/{id} and /batches/{id}/cancel with ModeBatch. Returns "" for operations not intercepted (e.g. DELETE /files/{id}). Shared by mod_ai_batch and mod_ai_rate_limit.
func CreateForbiddenResp ¶
CreateForbiddenResp returns a HTTP 403 response
func CreateInternalSrvErrResp ¶
CreateInternalSrvErrResp returns a HTTP 500 response
func CreateSpecifiedContentResp ¶ added in v1.8.0
func DetectAuthStyle ¶ added in v1.8.6
DetectAuthStyle infers the AI protocol/auth style from request characteristics. It is purely based on request path/headers and does not rely on user routing rules.
func DetectModeFromPath ¶ added in v1.8.6
DetectModeFromPath infers the AI request mode from the request path. It defaults to ModeChat for unknown paths to keep backward compatibility.
OpenAI standard endpoints are recognized with or without the /v1 version prefix: both /v1/embeddings and /embeddings map to ModeEmbedding, so the billing mode never depends on whether the client entry carries /v1 (consistent with the upstream path rewrite, issue #1379 follow-up). Provider-native entries whose prefix ends in a /v1 segment (the OpenAI SDK base_url form, e.g. /compatible-mode/v1/responses) reduce to the same endpoints (issue #1382).
func ErrorTypeForCode ¶ added in v1.8.9
ErrorTypeForCode returns the error.type for a catalog code, defaulting to internal_error for unknown codes.
func ExtractBatchInputFileId ¶ added in v1.8.9
ExtractBatchInputFileId parses input_file_id from a buffered batch create request body. Returns "" when the body is not fully buffered or does not parse. Used by the reverse proxy to derive the batch affinity hint before module callbacks run.
func IsOpenAIEndpoint ¶ added in v1.8.8
IsOpenAIEndpoint reports whether path (with any /v1 prefix already stripped) is a recognized OpenAI API endpoint, i.e. listed in openAIEndpointModes. Used by the bfe_server upstream path rewrite to decide whether the configured base path applies.
func SetAiIntentResolver ¶ added in v1.8.9
func SetAiIntentThreshold ¶ added in v1.8.9
func StripV1Prefix ¶ added in v1.8.8
StripV1Prefix strips a leading "/v1" version prefix from an OpenAI-style request path: "/v1/chat/completions" -> "/chat/completions"; paths without the prefix (including "/v10/xxx" and provider-native paths such as "/compatible-mode/v1/chat/completions") are returned unchanged. Shared by DetectModeFromPath and the bfe_server path rewrite so both treat the optional /v1 entry prefix identically.
Types ¶
type AiAuthInfo ¶ added in v1.8.3
type AiBasicInfo ¶ added in v1.8.3
type AiBasicInfo struct {
ClientApiKey string
ClientKeyId string
ClientModel string
TargetModel string
Mode string // request mode, e.g. chat, image_generation
Provider string // upstream model provider, e.g. openai, deepseek
AuthStyle string // request protocol/auth style, e.g. openai, anthropic
RetryCount uint32 // model invocation retry count (key-level retry)
CostCurrency string // cost currency, e.g. RMB, USD
ApikeyTags []ApikeyTag
TokenTimeInfo TokenTimeInfo
AiAuthInfo AiAuthInfo
ClusterKeyNames []ClusterKeyName // tried (cluster, key) pairs during request processing
// AI cache (mod_ai_cache) result
AiCacheHit bool // true when the response was served from the AI cache
AiCacheStatus string // cache status: hit / hit_semantic / miss / skip, empty if cache not enabled
AiCacheKey string // cache key, only filled when mod_ai_cache debug is on
AiCacheSemantic bool // true when the hit comes from the semantic (vector) cache
AiCacheSimilarity float64 // normalized similarity [0,1] of a semantic cache hit, 0 if not applicable
// AI context compress (mod_ai_context) result
ContextCompressStatus string // "" = not processed; skip_* / trim / rewrite / repair_rollback (also the fallback idempotency guard)
ContextTokensBefore int64 // estimated tokens before context compression (heuristic estimate)
ContextTokensAfter int64 // estimated tokens after context compression, 0 if not compressed
ContextCompressMode string // effective mode: conservative / balanced / aggressive
// Traffic mirroring (mod_traffic_mirror) result: only synchronous fields
// are recorded here; async mirror results (status/usage/latency) are
// reported via module Prometheus metrics and are not written back
MirrorHit bool // true when the request was selected for mirroring
MirrorCluster string // mirror target cluster name, empty if not mirrored
// Upstream error normalization (AIConf.NormalizeUpstreamError) result;
// all fields stay at zero values when normalization is disabled or the
// response is not an upstream error
UpstreamStatus int32 // original upstream HTTP status, 0 = not recorded
UpstreamErrCode string // original upstream error code (redacted)
ErrNormalized bool // true when the upstream error was rewritten into the unified error body
ErrNormalizeMiss bool // true when the parser did not recognize the upstream error body
StreamErrorRewritten bool // true when at least one SSE error event of the stream was rewritten
StreamTruncated bool // true when the stream ended without the protocol's terminal event
// UpstreamKey holds the last injected upstream credential; it is the
// pattern source for error-body credential redaction and must never be
// written to logs or responses.
UpstreamKey string
// Batch task (mod_ai_batch) context: filled on files/batches operations.
// BatchSettle carries the quota settlement contract consumed by
// mod_ai_token_auth: "settle" (price the parsed usage at batch price and
// release the reserve), "release" (release the reserve only) or "none".
BatchId string // batch_xxx, empty for non-batch traffic
BatchFileId string // file-xxx, empty when unknown
BatchOp string // BatchOp*: upload/create/get/list/cancel/download
BatchLines int64 // jsonl line count (upload counting / output parsing)
BatchBytes int64 // file bytes (upload counting / provider response)
BatchStatus string // provider status snapshot: validating/.../cancelling
BatchSettle string // BatchSettle*: none/settle/release
BatchSettleId string // idempotency key for settle/release (batch_id)
// Batch effective file limits, computed by mod_ai_rate_limit as
// min(bound policies' batch_limits, mod_ai_batch.data global hard
// ceiling); consumed by mod_ai_batch pre-forward checks. 0 = unlimited.
BatchEffMaxFileBytes int64
BatchEffMaxFileLines int64
// BatchUsageByModel carries per-model usage aggregated from a batch
// result file, keyed by target model; consumed by mod_ai_token_auth to
// price the settlement at mode=batch rates per model group.
BatchUsageByModel map[string]TokenUsage
// BatchSettleApplied reports whether this request actually executed the
// settle/release contract: mod_ai_token_auth sets it once the
// BATCH_SETTLED claim is won and the deduction/release ran. mod_ai_batch
// persists the settlement fields into BATCH_TASK only when it is true, so
// a batch already settled/released by another path (control-plane
// reconcile backstop, concurrent download) is never re-marked.
BatchSettleApplied bool
// BatchSettledUnits carries the RMB amount (1e-8 fixed-point units)
// actually charged by the settlement, published alongside
// BatchSettleApplied so mod_ai_batch can persist BATCH_TASK.settle_units.
// Zero is a legitimate value (price miss, no usage) and is still written.
BatchSettledUnits int64
// contains filtered or unexported fields
}
func (*AiBasicInfo) AppendClusterKeyName ¶ added in v1.8.5
func (aiinfo *AiBasicInfo) AppendClusterKeyName(clusterName, keyName string)
func (*AiBasicInfo) GetTokenUsage ¶ added in v1.8.3
func (aiinfo *AiBasicInfo) GetTokenUsage() *TokenUsage
func (*AiBasicInfo) IncrementRetryCount ¶ added in v1.8.5
func (aiinfo *AiBasicInfo) IncrementRetryCount()
func (*AiBasicInfo) IsAllowEstimateToken ¶ added in v1.8.4
func (aiinfo *AiBasicInfo) IsAllowEstimateToken() bool
func (*AiBasicInfo) IsFinalUsageSeen ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) IsFinalUsageSeen() bool
func (*AiBasicInfo) IsPriceMiss ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) IsPriceMiss() bool
IsPriceMiss reports whether MarkPriceMiss was recorded for this request.
func (*AiBasicInfo) IsResponseCompleted ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) IsResponseCompleted() bool
func (*AiBasicInfo) MarkFinalUsageSeen ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) MarkFinalUsageSeen()
func (*AiBasicInfo) MarkPriceMiss ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) MarkPriceMiss()
MarkPriceMiss records that the request's (model, mode) price entry was absent and its cost was computed with a fallback (or billed 0); the access log reports it as ai_price_miss (issue #1408).
func (*AiBasicInfo) MarkResponseCompleted ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) MarkResponseCompleted()
func (*AiBasicInfo) SetAllowEstimateToken ¶ added in v1.8.4
func (aiinfo *AiBasicInfo) SetAllowEstimateToken(allow bool)
func (*AiBasicInfo) SetUsageDisposition ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) SetUsageDisposition(disposition string)
SetUsageDisposition records whether the token usage of this request may be reported by the access log (issue #1409).
func (*AiBasicInfo) SetUsageSource ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) SetUsageSource(source string)
SetUsageSource records where the reported token usage came from (issue #1410); the access log reports it as ai_usage_source.
func (*AiBasicInfo) SetZeroCostReason ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) SetZeroCostReason(reason string)
SetZeroCostReason records why a zero-cost request was charged 0 (issue #1414); the access log reports it as ai_zero_cost_reason.
func (*AiBasicInfo) UsageDisposition ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) UsageDisposition() string
UsageDisposition returns the token-usage disposition set at request finish (UsageDispositionUnset when it was never judged).
func (*AiBasicInfo) UsageSource ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) UsageSource() string
UsageSource returns the usage source set at request finish (empty when it was never judged, e.g. the upstream call never succeeded).
func (*AiBasicInfo) ZeroCostReason ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) ZeroCostReason() string
ZeroCostReason returns the zero-cost reason (empty when the request was billed, when no RMB plan was bound, or when nothing judged it).
type AiBatchRouteHint ¶ added in v1.8.9
type AiBatchRouteHint struct {
BatchId string // batch_xxx for /v1/batches/{id}[...] operations
FileId string // file-xxx for /v1/files/{id}[...] operations
}
AiBatchRouteHint carries the batch/file identifiers of the current request from mod_ai_batch (which classifies the operation) to the reverse proxy (which performs batch-level key affinity in chooseAIKeyWithAffinity). It lives in bfe_basic so that bfe_server does not import module packages.
type AiError ¶ added in v1.8.3
type AiError struct {
Code string `json:"code"`
Type string `json:"type"`
Param *string `json:"param"`
Message string `json:"message"`
Details *AiErrorDetail `json:"details"`
}
func NewAiError ¶ added in v1.8.3
func NewAiErrorWithDetails ¶ added in v1.8.3
func NewAiErrorWithDetails(code, typeStr, message string, details *AiErrorDetail) *AiError
func (*AiError) CreateErrorResponse ¶ added in v1.8.3
func (*AiError) GenRespBody ¶ added in v1.8.3
func (aiError *AiError) GenRespBody() *AiErrorBody
func (*AiError) GenRespBodyStr ¶ added in v1.8.3
type AiErrorBody ¶ added in v1.8.3
type AiErrorBody struct {
Error AiError `json:"error"`
}
type AiErrorDetail ¶ added in v1.8.3
type AiErrorDetail struct {
ApiKey string `json:"api_key"`
KeyId string `json:"key_id"`
QuotaPlanId string `json:"quota_plan_id"`
LimitType string `json:"limit_type"`
Model string `json:"model"`
RetryAfterSeconds int `json:"retry_after_seconds"`
// UpstreamStatus/UpstreamCode are set by upstream error normalization
// (AIConf.NormalizeUpstreamError): the vendor's original HTTP status
// and error code, for cross-checking vendor documentation.
UpstreamStatus *int `json:"upstream_status,omitempty"`
UpstreamCode string `json:"upstream_code,omitempty"`
}
type AiIntent ¶ added in v1.8.9
type AiIntent struct {
QuestionsVersion string // version of the questions conf in use
Answers map[string]*IntentAnswer // answers by question name
Source string // answer source: header / model / cache
BackendVersion string // decision service backend version
LatencyMs int64 // classification latency in milliseconds
Resolved bool // true once resolve finished (even if all unknown)
ConsumedQuestion string // first question evaluated by route conditions; "" if none
ConsumedUnknown bool // that answer was below threshold (derived at read time)
}
AiIntent holds intent classification results for a request.
func GetAiIntent ¶ added in v1.8.9
GetAiIntent returns the intent classification result of the request, triggering lazy resolve on first call via the injected resolver.
type AiRateLimitHitInfo ¶ added in v1.8.3
type AiRateLimitHitInfo struct {
HitPolicyDict map[string]*HitPolicyInfo `json:"hit_rate_limit_policys"` //limite policy id -> HitPolicyInfo
}
func (*AiRateLimitHitInfo) GetPolicyHitInfo ¶ added in v1.8.3
func (obj *AiRateLimitHitInfo) GetPolicyHitInfo(policyId string) *HitPolicyInfo
type AiRouteFallback ¶ added in v1.8.4
type AiRouteResult ¶ added in v1.8.4
type AiRouteResult struct {
RouteType string // apikey / entity / global
Owner string // route table owner
RuleName string // hit rule name
Targets []AiRouteTarget
Fallbacks []AiRouteFallback
}
type AiRouteTarget ¶ added in v1.8.4
type BackendInfo ¶
type ClusterKeyName ¶ added in v1.8.5
ClusterKeyName represents a tried cluster and API-Key pair during request processing
type HitPolicyInfo ¶ added in v1.8.3
type IntentAnswer ¶ added in v1.8.9
type IntentAnswer struct {
QType string // question type: choice / score
Choice string // selected option; for score, level name derived from Score
Score float64 // expected level index, for score questions
LevelNames []string // ordered level names (low to high), for score questions
Probabilities map[string]float64 // option name / level name -> probability
AnswerConfidence float64 // confidence of the reported answer
Unknown bool // derived at read time, see Match()
}
IntentAnswer is the answer of a single intent question. It stores raw probabilities only: the Unknown flag is never persisted but derived at read time against the current MinConfidence threshold, so threshold hot-update takes effect immediately without re-classification.
type OperationStage ¶
type OperationStage int
const ( StageStartConn OperationStage = iota StageReadReqHeader StageReadReqBody StageConnBackend StageWriteBackend StageReadResponseHeader StageReadResponseBody StageWriteClient StageEndRequest )
type RedirectInfo ¶
type Request ¶
type Request struct {
Connection net.Conn
Session *Session
RemoteAddr *net.TCPAddr // address of remote peer
ClientAddr *net.TCPAddr // address of real client. Maybe nil if request is from
HttpRequest *bfe_http.Request // incoming request
OutRequest *bfe_http.Request // forwarded request
HttpResponse *bfe_http.Response // corresponding response
CookieMap bfe_http.CookieMap // cookie map
Query url.Values // save url query
LogId string // log id for each request
ReqBody []byte // req body, size is limited
ReqBodyPeeked bool // whether req body has been peeked
Route RequestRoute // for get backend cluster based on host/path/query/header/...
Tags RequestTags // request tag info
Trans RequestTransport // request transport
BfeStatusCode int // request directly return by bfe
ErrCode error // error code for handling request
ErrMsg string // additional error msg
Stat *RequestStat // time, data length, etc.
RetryTime int // times of retry
Backend BackendInfo // backend info
Redirect RedirectInfo // redirect info
SvrDataConf ServerDataConfInterface // interface for ServerDataConf
// User context associated with this request
Context map[interface{}]interface{}
IsSse bool
}
Request is a wrapper of HTTP request
func NewRequest ¶
func NewRequest(request *bfe_http.Request, conn net.Conn, stat *RequestStat, session *Session, svrDataConf ServerDataConfInterface) *Request
NewRequest creates and initializes a new request.
func (*Request) CachedCookie ¶
func (*Request) CachedQuery ¶
func (*Request) GetAiBasicInfo ¶ added in v1.8.3
func (r *Request) GetAiBasicInfo() *AiBasicInfo
Get user context by key.
func (*Request) GetAiBatchRouteHint ¶ added in v1.8.9
func (req *Request) GetAiBatchRouteHint() *AiBatchRouteHint
GetAiBatchRouteHint returns the hint set by mod_ai_batch, or nil.
func (*Request) GetAiRateLimitHitInfo ¶ added in v1.8.3
func (r *Request) GetAiRateLimitHitInfo() *AiRateLimitHitInfo
func (*Request) GetAiRouteResult ¶ added in v1.8.4
func (r *Request) GetAiRouteResult() *AiRouteResult
func (*Request) GetApikeyTags ¶ added in v1.8.3
func (*Request) GetContext ¶
func (req *Request) GetContext(key interface{}) interface{}
func (*Request) InitAiBasicInfo ¶ added in v1.8.3
func (r *Request) InitAiBasicInfo() *AiBasicInfo
Set user context by key and val.
func (*Request) InitAiRateLimitHitInfo ¶ added in v1.8.3
func (r *Request) InitAiRateLimitHitInfo() *AiRateLimitHitInfo
func (*Request) SetAiBatchRouteHint ¶ added in v1.8.9
func (req *Request) SetAiBatchRouteHint(hint *AiBatchRouteHint)
SetAiBatchRouteHint attaches the hint to the request context.
func (*Request) SetAiIntent ¶ added in v1.8.9
func (*Request) SetAiRouteResult ¶ added in v1.8.4
func (r *Request) SetAiRouteResult(result *AiRouteResult)
func (*Request) SetContext ¶
func (req *Request) SetContext(key, val interface{})
func (*Request) SetRequestTransport ¶
func (req *Request) SetRequestTransport(backend *backend.BfeBackend, transport bfe_http.RoundTripper)
type RequestRoute ¶
type RequestStat ¶
type RequestStat struct {
// time stat
ReadReqStart time.Time // after read first line of http request
ReadReqEnd time.Time // after read http request
FindProStart time.Time // just before find product
FindProEnd time.Time // after find product
LocateStart time.Time // just before find location
LocateEnd time.Time // after find location
ClusterStart time.Time // just before connect backend cluster
ClusterEnd time.Time // after get response from backend cluster
// info for last successful connected backend
BackendStart time.Time // just before connect backend
BackendEnd time.Time // after get response from backend
ResponseStart time.Time // before write response to client
ResponseEnd time.Time // after write response to client
BackendFirst time.Time // just before connect backend, for first invoke (retry may exist)
// data length
HeaderLenIn int // length of request header
BodyLenIn int // length of request body
HeaderLenOut int // length of response header
BodyLenOut int // length of response body
// some status
IsCrossCluster bool // with cross-cluster retry?
}
func NewRequestStat ¶
func NewRequestStat(start time.Time) *RequestStat
type RequestTags ¶
type RequestTransport ¶
type RequestTransport struct {
Backend *backend.BfeBackend // destination backend for request
Transport bfe_http.RoundTripper // transport to backend
}
type ServerDataConfInterface ¶
type ServerDataConfInterface interface {
ClusterTableLookup(clusterName string) (*bfe_cluster.BfeCluster, error)
HostTableLookup(hostname string) (string, error)
}
ServerDataConfInterface is an interface used for lookup config for each request
type Session ¶
type Session struct {
SessionId string // session id
StartTime time.Time // time of accept the connection
EndTime time.Time // time of close connection
Overhead time.Duration
Connection net.Conn
RemoteAddr *net.TCPAddr // client address
Use100Continue bool // "expect 100-continue" is used?
Proto string // protocol for the connection
IsSecure bool // over tls connection?
TlsState *bfe_tls.ConnectionState // tls state when using TLS
Vip net.IP // the virtual ip visited
Vport int // vip virtual port visited
Product string // product name of vip
Rtt uint32 // smoothed RTT for current connection (us)
// contains filtered or unexported fields
}
func NewSession ¶
NewSession creates and initializes a new session
func (*Session) ClearContext ¶ added in v1.2.0
func (s *Session) ClearContext()
ClearContext clears the old context and makes a new one.
func (*Session) GetContext ¶
func (s *Session) GetContext(key interface{}) interface{}
func (*Session) IncReqNumActive ¶
func (*Session) ReqNumActive ¶
func (*Session) SetContext ¶
func (s *Session) SetContext(key, val interface{})
func (*Session) SetReqNumActive ¶ added in v1.2.0
func (*Session) SetTrustSource ¶ added in v1.2.0
func (*Session) TrustSource ¶ added in v1.2.0
func (*Session) UpdateReadTotal ¶
func (*Session) UpdateWriteTotal ¶
func (*Session) WriteTotal ¶
type SessionStickyBackend ¶ added in v1.8.3
type TokenTimeInfo ¶ added in v1.8.3
type TokenTimeInfo struct {
TReqEnd int64 // Unix microsecond timestamp when the gateway finishes receiving the request body
TFirstToken int64 // Unix microsecond timestamp when the gateway receives the first chunk with valid generated text
TLastToken int64 // Unix microsecond timestamp when the last token is read
TTFT int64 // Time to first token (microseconds), TFirstToken - TReqEnd
TPOT int64 // Average time per output token (microseconds), (TLastToken - TFirstToken) / (CompletionTokens - 1)
}
type TokenUsage ¶ added in v1.8.3
type TokenUsage struct {
PromptTokens int64 // number of tokens in the prompt (includes cache_read_tokens, audio_input_tokens, image_input_tokens)
CompletionTokens int64 // number of tokens in the completion (includes audio_output_tokens)
CacheReadTokens int64 // usage.cache_read_tokens, already included in PromptTokens
CacheWriteTokens int64 // usage.cache_write_tokens, already included in PromptTokens (normalized for Anthropic)
CacheWriteTokens1h int64 // 1h-TTL cache write tokens (usage.cache_creation.ephemeral_1h_input_tokens), already included in CacheWriteTokens
AudioInputTokens int64 // usage.audio_input_tokens, already included in PromptTokens
AudioOutputTokens int64 // usage.audio_output_tokens, already included in CompletionTokens
ImageInputTokens int64 // usage.image_input_tokens / input_token_details.image_tokens, already included in PromptTokens
VideoCount int64 // number of generated videos for video generation models
ImageCount int64 // number of generated images for image generation models
UsedQuota int64 // used quota for this request (unit=total_token)
UsedCost int64 // used RMB cost for this request, 1 unit = 1e-8 yuan (unit=RMB)
}