Documentation
¶
Overview ¶
Package server since we do refactoring and migrating step by step, some api names are not unified, this will be updated in future
Index ¶
- Constants
- func AttachRecorderHooks(hc *protocol.HandleContext, recorder *ProtocolRecorder, model string, ...)
- func CalculateTPS(c *gin.Context, outputTokens int, streamed bool) float64
- func CalculateTTFT(c *gin.Context) int64
- func ConvertAnthropicToOpenAIResponseWithProvider(anthropicResp *anthropic.BetaMessage, responseModel string, ...) map[string]interface{}
- func FindGuardrailsConfig(configDir string) (string, error)
- func GenerateCurlCommand(apiBase, apiStyle, token, model string) string
- func GenerateOpenAPI(cfg *config.Config) (string, error)
- func GetCacheHit(c *gin.Context) (bool, bool)
- func GetFirstTokenTime(c *gin.Context) (time.Time, bool)
- func GetGuardrailsBuiltinDir(configDir string) string
- func GetGuardrailsCacheDir(configDir string) string
- func GetGuardrailsConfigPath(configDir string) string
- func GetGuardrailsCustomDir(configDir string) string
- func GetGuardrailsDBDir(configDir string) string
- func GetGuardrailsDBPath(configDir string) string
- func GetGuardrailsDir(configDir string) string
- func GetGuardrailsHistoryPath(configDir string) string
- func GetGuardrailsRegistryCachePath(configDir string) string
- func GetGuardrailsRemoteDir(configDir string) string
- func GetShutdownChannel() <-chan struct{}
- func GetTrackingContext(c *gin.Context) (rule *typ.Rule, provider *typ.Provider, ...)
- func GetTrackingContextScenario(c *gin.Context) (scenario string)
- func GetUserIDFromContext(c *gin.Context) string
- func NewGinHandlerWrapper(h gin.HandlerFunc) swagger.Handler
- func ResolveOpenAIEndpoint(provider *typ.Provider, flags typ.RuleFlags, incoming IncomingAPIType) (protocol.APIType, error)
- func RoundtripAnthropicBetaResponseViaOpenAI(anthropicResp *anthropic.BetaMessage, responseModel string, ...) (*anthropic.BetaMessage, error)
- func RoundtripOpenAIMapViaAnthropic(openaiResp map[string]interface{}, responseModel string, ...) (map[string]interface{}, error)
- func RoundtripOpenAIResponseViaAnthropic(openaiResp *openai.ChatCompletion, responseModel string, ...) (map[string]interface{}, error)
- func SendErrorResponse(c *gin.Context, err error, desc string)
- func SetCacheHit(c *gin.Context, isHit bool)
- func SetEnterpriseRateLimitReporter(reporter func(context.Context, string, string, string, string) error)
- func SetGlobalServer(server *Server)
- func SetTrackingContext(c *gin.Context, rule *typ.Rule, provider *typ.Provider, ...)
- func ShouldRoundtripResponse(c *gin.Context, target string) bool
- func UpdateTrackingForFailover(c *gin.Context, provider *typ.Provider, model string)
- type ActionHistoryEntry
- type ActionHistoryResponse
- type AffinityStore
- func (s *AffinityStore) CountByService(serviceID string) int
- func (s *AffinityStore) Delete(ruleUUID, sessionID string)
- func (s *AffinityStore) DeleteByRule(ruleUUID string)
- func (s *AffinityStore) GC()
- func (s *AffinityStore) Get(ruleUUID, sessionID string) (*routing.AffinityEntry, bool)
- func (s *AffinityStore) Set(ruleUUID, sessionID string, entry *routing.AffinityEntry)
- func (s *AffinityStore) StartGC()
- func (s *AffinityStore) UpdateMessageID(ruleUUID, sessionID, messageID string)
- type AllStatsResponse
- type AnthropicModel
- type AnthropicModelsResponse
- type CapabilitySupport
- type ClearStatsResponse
- type ContextManagementCapability
- type CurrentServiceResponse
- type EffortCapability
- type EndpointOverride
- type ErrorDetail
- type ErrorResponse
- type GenerateTokenRequest
- type HistoryResponse
- type IncomingAPIType
- type LBSimulator
- func (s *LBSimulator) Advance(d time.Duration)
- func (s *LBSimulator) BreakerStates() map[string]string
- func (s *LBSimulator) HealthStates() map[string]string
- func (s *LBSimulator) Pin(session string) string
- func (s *LBSimulator) PinDetail(session string) (serviceID string, lockedAt, expiresAt time.Time, ok bool)
- func (s *LBSimulator) Request(session string) (LBTrace, error)
- func (s *LBSimulator) SeedPin(session, provider, model string)
- type LBTrace
- type LoadBalancer
- func (lb *LoadBalancer) ClearAllStats()
- func (lb *LoadBalancer) ClearServiceStats(provider, model string)
- func (lb *LoadBalancer) GetAllServiceStats() map[string]*loadbalance.ServiceStats
- func (lb *LoadBalancer) GetRuleSummary(rule *typ.Rule) map[string]interface{}
- func (lb *LoadBalancer) GetServiceStats(provider, model string) *loadbalance.ServiceStats
- func (lb *LoadBalancer) HealthFilter() *typ.HealthFilter
- func (lb *LoadBalancer) RecordUsage(provider, model string, inputTokens, outputTokens int)
- func (lb *LoadBalancer) RegisterTactic(tacticType loadbalance.TacticType, tactic typ.LoadBalancingTactic)
- func (lb *LoadBalancer) SelectService(rule *typ.Rule) (*loadbalance.Service, error)
- func (lb *LoadBalancer) Stop()
- func (lb *LoadBalancer) UpdateServiceIndex(rule *typ.Rule, selectedService *loadbalance.Service)
- func (lb *LoadBalancer) ValidateRule(rule *typ.Rule) error
- type LoadBalancerAPI
- func (api *LoadBalancerAPI) ClearAllStats(c *gin.Context)
- func (api *LoadBalancerAPI) ClearRuleStats(c *gin.Context)
- func (api *LoadBalancerAPI) ClearServiceStats(c *gin.Context)
- func (api *LoadBalancerAPI) GetAllStats(c *gin.Context)
- func (api *LoadBalancerAPI) GetCurrentService(c *gin.Context)
- func (api *LoadBalancerAPI) GetMetrics(c *gin.Context)
- func (api *LoadBalancerAPI) GetRule(c *gin.Context)
- func (api *LoadBalancerAPI) GetRuleStats(c *gin.Context)
- func (api *LoadBalancerAPI) GetRuleSummary(c *gin.Context)
- func (api *LoadBalancerAPI) GetServiceHealth(c *gin.Context)
- func (api *LoadBalancerAPI) GetServiceStats(c *gin.Context)
- func (api *LoadBalancerAPI) GetServicesHealth(c *gin.Context)
- func (api *LoadBalancerAPI) RegisterRoutes(loadBalancer *gin.RouterGroup)
- func (api *LoadBalancerAPI) ResetServiceHealth(c *gin.Context)
- func (api *LoadBalancerAPI) UpdateRuleTactic(c *gin.Context)
- type LogEntry
- type LogsResponse
- type MetricsData
- type MetricsResponse
- type ModelCapabilities
- type ModelRequestDetail
- type ModelRequestEvent
- type ModelRequestSummary
- type ModelRequestsResponse
- type OpenAIChatCompletionResponse
- type OpenAIModel
- type OpenAIModelsResponse
- type ProbeProviderResponse
- type ProbeRequestDetail
- type ProbeResponse
- type ProbeResponseData
- type ProbeResponseDetail
- type ProbeUsage
- type ProtocolRecorder
- func (sr *ProtocolRecorder) EnableStreaming()
- func (sr *ProtocolRecorder) RecordError(err error)
- func (sr *ProtocolRecorder) RecordResponse(provider *typ.Provider, model string)
- func (sr *ProtocolRecorder) RecordStreamChunk(eventType string, chunk interface{})
- func (sr *ProtocolRecorder) SetActiveService(provider *typ.Provider, model string)
- func (sr *ProtocolRecorder) SetAssembledResponse(response any)
- func (sr *ProtocolRecorder) SetOriginalRequest(req *obs.RecordRequest)
- func (sr *ProtocolRecorder) SetTransformSteps(steps []string)
- func (sr *ProtocolRecorder) SetTransformedRequest(req *obs.RecordRequest)
- type RequestConfig
- type RuleStatsResponse
- type RuleSummaryResponse
- type Server
- func (s *Server) AnthropicCountTokens(c *gin.Context)
- func (s *Server) AnthropicListModelsForScenario(c *gin.Context, scenario typ.RuleScenario)
- func (s *Server) AnthropicMessagesV1(c *gin.Context, req *protocol.AnthropicMessagesRequest, requestModel string, ...)
- func (s *Server) AnthropicMessagesV1Beta(c *gin.Context, req *protocol.AnthropicBetaMessagesRequest, ...)
- func (s *Server) CallMCPToolWithHooks(ctx context.Context, toolName, arguments string, messages []map[string]any) (context.Context, coretool.ToolResult, error)
- func (s *Server) Cancel() context.CancelFunc
- func (s *Server) ClearGuardrailsHistory(c *gin.Context)
- func (s *Server) ClearLogs(c *gin.Context)
- func (s *Server) Context() context.Context
- func (s *Server) CreateGuardrailsCredential(c *gin.Context)
- func (s *Server) CreateGuardrailsGroup(c *gin.Context)
- func (s *Server) CreateGuardrailsPolicy(c *gin.Context)
- func (s *Server) DeleteGuardrailsCredential(c *gin.Context)
- func (s *Server) DeleteGuardrailsGroup(c *gin.Context)
- func (s *Server) DeleteGuardrailsPolicy(c *gin.Context)
- func (s *Server) EnsureProtocolRecorder(c *gin.Context, scenario string, provider *typ.Provider, model string, ...) *ProtocolRecorder
- func (s *Server) ExportGuardrailsFragments(c *gin.Context)
- func (s *Server) ExtractRequestContext(req interface{}) (*smartrouting.RequestContext, error)deprecated
- func (s *Server) GenerateToken(c *gin.Context)
- func (s *Server) GetActionHistory(c *gin.Context)
- func (s *Server) GetActionStats(c *gin.Context)
- func (s *Server) GetGuardrailsBuiltins(c *gin.Context)
- func (s *Server) GetGuardrailsConfig(c *gin.Context)
- func (s *Server) GetGuardrailsCredential(c *gin.Context)
- func (s *Server) GetGuardrailsCredentials(c *gin.Context)
- func (s *Server) GetGuardrailsHistory(c *gin.Context)
- func (s *Server) GetGuardrailsRegistry(c *gin.Context)
- func (s *Server) GetHistory(c *gin.Context)
- func (s *Server) GetLoadBalancer() *LoadBalancer
- func (s *Server) GetLogStats(c *gin.Context)
- func (s *Server) GetLogs(c *gin.Context)
- func (s *Server) GetModelRequestDetail(c *gin.Context)
- func (s *Server) GetModelRequests(c *gin.Context)
- func (s *Server) GetOrCreateScenarioSink(scenario typ.RuleScenario) *obs.Sink
- func (s *Server) GetRouter() *gin.Engine
- func (s *Server) GetRoutingSelector() *routing.SimpleSelector
- func (s *Server) GetScenarioRecordMode(scenario typ.RuleScenario) obs.RecordMode
- func (s *Server) GetStatus(c *gin.Context)
- func (s *Server) GetSystemLogLevel(c *gin.Context)
- func (s *Server) GetSystemLogStats(c *gin.Context)
- func (s *Server) GetSystemLogs(c *gin.Context)
- func (s *Server) GetToken(c *gin.Context)
- func (s *Server) GetUserToken(c *gin.Context)
- func (s *Server) HandleAnthropicListModels(c *gin.Context)
- func (s *Server) HandleAnthropicMessages(c *gin.Context)
- func (s *Server) HandleOpenAIChatCompletions(c *gin.Context)
- func (s *Server) HandleOpenAIEmbeddings(c *gin.Context)
- func (s *Server) HandleOpenAIImageGeneration(c *gin.Context)
- func (s *Server) HandleOpenAIListModels(c *gin.Context)
- func (s *Server) HandleResponsesCreate(c *gin.Context)
- func (s *Server) HandleResponsesGet(c *gin.Context)
- func (s *Server) HealthMonitor() *loadbalance.HealthMonitor
- func (s *Server) ImportGuardrailsFragment(c *gin.Context)
- func (s *Server) InstallGuardrailsRegistryPolicy(c *gin.Context)
- func (s *Server) IsRemoteCoderRunning() bool
- func (s *Server) ListModelsByScenario(c *gin.Context)
- func (s *Server) NewUsageTracker() *UsageTracker
- func (s *Server) OpenAIChatCompletion(c *gin.Context, req *protocol.OpenAIChatCompletionRequest, ...)
- func (s *Server) OpenAIListModelsForScenario(c *gin.Context, scenario typ.RuleScenario)
- func (s *Server) ReloadGuardrailsConfig(c *gin.Context)
- func (s *Server) ResetModelToken(c *gin.Context)
- func (s *Server) ResetUserToken(c *gin.Context)
- func (s *Server) ResponsesCreate(c *gin.Context, scenarioType typ.RuleScenario, provider *typ.Provider, ...)
- func (s *Server) RestartServer(c *gin.Context)
- func (s *Server) SelectServiceFromSmartRouting(matchedServices []*loadbalance.Service, rule *typ.Rule) (*loadbalance.Service, error)deprecated
- func (s *Server) SetSystemLogLevel(c *gin.Context)
- func (s *Server) SetupAnthropicEndpoints(group *gin.RouterGroup)
- func (s *Server) SetupMixinEndpoints(group *gin.RouterGroup)
- func (s *Server) SetupOpenAIEndpoints(group *gin.RouterGroup)
- func (s *Server) Start(port int) error
- func (s *Server) StartDynamicCallbackServer(sessionID string, port int) error
- func (s *Server) StartRemoteCoder() error
- func (s *Server) StartServer(c *gin.Context)
- func (s *Server) Stop(ctx context.Context) error
- func (s *Server) StopDynamicCallbackServer(sessionID string)
- func (s *Server) StopRemoteCoder()
- func (s *Server) StopServer(c *gin.Context)
- func (s *Server) SyncRemoteCoderBots(ctx context.Context) error
- func (s *Server) TrackUsage(ctx context.Context, inputTokens, outputTokens int, err error)
- func (s *Server) UpdateGuardrailsConfig(c *gin.Context)
- func (s *Server) UpdateGuardrailsCredential(c *gin.Context)
- func (s *Server) UpdateGuardrailsGroup(c *gin.Context)
- func (s *Server) UpdateGuardrailsPolicy(c *gin.Context)
- func (s *Server) UsageStore() *db.UsageStore
- func (s *Server) UseAIEndpoints()
- func (s *Server) UseIndexHTML(c *gin.Context)
- func (s *Server) UseLoadBalanceEndpoints()
- func (s *Server) UseTokenManagementEndpoints()
- func (s *Server) UseUIEndpoints(ctx context.Context)
- func (s *Server) UseVirtualModelEndpoints()
- func (s *Server) ValidateAuthToken(c *gin.Context)
- type ServerActionResponse
- type ServerOption
- func WithAdaptor(enabled bool) ServerOption
- func WithAuthMiddleware(userAuth, modelAuth gin.HandlerFunc) ServerOption
- func WithDebug(enabled bool) ServerOption
- func WithDefault() ServerOption
- func WithGuardrails(runtime *guardrails.Guardrails) ServerOption
- func WithHost(host string) ServerOption
- func WithModelAuthMiddleware(modelAuth gin.HandlerFunc) ServerOption
- func WithMultiLogger(logger *pkgobs.MultiLogger) ServerOption
- func WithOpenBrowser(enabled bool) ServerOption
- func WithRecordDir(dir string) ServerOption
- func WithRecordMode(mode obs.RecordMode) ServerOption
- func WithRecording(enabled bool) ServerOption
- func WithRecordingCAS(enabled bool) ServerOption
- func WithTemplateManager(tm *data.TemplateManager) ServerOption
- func WithUI(enabled bool) ServerOption
- func WithUserAuthMiddleware(userAuth gin.HandlerFunc) ServerOption
- func WithVersion(version string) ServerOption
- type ServiceHealthResponse
- type ServiceMetric
- type ServiceStatsResponse
- type StatusResponse
- type SystemLogEntry
- type SystemLogLevelRequest
- type SystemLogsResponse
- type ThinkingCapability
- type ThinkingTypes
- type TokenResponse
- type TransformRecorder
- type TransformStage
- type UpdateRuleTacticRequest
- type UpdateRuleTacticResponse
- type UsageTracker
Constants ¶
const ( ContextKeyRule = constant.CtxKeyRule ContextKeyProvider = constant.CtxKeyProvider ContextKeyModel = constant.CtxKeyModel ContextKeyRequestModel = constant.CtxKeyRequestModel ContextKeyScenario = constant.CtxKeyScenario ContextKeyStreamed = constant.CtxKeyStreamed ContextKeyStartTime = constant.CtxKeyStartTime ContextKeyFirstTokenTime = constant.CtxKeyFirstTokenTime ContextKeyCacheHit = constant.CtxKeyCacheHit ContextKeySessionID = constant.CtxKeySessionID ContextKeyLBServiceID = constant.CtxKeyLBServiceID ContextKeyLBTactic = constant.CtxKeyLBTactic )
Gin context key aliases — canonical values live in constant so that routing/ and middleware/ sub-packages can reference them without an import cycle.
const GuardrailsRegistryGitHubURL = "https://raw.githubusercontent.com/tingly-dev/tingly-guardrails-registry/main/index.yaml"
Leave the remote registry unset until the dedicated policy repository is ready. The API will surface this as an unavailable registry instead of coupling guardrails downloads to the main code repository.
Variables ¶
This section is empty.
Functions ¶
func AttachRecorderHooks ¶ added in v0.260531.1
func AttachRecorderHooks(hc *protocol.HandleContext, recorder *ProtocolRecorder, model string, provider *typ.Provider)
AttachRecorderHooks wires a ProtocolRecorder into a native Anthropic stream HandleContext. Raw SSE chunks are mirrored into the recorder's chunk log; an internal assembler synthesises the final *anthropic.Message once the stream completes; completion and error finalise the record.
func CalculateTPS ¶
CalculateTPS calculates Tokens Per Second (generation speed) for streaming requests. For non-streaming requests or when TTFT is not available, returns 0.
TPS is calculated as: outputTokens / (currentTime - firstTokenTime) This measures the actual token generation speed after the first token was received.
Parameters:
- c: Gin context containing timing information
- outputTokens: Number of output tokens generated
- streamed: Whether this was a streaming request
Returns:
- TPS value (tokens per second), or 0 if not applicable
func CalculateTTFT ¶
CalculateTTFT returns Time To First Token in milliseconds, or 0 when no first-token time was recorded (e.g. non-streaming requests). It must not fall back to total latency, which would make TTFT indistinguishable from it.
func ConvertAnthropicToOpenAIResponseWithProvider ¶
func ConvertAnthropicToOpenAIResponseWithProvider(anthropicResp *anthropic.BetaMessage, responseModel string, provider *typ.Provider, model string) map[string]interface{}
ConvertAnthropicToOpenAIResponseWithProvider converts an Anthropic response to OpenAI format and applies provider-specific transformations to the response
func FindGuardrailsConfig ¶ added in v0.260418.2200
func GenerateCurlCommand ¶
GenerateCurlCommand generates a curl command for testing the provider
func GenerateOpenAPI ¶ added in v0.260418.2200
GenerateOpenAPI creates an OpenAPI v3 schema without starting the server
func GetCacheHit ¶
GetCacheHit retrieves the cache hit status from the context. Returns the cache hit status and true if it exists, false and false otherwise.
func GetFirstTokenTime ¶
GetFirstTokenTime retrieves the first token time from the context. Returns the timestamp and true if it exists, zero time and false otherwise.
func GetGuardrailsBuiltinDir ¶ added in v0.260418.2200
func GetGuardrailsCacheDir ¶ added in v0.260418.2200
func GetGuardrailsConfigPath ¶ added in v0.260418.2200
func GetGuardrailsCustomDir ¶ added in v0.260418.2200
func GetGuardrailsDBDir ¶ added in v0.260418.2200
func GetGuardrailsDBPath ¶ added in v0.260418.2200
func GetGuardrailsDir ¶ added in v0.260418.2200
Guardrails config and storage live under one dedicated subdirectory. Keeping these path helpers next to the handlers makes the admin surface self-contained.
func GetGuardrailsHistoryPath ¶ added in v0.260418.2200
func GetGuardrailsRegistryCachePath ¶ added in v0.260418.2200
func GetGuardrailsRemoteDir ¶ added in v0.260418.2200
func GetShutdownChannel ¶
func GetShutdownChannel() <-chan struct{}
GetShutdownChannel returns the shutdown channel for the main process to listen on
func GetTrackingContext ¶
func GetTrackingContext(c *gin.Context) (rule *typ.Rule, provider *typ.Provider, actualModel, requestModel, scenario string, streamed bool, startTime time.Time)
GetTrackingContext retrieves tracking metadata from the gin context. Returns zero values if the context keys are not set.
func GetTrackingContextScenario ¶ added in v0.260625.1
func GetUserIDFromContext ¶ added in v0.260418.2200
GetUserIDFromContext extracts the user ID from gin context. Priority: user_id (from JWT API token or global auth) > enterprise_user_id (from enterprise JWT) > "" This ensures that JWT API token authentication takes precedence for user tracking.
func NewGinHandlerWrapper ¶
func NewGinHandlerWrapper(h gin.HandlerFunc) swagger.Handler
NewGinHandlerWrapper converts gin.HandlerFunc to swagger.Handler
func ResolveOpenAIEndpoint ¶ added in v0.260531.1
func ResolveOpenAIEndpoint(provider *typ.Provider, flags typ.RuleFlags, incoming IncomingAPIType) (protocol.APIType, error)
ResolveOpenAIEndpoint picks an OpenAI endpoint using the optional per-rule override first, then the provider's declared OpenAIEndpointMode.
Precedence:
- Rule flag (flags.OpenAIEndpointOverride). Overrides provider settings.
- provider.OpenAIEndpointMode: EndpointModeUnknown / zero value → Chat EndpointModeChat → Chat EndpointModeResponses → Responses EndpointModeBoth → mirror incoming
Rule override is honored unconditionally (per design intent). When an override conflicts with the provider's declared mode, a warning is logged but the override takes effect. This allows explicit routing control for debugging and special cases.
Defaulting unknown providers to Chat (not "mirror incoming") is intentional: most OpenAI-compatible vendors implement only /chat/completions. Providers that genuinely support Responses must declare it via template or OAuth.
When an incoming Responses request routes to Chat, Responses-only fields (previous_response_id, include, background, truncation, reasoning) are silently dropped by ConvertOpenAIResponsesToChat — the same posture as Anthropic→Chat downgrades. The user accepts this by declaring the mode.
Pure function: no Server state, no probe lookups, no I/O.
func RoundtripAnthropicBetaResponseViaOpenAI ¶
func RoundtripAnthropicBetaResponseViaOpenAI(anthropicResp *anthropic.BetaMessage, responseModel string, provider *typ.Provider, actualModel string) (*anthropic.BetaMessage, error)
func SendErrorResponse ¶ added in v0.260418.2200
SendErrorResponse registers the error into gin context for logging middleware and sends JSON response.
func SetCacheHit ¶
SetCacheHit records whether this request was a cache hit.
func SetEnterpriseRateLimitReporter ¶
func SetEnterpriseRateLimitReporter(reporter func(context.Context, string, string, string, string) error)
SetEnterpriseRateLimitReporter sets callback for enterprise 429 events.
func SetGlobalServer ¶
func SetGlobalServer(server *Server)
SetGlobalServer sets the global server instance for web UI control
func SetTrackingContext ¶
func SetTrackingContext(c *gin.Context, rule *typ.Rule, provider *typ.Provider, actualModel, requestModel string, streamed bool)
SetTrackingContext sets all tracking metadata in the gin context. This should be called once at the beginning of request processing to avoid explicit parameter passing throughout the handler chain.
Parameters:
- c: Gin context
- rule: The load balancer rule that was selected
- provider: The provider that was selected
- actualModel: The actual model name used (may differ from requested)
- requestModel: The original model name requested by the user
- streamed: Whether this is a streaming request
func UpdateTrackingForFailover ¶ added in v0.260625.1
UpdateTrackingForFailover updates provider and model tracking during failover retry. This ensures that logging/middleware shows the final successful service after failover, not the initially-selected failed service.
Parameters:
- c: Gin context
- provider: The new provider being tried in this failover attempt
- model: The new model being tried in this failover attempt
Types ¶
type ActionHistoryEntry ¶
type ActionHistoryEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Action string `json:"action,omitempty"`
Success bool `json:"success,omitempty"`
Details interface{} `json:"details,omitempty"`
Fields map[string]interface{} `json:"fields,omitempty"`
}
ActionHistoryEntry represents an action history entry for API response
type ActionHistoryResponse ¶
type ActionHistoryResponse struct {
Total int `json:"total"`
Actions []ActionHistoryEntry `json:"actions"`
}
ActionHistoryResponse represents the API response for action history
type AffinityStore ¶
type AffinityStore struct {
// contains filtered or unexported fields
}
AffinityStore maps (ruleUUID, sessionID) -> locked Service. It directly implements routing.AffinityStore interface.
func NewAffinityStore ¶
func NewAffinityStore(ttl time.Duration) *AffinityStore
NewAffinityStore creates a new affinity store with the given TTL
func (*AffinityStore) CountByService ¶ added in v0.260409.1540
func (s *AffinityStore) CountByService(serviceID string) int
CountByService returns the number of sessions locked to the given serviceID that were created within the capacity active window (last 30 minutes). This provides a "recently active users" count for seat utilization calculation.
func (*AffinityStore) Delete ¶
func (s *AffinityStore) Delete(ruleUUID, sessionID string)
Delete removes an affinity entry for the given rule and session
func (*AffinityStore) DeleteByRule ¶
func (s *AffinityStore) DeleteByRule(ruleUUID string)
DeleteByRule removes all affinity entries for a given rule UUID
func (*AffinityStore) Get ¶
func (s *AffinityStore) Get(ruleUUID, sessionID string) (*routing.AffinityEntry, bool)
Get retrieves an affinity entry for the given rule and session
func (*AffinityStore) Set ¶
func (s *AffinityStore) Set(ruleUUID, sessionID string, entry *routing.AffinityEntry)
Set stores an affinity entry for the given rule and session
func (*AffinityStore) StartGC ¶
func (s *AffinityStore) StartGC()
StartGC starts a background goroutine that periodically cleans up expired entries
func (*AffinityStore) UpdateMessageID ¶
func (s *AffinityStore) UpdateMessageID(ruleUUID, sessionID, messageID string)
UpdateMessageID updates the message ID for an existing affinity entry
type AllStatsResponse ¶
type AllStatsResponse struct {
Stats map[string]interface{} `json:"stats"`
}
AllStatsResponse represents the response for all statistics
type AnthropicModel ¶
type AnthropicModel struct {
ID string `json:"id"`
CreatedAt string `json:"created_at"`
DisplayName string `json:"display_name"`
Type string `json:"type"`
Capabilities *ModelCapabilities `json:"capabilities,omitempty"`
MaxInputTokens int `json:"max_input_tokens,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
// Description is a tingly-box extension (not in Anthropic's wire format)
// consumed by the frontend to show model description in the model picker.
Description string `json:"description,omitempty"`
// AuthType is a tingly-box extension (not in Anthropic's wire format)
// consumed by the frontend to order model picker entries:
// oauth -> api_key -> vmodel.
AuthType string `json:"auth_type,omitempty"`
}
AnthropicModel maps to Anthropic's native /v1/models response format.
type AnthropicModelsResponse ¶
type AnthropicModelsResponse struct {
Data []AnthropicModel `json:"data"`
FirstID string `json:"first_id"`
HasMore bool `json:"has_more"`
LastID string `json:"last_id"`
}
type CapabilitySupport ¶ added in v0.260611.1
type CapabilitySupport struct {
Supported bool `json:"supported"`
}
CapabilitySupport indicates whether a capability is supported.
type ClearStatsResponse ¶
type ClearStatsResponse struct {
Message string `json:"message" example:"Statistics cleared for rule: gpt-4"`
}
ClearStatsResponse represents the response for clearing statistics
type ContextManagementCapability ¶ added in v0.260611.1
type ContextManagementCapability struct {
Supported bool `json:"supported"`
ClearThinking20251015 CapabilitySupport `json:"clear_thinking_20251015,omitempty"`
ClearToolUses20250919 CapabilitySupport `json:"clear_tool_uses_20250919,omitempty"`
Compact20260112 CapabilitySupport `json:"compact_20260112,omitempty"`
}
ContextManagementCapability describes context management support.
type CurrentServiceResponse ¶
type CurrentServiceResponse struct {
Rule string `json:"rule" example:"gpt-4"`
Service interface{} `json:"service"`
ServiceID string `json:"service_id" example:"openai:gpt-4"`
Tactic string `json:"tactic" example:"adaptive"`
Stats map[string]interface{} `json:"stats,omitempty"`
}
CurrentServiceResponse represents the current service response
type EffortCapability ¶ added in v0.260611.1
type EffortCapability struct {
Supported bool `json:"supported"`
Low CapabilitySupport `json:"low,omitempty"`
Medium CapabilitySupport `json:"medium,omitempty"`
High CapabilitySupport `json:"high,omitempty"`
XHigh CapabilitySupport `json:"xhigh,omitempty"`
Max CapabilitySupport `json:"max,omitempty"`
}
EffortCapability describes reasoning_effort support and levels.
type EndpointOverride ¶ added in v0.260531.1
type EndpointOverride string
EndpointOverride is the typed value of the openai_endpoint_override rule flag. It forces an OpenAI request onto a specific endpoint, overriding the provider's declared OpenAIEndpointMode default (provider declarations trump conflicting overrides — see ResolveOpenAIEndpoint).
const ( OverrideAuto EndpointOverride = "auto" OverrideChat EndpointOverride = "chat" OverrideResponses EndpointOverride = "responses" )
func ParseEndpointOverride ¶ added in v0.260531.1
func ParseEndpointOverride(s string) EndpointOverride
ParseEndpointOverride coerces a raw rule-flag string to a known EndpointOverride. Empty, "auto" and any unrecognized value map to OverrideAuto so misconfigured rules degrade safely.
type ErrorDetail ¶
type ErrorDetail struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code,omitempty"`
}
ErrorDetail represents error details
type ErrorResponse ¶
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
ErrorResponse represents an error response
type GenerateTokenRequest ¶
type GenerateTokenRequest struct {
ClientID string `json:"client_id" binding:"required" description:"Client ID for token generation" example:"user123"`
}
GenerateTokenRequest represents the request to generate a token
type HistoryResponse ¶
type HistoryResponse struct {
Success bool `json:"success" example:"true"`
Data interface{} `json:"data"`
}
HistoryResponse represents the response for request history
type IncomingAPIType ¶ added in v0.260531.1
type IncomingAPIType string
IncomingAPIType describes which OpenAI-style endpoint the client originally hit on this gateway. Only consulted when the provider declares EndpointModeBoth; otherwise the provider's declared mode dictates the upstream endpoint regardless of what the client sent.
const ( IncomingAPIChat IncomingAPIType = "chat" IncomingAPIResponses IncomingAPIType = "responses" )
type LBSimulator ¶ added in v0.260625.1
type LBSimulator struct {
// contains filtered or unexported fields
}
LBSimulator drives the real load-balancing path — routing.ServiceSelector.Select (health → affinity → smart → strategy) followed by dispatchWithPriorityFailover — against programmable fake upstreams over a request sequence, with a deterministic breaker clock.
It is the shared engine behind both the Go scenario tests (internal/server/lb_scenario_test.go) and the `harness lb` CLI tier, so the "how an LB scenario is simulated" logic lives in exactly one place. It lives in package server because it must reach the unexported failover dispatch loop.
func NewLBSimulator ¶ added in v0.260625.1
func NewLBSimulator(rule *typ.Rule, faults map[string][]int) (sim *LBSimulator, cleanup func(), err error)
NewLBSimulator builds the real selection + dispatch stack for rule against a throwaway config, registering one provider per distinct service provider. The faults map keys are serviceIDs (loadbalance.Service.ServiceID(), i.e. "provider/model"); each value is a per-call status sequence (last repeats). Services without a fault entry always return 200.
It installs a deterministic breaker clock; the returned cleanup restores the real clock and removes the temp config dir, and must be called.
func (*LBSimulator) Advance ¶ added in v0.260625.1
func (s *LBSimulator) Advance(d time.Duration)
Advance moves the deterministic breaker clock forward, e.g. past OpenDuration to drive a half-open recovery probe.
func (*LBSimulator) BreakerStates ¶ added in v0.260625.1
func (s *LBSimulator) BreakerStates() map[string]string
BreakerStates returns a snapshot of every rule service's breaker state, keyed by serviceID (values: "closed" / "open" / "half_open").
func (*LBSimulator) HealthStates ¶ added in v0.260625.1
func (s *LBSimulator) HealthStates() map[string]string
HealthStates returns a snapshot of every rule service's health-monitor state, keyed by serviceID (values: "healthy" / "unhealthy"). This is the channel fed by the special status codes (429 → rate-limit, 401/403 → auth), separate from the breaker.
func (*LBSimulator) Pin ¶ added in v0.260625.1
func (s *LBSimulator) Pin(session string) string
Pin returns the serviceID the session is currently affinity-locked to ("" if none).
func (*LBSimulator) PinDetail ¶ added in v0.260625.1
func (s *LBSimulator) PinDetail(session string) (serviceID string, lockedAt, expiresAt time.Time, ok bool)
PinDetail returns the current (non-expired) affinity lock for a session: the serviceID and its LockedAt/ExpiresAt timestamps (on the simulator's fake clock). ok is false when there is no live lock. It reads through the store's strict-TTL Get, so an expired lock reports ok=false — exactly what selection sees. Used to assert strict (non-sliding) TTL: an unrefreshed lock keeps its original timestamps, and a re-lock after expiry carries a fresh LockedAt.
func (*LBSimulator) Request ¶ added in v0.260625.1
func (s *LBSimulator) Request(session string) (LBTrace, error)
Request runs one request for the given session (empty = no affinity) through the real selection + failover path, returning the trace.
func (*LBSimulator) SeedPin ¶ added in v0.260625.1
func (s *LBSimulator) SeedPin(session, provider, model string)
SeedPin manually locks a session to a service (e.g. to reproduce a stale pin).
type LBTrace ¶ added in v0.260625.1
type LBTrace struct {
Session string `json:"session"`
Attempts []string `json:"attempts"` // serviceIDs attempted, in order (failover hops)
Statuses []int `json:"statuses"` // per-attempt status, parallel to Attempts
FinalStatus int `json:"final_status"` // status the client would see
PinAfter string `json:"pin_after"` // affinity pin after this request ("" if none)
// State snapshots taken AFTER this request, keyed by serviceID.
BreakerAfter map[string]string `json:"breaker_after"` // closed/open/half_open
HealthAfter map[string]string `json:"health_after"` // healthy/unhealthy
}
LBTrace is the record of one simulated request.
type LoadBalancer ¶
type LoadBalancer struct {
// contains filtered or unexported fields
}
LoadBalancer manages load balancing across multiple services
func NewLoadBalancer ¶
func NewLoadBalancer(cfg *config.Config, healthFilter *typ.HealthFilter) *LoadBalancer
NewLoadBalancer creates a new load balancer
func (*LoadBalancer) ClearAllStats ¶
func (lb *LoadBalancer) ClearAllStats()
ClearAllStats clears all statistics (both in-memory and persisted in config)
func (*LoadBalancer) ClearServiceStats ¶
func (lb *LoadBalancer) ClearServiceStats(provider, model string)
ClearServiceStats clears statistics for a specific service
func (*LoadBalancer) GetAllServiceStats ¶
func (lb *LoadBalancer) GetAllServiceStats() map[string]*loadbalance.ServiceStats
GetAllServiceStats returns all service statistics from all active rules. Stats are keyed by provider:model since stats are global (shared across rules).
func (*LoadBalancer) GetRuleSummary ¶
func (lb *LoadBalancer) GetRuleSummary(rule *typ.Rule) map[string]interface{}
GetRuleSummary returns a summary of rule configuration and statistics
func (*LoadBalancer) GetServiceStats ¶
func (lb *LoadBalancer) GetServiceStats(provider, model string) *loadbalance.ServiceStats
GetServiceStats returns statistics for a specific service
func (*LoadBalancer) HealthFilter ¶
func (lb *LoadBalancer) HealthFilter() *typ.HealthFilter
HealthFilter returns the health filter for the load balancer
func (*LoadBalancer) RecordUsage ¶
func (lb *LoadBalancer) RecordUsage(provider, model string, inputTokens, outputTokens int)
RecordUsage records usage for a service Deprecated: This method is no longer needed as usage is recorded directly in handlers
func (*LoadBalancer) RegisterTactic ¶
func (lb *LoadBalancer) RegisterTactic(tacticType loadbalance.TacticType, tactic typ.LoadBalancingTactic)
RegisterTactic registers a custom tactic
func (*LoadBalancer) SelectService ¶
func (lb *LoadBalancer) SelectService(rule *typ.Rule) (*loadbalance.Service, error)
SelectService selects the best service for a rule based on the configured tactic
func (*LoadBalancer) Stop ¶
func (lb *LoadBalancer) Stop()
Stop stops the load balancer and cleanup resources
func (*LoadBalancer) UpdateServiceIndex ¶
func (lb *LoadBalancer) UpdateServiceIndex(rule *typ.Rule, selectedService *loadbalance.Service)
UpdateServiceIndex updates the current service ID for a rule
func (*LoadBalancer) ValidateRule ¶
func (lb *LoadBalancer) ValidateRule(rule *typ.Rule) error
ValidateRule validates a rule configuration
type LoadBalancerAPI ¶
type LoadBalancerAPI struct {
// contains filtered or unexported fields
}
LoadBalancerAPI provides REST endpoints for load balancer management
func NewLoadBalancerAPI ¶
func NewLoadBalancerAPI(loadBalancer *LoadBalancer, cfg *config.Config) *LoadBalancerAPI
NewLoadBalancerAPI creates a new load balancer API
func (*LoadBalancerAPI) ClearAllStats ¶
func (api *LoadBalancerAPI) ClearAllStats(c *gin.Context)
ClearAllStats clears all statistics
func (*LoadBalancerAPI) ClearRuleStats ¶
func (api *LoadBalancerAPI) ClearRuleStats(c *gin.Context)
ClearRuleStats clears statistics for all services in a rule
func (*LoadBalancerAPI) ClearServiceStats ¶
func (api *LoadBalancerAPI) ClearServiceStats(c *gin.Context)
ClearServiceStats clears statistics for a specific service
func (*LoadBalancerAPI) GetAllStats ¶
func (api *LoadBalancerAPI) GetAllStats(c *gin.Context)
GetAllStats returns statistics for all services
func (*LoadBalancerAPI) GetCurrentService ¶
func (api *LoadBalancerAPI) GetCurrentService(c *gin.Context)
GetCurrentService returns the currently active service for a rule
func (*LoadBalancerAPI) GetMetrics ¶
func (api *LoadBalancerAPI) GetMetrics(c *gin.Context)
GetMetrics returns load balancing metrics
func (*LoadBalancerAPI) GetRule ¶
func (api *LoadBalancerAPI) GetRule(c *gin.Context)
GetRule returns a specific rule configuration
func (*LoadBalancerAPI) GetRuleStats ¶
func (api *LoadBalancerAPI) GetRuleStats(c *gin.Context)
GetRuleStats returns statistics for all services in a rule
func (*LoadBalancerAPI) GetRuleSummary ¶
func (api *LoadBalancerAPI) GetRuleSummary(c *gin.Context)
GetRuleSummary returns a comprehensive summary of a rule including statistics
func (*LoadBalancerAPI) GetServiceHealth ¶
func (api *LoadBalancerAPI) GetServiceHealth(c *gin.Context)
GetServiceHealth checks the health of all services in a rule
func (*LoadBalancerAPI) GetServiceStats ¶
func (api *LoadBalancerAPI) GetServiceStats(c *gin.Context)
GetServiceStats returns statistics for a specific service
func (*LoadBalancerAPI) GetServicesHealth ¶
func (api *LoadBalancerAPI) GetServicesHealth(c *gin.Context)
GetServicesHealth returns health status for all services in a rule
func (*LoadBalancerAPI) RegisterRoutes ¶
func (api *LoadBalancerAPI) RegisterRoutes(loadBalancer *gin.RouterGroup)
RegisterRoutes registers the load balancer API routes
func (*LoadBalancerAPI) ResetServiceHealth ¶
func (api *LoadBalancerAPI) ResetServiceHealth(c *gin.Context)
ResetServiceHealth manually resets a service's health to healthy
func (*LoadBalancerAPI) UpdateRuleTactic ¶
func (api *LoadBalancerAPI) UpdateRuleTactic(c *gin.Context)
UpdateRuleTactic updates the load balancing tactic for a rule
type LogEntry ¶
type LogEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Data map[string]interface{} `json:"data,omitempty"`
Fields map[string]interface{} `json:"fields,omitempty"`
}
LogEntry represents a log entry for API response
type LogsResponse ¶
LogsResponse represents the API response for logs
type MetricsData ¶
type MetricsData struct {
InputTokens int // Number of input/prompt tokens
OutputTokens int // Number of output/completion tokens
LatencyMs int64 // Total request latency in milliseconds
TTFTMs int64 // Time To First Token in milliseconds (0 if not available/applicable)
CacheHit bool // Whether this request hit the cache
TPS float64 // Tokens Per Second - generation speed (0 for non-streaming requests)
}
MetricsData encapsulates all metrics collected for a request. This structure is used to pass comprehensive metrics to updateServiceStats without requiring frequent function signature changes.
type MetricsResponse ¶
type MetricsResponse struct {
Metrics []ServiceMetric `json:"metrics"`
TotalServices int `json:"total_services" example:"5"`
}
MetricsResponse represents the metrics response
type ModelCapabilities ¶ added in v0.260611.1
type ModelCapabilities struct {
Batch CapabilitySupport `json:"batch"`
Citations CapabilitySupport `json:"citations"`
CodeExecution CapabilitySupport `json:"code_execution"`
ContextManagement *ContextManagementCapability `json:"context_management,omitempty"`
Effort *EffortCapability `json:"effort,omitempty"`
ImageInput CapabilitySupport `json:"image_input"`
PDFInput CapabilitySupport `json:"pdf_input"`
StructuredOutputs CapabilitySupport `json:"structured_outputs"`
Thinking *ThinkingCapability `json:"thinking,omitempty"`
}
ModelCapabilities maps to Anthropic's ModelCapabilities in /v1/models.
type ModelRequestDetail ¶ added in v0.260604.1
type ModelRequestDetail struct {
ModelRequestSummary
Events []ModelRequestEvent `json:"events"`
}
ModelRequestDetail is a summary plus the full, time-ordered event timeline.
type ModelRequestEvent ¶ added in v0.260604.1
type ModelRequestEvent struct {
Time time.Time `json:"time"`
Source string `json:"source"`
Level string `json:"level"`
Stage string `json:"stage,omitempty"`
Message string `json:"message"`
Fields map[string]interface{} `json:"fields,omitempty"`
}
ModelRequestEvent is a single log line belonging to one model request, regardless of which pipeline stage emitted it (HTTP envelope, protocol conversion / upstream client call, or smart-routing evaluation).
type ModelRequestSummary ¶ added in v0.260604.1
type ModelRequestSummary struct {
RequestID string `json:"request_id"`
Time time.Time `json:"time"`
Scenario string `json:"scenario,omitempty"`
RequestModel string `json:"request_model,omitempty"`
RoutedModel string `json:"routed_model,omitempty"`
Provider string `json:"provider,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Status int `json:"status,omitempty"`
LatencyMs int64 `json:"latency_ms,omitempty"`
HasError bool `json:"has_error"`
MaxLevel string `json:"max_level,omitempty"`
EventCount int `json:"event_count"`
}
ModelRequestSummary is the per-request row shown in the Requests view. It is derived by correlating every event that shares a request_id.
type ModelRequestsResponse ¶ added in v0.260604.1
type ModelRequestsResponse struct {
Total int `json:"total"`
Requests []ModelRequestSummary `json:"requests"`
}
ModelRequestsResponse is the list response for the Requests view.
type OpenAIChatCompletionResponse ¶
type OpenAIChatCompletionResponse struct {
ID string `json:"id" example:"chatcmpl-123"`
Object string `json:"object" example:"chat.completion"`
Created int64 `json:"created" example:"1677652288"`
Model string `json:"model" example:"gpt-3.5-turbo"`
Choices []struct {
Index int `json:"index" example:"0"`
Message struct {
Role string `json:"role" example:"assistant"`
Content string `json:"content" example:"Hello! How can I help you?"`
} `json:"message"`
FinishReason string `json:"finish_reason" example:"stop"`
} `json:"choices"`
Usage struct {
PromptTokens int `json:"prompt_tokens" example:"10"`
CompletionTokens int `json:"completion_tokens" example:"20"`
TotalTokens int `json:"total_tokens" example:"30"`
} `json:"usage"`
}
OpenAIChatCompletionResponse represents the OpenAI chat completion response
type OpenAIModel ¶
type OpenAIModel struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
OwnedBy string `json:"owned_by"`
Description string `json:"description,omitempty"` // Model description
Context int `json:"context,omitempty"` // Max context window
MaxOutput int `json:"max_output,omitempty"` // Max output tokens
// AuthType reflects the primary backing provider's auth type. It is
// non-standard (OpenAI's models API has no such field) and consumed by
// the tingly-box frontend to order model picker entries:
// oauth -> api_key -> vmodel.
AuthType string `json:"auth_type,omitempty"`
}
OpenAIModel represents a model in OpenAI's models API format
type OpenAIModelsResponse ¶
type OpenAIModelsResponse struct {
Object string `json:"object"`
Data []OpenAIModel `json:"data"`
}
OpenAIModelsResponse represents OpenAI's models API response format
type ProbeProviderResponse ¶
type ProbeProviderResponse struct {
Success bool `json:"success" example:"true"`
Error *ErrorDetail `json:"error,omitempty"`
Data *probe.ProbeProviderResponseData `json:"data,omitempty"`
}
ProbeProviderResponse represents the response from provider probing. The wrapper stays here because it embeds *ErrorDetail (server's global error model). The Data shape lives in internal/probe.
type ProbeRequestDetail ¶
type ProbeRequestDetail struct {
Messages []map[string]interface{} `json:"messages"`
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Temperature float64 `json:"temperature"`
Provider string `json:"provider"`
Timestamp string `json:"timestamp"`
}
ProbeRequestDetail represents the mock request data for probing
func NewMockRequest ¶
func NewMockRequest(provider, model string) ProbeRequestDetail
NewMockRequest creates a new mock request with default values
type ProbeResponse ¶
type ProbeResponse struct {
Success bool `json:"success"`
Error *ErrorDetail `json:"error,omitempty"`
Data *ProbeResponseData `json:"data,omitempty"`
}
ProbeResponse represents the overall probe response
type ProbeResponseData ¶
type ProbeResponseData struct {
Request ProbeRequestDetail `json:"request"`
Response ProbeResponseDetail `json:"response"`
Usage ProbeUsage `json:"usage"`
CurlCommand string `json:"curl_command,omitempty"`
}
ProbeResponseData represents the response data structure
type ProbeResponseDetail ¶
type ProbeResponseDetail struct {
Content string `json:"content"`
Model string `json:"model"`
Provider string `json:"provider"`
FinishReason string `json:"finish_reason"`
Error string `json:"error,omitempty"`
}
ProbeResponseDetail represents the API response
type ProbeUsage ¶
type ProbeUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
TimeCost int `json:"time_cost"`
}
ProbeUsage represents token usage information
type ProtocolRecorder ¶
type ProtocolRecorder struct {
// contains filtered or unexported fields
}
ProtocolRecorder captures a single client→tingly-box→provider cycle.
It carries both the scenario-level (client/final) and protocol-level (transformed) request/response pairs, plus optional streaming state. The recorder is mode-driven: which fields are emitted to the sink is decided by RecordMode (set at construction).
Lifecycle:
- EnsureProtocolRecorder at handler entry — captures client request, session, mode.
- Optional: transform pipeline writes SetOriginalRequest / SetTransformedRequest via TransformRecorder.
- For streaming, hooks call EnableStreaming + RecordStreamChunk + SetAssembledResponse.
- RecordResponse (success) or RecordError (failure) emits one *obs.Record.
func (*ProtocolRecorder) EnableStreaming ¶ added in v0.260531.1
func (sr *ProtocolRecorder) EnableStreaming()
EnableStreaming puts the recorder into streaming mode.
func (*ProtocolRecorder) RecordError ¶
func (sr *ProtocolRecorder) RecordError(err error)
RecordError emits an error record. err may be nil.
func (*ProtocolRecorder) RecordResponse ¶ added in v0.260514.1
func (sr *ProtocolRecorder) RecordResponse(provider *typ.Provider, model string)
RecordResponse finalises provider/model and emits a Record to the sink.
func (*ProtocolRecorder) RecordStreamChunk ¶ added in v0.260531.1
func (sr *ProtocolRecorder) RecordStreamChunk(eventType string, chunk interface{})
RecordStreamChunk records a single stream chunk.
func (*ProtocolRecorder) SetActiveService ¶ added in v0.260604.1
func (sr *ProtocolRecorder) SetActiveService(provider *typ.Provider, model string)
SetActiveService re-binds the recorder to a new provider/model. The failover orchestrator calls this between attempts so a subsequent RecordError attributes the failure to the right service rather than to whichever service the recorder was last bound to.
func (*ProtocolRecorder) SetAssembledResponse ¶ added in v0.260514.1
func (sr *ProtocolRecorder) SetAssembledResponse(response any)
SetAssembledResponse stores the final assembled (post-stream) response. Accepts map, []byte, or any JSON-marshallable value.
func (*ProtocolRecorder) SetOriginalRequest ¶
func (sr *ProtocolRecorder) SetOriginalRequest(req *obs.RecordRequest)
SetOriginalRequest stores the pre-transform request.
func (*ProtocolRecorder) SetTransformSteps ¶
func (sr *ProtocolRecorder) SetTransformSteps(steps []string)
SetTransformSteps records which transforms were applied.
func (*ProtocolRecorder) SetTransformedRequest ¶
func (sr *ProtocolRecorder) SetTransformedRequest(req *obs.RecordRequest)
SetTransformedRequest stores the post-transform request.
type RequestConfig ¶
type RequestConfig struct {
RequestModel string `json:"request_model" example:"gpt-3.5-turbo"`
ResponseModel string `json:"response_model" example:"gpt-3.5-turbo"`
Provider string `json:"provider" example:"openai"`
DefaultModel string `json:"default_model" example:"gpt-3.5-turbo"`
}
RequestConfig represents a request configuration in defaults response
type RuleStatsResponse ¶
type RuleStatsResponse struct {
Rule string `json:"rule" example:"gpt-4"`
Stats map[string]interface{} `json:"stats"`
}
RuleStatsResponse represents the statistics response for a rule
type RuleSummaryResponse ¶
type RuleSummaryResponse struct {
Summary interface{} `json:"summary"`
}
RuleSummaryResponse represents a rule summary response
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents the HTTP server
func GetGlobalServer ¶
func GetGlobalServer() *Server
GetGlobalServer gets the global server instance
func NewServer ¶
func NewServer(cfg *config.Config, opts ...ServerOption) *Server
NewServer creates a new HTTP server instance with functional options
func (*Server) AnthropicCountTokens ¶
AnthropicCountTokens handles Anthropic v1 count_tokens endpoint This is the entry point that delegates to the appropriate implementation (v1 or beta)
func (*Server) AnthropicListModelsForScenario ¶
func (s *Server) AnthropicListModelsForScenario(c *gin.Context, scenario typ.RuleScenario)
AnthropicListModelsForScenario handles scenario-scoped model listing for Anthropic format
func (*Server) AnthropicMessagesV1 ¶
func (s *Server) AnthropicMessagesV1(c *gin.Context, req *protocol.AnthropicMessagesRequest, requestModel string, responseModel string, rule *typ.Rule, provider *typ.Provider)
AnthropicMessagesV1 implements standard v1 messages API.
It runs the provider-independent prologue once, then drives the failover loop whose per-attempt callback re-runs the whole provider-dependent pipeline (pre-chain → guardrails → target resolution → transform → dispatch) against the candidate selected for that attempt. Because the transform is re-run per attempt, failover can rotate across heterogeneous API styles.
func (*Server) AnthropicMessagesV1Beta ¶
func (s *Server) AnthropicMessagesV1Beta(c *gin.Context, req *protocol.AnthropicBetaMessagesRequest, requestModel string, responseModel string, rule *typ.Rule, provider *typ.Provider)
AnthropicMessagesV1Beta implements beta messages API.
Like AnthropicMessagesV1, the provider-independent prologue runs once and the per-attempt callback re-runs the provider-dependent pipeline so failover can rotate across heterogeneous API styles.
func (*Server) CallMCPToolWithHooks ¶ added in v0.260514.1
func (s *Server) CallMCPToolWithHooks(ctx context.Context, toolName, arguments string, messages []map[string]any) (context.Context, coretool.ToolResult, error)
CallMCPToolWithHooks is the exported variant of callMCPToolWithHooks.
func (*Server) Cancel ¶ added in v0.260414.2000
func (s *Server) Cancel() context.CancelFunc
func (*Server) ClearGuardrailsHistory ¶
ClearGuardrailsHistory deletes all persisted guardrails history rows.
func (*Server) CreateGuardrailsCredential ¶
func (*Server) CreateGuardrailsGroup ¶
CreateGuardrailsGroup creates a new group and reloads the engine.
func (*Server) CreateGuardrailsPolicy ¶
CreateGuardrailsPolicy creates a new policy and reloads the engine.
func (*Server) DeleteGuardrailsCredential ¶
func (*Server) DeleteGuardrailsGroup ¶
DeleteGuardrailsGroup deletes a group and reloads the engine.
func (*Server) DeleteGuardrailsPolicy ¶
DeleteGuardrailsPolicy deletes a policy and reloads the engine.
func (*Server) EnsureProtocolRecorder ¶ added in v0.260531.1
func (s *Server) EnsureProtocolRecorder(c *gin.Context, scenario string, provider *typ.Provider, model string, mode obs.RecordMode, bs []byte) *ProtocolRecorder
EnsureProtocolRecorder returns a ProtocolRecorder for the given scenario, reusing any recorder already stored in the gin context. Returns nil when recording is disabled (no sink) or the request body cannot be read.
func (*Server) ExportGuardrailsFragments ¶ added in v0.260418.2200
ExportGuardrailsFragments returns the raw imported fragment files selected by the user so the UI can download one or more source files directly.
func (*Server) ExtractRequestContext
deprecated
func (s *Server) ExtractRequestContext(req interface{}) (*smartrouting.RequestContext, error)
ExtractRequestContext extracts RequestContext from request based on type
Deprecated: Use routing/smart_routing_helper.go ExtractRequestContext() instead.
func (*Server) GenerateToken ¶
GenerateToken handles token generation requests
func (*Server) GetActionHistory ¶
GetActionHistory retrieves user action history from memory Query parameters:
- limit: maximum number of recent entries to return (default: 100, max: 1000)
func (*Server) GetActionStats ¶
GetActionStats returns statistics about user actions
func (*Server) GetGuardrailsBuiltins ¶
GetGuardrailsBuiltins returns curated builtin policies for the Guardrails UI.
func (*Server) GetGuardrailsConfig ¶
GetGuardrailsConfig returns the current guardrails config file content and parsed config.
func (*Server) GetGuardrailsCredential ¶
GetGuardrailsCredential returns a single protected credential, including the current secret, for the local editor dialog.
func (*Server) GetGuardrailsCredentials ¶
Credential list responses intentionally mask secrets; the edit dialog uses GetGuardrailsCredential when it needs the underlying value. GetGuardrailsCredentials returns protected credentials without exposing raw secrets.
func (*Server) GetGuardrailsHistory ¶
GetGuardrailsHistory returns the most recent guardrails history rows.
func (*Server) GetGuardrailsRegistry ¶ added in v0.260418.2200
GetGuardrailsRegistry lists downloadable policies from a remote registry.
func (*Server) GetHistory ¶
func (*Server) GetLoadBalancer ¶
func (s *Server) GetLoadBalancer() *LoadBalancer
GetLoadBalancer returns the load balancer instance
func (*Server) GetLogStats ¶
GetLogStats returns statistics about the logs
func (*Server) GetLogs ¶
GetLogs retrieves logs with optional filtering Query parameters:
- limit: maximum number of entries to return (default: 100)
- level: filter by log level (debug, info, warn, error)
- since: RFC3339 timestamp to filter entries after this time
func (*Server) GetModelRequestDetail ¶ added in v0.260604.1
GetModelRequestDetail returns the full event timeline for a single request id.
func (*Server) GetModelRequests ¶ added in v0.260604.1
GetModelRequests returns recent model requests, one row per correlation id, built by joining the HTTP access log, model_request stage logs and smart-routing traces from the in-memory sinks.
Query parameters:
- limit: maximum number of requests to return (default: 100, max: 1000)
- scenario / provider / status: optional exact-match filters
func (*Server) GetOrCreateScenarioSink ¶
func (s *Server) GetOrCreateScenarioSink(scenario typ.RuleScenario) *obs.Sink
GetOrCreateScenarioSink gets or creates a recording sink for the specified scenario The sink is created on-demand and cached for subsequent use
func (*Server) GetRoutingSelector ¶ added in v0.260414.2000
func (s *Server) GetRoutingSelector() *routing.SimpleSelector
GetRoutingSelector returns the server's routing selector for service selection.
func (*Server) GetScenarioRecordMode ¶ added in v0.260514.1
func (s *Server) GetScenarioRecordMode(scenario typ.RuleScenario) obs.RecordMode
func (*Server) GetSystemLogLevel ¶
GetSystemLogLevel returns the current system log level
func (*Server) GetSystemLogStats ¶
GetSystemLogStats returns statistics about the system logs
func (*Server) GetSystemLogs ¶
GetSystemLogs retrieves system logs with optional filtering Query parameters:
- limit: maximum number of recent entries to return (default: 100, max: 1000)
func (*Server) GetToken ¶
GetToken handles token retrieval requests - generates a token if it doesn't exist
func (*Server) GetUserToken ¶
GetUserToken returns the current user token (masked) Requires authentication
func (*Server) HandleAnthropicListModels ¶ added in v0.260625.1
HandleAnthropicListModels handles Anthropic v1 models endpoint
func (*Server) HandleAnthropicMessages ¶
HandleAnthropicMessages handles Anthropic v1 messages API requests This is the entry point that delegates to the appropriate implementation (v1 or beta)
func (*Server) HandleOpenAIChatCompletions ¶
HandleOpenAIChatCompletions handles OpenAI v1 chat completion requests
func (*Server) HandleOpenAIEmbeddings ¶ added in v0.260507.1
HandleOpenAIEmbeddings serves OpenAI-compatible embedding requests.
The endpoint is exposed via the mixin route group, so any scenario whose descriptor declares TransportOpenAI or TransportEmbed can reach it. The canonical home is the dedicated `embed` scenario; `openai` scenario also works because its descriptor is extended with TransportEmbed.
func (*Server) HandleOpenAIImageGeneration ¶ added in v0.260514.1
HandleOpenAIImageGeneration serves OpenAI-compatible image generation requests against the upstream POST /v1/images/generations endpoint. The request is forwarded as-is; tingly-box does not probe whether the upstream prefers the dedicated images endpoint or the Responses API — the caller chooses the surface and the corresponding tingly-box route.
Exposed via the mixin route group, so any scenario whose descriptor declares TransportImageGen (or TransportOpenAI as a mixin) can reach it. The canonical home is the dedicated `imagegen` scenario.
func (*Server) HandleOpenAIListModels ¶ added in v0.260625.1
HandleOpenAIListModels handles the /v1/models endpoint (OpenAI compatible)
func (*Server) HandleResponsesCreate ¶
HandleResponsesCreate handles POST /v1/responses
func (*Server) HandleResponsesGet ¶ added in v0.260625.1
HandleResponsesGet handles GET /v1/responses/{id}
func (*Server) HealthMonitor ¶
func (s *Server) HealthMonitor() *loadbalance.HealthMonitor
HealthMonitor returns the server's health monitor
func (*Server) ImportGuardrailsFragment ¶ added in v0.260418.2200
ImportGuardrailsFragment appends one or more policies from a fragment file into guardrails/custom/import.yaml and ensures the root config imports it.
func (*Server) InstallGuardrailsRegistryPolicy ¶ added in v0.260418.2200
InstallGuardrailsRegistryPolicy downloads a remote policy fragment into guardrails/remote and wires it into root imports.
func (*Server) IsRemoteCoderRunning ¶
IsRemoteCoderRunning returns whether the remote control service is running
func (*Server) ListModelsByScenario ¶
ListModelsByScenario handles the /v1/models endpoint for scenario-based routing
func (*Server) NewUsageTracker ¶
func (s *Server) NewUsageTracker() *UsageTracker
NewUsageTracker creates a new UsageTracker
func (*Server) OpenAIChatCompletion ¶
func (s *Server) OpenAIChatCompletion(c *gin.Context, req *protocol.OpenAIChatCompletionRequest, responseModel string, provider *typ.Provider, scenarioType typ.RuleScenario, rule *typ.Rule)
OpenAIChatCompletion runs the provider-independent prologue once, then drives the failover loop whose per-attempt callback re-runs the provider-dependent pipeline (align → cap → target resolution → transform → dispatch) so failover can rotate across heterogeneous API styles.
func (*Server) OpenAIListModelsForScenario ¶
func (s *Server) OpenAIListModelsForScenario(c *gin.Context, scenario typ.RuleScenario)
OpenAIListModelsForScenario handles scenario-scoped model listing for OpenAI format
func (*Server) ReloadGuardrailsConfig ¶
ReloadGuardrailsConfig reloads guardrails from disk and rebuilds the runtime.
func (*Server) ResetModelToken ¶
ResetModelToken generates a new secure random model token and updates the configuration Requires authentication
func (*Server) ResetUserToken ¶
ResetUserToken generates a new secure random token and updates the configuration Requires authentication
func (*Server) ResponsesCreate ¶
func (s *Server) ResponsesCreate(c *gin.Context, scenarioType typ.RuleScenario, provider *typ.Provider, rule *typ.Rule, req *protocol.ResponseCreateRequest, responseModel string, maxAllowed int)
ResponsesCreate runs the provider-independent prologue once, then drives the failover loop whose per-attempt callback re-runs the provider-dependent pipeline (target resolution → transform → dispatch) so failover can rotate across heterogeneous API styles.
func (*Server) RestartServer ¶
func (*Server) SelectServiceFromSmartRouting
deprecated
func (s *Server) SelectServiceFromSmartRouting(matchedServices []*loadbalance.Service, rule *typ.Rule) (*loadbalance.Service, error)
SelectServiceFromSmartRouting selects a service from matched smart routing services Creates a temporary rule with the matched services and uses the configured load balancing tactic
Deprecated: Use routing.SmartRoutingStage instead.
func (*Server) SetSystemLogLevel ¶
SetSystemLogLevel sets the minimum log level for system logs
func (*Server) SetupAnthropicEndpoints ¶
func (s *Server) SetupAnthropicEndpoints(group *gin.RouterGroup)
func (*Server) SetupMixinEndpoints ¶
func (s *Server) SetupMixinEndpoints(group *gin.RouterGroup)
func (*Server) SetupOpenAIEndpoints ¶
func (s *Server) SetupOpenAIEndpoints(group *gin.RouterGroup)
func (*Server) StartDynamicCallbackServer ¶
StartDynamicCallbackServer starts a temporary callback server for OAuth Implements CallbackServerManager interface for oauth module
func (*Server) StartRemoteCoder ¶
StartRemoteCoder starts the remote control service if not already running
func (*Server) StartServer ¶
func (*Server) StopDynamicCallbackServer ¶
StopDynamicCallbackServer stops a temporary callback server for OAuth Implements CallbackServerManager interface for oauth module
func (*Server) StopRemoteCoder ¶
func (s *Server) StopRemoteCoder()
StopRemoteCoder stops the remote control service if running
func (*Server) StopServer ¶
func (*Server) SyncRemoteCoderBots ¶
SyncRemoteCoderBots syncs bots with the remote control bot manager
func (*Server) TrackUsage ¶
TrackUsage implements the UsageTracker interface. It extracts the gin.Context from the provided context and calls trackUsageFromContext. The gin.Context should be stored in the context with the key "gin_context".
func (*Server) UpdateGuardrailsConfig ¶
UpdateGuardrailsConfig saves a new guardrails config and reloads the engine.
func (*Server) UpdateGuardrailsCredential ¶
func (*Server) UpdateGuardrailsGroup ¶
UpdateGuardrailsGroup updates a single group and reloads the engine.
func (*Server) UpdateGuardrailsPolicy ¶
UpdateGuardrailsPolicy updates a single policy and reloads the engine.
func (*Server) UsageStore ¶
func (s *Server) UsageStore() *db.UsageStore
UsageStore returns the server's usage store instance for internal integrations.
func (*Server) UseAIEndpoints ¶
func (s *Server) UseAIEndpoints()
func (*Server) UseIndexHTML ¶
func (*Server) UseLoadBalanceEndpoints ¶
func (s *Server) UseLoadBalanceEndpoints()
func (*Server) UseTokenManagementEndpoints ¶ added in v0.260418.2200
func (s *Server) UseTokenManagementEndpoints()
UseTokenManagementEndpoints registers the token management API endpoints.
func (*Server) UseUIEndpoints ¶
Init sets up Server routes and templates on the main server engine
func (*Server) UseVirtualModelEndpoints ¶
func (s *Server) UseVirtualModelEndpoints()
UseVirtualModelEndpoints sets up the direct virtual-model entrypoints, split per protocol:
/virtual/openai/v1/{models,chat/completions}
/virtual/anthropic/v1/{models,messages}
These bypass the provider/rule/scenario pipeline and call the in-process handler directly — useful when a client wants a fixed URL pointed at the vmodel registry without configuring a provider. The protocol split ensures /models returns only the model IDs the chosen protocol can actually dispatch.
The canonical path for virtual models in normal use is still /v1/messages and /v1/chat/completions, where the dispatcher short-circuits to the same handler when it resolves to a vmodel provider (see HandleAnthropicMessages and HandleOpenAIChatCompletions).
func (*Server) ValidateAuthToken ¶
ValidateAuthToken validates an authentication token without requiring auth This is used during login flow to verify a token before establishing session
type ServerActionResponse ¶
type ServerActionResponse struct {
Success bool `json:"success" example:"true"`
Message string `json:"message" example:"Server stopped successfully"`
}
ServerActionResponse represents the response for server actions (start/stop/restart)
type ServerOption ¶
type ServerOption func(*Server)
ServerOption defines a functional option for Server configuration
func WithAdaptor ¶
func WithAdaptor(enabled bool) ServerOption
WithAdaptor enables or disables the adaptor for the server
func WithAuthMiddleware ¶
func WithAuthMiddleware(userAuth, modelAuth gin.HandlerFunc) ServerOption
WithAuthMiddleware sets custom auth middlewares for WebUI and Model API endpoints This allows TBE to inject its own JWT auth middleware instead of using tingly-box's default UserAuthMiddleware and ModelAuthMiddleware
Usage in TBE:
server := NewServer(cfg,
WithAuthMiddleware(tbeUserAuth, tbeModelAuth),
)
func WithDebug ¶
func WithDebug(enabled bool) ServerOption
WithDebug enables or disables debug mode for the server
func WithGuardrails ¶
func WithGuardrails(runtime *guardrails.Guardrails) ServerOption
WithGuardrails sets a guardrails runtime for stream evaluation.
func WithHost ¶
func WithHost(host string) ServerOption
func WithModelAuthMiddleware ¶
func WithModelAuthMiddleware(modelAuth gin.HandlerFunc) ServerOption
WithModelAuthMiddleware sets a custom model auth middleware for Model API endpoints Use this if you only want to replace ModelAuthMiddleware but keep UserAuthMiddleware
func WithMultiLogger ¶
func WithMultiLogger(logger *pkgobs.MultiLogger) ServerOption
WithMultiLogger sets the multi-mode logger for the server
func WithOpenBrowser ¶
func WithOpenBrowser(enabled bool) ServerOption
WithOpenBrowser enables or disables automatic browser opening
func WithRecordDir ¶
func WithRecordDir(dir string) ServerOption
WithRecordDir sets the scenario-level record directory
func WithRecordMode ¶
func WithRecordMode(mode obs.RecordMode) ServerOption
WithRecordMode sets the record mode for request/response recording mode: empty string = disabled, "all" = record all, "response" = response only, "scenario" = record scenario only
func WithRecording ¶
func WithRecording(enabled bool) ServerOption
WithRecording enables dual-stage recording for protocol conversion scenarios
func WithRecordingCAS ¶ added in v0.260514.1
func WithRecordingCAS(enabled bool) ServerOption
WithRecordingCAS toggles content-addressed dedup alongside the default gzip recording. When enabled, each session is written twice: once as a gzip JSONL.gz (default), and once as content-addressed slim JSONL plus a per-record blob tree. Useful for cross-session prompt analysis and replay.
func WithTemplateManager ¶ added in v0.260409.1540
func WithTemplateManager(tm *data.TemplateManager) ServerOption
WithTemplateManager allows TBE to inject a custom TemplateManager. This follows the same pattern as WithAuthMiddleware for consistency.
func WithUI ¶
func WithUI(enabled bool) ServerOption
WithUI enables or disables the UI for the server
func WithUserAuthMiddleware ¶
func WithUserAuthMiddleware(userAuth gin.HandlerFunc) ServerOption
WithUserAuthMiddleware sets a custom user auth middleware for WebUI endpoints Use this if you only want to replace UserAuthMiddleware but keep ModelAuthMiddleware
func WithVersion ¶
func WithVersion(version string) ServerOption
type ServiceHealthResponse ¶
type ServiceHealthResponse struct {
Rule string `json:"rule" example:"gpt-4"`
Health map[string]interface{} `json:"health"`
}
ServiceHealthResponse represents the health check response for services
type ServiceMetric ¶
type ServiceMetric struct {
ServiceID string `json:"service_id" example:"openai:gpt-4"`
RequestCount int64 `json:"request_count" example:"100"`
WindowRequestCount int64 `json:"window_request_count" example:"50"`
WindowTokensConsumed int64 `json:"window_tokens_consumed" example:"25000"`
WindowInputTokens int64 `json:"window_input_tokens" example:"15000"`
WindowOutputTokens int64 `json:"window_output_tokens" example:"10000"`
LastUsed string `json:"last_used" example:"2024-01-01T12:00:00Z"`
}
ServiceMetric represents a service metric entry
type ServiceStatsResponse ¶
type ServiceStatsResponse struct {
ServiceID string `json:"service_id" example:"openai:gpt-4"`
Stats map[string]interface{} `json:"stats,omitempty"`
}
ServiceStatsResponse represents the statistics response for a service
type StatusResponse ¶
type StatusResponse struct {
Success bool `json:"success" example:"true"`
Data struct {
ServerRunning bool `json:"server_running" example:"true"`
Port int `json:"port" example:"12580"`
ProvidersTotal int `json:"providers_total" example:"3"`
ProvidersEnabled int `json:"providers_enabled" example:"2"`
RequestCount int `json:"request_count" example:"100"`
} `json:"data"`
}
OpenAIModel represents a model in OpenAI's models API format
type SystemLogEntry ¶
type SystemLogEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Fields map[string]interface{} `json:"fields,omitempty"`
}
SystemLogEntry represents a system log entry for API response
type SystemLogLevelRequest ¶
type SystemLogLevelRequest struct {
Level string `json:"level" binding:"required"`
}
SystemLogLevelRequest represents a request to set the log level
type SystemLogsResponse ¶
type SystemLogsResponse struct {
Total int `json:"total"`
Logs []SystemLogEntry `json:"logs"`
}
SystemLogsResponse represents the API response for system logs
type ThinkingCapability ¶ added in v0.260611.1
type ThinkingCapability struct {
Supported bool `json:"supported"`
Types *ThinkingTypes `json:"types,omitempty"`
}
ThinkingCapability describes thinking support.
type ThinkingTypes ¶ added in v0.260611.1
type ThinkingTypes struct {
Adaptive CapabilitySupport `json:"adaptive,omitempty"`
Enabled CapabilitySupport `json:"enabled,omitempty"`
}
ThinkingTypes describes supported thinking type configurations.
type TokenResponse ¶
type TokenResponse struct {
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."`
Type string `json:"type" example:"Bearer"`
}
TokenResponse represents the token response
type TransformRecorder ¶ added in v0.260531.1
type TransformRecorder struct {
// contains filtered or unexported fields
}
TransformRecorder is a transform.Transform that snapshots the request body at a given stage and stores it on a ProtocolRecorder.
func NewTransformRecorder ¶ added in v0.260531.1
func NewTransformRecorder(c *gin.Context, recorder *ProtocolRecorder, stage TransformStage) *TransformRecorder
NewTransformRecorder builds a recorder transform for the given stage.
func (*TransformRecorder) Apply ¶ added in v0.260531.1
func (t *TransformRecorder) Apply(ctx *transform.TransformContext) error
func (*TransformRecorder) Name ¶ added in v0.260531.1
func (t *TransformRecorder) Name() string
type TransformStage ¶ added in v0.260531.1
type TransformStage int
TransformStage selects which side of the transform pipeline the recorder captures from.
const ( // StagePre captures ctx.OriginalRequest before any transformation is // applied. StagePre TransformStage = iota // StagePost captures ctx.Request after base transformation. StagePost )
type UpdateRuleTacticRequest ¶
type UpdateRuleTacticRequest struct {
Tactic string `` /* 147-byte string literal not displayed */
}
UpdateRuleTacticRequest represents the request to update rule tactic
type UpdateRuleTacticResponse ¶
type UpdateRuleTacticResponse struct {
Message string `json:"message" example:"Tactic updated successfully"`
Tactic string `json:"tactic" example:"adaptive"`
}
UpdateRuleTacticResponse represents the response for updating rule tactic
type UsageTracker ¶
type UsageTracker struct {
// contains filtered or unexported fields
}
UsageTracker provides usage tracking methods for handlers. It encapsulates the logic for recording token usage to both service stats and detailed usage records.
func (*UsageTracker) RecordUsage ¶
func (t *UsageTracker) RecordUsage( c *gin.Context, rule *typ.Rule, provider *typ.Provider, model, requestModel string, inputTokens, outputTokens int, streamed bool, status, errorCode string, )
RecordUsage records token usage from a handler. It updates both the service-level stats and the detailed usage records.
Parameters:
- c: Gin context for accessing request metadata
- rule: The load balancer rule that was used
- provider: The provider that handled the request
- model: The actual model name used (not the requested model)
- requestModel: The original model name requested by the user
- inputTokens: Number of input/prompt tokens consumed
- outputTokens: Number of output/completion tokens consumed
- streamed: Whether this was a streaming request
- status: Request status - "success", "error", or "partial"
- errorCode: Error code if status is not "success"
Source Files
¶
- affinity.go
- anthropic_1m.go
- anthropic_affinity.go
- anthropic_count_tokens.go
- anthropic_message.go
- anthropic_model.go
- anthropic_to_openai_mcp_stream.go
- cursor_compat.go
- failover_dispatch.go
- guardrails_handler.go
- guardrails_runtime.go
- handlers.go
- load_balance.go
- load_balance_handler.go
- load_balance_simulator.go
- log_handler.go
- mcp_anthropic_loop.go
- mcp_anthropic_v1_helper.go
- mcp_tool_error.go
- model_list_helper.go
- model_request_handler.go
- native_advisor_detection.go
- openai_chat.go
- openai_embeddings.go
- openai_image.go
- openai_mcp.go
- openai_model.go
- openai_responses.go
- openapi.go
- protocol_cross.go
- protocol_dispatch.go
- protocol_endpoint.go
- protocol_passthrough.go
- protocol_recording.go
- protocol_roundtrip.go
- protocol_transform.go
- recording_hooks.go
- recording_transform.go
- request_clone.go
- rule_flags.go
- server.go
- server_control.go
- server_flags.go
- server_lifecycle.go
- server_log_handler.go
- server_middleware.go
- server_oauth.go
- server_options.go
- server_routes.go
- server_scenario.go
- server_types.go
- smart_routing_helper.go
- tracking.go
- tracking_context.go
- usage_tracking.go
- webui.go
- webui_api.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package middleware provides Gin middleware for the tingly-box server.
|
Package middleware provides Gin middleware for the tingly-box server. |
|
module
|
|
|
imbot
Package imbotsettings provides handlers for ImBot settings management.
|
Package imbotsettings provides handlers for ImBot settings management. |
|
info
Package versioncheck provides version lookup against the npm registry (with npmmirror as a China-mirror fallback) and semver-style comparison.
|
Package versioncheck provides version lookup against the npm registry (with npmmirror as a China-mirror fallback) and semver-style comparison. |
|
notify
Package notify is the HTTP front end for scenario plugin events.
|
Package notify is the HTTP front end for scenario plugin events. |
|
provider
Package provider handles CRUD and model-management HTTP endpoints for AI provider configurations.
|
Package provider handles CRUD and model-management HTTP endpoints for AI provider configurations. |
|
sharing
Package apitoken implements CRUD HTTP endpoints for shared API tokens.
|
Package apitoken implements CRUD HTTP endpoints for shared API tokens. |
|
virtualmodel
Package virtualmodel exposes management endpoints for the in-process virtual-model providers.
|
Package virtualmodel exposes management endpoints for the in-process virtual-model providers. |