proxy

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0

Documentation

Overview

Package proxy provides a high-performance LLM request proxy with support for multiple providers, intelligent routing, caching, and extensible middleware.

Package proxy provides the core business logic for LLM request proxying

Index

Constants

View Source
const (
	// CacheStatusKey is the context key for cache status
	CacheStatusKey contextKey = "X-Cache"

	// CacheStatusHit indicates a cache hit
	CacheStatusHit = "HIT"
	// CacheStatusMiss indicates a cache miss
	CacheStatusMiss = "MISS"
)

Variables

View Source
var (
	// ErrNoValidModel indicates no valid model was specified
	ErrNoValidModel = errors.New("no valid model specified")

	// ErrNoAvailableProvider indicates no provider is available for the request
	ErrNoAvailableProvider = errors.New("no available provider for model")

	// ErrInvalidRequest indicates the request is malformed
	ErrInvalidRequest = errors.New("invalid request")

	// ErrProviderUnavailable indicates the provider is temporarily unavailable
	ErrProviderUnavailable = errors.New("provider temporarily unavailable")

	// ErrRateLimitExceeded indicates rate limit has been exceeded
	ErrRateLimitExceeded = errors.New("rate limit exceeded")

	// ErrInsufficientQuota indicates the user has insufficient quota
	ErrInsufficientQuota = errors.New("insufficient quota")

	// ErrStreamingNotSupported indicates streaming is not supported for this request
	ErrStreamingNotSupported = errors.New("streaming not supported")

	// ErrEmbeddingsNotSupported indicates embeddings are not supported by the provider
	ErrEmbeddingsNotSupported = errors.New("embeddings not supported by provider")
)

Common proxy errors

Functions

func ExtractProviderFromModel

func ExtractProviderFromModel(modelID string) (provider, model string)

ExtractProviderFromModel extracts a provider-scoped model ID.

func GenerateCompletionID

func GenerateCompletionID() string

GenerateCompletionID generates a unique ID for a completion

func GetRequestStartTime

func GetRequestStartTime(ctx context.Context) (time.Time, bool)

GetRequestStartTime retrieves the request start time from context.

func NormalizeModelID

func NormalizeModelID(modelID string) string

NormalizeModelID preserves provider-scoped and canonical model IDs.

func TransformChatRequest

func TransformChatRequest(req *ChatCompletionRequest) (*connectors.ChatRequest, error)

TransformChatRequest converts the canonical use-case request at the provider boundary.

func TransformEmbeddingsRequest

func TransformEmbeddingsRequest(req *EmbeddingsRequest) *connectors.EmbeddingsRequest

TransformEmbeddingsRequest converts a proxy EmbeddingsRequest to a connector EmbeddingsRequest

func ValidateChatCompletionRequest

func ValidateChatCompletionRequest(req *ChatCompletionRequest) error

ValidateChatCompletionRequest validates one canonical gateway chat request.

func ValidateEmbeddingsRequest

func ValidateEmbeddingsRequest(req *EmbeddingsRequest) error

ValidateEmbeddingsRequest validates one canonical embedding request.

Types

type APIKeyRoutingConfig

type APIKeyRoutingConfig struct {
	AllowedProviders []string
	AllowedModels    []string
	ModelOverrides   map[string]string
	RateLimitTier    string
}

APIKeyRoutingConfig contains API-key scoped routing restrictions.

type Builder

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

Builder provides a fluent interface for building proxy configuration.

func NewBuilder

func NewBuilder(registry *registry.Registry, router router.ModelRouter) *Builder

NewBuilder creates a new proxy configuration builder.

func (*Builder) Build

func (b *Builder) Build() Proxy

Build creates the proxy service with the configured options.

func (*Builder) WithCache

func (b *Builder) WithCache(manager *cache.Manager, config *CacheConfig) *Builder

WithCache adds caching to the proxy.

func (*Builder) WithMiddleware

