Documentation
¶
Index ¶
- Constants
- Variables
- 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 GetApiKey(req *Request) string
- func IsOpenAIEndpoint(path string) bool
- 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) IsResponseCompleted() bool
- func (aiinfo *AiBasicInfo) MarkFinalUsageSeen()
- func (aiinfo *AiBasicInfo) MarkResponseCompleted()
- func (aiinfo *AiBasicInfo) SetAllowEstimateToken(allow bool)
- type AiError
- type AiErrorBody
- type AiErrorDetail
- type AiRateLimitHitInfo
- type AiRouteFallback
- type AiRouteResult
- type AiRouteTarget
- type ApikeyTag
- type BackendInfo
- type ClusterKeyName
- type HitPolicyInfo
- 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 (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 (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" )
AI request modes, inferred from request path.
const ( AuthStyleOpenAI = "openai" AuthStyleAnthropic = "anthropic" AuthStyleGemini = "gemini" AuthStyleUnknown = "unknown" )
AI protocol/auth styles.
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" CodeProviderProtocolMismatch = "PROVIDER_PROTOCOL_MISMATCH" 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" )
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 (
COMPLETION_TOKENS_UNKNOWN = -1
)
const CtxAiRouteResult = "__REQ_AI_ROUTE_RESULT"
const (
GlobalProduct = "global"
)
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 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, CodeConfigLoadError: 500, CodeBackendUnavailable: 502, CodeInvalidRequestBody: 400, CodeModelParamMissing: 400, CodeUserQuotaExhausted: 429, CodeSessionQuotaExhausted: 429, CodeFunctionQuotaExhausted: 429, CodeCostBudgetExhausted: 429, CodeGeoRestricted: 403, CodeTimeWindowRestricted: 403, CodeProviderProtocolMismatch: 400, }
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 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 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 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
// 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) 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) MarkResponseCompleted ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) MarkResponseCompleted()
func (*AiBasicInfo) SetAllowEstimateToken ¶ added in v1.8.4
func (aiinfo *AiBasicInfo) SetAllowEstimateToken(allow bool)
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 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 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) 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) 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)
}