analytics

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 26 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const ServiceTierNone = "none"

ServiceTierNone selects the records without a service tier (list-price traffic, rows written before the tier was recorded, and rows an early build stored as "default"/"auto") in the ServiceTierUsage filter. In the report those rows have tier "".

Variables

View Source
var ErrEdgeBatchUnsupported = errors.New("analytics handler cannot store an edge batch once")

ErrEdgeBatchUnsupported is returned by RecordEdgeBatch when the handler in use cannot store a batch once. The caller records the batch's records the usual way.

View Source
var ErrRecorderBusy = errors.New("analytics recorder busy")

ErrRecorderBusy is returned by RecordMCPCalls when the batch was not queued: the buffer is full or the recorder has stopped.

View Source
var MCPIntervals = map[string]bool{"hour": true, "day": true}

MCPIntervals are the time series bucket sizes.

View Source
var TeeQueueSize = 10000

TeeQueueSize is the per-sink queue length.

Functions

func BindHandler added in v2.3.0

func BindHandler(ctx context.Context) context.Context

BindHandler returns ctx with the handler its records go to now fixed on it: the one WithHandler put there, else the current global handler. Records made on ctx (or a context derived from it) later go to that handler even if the global one has been replaced in between. The proxy binds every request it serves, so analysis that finishes after the response never lands in a handler installed after the request arrived (a test's, when tests swap the global handler). With neither, ctx is returned unchanged and records resolve the global handler when they are made, as before.

func CaptureSink added in v2.3.0

func CaptureSink() agenttrace.Sink

CaptureSink is the agenttrace.Sink that sends finished captures to the global analytics handler. The hub installs it with agenttrace.SetSink once the tracing start gate has passed; so does the Enterprise microgateway.

func EncodeCaptureRows added in v2.3.0

func EncodeCaptureRows(source string, events []*agenttrace.Event, onDrop func(reason string, n int64)) []models.AgentTraceCaptureEvent

EncodeCaptureRows turns events into staging rows for source (SourceEmbedded or an edge id). The idempotency key is always rebuilt from source, so an edge cannot write keys in another source's space.

func GetAppActivity

func GetAppActivity(db *gorm.DB, appIDs []uint, since time.Time) (map[uint]*AppActivity, error)

GetAppActivity returns activity keyed by app id for the given apps. Apps with no chat records are absent from the map.

func GetAppSpending

func GetAppSpending(db *gorm.DB, windows []AppSpendWindow, end time.Time) (map[uint]map[string]float64, error)

GetAppSpending returns each app's spend between its own window start and `end`, by currency (budget.CurrencySQL), in the same units as the budget service (llm_chat_records.cost is stored x10000; see proxy/analyze_utils.go). A budget's currency is implied by its spend: read each app's figures with budget.SplitCurrency. One query for every app: each app contributes an (app_id, start) predicate, so a user with twenty apps costs one round trip rather than twenty. Apps with no records are absent.

func GetBudgetUsage

func GetBudgetUsage(db *gorm.DB, startDate, endDate *time.Time, llmID *uint) ([]models.BudgetUsage, error)

GetBudgetUsage returns usage statistics for all LLMs and Apps that have costs, with optional date range. Each entity's monthly usage (Spent, Usage) is its spend in its current budget period, as budget enforcement counts it (see periodUsage), in Currency; a period that mixes currencies is reported in MixedCurrencySpend instead. TotalCost and TotalTokens cover the date range.

func GetChatLogsForChatID

func GetChatLogsForChatID(db *gorm.DB, chatID uint) ([]models.LLMChatLogEntry, error)

GetChatLogsForChatID retrieves all chat log entries for a specific chat ID

func GetCostAnalysis

func GetCostAnalysis(db *gorm.DB, startDate, endDate time.Time, interactionType *models.InteractionType) (map[string]*ChartData, error)

GetCostAnalysis returns the total cost per day for each currency and interaction type

func GetProxyLogsForAppID

func GetProxyLogsForAppID(db *gorm.DB, startDate, endDate time.Time, appID uint, page, pageSize int, search string) ([]models.ProxyLog, int64, error)

GetProxyLogsForAppID returns paginated proxy logs for a specific app Optional search parameter: a request id, or text in request_body or response_body

func GetProxyLogsForLLM

func GetProxyLogsForLLM(db *gorm.DB, startDate, endDate time.Time, llmID uint, page, pageSize int, search string) ([]models.ProxyLog, int64, error)

GetProxyLogsForLLM returns paginated proxy logs for a specific LLM by filtering on vendor Optional search parameter searches request_body and response_body fields

func GetTokenUsageAndCostForApp

func GetTokenUsageAndCostForApp(db *gorm.DB, startDate, endDate time.Time, appID uint) (*models.MultiAxisChartData, error)

GetTokenUsageAndCostForApp returns the token usage and total cost for a specific app over time

func GetToolOperationsUsageOverTime

func GetToolOperationsUsageOverTime(db *gorm.DB, toolID uint, startDate, endDate time.Time) (*models.MultiAxisChartData, error)

GetToolOperationsUsageOverTime returns the usage count for each operation of a specific tool over time

func GetUsage

func GetUsage(db *gorm.DB, startDate, endDate time.Time, vendor string, llmID, appID *uint, interactionType *models.InteractionType, modelName string) (*models.MultiAxisChartData, error)

GetUsage returns token usage and cost data based on provided filters modelName, when non-empty, restricts the series to a single model (matched on the recorded model name, so an alias appears under its resolved name).

func Init

func Init(ctx context.Context, db *gorm.DB)

Init initializes analytics with default database handler (for backward compatibility)

func InitDefault

func InitDefault(ctx context.Context, db *gorm.DB)

InitDefault initializes the default database analytics handler

func Migrate

func Migrate(db *gorm.DB) error

Migrate creates or updates the analytics tables. pkg/studio runs it with the other migrations under the cross-instance migration lock. The handler does not migrate: it may write to a database whose schema another instance owns, so whoever owns the schema calls Migrate before recording starts.

func RecordCaptureEvents added in v2.3.0

func RecordCaptureEvents(ctx context.Context, events []*agenttrace.Event)

RecordCaptureEvents hands capture events to the global handler when it stages them. Other handlers ignore them.

func RecordChatLogEntry

func RecordChatLogEntry(ctx context.Context, log *models.LLMChatLogEntry)

func RecordChatRecord

func RecordChatRecord(ctx context.Context, record *models.LLMChatRecord)

func RecordChatRecordsBatch

func RecordChatRecordsBatch(ctx context.Context, records []*models.LLMChatRecord)

RecordChatRecordsBatch records multiple chat records in a batch for improved performance

func RecordComplianceEvents

func RecordComplianceEvents(ctx context.Context, events []*models.ComplianceEvent)

RecordComplianceEvents records filter script compliance events asynchronously

func RecordContentMessage

func RecordContentMessage(
	mc *llms.MessageContent,
	cr *llms.ContentResponse,
	vendor models.Vendor,
	name, chatID string,
	timeMs int, userID, appID, llmID uint,
	t time.Time,
	svc services.ServiceInterface,
	dontLogBodies bool,
)

func RecordEdgeBatch added in v2.3.0

func RecordEdgeBatch(ctx context.Context, b *EdgeBatch) (stored bool, err error)

RecordEdgeBatch stores an edge's batch once through the handler for ctx. See EdgeBatchRecorder for what it returns.

func RecordExchange

func RecordExchange(ctx context.Context, log *models.ProxyLog, rec *models.LLMChatRecord)

RecordExchange records a proxied request's proxy log together with its chat record (nil when the response yielded no usage). A handler that implements ExchangeRecorder gets both in one call; any other handler gets RecordProxyLog followed by RecordChatRecord, as before.

func RecordMCPCalls added in v2.3.0

func RecordMCPCalls(ctx context.Context, records []models.MCPCallRecord) error

RecordMCPCalls records MCP calls a Tyk Gateway proxied, as ingested from Tyk Pump. It returns ErrRecorderBusy when the handler could not take the batch, so the sender retries it. With no handler, or one that does not record MCP calls (MCPCallRecorder), there is nothing to record into and a retry would never succeed: the batch is dropped (logged once).

func RecordProxyLog

func RecordProxyLog(ctx context.Context, log *models.ProxyLog)

func RecordProxyLogsBatch

func RecordProxyLogsBatch(ctx context.Context, logs []*models.ProxyLog)

RecordProxyLogsBatch records multiple proxy logs in a batch for improved performance

func RecordToolCall

func RecordToolCall(ctx context.Context, name string, t time.Time, execTime int, toolID uint)

func RequestLatencyMS

func RequestLatencyMS(ctx context.Context, end time.Time) (int, bool)

RequestLatencyMS is the time from the request's start to end, in milliseconds. end is normally the moment the response completed (a record's TimeStamp); when it is not after the start (a timestamp taken at the start of the request) the time elapsed until now is used instead. ok is false when the context carries no start.

