gateway

package
v0.7.44 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 23 Imported by: 0 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

Index

Constants

This section is empty.

Variables

View Source
var ErrInflatedBodyTooLarge = errors.New("decompressed request body too large")

ErrInflatedBodyTooLarge is returned when a decompressed body exceeds the inflated limit. Unlike io.LimitReader, this is a hard reject: the caller must not continue with a truncated body.

View Source
var ErrUnsupportedContentEncoding = errors.New("unsupported content encoding")

ErrUnsupportedContentEncoding reports a Content-Encoding the gateway cannot decode. Callers turn it into a 415.

Functions

func BuildChatUsage

func BuildChatUsage(res executor.ChatResult) map[string]any

func ClassifyAPIError

func ClassifyAPIError(err error) executor.Classified

func ConversationIDFromContext added in v0.7.34

func ConversationIDFromContext(ctx context.Context) string

func IsStreamClientDisconnect

func IsStreamClientDisconnect(err error) bool

func SSEDeltaFinishReason added in v0.7.0

func SSEDeltaFinishReason(line string) string

func SSEDeltaHasToken

func SSEDeltaHasToken(line string) bool

func WithConversationID added in v0.7.34

func WithConversationID(ctx context.Context, id string) context.Context

WithConversationID records a client-supplied conversation/session id found in the decoded request. Headers win; body aliases are the compatibility path for clients that never send X-CLI2API-Session.

func WriteClassifiedErr

func WriteClassifiedErr(w http.ResponseWriter, err error)

Types

type CatalogQuery

type CatalogQuery func(refresh bool, accountID string) ([]map[string]any, error)

CatalogQuery loads the public /v1/models display catalog. Gateway must not import store or the runtime manager; app injects the catalog fetch path.

type Execution

type Execution struct {
	Context            context.Context
	RequestID          string
	Started            time.Time
	Request            translate.ChatRequest
	NativeRequest      *translate.NativeResponsesRequest
	UseNativeResponses bool
	PublicModel        string
	ProviderFilter     string
	Prefer             string
	// ResponseToolNames restores namespaced Responses tool identities on the
	// reply. Gateway-local: it is never handed to the executor or a provider.
	ResponseToolNames map[string]translate.ResponseToolName
}

type Handler

type Handler struct {
	Executor          executor.ChatExecutor
	Pool              *executor.Pool
	Recorder          *applogs.RequestRecorder
	ModelContexts     executor.ModelContextStore
	Catalogs          executor.CatalogPreparer
	Logs              executor.RequestStarter
	CrossProviderPool *atomic.Bool
	Models            CatalogQuery
	CatalogStatus     func() map[string]any
	RequestedAccount  func(*http.Request) string
	FilterModels      func(*http.Request, []map[string]any) []map[string]any
	DecorateModels    func(*http.Request, []map[string]any) []map[string]any
	// AfterAccountUse is an optional non-blocking quota invalidation hook. It
	// runs after the response/stream finishes, never on receipt of SSE headers.
	AfterAccountUse func(accountID, publicModel string)
	// KeyLimits caps concurrent chat requests per named API key. Nil means
	// unlimited, which tests and the console chat path rely on.
	KeyLimits *KeyInFlight
}

func (*Handler) HandleAnthropicMessages

func (h *Handler) HandleAnthropicMessages(w http.ResponseWriter, r *http.Request)

func (*Handler) HandleChatCompletions

func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request)

func (*Handler) HandleModels

func (h *Handler) HandleModels(w http.ResponseWriter, r *http.Request)

func (*Handler) HandleResponses

func (h *Handler) HandleResponses(w http.ResponseWriter, r *http.Request)

func (*Handler) PrepareChatExecution

func (h *Handler) PrepareChatExecution(r *http.Request, request translate.ChatRequest) (Execution, error)

func (*Handler) PrepareCompatibilityExecution

func (h *Handler) PrepareCompatibilityExecution(r *http.Request, request translate.ChatRequest) (Execution, error)

func (*Handler) PrepareNativeResponsesExecution added in v0.6.7

func (h *Handler) PrepareNativeResponsesExecution(r *http.Request, native *translate.NativeResponsesRequest, compat translate.ChatRequest) (Execution, error)

type KeyInFlight added in v0.7.34

type KeyInFlight struct {
	// contains filtered or unexported fields
}

KeyInFlight tracks concurrent chat requests per named API key. The cap is read from the authenticated identity on each acquire, so an edit takes effect on the next request without restarting. Console traffic is not counted. Counts live in memory and reset on process restart, same as account in-flight slots.

type StreamFlushWriter

type StreamFlushWriter struct {
	W http.ResponseWriter
	F http.Flusher
}

func (StreamFlushWriter) Write

func (w StreamFlushWriter) Write(data []byte) (int, error)

type StreamRelayStats

type StreamRelayStats struct {
	PromptTokens     *int
	CompletionTokens *int
	CacheReadTokens  *int
	CacheWriteTokens *int
	CachedTokens     *int
	UsageSource      string
	Credits          *float64
	ConsumedCredits  *float64
	Model            string
	FinishReason     string
	FirstTokenAt     *time.Time
	SSEEventCount    int
	BytesRead        int64
	LastEvent        string
	SawDone          bool
}

func ParseStreamUsageLine

func ParseStreamUsageLine(line string) (StreamRelayStats, bool)

func RelayAnthropicStream

func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model string) (StreamRelayStats, error)

func RelayNativeResponsesStream added in v0.6.7

func RelayNativeResponsesStream(writer io.Writer, body io.Reader, names map[string]translate.ResponseToolName) (StreamRelayStats, error)

RelayNativeResponsesStream relays an upstream OpenAI Responses SSE body while observing the frames needed for accounting: first-token timing, terminal status, and token usage. It writes no events of its own — the upstream already emits a well-formed stream including response.created / response.completed.

Frames are relayed verbatim except for one rewrite: when names is non-empty, flattened namespace tool names (the form providers receive) are restored to the caller's namespace + name on function_call items, exactly as the compatibility relay does. Frames that carry no such tool call stay byte-for-byte.

func RelayOpenAIStream

func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelayStats, returnErr error)

func RelayResponsesStream

func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model string, names map[string]translate.ResponseToolName) (StreamRelayStats, error)

type StreamRelayWriteError

type StreamRelayWriteError struct {
	// contains filtered or unexported fields
}

func (*StreamRelayWriteError) Error

func (e *StreamRelayWriteError) Error() string

func (*StreamRelayWriteError) Unwrap

func (e *StreamRelayWriteError) Unwrap() error

Jump to

Keyboard shortcuts

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