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: types and handler for llm pricing rules (#10908)

Nityananda Gohain755390c4b5b2
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 0fbbd951fb..8a17b30329 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -2632,6 +2632,158 @@ components:
- list
- grouped_list
type: string
+ LlmpricingruletypesGettablePricingRules:
+ properties:
+ items:
+ items:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMPricingRule'
+ nullable: true
+ type: array
+ limit:
+ type: integer
+ offset:
+ type: integer
+ total:
+ type: integer
+ required:
+ - items
+ - total
+ - offset
+ - limit
+ type: object
+ LlmpricingruletypesLLMPricingCacheCosts:
+ properties:
+ mode:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMPricingRuleCacheMode'
+ read:
+ format: double
+ type: number
+ write:
+ format: double
+ type: number
+ required:
+ - mode
+ type: object
+ LlmpricingruletypesLLMPricingRule:
+ properties:
+ createdAt:
+ format: date-time
+ type: string
+ createdBy:
+ type: string
+ enabled:
+ type: boolean
+ id:
+ type: string
+ isOverride:
+ type: boolean
+ modelName:
+ type: string
+ modelPattern:
+ $ref: '#/components/schemas/LlmpricingruletypesStringSlice'
+ orgId:
+ type: string
+ pricing:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMRulePricing'
+ provider:
+ type: string
+ sourceId:
+ type: string
+ syncedAt:
+ format: date-time
+ nullable: true
+ type: string
+ unit:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMPricingRuleUnit'
+ updatedAt:
+ format: date-time
+ type: string
+ updatedBy:
+ type: string
+ required:
+ - id
+ - orgId
+ - modelName
+ - provider
+ - modelPattern
+ - unit
+ - pricing
+ - isOverride
+ - enabled
+ type: object
+ LlmpricingruletypesLLMPricingRuleCacheMode:
+ enum:
+ - subtract
+ - additive
+ - unknown
+ type: string
+ LlmpricingruletypesLLMPricingRuleUnit:
+ enum:
+ - per_million_tokens
+ type: string
+ LlmpricingruletypesLLMRulePricing:
+ properties:
+ cache:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMPricingCacheCosts'
+ input:
+ format: double
+ type: number
+ output:
+ format: double
+ type: number
+ required:
+ - input
+ - output
+ type: object
+ LlmpricingruletypesStringSlice:
+ items:
+ type: string
+ nullable: true
+ type: array
+ LlmpricingruletypesUpdatableLLMPricingRule:
+ properties:
+ enabled:
+ type: boolean
+ id:
+ nullable: true
+ type: string
+ isOverride:
+ nullable: true
+ type: boolean
+ modelName:
+ type: string
+ modelPattern:
+ items:
+ type: string
+ nullable: true
+ type: array
+ pricing:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMRulePricing'
+ provider:
+ type: string
+ sourceId:
+ nullable: true
+ type: string
+ unit:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMPricingRuleUnit'
+ required:
+ - modelName
+ - provider
+ - modelPattern
+ - unit
+ - pricing
+ - enabled
+ type: object
+ LlmpricingruletypesUpdatableLLMPricingRules:
+ properties:
+ rules:
+ items:
+ $ref: '#/components/schemas/LlmpricingruletypesUpdatableLLMPricingRule'
+ nullable: true
+ type: array
+ required:
+ - rules
+ type: object
MetricsexplorertypesInspectMetricsRequest:
properties:
end:
@@ -7675,6 +7827,218 @@ paths:
summary: Create bulk invite
tags:
- users
+ /api/v1/llm_pricing_rules:
+ get:
+ deprecated: false
+ description: Returns all LLM pricing rules for the authenticated org, with pagination.
+ operationId: ListLLMPricingRules
+ parameters:
+ - in: query
+ name: offset
+ schema:
+ type: integer
+ - in: query
+ name: limit
+ schema:
+ type: integer
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/LlmpricingruletypesGettablePricingRules'
+ 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 pricing rules
+ tags:
+ - llmpricingrules
+ put:
+ deprecated: false
+ description: Single write endpoint used by both the user and the Zeus sync job.
+ Per-rule match is by id, then sourceId, then insert. Override rows (is_override=true)
+ are fully preserved when the request does not provide isOverride; only synced_at
+ is stamped.
+ operationId: CreateOrUpdateLLMPricingRules
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LlmpricingruletypesUpdatableLLMPricingRules'
+ responses:
+ "204":
+ description: No Content
+ "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:
+ - ADMIN
+ - tokenizer:
+ - ADMIN
+ summary: Create or update pricing rules
+ tags:
+ - llmpricingrules
+ /api/v1/llm_pricing_rules/{id}:
+ delete:
+ deprecated: false
+ description: Hard-deletes a pricing rule. If auto-synced, it will be recreated
+ on the next sync cycle.
+ operationId: DeleteLLMPricingRule
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - ADMIN
+ - tokenizer:
+ - ADMIN
+ summary: Delete a pricing rule
+ tags:
+ - llmpricingrules
+ get:
+ deprecated: false
+ description: Returns a single LLM pricing rule by ID.
+ operationId: GetLLMPricingRule
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/LlmpricingruletypesLLMPricingRule'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - VIEWER
+ - tokenizer:
+ - VIEWER
+ summary: Get a pricing rule
+ 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
new file mode 100644
index 0000000000..e82752c68b
--- /dev/null
+++ b/frontend/src/api/generated/services/llmpricingrules/index.ts
@@ -0,0 +1,399 @@
+/**
+ * ! Do not edit manually
+ * * The file has been auto-generated using Orval for SigNoz
+ * * regenerate with 'yarn generate:api'
+ * SigNoz
+ */
+import { useMutation, useQuery } from 'react-query';
+import type {
+ InvalidateOptions,
+ MutationFunction,
+ QueryClient,
+ QueryFunction,
+ QueryKey,
+ UseMutationOptions,
+ UseMutationResult,
+ UseQueryOptions,
+ UseQueryResult,
+} from 'react-query';
+
+import type {
+ DeleteLLMPricingRulePathParameters,
+ GetLLMPricingRule200,
+ GetLLMPricingRulePathParameters,
+ ListLLMPricingRules200,
+ ListLLMPricingRulesParams,
+ LlmpricingruletypesUpdatableLLMPricingRulesDTO,
+ RenderErrorResponseDTO,
+} from '../sigNoz.schemas';
+
+import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
+import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
+
+/**
+ * Returns all LLM pricing rules for the authenticated org, with pagination.
+ * @summary List pricing rules
+ */
+export const listLLMPricingRules = (
+ params?: ListLLMPricingRulesParams,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ListLLMPricingRules200>({
+ url: `/api/v1/llm_pricing_rules`,
+ method: 'GET',
+ params,
+ signal,
+ });
+};
+
+export const getListLLMPricingRulesQueryKey = (
+ params?: ListLLMPricingRulesParams,
+) => {
+ return [`/api/v1/llm_pricing_rules`, ...(params ? [params] : [])] as const;
+};
+
+export const getListLLMPricingRulesQueryOptions = <
+ TData = Awaited<ReturnType<typeof listLLMPricingRules>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ params?: ListLLMPricingRulesParams,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof listLLMPricingRules>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ?? getListLLMPricingRulesQueryKey(params);
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof listLLMPricingRules>>
+ > = ({ signal }) => listLLMPricingRules(params, signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof listLLMPricingRules>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type ListLLMPricingRulesQueryResult = NonNullable<
+ Awaited<ReturnType<typeof listLLMPricingRules>>
+>;
+export type ListLLMPricingRulesQueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary List pricing rules
+ */
+
+export function useListLLMPricingRules<
+ TData = Awaited<ReturnType<typeof listLLMPricingRules>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ params?: ListLLMPricingRulesParams,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof listLLMPricingRules>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getListLLMPricingRulesQueryOptions(params, options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary List pricing rules
+ */
+export const invalidateListLLMPricingRules = async (
+ queryClient: QueryClient,
+ params?: ListLLMPricingRulesParams,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getListLLMPricingRulesQueryKey(params) },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * Single write endpoint used by both the user and the Zeus sync job. Per-rule match is by id, then sourceId, then insert. Override rows (is_override=true) are fully preserved when the request does not provide isOverride; only synced_at is stamped.
+ * @summary Create or update pricing rules
+ */
+export const createOrUpdateLLMPricingRules = (
+ llmpricingruletypesUpdatableLLMPricingRulesDTO: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO>,
+) => {
+ return GeneratedAPIInstance<void>({
+ url: `/api/v1/llm_pricing_rules`,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ data: llmpricingruletypesUpdatableLLMPricingRulesDTO,
+ });
+};
+
+export const getCreateOrUpdateLLMPricingRulesMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
+ TError,
+ { data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
+ TError,
+ { data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
+ TContext
+> => {
+ const mutationKey = ['createOrUpdateLLMPricingRules'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
+ { data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> }
+ > = (props) => {
+ const { data } = props ?? {};
+
+ return createOrUpdateLLMPricingRules(data);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type CreateOrUpdateLLMPricingRulesMutationResult = NonNullable<
+ Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>
+>;
+export type CreateOrUpdateLLMPricingRulesMutationBody =
+ BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO>;
+export type CreateOrUpdateLLMPricingRulesMutationError =
+ ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Create or update pricing rules
+ */
+export const useCreateOrUpdateLLMPricingRules = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
+ TError,
+ { data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
+ TError,
+ { data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
+ TContext
+> => {
+ const mutationOptions =
+ getCreateOrUpdateLLMPricingRulesMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Hard-deletes a pricing rule. If auto-synced, it will be recreated on the next sync cycle.
+ * @summary Delete a pricing rule
+ */
+export const deleteLLMPricingRule = ({
+ id,
+}: DeleteLLMPricingRulePathParameters) => {
+ return GeneratedAPIInstance<void>({
+ url: `/api/v1/llm_pricing_rules/${id}`,
+ method: 'DELETE',
+ });
+};
+
+export const getDeleteLLMPricingRuleMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof deleteLLMPricingRule>>,
+ TError,
+ { pathParams: DeleteLLMPricingRulePathParameters },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof deleteLLMPricingRule>>,
+ TError,
+ { pathParams: DeleteLLMPricingRulePathParameters },
+ TContext
+> => {
+ const mutationKey = ['deleteLLMPricingRule'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof deleteLLMPricingRule>>,
+ { pathParams: DeleteLLMPricingRulePathParameters }
+ > = (props) => {
+ const { pathParams } = props ?? {};
+
+ return deleteLLMPricingRule(pathParams);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type DeleteLLMPricingRuleMutationResult = NonNullable<
+ Awaited<ReturnType<typeof deleteLLMPricingRule>>
+>;
+
+export type DeleteLLMPricingRuleMutationError =
+ ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Delete a pricing rule
+ */
+export const useDeleteLLMPricingRule = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof deleteLLMPricingRule>>,
+ TError,
+ { pathParams: DeleteLLMPricingRulePathParameters },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof deleteLLMPricingRule>>,
+ TError,
+ { pathParams: DeleteLLMPricingRulePathParameters },
+ TContext
+> => {
+ const mutationOptions = getDeleteLLMPricingRuleMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Returns a single LLM pricing rule by ID.
+ * @summary Get a pricing rule
+ */
+export const getLLMPricingRule = (
+ { id }: GetLLMPricingRulePathParameters,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<GetLLMPricingRule200>({
+ url: `/api/v1/llm_pricing_rules/${id}`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getGetLLMPricingRuleQueryKey = ({
+ id,
+}: GetLLMPricingRulePathParameters) => {
+ return [`/api/v1/llm_pricing_rules/${id}`] as const;
+};
+
+export const getGetLLMPricingRuleQueryOptions = <
+ TData = Awaited<ReturnType<typeof getLLMPricingRule>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ { id }: GetLLMPricingRulePathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getLLMPricingRule>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ?? getGetLLMPricingRuleQueryKey({ id });
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getLLMPricingRule>>
+ > = ({ signal }) => getLLMPricingRule({ id }, signal);
+
+ return {
+ queryKey,
+ queryFn,
+ enabled: !!id,
+ ...queryOptions,
+ } as UseQueryOptions<
+ Awaited<ReturnType<typeof getLLMPricingRule>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetLLMPricingRuleQueryResult = NonNullable<
+ Awaited<ReturnType<typeof getLLMPricingRule>>
+>;
+export type GetLLMPricingRuleQueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Get a pricing rule
+ */
+
+export function useGetLLMPricingRule<
+ TData = Awaited<ReturnType<typeof getLLMPricingRule>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ { id }: GetLLMPricingRulePathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getLLMPricingRule>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetLLMPricingRuleQueryOptions({ id }, options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary Get a pricing rule
+ */
+export const invalidateGetLLMPricingRule = async (
+ queryClient: QueryClient,
+ { id }: GetLLMPricingRulePathParameters,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetLLMPricingRuleQueryKey({ id }) },
+ options,
+ );
+
+ return queryClient;
+};
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 44467be28a..387ca6d56c 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -3413,6 +3413,170 @@ export enum InframonitoringtypesResponseTypeDTO {
list = 'list',
grouped_list = 'grouped_list',
}
+export interface LlmpricingruletypesGettablePricingRulesDTO {
+ /**
+ * @type array
+ * @nullable true
+ */
+ items: LlmpricingruletypesLLMPricingRuleDTO[] | null;
+ /**
+ * @type integer
+ */
+ limit: number;
+ /**
+ * @type integer
+ */
+ offset: number;
+ /**
+ * @type integer
+ */
+ total: number;
+}
+
+export interface LlmpricingruletypesLLMPricingCacheCostsDTO {
+ mode: LlmpricingruletypesLLMPricingRuleCacheModeDTO;
+ /**
+ * @type number
+ * @format double
+ */
+ read?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ write?: number;
+}
+
+export interface LlmpricingruletypesLLMPricingRuleDTO {
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt?: Date;
+ /**
+ * @type string
+ */
+ createdBy?: string;
+ /**
+ * @type boolean
+ */
+ enabled: boolean;
+ /**
+ * @type string
+ */
+ id: string;
+ /**
+ * @type boolean
+ */
+ isOverride: boolean;
+ /**
+ * @type string
+ */
+ modelName: string;
+ modelPattern: LlmpricingruletypesStringSliceDTO;
+ /**
+ * @type string
+ */
+ orgId: string;
+ pricing: LlmpricingruletypesLLMRulePricingDTO;
+ /**
+ * @type string
+ */
+ provider: string;
+ /**
+ * @type string
+ */
+ sourceId?: string;
+ /**
+ * @type string
+ * @format date-time
+ * @nullable true
+ */
+ syncedAt?: Date | null;
+ unit: LlmpricingruletypesLLMPricingRuleUnitDTO;
+ /**
+ * @type string
+ * @format date-time
+ */
+ updatedAt?: Date;
+ /**
+ * @type string
+ */
+ updatedBy?: string;
+}
+
+export enum LlmpricingruletypesLLMPricingRuleCacheModeDTO {
+ subtract = 'subtract',
+ additive = 'additive',
+ unknown = 'unknown',
+}
+export enum LlmpricingruletypesLLMPricingRuleUnitDTO {
+ per_million_tokens = 'per_million_tokens',
+}
+export interface LlmpricingruletypesLLMRulePricingDTO {
+ cache?: LlmpricingruletypesLLMPricingCacheCostsDTO;
+ /**
+ * @type number
+ * @format double
+ */
+ input: number;
+ /**
+ * @type number
+ * @format double
+ */
+ output: number;
+}
+
+/**
+ * @nullable
+ */
+export type LlmpricingruletypesStringSliceDTO = string[] | null;
+
+export interface LlmpricingruletypesUpdatableLLMPricingRuleDTO {
+ /**
+ * @type boolean
+ */
+ enabled: boolean;
+ /**
+ * @type string
+ * @nullable true
+ */
+ id?: string | null;
+ /**
+ * @type boolean
+ * @nullable true
+ */
+ isOverride?: boolean | null;
+ /**
+ * @type string
+ */
+ modelName: string;
+ /**
+ * @type array
+ * @nullable true
+ */
+ modelPattern: string[] | null;
+ pricing: LlmpricingruletypesLLMRulePricingDTO;
+ /**
+ * @type string
+ */
+ provider: string;
+ /**
+ * @type string
+ * @nullable true
+ */
+ sourceId?: string | null;
+ unit: LlmpricingruletypesLLMPricingRuleUnitDTO;
+}
+
+export interface LlmpricingruletypesUpdatableLLMPricingRulesDTO {
+ /**
+ * @type array
+ * @nullable true
+ */
+ rules: LlmpricingruletypesUpdatableLLMPricingRuleDTO[] | null;
+}
+
export interface MetricsexplorertypesInspectMetricsRequestDTO {
/**
* @type integer
@@ -7004,6 +7168,41 @@ export type CreateInvite201 = {
status: string;
};
+export type ListLLMPricingRulesParams = {
+ /**
+ * @type integer
+ * @description undefined
+ */
+ offset?: number;
+ /**
+ * @type integer
+ * @description undefined
+ */
+ limit?: number;
+};
+
+export type ListLLMPricingRules200 = {
+ data: LlmpricingruletypesGettablePricingRulesDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
+export type DeleteLLMPricingRulePathParameters = {
+ id: string;
+};
+export type GetLLMPricingRulePathParameters = {
+ id: string;
+};
+export type GetLLMPricingRule200 = {
+ data: LlmpricingruletypesLLMPricingRuleDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type ListPromotedAndIndexedPaths200 = {
/**
* @type array
diff --git a/pkg/apiserver/signozapiserver/llmpricingrule.go b/pkg/apiserver/signozapiserver/llmpricingrule.go
new file mode 100644
index 0000000000..faab7dbb35
--- /dev/null
+++ b/pkg/apiserver/signozapiserver/llmpricingrule.go
@@ -0,0 +1,93 @@
+package signozapiserver
+
+import (
+ "net/http"
+
+ "github.com/SigNoz/signoz/pkg/http/handler"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"
+ "github.com/gorilla/mux"
+)
+
+func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
+ if err := router.Handle("/api/v1/llm_pricing_rules", handler.New(
+ provider.authZ.ViewAccess(provider.llmPricingRuleHandler.List),
+ handler.OpenAPIDef{
+ ID: "ListLLMPricingRules",
+ Tags: []string{"llmpricingrules"},
+ Summary: "List pricing rules",
+ Description: "Returns all LLM pricing rules for the authenticated org, with pagination.",
+ Request: nil,
+ RequestContentType: "",
+ RequestQuery: new(llmpricingruletypes.ListPricingRulesQuery),
+ Response: new(llmpricingruletypes.GettablePricingRules),
+ 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", handler.New(
+ provider.authZ.AdminAccess(provider.llmPricingRuleHandler.CreateOrUpdate),
+ handler.OpenAPIDef{
+ ID: "CreateOrUpdateLLMPricingRules",
+ Tags: []string{"llmpricingrules"},
+ Summary: "Create or update pricing rules",
+ Description: "Single write endpoint used by both the user and the Zeus sync job. Per-rule match is by id, then sourceId, then insert. Override rows (is_override=true) are fully preserved when the request does not provide isOverride; only synced_at is stamped.",
+ Request: new(llmpricingruletypes.UpdatableLLMPricingRules),
+ RequestContentType: "application/json",
+ SuccessStatusCode: http.StatusNoContent,
+ ErrorStatusCodes: []int{http.StatusBadRequest},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
+ },
+ )).Methods(http.MethodPut).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v1/llm_pricing_rules/{id}", handler.New(
+ provider.authZ.ViewAccess(provider.llmPricingRuleHandler.Get),
+ handler.OpenAPIDef{
+ ID: "GetLLMPricingRule",
+ Tags: []string{"llmpricingrules"},
+ Summary: "Get a pricing rule",
+ Description: "Returns a single LLM pricing rule by ID.",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(llmpricingruletypes.GettableLLMPricingRule),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusNotFound},
+ 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.authZ.AdminAccess(provider.llmPricingRuleHandler.Delete),
+ handler.OpenAPIDef{
+ ID: "DeleteLLMPricingRule",
+ Tags: []string{"llmpricingrules"},
+ Summary: "Delete a pricing rule",
+ Description: "Hard-deletes a pricing rule. If auto-synced, it will be recreated on the next sync cycle.",
+ Request: nil,
+ RequestContentType: "",
+ Response: nil,
+ ResponseContentType: "",
+ SuccessStatusCode: http.StatusNoContent,
+ ErrorStatusCodes: []int{http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
+ },
+ )).Methods(http.MethodDelete).GetError(); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/pkg/apiserver/signozapiserver/provider.go b/pkg/apiserver/signozapiserver/provider.go
index 6027ac49a5..0c79cd71a0 100644
--- a/pkg/apiserver/signozapiserver/provider.go
+++ b/pkg/apiserver/signozapiserver/provider.go
@@ -17,6 +17,7 @@ import (
"github.com/SigNoz/signoz/pkg/modules/dashboard"
"github.com/SigNoz/signoz/pkg/modules/fields"
"github.com/SigNoz/signoz/pkg/modules/inframonitoring"
+ "github.com/SigNoz/signoz/pkg/modules/llmpricingrule"
"github.com/SigNoz/signoz/pkg/modules/metricsexplorer"
"github.com/SigNoz/signoz/pkg/modules/organization"
"github.com/SigNoz/signoz/pkg/modules/preference"
@@ -67,6 +68,7 @@ type provider struct {
alertmanagerHandler alertmanager.Handler
traceDetailHandler tracedetail.Handler
rulerHandler ruler.Handler
+ llmPricingRuleHandler llmpricingrule.Handler
}
func NewFactory(
@@ -96,6 +98,7 @@ func NewFactory(
ruleStateHistoryHandler rulestatehistory.Handler,
spanMapperHandler spanmapper.Handler,
alertmanagerHandler alertmanager.Handler,
+ llmPricingRuleHandler llmpricingrule.Handler,
traceDetailHandler tracedetail.Handler,
rulerHandler ruler.Handler,
) factory.ProviderFactory[apiserver.APIServer, apiserver.Config] {
@@ -130,6 +133,7 @@ func NewFactory(
ruleStateHistoryHandler,
spanMapperHandler,
alertmanagerHandler,
+ llmPricingRuleHandler,
traceDetailHandler,
rulerHandler,
)
@@ -166,6 +170,7 @@ func newProvider(
ruleStateHistoryHandler rulestatehistory.Handler,
spanMapperHandler spanmapper.Handler,
alertmanagerHandler alertmanager.Handler,
+ llmPricingRuleHandler llmpricingrule.Handler,
traceDetailHandler tracedetail.Handler,
rulerHandler ruler.Handler,
) (apiserver.APIServer, error) {
@@ -202,6 +207,7 @@ func newProvider(
alertmanagerHandler: alertmanagerHandler,
traceDetailHandler: traceDetailHandler,
rulerHandler: rulerHandler,
+ llmPricingRuleHandler: llmPricingRuleHandler,
}
provider.authZ = middleware.NewAuthZ(settings.Logger(), orgGetter, authz)
@@ -314,6 +320,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {
return err
}
+ if err := provider.addLLMPricingRuleRoutes(router); err != nil {
+ return err
+ }
+
if err := provider.addTraceDetailRoutes(router); err != nil {
return err
}
diff --git a/pkg/modules/llmpricingrule/impllmpricingrule/handler.go b/pkg/modules/llmpricingrule/impllmpricingrule/handler.go
new file mode 100644
index 0000000000..13a4b8fa19
--- /dev/null
+++ b/pkg/modules/llmpricingrule/impllmpricingrule/handler.go
@@ -0,0 +1,158 @@
+package impllmpricingrule
+
+import (
+ "context"
+ "net/http"
+ "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"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/gorilla/mux"
+)
+
+const maxLimit = 100
+
+type handler struct {
+ module llmpricingrule.Module
+ providerSettings factory.ProviderSettings
+}
+
+func NewHandler(module llmpricingrule.Module, providerSettings factory.ProviderSettings) llmpricingrule.Handler {
+ return &handler{module: module, providerSettings: providerSettings}
+}
+
+// List handles GET /api/v1/llm_pricing_rules.
+func (h *handler) List(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)
+
+ var q llmpricingruletypes.ListPricingRulesQuery
+ if err := binding.Query.BindQuery(r.URL.Query(), &q); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ if q.Limit <= 0 {
+ q.Limit = 20
+ } else if q.Limit > maxLimit {
+ q.Limit = maxLimit
+ }
+ if q.Offset < 0 {
+ render.Error(rw, errors.Newf(errors.TypeInvalidInput, llmpricingruletypes.ErrCodePricingRuleInvalidInput, "offset must be a non-negative integer"))
+ return
+ }
+
+ rules, total, err := h.module.List(ctx, orgID, q.Offset, q.Limit)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, llmpricingruletypes.NewGettableLLMPricingRulesFromLLMPricingRules(rules, total, q.Offset, q.Limit))
+}
+
+// Get handles GET /api/v1/llm_pricing_rules/{id}.
+func (h *handler) Get(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)
+
+ id, err := ruleIDFromPath(r)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ rule, err := h.module.Get(ctx, orgID, id)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, rule)
+}
+
+func (h *handler) CreateOrUpdate(rw http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgID := valuer.MustNewUUID(claims.OrgID)
+
+ req := new(llmpricingruletypes.UpdatableLLMPricingRules)
+ if err := binding.JSON.BindBody(r.Body, req); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ err = h.module.CreateOrUpdate(ctx, orgID, claims.Email, req.Rules)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusNoContent, nil)
+}
+
+// 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)
+ defer cancel()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgID := valuer.MustNewUUID(claims.OrgID)
+
+ id, err := ruleIDFromPath(r)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ if err := h.module.Delete(ctx, orgID, id); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusNoContent, nil)
+}
+
+// ruleIDFromPath extracts and validates the {id} path variable.
+func ruleIDFromPath(r *http.Request) (valuer.UUID, error) {
+ raw := mux.Vars(r)["id"]
+ id, err := valuer.NewUUID(raw)
+ if err != nil {
+ return valuer.UUID{}, errors.Wrapf(err, errors.TypeInvalidInput, llmpricingruletypes.ErrCodePricingRuleInvalidInput, "id is not a valid uuid")
+ }
+ return id, nil
+}
diff --git a/pkg/modules/llmpricingrule/llmpricingrule.go b/pkg/modules/llmpricingrule/llmpricingrule.go
new file mode 100644
index 0000000000..e4cec830d6
--- /dev/null
+++ b/pkg/modules/llmpricingrule/llmpricingrule.go
@@ -0,0 +1,24 @@
+package llmpricingrule
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+type Module interface {
+ 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)
+ Delete(ctx context.Context, orgID, id valuer.UUID) error
+}
+
+// Handler defines the HTTP handler interface for pricing rule endpoints.
+type Handler interface {
+ List(rw http.ResponseWriter, r *http.Request)
+ Get(rw http.ResponseWriter, r *http.Request)
+ CreateOrUpdate(rw http.ResponseWriter, r *http.Request)
+ Delete(rw http.ResponseWriter, r *http.Request)
+}
diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.go
index d9d6ecfbe2..fdc19568c2 100644
--- a/pkg/signoz/handler.go
+++ b/pkg/signoz/handler.go
@@ -22,6 +22,8 @@ import (
"github.com/SigNoz/signoz/pkg/modules/fields/implfields"
"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/quickfilter"
@@ -77,6 +79,7 @@ type Handlers struct {
AlertmanagerHandler alertmanager.Handler
TraceDetail tracedetail.Handler
RulerHandler ruler.Handler
+ LLMPricingRuleHandler llmpricingrule.Handler
}
func NewHandlers(
@@ -121,5 +124,6 @@ func NewHandlers(
AlertmanagerHandler: signozalertmanager.NewHandler(alertmanagerService),
TraceDetail: impltracedetail.NewHandler(modules.TraceDetail),
RulerHandler: signozruler.NewHandler(rulerService),
+ LLMPricingRuleHandler: impllmpricingrule.NewHandler(nil, providerSettings),
}
}
diff --git a/pkg/signoz/openapi.go b/pkg/signoz/openapi.go
index b5d2ea9b69..6460d703c4 100644
--- a/pkg/signoz/openapi.go
+++ b/pkg/signoz/openapi.go
@@ -22,6 +22,7 @@ import (
"github.com/SigNoz/signoz/pkg/modules/dashboard"
"github.com/SigNoz/signoz/pkg/modules/fields"
"github.com/SigNoz/signoz/pkg/modules/inframonitoring"
+ "github.com/SigNoz/signoz/pkg/modules/llmpricingrule"
"github.com/SigNoz/signoz/pkg/modules/metricsexplorer"
"github.com/SigNoz/signoz/pkg/modules/organization"
"github.com/SigNoz/signoz/pkg/modules/preference"
@@ -77,6 +78,7 @@ func NewOpenAPI(ctx context.Context, instrumentation instrumentation.Instrumenta
struct{ rulestatehistory.Handler }{},
struct{ spanmapper.Handler }{},
struct{ alertmanager.Handler }{},
+ struct{ llmpricingrule.Handler }{},
struct{ tracedetail.Handler }{},
struct{ ruler.Handler }{},
).New(ctx, instrumentation.ToProviderSettings(), apiserver.Config{})
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 57519bec1d..ed968b393f 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -283,6 +283,7 @@ func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.Au
handlers.RuleStateHistory,
handlers.SpanMapperHandler,
handlers.AlertmanagerHandler,
+ handlers.LLMPricingRuleHandler,
handlers.TraceDetail,
handlers.RulerHandler,
),
diff --git a/pkg/types/llmpricingruletypes/pricing.go b/pkg/types/llmpricingruletypes/pricing.go
new file mode 100644
index 0000000000..0bd6b37a20
--- /dev/null
+++ b/pkg/types/llmpricingruletypes/pricing.go
@@ -0,0 +1,185 @@
+package llmpricingruletypes
+
+import (
+ "database/sql/driver"
+ "encoding/json"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/uptrace/bun"
+)
+
+var (
+ ErrCodePricingRuleNotFound = errors.MustNewCode("pricing_rule_not_found")
+ ErrCodePricingRuleInvalidInput = errors.MustNewCode("pricing_rule_invalid_input")
+)
+
+type LLMPricingRuleUnit struct {
+ valuer.String
+}
+
+var (
+ UnitPerMillionTokens = LLMPricingRuleUnit{valuer.NewString("per_million_tokens")}
+)
+
+type LLMPricingRuleCacheMode struct {
+ valuer.String
+}
+
+var (
+ // LLMPricingRuleCacheModeSubtract: cached tokens are inside input_tokens (OpenAI-style).
+ LLMPricingRuleCacheModeSubtract = LLMPricingRuleCacheMode{valuer.NewString("subtract")}
+ // LLMPricingRuleCacheModeAdditive: cached tokens are reported separately (Anthropic-style).
+ LLMPricingRuleCacheModeAdditive = LLMPricingRuleCacheMode{valuer.NewString("additive")}
+ // LLMPricingRuleCacheModeUnknown: provider behaviour is unknown; falls back to subtract.
+ LLMPricingRuleCacheModeUnknown = LLMPricingRuleCacheMode{valuer.NewString("unknown")}
+)
+
+// StringSlice is a []string that is stored as a JSON text column.
+// It is compatible with both SQLite and PostgreSQL.
+type StringSlice []string
+
+// LLMRulePricing is the per-rule pricing shape, persisted as a single JSON.
+type LLMRulePricing struct {
+ Input float64 `json:"input" required:"true"`
+ Output float64 `json:"output" required:"true"`
+ Cache *LLMPricingCacheCosts `json:"cache,omitempty"`
+}
+
+type LLMPricingCacheCosts struct {
+ Mode LLMPricingRuleCacheMode `json:"mode" required:"true"`
+ Read float64 `json:"read"`
+ Write float64 `json:"write"`
+}
+
+type LLMPricingRule struct {
+ bun.BaseModel `bun:"table:llm_pricing_rule,alias:llm_pricing_rule" json:"-"`
+
+ types.Identifiable
+ types.TimeAuditable
+ types.UserAuditable
+
+ OrgID valuer.UUID `bun:"org_id,type:text,notnull" json:"orgId" required:"true"`
+ SourceID *valuer.UUID `bun:"source_id,type:text" json:"sourceId,omitempty"`
+ Model string `bun:"model,type:text,notnull" json:"modelName" required:"true"`
+ Provider string `bun:"provider,type:text,notnull" json:"provider" required:"true"`
+ ModelPattern StringSlice `bun:"model_pattern,type:text,notnull" json:"modelPattern" required:"true"`
+ Unit LLMPricingRuleUnit `bun:"unit,type:text,notnull" json:"unit" required:"true"`
+ Pricing LLMRulePricing `bun:"pricing,type:text,notnull,default:'{}'" json:"pricing" required:"true"`
+ // IsOverride marks the row as user-pinned. When true, Zeus skips it entirely.
+ IsOverride bool `bun:"is_override,notnull,default:false" json:"isOverride" required:"true"`
+ SyncedAt *time.Time `bun:"synced_at" json:"syncedAt,omitempty"`
+ Enabled bool `bun:"enabled,notnull,default:true" json:"enabled" required:"true"`
+}
+
+type GettableLLMPricingRule = LLMPricingRule
+
+type StorableLLMPricingRule = LLMPricingRule
+
+// UpdatableLLMPricingRule is one entry in the bulk upsert batch.
+//
+// Identification:
+// - ID set → match by id (user editing a known row).
+// - SourceID set → match by source_id (Zeus sync, or user editing a Zeus-synced row).
+// - neither set → insert a new row with source_id = NULL (user-created custom rule).
+//
+// IsOverride is a pointer so the caller can distinguish "not sent" from "set to false".
+// When IsOverride is nil AND the matched row has is_override = true, the row is fully
+// preserved — only synced_at is stamped.
+type UpdatableLLMPricingRule struct {
+ ID *valuer.UUID `json:"id,omitempty"`
+ SourceID *valuer.UUID `json:"sourceId,omitempty"`
+ Model string `json:"modelName" required:"true"`
+ Provider string `json:"provider" required:"true"`
+ ModelPattern []string `json:"modelPattern" required:"true"`
+ Unit LLMPricingRuleUnit `json:"unit" required:"true"`
+ Pricing LLMRulePricing `json:"pricing" required:"true"`
+ IsOverride *bool `json:"isOverride,omitempty"`
+ Enabled bool `json:"enabled" required:"true"`
+}
+
+type UpdatableLLMPricingRules struct {
+ Rules []UpdatableLLMPricingRule `json:"rules" required:"true"`
+}
+
+type ListPricingRulesQuery struct {
+ Offset int `query:"offset" json:"offset"`
+ Limit int `query:"limit" json:"limit"`
+}
+
+type GettablePricingRules struct {
+ Items []*GettableLLMPricingRule `json:"items" required:"true"`
+ Total int `json:"total" required:"true"`
+ Offset int `json:"offset" required:"true"`
+ Limit int `json:"limit" required:"true"`
+}
+
+func (LLMPricingRuleUnit) Enum() []any {
+ return []any{UnitPerMillionTokens}
+}
+
+func (LLMPricingRuleCacheMode) Enum() []any {
+ return []any{LLMPricingRuleCacheModeSubtract, LLMPricingRuleCacheModeAdditive, LLMPricingRuleCacheModeUnknown}
+}
+
+func (s StringSlice) Value() (driver.Value, error) {
+ if s == nil {
+ return "[]", nil
+ }
+ b, err := json.Marshal(s)
+ if err != nil {
+ return nil, err
+ }
+ return string(b), nil
+}
+
+func (s *StringSlice) Scan(src any) error {
+ var raw []byte
+ switch v := src.(type) {
+ case string:
+ raw = []byte(v)
+ case []byte:
+ raw = v
+ case nil:
+ *s = nil
+ return nil
+ default:
+ return errors.NewInternalf(errors.CodeInternal, "llmpricingruletypes: cannot scan %T into StringSlice", src)
+ }
+ return json.Unmarshal(raw, s)
+}
+
+func (p LLMRulePricing) Value() (driver.Value, error) {
+ b, err := json.Marshal(p)
+ if err != nil {
+ return nil, err
+ }
+ return string(b), nil
+}
+
+func (p *LLMRulePricing) Scan(src any) error {
+ var raw []byte
+ switch v := src.(type) {
+ case string:
+ raw = []byte(v)
+ case []byte:
+ raw = v
+ case nil:
+ *p = LLMRulePricing{}
+ return nil
+ default:
+ return errors.NewInternalf(errors.CodeInternal, "llmpricingruletypes: cannot scan %T into LLMRulePricing", src)
+ }
+ return json.Unmarshal(raw, p)
+}
+
+func NewGettableLLMPricingRulesFromLLMPricingRules(items []*LLMPricingRule, total, offset, limit int) *GettablePricingRules {
+ return &GettablePricingRules{
+ Items: items,
+ Total: total,
+ Offset: offset,
+ Limit: limit,
+ }
+}
diff --git a/pkg/types/llmpricingruletypes/store.go b/pkg/types/llmpricingruletypes/store.go
new file mode 100644
index 0000000000..0a1add5ac5
--- /dev/null
+++ b/pkg/types/llmpricingruletypes/store.go
@@ -0,0 +1,16 @@
+package llmpricingruletypes
+
+import (
+ "context"
+
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+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
+ Delete(ctx context.Context, orgID, id valuer.UUID) error
+}