func ResetHandler

func ResetHandler()

ResetHandler resets the global analytics handler (useful for testing). When the handler is a stopped database recorder, it waits (briefly) for the recorder's worker to finish, so it does not outlive the Studio that stopped it: a Studio started next in the process replaces the package state (the logger) the worker still uses.

func SetBufferSize

func SetBufferSize(n int)

SetBufferSize sets how many records wait in memory to be written (Studio passes AppConf.AnalyticsBufferSize); without it, ANALYTICS_BUFFER_SIZE decides. Call it before StartRecording.

func SetCaptureLimits added in v2.3.0

func SetCaptureLimits(maxEvents int, maxBytes int64)

SetCaptureLimits sets the capture queue caps; zero or less keeps the default (10,000 events, 64 MiB). Call it before the first capture.

func SetComplianceEventsStored added in v2.3.0

func SetComplianceEventsStored(fn func([]*models.ComplianceEvent))

SetComplianceEventsStored sets the hook; nil removes it.

func SetHandler

func SetHandler(handler AnalyticsHandler)

SetHandler sets the global analytics handler implementation

func StageCaptureEvents added in v2.3.0

func StageCaptureEvents(db *gorm.DB, source string, events []*agenttrace.Event) (int64, error)

StageCaptureEvents writes events received from source (an edge id) to the staging table synchronously, skipping duplicates, and returns how many rows were inserted. The hub's pulse handler uses it so that a failed write fails the pulse and the edge retries; the idempotency key makes retries safe.

