bfe_model_protocol

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 8 Imported by: ? 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

Overview

Package bfe_model_protocol hosts the per-protocol (model_protocol) adapters that carry all protocol knowledge of the AI gateway: auth header injection, supplementary headers (e.g. anthropic-version), usage field extraction and upstream error normalization. Adding a new protocol means adding one detection rule in detect.go plus one adapter package registered in registry.go, without touching the callers.

The concrete UsageFields / ProtocolError / ErrorNormalizer types live in the utils sub-package (a leaf with no BFE dependencies) so that adapter subpackages can reference them without import cycles; this package re-exports them via aliases.

Index

Constants

View Source
const (
	CodeUpstreamInvalidRequest = utils.CodeUpstreamInvalidRequest
	CodeUpstreamRateLimited    = utils.CodeUpstreamRateLimited
	CodeUpstreamQuotaExhausted = utils.CodeUpstreamQuotaExhausted
	CodeUpstreamAuthError      = utils.CodeUpstreamAuthError
	CodeUpstreamModelNotFound  = utils.CodeUpstreamModelNotFound
	CodeUpstreamOverloaded     = utils.CodeUpstreamOverloaded
	CodeUpstreamUnknown        = utils.CodeUpstreamUnknown

	CodeContextLengthExceeded = utils.CodeContextLengthExceeded
	CodeContentFiltered       = utils.CodeContentFiltered
	CodeModelInternalError    = utils.CodeModelInternalError
	CodeBackendTimeout        = utils.CodeBackendTimeout
)

Normalized upstream error catalog codes (single source in utils).

View Source
const (
	ProtocolOpenAI    = utils.ProtocolOpenAI
	ProtocolAnthropic = utils.ProtocolAnthropic
	ProtocolGemini    = utils.ProtocolGemini
	ProtocolUnknown   = utils.ProtocolUnknown
)

Model protocol identifiers.

Variables

This section is empty.

Functions

func CredentialHeaderNames added in v1.8.9

func CredentialHeaderNames() []string

