Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: add endpoint for fetching unpriced models (#11763)

Nityananda Gohain84834b087b10
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index fd8d08398e..faac87f230 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -5224,6 +5224,16 @@ components:
- offset
- limit
type: object
+ LlmpricingruletypesGettableUnmappedModels:
+ properties:
+ items:
+ items:
+ $ref: '#/components/schemas/LlmpricingruletypesUnmappedModel'
+ nullable: true
+ type: array
+ required:
+ - items
+ type: object
LlmpricingruletypesLLMPricingCacheCosts:
properties:
mode:
@@ -5313,6 +5323,19 @@ components:
type: string
nullable: true
type: array
+ LlmpricingruletypesUnmappedModel:
+ properties:
+ modelName:
+ type: string
+ provider:
+ type: string
+ spanCount:
+ minimum: 0
+ type: integer
+ required:
+ - modelName
+ - spanCount
+ type: object
LlmpricingruletypesUpdatableLLMPricingRule:
properties:
enabled:
@@ -11190,6 +11213,60 @@ paths:
summary: Get a pricing rule
tags:
- llmpricingrules
+ /api/v1/llm_pricing_rules/unmapped_models:
+ get:
+ deprecated: false
+ description: Returns models seen in the last hour of trace data (gen_ai.request.model)
+ that no pricing rule pattern matches, so the user can add them to an existing
+ rule or create a new one.
+ operationId: ListUnmappedLLMModels
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/LlmpricingruletypesGettableUnmappedModels'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Bad Request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - VIEWER
+ - tokenizer:
+ - VIEWER
+ summary: List unmapped models
+ tags:
+ - llmpricingrules
/api/v1/logs/promote_paths:
get:
deprecated: false
diff --git a/frontend/src/api/generated/services/llmpricingrules/index.ts b/frontend/src/api/generated/services/llmpricingrules/index.ts
index 0f2f5a21f1..bd83171c3f 100644
--- a/frontend/src/api/generated/services/llmpricingrules/index.ts
+++ b/frontend/src/api/generated/services/llmpricingrules/index.ts
@@ -23,6 +23,7 @@ import type {
GetLLMPricingRulePathParameters,
ListLLMPricingRules200,
ListLLMPricingRulesParams,
+ ListUnmappedLLMModels200,
LlmpricingruletypesUpdatableLLMPricingRulesDTO,
RenderErrorResponseDTO,
} from '../sigNoz.schemas';
@@ -393,3 +394,87 @@ export const invalidateGetLLMPricingRule = async (
return queryClient;
};
+
+/**
+ * Returns models seen in the last hour of trace data (gen_ai.request.model) that no pricing rule pattern matches, so the user can add them to an existing rule or create a new one.
+ * @summary List unmapped models
+ */
+export const listUnmappedLLMModels = (signal?: AbortSignal) => {
+ return GeneratedAPIInstance<ListUnmappedLLMModels200>({
+ url: `/api/v1/llm_pricing_rules/unmapped_models`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getListUnmappedLLMModelsQueryKey = () => {
+ return [`/api/v1/llm_pricing_rules/unmapped_models`] as const;
+};
+
+export const getListUnmappedLLMModelsQueryOptions = <
+ TData = Awaited<ReturnType<typeof listUnmappedLLMModels>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof listUnmappedLLMModels>>,
+ TError,
+ TData
+ >;
+}) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey = queryOptions?.queryKey ?? getListUnmappedLLMModelsQueryKey();
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof listUnmappedLLMModels>>
+ > = ({ signal }) => listUnmappedLLMModels(signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof listUnmappedLLMModels>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type ListUnmappedLLMModelsQueryResult = NonNullable<
+ Awaited<ReturnType<typeof listUnmappedLLMModels>>
+>;
+export type ListUnmappedLLMModelsQueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary List unmapped models
+ */
+
+export function useListUnmappedLLMModels<
+ TData = Awaited<ReturnType<typeof listUnmappedLLMModels>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof listUnmappedLLMModels>>,
+ TError,
+ TData
+ >;
+}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getListUnmappedLLMModelsQueryOptions(options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ return { ...query, queryKey: queryOptions.queryKey };
+}
+
+/**
+ * @summary List unmapped models
+ */
+export const invalidateListUnmappedLLMModels = async (
+ queryClient: QueryClient,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getListUnmappedLLMModelsQueryKey() },
+ options,
+ );
+
+ return queryClient;
+};
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index f470eb71cc..e80ee3836b 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -6818,6 +6818,29 @@ export interface LlmpricingruletypesGettablePricingRulesDTO {
total: number;
}
+export interface LlmpricingruletypesUnmappedModelDTO {
+ /**
+ * @type string
+ */
+ modelName: string;
+ /**
+ * @type string
+ */
+ provider?: string;
+ /**
+ * @type integer
+ * @minimum 0
+ */
+ spanCount: number;
+}
+
+export interface LlmpricingruletypesGettableUnmappedModelsDTO {
+ /**
+ * @type array,null
+ */
+ items: LlmpricingruletypesUnmappedModelDTO[] | null;
+}
+
export interface LlmpricingruletypesUpdatableLLMPricingRuleDTO {
/**
* @type boolean
@@ -10168,6 +10191,14 @@ export type GetLLMPricingRule200 = {
status: string;
};
+export type ListUnmappedLLMModels200 = {
+ data: LlmpricingruletypesGettableUnmappedModelsDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type ListPromotedAndIndexedPaths200 = {
/**
* @type array,null
diff --git a/pkg/apiserver/signozapiserver/llmpricingrule.go b/pkg/apiserver/signozapiserver/llmpricingrule.go
index 2bddaa93fb..007928b5f3 100644
--- a/pkg/apiserver/signozapiserver/llmpricingrule.go
+++ b/pkg/apiserver/signozapiserver/llmpricingrule.go
@@ -49,6 +49,26 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
return err
}
+ if err := router.Handle("/api/v1/llm_pricing_rules/unmapped_models", handler.New(
+ provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.ListUnmappedModels),
+ handler.OpenAPIDef{
+ ID: "ListUnmappedLLMModels",
+ Tags: []string{"llmpricingrules"},
+ Summary: "List unmapped models",
+ Description: "Returns models seen in the last hour of trace data (gen_ai.request.model) that no pricing rule pattern matches, so the user can add them to an existing rule or create a new one.",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(llmpricingruletypes.GettableUnmappedModels),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),
+ },
+ )).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
if err := router.Handle("/api/v1/llm_pricing_rules/{id}", handler.New(
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.Get),
handler.OpenAPIDef{
diff --git a/pkg/modules/llmpricingrule/impllmpricingrule/handler.go b/pkg/modules/llmpricingrule/impllmpricingrule/handler.go
index 0ac39e2e37..8cf9e0bc69 100644
--- a/pkg/modules/llmpricingrule/impllmpricingrule/handler.go
+++ b/pkg/modules/llmpricingrule/impllmpricingrule/handler.go
@@ -92,7 +92,7 @@ func (h *handler) Get(rw http.ResponseWriter, r *http.Request) {
}
func (h *handler) CreateOrUpdate(rw http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
claims, err := authtypes.ClaimsFromContext(ctx)
@@ -118,6 +118,28 @@ func (h *handler) CreateOrUpdate(rw http.ResponseWriter, r *http.Request) {
render.Success(rw, http.StatusNoContent, nil)
}
+// ListUnmappedModels handles GET /api/v1/llm_pricing_rules/unmapped_models.
+func (h *handler) ListUnmappedModels(rw http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
+ defer cancel()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgID := valuer.MustNewUUID(claims.OrgID)
+
+ models, err := h.module.ListUnmappedModels(ctx, orgID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, llmpricingruletypes.NewGettableUnmappedModels(models))
+}
+
// Delete handles DELETE /api/v1/llm_pricing_rules/{id}.
func (h *handler) Delete(rw http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
diff --git a/pkg/modules/llmpricingrule/impllmpricingrule/module.go b/pkg/modules/llmpricingrule/impllmpricingrule/module.go
index 83c00e59e7..d7be584caf 100644
--- a/pkg/modules/llmpricingrule/impllmpricingrule/module.go
+++ b/pkg/modules/llmpricingrule/impllmpricingrule/module.go
@@ -3,24 +3,32 @@ package impllmpricingrule
import (
"context"
"encoding/json"
+ "fmt"
"time"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/modules/llmpricingrule"
+ "github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/query-service/agentConf"
"github.com/SigNoz/signoz/pkg/types/featuretypes"
"github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"
"github.com/SigNoz/signoz/pkg/types/opamptypes"
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
+// unmappedModelsLookback is the trace data window scanned to discover models in use.
+const unmappedModelsLookback = time.Hour
+
type module struct {
store llmpricingruletypes.Store
+ querier querier.Querier
flagger flagger.Flagger
}
-func NewModule(store llmpricingruletypes.Store, flagger flagger.Flagger) llmpricingrule.Module {
+func NewModule(store llmpricingruletypes.Store, flagger flagger.Flagger, querier querier.Querier) llmpricingrule.Module {
return &module{store: store, flagger: flagger}
}
@@ -32,6 +40,28 @@ func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID
return module.store.Get(ctx, orgID, id)
}
+// ListUnmappedModels discovers the models present in the last hour of trace data
+// (gen_ai.request.model) and returns the ones that no pricing rule pattern matches.
+func (module *module) ListUnmappedModels(ctx context.Context, orgID valuer.UUID) ([]*llmpricingruletypes.UnmappedModel, error) {
+ models, err := module.discoverModels(ctx, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ rules, err := module.listAllRules(ctx, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ unmapped := make([]*llmpricingruletypes.UnmappedModel, 0, len(models))
+ for _, m := range models {
+ if !llmpricingruletypes.ModelMatchesAnyRule(m.ModelName, rules) {
+ unmapped = append(unmapped, m)
+ }
+ }
+ return unmapped, nil
+}
+
// CreateOrUpdate applies a batch of pricing rule changes:
// - ID set → match by id, overwrite fields.
// - SourceID set → match by source_id; if found overwrite, else insert.
@@ -121,7 +151,7 @@ func (module *module) RecommendAgentConfig(orgID valuer.UUID, currentConfYaml []
}
func (module *module) getEnabledRules(ctx context.Context, orgID valuer.UUID) ([]*llmpricingruletypes.LLMPricingRule, error) {
- rules, _, err := module.List(ctx, orgID, 0, 10000, "", nil)
+ rules, err := module.listAllRules(ctx, orgID)
if err != nil {
return nil, err
}
@@ -135,6 +165,25 @@ func (module *module) getEnabledRules(ctx context.Context, orgID valuer.UUID) ([
return enabled, nil
}
+// listAllRules pages through every pricing rule for the org, since rule matching
+// needs the full set and the count is otherwise unbounded.
+func (module *module) listAllRules(ctx context.Context, orgID valuer.UUID) ([]*llmpricingruletypes.LLMPricingRule, error) {
+ const pageSize = 1000
+
+ all := make([]*llmpricingruletypes.LLMPricingRule, 0)
+ for offset := 0; ; offset += pageSize {
+ page, total, err := module.store.List(ctx, orgID, offset, pageSize, "", nil)
+ if err != nil {
+ return nil, err
+ }
+ all = append(all, page...)
+ if len(page) == 0 || len(all) >= total {
+ break
+ }
+ }
+ return all, nil
+}
+
// findExisting returns the row matching the updatable's ID or SourceID.
// Returns a TypeNotFound error when neither matches; the caller treats that
// as "insert new".
@@ -148,3 +197,91 @@ func (module *module) findExisting(ctx context.Context, orgID valuer.UUID, u *ll
return nil, errors.Newf(errors.TypeNotFound, llmpricingruletypes.ErrCodePricingRuleNotFound, "rule has neither id nor sourceId")
}
}
+
+// discoverModels runs a QBv5 traces aggregation grouped by gen_ai.request.model
+// over the lookback window and returns each distinct model with its span count.
+func (module *module) discoverModels(ctx context.Context, orgID valuer.UUID) ([]*llmpricingruletypes.UnmappedModel, error) {
+ now := time.Now()
+ req := &qbtypes.QueryRangeRequest{
+ Start: uint64(now.Add(-unmappedModelsLookback).UnixMilli()),
+ End: uint64(now.UnixMilli()),
+ RequestType: qbtypes.RequestTypeScalar,
+ CompositeQuery: qbtypes.CompositeQuery{
+ Queries: []qbtypes.QueryEnvelope{
+ {
+ Type: qbtypes.QueryTypeBuilder,
+ Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
+ Name: "A",
+ Signal: telemetrytypes.SignalTraces,
+ Filter: &qbtypes.Filter{Expression: fmt.Sprintf("%s EXISTS", llmpricingruletypes.GenAIRequestModel)},
+ Aggregations: []qbtypes.TraceAggregation{
+ {Expression: "count()", Alias: "spanCount"},
+ },
+ GroupBy: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
+ Name: llmpricingruletypes.GenAIRequestModel,
+ FieldContext: telemetrytypes.FieldContextSpan,
+ FieldDataType: telemetrytypes.FieldDataTypeString,
+ }},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
+ Name: llmpricingruletypes.GenAIProviderName,
+ FieldContext: telemetrytypes.FieldContextSpan,
+ FieldDataType: telemetrytypes.FieldDataTypeString,
+ }},
+ },
+ Limit: 1000,
+ },
+ },
+ },
+ },
+ }
+
+ resp, err := module.querier.QueryRange(ctx, orgID, req)
+ if err != nil {
+ return nil, err
+ }
+
+ if resp == nil || len(resp.Data.Results) == 0 {
+ return nil, nil
+ }
+ sd, ok := resp.Data.Results[0].(*qbtypes.ScalarData)
+ if !ok || sd == nil {
+ return nil, nil
+ }
+
+ modelIdx, providerIdx, countIdx := -1, -1, -1
+ for i, c := range sd.Columns {
+ switch c.Type {
+ case qbtypes.ColumnTypeGroup:
+ switch c.Name {
+ case llmpricingruletypes.GenAIRequestModel:
+ modelIdx = i
+ case llmpricingruletypes.GenAIProviderName:
+ providerIdx = i
+ }
+ case qbtypes.ColumnTypeAggregation:
+ countIdx = i
+ }
+ }
+ if modelIdx == -1 {
+ return nil, nil
+ }
+
+ models := make([]*llmpricingruletypes.UnmappedModel, 0, len(sd.Data))
+ for _, row := range sd.Data {
+ name, _ := row[modelIdx].(string)
+ if name == "" {
+ continue
+ }
+ provider := ""
+ if providerIdx != -1 {
+ provider, _ = row[providerIdx].(string)
+ }
+ var spanCount uint64
+ if countIdx >= 0 && countIdx < len(row) {
+ spanCount, _ = row[countIdx].(uint64)
+ }
+ models = append(models, &llmpricingruletypes.UnmappedModel{ModelName: name, Provider: provider, SpanCount: spanCount})
+ }
+ return models, nil
+}
diff --git a/pkg/modules/llmpricingrule/llmpricingrule.go b/pkg/modules/llmpricingrule/llmpricingrule.go
index 545c2f88c0..a9ae768a4a 100644
--- a/pkg/modules/llmpricingrule/llmpricingrule.go
+++ b/pkg/modules/llmpricingrule/llmpricingrule.go
@@ -17,6 +17,7 @@ type Module interface {
Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*llmpricingruletypes.LLMPricingRule, error)
CreateOrUpdate(ctx context.Context, orgID valuer.UUID, userEmail string, rules []*llmpricingruletypes.UpdatableLLMPricingRule) (err error)
Delete(ctx context.Context, orgID, id valuer.UUID) error
+ ListUnmappedModels(ctx context.Context, orgID valuer.UUID) ([]*llmpricingruletypes.UnmappedModel, error)
}
// Handler defines the HTTP handler interface for pricing rule endpoints.
@@ -25,4 +26,5 @@ type Handler interface {
Get(rw http.ResponseWriter, r *http.Request)
CreateOrUpdate(rw http.ResponseWriter, r *http.Request)
Delete(rw http.ResponseWriter, r *http.Request)
+ ListUnmappedModels(rw http.ResponseWriter, r *http.Request)
}
diff --git a/pkg/signoz/module.go b/pkg/signoz/module.go
index ade78358fc..072dfd03ff 100644
--- a/pkg/signoz/module.go
+++ b/pkg/signoz/module.go
@@ -160,7 +160,7 @@ func NewModules(
CloudIntegration: cloudIntegrationModule,
TraceDetail: impltracedetail.NewModule(impltracedetail.NewTraceStore(telemetryStore), providerSettings, config.TraceDetail),
SpanMapper: implspanmapper.NewModule(implspanmapper.NewStore(sqlstore), fl),
- LLMPricingRule: impllmpricingrule.NewModule(impllmpricingrule.NewStore(sqlstore), fl),
+ LLMPricingRule: impllmpricingrule.NewModule(impllmpricingrule.NewStore(sqlstore), fl, querier),
Tag: tagModule,
}
}
diff --git a/pkg/types/llmpricingruletypes/pricing.go b/pkg/types/llmpricingruletypes/pricing.go
index d3f8637995..951ae5a9c3 100644
--- a/pkg/types/llmpricingruletypes/pricing.go
+++ b/pkg/types/llmpricingruletypes/pricing.go
@@ -3,6 +3,7 @@ package llmpricingruletypes
import (
"database/sql/driver"
"encoding/json"
+ "path"
"time"
"github.com/SigNoz/signoz/pkg/errors"
@@ -16,6 +17,7 @@ const (
LLMCostFeatureType agentConf.AgentFeatureType = "llm_pricing"
GenAIRequestModel = "gen_ai.request.model"
+ GenAIProviderName = "gen_ai.provider.name"
GenAIUsageInputTokens = "gen_ai.usage.input_tokens"
GenAIUsageOutputTokens = "gen_ai.usage.output_tokens"
GenAIUsageCacheReadInputTokens = "gen_ai.usage.cache_read.input_tokens"
@@ -139,6 +141,17 @@ type GettablePricingRules struct {
Limit int `json:"limit" required:"true"`
}
+// Models deleted from spans which doesn't have a corresponding pricing entry.
+type UnmappedModel struct {
+ ModelName string `json:"modelName" required:"true"`
+ Provider string `json:"provider"`
+ SpanCount uint64 `json:"spanCount" required:"true"`
+}
+
+type GettableUnmappedModels struct {
+ Items []*UnmappedModel `json:"items" required:"true"`
+}
+
func (LLMPricingRuleUnit) Enum() []any {
return []any{UnitPerMillionTokens}
}
@@ -207,6 +220,12 @@ func NewGettableLLMPricingRulesFromLLMPricingRules(items []*LLMPricingRule, tota
}
}
+func NewGettableUnmappedModels(items []*UnmappedModel) *GettableUnmappedModels {
+ return &GettableUnmappedModels{
+ Items: items,
+ }
+}
+
func NewLLMPricingRuleFromUpdatable(u *UpdatableLLMPricingRule, orgID valuer.UUID, userEmail string, now time.Time) *LLMPricingRule {
isOverride := true
if u.IsOverride != nil {
@@ -251,3 +270,14 @@ func (r *LLMPricingRule) Update(u *UpdatableLLMPricingRule, userEmail string, no
r.UpdatedAt = now
r.UpdatedBy = userEmail
}
+
+func ModelMatchesAnyRule(model string, rules []*LLMPricingRule) bool {
+ for _, r := range rules {
+ for _, pattern := range r.ModelPattern {
+ if ok, err := path.Match(pattern, model); err == nil && ok {
+ return true
+ }
+ }
+ }
+ return false
+}