func StartRecording

func StartRecording(ctx context.Context, db *gorm.DB)

StartRecording is deprecated, use InitDefault instead

func WithHandler added in v2.3.0

func WithHandler(ctx context.Context, h AnalyticsHandler) context.Context

WithHandler returns a copy of ctx whose records go to h rather than to the global handler: the Record functions that take a context (RecordExchange, RecordProxyLog, RecordChatRecord, ...) look for it first. Values survive context.WithoutCancel, so analysis detached from a request still finds it. Tests use it to give each test its own recorder, so tests that record analytics can run in parallel; production installs the global handler.

func WithRequestStart

func WithRequestStart(ctx context.Context, start time.Time) context.Context

WithRequestStart records when the gateway received the request.

Types

type AnalyticsHandler

type AnalyticsHandler interface {
	// RecordChatRecord records LLM chat/proxy usage
	RecordChatRecord(ctx context.Context, record *models.LLMChatRecord)

	// RecordChatLogEntry records detailed chat log entries
	RecordChatLogEntry(ctx context.Context, log *models.LLMChatLogEntry)

	// RecordProxyLog records proxy request/response logs
	RecordProxyLog(ctx context.Context, log *models.ProxyLog)

	// RecordToolCall records tool call execution
	RecordToolCall(ctx context.Context, name string, timestamp time.Time, execTime int, toolID uint)

	// SetAsGlobalHandler sets this handler as the global analytics handler
	SetAsGlobalHandler()

	// Batch processing methods for improved performance
	RecordChatRecordsBatch(ctx context.Context, records []*models.LLMChatRecord)
	RecordProxyLogsBatch(ctx context.Context, logs []*models.ProxyLog)

	// RecordComplianceEvents records filter script compliance events
	RecordComplianceEvents(ctx context.Context, events []*models.ComplianceEvent)
}

AnalyticsHandler defines the interface for analytics implementations

func GetHandler

func GetHandler() AnalyticsHandler

GetHandler returns the current analytics handler (useful for testing)

type AppActivity

type AppActivity struct {
	AppID        uint
	LastAccessAt *time.Time
	Requests     int64
}

AppActivity is the portal overview's per-app activity summary: when the app last completed an LLM interaction and how many it made in the window.

It reads llm_chat_records, the same table the app page's token, cost and interaction charts and the budget spend are computed from, so the overview never disagrees with the app page (proxy_logs also records rejected and failed attempts, which the app page does not count). One grouped query over the caller's apps, so the overview costs one round trip however many apps there are.

type AppSpendWindow

type AppSpendWindow struct {
	AppID uint
	Start time.Time
}

AppSpendWindow names an app and the start of its budget period.

type CaptureRecorder added in v2.3.0

type CaptureRecorder interface {
	RecordCaptureEvents(ctx context.Context, events []*agenttrace.Event)
}

CaptureRecorder is implemented by handlers that stage Agent Call Tracing capture events (spec §4.1, D3): the hub's DatabaseHandler writes them to the staging table, the microgateway's handler sends them on the pulse. It is only ever called while tracing is on. Implementations must never block the request.

type ChartData

type ChartData struct {
	Labels []string  `json:"labels"`
	Data   []float64 `json:"data"`
	Cost   []float64 `json:"cost,omitempty"`
}

func GetAppInteractionsOverTime

func GetAppInteractionsOverTime(db *gorm.DB, startDate, endDate time.Time, appID uint) (*ChartData, error)

GetAppInteractionsOverTime returns the number of LLM interactions for a specific app over time

func GetChatInteractionsForChat

func GetChatInteractionsForChat(db *gorm.DB, startDate, endDate time.Time, chatID string) (*ChartData, error)

GetChatInteractionsForChat returns the number of interactions for a specific chat over time

func GetChatRecordsPerDay

func GetChatRecordsPerDay(db *gorm.DB, startDate, endDate *time.Time) (*ChartData, error)

GetChatRecordsPerDay returns the total number of chat records per day for a given time period

func GetChatRecordsPerUser

func GetChatRecordsPerUser(db *gorm.DB, startDate, endDate time.Time) (*ChartData, error)

GetChatRecordsPerUser returns the total number of chat records per user for a given time period

func GetModelUsage

func GetModelUsage(db *gorm.DB, startDate, endDate time.Time, modelName string) (*ChartData, error)

GetModelUsage returns the usage statistics for a specific model over time

func GetMostUsedLLMModels