func (b *Builder) WithMiddleware(m Middleware) *Builder

WithMiddleware adds a middleware to the proxy.

func (*Builder) WithOptions

func (b *Builder) WithOptions(opts *Options) *Builder

WithOptions adds advanced options to the proxy.

type CacheConfig

type CacheConfig struct {
	// Enable caching for different endpoints
	EnableChatCache      bool `env:"ENABLE_CHAT_CACHE,default=true"`
	EnableEmbeddingCache bool `env:"ENABLE_EMBEDDING_CACHE,default=true"`
	EnableModelCache     bool `env:"ENABLE_MODEL_CACHE,default=true"`
	EnableProviderCache  bool `env:"ENABLE_PROVIDER_CACHE,default=true"`
	// Skip cache for specific models or patterns
	SkipCacheModels []string `env:"SKIP_CACHE_MODELS"`
	// Force cache refresh header
	CacheControlHeader string `env:"CACHE_CONTROL_HEADER,default=X-Cache-Control"`
}

CacheConfig defines caching behavior

type CacheCost

type CacheCost struct {
	WriteTokens float64 `json:"write_tokens"` // Cost of writing tokens to cache
	ReadTokens  float64 `json:"read_tokens"`  // Cost of reading tokens from cache
	TotalCost   float64 `json:"total_cost"`   // Total cost including cache operations
}

CacheCost represents the cost of cache operations

type CacheManager

type CacheManager interface {
	GetModel(ctx context.Context, key string) (any, bool, error)
	SetModel(ctx context.Context, key string, value any) error
	GetResponse(ctx context.Context, key string) ([]byte, bool, error)
	SetResponse(ctx context.Context, key string, response []byte) error
}

CacheManager interface defines the cache operations used by the proxy

type CacheMiddleware

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

CacheMiddleware provides caching functionality for proxy services.

func (*CacheMiddleware) Wrap

func (m *CacheMiddleware) Wrap(next Proxy) Proxy

Wrap wraps the service with caching functionality.

type CacheStatusProvider

type CacheStatusProvider interface {
	GetCacheStatus() string
	GetCacheAge() int // Returns cache age in seconds, or 0 if not cached
}

CacheStatusProvider is an interface to check cache status on streams

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Request  inference.ChatRequest
	Route    string
	Provider *ProviderPreferences

	// Internal fields
	APIKey       string               `json:"-"`
	TenantID     string               `json:"-"`
	APIKeyConfig *APIKeyRoutingConfig `json:"-"`
	RequestID    string               `json:"-"`
}

ChatCompletionRequest is a canonical chat request plus gateway policy and identity.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	Response inference.ChatResponse

	// Internal fields (not serialized)
	CacheStatus string     `json:"-"`
	CacheAge    int        `json:"-"` // Seconds since cached
	ETag        string     `json:"-"` // Entity tag for response
	CacheCost   *CacheCost `json:"-"` // Cache pricing information
}

ChatCompletionResponse is a canonical result plus gateway response metadata.

func TransformChatResponse

func TransformChatResponse(resp *connectors.ChatResponse, modelUsed string) (*ChatCompletionResponse, error)

TransformChatResponse converts a connector ChatResponse to a proxy ChatCompletionResponse

type ChatCompletionStreamResponse

type ChatCompletionStreamResponse interface {
	// Read returns the next canonical event or io.EOF when done.
	Read() (*inference.StreamEvent, error)

	// Close releases any resources
	Close() error
}

ChatCompletionStreamResponse represents a streaming response

type Config

type Config struct {
	// Registry provides access to LLM provider connectors
	Registry *registry.Registry

	// Router handles intelligent model selection and failover
	Router router.ModelRouter

	// CacheManager handles response caching (optional)
	CacheManager *cache.Manager

	// CacheConfig configures caching behavior (optional)
	CacheConfig *CacheConfig

	// Middlewares to apply to the proxy service
	Middlewares []Middleware
}

