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
- func EstimateContentToken(val string) int64
- func FirstNonEmpty(ss ...string) string
- type DefaultErrorNormalizer
- type ErrorNormalizer
- type ErrorParser
- type ProtocolError
- type StreamEndsAtEOFReporter
- type StreamErrorEventBuilder
- type StreamErrorParser
- type StreamEvent
- type StreamTerminalMarkersReporter
- type UsageFields
Constants ¶
const ( CodeUpstreamInvalidRequest = "UPSTREAM_INVALID_REQUEST" CodeUpstreamRateLimited = "UPSTREAM_RATE_LIMITED" CodeUpstreamQuotaExhausted = "UPSTREAM_QUOTA_EXHAUSTED" CodeUpstreamAuthError = "UPSTREAM_AUTH_ERROR" CodeUpstreamModelNotFound = "UPSTREAM_MODEL_NOT_FOUND" CodeUpstreamOverloaded = "UPSTREAM_OVERLOADED" CodeUpstreamUnknown = "UPSTREAM_UNKNOWN" // Activated reserved codes (shared catalog, defined in bfe_basic). CodeContextLengthExceeded = "CONTEXT_LENGTH_EXCEEDED" CodeContentFiltered = "CONTENT_FILTERED" CodeModelInternalError = "MODEL_INTERNAL_ERROR" CodeBackendTimeout = "BACKEND_TIMEOUT" )
Normalized upstream error catalog codes. The string values mirror the AiError catalog in bfe_basic/request_ai_basic.go; they live in this leaf package so protocol adapters (which never depend on other BFE packages) and the bfe_basic catalog share a single source.
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.
func FirstNonEmpty ¶ added in v1.8.9
FirstNonEmpty returns the first non-empty string of its arguments.
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.
This is the internal fault-tolerance seam (shouldTriggerFallback); it stays decoupled from the client-facing ErrorParser below so that enabling client-side normalization never changes fallback semantics.
type ErrorParser ¶ added in v1.8.9
type ErrorParser interface {
ParseError(statusCode int, body []byte, header http.Header) *ProtocolError
}
ErrorParser parses a non-streaming upstream error envelope into a ProtocolError. Returning nil means the body was not recognized as a protocol error envelope; the caller then applies its configured unrecognized-action (pass-through by default). Client-facing normalization (AIConf.NormalizeUpstreamError) uses this interface.
type ProtocolError ¶
type ProtocolError struct {
Code string // normalized gateway catalog code
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
// UpstreamCode is the vendor's original error code (OpenAI error.code /
// Anthropic error.type / Gemini error.status), kept for logging and
// the error.details.upstream_code field.
UpstreamCode string
// Param carries the vendor's error.param when present.
Param *string
// RetryAfterSeconds is parsed from the upstream Retry-After header
// (429 only); 0 when absent.
RetryAfterSeconds int
}
ProtocolError is the normalized form of an upstream error response. Code carries the gateway catalog code (e.g. UPSTREAM_RATE_LIMITED); the legacy retry booleans are filled for future fault-tolerance use and are not consumed by the client-facing normalization path.
type StreamEndsAtEOFReporter ¶ added in v1.8.9
type StreamEndsAtEOFReporter interface {
StreamEndsAtEOF() bool
}
StreamEndsAtEOFReporter is an optional adapter capability: when implemented and returning true, the protocol's streams end at HTTP EOF and absence of a terminal event must NOT be reported as truncation (e.g. Gemini streamGenerateContent).
type StreamErrorEventBuilder ¶ added in v1.9.0
type StreamErrorEventBuilder interface {
// NativeStreamErrorEvent builds an error event in the protocol's own
// error envelope, carrying message.
NativeStreamErrorEvent(message string) []byte
// WrapStreamErrorPayload wraps an already-serialized error JSON payload
// (e.g. the unified AiError body) into the protocol's SSE error event.
WrapStreamErrorPayload(payload string) []byte
}
StreamErrorEventBuilder is an optional adapter capability (issue #1474): it builds the protocol's wire-level SSE error event for a gateway-side stream termination (upstream connection dropped mid-stream). Both methods return one complete SSE event including its terminating blank line.
type StreamErrorParser ¶ added in v1.8.9
type StreamErrorParser interface {
ParseStreamError(ev StreamEvent) *ProtocolError
}
StreamErrorParser inspects a single streaming (SSE) event. Returning non-nil means the event is an error event and carries the normalized form; the caller rewrites the event data payload with the unified error body. Returning nil means the event is not an error event and is passed through unchanged.
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 StreamTerminalMarkersReporter ¶ added in v1.9.0
type StreamTerminalMarkersReporter interface {
StreamTerminalMarkers() [][]byte
}
StreamTerminalMarkersReporter is an optional adapter capability (issue #1474): wire-level byte markers that terminate the protocol's stream. Pass-through filters that do not parse SSE events use them for cheap truncation detection; returning nil markers means the filter cannot detect termination and must not inject.
type UsageFields ¶
type UsageFields struct {
// UsagePresent records that the upstream response actually carried a
// usage object (the key exists), regardless of the values inside it
// (issue #1414). It is what distinguishes an upstream that explicitly
// reports all-zero usage from an upstream that reports none: the
// callers classify and bill by presence, not by "some value is > 0".
UsagePresent bool
// PromptPresent records that this usage object actually carried the
// prompt/input token field. Anthropic's streaming final usage
// (message_delta) omits it, so "absent" must be told apart from
// "reported as 0" before an earlier prompt is carried over during
// streaming accumulation (issue #1414).
PromptPresent bool
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.