func GetMostUsedLLMModels(db *gorm.DB, startDate, endDate time.Time, interactionType *models.InteractionType) (*ChartData, error)

GetMostUsedLLMModels returns the usage count for each LLM model

func GetTokenUsageForApp

func GetTokenUsageForApp(db *gorm.DB, startDate, endDate time.Time, appID uint) (*ChartData, error)

GetTokenUsageForApp returns the token usage for a specific app over time

func GetTokenUsagePerApp

func GetTokenUsagePerApp(db *gorm.DB, startDate, endDate time.Time, interactionType *models.InteractionType) (*ChartData, error)

GetTokenUsagePerApp returns the total token usage for each app

func GetTokenUsagePerUser

func GetTokenUsagePerUser(db *gorm.DB, startDate, endDate time.Time, interactionType *models.InteractionType) (*ChartData, error)

GetTokenUsagePerUser returns the total token usage for each user

func GetToolCallsPerDay

func GetToolCallsPerDay(db *gorm.DB, startDate, endDate time.Time) (*ChartData, error)

func GetToolUsageStatistics

func GetToolUsageStatistics(db *gorm.DB, startDate, endDate time.Time) (*ChartData, error)

GetToolUsageStatistics returns the usage count for each tool

func GetUniqueUsersPerDay

func GetUniqueUsersPerDay(db *gorm.DB, startDate, endDate time.Time) (*ChartData, error)

GetUniqueUsersPerDay returns the number of unique users per day

func GetVendorUsage

func GetVendorUsage(db *gorm.DB, startDate, endDate time.Time, vendor string, llmID *uint) (*ChartData, error)

GetVendorUsage returns the usage statistics for a specific vendor over time

type DatabaseHandler

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

DatabaseHandler implements AnalyticsHandler using the existing database/channel system

func NewDatabaseHandler

func NewDatabaseHandler(ctx context.Context, db *gorm.DB) *DatabaseHandler

NewDatabaseHandler creates a new database analytics handler

func (*DatabaseHandler) RecordCaptureEvents added in v2.3.0

func (h *DatabaseHandler) RecordCaptureEvents(_ context.Context, events []*agenttrace.Event)

RecordCaptureEvents queues capture events for staging. The queue and its flusher start on first use, so a handler that never sees tracing traffic (tracing off, Community Edition) allocates nothing for it.

func (*DatabaseHandler) RecordChatLogEntry

func (h *DatabaseHandler) RecordChatLogEntry(_ context.Context, logEntry *models.LLMChatLogEntry)

RecordChatLogEntry implements analytics.AnalyticsHandler

func (*DatabaseHandler) RecordChatRecord

func (h *DatabaseHandler) RecordChatRecord(_ context.Context, record *models.LLMChatRecord)

Implement AnalyticsHandler interface methods

func (*DatabaseHandler) RecordChatRecordsBatch

func (h *DatabaseHandler) RecordChatRecordsBatch(_ context.Context, records []*models.LLMChatRecord)

RecordChatRecordsBatch records multiple chat records asynchronously using background worker This method is non-blocking and returns immediately to avoid impacting request latency

func (*DatabaseHandler) RecordComplianceEvents

func (h *DatabaseHandler) RecordComplianceEvents(_ context.Context, events []*models.ComplianceEvent)

RecordComplianceEvents records filter script compliance events asynchronously

func (*DatabaseHandler) RecordEdgeBatch added in v2.3.0

func (h *DatabaseHandler) RecordEdgeBatch(ctx context.Context, b *EdgeBatch) (bool, error)

RecordEdgeBatch implements EdgeBatchRecorder. One transaction records the batch's key and writes its records; a key that is already there ends it with nothing written. A row the database refuses on its own (an edge value over a column's size on Postgres) is left out and logged, as the background writer does for proxy logs, so one bad record cannot keep an edge sending the same batch for a day; any other failure fails the whole batch.

func (*DatabaseHandler) RecordMCPCalls added in v2.3.0

func (h *DatabaseHandler) RecordMCPCalls(_ context.Context, records []models.MCPCallRecord) error

RecordMCPCalls queues MCP calls for the MCP writer. The writer writes the slice it is given, so the caller must not reuse it. ErrRecorderBusy means the batch was not queued (buffer full, or the handler stopped): the ingest endpoint answers 503 so the pump retries it.

func (*DatabaseHandler) RecordProxyLog

func (h *DatabaseHandler) RecordProxyLog(_ context.Context, log *models.ProxyLog)

func (*DatabaseHandler) RecordProxyLogsBatch

func (h *DatabaseHandler) RecordProxyLogsBatch(_ context.Context, logs []*models.ProxyLog)

RecordProxyLogsBatch records multiple proxy logs asynchronously using background worker This method is non-blocking and returns immediately to avoid impacting request latency

func (*DatabaseHandler) RecordToolCall

func (h *DatabaseHandler) RecordToolCall(_ context.Context, name string, timestamp time.Time, execTime int, toolID uint)

func (*DatabaseHandler) SetAsGlobalHandler

func (h *DatabaseHandler) SetAsGlobalHandler()