Config holds the configuration for creating a new proxy service.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default proxy configuration.

type EmbeddingsRequest

type EmbeddingsRequest struct {
	Request inference.EmbeddingRequest

	// Internal fields
	APIKey       string               `json:"-"`
	TenantID     string               `json:"-"`
	APIKeyConfig *APIKeyRoutingConfig `json:"-"`
	RequestID    string               `json:"-"`
}

EmbeddingsRequest is a canonical embedding request plus gateway identity.

type EmbeddingsResponse

type EmbeddingsResponse struct {
	Response inference.EmbeddingResponse

	// Internal fields (not serialized)
	CacheStatus string     `json:"-"`
	CacheAge    int        `json:"-"` // Seconds since cached
	ETag        string     `json:"-"` // Entity tag for response
	CacheCost   *CacheCost `json:"-"` // Cache pricing information
}

EmbeddingsResponse is a canonical embedding result plus gateway metadata.

func TransformEmbeddingsResponse

func TransformEmbeddingsResponse(resp *connectors.EmbeddingsResponse) (*EmbeddingsResponse, error)

TransformEmbeddingsResponse converts a connector EmbeddingsResponse to a proxy EmbeddingsResponse

type EndpointInfo

type EndpointInfo struct {
	Provider   string `json:"provider"`
	Endpoint   string `json:"endpoint"`
	Available  bool   `json:"available"`
	Latency    *int   `json:"latency_ms,omitempty"`
	CostPrompt string `json:"cost_prompt,omitempty"`
	CostOutput string `json:"cost_output,omitempty"`
}

EndpointInfo represents an endpoint that can serve a model

type Middleware

type Middleware interface {
	// Wrap wraps the given proxy with the middleware functionality
	Wrap(Proxy) Proxy
}

Middleware wraps a Proxy with additional functionality. Middlewares can be composed to create a chain of handlers.

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain combines multiple middlewares into a single middleware. The middlewares are applied in the order they are provided.

func LoggingMiddleware

func LoggingMiddleware() Middleware

LoggingMiddleware creates a middleware that logs requests and responses.

func NewCacheMiddleware

func NewCacheMiddleware(manager CacheManager, config *CacheConfig, catalog catalogGenerationSource) Middleware

NewCacheMiddleware creates a new cache middleware.

func TimingMiddleware

func TimingMiddleware() Middleware

TimingMiddleware creates a middleware that adds timing information to context.

type MiddlewareFunc

type MiddlewareFunc func(Proxy) Proxy

MiddlewareFunc is a function that implements the Middleware interface.

func (MiddlewareFunc) Wrap

func (f MiddlewareFunc) Wrap(p Proxy) Proxy

Wrap implements the Middleware interface.

type ModelArchitecture

type ModelArchitecture struct {
	InputModalities  []string `json:"input_modalities"`
	OutputModalities []string `json:"output_modalities"`
	Tokenizer        string   `json:"tokenizer"`
	InstructType     *string  `json:"instruct_type"`
}

ModelArchitecture describes protocol-facing model capabilities.

type ModelEndpointsResponse

type ModelEndpointsResponse struct {
	Model     string         `json:"model"`
	Endpoints []EndpointInfo `json:"endpoints"`
}

ModelEndpointsResponse represents available endpoints for a model

type ModelInfo

type ModelInfo struct {
	ID            string `json:"id"`
	CanonicalSlug string `json:"canonical_slug,omitempty"`
	Name          string `json:"name,omitempty"`
	Object        string `json:"object"`
	Created       int64  `json:"created"`
	OwnedBy       string `json:"owned_by"`

	// Extended metadata for OpenRouter compatibility
	Pricing             *ModelPricing      `json:"pricing,omitempty"`
	Context             *int               `json:"context_length,omitempty"`
	Type                string             `json:"type,omitempty"`
	Description         string             `json:"description,omitempty"`
	Architecture        *ModelArchitecture `json:"architecture,omitempty"`
	TopProvider         *TopProviderInfo   `json:"top_provider,omitempty"`
	SupportedParameters []string           `json:"supported_parameters,omitempty"`
}

