Documentation
¶
Overview ¶
Package aigateway provides a simple interface to use the Midsommar AI Gateway as an importable library in standalone applications.
Index ¶
- type Config
- type ConfigProvider
- type Gateway
- type HTTPAnalyticsHandler
- func (h *HTTPAnalyticsHandler) RecordChatLogEntry(_ context.Context, log *models.LLMChatLogEntry)
- func (h *HTTPAnalyticsHandler) RecordChatRecord(_ context.Context, record *models.LLMChatRecord)
- func (h *HTTPAnalyticsHandler) RecordChatRecordsBatch(_ context.Context, records []*models.LLMChatRecord)
- func (h *HTTPAnalyticsHandler) RecordComplianceEvents(_ context.Context, events []*models.ComplianceEvent)
- func (h *HTTPAnalyticsHandler) RecordProxyLog(_ context.Context, log *models.ProxyLog)
- func (h *HTTPAnalyticsHandler) RecordProxyLogsBatch(_ context.Context, logs []*models.ProxyLog)
- func (h *HTTPAnalyticsHandler) RecordToolCall(_ context.Context, name string, timestamp time.Time, execTime int, toolID uint)
- func (h *HTTPAnalyticsHandler) SetAsGlobalHandler()
- type ServiceProvider
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Port int
// TLSEnabled must be set when the host serves this gateway over HTTPS on
// Port. The OpenAI-compatible endpoints (/ai/ and the unified router) call
// back into /llm/call/ over a loopback connection to Port, and that hop has
// to match the listener's scheme or the server rejects it as plain HTTP.
TLSEnabled bool
// LLMTimeout is the timeout for upstream LLM HTTP requests.
// Defaults to 5 minutes if zero, suitable for long-running agentic workloads.
LLMTimeout time.Duration
// UnifiedRouterBasePath moves the OpenRouter-style single-endpoint ingress
// ({base}/chat/completions, {base}/completions, {base}/models) off its default
// "/v1". Set it when embedding the gateway in a host that already owns "/v1",
// or that mounts this handler under a prefix of its own.
UnifiedRouterBasePath string
// DisableUnifiedRouter turns the unified ingress off entirely. The per-route
// endpoints (/ai/, /llm/, /anthropic/) are unaffected.
DisableUnifiedRouter bool
// ServerTiming adds Server-Timing headers/trailers splitting each LLM
// request into gateway and upstream time. Off by default.
ServerTiming bool
}
Config represents the configuration for the AI Gateway
type ConfigProvider ¶
type ConfigProvider interface {
// GetLLMs returns the list of active LLM configurations
GetLLMs(ctx context.Context) ([]models.LLM, error)
// GetDatasources returns the list of active datasource configurations
GetDatasources(ctx context.Context) ([]models.Datasource, error)
// GetFilters returns the list of filters to be applied
GetFilters(ctx context.Context) ([]models.Filter, error)
// Watch returns a channel that signals when configuration changes occur.
// This enables hot reloading of the gateway configuration.
Watch() <-chan struct{}
}
ConfigProvider is an interface that allows custom configuration sources for the AI Gateway. This enables users to provide LLM configurations, datasources, and filters from various sources (database, files, APIs, etc.)
type Gateway ¶
type Gateway interface {
// Start starts the gateway as an HTTP server on the configured port
Start() error
// Stop gracefully stops the gateway server
Stop(ctx context.Context) error
// Handler returns an http.Handler that can be integrated into existing HTTP servers
Handler() http.Handler
// UnifiedRouterBasePath reports the path prefix the OpenRouter-style unified
// ingress is served under ("/v1" by default), or "" when it is disabled.
// Hosts mounting Handler() behind their own router forward this prefix.
UnifiedRouterBasePath() string
// Reload reloads the gateway configuration (LLMs, datasources, filters)
Reload() error
// AddResponseHook adds a response hook for REST request processing (REST-only, not streaming)
AddResponseHook(hook proxy.ResponseHook)
// SetAuthHooks sets authentication lifecycle hooks (replaces SetPostAuthCallback)
SetAuthHooks(hooks *proxy.AuthHooks)
// SetPostAuthCallback is deprecated, use SetAuthHooks instead
SetPostAuthCallback(callback proxy.PostAuthCallback)
// SetRouteResolver installs the router implementation for the /ai/ chain
// and the unified ingress (Model Routers). Nil disables routers.
SetRouteResolver(resolver proxy.RouteResolver)
}
Gateway represents an AI Gateway instance that can proxy requests to LLM providers, enforce authentication, budgets, and policies, and provide analytics.
func New ¶
func New( gatewayService services.ServiceInterface, budgetService services.BudgetServiceInterface, config *Config, ) Gateway
New creates a new Gateway instance using the unified services interface with default database analytics. This approach allows for flexible backend implementations (database, file, API, etc.).
Parameters:
- gatewayService: Service interface for configuration, authentication, and pricing
- budgetService: Budget interface for spending validation and tracking
- config: Gateway configuration including port settings
Example with database backend:
db := setupDatabase()
service := services.NewService(db)
budgetService := services.NewBudgetService(db, service)
gateway := aigateway.New(
service, // directly use services.Service
budgetService, // directly use services.BudgetService
&aigateway.Config{Port: 9090},
)
gateway.Start()
Example with file-based backend:
gateway := aigateway.New(
fileGatewayService, // implements services.ServiceInterface
fileBudgetService, // implements services.BudgetServiceInterface
&aigateway.Config{Port: 9090},
)
func NewWithAnalytics ¶
func NewWithAnalytics( gatewayService services.ServiceInterface, budgetService services.BudgetServiceInterface, analyticsHandler analytics.AnalyticsHandler, config *Config, ) Gateway
NewWithAnalytics creates a new Gateway instance with a custom analytics handler. This allows full control over where analytics data is sent (HTTP API, message queue, etc.).
Parameters:
- gatewayService: Service interface for configuration, authentication, and pricing
- budgetService: Budget service interface for spending validation and tracking
- analyticsHandler: Analytics handler for recording usage data (nil uses existing global handler)
- config: Gateway configuration including port settings
Example with HTTP analytics:
gateway := aigateway.NewWithAnalytics(
service, // implements services.ServiceInterface
budgetService, // implements services.BudgetServiceInterface
aigateway.NewHTTPAnalyticsHandler("https://my-control-plane/api"),
&aigateway.Config{Port: 9090},
)
type HTTPAnalyticsHandler ¶
type HTTPAnalyticsHandler struct {
// contains filtered or unexported fields
}
HTTPAnalyticsHandler sends analytics to an HTTP endpoint
func NewHTTPAnalyticsHandler ¶
func NewHTTPAnalyticsHandler(endpoint string) *HTTPAnalyticsHandler
NewHTTPAnalyticsHandler creates a new HTTP analytics handler
func (*HTTPAnalyticsHandler) RecordChatLogEntry ¶
func (h *HTTPAnalyticsHandler) RecordChatLogEntry(_ context.Context, log *models.LLMChatLogEntry)
RecordChatLogEntry implements analytics.AnalyticsHandler
func (*HTTPAnalyticsHandler) RecordChatRecord ¶
func (h *HTTPAnalyticsHandler) RecordChatRecord(_ context.Context, record *models.LLMChatRecord)
RecordChatRecord implements analytics.AnalyticsHandler
func (*HTTPAnalyticsHandler) RecordChatRecordsBatch ¶
func (h *HTTPAnalyticsHandler) RecordChatRecordsBatch(_ context.Context, records []*models.LLMChatRecord)
RecordChatRecordsBatch implements batch recording for HTTP analytics
func (*HTTPAnalyticsHandler) RecordComplianceEvents ¶
func (h *HTTPAnalyticsHandler) RecordComplianceEvents(_ context.Context, events []*models.ComplianceEvent)
RecordComplianceEvents implements analytics.AnalyticsHandler (no-op for HTTP handler)
func (*HTTPAnalyticsHandler) RecordProxyLog ¶
func (h *HTTPAnalyticsHandler) RecordProxyLog(_ context.Context, log *models.ProxyLog)
RecordProxyLog implements analytics.AnalyticsHandler
func (*HTTPAnalyticsHandler) RecordProxyLogsBatch ¶
func (h *HTTPAnalyticsHandler) RecordProxyLogsBatch(_ context.Context, logs []*models.ProxyLog)
RecordProxyLogsBatch implements batch recording for HTTP analytics
func (*HTTPAnalyticsHandler) RecordToolCall ¶
func (h *HTTPAnalyticsHandler) RecordToolCall(_ context.Context, name string, timestamp time.Time, execTime int, toolID uint)
RecordToolCall implements analytics.AnalyticsHandler
func (*HTTPAnalyticsHandler) SetAsGlobalHandler ¶
func (h *HTTPAnalyticsHandler) SetAsGlobalHandler()
SetAsGlobalHandler sets this handler as the global analytics handler
type ServiceProvider ¶
type ServiceProvider interface {
// GetActiveLLMs returns the list of active LLM configurations
GetActiveLLMs() ([]models.LLM, error)
// GetActiveDatasources returns the list of active datasource configurations
GetActiveDatasources() ([]models.Datasource, error)
// CallToolOperation executes a tool operation
CallToolOperation(toolID uint, operationID string, params map[string][]string, payload map[string]interface{}, headers map[string][]string) (interface{}, error)
// GetToolBySlug retrieves a tool by its slug identifier
GetToolBySlug(slug string) (*models.Tool, error)
}
ServiceProvider is an interface that provides the core service operations needed by the gateway. This allows users to provide custom implementations or wrap existing services.