SetAsGlobalHandler sets this handler as the global analytics handler

func (*DatabaseHandler) Stop

func (h *DatabaseHandler) Stop()

Stop gracefully stops the database handler

type DecisionDaySeries added in v2.3.0

type DecisionDaySeries struct {
	Labels    []string  `json:"labels"`
	Requests  []int64   `json:"requests"`
	Failed    []int64   `json:"failed"`
	Questions []int64   `json:"questions"`
	Refusals  []int64   `json:"refusals"`
	Cost      []float64 `json:"cost"`
}

DecisionDaySeries is decision traffic per day, aligned on Labels (dates). Cost sums every currency; it is a trend line, not an invoice.

type DecisionModelUsage added in v2.3.0

type DecisionModelUsage struct {
	Vendor      string  `json:"vendor"`
	Model       string  `json:"model"`
	Currency    string  `json:"currency"`
	Requests    int64   `json:"requests"`
	Failed      int64   `json:"failed"`
	Questions   int64   `json:"questions"`
	Refusals    int64   `json:"refusals"`
	InputTokens int64   `json:"input_tokens"`
	Cost        float64 `json:"cost"`
	// CostPerThousand is the cost of a thousand answered decision requests
	// at this period's average, the number decision pricing is usually
	// compared on.
	CostPerThousand float64 `json:"cost_per_thousand"`
}

DecisionModelUsage is decision traffic for one vendor/model.

type DecisionTotals added in v2.3.0

type DecisionTotals struct {
	Requests       int64              `json:"requests"`
	Failed         int64              `json:"failed"`
	Questions      int64              `json:"questions"`
	Answered       int64              `json:"answered"`
	Refusals       int64              `json:"refusals"`
	InputTokens    int64              `json:"input_tokens"`
	CostByCurrency map[string]float64 `json:"cost_by_currency"`
}

DecisionTotals summarises decision-model traffic over a period. Costs are in currency units (dollars), keyed by currency. Requests are the calls the model answered; Failed are the calls that came back without answers (an upstream error such as model_not_found, a budget denial, a policy block). Questions, Answered and Refusals count answered calls only, so a failed call's questions are not read as unanswered ones.

type DecisionUsage added in v2.3.0

type DecisionUsage struct {
	Totals  DecisionTotals       `json:"totals"`
	ByDay   DecisionDaySeries    `json:"by_day"`
	ByModel []DecisionModelUsage `json:"by_model"`
}

DecisionUsage is the decision-model report for a period.

func GetDecisionUsage added in v2.3.0

func GetDecisionUsage(db *gorm.DB, startDate, endDate time.Time, llmID, appID *uint) (*DecisionUsage, error)

GetDecisionUsage reports decision-model traffic between startDate and endDate, optionally for one LLM and/or one App. Decision calls are the chat records with request_kind "decision"; their answered questions are the records' choices. A record with neither choices nor refusals is a failed call: the gateway records failed exchanges too, with the questions the request asked (responses.DecisionResponse), and the model answered none.

type EdgeBatch added in v2.3.0

type EdgeBatch struct {
	// Key identifies the batch: models.EdgeAnalyticsBatchKey.
	Key string
	// EdgeID is the edge that sent it.
	EdgeID string

	ProxyLogs        []*models.ProxyLog
	ChatRecords      []*models.LLMChatRecord
	ComplianceEvents []*models.ComplianceEvent
	ToolCalls        []*models.ToolCallRecord
}

EdgeBatch is the records of one analytics pulse from an edge, to be stored together and at most once.

An edge sends a batch again when it did not get the acknowledgement, typically because the control plane that stored it went away before answering and the edge moved to another one (features/ActiveActive.md, Phase 2). The other Record functions cannot make that safe: they queue records for a background writer and return, so nothing ties "this batch was stored" to the records. RecordEdgeBatch writes the records and the batch's key in one transaction and returns when it has committed.

func (*EdgeBatch) Records added in v2.3.0

func (b *EdgeBatch) Records() int

Records is the number of records in the batch.

type EdgeBatchRecorder added in v2.3.0

type EdgeBatchRecorder interface {
	// RecordEdgeBatch stores the batch and returns once it is committed.
	// stored is false, with no error, when a batch with this key was stored
	// before: nothing was written. An error means nothing was stored and
	// the edge should send the batch again; ErrEdgeBatchUnsupported means
	// this handler cannot store batches this way at all.
	RecordEdgeBatch(ctx context.Context, b *EdgeBatch) (stored bool, err error)
}

EdgeBatchRecorder is implemented by handlers that can store an edge's batch once. It is optional, as MCPCallRecorder is: a host's own AnalyticsHandler keeps compiling without it, and an edge's batches are then recorded as before, without de-duplication.

type ExchangeRecorder

type ExchangeRecorder interface {
	// RecordExchange records one proxied request. rec is nil when the
	// response yielded no usage (an error, or nothing to parse).
	RecordExchange(ctx context.Context, log *models.ProxyLog, rec *models.LLMChatRecord)
}

