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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(llmpricing): implement store and module and integrate with opamp (#11089)
Nityananda Gohain3c1fba3a07ab
diff --git a/ee/query-service/app/server.go b/ee/query-service/app/server.goindex 006c883add..1b816c47ef 100644--- a/ee/query-service/app/server.go+++ b/ee/query-service/app/server.go@@ -114,7 +114,7 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {// initiate agent config handleragentConfMgr, err := agentConf.Initiate(&agentConf.ManagerOptions{Store: signoz.SQLStore,- AgentFeatures: []agentConf.AgentFeature{logParsingPipelineController},+ AgentFeatures: []agentConf.AgentFeature{logParsingPipelineController, signoz.Modules.LLMPricingRule},})if err != nil {return nil, errdiff --git a/pkg/modules/llmpricingrule/impllmpricingrule/handler.go b/pkg/modules/llmpricingrule/impllmpricingrule/handler.goindex 13a4b8fa19..7d7e13d786 100644--- a/pkg/modules/llmpricingrule/impllmpricingrule/handler.go+++ b/pkg/modules/llmpricingrule/impllmpricingrule/handler.go@@ -6,7 +6,6 @@ import ("time""github.com/SigNoz/signoz/pkg/errors"- "github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/http/binding""github.com/SigNoz/signoz/pkg/http/render""github.com/SigNoz/signoz/pkg/modules/llmpricingrule"@@ -19,12 +18,11 @@ import (const maxLimit = 100type handler struct {- module llmpricingrule.Module- providerSettings factory.ProviderSettings+ module llmpricingrule.Module}-func NewHandler(module llmpricingrule.Module, providerSettings factory.ProviderSettings) llmpricingrule.Handler {- return &handler{module: module, providerSettings: providerSettings}+func NewHandler(module llmpricingrule.Module) llmpricingrule.Handler {+ return &handler{module: module}}// List handles GET /api/v1/llm_pricing_rules.diff --git a/pkg/modules/llmpricingrule/impllmpricingrule/module.go b/pkg/modules/llmpricingrule/impllmpricingrule/module.gonew file mode 100644index 0000000000..b5afa42c57--- /dev/null+++ b/pkg/modules/llmpricingrule/impllmpricingrule/module.go@@ -0,0 +1,137 @@+package impllmpricingrule++import (+ "context"+ "encoding/json"+ "time"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/modules/llmpricingrule"+ "github.com/SigNoz/signoz/pkg/query-service/agentConf"+ "github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"+ "github.com/SigNoz/signoz/pkg/types/opamptypes"+ "github.com/SigNoz/signoz/pkg/valuer"+)++type module struct {+ store llmpricingruletypes.Store+}++func NewModule(store llmpricingruletypes.Store) llmpricingrule.Module {+ return &module{store: store}+}++func (module *module) List(ctx context.Context, orgID valuer.UUID, offset, limit int) ([]*llmpricingruletypes.LLMPricingRule, int, error) {+ return module.store.List(ctx, orgID, offset, limit)+}++func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*llmpricingruletypes.LLMPricingRule, error) {+ return module.store.Get(ctx, orgID, id)+}++// 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.+// - neither set → insert a new user-created row (is_override = true).+//+// When UpdatableLLMPricingRule.IsOverride is nil AND the matched row has+// is_override = true, the row is fully preserved — only synced_at is stamped.+func (module *module) CreateOrUpdate(ctx context.Context, orgID valuer.UUID, userEmail string, rules []*llmpricingruletypes.UpdatableLLMPricingRule) error {+ now := time.Now()++ upsert := func(ctx context.Context, u *llmpricingruletypes.UpdatableLLMPricingRule) error {+ if u == nil {+ return errors.Newf(errors.TypeInvalidInput, llmpricingruletypes.ErrCodePricingRuleInvalidInput, "rule entry is null")+ }+ existing, err := module.findExisting(ctx, orgID, u)+ if err != nil && errors.Ast(err, errors.TypeNotFound) {+ return module.store.Create(ctx, llmpricingruletypes.NewLLMPricingRuleFromUpdatable(u, orgID, userEmail, now))+ }+ if err != nil {+ return err+ }+ existing.Update(u, userEmail, now)+ return module.store.Update(ctx, existing)+ }++ err := module.store.RunInTx(ctx, func(ctx context.Context) error {+ for _, u := range rules {+ if err := upsert(ctx, u); err != nil {+ return err+ }+ }+ return nil+ })+ if err != nil {+ return err+ }++ agentConf.NotifyConfigUpdate(ctx)+ return nil+}++func (module *module) Delete(ctx context.Context, orgID, id valuer.UUID) error {+ if err := module.store.Delete(ctx, orgID, id); err != nil {+ return err+ }++ agentConf.NotifyConfigUpdate(ctx)++ return nil+}++func (module *module) AgentFeatureType() agentConf.AgentFeatureType {+ return llmpricingruletypes.LLMCostFeatureType+}++// RecommendAgentConfig reads pricing rules and generates the+// signozllmpricing processor config for deployment to OTel collectors via OpAMP.+func (module *module) RecommendAgentConfig(orgID valuer.UUID, currentConfYaml []byte, configVersion *opamptypes.AgentConfigVersion) ([]byte, string, error) {+ ctx := context.Background()++ rules, err := module.getEnabledRules(ctx, orgID)+ if err != nil {+ return nil, "", err+ }++ updatedConf, err := llmpricingruletypes.GenerateCollectorConfigWithLLMPricingProcessor(currentConfYaml, rules)+ if err != nil {+ return nil, "", err+ }++ serialized, err := json.Marshal(rules)+ if err != nil {+ return nil, "", err+ }++ return updatedConf, string(serialized), nil+}++func (module *module) getEnabledRules(ctx context.Context, orgID valuer.UUID) ([]*llmpricingruletypes.LLMPricingRule, error) {+ rules, _, err := module.List(ctx, orgID, 0, 10000)+ if err != nil {+ return nil, err+ }++ enabled := make([]*llmpricingruletypes.LLMPricingRule, 0, len(rules))+ for _, r := range rules {+ if r.Enabled {+ enabled = append(enabled, r)+ }+ }+ return enabled, 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".+func (module *module) findExisting(ctx context.Context, orgID valuer.UUID, u *llmpricingruletypes.UpdatableLLMPricingRule) (*llmpricingruletypes.LLMPricingRule, error) {+ switch {+ case u.ID != nil:+ return module.store.Get(ctx, orgID, *u.ID)+ case u.SourceID != nil:+ return module.store.GetBySourceID(ctx, orgID, *u.SourceID)+ default:+ return nil, errors.Newf(errors.TypeNotFound, llmpricingruletypes.ErrCodePricingRuleNotFound, "rule has neither id nor sourceId")+ }+}diff --git a/pkg/modules/llmpricingrule/impllmpricingrule/store.go b/pkg/modules/llmpricingrule/impllmpricingrule/store.gonew file mode 100644index 0000000000..9c0cb5b014--- /dev/null+++ b/pkg/modules/llmpricingrule/impllmpricingrule/store.go@@ -0,0 +1,134 @@+package impllmpricingrule++import (+ "context"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/sqlstore"+ "github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"+ "github.com/SigNoz/signoz/pkg/valuer"+)++type store struct {+ sqlstore sqlstore.SQLStore+}++func NewStore(sqlstore sqlstore.SQLStore) llmpricingruletypes.Store {+ return &store{sqlstore: sqlstore}+}++func (store *store) List(ctx context.Context, orgID valuer.UUID, offset, limit int) ([]*llmpricingruletypes.LLMPricingRule, int, error) {+ rules := make([]*llmpricingruletypes.LLMPricingRule, 0)++ count, err := store.sqlstore.+ BunDBCtx(ctx).+ NewSelect().+ Model(&rules).+ Where("org_id = ?", orgID).+ Order("created_at DESC").+ Offset(offset).+ Limit(limit).+ ScanAndCount(ctx)+ if err != nil {+ return nil, 0, err+ }++ return rules, count, nil+}++func (store *store) Get(ctx context.Context, orgID, id valuer.UUID) (*llmpricingruletypes.LLMPricingRule, error) {+ rule := new(llmpricingruletypes.LLMPricingRule)++ err := store.sqlstore.+ BunDBCtx(ctx).+ NewSelect().+ Model(rule).+ Where("org_id = ?", orgID).+ Where("id = ?", id).+ Scan(ctx)+ if err != nil {+ return nil, store.sqlstore.WrapNotFoundErrf(err, llmpricingruletypes.ErrCodePricingRuleNotFound, "pricing rule %s not found in the org", id)+ }++ return rule, nil+}++func (store *store) GetBySourceID(ctx context.Context, orgID, sourceID valuer.UUID) (*llmpricingruletypes.LLMPricingRule, error) {+ rule := new(llmpricingruletypes.LLMPricingRule)++ err := store.sqlstore.+ BunDBCtx(ctx).+ NewSelect().+ Model(rule).+ Where("org_id = ?", orgID).+ Where("source_id = ?", sourceID).+ Scan(ctx)+ if err != nil {+ return nil, store.sqlstore.WrapNotFoundErrf(err, llmpricingruletypes.ErrCodePricingRuleNotFound, "pricing rule with source_id %s not found in the org", sourceID)+ }++ return rule, nil+}++func (store *store) Create(ctx context.Context, rule *llmpricingruletypes.LLMPricingRule) error {+ _, err := store.sqlstore.+ BunDBCtx(ctx).+ NewInsert().+ Model(rule).+ Exec(ctx)+ if err != nil {+ return store.sqlstore.WrapAlreadyExistsErrf(err, llmpricingruletypes.ErrCodePricingRuleAlreadyExists, "pricing rule with model %s already exists", rule.Model)+ }+ return nil+}++func (store *store) Update(ctx context.Context, rule *llmpricingruletypes.LLMPricingRule) error {+ res, err := store.sqlstore.+ BunDBCtx(ctx).+ NewUpdate().+ Model(rule).+ Where("org_id = ?", rule.OrgID).+ Where("id = ?", rule.ID).+ ExcludeColumn("id", "org_id", "source_id", "created_at", "created_by").+ Exec(ctx)+ if err != nil {+ return err+ }++ rowsAffected, err := res.RowsAffected()+ if err != nil {+ return err+ }+ if rowsAffected == 0 {+ return errors.Newf(errors.TypeNotFound, llmpricingruletypes.ErrCodePricingRuleNotFound, "pricing rule %s not found in the org", rule.ID)+ }++ return nil+}++func (store *store) Delete(ctx context.Context, orgID, id valuer.UUID) error {+ res, err := store.sqlstore.+ BunDBCtx(ctx).+ NewDelete().+ Model((*llmpricingruletypes.LLMPricingRule)(nil)).+ Where("org_id = ?", orgID).+ Where("id = ?", id).+ Exec(ctx)+ if err != nil {+ return err+ }++ rowsAffected, err := res.RowsAffected()+ if err != nil {+ return err+ }+ if rowsAffected == 0 {+ return errors.Newf(errors.TypeNotFound, llmpricingruletypes.ErrCodePricingRuleNotFound, "pricing rule %s not found in the org", id)+ }++ return nil+}++func (store *store) RunInTx(ctx context.Context, cb func(ctx context.Context) error) error {+ return store.sqlstore.RunInTxCtx(ctx, nil, cb)+}diff --git a/pkg/modules/llmpricingrule/llmpricingrule.go b/pkg/modules/llmpricingrule/llmpricingrule.goindex e4cec830d6..cfe3811171 100644--- a/pkg/modules/llmpricingrule/llmpricingrule.go+++ b/pkg/modules/llmpricingrule/llmpricingrule.go@@ -4,14 +4,18 @@ import ("context""net/http"+ "github.com/SigNoz/signoz/pkg/query-service/agentConf""github.com/SigNoz/signoz/pkg/types/llmpricingruletypes""github.com/SigNoz/signoz/pkg/valuer")type Module interface {+ // Since this module interacts with OpAMP, it must implement the AgentFeature interface.+ agentConf.AgentFeature+List(ctx context.Context, orgID valuer.UUID, offset, limit int) ([]*llmpricingruletypes.LLMPricingRule, int, error)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)+ CreateOrUpdate(ctx context.Context, orgID valuer.UUID, userEmail string, rules []*llmpricingruletypes.UpdatableLLMPricingRule) (err error)Delete(ctx context.Context, orgID, id valuer.UUID) error}diff --git a/pkg/query-service/app/server.go b/pkg/query-service/app/server.goindex 4be343e248..01f0181608 100644--- a/pkg/query-service/app/server.go+++ b/pkg/query-service/app/server.go@@ -135,6 +135,7 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {Store: signoz.SQLStore,AgentFeatures: []agentConf.AgentFeature{logParsingPipelineController,+ signoz.Modules.LLMPricingRule,},},)diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.goindex fdc19568c2..05bda45ece 100644--- a/pkg/signoz/handler.go+++ b/pkg/signoz/handler.go@@ -124,6 +124,6 @@ func NewHandlers(AlertmanagerHandler: signozalertmanager.NewHandler(alertmanagerService),TraceDetail: impltracedetail.NewHandler(modules.TraceDetail),RulerHandler: signozruler.NewHandler(rulerService),- LLMPricingRuleHandler: impllmpricingrule.NewHandler(nil, providerSettings),+ LLMPricingRuleHandler: impllmpricingrule.NewHandler(modules.LLMPricingRule),}}diff --git a/pkg/signoz/module.go b/pkg/signoz/module.goindex 2f9f755110..4dd9d0670f 100644--- a/pkg/signoz/module.go+++ b/pkg/signoz/module.go@@ -17,6 +17,8 @@ import ("github.com/SigNoz/signoz/pkg/modules/dashboard""github.com/SigNoz/signoz/pkg/modules/inframonitoring""github.com/SigNoz/signoz/pkg/modules/inframonitoring/implinframonitoring"+ "github.com/SigNoz/signoz/pkg/modules/llmpricingrule"+ "github.com/SigNoz/signoz/pkg/modules/llmpricingrule/impllmpricingrule""github.com/SigNoz/signoz/pkg/modules/metricsexplorer""github.com/SigNoz/signoz/pkg/modules/metricsexplorer/implmetricsexplorer""github.com/SigNoz/signoz/pkg/modules/organization"@@ -82,6 +84,7 @@ type Modules struct {CloudIntegration cloudintegration.ModuleRuleStateHistory rulestatehistory.ModuleTraceDetail tracedetail.Module+ LLMPricingRule llmpricingrule.Module}func NewModules(@@ -137,5 +140,6 @@ func NewModules(RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger)),CloudIntegration: cloudIntegrationModule,TraceDetail: impltracedetail.NewModule(impltracedetail.NewTraceStore(telemetryStore), providerSettings, config.TraceDetail),+ LLMPricingRule: impllmpricingrule.NewModule(impllmpricingrule.NewStore(sqlstore)),}}diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex 1e5b9c3deb..fdb863ce96 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -198,6 +198,7 @@ func NewSQLMigrationProviderFactories(sqlmigration.NewDropUserDeletedAtFactory(sqlstore, sqlschema),sqlmigration.NewMigrateAWSAllRegionsFactory(sqlstore),sqlmigration.NewAddServiceAccountManagedRoleTransactionsFactory(sqlstore),+ sqlmigration.NewAddLLMPricingRulesFactory(sqlstore, sqlschema),)}diff --git a/pkg/sqlmigration/079_add_llm_pricing_rules.go b/pkg/sqlmigration/079_add_llm_pricing_rules.gonew file mode 100644index 0000000000..03597301b2--- /dev/null+++ b/pkg/sqlmigration/079_add_llm_pricing_rules.go@@ -0,0 +1,98 @@+package sqlmigration++import (+ "context"++ "github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/sqlschema"+ "github.com/SigNoz/signoz/pkg/sqlstore"+ "github.com/uptrace/bun"+ "github.com/uptrace/bun/migrate"+)++type addLLMPricingRules struct {+ sqlschema sqlschema.SQLSchema+ sqlstore sqlstore.SQLStore+}++func NewAddLLMPricingRulesFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {+ return factory.NewProviderFactory(factory.MustNewName("add_llm_pricing_rule"), func(_ context.Context, _ factory.ProviderSettings, _ Config) (SQLMigration, error) {+ return &addLLMPricingRules{+ sqlschema: sqlschema,+ sqlstore: sqlstore,+ }, nil+ })+}++func (migration *addLLMPricingRules) Register(migrations *migrate.Migrations) error {+ if err := migrations.Register(migration.Up, migration.Down); err != nil {+ return err+ }+ return nil+}++func (migration *addLLMPricingRules) Up(ctx context.Context, db *bun.DB) error {+ tx, err := db.BeginTx(ctx, nil)+ if err != nil {+ return err+ }++ defer func() {+ _ = tx.Rollback()+ }()++ sqls := [][]byte{}++ tableSQLs := migration.sqlschema.Operator().CreateTable(&sqlschema.Table{+ Name: "llm_pricing_rule",+ Columns: []*sqlschema.Column{+ {Name: "id", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "source_id", DataType: sqlschema.DataTypeText, Nullable: true},+ {Name: "model", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "provider", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "model_pattern", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "unit", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "pricing", DataType: sqlschema.DataTypeText, Nullable: false, Default: "'{}'"},+ {Name: "is_override", DataType: sqlschema.DataTypeBoolean, Nullable: false, Default: "false"},+ {Name: "synced_at", DataType: sqlschema.DataTypeTimestamp, Nullable: true},+ {Name: "enabled", DataType: sqlschema.DataTypeBoolean, Nullable: false, Default: "true"},+ {Name: "org_id", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "created_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},+ {Name: "updated_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},+ {Name: "created_by", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "updated_by", DataType: sqlschema.DataTypeText, Nullable: false},+ },+ PrimaryKeyConstraint: &sqlschema.PrimaryKeyConstraint{+ ColumnNames: []sqlschema.ColumnName{"id"},+ },+ ForeignKeyConstraints: []*sqlschema.ForeignKeyConstraint{+ {+ ReferencingColumnName: sqlschema.ColumnName("org_id"),+ ReferencedTableName: sqlschema.TableName("organizations"),+ ReferencedColumnName: sqlschema.ColumnName("id"),+ },+ },+ })+ sqls = append(sqls, tableSQLs...)++ indexSQLs := migration.sqlschema.Operator().CreateIndex(+ &sqlschema.PartialUniqueIndex{+ TableName: "llm_pricing_rule",+ ColumnNames: []sqlschema.ColumnName{"org_id", "source_id"},+ Where: "source_id IS NOT NULL",+ })++ sqls = append(sqls, indexSQLs...)++ for _, sql := range sqls {+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (migration *addLLMPricingRules) Down(context.Context, *bun.DB) error {+ return nil+}diff --git a/pkg/types/llmpricingruletypes/pricing.go b/pkg/types/llmpricingruletypes/pricing.goindex 0bd6b37a20..a9f9b1a5a9 100644--- a/pkg/types/llmpricingruletypes/pricing.go+++ b/pkg/types/llmpricingruletypes/pricing.go@@ -6,14 +6,34 @@ import ("time""github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/query-service/agentConf""github.com/SigNoz/signoz/pkg/types""github.com/SigNoz/signoz/pkg/valuer""github.com/uptrace/bun")+const (+ LLMCostFeatureType agentConf.AgentFeatureType = "llm_pricing"++ GenAIRequestModel = "gen_ai.request.model"+ GenAIUsageInputTokens = "gen_ai.usage.input_tokens"+ GenAIUsageOutputTokens = "gen_ai.usage.output_tokens"+ GenAIUsageCacheReadInputTokens = "gen_ai.usage.cache_read.input_tokens"+ GenAIUsageCacheCreationInputTokens = "gen_ai.usage.cache_creation.input_tokens"++ SignozGenAICostInput = "_signoz.gen_ai.cost_input"+ SignozGenAICostOutput = "_signoz.gen_ai.cost_output"+ SignozGenAICostCacheRead = "_signoz.gen_ai.cost_cache_read"+ SignozGenAICostCacheWrite = "_signoz.gen_ai.cost_cache_write"+ SignozGenAITotalCost = "_signoz.gen_ai.total_cost"+)+var (- ErrCodePricingRuleNotFound = errors.MustNewCode("pricing_rule_not_found")- ErrCodePricingRuleInvalidInput = errors.MustNewCode("pricing_rule_invalid_input")+ ErrCodePricingRuleAlreadyExists = errors.MustNewCode("pricing_rule_already_exists")+ ErrCodePricingRuleNotFound = errors.MustNewCode("pricing_rule_not_found")+ ErrCodePricingRuleInvalidInput = errors.MustNewCode("pricing_rule_invalid_input")+ ErrCodeInvalidCollectorConfig = errors.MustNewCode("invalid_collector_config")+ ErrCodeBuildPricingProcessorConf = errors.MustNewCode("build_pricing_processor_config"))type LLMPricingRuleUnit struct {@@ -101,7 +121,7 @@ type UpdatableLLMPricingRule struct {}type UpdatableLLMPricingRules struct {- Rules []UpdatableLLMPricingRule `json:"rules" required:"true"`+ Rules []*UpdatableLLMPricingRule `json:"rules" required:"true"`}type ListPricingRulesQuery struct {@@ -183,3 +203,48 @@ func NewGettableLLMPricingRulesFromLLMPricingRules(items []*LLMPricingRule, totaLimit: limit,}}++func NewLLMPricingRuleFromUpdatable(u *UpdatableLLMPricingRule, orgID valuer.UUID, userEmail string, now time.Time) *LLMPricingRule {+ isOverride := true+ if u.IsOverride != nil {+ isOverride = *u.IsOverride+ } else if u.SourceID != nil {+ isOverride = false+ }++ return &LLMPricingRule{+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},+ TimeAuditable: types.TimeAuditable{CreatedAt: now, UpdatedAt: now},+ UserAuditable: types.UserAuditable{CreatedBy: userEmail, UpdatedBy: userEmail},+ OrgID: orgID,+ SourceID: u.SourceID,+ Model: u.Model,+ Provider: u.Provider,+ ModelPattern: StringSlice(u.ModelPattern),+ Unit: u.Unit,+ Pricing: u.Pricing,+ IsOverride: isOverride,+ SyncedAt: &now,+ Enabled: u.Enabled,+ }+}++func (r *LLMPricingRule) Update(u *UpdatableLLMPricingRule, userEmail string, now time.Time) {+ if u.IsOverride == nil && r.IsOverride {+ r.SyncedAt = &now+ return+ }++ r.Model = u.Model+ r.Provider = u.Provider+ r.ModelPattern = StringSlice(u.ModelPattern)+ r.Unit = u.Unit+ r.Pricing = u.Pricing+ if u.IsOverride != nil {+ r.IsOverride = *u.IsOverride+ }+ r.Enabled = u.Enabled+ r.SyncedAt = &now+ r.UpdatedAt = now+ r.UpdatedBy = userEmail+}diff --git a/pkg/types/llmpricingruletypes/processorconfig.go b/pkg/types/llmpricingruletypes/processorconfig.gonew file mode 100644index 0000000000..5b86509223--- /dev/null+++ b/pkg/types/llmpricingruletypes/processorconfig.go@@ -0,0 +1,139 @@+package llmpricingruletypes++import (+ "bytes"++ "github.com/SigNoz/signoz/pkg/errors"+ "gopkg.in/yaml.v3"+)++const ProcessorName = "signozllmpricing"++// LLMPricingRuleProcessorConfig is the top-level config for the signozllmpricing+// OTel processor that gets deployed to collectors via OpAMP.+type LLMPricingRuleProcessorConfig struct {+ Attrs LLMPricingRuleProcessorAttrs `yaml:"attrs" json:"attrs"`+ DefaultPricing LLMPricingRuleProcessorDefaultPricing `yaml:"default_pricing" json:"default_pricing"`+ OutputAttrs LLMPricingRuleProcessorOutputAttrs `yaml:"output_attrs" json:"output_attrs"`+}++// LLMPricingRuleProcessorAttrs maps span attribute names to the processor's input fields.+type LLMPricingRuleProcessorAttrs struct {+ Model string `yaml:"model" json:"model"`+ In string `yaml:"in" json:"in"`+ Out string `yaml:"out" json:"out"`+ CacheRead string `yaml:"cache_read" json:"cache_read"`+ CacheWrite string `yaml:"cache_write" json:"cache_write"`+}++// LLMPricingRuleProcessorDefaultPricing holds the pricing unit and the list of model-specific rules.+type LLMPricingRuleProcessorDefaultPricing struct {+ Unit string `yaml:"unit" json:"unit"`+ Rules []LLMPricingRuleProcessor `yaml:"rules" json:"rules"`+}++// LLMPricingRuleProcessor is a single pricing rule inside the processor config.+type LLMPricingRuleProcessor struct {+ Name string `yaml:"name" json:"name"`+ Pattern []string `yaml:"pattern" json:"pattern"`+ Cache LLMPricingRuleProcessorCache `yaml:"cache" json:"cache"`+ In float64 `yaml:"in" json:"in"`+ Out float64 `yaml:"out" json:"out"`+}++// LLMPricingRuleProcessorCache describes how cached tokens are accounted for.+type LLMPricingRuleProcessorCache struct {+ Mode string `yaml:"mode" json:"mode"`+ Read float64 `yaml:"read" json:"read"`+ Write float64 `yaml:"write" json:"write"`+}++// LLMPricingRuleProcessorOutputAttrs maps the processor's computed cost fields to span attribute names.+type LLMPricingRuleProcessorOutputAttrs struct {+ In string `yaml:"in" json:"in"`+ Out string `yaml:"out" json:"out"`+ CacheRead string `yaml:"cache_read" json:"cache_read"`+ CacheWrite string `yaml:"cache_write" json:"cache_write"`+ Total string `yaml:"total" json:"total"`+}++// buildProcessorConfig converts pricing rules into the signozllmpricing processor config.+func buildProcessorConfig(rules []*LLMPricingRule) *LLMPricingRuleProcessorConfig {+ pricingRules := make([]LLMPricingRuleProcessor, 0, len(rules))+ for _, r := range rules {+ var cache LLMPricingRuleProcessorCache+ if r.Pricing.Cache != nil {+ cache = LLMPricingRuleProcessorCache{+ Mode: r.Pricing.Cache.Mode.StringValue(),+ Read: r.Pricing.Cache.Read,+ Write: r.Pricing.Cache.Write,+ }+ }+ pricingRules = append(pricingRules, LLMPricingRuleProcessor{+ Name: r.Model,+ Pattern: r.ModelPattern,+ Cache: cache,+ In: r.Pricing.Input,+ Out: r.Pricing.Output,+ })+ }++ return &LLMPricingRuleProcessorConfig{+ Attrs: LLMPricingRuleProcessorAttrs{+ Model: GenAIRequestModel,+ In: GenAIUsageInputTokens,+ Out: GenAIUsageOutputTokens,+ CacheRead: GenAIUsageCacheReadInputTokens,+ CacheWrite: GenAIUsageCacheCreationInputTokens,+ },+ DefaultPricing: LLMPricingRuleProcessorDefaultPricing{+ Unit: UnitPerMillionTokens.StringValue(),+ Rules: pricingRules,+ },+ OutputAttrs: LLMPricingRuleProcessorOutputAttrs{+ In: SignozGenAICostInput,+ Out: SignozGenAICostOutput,+ CacheRead: SignozGenAICostCacheRead,+ CacheWrite: SignozGenAICostCacheWrite,+ Total: SignozGenAITotalCost,+ },+ }+}++// GenerateCollectorConfigWithLLMPricingProcessor injects (or replaces) the signozllmpricing+// processor block in the collector YAML with one built from the given rules.+func GenerateCollectorConfigWithLLMPricingProcessor(+ currentConfYaml []byte,+ rules []*LLMPricingRule,+) ([]byte, error) {+ if len(bytes.TrimSpace(currentConfYaml)) == 0 {+ return currentConfYaml, nil+ }++ var collectorConf map[string]any+ if err := yaml.Unmarshal(currentConfYaml, &collectorConf); err != nil {+ return nil, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodeInvalidCollectorConfig, "failed to unmarshal collector config")+ }+ // rare but don't do anything in this case, also means it's just comments.+ if collectorConf == nil {+ return currentConfYaml, nil+ }++ processors := map[string]any{}+ if existing, ok := collectorConf["processors"]; ok && existing != nil {+ p, ok := existing.(map[string]any)+ if !ok {+ return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidCollectorConfig, "collector config 'processors' must be a mapping, got %T", existing)+ }+ processors = p+ }++ processors[ProcessorName] = buildProcessorConfig(rules)+ collectorConf["processors"] = processors++ out, err := yaml.Marshal(collectorConf)+ if err != nil {+ return nil, errors.Wrapf(err, errors.TypeInternal, ErrCodeBuildPricingProcessorConf, "failed to marshal llm pricing processor config")+ }+ return out, nil+}diff --git a/pkg/types/llmpricingruletypes/processorconfig_test.go b/pkg/types/llmpricingruletypes/processorconfig_test.gonew file mode 100644index 0000000000..d5e1fe6b35--- /dev/null+++ b/pkg/types/llmpricingruletypes/processorconfig_test.go@@ -0,0 +1,91 @@+package llmpricingruletypes++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "gopkg.in/yaml.v3"+)++// assertYAMLEqualToFile decodes both sides into any and compares structurally,+// so map key ordering is irrelevant.+func assertYAMLEqualToFile(t *testing.T, name string, actual []byte) {+ t.Helper()+ expected, err := os.ReadFile(filepath.Join("testdata", name))+ require.NoError(t, err)++ var e, a any+ require.NoError(t, yaml.Unmarshal(expected, &e))+ require.NoError(t, yaml.Unmarshal(actual, &a))+ assert.Equal(t, e, a)+}++func makePricingRule(model string, patterns []string, cacheMode LLMPricingRuleCacheMode, costIn, costOut, cacheRead, cacheWrite float64) *LLMPricingRule {+ return &LLMPricingRule{+ Model: model,+ ModelPattern: StringSlice(patterns),+ Unit: UnitPerMillionTokens,+ Pricing: LLMRulePricing{+ Input: costIn,+ Output: costOut,+ Cache: &LLMPricingCacheCosts{+ Mode: cacheMode,+ Read: cacheRead,+ Write: cacheWrite,+ },+ },+ Enabled: true,+ }+}++func TestGenerateCollectorConfigWithLLMPricingProcessor(t *testing.T) {+ tests := []struct {+ name string+ rules []*LLMPricingRule+ expectedFile string+ }{+ {+ name: "with_rule",+ rules: []*LLMPricingRule{+ makePricingRule("gpt-4o", []string{"gpt-4o*"}, LLMPricingRuleCacheModeSubtract, 5.0, 15.0, 2.5, 0),+ },+ expectedFile: "collector_with_rule.yaml",+ },+ // We deploy the processor even with zero rules so rules can be added+ // later (by a user or by Zeus) without any config-shape change.+ // Pipeline wiring is handled by the collector's baseline config.+ {+ name: "no_rules",+ rules: nil,+ expectedFile: "collector_no_rules.yaml",+ },+ }++ input, err := os.ReadFile(filepath.Join("testdata", "collector_baseline.yaml"))+ require.NoError(t, err)++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ out, err := GenerateCollectorConfigWithLLMPricingProcessor(input, tc.rules)+ require.NoError(t, err)+ assertYAMLEqualToFile(t, tc.expectedFile, out)+ })+ }+}++func TestGenerateCollectorConfig_EmptyInputPassthrough(t *testing.T) {+ // yaml.v3 errors on empty/whitespace input; the generator passes such+ // input through unchanged instead.+ rules := []*LLMPricingRule{+ makePricingRule("gpt-4o", []string{"gpt-4o*"}, LLMPricingRuleCacheModeSubtract, 5.0, 15.0, 2.5, 0),+ }++ for _, in := range [][]byte{nil, []byte(" \n")} {+ out, err := GenerateCollectorConfigWithLLMPricingProcessor(in, rules)+ require.NoError(t, err)+ assert.Equal(t, in, out)+ }+}diff --git a/pkg/types/llmpricingruletypes/store.go b/pkg/types/llmpricingruletypes/store.goindex 0a1add5ac5..d8b2deda48 100644--- a/pkg/types/llmpricingruletypes/store.go+++ b/pkg/types/llmpricingruletypes/store.go@@ -7,10 +7,11 @@ import ()type Store interface {- List(ctx context.Context, orgID valuer.UUID, offset, limit int) ([]*StorableLLMPricingRule, int, error)- Get(ctx context.Context, orgID, id valuer.UUID) (*StorableLLMPricingRule, error)- GetBySourceID(ctx context.Context, orgID, sourceID valuer.UUID) (*StorableLLMPricingRule, error)- Create(ctx context.Context, rule *StorableLLMPricingRule) error- Update(ctx context.Context, rule *StorableLLMPricingRule) error+ List(ctx context.Context, orgID valuer.UUID, offset, limit int) ([]*LLMPricingRule, int, error)+ Get(ctx context.Context, orgID, id valuer.UUID) (*LLMPricingRule, error)+ GetBySourceID(ctx context.Context, orgID, sourceID valuer.UUID) (*LLMPricingRule, error)+ Create(ctx context.Context, rule *LLMPricingRule) error+ Update(ctx context.Context, rule *LLMPricingRule) errorDelete(ctx context.Context, orgID, id valuer.UUID) error+ RunInTx(ctx context.Context, cb func(ctx context.Context) error) error}diff --git a/pkg/types/llmpricingruletypes/testdata/collector_baseline.yaml b/pkg/types/llmpricingruletypes/testdata/collector_baseline.yamlnew file mode 100644index 0000000000..342b0a84dc--- /dev/null+++ b/pkg/types/llmpricingruletypes/testdata/collector_baseline.yaml@@ -0,0 +1,31 @@+receivers:+ otlp:+ protocols:+ grpc:+processors:+ signozllmpricing:+ attrs:+ model: gen_ai.request.model+ in: gen_ai.usage.input_tokens+ out: gen_ai.usage.output_tokens+ cache_read: gen_ai.usage.cache_read.input_tokens+ cache_write: gen_ai.usage.cache_creation.input_tokens+ default_pricing:+ unit: per_million_tokens+ rules: []+ output_attrs:+ in: _signoz.gen_ai.cost_input+ out: _signoz.gen_ai.cost_output+ cache_read: _signoz.gen_ai.cost_cache_read+ cache_write: _signoz.gen_ai.cost_cache_write+ total: _signoz.gen_ai.total_cost+ batch: {}+exporters:+ otlp:+ endpoint: localhost:4317+service:+ pipelines:+ traces:+ receivers: [otlp]+ processors: [batch, signozllmpricing]+ exporters: [otlp]diff --git a/pkg/types/llmpricingruletypes/testdata/collector_no_rules.yaml b/pkg/types/llmpricingruletypes/testdata/collector_no_rules.yamlnew file mode 100644index 0000000000..0c2c73bc96--- /dev/null+++ b/pkg/types/llmpricingruletypes/testdata/collector_no_rules.yaml@@ -0,0 +1,35 @@+exporters:+ otlp:+ endpoint: localhost:4317+processors:+ batch: {}+ signozllmpricing:+ attrs:+ model: gen_ai.request.model+ in: gen_ai.usage.input_tokens+ out: gen_ai.usage.output_tokens+ cache_read: gen_ai.usage.cache_read.input_tokens+ cache_write: gen_ai.usage.cache_creation.input_tokens+ default_pricing:+ unit: per_million_tokens+ rules: []+ output_attrs:+ in: _signoz.gen_ai.cost_input+ out: _signoz.gen_ai.cost_output+ cache_read: _signoz.gen_ai.cost_cache_read+ cache_write: _signoz.gen_ai.cost_cache_write+ total: _signoz.gen_ai.total_cost+receivers:+ otlp:+ protocols:+ grpc: null+service:+ pipelines:+ traces:+ exporters:+ - otlp+ processors:+ - batch+ - signozllmpricing+ receivers:+ - otlpdiff --git a/pkg/types/llmpricingruletypes/testdata/collector_with_rule.yaml b/pkg/types/llmpricingruletypes/testdata/collector_with_rule.yamlnew file mode 100644index 0000000000..09ec9b8ebd--- /dev/null+++ b/pkg/types/llmpricingruletypes/testdata/collector_with_rule.yaml@@ -0,0 +1,44 @@+exporters:+ otlp:+ endpoint: localhost:4317+processors:+ batch: {}+ signozllmpricing:+ attrs:+ model: gen_ai.request.model+ in: gen_ai.usage.input_tokens+ out: gen_ai.usage.output_tokens+ cache_read: gen_ai.usage.cache_read.input_tokens+ cache_write: gen_ai.usage.cache_creation.input_tokens+ default_pricing:+ unit: per_million_tokens+ rules:+ - name: gpt-4o+ pattern:+ - gpt-4o*+ cache:+ mode: subtract+ read: 2.5+ write: 0+ in: 5+ out: 15+ output_attrs:+ in: _signoz.gen_ai.cost_input+ out: _signoz.gen_ai.cost_output+ cache_read: _signoz.gen_ai.cost_cache_read+ cache_write: _signoz.gen_ai.cost_cache_write+ total: _signoz.gen_ai.total_cost+receivers:+ otlp:+ protocols:+ grpc: null+service:+ pipelines:+ traces:+ exporters:+ - otlp+ processors:+ - batch+ - signozllmpricing+ receivers:+ - otlp