ModelInfo represents model information

type ModelPricing

type ModelPricing struct {
	Prompt     string `json:"prompt"`
	Completion string `json:"completion"`
	Currency   string `json:"currency"`
}

ModelPricing represents model pricing information

type ModelsResponse

type ModelsResponse struct {
	Object string      `json:"object"`
	Data   []ModelInfo `json:"data"`

	// Internal fields (not serialized)
	CacheStatus string `json:"-"`
}

ModelsResponse represents a list of available models

type Option

type Option func(*Config)

Option configures the proxy service.

func WithCache

func WithCache(manager *cache.Manager, config *CacheConfig) Option

WithCache enables caching with the specified cache manager and configuration.

func WithCacheConfig

func WithCacheConfig(config *CacheConfig) Option

WithCacheConfig sets custom cache configuration. If a cache manager is not provided separately, a default one will be created.

func WithMiddleware

func WithMiddleware(m Middleware) Option

WithMiddleware adds a middleware to the proxy service. Middlewares are applied in the order they are added.

func WithOptions

func WithOptions(opts *Options) Option

WithOptions sets advanced proxy options.

func WithRequestTimeout

func WithRequestTimeout(timeout time.Duration) Option

WithRequestTimeout sets the timeout for individual requests.

func WithRouting

func WithRouting(config *RoutingConfig) Option

WithRouting configures routing behavior.

func WithSecurity

func WithSecurity(config *SecurityConfig) Option

WithSecurity configures security features.

func WithValidation

func WithValidation(config *ValidationConfig) Option

WithValidation configures request validation.

type Options

type Options struct {
	// RequestTimeout is the timeout for individual requests
	RequestTimeout time.Duration

	// EnableMetrics enables metrics collection
	EnableMetrics bool

	// EnableLogging enables request/response logging
	EnableLogging bool
}

Options contains advanced configuration options for the proxy.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns default proxy options.

type ProviderError

type ProviderError struct {
	Provider string
	Code     string
	Message  string
	Err      error
}

ProviderError represents an error from a provider

func (*ProviderError) Error

func (e *ProviderError) Error() string

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

type ProviderInfo

type ProviderInfo struct {
	ID              string   `json:"id"`
	Name            string   `json:"name"`
	Description     string   `json:"description,omitempty"`
	URL             string   `json:"url,omitempty"`
	Models          []string `json:"models"`
	Capabilities    []string `json:"capabilities,omitempty"`
	RequiresAuth    bool     `json:"requires_auth"`
	AuthDescription string   `json:"auth_description,omitempty"`
}

ProviderInfo represents provider metadata

type ProviderPreferences

type ProviderPreferences struct {
	Order         []string `json:"order,omitempty"`
	Ignore        []string `json:"ignore,omitempty"`
	Only          []string `json:"only,omitempty"`
	AllowFallback bool     `json:"allow_fallback,omitempty"`
}

ProviderPreferences represents provider routing preferences

type ProvidersResponse

type ProvidersResponse struct {
	Providers []ProviderInfo `json:"providers"`

	// Internal fields (not serialized)
	CacheStatus string `json:"-"`
}

ProvidersResponse represents provider information

type Proxy

type Proxy interface {
	// ProcessChatCompletion handles chat completion requests with routing and processing
	ProcessChatCompletion(ctx context.Context, req *ChatCompletionRequest) (*ChatCompletionResponse, error)

	// ProcessChatCompletionStream handles streaming chat completion requests
	ProcessChatCompletionStream(ctx context.Context, req *ChatCompletionRequest) (ChatCompletionStreamResponse, error)

	// ProcessEmbeddings handles embedding generation requests
	ProcessEmbeddings(ctx context.Context, req *EmbeddingsRequest) (*EmbeddingsResponse, error)

	// ListModels returns available models based on routing configuration
	ListModels(ctx context.Context) (*ModelsResponse, error)

	// ListProviders returns available provider information
	ListProviders(ctx context.Context) (*ProvidersResponse, error)

	// GetModelEndpoints returns provider endpoints for a specific model
	GetModelEndpoints(ctx context.Context, modelID string) (*ModelEndpointsResponse, error)
}