ExchangeRecorder is implemented by handlers that record a proxied request's proxy log and its chat record together. The gateway produces both for one request; a handler that stores them as one row needs them in one call rather than having to pair two separate calls up again.

type MCPAppRow added in v2.3.0

type MCPAppRow struct {
	AppID      *uint      `json:"app_id"`
	AppName    string     `json:"app_name"`
	Calls      int64      `json:"calls"`
	Errors     int64      `json:"errors"`
	ErrorRate  float64    `json:"error_rate"`
	LastSeenAt *time.Time `json:"last_seen_at"`
}

MCPAppRow is one App's use of a server. A nil AppID is the traffic no App could be attributed to.

func GetMCPAppStats added in v2.3.0

func GetMCPAppStats(db *gorm.DB, f MCPStatsFilter, page, pageSize int, search string) ([]MCPAppRow, int64, error)

GetMCPAppStats returns one page of the Apps calling a server, busiest first, with the unattributed traffic as a row of its own. search matches the App name.

type MCPCallRecorder added in v2.3.0

type MCPCallRecorder interface {
	RecordMCPCalls(ctx context.Context, records []models.MCPCallRecord) error
}

MCPCallRecorder is implemented by handlers that record MCP calls a Tyk Gateway proxied (ingested from Tyk Pump). It is optional, so a host's own AnalyticsHandler keeps compiling; a handler without it does not receive MCP calls. Unlike the AnalyticsHandler methods it reports a batch it could not take (ErrRecorderBusy), because its caller can have the sender retry.

type MCPOverview added in v2.3.0

type MCPOverview struct {
	MCPSummary
	TopTools []MCPTopTool `json:"top_tools"`
}

MCPOverview is all MCP traffic: the summary and the busiest tools.

func GetMCPOverview added in v2.3.0

func GetMCPOverview(db *gorm.DB, f MCPStatsFilter) (*MCPOverview, error)

GetMCPOverview returns the summary of all MCP traffic in the range and its busiest tools.

type MCPServerRow added in v2.3.0

type MCPServerRow struct {
	MCPServerID  uint       `json:"mcp_server_id"`
	ServerName   string     `json:"server_name"`
	ConnectionID uint       `json:"connection_id"`
	Calls        int64      `json:"calls"`
	Errors       int64      `json:"errors"`
	ErrorRate    float64    `json:"error_rate"`
	P95Ms        float64    `json:"p95_ms"`
	LastSeenAt   *time.Time `json:"last_seen_at"`
}

MCPServerRow is one server's traffic (for an App, or overall).

func GetMCPServerStats added in v2.3.0

func GetMCPServerStats(db *gorm.DB, f MCPStatsFilter) ([]MCPServerRow, error)