CredentialHeaderNames returns the credential headers declared by the registered adapters, in canonical form and sorted. These are the headers a client may use to authenticate to BFE (detect.go recognizes the same set), and therefore the set that must not survive into an outbound request whose credential is injected by the gateway (issue #1447: an upstream picks its credential by its own provider-private priority, so a residual client header would override the injected one). The list is derived from the registry, so a newly registered protocol is covered without further work.

func DetectProtocol

func DetectProtocol(req *bfe_http.Request) string

DetectProtocol 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. A nil request (or one without a URL) reports ProtocolUnknown.

func DetectProtocolAndKey

func DetectProtocolAndKey(req *bfe_http.Request) (protocol, key string)

DetectProtocolAndKey extracts the client API key and the request's protocol/auth style from the request headers. Authorization: Bearer is preferred (the "Bearer " and "sk-" prefixes are stripped); it falls back to the x-api-key header (Anthropic style), then to the x-goog-api-key header (Gemini style). When no credential header is present it returns empty strings.

func ExtractModelFromPath added in v1.8.8

func ExtractModelFromPath(req *bfe_http.Request) string

ExtractModelFromPath returns the model name carried in the request path for protocols that put it there (currently only Gemini: /v1beta/models/{model}[:action], see issue #1384). It returns "" for protocols that carry the model in the request body (openai/anthropic), for unrecognized paths, and for nil requests. This is the single entry point for path-based model extraction; future protocols with the same trait extend it here.

func ForeignCredentialHeaders added in v1.8.9

func ForeignCredentialHeaders(h bfe_http.Header, keep string) []string

ForeignCredentialHeaders returns the recognized credential headers present in h other than keep, in canonical form. A header present with an empty value counts as present: an empty residual header is harmless upstream today, but "present means remove" keeps the rule unambiguous. keep may be given in any case; an empty keep selects every recognized credential header.

func Register

func Register(a ProtocolAdapter)

Register adds a protocol adapter to the registry.

func RemoveForeignCredentialHeaders added in v1.8.9

func RemoveForeignCredentialHeaders(h bfe_http.Header, keep string) []string

RemoveForeignCredentialHeaders deletes every recognized credential header other than keep from h and returns the removed header names. Unrecognized credential-like headers (e.g. an Azure-style api-key) are left untouched.

func Supports

func Supports(protocols []string, p string) bool

Supports reports whether protocol p is in the protocols list. An empty list defaults to openai only, preserving backward compatibility of AIConf.ModelProtocols.

func ValidateProtocols

func ValidateProtocols(protocols []string) error

ValidateProtocols checks that every value is a protocol known to the registry. An empty list is valid (callers default it to ["openai"]).

Types

type ErrorNormalizer

type ErrorNormalizer = utils.ErrorNormalizer

ErrorNormalizer parses an upstream error body into a ProtocolError. The canonical definition lives in the utils sub-package; it is re-exported here so callers only need to import bfe_model_protocol.

type ErrorParser added in v1.8.9

type ErrorParser = utils.ErrorParser

ErrorParser parses a non-streaming upstream error envelope into a ProtocolError (client-facing normalization path).

type ProtocolAdapter

type ProtocolAdapter interface {
	Key() string

	// InjectAuth writes the upstream credential into the outgoing request.
	// An empty key is a no-op.
	InjectAuth(outreq *bfe_http.Request, key string) error

	// CredentialHeader returns the header InjectAuth writes the upstream
	// credential into, in canonical form (e.g. "Authorization"). Together
	// with the other adapters' credential headers it forms the set of client
	// credential headers that must not survive into an outbound request
	// carrying a gateway-injected credential (issue #1447).
	CredentialHeader() string

	// ExtraHeaders returns protocol-level supplementary headers (e.g.
	// anthropic-version). It returns nil when there are none.
	ExtraHeaders() map[string]string

	// ExtractUsageFields extracts usage fields from one response body
	// (SSE event data or a complete non-streaming body).
	ExtractUsageFields(data []byte) UsageFields

	// ErrorNormalizer returns the upstream error normalizer for this
	// protocol. The phase-1 default never recognizes errors, so callers
	// keep their existing status-code whitelist.
	ErrorNormalizer() ErrorNormalizer

	// ErrorParser returns the client-facing upstream error parser used by
	// normalization (AIConf.NormalizeUpstreamError). Unlike
	// ErrorNormalizer (the fault-tolerance seam), this parser serves the
	// caller-facing rewrite path only and never affects fallback
	// decisions.
	ErrorParser() ErrorParser

	// StreamErrorParser returns the per-event SSE error parser: non-nil
	// result means the event is an error event whose data payload the
	// caller rewrites with the unified error body.
	StreamErrorParser() StreamErrorParser

	// IsStreamTerminal reports whether the given event terminates the
	// response stream (e.g. Anthropic message_stop, OpenAI [DONE]).
	// Protocols without an SSE termination event (Gemini) always return
	// false; their streams end at HTTP EOF, which the callers already
	// handle as a fallback.
	IsStreamTerminal(ev StreamEvent) bool

	// IsFinalUsageEvent reports whether the given event carries the final
	// usage of the response. Callers only consult it for events that
	// already parsed a non-guess usage, and only mark the final usage when
	// completion tokens are present.
	IsFinalUsageEvent(ev StreamEvent) bool
}

ProtocolAdapter carries all protocol knowledge of one model_protocol. Adapters are stateless singletons held by the compile-time registry; per-cluster differences (which key to use) are passed via method arguments and never stored on the adapter.

func Get

func Get(protocol string) ProtocolAdapter

Get returns the adapter for the given protocol. Unknown or empty protocol names fall back to the openai adapter, matching the previous hard-coded fallback behavior.

type ProtocolError

type ProtocolError = utils.ProtocolError

ProtocolError is the normalized form of an upstream error response. The canonical definition lives in the utils sub-package; it is re-exported here so callers only need to import bfe_model_protocol.

type StreamEndsAtEOFReporter added in v1.8.9

type StreamEndsAtEOFReporter = utils.StreamEndsAtEOFReporter

StreamEndsAtEOFReporter is the optional adapter capability marking protocols whose streams end at HTTP EOF (no truncation reporting).

type StreamErrorParser added in v1.8.9

type StreamErrorParser = utils.StreamErrorParser

StreamErrorParser inspects a single SSE event for error semantics.

type StreamEvent

type StreamEvent = utils.StreamEvent

StreamEvent is the protocol-neutral view of a single streaming (SSE) event. The canonical definition lives in the utils sub-package; it is re-exported here so callers only need to import bfe_model_protocol.

type UsageFields

type UsageFields = utils.UsageFields

UsageFields is the protocol-neutral result of usage extraction. The canonical definition lives in the utils sub-package; it is re-exported here so callers only need to import bfe_model_protocol.

Directories

Path Synopsis
Package anthropic implements the model_protocol adapter for the Anthropic (Claude) protocol.
Package anthropic implements the model_protocol adapter for the Anthropic (Claude) protocol.
Package gemini implements the model_protocol adapter for the Google Gemini protocol (generateContent / streamGenerateContent).
Package gemini implements the model_protocol adapter for the Google Gemini protocol (generateContent / streamGenerateContent).
Package openai implements the model_protocol adapter for the OpenAI protocol family (OpenAI chat/completions, DeepSeek, Groq and the OpenAI Responses API).
Package openai implements the model_protocol adapter for the OpenAI protocol family (OpenAI chat/completions, DeepSeek, Groq and the OpenAI Responses API).
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.
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.

Jump to

Keyboard shortcuts

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