Documentation
¶
Overview ¶
Package utils holds protocol-neutral helpers shared by the model-protocol adapters: protocol name constants, the neutral usage result structure, upstream-error normalization types and the gjson usage extraction chains. It intentionally depends only on the standard library and third-party packages so that both bfe_model_protocol and its adapter subpackages can import it without cycles.
Index ¶
Constants ¶
const ( ProtocolOpenAI = "openai" ProtocolAnthropic = "anthropic" ProtocolGemini = "gemini" ProtocolUnknown = "unknown" )
Model protocol identifiers.
Variables ¶
This section is empty.
Functions ¶
func EstimateContentToken ¶
EstimateContentToken estimates the token count of a response body chunk. It assumes roughly 4 bytes per token. Moved verbatim from bfe_modules/mod_body_process/llm_util.go.
Types ¶
type DefaultErrorNormalizer ¶
type DefaultErrorNormalizer struct{}
DefaultErrorNormalizer is the phase-1 error normalizer: it never recognizes an error, so callers keep using their existing status-code whitelist. Protocol adapters return it until a protocol-specific normalization is implemented.
func (DefaultErrorNormalizer) Normalize ¶
func (DefaultErrorNormalizer) Normalize(statusCode int, body []byte, header http.Header) *ProtocolError
type ErrorNormalizer ¶
type ErrorNormalizer interface {
Normalize(statusCode int, body []byte, header http.Header) *ProtocolError
}
ErrorNormalizer parses an upstream error body into a ProtocolError. Returning nil means the error was not recognized and the caller falls back to its existing handling (the status-code whitelist in phase 1). body may be nil.
type ProtocolError ¶
type ProtocolError struct {
Code string // auth_invalid | rate_limited | model_not_found | server_error | unknown
StatusCode int // upstream HTTP status code
IsUpstream bool // true=upstream error (may swap key / fallback), false=gateway-side error
Retryable bool // retry with the same key after backoff
SwapKey bool // rotate to another key (e.g. 429)
MarkDead bool // mark the key as dead (e.g. 401/402/403)
Message string
}
ProtocolError is the normalized form of an upstream error response.
type StreamEvent ¶
StreamEvent is the protocol-neutral view of a single streaming (SSE) event used by the adapters' stream-termination and final-usage decisions. Type is the top-level "type" field of the event data payload ("" when absent, e.g. OpenAI usage chunks); Data is the raw event data. It deliberately lives in this leaf package so that ProtocolAdapter implementations never depend on BFE module types such as mod_body_process.SSEEvent.
type UsageFields ¶
type UsageFields struct {
UsedQuota int64
PromptTokens int64
CompletionTokens int64
CacheReadTokens int64
CacheWriteTokens int64
CacheWriteTokens1h int64 // 1h-TTL cache write tokens, already included in CacheWriteTokens
AudioInputTokens int64
AudioOutputTokens int64
ImageInputTokens int64
ImageCount int64
VideoCount int64
}
UsageFields is the protocol-neutral result of usage extraction. The two callers of the extraction chains (mod_body_process.QuotaUsage and bfe_basic.TokenUsage) each map these fields onto their own structures, so this package stays free of dependencies on bfe_basic / bfe_modules.
func ParseAnthropicUsageFields ¶
func ParseAnthropicUsageFields(data []byte) UsageFields
ParseAnthropicUsageFields extracts usage fields from Anthropic (Claude) response bodies: input_tokens / output_tokens / cache_read_input_tokens / cache_creation_input_tokens.
Anthropic input_tokens only counts fresh (cache-missing) tokens and excludes cache read/write tokens. Normalize PromptTokens to the total input token count so downstream cost splitting (prompt - cacheRead - cacheWrite) works the same as the OpenAI/DeepSeek semantics.
In streaming responses the initial usage is nested under message.usage (message_start); the final usage arrives in the top-level usage of the message_delta event. Both shapes are accepted.
func ParseGeminiUsageFields ¶
func ParseGeminiUsageFields(data []byte) UsageFields
ParseGeminiUsageFields extracts usage fields from Gemini response bodies. The usage block is the top-level "usageMetadata" object with camelCase fields:
promptTokenCount -> PromptTokens (already includes the cached content tokens) candidatesTokenCount -> CompletionTokens cachedContentTokenCount -> CacheReadTokens (a subset of PromptTokens) totalTokenCount -> UsedQuota
When totalTokenCount is absent, UsedQuota falls back to promptTokenCount + candidatesTokenCount. In streaming responses every chunk carries the accumulated usageMetadata, so callers must consume the last usage-bearing chunk (see the gemini adapter's IsFinalUsageEvent).
func ParseOpenAIUsageFields ¶
func ParseOpenAIUsageFields(data []byte) UsageFields
ParseOpenAIUsageFields extracts usage fields from OpenAI-family response bodies: the OpenAI chat main chain plus the DeepSeek and Responses API cache-read fallbacks, and the Responses API input/output_tokens chains (issue #1381). The Claude (Anthropic) fallback chain is NOT part of this extraction; it lives in ParseAnthropicUsageFields.
func ParseUsageFieldsCrossProtocol ¶
func ParseUsageFieldsCrossProtocol(data []byte) UsageFields
ParseUsageFieldsCrossProtocol extracts usage fields by composing the protocol chains: the OpenAI-family chain first, then the Anthropic (Claude) chain when no OpenAI-style prompt/completion tokens are present, then the Gemini chain when still none are present. This mirrors the legacy all-chain extraction field-for-field and is response-format-agnostic: it recovers the full usage even when the auth style detected from the request does not match the format of the response body (issue #1364, e.g. a Bearer key detected as openai while the backend returns an Anthropic body). The Gemini fields are camelCase and never conflict with the OpenAI snake_case fields, but the chain is kept as an explicit third stage to preserve the cross-protocol mismatch fallback.