GetMCPServerStats returns the servers the calls f selects went to, busiest first (an App's MCP usage).

type MCPStatsFilter added in v2.3.0

type MCPStatsFilter struct {
	Start    time.Time
	End      time.Time
	ServerID *uint
	AppID    *uint
}

MCPStatsFilter selects the calls a statistic covers: Start <= timestamp < End. End is exclusive so a call in the last (sub-)second of a day is counted: Gateway timestamps carry nanoseconds. Nil ids do not filter.

type MCPSummary added in v2.3.0

type MCPSummary struct {
	Calls      int64      `json:"calls"`
	Errors     int64      `json:"errors"`
	ErrorRate  float64    `json:"error_rate"`
	AvgMs      float64    `json:"avg_ms"`
	P50Ms      float64    `json:"p50_ms"`
	P95Ms      float64    `json:"p95_ms"`
	LastSeenAt *time.Time `json:"last_seen_at"`
}

MCPSummary is the headline numbers of a set of calls.

func GetMCPSummary added in v2.3.0

func GetMCPSummary(db *gorm.DB, f MCPStatsFilter) (*MCPSummary, error)

GetMCPSummary returns the headline numbers of the calls f selects.

type MCPTimeseries added in v2.3.0

type MCPTimeseries struct {
	Interval string               `json:"interval"`
	Points   []MCPTimeseriesPoint `json:"points"`
}

MCPTimeseries is calls and errors over time.

func GetMCPTimeseries added in v2.3.0

func GetMCPTimeseries(db *gorm.DB, f MCPStatsFilter, interval string) (*MCPTimeseries, error)

GetMCPTimeseries returns calls, errors and latency per bucket ("hour" or "day"). Only buckets with calls are returned.

type MCPTimeseriesPoint added in v2.3.0

type MCPTimeseriesPoint struct {
	Bucket time.Time `json:"bucket"`
	Calls  int64     `json:"calls"`
	Errors int64     `json:"errors"`
	P50Ms  float64   `json:"p50_ms"`
	P95Ms  float64   `json:"p95_ms"`
}

MCPTimeseriesPoint is one bucket of a time series.

type MCPToolRow added in v2.3.0

type MCPToolRow struct {
	PrimitiveType string     `json:"primitive_type"`
	PrimitiveName string     `json:"primitive_name"`
	Calls         int64      `json:"calls"`
	Errors        int64      `json:"errors"`
	ErrorRate     float64    `json:"error_rate"`
	AvgMs         float64    `json:"avg_ms"`
	P50Ms         float64    `json:"p50_ms"`
	P95Ms         float64    `json:"p95_ms"`
	LastSeenAt    *time.Time `json:"last_seen_at"`
}

MCPToolRow is one tool (or resource, prompt...) of a server.

func GetMCPToolStats added in v2.3.0

func GetMCPToolStats(db *gorm.DB, f MCPStatsFilter, page, pageSize int, search string) ([]MCPToolRow, int64, error)

GetMCPToolStats returns one page of a server's tools (every primitive: tools, resources, prompts, discovery), busiest first. search matches the primitive name.

type MCPTopTool added in v2.3.0

type MCPTopTool struct {
	MCPServerID   uint    `json:"mcp_server_id"`
	ServerName    string  `json:"server_name"`
	PrimitiveType string  `json:"primitive_type"`
	PrimitiveName string  `json:"primitive_name"`
	Calls         int64   `json:"calls"`
	Errors        int64   `json:"errors"`
	ErrorRate     float64 `json:"error_rate"`
}

MCPTopTool is a tool in the overview's busiest list.

type ModelAppUsage

type ModelAppUsage struct {
	AppID        uint     `json:"appId"`
	AppName      string   `json:"appName"`
	AppDeleted   bool     `json:"appDeleted"`
	OwnerUserID  uint     `json:"ownerUserId"`
	OwnerEmail   string   `json:"ownerEmail"`
	RequestCount int64    `json:"requestCount"`
	TotalTokens  int64    `json:"totalTokens"`
	TotalCost    float64  `json:"totalCost"`
	FirstUsed    ScanTime `json:"firstUsed"`
	LastUsed     ScanTime `json:"lastUsed"`
}

ModelAppUsage is one app's usage of a specific model under a specific LLM entry. It answers "who is using model X?" with enough detail to contact the app owner.

func GetAppsForModel

func GetAppsForModel(db *gorm.DB, startDate, endDate time.Time, llmID uint, modelName string, interactionType *models.InteractionType) ([]ModelAppUsage, error)

GetAppsForModel returns every app that called the given model through the given LLM entry within the date range, most recently used first. The LLM scope matters: the same model name can sit under two LLM entries (two keys for the same vendor), and the question is asked from one provider's page. Soft-deleted apps are still returned so historical usage stays attributable; they are flagged rather than hidden.

type ScanTime

type ScanTime struct {
	time.Time
}

ScanTime is a time.Time that can be scanned from an aggregated datetime column such as MAX(time_stamp). An aggregate result column has no declared type, so the SQLite driver hands back the raw TEXT instead of a time.Time (Postgres keeps the timestamp type). Scanning such a column straight into a time.Time fails on SQLite with "unsupported Scan, storing driver.Value type string into type *time.Time"; this type accepts all three representations.

func (*ScanTime) Scan

func (s *ScanTime) Scan(value interface{}) error

Scan implements sql.Scanner.

func (ScanTime) Value

func (s ScanTime) Value() (driver.Value, error)

Value implements driver.Valuer so GORM treats the type as a plain column.

type ServiceTierModelUsage added in v2.3.0

type ServiceTierModelUsage struct {
	ServiceTier    string  `json:"service_tier"`
	Vendor         string  `json:"vendor"`
	Model          string  `json:"model"`
	Currency       string  `json:"currency"`
	Requests       int64   `json:"requests"`
	PromptTokens   int64   `json:"prompt_tokens"`
	ResponseTokens int64   `json:"response_tokens"`
	TotalTokens    int64   `json:"total_tokens"`
	Cost           float64 `json:"cost"`
}

ServiceTierModelUsage is one vendor/model's traffic at one service tier. Cost is in currency units, already at the tier's price.

type ServiceTierTotals added in v2.3.0

type ServiceTierTotals struct {
	ServiceTier    string             `json:"service_tier"`
	Requests       int64              `json:"requests"`
	TotalTokens    int64              `json:"total_tokens"`
	CostByCurrency map[string]float64 `json:"cost_by_currency"`
}

ServiceTierTotals sums one service tier over every model. Costs are keyed by currency.

type ServiceTierUsage added in v2.3.0

type ServiceTierUsage struct {
	ByTier  []ServiceTierTotals     `json:"by_tier"`
	ByModel []ServiceTierModelUsage `json:"by_model"`
}

ServiceTierUsage breaks spend down by vendor service tier (batch, priority, flex...).

func GetServiceTierUsage added in v2.3.0

func GetServiceTierUsage(db *gorm.DB, startDate, endDate time.Time, llmID, appID *uint, tier *string) (*ServiceTierUsage, error)

GetServiceTierUsage reports chat-record traffic between startDate and endDate per service tier and model, optionally for one LLM, one App and one tier (ServiceTierNone for records without one). Edge traffic is included: the pulse carries the tier.

type Tee

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

Tee sends every record to a primary handler (Studio's database handler: budgets and spend are computed from it) and to extra sinks, for a host that ships analytics into its own pipeline. Sinks never slow a request: each has a bounded queue drained by its own goroutine, and records that do not fit are dropped and counted. Sinks receive copies, so they never share a record with the primary handler (which writes IDs back into it).

func NewTee

func NewTee(primary AnalyticsHandler, sinks ...AnalyticsHandler) *Tee

NewTee returns a Tee over primary and sinks. Stop it to drain the sinks.

func (*Tee) Dropped

func (t *Tee) Dropped() []uint64

Dropped reports, per sink, how many records did not fit its queue.

func (*Tee) RecordCaptureEvents added in v2.3.0

func (t *Tee) RecordCaptureEvents(ctx context.Context, events []*agenttrace.Event)

RecordCaptureEvents forwards agent tracing capture events to the primary and to the sinks that stage them. Sinks get copies: the primary may strip payloads from its events under queue pressure.

Only trusted handlers may implement CaptureRecorder: the hub's database handler, or an embedding host's own sink (hosts are already trusted with proxy logs, and EncodeStaged/ProcessContent mean a sink only ever sees processed, redacted content). A plugin or data-collector sink must never implement it, or capture content would reach plugins.

func (*Tee) RecordChatLogEntry

func (t *Tee) RecordChatLogEntry(ctx context.Context, log *models.LLMChatLogEntry)

func (*Tee) RecordChatRecord

func (t *Tee) RecordChatRecord(ctx context.Context, record *models.LLMChatRecord)

func (*Tee) RecordChatRecordsBatch

func (t *Tee) RecordChatRecordsBatch(ctx context.Context, records []*models.LLMChatRecord)

func (*Tee) RecordComplianceEvents

func (t *Tee) RecordComplianceEvents(ctx context.Context, events []*models.ComplianceEvent)

func (*Tee) RecordEdgeBatch added in v2.3.0

func (t *Tee) RecordEdgeBatch(ctx context.Context, b *EdgeBatch) (bool, error)

RecordEdgeBatch implements EdgeBatchRecorder: the primary stores the batch once, and the sinks get copies of its records only when it was stored, so they do not see a repeated batch either.

func (*Tee) RecordExchange

func (t *Tee) RecordExchange(ctx context.Context, log *models.ProxyLog, rec *models.LLMChatRecord)

RecordExchange keeps a proxied request's log and chat record together for handlers that store them as one (ExchangeRecorder) and splits them for the others, as the package-level RecordExchange does.

func (*Tee) RecordMCPCalls added in v2.3.0

func (t *Tee) RecordMCPCalls(ctx context.Context, records []models.MCPCallRecord) error

func (*Tee) RecordProxyLog

func (t *Tee) RecordProxyLog(ctx context.Context, log *models.ProxyLog)

func (*Tee) RecordProxyLogsBatch

func (t *Tee) RecordProxyLogsBatch(ctx context.Context, logs []*models.ProxyLog)

func (*Tee) RecordToolCall

func (t *Tee) RecordToolCall(ctx context.Context, name string, timestamp time.Time, execTime int, toolID uint)

func (*Tee) SetAsGlobalHandler

func (t *Tee) SetAsGlobalHandler()

SetAsGlobalHandler makes the Tee the process's analytics handler.

func (*Tee) Stop

func (t *Tee) Stop(timeout time.Duration)

Stop waits up to timeout for the sinks to take what is queued. Records sent after Stop are lost to the sinks (the primary still gets them).

type VendorModelCost

type VendorModelCost struct {
	Model            string  `json:"model"`
	ModelPriceID     *uint   `json:"modelPriceId"`
	TotalCost        float64 `json:"totalCost"`
	PromptCost       float64 `json:"promptCost"`
	ResponseCost     float64 `json:"responseCost"`
	CacheWriteCost   float64 `json:"cacheWriteCost"`
	CacheReadCost    float64 `json:"cacheReadCost"`
	TotalTokens      int64   `json:"totalTokens"` // Total of all token types
	PromptTokens     int64   `json:"promptTokens"`
	ResponseTokens   int64   `json:"responseTokens"`
	CacheWriteTokens int64   `json:"cacheWriteTokens"`
	CacheReadTokens  int64   `json:"cacheReadTokens"`
	// Usage columns backing the "Models in use" view on the LLM details page.
	RequestCount int64    `json:"requestCount"`
	AppCount     int64    `json:"appCount"`
	LastUsed     ScanTime `json:"lastUsed"`
}

VendorModelCost represents the total cost for a specific vendor and model

func GetTotalCostPerVendorAndModel

func GetTotalCostPerVendorAndModel(db *gorm.DB, startDate, endDate time.Time, interactionType *models.InteractionType, llmID *uint) ([]VendorModelCost, error)

GetTotalCostPerVendorAndModel returns the total cost per vendor and model with detailed breakdowns

Jump to

Keyboard shortcuts

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