Proxy defines the core proxy interface for LLM request handling. This interface serves three primary purposes: 1. Testing - allows easy mocking in unit tests 2. Middleware composition - enables wrapping with caching, logging, metrics, etc. 3. Dependency injection - provides clean separation for HTTP handlers

The proxy handles routing requests to appropriate LLM providers, managing fallbacks, and transforming between different API formats.

func New

func New(registry *registry.Registry, router router.ModelRouter, opts ...Option) Proxy

New creates a new proxy service with the given registry and router. Additional functionality can be added using options.

Example:

// Basic proxy
proxy := proxy.New(registry, router)

// Proxy with caching
proxy := proxy.New(registry, router,
    proxy.WithCache(cacheManager, cacheConfig),
)

// Proxy with custom middleware
proxy := proxy.New(registry, router,
    proxy.WithMiddleware(loggingMiddleware),
    proxy.WithMiddleware(metricsMiddleware),
)

func NewFromConfig

func NewFromConfig(config *Config) Proxy

NewFromConfig creates a new proxy service from a configuration struct. This is useful when you have a pre-built configuration.

type RoutingConfig

type RoutingConfig struct {
	// EnableFailover enables automatic failover to other providers
	EnableFailover bool

	// PreferredProviders is an ordered list of preferred providers
	PreferredProviders []string

	// ExcludedProviders is a list of providers to exclude
	ExcludedProviders []string

	// EnableLoadBalancing enables load balancing across providers
	EnableLoadBalancing bool

	// EnableStickyRouting enables sticky routing for conversations
	EnableStickyRouting bool
}

RoutingConfig configures routing behavior.

func DefaultRoutingConfig

func DefaultRoutingConfig() *RoutingConfig

DefaultRoutingConfig returns default routing configuration.

type RoutingError

type RoutingError struct {
	Model  string
	Reason string
	Err    error
}

RoutingError represents an error during model routing

func (*RoutingError) Error

func (e *RoutingError) Error() string

func (*RoutingError) Unwrap

func (e *RoutingError) Unwrap() error

type SecurityConfig

type SecurityConfig struct {
	// EnableRateLimiting enables rate limiting
	EnableRateLimiting bool

	// RateLimitPerMinute is the number of requests allowed per minute
	RateLimitPerMinute int

	// EnableContentFiltering enables content filtering
	EnableContentFiltering bool

	// BlockedPatterns is a list of regex patterns to block
	BlockedPatterns []string

	// EnableAPIKeyValidation enables API key validation
	EnableAPIKeyValidation bool
}

SecurityConfig configures security features.

func DefaultSecurityConfig

func DefaultSecurityConfig() *SecurityConfig

DefaultSecurityConfig returns default security configuration.

type TopProviderInfo

type TopProviderInfo struct {
	ContextLength       int `json:"context_length"`
	MaxCompletionTokens int `json:"max_completion_tokens"`
}

TopProviderInfo describes the selected representative offering limits.

type ValidationConfig

type ValidationConfig struct {
	// StrictMode enables strict validation of requests
	StrictMode bool

	// MaxTokensLimit is the maximum allowed max_tokens value
	MaxTokensLimit int

	// MaxMessagesLimit is the maximum number of messages allowed
	MaxMessagesLimit int

	// MaxMessageLength is the maximum length of a single message
	MaxMessageLength int
}

ValidationConfig configures request validation behavior.

func DefaultValidationConfig

func DefaultValidationConfig() *ValidationConfig

DefaultValidationConfig returns default validation configuration.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a request validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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