🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(model-prices): add model pricing tiers (#10606)
Hassieb Pakzadad16fa0ada15
diff --git a/.gitignore b/.gitignoreindex a6ebd399f6..4b485b7199 100644--- a/.gitignore+++ b/.gitignore@@ -72,3 +72,5 @@ web/test-results/*# local config files*.local.*++.claude/tsc-cachediff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex a74ed0098b..d91bfcacaa 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -447,7 +447,16 @@ types:properties:datasetRunItems: list<DatasetRunItem>Model:- docs: Model definition used for transforming usage into USD cost and/or tokenization.+ docs: |+ Model definition used for transforming usage into USD cost and/or tokenization.++ Models can have either simple flat pricing or tiered pricing:+ - Flat pricing: Single price per usage type (legacy, but still supported)+ - Tiered pricing: Multiple pricing tiers with conditional matching based on usage patterns++ The pricing tiers approach is recommended for models with usage-based pricing variations.+ When using tiered pricing, the flat price fields (inputPrice, outputPrice, prices) are populated+ from the default tier for backward compatibility.properties:id: stringmodelName:@@ -479,14 +488,210 @@ types:type: optional<unknown>isLangfuseManaged:type: boolean+ createdAt:+ docs: Timestamp when the model was created+ type: datetimeprices:- docs: Price (USD) by usage type+ docs: |+ Deprecated. Use 'pricingTiers' instead for models with usage-based pricing variations.++ This field shows prices by usage type from the default pricing tier. Maintained for backward compatibility.+ If the model uses tiered pricing, this field will be populated from the default tier's prices.type: map<string, ModelPrice>+ pricingTiers:+ docs: |+ Array of pricing tiers with conditional pricing based on usage thresholds.++ Pricing tiers enable accurate cost tracking for models that charge different rates based on usage patterns+ (e.g., different rates for high-volume usage, large context windows, or cached tokens).++ Each model must have exactly one default tier (isDefault=true, priority=0) that serves as a fallback.+ Additional conditional tiers can be defined with specific matching criteria.++ If this array is empty, the model uses legacy flat pricing from the inputPrice/outputPrice/totalPrice fields.+ type: list<PricingTier>ModelPrice:properties:price: double+ PricingTierCondition:+ docs: |+ Condition for matching a pricing tier based on usage details. Used to implement tiered pricing models where costs vary based on usage thresholds.++ How it works:+ 1. The regex pattern matches against usage detail keys (e.g., "input_tokens", "input_cached")+ 2. Values of all matching keys are summed together+ 3. The sum is compared against the threshold value using the specified operator+ 4. All conditions in a tier must be met (AND logic) for the tier to match++ Common use cases:+ - Threshold-based pricing: Match when accumulated usage exceeds a certain amount+ - Usage-type-specific pricing: Different rates for cached vs non-cached tokens, or input vs output+ - Volume-based pricing: Different rates based on total request or token count+ properties:+ usageDetailPattern:+ docs: |+ Regex pattern to match against usage detail keys. All matching keys' values are summed for threshold comparison.++ Examples:+ - "^input" matches "input", "input_tokens", "input_cached", etc.+ - "^(input|prompt)" matches both "input_tokens" and "prompt_tokens"+ - "_cache$" matches "input_cache", "output_cache", etc.++ The pattern is case-insensitive by default. If no keys match, the sum is treated as zero.+ type: string+ operator:+ docs: |+ Comparison operator to apply between the summed value and the threshold.++ - gt: greater than (sum > threshold)+ - gte: greater than or equal (sum >= threshold)+ - lt: less than (sum < threshold)+ - lte: less than or equal (sum <= threshold)+ - eq: equal (sum == threshold)+ - neq: not equal (sum != threshold)+ type: PricingTierOperator+ value:+ docs: Threshold value for comparison. For token-based pricing, this is typically the token count threshold (e.g., 200000 for a 200K token threshold).+ type: double+ caseSensitive:+ docs: Whether the regex pattern matching is case-sensitive. Default is false (case-insensitive matching).+ type: boolean++ PricingTier:+ docs: |+ Pricing tier definition with conditional pricing based on usage thresholds.++ Pricing tiers enable accurate cost tracking for LLM providers that charge different rates based on usage patterns.+ For example, some providers charge higher rates when context size exceeds certain thresholds.++ How tier matching works:+ 1. Tiers are evaluated in ascending priority order (priority 1 before priority 2, etc.)+ 2. The first tier where ALL conditions match is selected+ 3. If no conditional tiers match, the default tier is used as a fallback+ 4. The default tier has priority 0 and no conditions++ Why priorities matter:+ - Lower priority numbers are evaluated first, allowing you to define specific cases before general ones+ - Example: Priority 1 for "high usage" (>200K tokens), Priority 2 for "medium usage" (>100K tokens), Priority 0 for default+ - Without proper ordering, a less specific condition might match before a more specific one++ Every model must have exactly one default tier to ensure cost calculation always succeeds.+ properties:+ id:+ docs: Unique identifier for the pricing tier+ type: string+ name:+ docs: |+ Name of the pricing tier for display and identification purposes.++ Examples: "Standard", "High Volume Tier", "Large Context", "Extended Context Tier"+ type: string+ isDefault:+ docs: |+ Whether this is the default tier. Every model must have exactly one default tier with priority 0 and no conditions.++ The default tier serves as a fallback when no conditional tiers match, ensuring cost calculation always succeeds.+ It typically represents the base pricing for standard usage patterns.+ type: boolean+ priority:+ docs: |+ Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).++ The default tier must always have priority 0. Conditional tiers should have priority 1, 2, 3, etc.++ Example ordering:+ - Priority 0: Default tier (no conditions, always matches as fallback)+ - Priority 1: High usage tier (e.g., >200K tokens)+ - Priority 2: Medium usage tier (e.g., >100K tokens)++ This ensures more specific conditions are checked before general ones.+ type: integer+ conditions:+ docs: |+ Array of conditions that must ALL be met for this tier to match (AND logic).++ The default tier must have an empty conditions array. Conditional tiers should have one or more conditions+ that define when this tier's pricing applies.++ Multiple conditions enable complex matching scenarios (e.g., "high input tokens AND low output tokens").+ type: list<PricingTierCondition>+ prices:+ docs: |+ Prices (USD) by usage type for this tier.++ Common usage types: "input", "output", "total", "request", "image"+ Prices are specified in USD per unit (e.g., per token, per request, per second).++ Example: {"input": 0.000003, "output": 0.000015} means $3 per million input tokens and $15 per million output tokens.+ type: map<string, double>++ PricingTierInput:+ docs: |+ Input schema for creating a pricing tier. The tier ID will be automatically generated server-side.++ When creating a model with pricing tiers:+ - Exactly one tier must have isDefault=true (the fallback tier)+ - The default tier must have priority=0 and conditions=[]+ - All tier names and priorities must be unique within the model+ - Each tier must define at least one price++ See PricingTier for detailed information about how tiers work and why they're useful.+ properties:+ name:+ docs: |+ Name of the pricing tier for display and identification purposes.++ Must be unique within the model. Common patterns: "Standard", "High Volume Tier", "Extended Context"+ type: string+ isDefault:+ docs: |+ Whether this is the default tier. Exactly one tier per model must be marked as default.++ Requirements for default tier:+ - Must have isDefault=true+ - Must have priority=0+ - Must have empty conditions array (conditions=[])++ The default tier acts as a fallback when no conditional tiers match.+ type: boolean+ priority:+ docs: |+ Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).++ Must be unique within the model. The default tier must have priority=0.+ Conditional tiers should use priority 1, 2, 3, etc. based on their specificity.+ type: integer+ conditions:+ docs: |+ Array of conditions that must ALL be met for this tier to match (AND logic).++ The default tier must have an empty array (conditions=[]).+ Conditional tiers should define one or more conditions that specify when this tier's pricing applies.++ Each condition specifies a regex pattern, operator, and threshold value for matching against usage details.+ type: list<PricingTierCondition>+ prices:+ docs: |+ Prices (USD) by usage type for this tier. At least one price must be defined.++ Common usage types: "input", "output", "total", "request", "image"+ Prices are in USD per unit (e.g., per token).++ Example: {"input": 0.000003, "output": 0.000015} represents $3 per million input tokens and $15 per million output tokens.+ type: map<string, double>++ PricingTierOperator:+ docs: Comparison operators for pricing tier conditions+ enum:+ - gt+ - gte+ - lt+ - lte+ - eq+ - neq+# UtilitiesModelUsageUnit:docs: Unit of usage in Langfusediff --git a/fern/apis/server/definition/models.yml b/fern/apis/server/definition/models.ymlindex 743d1e2364..374c72a604 100644--- a/fern/apis/server/definition/models.yml+++ b/fern/apis/server/definition/models.yml@@ -60,14 +60,35 @@ types:docs: Unit used by this model.type: optional<commons.ModelUsageUnit>inputPrice:- docs: Price (USD) per input unit+ docs: Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit. Creates a default tier if pricingTiers not provided.type: optional<double>outputPrice:- docs: Price (USD) per output unit+ docs: Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit. Creates a default tier if pricingTiers not provided.type: optional<double>totalPrice:- docs: Price (USD) per total units. Cannot be set if input or output price is set.+ docs: Deprecated. Use 'pricingTiers' instead. Price (USD) per total units. Cannot be set if input or output price is set. Creates a default tier if pricingTiers not provided.type: optional<double>+ pricingTiers:+ docs: |+ Optional. Array of pricing tiers for this model.++ Use pricing tiers for all models - both those with threshold-based pricing variations and those with simple flat pricing:++ - For models with standard flat pricing: Create a single default tier with your prices+ (e.g., one tier with isDefault=true, priority=0, conditions=[], and your standard prices)++ - For models with threshold-based pricing: Create a default tier plus additional conditional tiers+ (e.g., default tier for standard usage + high-volume tier for usage above certain thresholds)++ Requirements:+ - Cannot be provided with flat prices (inputPrice/outputPrice/totalPrice) - use one approach or the other+ - Must include exactly one default tier with isDefault=true, priority=0, and conditions=[]+ - All tier names and priorities must be unique within the model+ - Each tier must define at least one price++ If omitted, you must provide flat prices instead (inputPrice/outputPrice/totalPrice),+ which will automatically create a single default tier named "Standard".+ type: optional<list<commons.PricingTierInput>>tokenizerId:docs: Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.type: optional<string>diff --git a/packages/shared/clickhouse/migrations/clustered/0031_add_usage_pricing_tier_columns.down.sql b/packages/shared/clickhouse/migrations/clustered/0031_add_usage_pricing_tier_columns.down.sqlnew file mode 100644index 0000000000..3165573eab--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0031_add_usage_pricing_tier_columns.down.sql@@ -0,0 +1,2 @@+ALTER TABLE observations ON CLUSTER default DROP COLUMN IF EXISTS usage_pricing_tier_name;+ALTER TABLE observations ON CLUSTER default DROP COLUMN IF EXISTS usage_pricing_tier_id;diff --git a/packages/shared/clickhouse/migrations/clustered/0031_add_usage_pricing_tier_columns.up.sql b/packages/shared/clickhouse/migrations/clustered/0031_add_usage_pricing_tier_columns.up.sqlnew file mode 100644index 0000000000..03a4a5ebf0--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0031_add_usage_pricing_tier_columns.up.sql@@ -0,0 +1,2 @@+ALTER TABLE observations ON CLUSTER default ADD COLUMN usage_pricing_tier_id Nullable(String) AFTER total_cost;+ALTER TABLE observations ON CLUSTER default ADD COLUMN usage_pricing_tier_name Nullable(String) AFTER usage_pricing_tier_id;diff --git a/packages/shared/clickhouse/migrations/unclustered/0031_add_usage_pricing_tier_columns.down.sql b/packages/shared/clickhouse/migrations/unclustered/0031_add_usage_pricing_tier_columns.down.sqlnew file mode 100644index 0000000000..9dc3a6e6db--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0031_add_usage_pricing_tier_columns.down.sql@@ -0,0 +1,2 @@+ALTER TABLE observations DROP COLUMN IF EXISTS usage_pricing_tier_name;+ALTER TABLE observations DROP COLUMN IF EXISTS usage_pricing_tier_id;diff --git a/packages/shared/clickhouse/migrations/unclustered/0031_add_usage_pricing_tier_columns.up.sql b/packages/shared/clickhouse/migrations/unclustered/0031_add_usage_pricing_tier_columns.up.sqlnew file mode 100644index 0000000000..146422b86c--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0031_add_usage_pricing_tier_columns.up.sql@@ -0,0 +1,2 @@+ALTER TABLE observations ADD COLUMN usage_pricing_tier_id Nullable(String) AFTER total_cost;+ALTER TABLE observations ADD COLUMN usage_pricing_tier_name Nullable(String) AFTER usage_pricing_tier_id;diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex 3cb7e239cc..ebbe78c474 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -38,26 +38,25 @@ fi# Ensure CLICKHOUSE_DB is setif [ -z "${CLICKHOUSE_DB}" ]; then- export CLICKHOUSE_DB="default"+ export CLICKHOUSE_DB="default"fi# Parse the CLICKHOUSE_MIGRATION_URL to extract host and port# Expected format: clickhouse://localhost:9000if [[ $CLICKHOUSE_MIGRATION_URL =~ ^clickhouse://([^:]+):([0-9]+)$ ]]; then- CLICKHOUSE_HOST="${BASH_REMATCH[1]}"- CLICKHOUSE_PORT="${BASH_REMATCH[2]}"+ CLICKHOUSE_HOST="${BASH_REMATCH[1]}"+ CLICKHOUSE_PORT="${BASH_REMATCH[2]}"elif [[ $CLICKHOUSE_MIGRATION_URL =~ ^clickhouse://([^:]+)$ ]]; then- CLICKHOUSE_HOST="${BASH_REMATCH[1]}"- CLICKHOUSE_PORT="9000" # Default native protocol port+ CLICKHOUSE_HOST="${BASH_REMATCH[1]}"+ CLICKHOUSE_PORT="9000" # Default native protocol portelse- echo "Error: Could not parse CLICKHOUSE_MIGRATION_URL: ${CLICKHOUSE_MIGRATION_URL}"- exit 1+ echo "Error: Could not parse CLICKHOUSE_MIGRATION_URL: ${CLICKHOUSE_MIGRATION_URL}"+ exit 1fi-if ! command -v clickhouse &> /dev/null-then- echo "Error: clickhouse binary could not be found. Please install ClickHouse client tools."- exit 1+if ! command -v clickhouse &>/dev/null; then+ echo "Error: clickhouse binary could not be found. Please install ClickHouse client tools."+ exit 1fiecho "Creating development tables in ClickHouse..."@@ -101,6 +100,8 @@ CREATE TABLE IF NOT EXISTS observations_batch_stagingprovided_cost_details Map(LowCardinality(String), Decimal64(12)),cost_details Map(LowCardinality(String), Decimal64(12)),total_cost Nullable(Decimal64(12)),+ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),completion_start_time Nullable(DateTime64(3)),prompt_id Nullable(String),prompt_name Nullable(String),@@ -190,6 +191,8 @@ CREATE TABLE IF NOT EXISTS eventscalculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),total_cost Decimal(18, 12) ALIAS cost_details_json.total,+ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),-- I/Oinput String CODEC(ZSTD(3)),diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 75671f6c2e..145d9f4a34 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -97,6 +97,7 @@"next-auth": "^4.24.12","nodemailer": "^7.0.10","prisma-extension-kysely": "^3.0.0",+ "safe-regex2": "^5.0.0","uuid": "^9.0.1","winston": "^3.15.0","zod": "^3.25.62",diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex f1a58b3017..36c8897037 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -741,9 +741,20 @@ export type Price = {updated_at: Generated<Timestamp>;model_id: string;project_id: string | null;+ pricing_tier_id: string;usage_type: string;price: string;};+export type PricingTier = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ model_id: string;+ name: string;+ is_default: Generated<boolean>;+ priority: number;+ conditions: unknown;+};export type Project = {id: string;org_id: string;@@ -944,6 +955,7 @@ export type DB = {pending_deletions: PendingDeletion;posthog_integrations: PosthogIntegration;prices: Price;+ pricing_tiers: PricingTier;project_memberships: ProjectMembership;projects: Project;prompt_dependencies: PromptDependency;diff --git a/packages/shared/prisma/migrations/20251120105316_add_pricing_tiers/migration.sql b/packages/shared/prisma/migrations/20251120105316_add_pricing_tiers/migration.sqlnew file mode 100644index 0000000000..7783289c14--- /dev/null+++ b/packages/shared/prisma/migrations/20251120105316_add_pricing_tiers/migration.sql@@ -0,0 +1,63 @@+BEGIN;++-- CreateTable+CREATE TABLE "pricing_tiers" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "model_id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "is_default" BOOLEAN NOT NULL DEFAULT false,+ "priority" INTEGER NOT NULL,+ "conditions" JSONB NOT NULL,++ CONSTRAINT "pricing_tiers_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "pricing_tiers_model_id_priority_key" ON "pricing_tiers"("model_id", "priority");++-- CreateIndex+CREATE UNIQUE INDEX "pricing_tiers_model_id_name_key" ON "pricing_tiers"("model_id", "name");++-- AddForeignKey+ALTER TABLE "pricing_tiers" ADD CONSTRAINT "pricing_tiers_model_id_fkey" FOREIGN KEY ("model_id") REFERENCES "models"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AlterTable+ALTER TABLE "prices" ADD COLUMN "pricing_tier_id" TEXT;++-- Data Migration: Create default pricing tiers with DETERMINISTIC IDs+-- Pattern: {model_id}_tier_default+INSERT INTO "pricing_tiers" (id, model_id, name, is_default, priority, conditions)+SELECT+ model_id || '_tier_default',+ model_id,+ 'Standard',+ TRUE,+ 0,+ '[]'::jsonb+FROM (+ SELECT DISTINCT model_id+ FROM prices+ WHERE pricing_tier_id IS NULL+) AS distinct_models+ON CONFLICT (id) DO NOTHING;++-- Data Migration: Link existing prices to their default tiers using deterministic IDs+UPDATE prices+SET pricing_tier_id = model_id || '_tier_default'+WHERE pricing_tier_id IS NULL;++-- AlterTable: Make pricing_tier_id NOT NULL+ALTER TABLE "prices" ALTER COLUMN "pricing_tier_id" SET NOT NULL;++-- AddForeignKey+ALTER TABLE "prices" ADD CONSTRAINT "prices_pricing_tier_id_fkey" FOREIGN KEY ("pricing_tier_id") REFERENCES "pricing_tiers"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- DropIndex+DROP INDEX IF EXISTS "prices_model_id_usage_type_key";++-- CreateIndex+CREATE UNIQUE INDEX "prices_model_id_usage_type_pricing_tier_id_key" ON "prices"("model_id", "usage_type", "pricing_tier_id");++COMMIT;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 74cd602800..28783f194c 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -850,6 +850,7 @@ model Model {tokenizerId String? @map("tokenizer_id")tokenizerConfig Json? @map("tokenizer_config")Price Price[]+ pricingTiers PricingTier[]@@unique([projectId, modelName, startDate, unit])@@index(modelName)@@ -864,13 +865,35 @@ model Price {Model Model @relation(fields: [modelId], references: [id], onDelete: Cascade)projectId String? @map("project_id")project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)+ pricingTierId String @map("pricing_tier_id")+ pricingTier PricingTier @relation(fields: [pricingTierId], references: [id], onDelete: Cascade)usageType String @map("usage_type")price Decimal- @@unique([modelId, usageType])+ @@unique([modelId, usageType, pricingTierId])@@map("prices")}+model PricingTier {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ modelId String @map("model_id")+ model Model @relation(fields: [modelId], references: [id], onDelete: Cascade)++ name String @map("name")+ isDefault Boolean @default(false) @map("is_default")+ priority Int @map("priority")+ conditions Json @map("conditions") @db.JsonB++ prices Price[]++ @@unique([modelId, priority])+ @@unique([modelId, name])+ @@map("pricing_tiers")+}+enum AuditLogRecordType {USERAPI_KEYdiff --git a/packages/shared/src/domain/observations.ts b/packages/shared/src/domain/observations.tsindex bde0205e09..d5098659bc 100644--- a/packages/shared/src/domain/observations.ts+++ b/packages/shared/src/domain/observations.ts@@ -90,6 +90,9 @@ export const ObservationSchema = z.object({inputUsage: z.number(),outputUsage: z.number(),totalUsage: z.number(),+ // pricing tier information+ usagePricingTierId: z.string().nullable(),+ usagePricingTierName: z.string().nullable(),});export type Observation = z.infer<typeof ObservationSchema>;diff --git a/packages/shared/src/features/model-pricing/index.ts b/packages/shared/src/features/model-pricing/index.tsnew file mode 100644index 0000000000..99455b8180--- /dev/null+++ b/packages/shared/src/features/model-pricing/index.ts@@ -0,0 +1 @@+export * from "./validation";diff --git a/packages/shared/src/features/model-pricing/validation.ts b/packages/shared/src/features/model-pricing/validation.tsnew file mode 100644index 0000000000..06a52d5594--- /dev/null+++ b/packages/shared/src/features/model-pricing/validation.ts@@ -0,0 +1,251 @@+import safeRegex from "safe-regex2";+import { z } from "zod/v4";++/**+ * Shared validation for pricing tier regex patterns and conditions+ * Used by both Public API and tRPC routes+ */++/**+ * Validates a regex pattern for safety and correctness+ * @throws Error with descriptive message if pattern is invalid+ */+export function validateRegexPattern(pattern: string): void {+ // Length check+ if (pattern.length > 200) {+ throw new Error("Pattern exceeds maximum length of 200 characters");+ }++ // Check for empty pattern+ if (pattern.length === 0) {+ throw new Error("Pattern cannot be empty");+ }++ // Syntax check+ try {+ new RegExp(pattern);+ } catch (e) {+ throw new Error(+ `Invalid regex syntax: ${e instanceof Error ? e.message : String(e)}`,+ );+ }++ // Safety check (catastrophic backtracking)+ if (!safeRegex(pattern)) {+ throw new Error(+ "Pattern may cause catastrophic backtracking. Please simplify your regex.",+ );+ }+}++/**+ * Pricing tier condition schema (shared across API and tRPC)+ */+export const PricingTierConditionSchema = z.object({+ usageDetailPattern: z+ .string()+ .min(1, "Pattern cannot be empty")+ .max(200, "Pattern exceeds maximum length of 200 characters")+ .refine(+ (pattern) => {+ try {+ validateRegexPattern(pattern);+ return true;+ } catch {+ return false;+ }+ },+ {+ message:+ "Invalid regex pattern: must be valid regex and not cause catastrophic backtracking",+ },+ ),+ operator: z.enum(["gt", "gte", "lt", "lte", "eq", "neq"]),+ value: z.number().nonnegative(),+ caseSensitive: z.boolean().default(false),+});++export type PricingTierCondition = z.infer<typeof PricingTierConditionSchema>;++/**+ * Pricing tier input schema (for creation - no ID)+ * Used when creating new tiers via API or tRPC+ */+export const PricingTierInputSchema = z.object({+ name: z+ .string()+ .min(1, "Name cannot be empty")+ .max(100, "Name exceeds maximum length of 100 characters"),+ isDefault: z.boolean().default(false),+ priority: z+ .number()+ .int("Priority must be an integer")+ .min(0, "Priority must be non-negative")+ .max(999, "Priority cannot exceed 999"),+ conditions: z.array(PricingTierConditionSchema),+ prices: z.record(+ z.string(),+ z.number().nonnegative("Price must be non-negative"),+ ),+});++export type PricingTierInput = z.infer<typeof PricingTierInputSchema>;++/**+ * Validates an array of pricing tiers+ * Ensures:+ * - Exactly one default tier+ * - Unique priorities+ * - Unique names+ * - Default tier has priority 0 and empty conditions+ */+export function validatePricingTiers(+ tiers: PricingTierInput[],+): { valid: true } | { valid: false; error: string } {+ if (tiers.length === 0) {+ return { valid: false, error: "At least one pricing tier is required" };+ }++ // Check for exactly one default tier+ const defaultTiers = tiers.filter((t) => t.isDefault);+ if (defaultTiers.length === 0) {+ return {+ valid: false,+ error: "Exactly one pricing tier must have isDefault: true",+ };+ }+ if (defaultTiers.length > 1) {+ return {+ valid: false,+ error:+ "Only one pricing tier can have isDefault: true, found " ++ defaultTiers.length,+ };+ }++ // Validate default tier has priority 0 and empty conditions+ const defaultTier = defaultTiers[0];+ if (defaultTier.priority !== 0) {+ return {+ valid: false,+ error: "Default pricing tier must have priority: 0",+ };+ }+ if (defaultTier.conditions.length > 0) {+ return {+ valid: false,+ error: "Default pricing tier must have empty conditions array",+ };+ }++ // Validate non-default tiers have at least 1 condition+ for (const tier of tiers) {+ if (!tier.isDefault && tier.conditions.length === 0) {+ return {+ valid: false,+ error: `Non-default pricing tier "${tier.name}" must have at least one condition`,+ };+ }+ }++ // Check for unique priorities+ const priorities = tiers.map((t) => t.priority);+ const uniquePriorities = new Set(priorities);+ if (priorities.length !== uniquePriorities.size) {+ return {+ valid: false,+ error: "Pricing tier priorities must be unique within a model",+ };+ }++ // Check for unique names+ const names = tiers.map((t) => t.name);+ const uniqueNames = new Set(names);+ if (names.length !== uniqueNames.size) {+ return { valid: false, error: "Pricing tier names must be unique" };+ }++ // Validate all conditions have valid regex patterns+ for (const tier of tiers) {+ for (const condition of tier.conditions) {+ try {+ validateRegexPattern(condition.usageDetailPattern);+ } catch (error) {+ return {+ valid: false,+ error: `Invalid regex pattern in tier "${tier.name}": ${+ error instanceof Error ? error.message : String(error)+ }`,+ };+ }+ }+ }++ // Validate all tiers have at least one price+ for (const tier of tiers) {+ if (Object.keys(tier.prices).length === 0) {+ return {+ valid: false,+ error: `Pricing tier "${tier.name}" must have at least one price defined`,+ };+ }+ }++ // Validate all tiers have the same usage keys+ if (tiers.length > 1) {+ const defaultTierForKeys = tiers.find((t) => t.isDefault);+ if (!defaultTierForKeys) {+ return { valid: false, error: "No default tier found" };+ }++ const defaultKeys = Object.keys(defaultTierForKeys.prices).sort();++ for (const tier of tiers) {+ if (tier.isDefault) continue;++ const tierKeys = Object.keys(tier.prices).sort();++ // Check if keys match+ if (+ defaultKeys.length !== tierKeys.length ||+ !defaultKeys.every((key, index) => key === tierKeys[index])+ ) {+ return {+ valid: false,+ error: `Pricing tier "${tier.name}" must have the same usage keys as the default tier. Expected: [${defaultKeys.join(", ")}], Got: [${tierKeys.join(", ")}]`,+ };+ }+ }+ }++ return { valid: true };+}++/**+ * Validates that pricing tiers can be used with flat prices+ * Returns error if both are provided+ */+export function validatePricingMethod(params: {+ hasFlatPrices: boolean;+ hasPricingTiers: boolean;+}): { valid: true } | { valid: false; error: string } {+ const { hasFlatPrices, hasPricingTiers } = params;++ if (hasFlatPrices && hasPricingTiers) {+ return {+ valid: false,+ error:+ "Cannot provide both flat prices (inputPrice/outputPrice/totalPrice) and pricingTiers",+ };+ }++ if (!hasFlatPrices && !hasPricingTiers) {+ return {+ valid: false,+ error:+ "Must provide either flat prices (inputPrice/outputPrice/totalPrice) OR pricingTiers",+ };+ }++ return { valid: true };+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 602a27eea8..d6d4858b63 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -52,6 +52,9 @@ export * from "./features/experiments/utils";// datasetsexport * from "./features/datasets/validation";+// model pricing+export * from "./features/model-pricing/";+// promptsexport * from "./features/prompts/parsePromptDependencyTags";export * from "./features/prompts/validation";diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex aa24a59ed4..c59b0e2e39 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -40,6 +40,7 @@ export * from "../server/ingestion/modelMatch";export * from "./ingestion/processEventBatch";export * from "../server/ingestion/validateAndInflateScore";export * from "../server/queries/public-api-filter-builder";+export * from "../server/pricing-tiers";export * from "./redis/redis";export * from "./redis/traceUpsert";export * from "./redis/createEvalQueue";diff --git a/packages/shared/src/server/ingestion/modelMatch.ts b/packages/shared/src/server/ingestion/modelMatch.tsindex 92d50e07f6..18134e700e 100644--- a/packages/shared/src/server/ingestion/modelMatch.ts+++ b/packages/shared/src/server/ingestion/modelMatch.ts@@ -1,4 +1,4 @@-import { Model, Price, Prisma } from "../../";+import { Model, Prisma } from "../../";import {instrumentAsync,logger,@@ -10,6 +10,7 @@ import {import { env } from "../../env";import { Decimal } from "decimal.js";import { prisma } from "../../db";+import type { PricingTierWithPrices } from "../pricing-tiers";export type ModelMatchProps = {projectId: string;@@ -18,7 +19,7 @@ export type ModelMatchProps = {export type ModelWithPrices = {model: Model | null;- prices: Price[];+ pricingTiers: PricingTierWithPrices[];};const MODEL_MATCH_CACHE_LOCKED_KEY = "LOCK:model-match-clear";@@ -36,7 +37,7 @@ export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {span.setAttribute("model_match_source", "redis");if (cachedResult.model === null) {- return { model: null, prices: [] };+ return { model: null, pricingTiers: [] };} else {logger.debug(`Found model name ${cachedResult.model?.modelName} (id: ${cachedResult.model?.id}) for project ${p.projectId} and model ${p.model}`,@@ -51,8 +52,8 @@ export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {const postgresModel = await findModelInPostgres(p);if (postgresModel && env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {- const prices = await findPricesForModel(postgresModel.id);- await addModelWithPricesToRedis(p, postgresModel, prices);+ const pricingTiers = await findPricingTiersForModel(postgresModel.id);+ await addModelWithPricingTiersToRedis(p, postgresModel, pricingTiers);span.setAttribute("matched_model_id", postgresModel.id);span.setAttribute("model_match_source", "postgres");@@ -61,9 +62,9 @@ export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {logger.debug(`Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,);- return { model: postgresModel, prices };+ return { model: postgresModel, pricingTiers };} else if (postgresModel) {- const prices = await findPricesForModel(postgresModel.id);+ const pricingTiers = await findPricingTiersForModel(postgresModel.id);span.setAttribute("matched_model_id", postgresModel.id);span.setAttribute("model_match_source", "postgres");span.setAttribute("model_cache_set", "false");@@ -71,7 +72,7 @@ export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {logger.debug(`Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,);- return { model: postgresModel, prices };+ return { model: postgresModel, pricingTiers };} else {span.setAttribute("model_match_source", "none");@@ -83,7 +84,7 @@ export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {logger.debug(`Model not found for project ${p.projectId} and model ${p.model}`,);- return { model: null, prices: [] };+ return { model: null, pricingTiers: [] };}},);@@ -115,41 +116,53 @@ const getModelWithPricesFromRedis = async (recordIncrement("langfuse.model_match.cache_hit", 1);if (redisValue === NOT_FOUND_TOKEN) {- return { model: null, prices: [] };+ return { model: null, pricingTiers: [] };}const parsed = JSON.parse(redisValue);- // NEW FORMAT: { model: {...}, prices: [...] }- if (parsed.model !== undefined && parsed.prices !== undefined) {+ // NEW FORMAT: { model: {...}, pricingTiers: [...] }+ if (parsed.model !== undefined && parsed.pricingTiers !== undefined) {const model = redisModelToPrismaModel(JSON.stringify(parsed.model));- const prices = parsed.prices.map(- (p: any): Price => ({- ...p,- price: new Decimal(p.price),- createdAt: new Date(p.createdAt),- updatedAt: new Date(p.updatedAt),+ const pricingTiers: PricingTierWithPrices[] = parsed.pricingTiers.map(+ (tier: any) => ({+ ...tier,+ prices: tier.prices.map((p: any) => ({+ ...p,+ price: new Decimal(p.price),+ })),}),);- return { model, prices };++ return { model, pricingTiers };}- // OLD FORMAT: just the model (backwards compatible)- // Fetch prices and update cache- const model = redisModelToPrismaModel(redisValue);- const prices = await findPricesForModel(model.id);-- // Update cache with new format asynchronously (don't await)- if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {- addModelWithPricesToRedis(p, model, prices).catch((error) => {- logger.error(- `Error updating cache with prices for ${JSON.stringify(p)}`,- error,+ // OLD FORMAT: { model: {...}, prices: [...] } (backwards compatible)+ // Convert old format to new format with pricing tiers+ if (parsed.model !== undefined && parsed.prices !== undefined) {+ const model = redisModelToPrismaModel(JSON.stringify(parsed.model));+ const pricingTiers = await findPricingTiersForModel(model.id);++ // Update cache with new format asynchronously (don't await)+ if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {+ addModelWithPricingTiersToRedis(p, model, pricingTiers).catch(+ (error) => {+ logger.error(+ `Error updating cache with pricing tiers for ${JSON.stringify(p)}`,+ error,+ );+ },);- });+ }++ return { model, pricingTiers };}- return { model, prices };+ // Unknown format+ logger.warn(+ `Unknown cache format for model match: ${JSON.stringify(parsed)}`,+ );+ return null;} catch (error) {logger.error(`Error getting model for ${JSON.stringify(p)} from Redis`,@@ -159,8 +172,30 @@ const getModelWithPricesFromRedis = async (}};-export async function findPricesForModel(modelId: string): Promise<Price[]> {- return (await prisma.price.findMany({ where: { modelId } })) ?? [];+export async function findPricingTiersForModel(+ modelId: string,+): Promise<PricingTierWithPrices[]> {+ const tiers = await prisma.pricingTier.findMany({+ where: { modelId },+ include: {+ prices: {+ select: {+ usageType: true,+ price: true,+ },+ },+ },+ orderBy: { priority: "asc" },+ });++ return tiers.map((tier) => ({+ id: tier.id,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions as any, // Cast from JsonValue to PricingTierCondition[]+ prices: tier.prices,+ }));}export async function findModelInPostgres(@@ -224,22 +259,22 @@ const addModelNotFoundTokenToRedis = async (p: ModelMatchProps) => {}};-const addModelWithPricesToRedis = async (+const addModelWithPricingTiersToRedis = async (p: ModelMatchProps,model: Model,- prices: Price[],+ pricingTiers: PricingTierWithPrices[],) => {try {const key = getRedisModelKey(p);await redis?.set(key,- JSON.stringify({ model, prices }),+ JSON.stringify({ model, pricingTiers }),"EX",env.LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS,);} catch (error) {logger.error(- `Error adding model with prices for ${JSON.stringify(p)} to Redis`,+ `Error adding model with pricing tiers for ${JSON.stringify(p)} to Redis`,error,);}diff --git a/packages/shared/src/server/pricing-tiers/index.ts b/packages/shared/src/server/pricing-tiers/index.tsnew file mode 100644index 0000000000..31ae589b33--- /dev/null+++ b/packages/shared/src/server/pricing-tiers/index.ts@@ -0,0 +1,8 @@+/**+ * Shared pricing tier utilities+ * Export validation, types, and other utilities for use across the codebase+ */++export type { PricingTierMatchResult, PricingTierWithPrices } from "./types";++export { matchPricingTier } from "./matcher";diff --git a/packages/shared/src/server/pricing-tiers/matcher.ts b/packages/shared/src/server/pricing-tiers/matcher.tsnew file mode 100644index 0000000000..4d7a1c9a53--- /dev/null+++ b/packages/shared/src/server/pricing-tiers/matcher.ts@@ -0,0 +1,125 @@+import { PricingTierCondition } from "../../features/model-pricing";+import type { PricingTierMatchResult, PricingTierWithPrices } from "./types";++/**+ * Pricing tier matching algorithm+ * Evaluates conditions and selects the appropriate tier based on usage details+ */++/**+ * Evaluates a single condition against usage details+ * Sums all usage_details keys matching the pattern and compares to threshold+ */+function evaluateCondition(+ condition: PricingTierCondition,+ usageDetails: Record<string, number>,+): boolean {+ try {+ // Build regex with case sensitivity flag+ const flags = condition.caseSensitive ? "" : "i";+ const regex = new RegExp(condition.usageDetailPattern, flags);++ // Find all keys matching the pattern+ const matchingKeys = Object.keys(usageDetails).filter((key) =>+ regex.test(key),+ );++ // Sum values of matching keys+ const sum = matchingKeys.reduce(+ (acc, key) => acc + (usageDetails[key] || 0),+ 0,+ );++ // Compare sum to threshold+ switch (condition.operator) {+ case "gt":+ return sum > condition.value;+ case "gte":+ return sum >= condition.value;+ case "lt":+ return sum < condition.value;+ case "lte":+ return sum <= condition.value;+ case "eq":+ return sum === condition.value;+ case "neq":+ return sum !== condition.value;+ default:+ return false;+ }+ } catch (error) {+ return false; // Fail-safe: condition fails on error+ }+}++/**+ * Evaluates all conditions for a tier (AND logic)+ * Returns true only if ALL conditions pass+ */+function evaluateConditions(+ conditions: PricingTierCondition[],+ usageDetails: Record<string, number>,+): boolean {+ // Empty conditions should never match (except for default tiers)+ if (conditions.length === 0) {+ return false;+ }++ // All conditions must pass (AND logic)+ return conditions.every((condition) =>+ evaluateCondition(condition, usageDetails),+ );+}++/**+ * Matches usage details against pricing tiers and returns applicable tier with prices+ *+ * Algorithm:+ * 1. Filter out default tier and sort remaining tiers by priority (ascending)+ * 2. Evaluate each tier's conditions in priority order+ * 3. Return first tier where all conditions match+ * 4. If no match, fall back to default tier+ * 5. If no default tier exists, return null (should not happen after migration)+ *+ * @param tiers - Array of pricing tiers with prices+ * @param usageDetails - Usage details from the observation (e.g., { input_tokens: 250000, output_tokens: 2000 })+ * @returns Matched tier with prices, or null if no match and no default+ */+export function matchPricingTier(+ tiers: PricingTierWithPrices[],+ usageDetails: Record<string, number>,+): PricingTierMatchResult | null {+ // 1. Filter and sort non-default tiers by priority (ascending)+ const sortedTiers = tiers+ .filter((tier) => !tier.isDefault)+ .sort((a, b) => a.priority - b.priority);++ // 2. Try to match each tier in priority order+ for (const tier of sortedTiers) {+ if (evaluateConditions(tier.conditions, usageDetails)) {+ return {+ pricingTierId: tier.id,+ pricingTierName: tier.name,+ prices: Object.fromEntries(+ tier.prices.map((p) => [p.usageType, p.price]),+ ),+ };+ }+ }++ // 3. Fall back to default tier+ const defaultTier = tiers.find((tier) => tier.isDefault);++ if (defaultTier) {+ return {+ pricingTierId: defaultTier.id,+ pricingTierName: defaultTier.name,+ prices: Object.fromEntries(+ defaultTier.prices.map((p) => [p.usageType, p.price]),+ ),+ };+ }++ // 4. No match and no default (should not happen after migration)+ return null;+}diff --git a/packages/shared/src/server/pricing-tiers/types.ts b/packages/shared/src/server/pricing-tiers/types.tsnew file mode 100644index 0000000000..2b58f03a03--- /dev/null+++ b/packages/shared/src/server/pricing-tiers/types.ts@@ -0,0 +1,31 @@+import { type Decimal } from "decimal.js";+import { PricingTierCondition } from "../../features/model-pricing";++/**+ * Shared types for pricing tier functionality+ * Used across Public API, tRPC, and internal services+ */++/**+ * Result of pricing tier matching+ */+export type PricingTierMatchResult = {+ pricingTierId: string;+ pricingTierName: string;+ prices: Record<string, Decimal>; // usageType -> price+};++/**+ * Pricing tier with prices included (from database)+ */+export type PricingTierWithPrices = {+ id: string;+ name: string;+ isDefault: boolean;+ priority: number;+ conditions: PricingTierCondition[];+ prices: Array<{+ usageType: string;+ price: Decimal;+ }>;+};diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex 19d5b37247..73c3ca6926 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -48,6 +48,8 @@ export const observationRecordBaseSchema = z.object({internal_model_id: z.string().nullish(),model_parameters: z.string().nullish(),total_cost: z.number().nullish(),+ usage_pricing_tier_id: z.string().nullish(),+ usage_pricing_tier_name: z.string().nullish(),prompt_id: z.string().nullish(),prompt_name: z.string().nullish(),prompt_version: z.number().nullish(),diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 9db9c94940..a495f2a60c 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -164,6 +164,8 @@ export const getObservationsForTrace = async <IncludeIO extends boolean>(provided_cost_details,cost_details,total_cost,+ usage_pricing_tier_id,+ usage_pricing_tier_name,completion_start_time,prompt_id,prompt_name,@@ -279,6 +281,8 @@ export const getObservationForTraceIdByName = async ({provided_cost_details,cost_details,total_cost,+ usage_pricing_tier_id,+ usage_pricing_tier_name,completion_start_time,prompt_id,prompt_name,@@ -399,6 +403,8 @@ export const getObservationsById = async (provided_cost_details,cost_details,total_cost,+ usage_pricing_tier_id,+ usage_pricing_tier_name,completion_start_time,prompt_id,prompt_name,@@ -461,6 +467,8 @@ const getObservationByIdInternal = async ({provided_cost_details,cost_details,total_cost,+ usage_pricing_tier_id,+ usage_pricing_tier_name,completion_start_time,prompt_id,prompt_name,@@ -625,6 +633,8 @@ const getObservationsTableInternal = async <T>(o.updated_at as "updated_at",o.provided_model_name as "provided_model_name",o.total_cost as "total_cost",+ o.usage_pricing_tier_id as "usage_pricing_tier_id",+ o.usage_pricing_tier_name as "usage_pricing_tier_name",o.prompt_id as "prompt_id",o.prompt_name as "prompt_name",o.prompt_version as "prompt_version",diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.tsindex e773918ca0..1998dc6d06 100644--- a/packages/shared/src/server/repositories/observations_converters.ts+++ b/packages/shared/src/server/repositories/observations_converters.ts@@ -237,6 +237,14 @@ export function convertObservationPartial(: null,}),+ // Pricing tier fields+ ...(record.usage_pricing_tier_id !== undefined && {+ usagePricingTierId: record.usage_pricing_tier_id ?? null,+ }),+ ...(record.usage_pricing_tier_name !== undefined && {+ usagePricingTierName: record.usage_pricing_tier_name ?? null,+ }),+// Metrics (calculated fields)...((record.end_time !== undefined || record.start_time !== undefined) && {latency:@@ -299,6 +307,8 @@ export function convertObservationPartial(inputUsage: partial.inputUsage ?? 0,outputUsage: partial.outputUsage ?? 0,totalUsage: partial.totalUsage ?? 0,+ usagePricingTierId: partial.usagePricingTierId ?? null,+ usagePricingTierName: partial.usagePricingTierName ?? null,};}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 442fe7d468..598090f2b9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -258,6 +258,9 @@ importers:react:specifier: ~19.2.0version: 19.2.0+ safe-regex2:+ specifier: ^5.0.0+ version: 5.0.0uuid:specifier: ^9.0.1version: 9.0.1@@ -12033,6 +12036,10 @@ packages:resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w==}engines: {node: '>=14'}@@ -12111,6 +12118,9 @@ packages:resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-YwJwe5a51WlK7KbOJREPdjNrpViQBI3p4T50lfwPuDhZnE3XGVTlGvi+aolc5+RvxDD6bnUmjVsU9n1eboLUYw==}+resolution: {integrity: sha512-e2bDA2WJT0wxseVd4lsDP4+3ONX6HpMXQa1ZhFQ7SU+GjvORCmShbCMltrtIDfkYhVHrOcPtj+KhmDBdPdZD1g==}engines: {node: '>=10'}@@ -28524,6 +28534,8 @@ snapshots:onetime: 7.0.0signal-exit: 4.1.0+ [email protected]: {}+dependencies:'@types/request': 2.48.13@@ -28640,6 +28652,10 @@ snapshots:es-errors: 1.3.0is-regex: 1.2.1+ dependencies:+ ret: 0.5.0+diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex cec769a033..8d5696f3a3 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -6563,6 +6563,24 @@ components:description: >-Model definition used for transforming usage into USD cost and/ortokenization.+++ Models can have either simple flat pricing or tiered pricing:++ - Flat pricing: Single price per usage type (legacy, but still+ supported)++ - Tiered pricing: Multiple pricing tiers with conditional matching based+ on usage patterns+++ The pricing tiers approach is recommended for models with usage-based+ pricing variations.++ When using tiered pricing, the flat price fields (inputPrice,+ outputPrice, prices) are populated++ from the default tier for backward compatibility.properties:id:type: string@@ -6618,17 +6636,57 @@ components:JSON. See docs for more details.isLangfuseManaged:type: boolean+ createdAt:+ type: string+ format: date-time+ description: Timestamp when the model was createdprices:type: objectadditionalProperties:$ref: '#/components/schemas/ModelPrice'- description: Price (USD) by usage type+ description: >-+ Deprecated. Use 'pricingTiers' instead for models with usage-based+ pricing variations.+++ This field shows prices by usage type from the default pricing tier.+ Maintained for backward compatibility.++ If the model uses tiered pricing, this field will be populated from+ the default tier's prices.+ pricingTiers:+ type: array+ items:+ $ref: '#/components/schemas/PricingTier'+ description: >-+ Array of pricing tiers with conditional pricing based on usage+ thresholds.+++ Pricing tiers enable accurate cost tracking for models that charge+ different rates based on usage patterns++ (e.g., different rates for high-volume usage, large context windows,+ or cached tokens).+++ Each model must have exactly one default tier (isDefault=true,+ priority=0) that serves as a fallback.++ Additional conditional tiers can be defined with specific matching+ criteria.+++ If this array is empty, the model uses legacy flat pricing from the+ inputPrice/outputPrice/totalPrice fields.required:- id- modelName- matchPattern- isLangfuseManaged+ - createdAt- prices+ - pricingTiersModelPrice:title: ModelPricetype: object@@ -6638,6 +6696,332 @@ components:format: doublerequired:- price+ PricingTierCondition:+ title: PricingTierCondition+ type: object+ description: >-+ Condition for matching a pricing tier based on usage details. Used to+ implement tiered pricing models where costs vary based on usage+ thresholds.+++ How it works:++ 1. The regex pattern matches against usage detail keys (e.g.,+ "input_tokens", "input_cached")++ 2. Values of all matching keys are summed together++ 3. The sum is compared against the threshold value using the specified+ operator++ 4. All conditions in a tier must be met (AND logic) for the tier to+ match+++ Common use cases:++ - Threshold-based pricing: Match when accumulated usage exceeds a+ certain amount++ - Usage-type-specific pricing: Different rates for cached vs non-cached+ tokens, or input vs output++ - Volume-based pricing: Different rates based on total request or token+ count+ properties:+ usageDetailPattern:+ type: string+ description: >-+ Regex pattern to match against usage detail keys. All matching keys'+ values are summed for threshold comparison.+++ Examples:++ - "^input" matches "input", "input_tokens", "input_cached", etc.++ - "^(input|prompt)" matches both "input_tokens" and "prompt_tokens"++ - "_cache$" matches "input_cache", "output_cache", etc.+++ The pattern is case-insensitive by default. If no keys match, the+ sum is treated as zero.+ operator:+ $ref: '#/components/schemas/PricingTierOperator'+ description: >-+ Comparison operator to apply between the summed value and the+ threshold.+++ - gt: greater than (sum > threshold)++ - gte: greater than or equal (sum >= threshold)++ - lt: less than (sum < threshold)++ - lte: less than or equal (sum <= threshold)++ - eq: equal (sum == threshold)++ - neq: not equal (sum != threshold)+ value:+ type: number+ format: double+ description: >-+ Threshold value for comparison. For token-based pricing, this is+ typically the token count threshold (e.g., 200000 for a 200K token+ threshold).+ caseSensitive:+ type: boolean+ description: >-+ Whether the regex pattern matching is case-sensitive. Default is+ false (case-insensitive matching).+ required:+ - usageDetailPattern+ - operator+ - value+ - caseSensitive+ PricingTier:+ title: PricingTier+ type: object+ description: >-+ Pricing tier definition with conditional pricing based on usage+ thresholds.+++ Pricing tiers enable accurate cost tracking for LLM providers that+ charge different rates based on usage patterns.++ For example, some providers charge higher rates when context size+ exceeds certain thresholds.+++ How tier matching works:++ 1. Tiers are evaluated in ascending priority order (priority 1 before+ priority 2, etc.)++ 2. The first tier where ALL conditions match is selected++ 3. If no conditional tiers match, the default tier is used as a fallback++ 4. The default tier has priority 0 and no conditions+++ Why priorities matter:++ - Lower priority numbers are evaluated first, allowing you to define+ specific cases before general ones++ - Example: Priority 1 for "high usage" (>200K tokens), Priority 2 for+ "medium usage" (>100K tokens), Priority 0 for default++ - Without proper ordering, a less specific condition might match before+ a more specific one+++ Every model must have exactly one default tier to ensure cost+ calculation always succeeds.+ properties:+ id:+ type: string+ description: Unique identifier for the pricing tier+ name:+ type: string+ description: >-+ Name of the pricing tier for display and identification purposes.+++ Examples: "Standard", "High Volume Tier", "Large Context",+ "Extended Context Tier"+ isDefault:+ type: boolean+ description: >-+ Whether this is the default tier. Every model must have exactly one+ default tier with priority 0 and no conditions.+++ The default tier serves as a fallback when no conditional tiers+ match, ensuring cost calculation always succeeds.++ It typically represents the base pricing for standard usage+ patterns.+ priority:+ type: integer+ description: >-+ Priority for tier matching evaluation. Lower numbers = higher+ priority (evaluated first).+++ The default tier must always have priority 0. Conditional tiers+ should have priority 1, 2, 3, etc.+++ Example ordering:++ - Priority 0: Default tier (no conditions, always matches as+ fallback)++ - Priority 1: High usage tier (e.g., >200K tokens)++ - Priority 2: Medium usage tier (e.g., >100K tokens)+++ This ensures more specific conditions are checked before general+ ones.+ conditions:+ type: array+ items:+ $ref: '#/components/schemas/PricingTierCondition'+ description: >-+ Array of conditions that must ALL be met for this tier to match (AND+ logic).+++ The default tier must have an empty conditions array. Conditional+ tiers should have one or more conditions++ that define when this tier's pricing applies.+++ Multiple conditions enable complex matching scenarios (e.g., "high+ input tokens AND low output tokens").+ prices:+ type: object+ additionalProperties:+ type: number+ format: double+ description: >-+ Prices (USD) by usage type for this tier.+++ Common usage types: "input", "output", "total", "request", "image"++ Prices are specified in USD per unit (e.g., per token, per request,+ per second).+++ Example: {"input": 0.000003, "output": 0.000015} means $3 per+ million input tokens and $15 per million output tokens.+ required:+ - id+ - name+ - isDefault+ - priority+ - conditions+ - prices+ PricingTierInput:+ title: PricingTierInput+ type: object+ description: >-+ Input schema for creating a pricing tier. The tier ID will be+ automatically generated server-side.+++ When creating a model with pricing tiers:++ - Exactly one tier must have isDefault=true (the fallback tier)++ - The default tier must have priority=0 and conditions=[]++ - All tier names and priorities must be unique within the model++ - Each tier must define at least one price+++ See PricingTier for detailed information about how tiers work and why+ they're useful.+ properties:+ name:+ type: string+ description: >-+ Name of the pricing tier for display and identification purposes.+++ Must be unique within the model. Common patterns: "Standard+ Pricing", "High Volume Tier", "Extended Context"+ isDefault:+ type: boolean+ description: >-+ Whether this is the default tier. Exactly one tier per model must be+ marked as default.+++ Requirements for default tier:++ - Must have isDefault=true++ - Must have priority=0++ - Must have empty conditions array (conditions=[])+++ The default tier acts as a fallback when no conditional tiers match.+ priority:+ type: integer+ description: >-+ Priority for tier matching evaluation. Lower numbers = higher+ priority (evaluated first).+++ Must be unique within the model. The default tier must have+ priority=0.++ Conditional tiers should use priority 1, 2, 3, etc. based on their+ specificity.+ conditions:+ type: array+ items:+ $ref: '#/components/schemas/PricingTierCondition'+ description: >-+ Array of conditions that must ALL be met for this tier to match (AND+ logic).+++ The default tier must have an empty array (conditions=[]).++ Conditional tiers should define one or more conditions that specify+ when this tier's pricing applies.+++ Each condition specifies a regex pattern, operator, and threshold+ value for matching against usage details.+ prices:+ type: object+ additionalProperties:+ type: number+ format: double+ description: >-+ Prices (USD) by usage type for this tier. At least one price must be+ defined.+++ Common usage types: "input", "output", "total", "request", "image"++ Prices are in USD per unit (e.g., per token).+++ Example: {"input": 0.000003, "output": 0.000015} represents $3 per+ million input tokens and $15 per million output tokens.+ required:+ - name+ - isDefault+ - priority+ - conditions+ - prices+ PricingTierOperator:+ title: PricingTierOperator+ type: string+ enum:+ - gt+ - gte+ - lt+ - lte+ - eq+ - neq+ description: Comparison operators for pricing tier conditionsModelUsageUnit:title: ModelUsageUnittype: string@@ -7885,19 +8269,63 @@ components:type: numberformat: doublenullable: true- description: Price (USD) per input unit+ description: >-+ Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit.+ Creates a default tier if pricingTiers not provided.outputPrice:type: numberformat: doublenullable: true- description: Price (USD) per output unit+ description: >-+ Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit.+ Creates a default tier if pricingTiers not provided.totalPrice:type: numberformat: doublenullable: truedescription: >-- Price (USD) per total units. Cannot be set if input or output price- is set.+ Deprecated. Use 'pricingTiers' instead. Price (USD) per total units.+ Cannot be set if input or output price is set. Creates a default+ tier if pricingTiers not provided.+ pricingTiers:+ type: array+ items:+ $ref: '#/components/schemas/PricingTierInput'+ nullable: true+ description: >-+ Optional. Array of pricing tiers for this model.+++ Use pricing tiers for all models - both those with threshold-based+ pricing variations and those with simple flat pricing:+++ - For models with standard flat pricing: Create a single default+ tier with your prices+ (e.g., one tier with isDefault=true, priority=0, conditions=[], and your standard prices)++ - For models with threshold-based pricing: Create a default tier+ plus additional conditional tiers+ (e.g., default tier for standard usage + high-volume tier for usage above certain thresholds)++ Requirements:++ - Cannot be provided with flat prices+ (inputPrice/outputPrice/totalPrice) - use one approach or the other++ - Must include exactly one default tier with isDefault=true,+ priority=0, and conditions=[]++ - All tier names and priorities must be unique within the model++ - Each tier must define at least one price+++ If omitted, you must provide flat prices instead+ (inputPrice/outputPrice/totalPrice),++ which will automatically create a single default tier named+ "Standard".tokenizerId:type: stringnullable: truediff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex aabac4778c..9c73d4bf9e 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -1598,7 +1598,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"modelName\": \"example\",\n \"matchPattern\": \"example\",\n \"startDate\": \"1994-11-05T13:15:30Z\",\n \"unit\": \"CHARACTERS\",\n \"inputPrice\": 0,\n \"outputPrice\": 0,\n \"totalPrice\": 0,\n \"tokenizerId\": \"example\",\n \"tokenizerConfig\": \"UNKNOWN\"\n}",+ "raw": "{\n \"modelName\": \"example\",\n \"matchPattern\": \"example\",\n \"startDate\": \"1994-11-05T13:15:30Z\",\n \"unit\": \"CHARACTERS\",\n \"inputPrice\": 0,\n \"outputPrice\": 0,\n \"totalPrice\": 0,\n \"pricingTiers\": [\n {\n \"name\": \"example\",\n \"isDefault\": true,\n \"priority\": 0,\n \"conditions\": [\n {\n \"usageDetailPattern\": \"example\",\n \"operator\": \"gt\",\n \"value\": 0,\n \"caseSensitive\": true\n }\n ],\n \"prices\": {\n \"example\": 0\n }\n }\n ],\n \"tokenizerId\": \"example\",\n \"tokenizerConfig\": \"UNKNOWN\"\n}","options": {"raw": {"language": "json"diff --git a/web/src/__tests__/async/model-pricing-tiers.servertest.ts b/web/src/__tests__/async/model-pricing-tiers.servertest.tsnew file mode 100644index 0000000000..b17cec5123--- /dev/null+++ b/web/src/__tests__/async/model-pricing-tiers.servertest.ts@@ -0,0 +1,1127 @@+/** @jest-environment node */++import { randomUUID } from "crypto";+import { prisma } from "@langfuse/shared/src/db";+import {+ makeAPICall,+ makeZodVerifiedAPICall,+} from "@/src/__tests__/test-utils";+import {+ GetModelV1Response,+ GetModelsV1Response,+ PostModelsV1Response,+} from "@/src/features/public-api/types/models";++import {+ validateRegexPattern,+ validatePricingTiers,+ validatePricingMethod,+ type PricingTierInput,+} from "@langfuse/shared";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";++describe("validation methods", () => {+ describe("validateRegexPattern", () => {+ it("should accept valid regex patterns", () => {+ expect(() => validateRegexPattern("^input")).not.toThrow();+ expect(() => validateRegexPattern("^(input|prompt)")).not.toThrow();+ expect(() => validateRegexPattern("_cache")).not.toThrow();+ expect(() => validateRegexPattern(".*")).not.toThrow();+ });++ it("should reject empty patterns", () => {+ expect(() => validateRegexPattern("")).toThrow("Pattern cannot be empty");+ });++ it("should reject patterns exceeding 200 characters", () => {+ const longPattern = "a".repeat(201);+ expect(() => validateRegexPattern(longPattern)).toThrow(+ "Pattern exceeds maximum length of 200 characters",+ );+ });++ it("should reject invalid regex syntax", () => {+ expect(() => validateRegexPattern("(unclosed")).toThrow(+ "Invalid regex syntax",+ );+ expect(() => validateRegexPattern("[unclosed")).toThrow(+ "Invalid regex syntax",+ );+ expect(() => validateRegexPattern("(?invalid)")).toThrow(+ "Invalid regex syntax",+ );+ });++ it("should reject patterns that may cause catastrophic backtracking", () => {+ // Known unsafe pattern (exponential backtracking)+ expect(() => validateRegexPattern("(a+)+b")).toThrow(+ "catastrophic backtracking",+ );+ expect(() => validateRegexPattern("(x+x+)+y")).toThrow(+ "catastrophic backtracking",+ );+ });+ });++ describe("validatePricingTiers", () => {+ it("should accept valid pricing tiers", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 15.0 },+ },+ {+ name: "Large Context",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: { input: 6.0, output: 15.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(true);+ });++ it("should reject empty tier array", () => {+ const result = validatePricingTiers([]);+ expect(result.valid).toBe(false);+ expect(result.error).toContain("At least one pricing tier is required");+ });++ it("should reject tiers with no default", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Tier 1",+ isDefault: false,+ priority: 1,+ conditions: [],+ prices: { input: 3.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain(+ "Exactly one pricing tier must have isDefault: true",+ );+ });++ it("should reject tiers with multiple defaults", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Default 1",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Default 2",+ isDefault: true,+ priority: 1,+ conditions: [],+ prices: { input: 6.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain(+ "Only one pricing tier can have isDefault: true",+ );+ });++ it("should reject default tier with non-zero priority", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 1, // Should be 0+ conditions: [],+ prices: { input: 3.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain(+ "Default pricing tier must have priority: 0",+ );+ });++ it("should reject default tier with conditions", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 3.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain(+ "Default pricing tier must have empty conditions array",+ );+ });++ it("should reject duplicate priorities", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Tier 1",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 5.0 },+ },+ {+ name: "Tier 2",+ isDefault: false,+ priority: 1, // Duplicate!+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200,+ caseSensitive: false,+ },+ ],+ prices: { input: 7.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain("priorities must be unique");+ });++ it("should reject duplicate names", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Standard", // Duplicate!+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 5.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain("names must be unique");+ });++ it("should reject tier with invalid regex pattern", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Large Context",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "(unclosed", // Invalid regex+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 5.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain("Invalid regex pattern");+ });++ it("should reject tier with no prices", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: {}, // Empty!+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain("must have at least one price defined");+ });++ it("should reject non-default tier with no conditions", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Custom Tier",+ isDefault: false,+ priority: 1,+ conditions: [], // Invalid: non-default must have conditions+ prices: { input: 5.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain(+ 'Non-default pricing tier "Custom Tier" must have at least one condition',+ );+ });++ it("should reject tiers with mismatched usage keys", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 6.0 },+ },+ {+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100000,+ caseSensitive: false,+ },+ ],+ prices: { input: 2.5, output_tokens: 5.0 }, // Different keys!+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(false);+ expect(result.error).toContain(+ 'Pricing tier "High Volume" must have the same usage keys as the default tier',+ );+ expect(result.error).toContain("Expected: [input, output]");+ });++ it("should accept tiers with same keys in different order", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 6.0, cache_read: 1.5 },+ },+ {+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100000,+ caseSensitive: false,+ },+ ],+ prices: { cache_read: 1.0, input: 2.5, output: 5.0 }, // Same keys, different order+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(true);+ });++ it("should accept single default tier without key consistency check", () => {+ const tiers: PricingTierInput[] = [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 6.0 },+ },+ ];++ const result = validatePricingTiers(tiers);+ expect(result.valid).toBe(true);+ });+ });++ describe("validatePricingMethod", () => {+ it("should accept flat prices only", () => {+ const result = validatePricingMethod({+ hasFlatPrices: true,+ hasPricingTiers: false,+ });+ expect(result.valid).toBe(true);+ });++ it("should accept pricing tiers only", () => {+ const result = validatePricingMethod({+ hasFlatPrices: false,+ hasPricingTiers: true,+ });+ expect(result.valid).toBe(true);+ });++ it("should reject both flat prices and pricing tiers", () => {+ const result = validatePricingMethod({+ hasFlatPrices: true,+ hasPricingTiers: true,+ });+ expect(result.valid).toBe(false);+ expect(result.error).toContain("Cannot provide both");+ });++ it("should reject neither flat prices nor pricing tiers", () => {+ const result = validatePricingMethod({+ hasFlatPrices: false,+ hasPricingTiers: false,+ });+ expect(result.valid).toBe(false);+ expect(result.error).toContain("Must provide either");+ });+ });+});++describe("/models API Endpoints - Pricing Tiers", () => {+ describe("GET /models - with pricing tiers", () => {+ it("should return models with pricingTiers array", async () => {+ const uniqueId = randomUUID();+ const { auth, projectId } = await createOrgProjectAndApiKey();++ // Create model with pricing tiers+ const modelId = `model_${uniqueId}`;+ const model = await prisma.model.create({+ data: {+ id: modelId,+ projectId,+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ },+ });++ // Create default tier+ const defaultTier = await prisma.pricingTier.create({+ data: {+ modelId: model.id,+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ },+ });++ await prisma.price.createMany({+ data: [+ {+ modelId: model.id,+ projectId,+ pricingTierId: defaultTier.id,+ usageType: "input",+ price: 3.0,+ },+ {+ modelId: model.id,+ projectId,+ pricingTierId: defaultTier.id,+ usageType: "output",+ price: 15.0,+ },+ ],+ });++ // Create large context tier+ const largeTier = await prisma.pricingTier.create({+ data: {+ modelId: model.id,+ name: "Large Context",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ },+ });++ await prisma.price.createMany({+ data: [+ {+ modelId: model.id,+ projectId,+ pricingTierId: largeTier.id,+ usageType: "input",+ price: 6.0,+ },+ {+ modelId: model.id,+ projectId,+ pricingTierId: largeTier.id,+ usageType: "output",+ price: 15.0,+ },+ ],+ });++ // Test GET /models+ const response = await makeZodVerifiedAPICall(+ GetModelsV1Response,+ "GET",+ "/api/public/models",+ undefined,+ auth,+ );++ expect(response.status).toBe(200);+ const returnedModel = response.body.data.find((m) => m.id === modelId);+ expect(returnedModel).toBeDefined();++ // Check backward-compatible fields (populated from default tier)+ expect(returnedModel?.inputPrice).toBe(3.0);+ expect(returnedModel?.outputPrice).toBe(15.0);+ expect(returnedModel?.prices).toMatchObject({+ input: { price: 3.0 },+ output: { price: 15.0 },+ });++ // Check new pricingTiers array+ expect(returnedModel?.pricingTiers).toHaveLength(2);++ const defaultTierResponse = returnedModel?.pricingTiers.find(+ (t) => t.isDefault,+ );+ expect(defaultTierResponse).toMatchObject({+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 15.0 },+ });++ const largeTierResponse = returnedModel?.pricingTiers.find(+ (t) => !t.isDefault,+ );+ expect(largeTierResponse).toMatchObject({+ name: "Large Context",+ isDefault: false,+ priority: 1,+ prices: { input: 6.0, output: 15.0 },+ });+ expect(largeTierResponse?.conditions).toHaveLength(1);+ expect(largeTierResponse?.conditions[0]).toMatchObject({+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ });+ });+ });++ describe("GET /models/{modelId} - with pricing tiers", () => {+ it("should return single model with pricingTiers array", async () => {+ const uniqueId = randomUUID();+ const { auth, projectId } = await createOrgProjectAndApiKey();++ // Create model with pricing tiers+ const modelId = `model_${uniqueId}`;+ const model = await prisma.model.create({+ data: {+ id: modelId,+ projectId,+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ },+ });++ // Create default tier+ const defaultTier = await prisma.pricingTier.create({+ data: {+ modelId: model.id,+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ },+ });++ await prisma.price.createMany({+ data: [+ {+ modelId: model.id,+ projectId,+ pricingTierId: defaultTier.id,+ usageType: "input",+ price: 2.5,+ },+ {+ modelId: model.id,+ projectId,+ pricingTierId: defaultTier.id,+ usageType: "output",+ price: 10.0,+ },+ ],+ });++ // Test GET /models/{modelId}+ const response = await makeZodVerifiedAPICall(+ GetModelV1Response,+ "GET",+ `/api/public/models/${modelId}`,+ undefined,+ auth,+ );++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(modelId);++ // Check backward-compatible fields+ expect(response.body.inputPrice).toBe(2.5);+ expect(response.body.outputPrice).toBe(10.0);++ // Check pricingTiers+ expect(response.body.pricingTiers).toHaveLength(1);+ expect(response.body.pricingTiers[0]).toMatchObject({+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 2.5, output: 10.0 },+ });+ });+ });++ describe("POST /models - backward compatible (flat prices)", () => {+ it("should create model with default tier from flat prices", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ // Create model with flat prices (legacy format)+ const response = await makeZodVerifiedAPICall(+ PostModelsV1Response,+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ inputPrice: 2.5,+ outputPrice: 10.0,+ },+ auth,+ );++ expect(response.status).toBe(200);+ const modelId = response.body.id;++ // Verify default tier was created+ const tiers = await prisma.pricingTier.findMany({+ where: { modelId },+ include: { prices: true },+ });++ expect(tiers).toHaveLength(1);+ expect(tiers[0]).toMatchObject({+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ });++ // Verify prices are linked to tier+ expect(tiers[0].prices).toHaveLength(2);+ const inputPrice = tiers[0].prices.find((p) => p.usageType === "input");+ const outputPrice = tiers[0].prices.find((p) => p.usageType === "output");+ expect(inputPrice?.price.toNumber()).toBe(2.5);+ expect(outputPrice?.price.toNumber()).toBe(10.0);++ // Verify response includes pricingTiers+ expect(response.body.pricingTiers).toHaveLength(1);+ expect(response.body.pricingTiers[0]).toMatchObject({+ name: "Standard",+ isDefault: true,+ priority: 0,+ prices: { input: 2.5, output: 10.0 },+ });++ // Verify backward-compatible fields are populated+ expect(response.body.inputPrice).toBe(2.5);+ expect(response.body.outputPrice).toBe(10.0);+ });+ });++ describe("POST /models - with pricing tiers", () => {+ it("should create model with multiple pricing tiers", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeZodVerifiedAPICall(+ PostModelsV1Response,+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 15.0 },+ },+ {+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: { input: 6.0, output: 15.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(200);+ const modelId = response.body.id;++ // Verify tiers were created in database+ const tiers = await prisma.pricingTier.findMany({+ where: { modelId },+ include: { prices: true },+ orderBy: { priority: "asc" },+ });++ expect(tiers).toHaveLength(2);++ // Verify default tier+ expect(tiers[0]).toMatchObject({+ name: "Standard",+ isDefault: true,+ priority: 0,+ });+ expect(tiers[0].prices).toHaveLength(2);++ // Verify large context tier+ expect(tiers[1]).toMatchObject({+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ });+ expect(tiers[1].conditions).toMatchObject([+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ]);++ // Verify response+ expect(response.body.pricingTiers).toHaveLength(2);+ expect(response.body.inputPrice).toBe(3.0); // From default tier+ expect(response.body.outputPrice).toBe(15.0); // From default tier+ });+ });++ describe("POST /models - validation", () => {+ it("should reject model with both flat prices and pricing tiers", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ inputPrice: 2.5, // Flat price+ pricingTiers: [+ // AND tiers (not allowed!)+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain(+ "Must provide either flat prices",+ );+ });++ it("should reject model with no pricing information", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ // No flat prices AND no pricing tiers+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain(+ "Must provide either flat prices",+ );+ });++ it("should reject pricing tiers with no default", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Tier 1",+ isDefault: false, // No default!+ priority: 1,+ conditions: [],+ prices: { input: 3.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain("isDefault: true");+ });++ it("should reject pricing tiers with multiple defaults", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Default 1",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Default 2",+ isDefault: true, // Multiple defaults!+ priority: 1,+ conditions: [],+ prices: { input: 6.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain("Only one pricing tier");+ });++ it("should reject pricing tiers with duplicate priorities", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Tier 1",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 5.0 },+ },+ {+ name: "Tier 2",+ isDefault: false,+ priority: 1, // Duplicate!+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200,+ caseSensitive: false,+ },+ ],+ prices: { input: 7.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain(+ "priorities must be unique",+ );+ });++ it("should reject pricing tiers with duplicate names", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Standard", // Duplicate name!+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 5.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain("names must be unique");+ });++ it("should reject pricing tiers with invalid regex pattern", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0 },+ },+ {+ name: "Large Context",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "(unclosed", // Invalid regex!+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 5.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain("regex");+ });++ it("should reject default tier with non-zero priority", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 1, // Should be 0!+ conditions: [],+ prices: { input: 3.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain("priority: 0");+ });++ it("should reject default tier with conditions", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: `aaa-test-model-${uniqueId}`,+ matchPattern: `^aaa-test-model-${uniqueId}`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [+ // Default shouldn't have conditions!+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: { input: 3.0 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain("empty conditions");+ });+ });+});diff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/async/repositories/event-repository.servertest.tsindex 96b8a768a7..fa02c340e4 100644--- a/web/src/__tests__/async/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/event-repository.servertest.ts@@ -51,21 +51,33 @@ describe("Clickhouse Events Repository Test", () => {matchPattern: `(?i)^(gpt-?4-${modelId})$`,startDate: new Date("2023-01-01"),unit: "TOKENS",- Price: {- create: [- {- usageType: "input",- price: 0.03,- },- {- usageType: "output",- price: 0.06,- },- {- usageType: "total",- price: 0.09,++ pricingTiers: {+ create: {+ isDefault: true,+ conditions: [],+ name: "Standard",+ priority: 0,+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.03,+ modelId,+ },+ {+ usageType: "output",+ price: 0.06,+ modelId,+ },+ {+ usageType: "total",+ price: 0.09,+ modelId,+ },+ ],},- ],+ },},},});@@ -1460,17 +1472,27 @@ describe("Clickhouse Events Repository Test", () => {matchPattern: `(?i)^(test-model-${modelId})$`,startDate: new Date("2023-01-01"),unit: "TOKENS",- Price: {- create: [- {- usageType: "input",- price: 0.01,- },- {- usageType: "output",- price: 0.02,+ pricingTiers: {+ create: {+ isDefault: true,+ conditions: [],+ name: "Standard",+ priority: 0,+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.01,+ modelId,+ },+ {+ usageType: "output",+ price: 0.02,+ modelId,+ },+ ],},- ],+ },},},});diff --git a/web/src/__tests__/model-definitions.servertest.ts b/web/src/__tests__/model-definitions.servertest.tsindex e14719db74..404eb02776 100644--- a/web/src/__tests__/model-definitions.servertest.ts+++ b/web/src/__tests__/model-definitions.servertest.ts@@ -13,6 +13,7 @@ import {PostModelsV1Response,} from "@/src/features/public-api/types/models";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import { v4 } from "uuid";describe("/models API Endpoints", () => {let auth: string;@@ -38,6 +39,17 @@ describe("/models API Endpoints", () => {unit: "TOKENS",},});+ const pricingTierId1 = v4();+ await prisma.pricingTier.create({+ data: {+ id: pricingTierId1,+ isDefault: true,+ priority: 0,+ conditions: [],+ name: "Standard",+ modelId: "model-1",+ },+ });await prisma.price.createMany({data: [{@@ -45,16 +57,25 @@ describe("/models API Endpoints", () => {projectId: null,usageType: "input",price: 0.001,+ pricingTierId: pricingTierId1,},{modelId: "model-1",projectId: null,usageType: "output",price: 0.002,+ pricingTierId: pricingTierId1,+ },+ {+ modelId: "model-1",+ projectId: null,+ usageType: "total",+ price: 0.1,+ pricingTierId: pricingTierId1,},- { modelId: "model-1", projectId: null, usageType: "total", price: 0.1 },],});+await prisma.model.create({data: {id: "model-2",@@ -68,6 +89,17 @@ describe("/models API Endpoints", () => {unit: "TOKENS",},});+ const pricingTierId2 = v4();+ await prisma.pricingTier.create({+ data: {+ id: pricingTierId2,+ isDefault: true,+ priority: 0,+ conditions: [],+ name: "Standard",+ modelId: "model-2",+ },+ });await prisma.price.createMany({data: [{@@ -75,12 +107,14 @@ describe("/models API Endpoints", () => {projectId: null,usageType: "input",price: 0.02,+ pricingTierId: pricingTierId2,},{modelId: "model-2",projectId: null,usageType: "output",price: 0.04,+ pricingTierId: pricingTierId2,},],});@@ -218,20 +252,6 @@ describe("/models API Endpoints", () => {expect(customModel.status).toBe(400);});- it("Post model without prices or tokenizer", async () => {- await makeZodVerifiedAPICall(- PostModelsV1Response,- "POST",- "/api/public/models",- {- modelName: "gpt-3.5-turbo",- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",- unit: "TOKENS",- },- auth,- );- });-it("Post model with missing fields", async () => {const { status } = await makeAPICall("POST",diff --git a/web/src/components/layouts/settings-table-card.tsx b/web/src/components/layouts/settings-table-card.tsxindex d4ed4a6426..a269caca2a 100644--- a/web/src/components/layouts/settings-table-card.tsx+++ b/web/src/components/layouts/settings-table-card.tsx@@ -1,12 +1,20 @@import { Card } from "@/src/components/ui/card";+import { cn } from "@/src/utils/tailwind";export const SettingsTableCard = ({children,+ className,}: {children: React.ReactNode;+ className?: string;}) => {return (- <Card className="mb-4 flex max-h-[60dvh] flex-col overflow-hidden [&>:first-child>:first-child]:border-t-0">+ <Card+ className={cn(+ "mb-4 flex max-h-[60dvh] flex-col overflow-hidden [&>:first-child>:first-child]:border-t-0",+ className,+ )}+ >{children}</Card>);diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsxindex 06a42e3d50..b985cebf5c 100644--- a/web/src/components/table/data-table-toolbar.tsx+++ b/web/src/components/table/data-table-toolbar.tsx@@ -59,12 +59,12 @@ export interface MultiSelect {}interface SearchConfig {- metadataSearchFields: string[];+ metadataSearchFields?: string[];updateQuery: (event: string) => void;currentQuery?: string;tableAllowsFullTextSearch?: boolean;- setSearchType: ((newSearchType: TracingSearchType[]) => void) | undefined;- searchType: TracingSearchType[] | undefined;+ setSearchType?: (newSearchType: TracingSearchType[]) => void;+ searchType?: TracingSearchType[];customDropdownLabels?: {metadata: string;fullText: string;@@ -196,7 +196,7 @@ export function DataTableToolbar<TData, TValue>({placeholder={searchConfig.tableAllowsFullTextSearch? "Search..."- : `Search (${searchConfig.metadataSearchFields.join(", ")})`+ : `Search (${searchConfig.metadataSearchFields?.join(", ")})`}value={searchString}onChange={(event) => {@@ -239,14 +239,14 @@ export function DataTableToolbar<TData, TValue>({) ? (<p className="text-xs font-normal text-primary">Searches in Input/Output and{" "}- {searchConfig.metadataSearchFields.join(", ")}.+ {searchConfig.metadataSearchFields?.join(", ")}.{!searchConfig.hidePerformanceWarning &&" For improved performance, please filter the table down."}</p>) : (<p className="text-xs font-normal text-primary">Searches in{" "}- {searchConfig.metadataSearchFields.join(", ")}.+ {searchConfig.metadataSearchFields?.join(", ")}.</p>)}diff --git a/web/src/components/table/use-cases/models.tsx b/web/src/components/table/use-cases/models.tsxindex fc87b47e20..3023e675ea 100644--- a/web/src/components/table/use-cases/models.tsx+++ b/web/src/components/table/use-cases/models.tsx@@ -4,7 +4,12 @@ import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumimport { api } from "@/src/utils/api";import { safeExtract } from "@/src/utils/map-utils";import { type Prisma } from "@langfuse/shared/src/db";-import { useQueryParams, withDefault, NumberParam } from "use-query-params";+import {+ useQueryParams,+ withDefault,+ NumberParam,+ StringParam,+} from "use-query-params";import { IOTableCell } from "../../ui/IOTableCell";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";@@ -24,7 +29,8 @@ import { LangfuseIcon } from "@/src/components/LangfuseLogo";import { useRouter } from "next/router";import { PriceUnitSelector } from "@/src/features/models/components/PriceUnitSelector";import { usePriceUnitMultiplier } from "@/src/features/models/hooks/usePriceUnitMultiplier";-import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";+import { TestModelMatchButton } from "@/src/features/models/components/test-match/TestModelMatchButton";import { ActionButton } from "@/src/components/ActionButton";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";@@ -66,11 +72,16 @@ export default function ModelTable({ projectId }: { projectId: string }) {pageIndex: withDefault(NumberParam, 0),pageSize: withDefault(NumberParam, 50),});+ const [queryParams, setQueryParams] = useQueryParams({+ search: withDefault(StringParam, ""),+ });+ const searchString = queryParams.search;const models = api.models.getAll.useQuery({page: paginationState.pageIndex,limit: paginationState.pageSize,projectId,+ searchString,},{refetchOnWindowFocus: false,@@ -257,12 +268,16 @@ export default function ModelTable({ projectId }: { projectId: string }) {);const convertToTableRow = (model: GetModelResult): ModelTableRow => {+ // Get default tier prices for backward compatibility+ const defaultTier = model.pricingTiers.find((t) => t.isDefault);+ const prices = defaultTier?.prices;+return {modelId: model.id,maintainer: model.projectId ? "User" : "Langfuse",modelName: model.modelName,matchPattern: model.matchPattern,- prices: model.prices,+ prices,tokenizerId: model.tokenizerId ?? undefined,config: model.tokenizerConfig,lastUsed: model.lastUsed,@@ -280,21 +295,31 @@ export default function ModelTable({ projectId }: { projectId: string }) {setColumnOrder={setColumnOrder}rowHeight={rowHeight}setRowHeight={setRowHeight}+ searchConfig={{+ updateQuery: (event: string) => {+ setQueryParams({ search: event });+ },+ tableAllowsFullTextSearch: true,+ currentQuery: searchString,+ }}actionButtons={- <UpsertModelFormDrawer {...{ projectId, action: "create" }}>- <ActionButton- variant="secondary"- icon={<PlusIcon className="h-4 w-4" />}- hasAccess={hasWriteAccess}- onClick={() => capture("models:new_form_open")}- >- Add model definition- </ActionButton>- </UpsertModelFormDrawer>+ <>+ <TestModelMatchButton projectId={projectId} />+ <UpsertModelFormDialog {...{ projectId, action: "create" }}>+ <ActionButton+ variant="secondary"+ icon={<PlusIcon className="h-4 w-4" />}+ hasAccess={hasWriteAccess}+ onClick={() => capture("models:new_form_open")}+ >+ Add Model Definition+ </ActionButton>+ </UpsertModelFormDialog>+ </>}className="px-0"/>- <SettingsTableCard>+ <SettingsTableCard className="max-h-[75dvh]"><DataTabletableName={"models"}columns={columns}diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsxindex 33448b252f..eca3cfb581 100644--- a/web/src/components/table/use-cases/observations.tsx+++ b/web/src/components/table/use-cases/observations.tsx@@ -41,9 +41,12 @@ import { type ScoreAggregate } from "@langfuse/shared";import TagList from "@/src/features/tag/components/TagList";import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";-import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";+import {+ BreakdownTooltip,+ calculateAggregatedUsage,+} from "@/src/components/trace/BreakdownToolTip";import { InfoIcon, PlusCircle } from "lucide-react";-import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";import { LocalIsoDate } from "@/src/components/LocalIsoDate";import { Badge } from "@/src/components/ui/badge";import { type RowSelectionState, type Row } from "@tanstack/react-table";@@ -85,6 +88,7 @@ export type ObservationsTableRow = {usageDetails: Record<string, number>;totalCost?: number;costDetails: Record<string, number>;+ usagePricingTierName?: string | null;model?: string;promptName?: string;environment?: string;@@ -629,7 +633,11 @@ export default function ObservationsTable({const value: number | undefined = row.getValue("totalCost");return value !== undefined ? (- <BreakdownTooltip details={row.original.costDetails} isCost>+ <BreakdownTooltip+ details={row.original.costDetails}+ isCost+ pricingTierName={row.original.usagePricingTierName ?? undefined}+ ><div className="flex items-center gap-1"><span>{usdFormatter(value)}</span><InfoIcon className="h-3 w-3" />@@ -664,18 +672,19 @@ export default function ObservationsTable({id: "tokens",size: 150,cell: ({ row }) => {- const value: {- inputUsage: number;- outputUsage: number;- totalUsage: number;- } = row.getValue("usage");+ const aggregatedUsage = calculateAggregatedUsage(+ row.original.usageDetails,+ );return (- <BreakdownTooltip details={row.original.usageDetails}>+ <BreakdownTooltip+ details={row.original.usageDetails}+ pricingTierName={row.original.usagePricingTierName ?? undefined}+ ><div className="flex items-center gap-1"><TokenUsageBadge- inputUsage={value.inputUsage}- outputUsage={value.outputUsage}- totalUsage={value.totalUsage}+ inputUsage={aggregatedUsage.input}+ outputUsage={aggregatedUsage.output}+ totalUsage={aggregatedUsage.total}inline/><InfoIcon className="h-3 w-3" />@@ -702,7 +711,7 @@ export default function ObservationsTable({return modelId ? (<TableIdOrName value={model} />) : (- <UpsertModelFormDrawer+ <UpsertModelFormDialogaction="create"projectId={projectId}prefilledModelData={{@@ -726,7 +735,7 @@ export default function ObservationsTable({<span>{model}</span><PlusCircle className="h-3 w-3" /></span>- </UpsertModelFormDrawer>+ </UpsertModelFormDialog>);},},@@ -1132,6 +1141,7 @@ export default function ObservationsTable({timestamp: generation.traceTimestamp ?? undefined,usageDetails: generation.usageDetails ?? {},costDetails: generation.costDetails ?? {},+ usagePricingTierName: generation.usagePricingTierName ?? undefined,environment: generation.environment ?? undefined,};})diff --git a/web/src/components/trace/BreakdownToolTip.tsx b/web/src/components/trace/BreakdownToolTip.tsxindex 8de1c32cbb..96b88f135b 100644--- a/web/src/components/trace/BreakdownToolTip.tsx+++ b/web/src/components/trace/BreakdownToolTip.tsx@@ -12,30 +12,77 @@ interface Details {[key: string]: number | undefined;}+/**+ * Aggregates an array of detail objects into a single object by summing matching keys.+ * If a single object is provided, returns it as-is.+ */+const aggregateDetailsArray = (details: Details | Details[]): Details => {+ return Array.isArray(details)+ ? details.reduce<Details>((acc, curr) => {+ Object.entries(curr).forEach(([key, value]) => {+ acc[key] = new Decimal(acc[key] || 0)+ .plus(new Decimal(value || 0))+ .toNumber();+ });+ return acc;+ }, {})+ : details;+};++/**+ * Aggregates usage or cost details by summing values based on key patterns.+ * Used to calculate input/output/total values from detailed breakdowns.+ */+export const calculateAggregatedUsage = (+ details: Details | Details[],+): {+ input: number;+ output: number;+ total: number;+} => {+ const aggregatedDetails = aggregateDetailsArray(details);++ // Sum all keys containing "input"+ const input = Object.entries(aggregatedDetails)+ .filter(([key]) => key.includes("input"))+ .reduce(+ (sum, [_, value]) =>+ new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),+ 0,+ );++ // Sum all keys containing "output"+ const output = Object.entries(aggregatedDetails)+ .filter(([key]) => key.includes("output"))+ .reduce(+ (sum, [_, value]) =>+ new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),+ 0,+ );++ // Get total or calculate from input + output+ const total = aggregatedDetails.total ?? input + output;++ return { input, output, total };+};+interface BreakdownTooltipProps {details: Details | Details[];children: React.ReactNode;isCost?: boolean;+ pricingTierName?: string;}export const BreakdownTooltip = ({details,children,isCost = false,+ pricingTierName,}: BreakdownTooltipProps) => {const [isOpen, setIsOpen] = useState(false);// Aggregate details if array is provided- const aggregatedDetails = Array.isArray(details)- ? details.reduce<Details>((acc, curr) => {- Object.entries(curr).forEach(([key, value]) => {- acc[key] = new Decimal(acc[key] || 0)- .plus(new Decimal(value || 0))- .toNumber();- });- return acc;- }, {})- : details;+ const aggregatedDetails = aggregateDetailsArray(details);const formatValueWithPadding = (value: number, maxDecimals: number) => {return !value@@ -72,6 +119,17 @@ export const BreakdownTooltip = ({{details.length === 1 ? "generation" : "generations"}</span>)}+ {/* Pricing Tier Section */}+ {pricingTierName && (+ <div className="flex flex-row items-center gap-1 border-b pb-2">+ <span className="text-xs text-muted-foreground">+ Pricing Tier:+ </span>+ <span className="text-xs font-medium text-muted-foreground">+ {pricingTierName}+ </span>+ </div>+ )}</div>{/* Input Section */}@@ -145,10 +203,10 @@ const Section = ({ title, details, filterFn, formatValue }: SectionProps) => {{filteredEntries.map(([key, value]) => (<divkey={key}- className="flex justify-between text-xs text-muted-foreground"+ className="flex justify-between gap-4 text-xs text-muted-foreground">- <span className="mr-4">{key}</span>- <span className="font-mono">{formatValue(value ?? 0)}</span>+ <span className="break-words">{key}</span>+ <span className="shrink-0 font-mono">{formatValue(value ?? 0)}</span></div>))}</div>@@ -190,10 +248,10 @@ const OtherSection = ({ details, isCost, formatValue }: OtherSectionProps) => {{otherEntries.map(([key, value]) => (<divkey={key}- className="flex justify-between text-xs text-muted-foreground"+ className="flex justify-between gap-4 text-xs text-muted-foreground">- <span className="mr-4">{key}</span>- <span className="font-mono">{formatValue(value ?? 0)}</span>+ <span className="break-words">{key}</span>+ <span className="shrink-0 font-mono">{formatValue(value ?? 0)}</span></div>))}</div>diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsxindex f3eda28a8c..fb95650d93 100644--- a/web/src/components/trace/ObservationPreview.tsx+++ b/web/src/components/trace/ObservationPreview.tsx@@ -30,9 +30,9 @@ import {TabsBarTrigger,TabsBarContent,} from "@/src/components/ui/tabs-bar";-import { BreakdownTooltip } from "./BreakdownToolTip";+import { BreakdownTooltip, calculateAggregatedUsage } from "./BreakdownToolTip";import { ExternalLinkIcon, InfoIcon, PlusCircle } from "lucide-react";-import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";import { LocalIsoDate } from "@/src/components/LocalIsoDate";import { ItemBadge } from "@/src/components/ItemBadge";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -261,6 +261,9 @@ export const ObservationPreview = ({<BreakdownTooltipdetails={preloadedObservation.costDetails}isCost={true}+ pricingTierName={+ preloadedObservation.usagePricingTierName ?? undefined+ }><Badgevariant="tertiary"@@ -283,27 +286,38 @@ export const ObservationPreview = ({projectId={preloadedObservation.projectId}/>) : undefined}- {isGenerationLike(preloadedObservation.type) && (- <BreakdownTooltip- details={preloadedObservation.usageDetails}- isCost={false}- >- <Badge- variant="tertiary"- className="flex items-center gap-1"- >- <span>- {formatTokenCounts(- preloadedObservation.inputUsage,- preloadedObservation.outputUsage,- preloadedObservation.totalUsage,- true,- )}- </span>- <InfoIcon className="h-3 w-3" />- </Badge>- </BreakdownTooltip>- )}+ {isGenerationLike(preloadedObservation.type) &&+ (() => {+ const aggregatedUsage = calculateAggregatedUsage(+ preloadedObservation.usageDetails,+ );++ return (+ <BreakdownTooltip+ details={preloadedObservation.usageDetails}+ isCost={false}+ pricingTierName={+ preloadedObservation.usagePricingTierName ??+ undefined+ }+ >+ <Badge+ variant="tertiary"+ className="flex items-center gap-1"+ >+ <span>+ {formatTokenCounts(+ aggregatedUsage.input,+ aggregatedUsage.output,+ aggregatedUsage.total,+ true,+ )}+ </span>+ <InfoIcon className="h-3 w-3" />+ </Badge>+ </BreakdownTooltip>+ );+ })()}{preloadedObservation.version ? (<Badge variant="tertiary">Version: {preloadedObservation.version}@@ -324,7 +338,7 @@ export const ObservationPreview = ({</Link></Badge>) : (- <UpsertModelFormDrawer+ <UpsertModelFormDialogaction="create"projectId={preloadedObservation.projectId}prefilledModelData={{@@ -352,7 +366,7 @@ export const ObservationPreview = ({<span>{preloadedObservation.model}</span><PlusCircle className="h-3 w-3" /></Badge>- </UpsertModelFormDrawer>+ </UpsertModelFormDialog>)) : null}diff --git a/web/src/components/trace/SpanItem.tsx b/web/src/components/trace/SpanItem.tsxindex c998dcf69a..cda306453d 100644--- a/web/src/components/trace/SpanItem.tsx+++ b/web/src/components/trace/SpanItem.tsx@@ -10,6 +10,7 @@ import { type ScoreDomain } from "@langfuse/shared";import type Decimal from "decimal.js";import React from "react";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { calculateAggregatedUsage } from "@/src/components/trace/BreakdownToolTip";export interface SpanItemProps {node: TreeNode;@@ -41,6 +42,15 @@ export const SpanItem: React.FC<SpanItemProps> = ({// Use pre-computed cost from the TreeNode (computed during tree building)const totalCost = node.totalCost;+ // Calculate aggregated usage from usageDetails when available+ const aggregatedUsage = node.usageDetails+ ? calculateAggregatedUsage(node.usageDetails)+ : {+ input: node.inputUsage ?? 0,+ output: node.outputUsage ?? 0,+ total: node.totalUsage ?? 0,+ };+const duration =node.endTime && node.startTime? node.endTime.getTime() - node.startTime.getTime()@@ -111,12 +121,14 @@ export const SpanItem: React.FC<SpanItemProps> = ({</span>) : null}{shouldRenderCostTokens &&- (node.inputUsage || node.outputUsage || node.totalUsage) ? (+ (aggregatedUsage.input ||+ aggregatedUsage.output ||+ aggregatedUsage.total) ? (<span className="text-xs text-muted-foreground">{formatTokenCounts(- node.inputUsage,- node.outputUsage,- node.totalUsage,+ aggregatedUsage.input,+ aggregatedUsage.output,+ aggregatedUsage.total,)}</span>) : null}diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.tsindex 7955b96494..17bfa4984c 100644--- a/web/src/components/trace/lib/helpers.ts+++ b/web/src/components/trace/lib/helpers.ts@@ -296,6 +296,7 @@ function buildTraceTree(inputUsage: obs.inputUsage,outputUsage: obs.outputUsage,totalUsage: obs.totalUsage,+ usageDetails: obs.usageDetails,calculatedInputCost: obs.inputCost,calculatedOutputCost: obs.outputCost,calculatedTotalCost: obs.totalCost,diff --git a/web/src/components/trace/lib/types.ts b/web/src/components/trace/lib/types.tsindex 76be410caa..28c656549e 100644--- a/web/src/components/trace/lib/types.ts+++ b/web/src/components/trace/lib/types.ts@@ -14,6 +14,7 @@ export type TreeNode = {inputUsage?: number | null;outputUsage?: number | null;totalUsage?: number | null;+ usageDetails?: Record<string, number>;calculatedInputCost?: any;calculatedOutputCost?: any;calculatedTotalCost?: any;diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex b1a673e6b6..a15e4ae75b 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -36,7 +36,7 @@ import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrdeimport { BatchExportTableButton } from "@/src/components/BatchExportTableButton";import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";import { InfoIcon, PlusCircle } from "lucide-react";-import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";import { LocalIsoDate } from "@/src/components/LocalIsoDate";import { Badge } from "@/src/components/ui/badge";import { type Row, type RowSelectionState } from "@tanstack/react-table";@@ -109,6 +109,7 @@ export type EventsTableRow = {outputCost?: number;};costDetails: Record<string, number>;+ usagePricingTierName?: string | null;// Performance metricslatency?: number;@@ -444,7 +445,11 @@ export default function ObservationsEventsTable({const value: number | undefined = row.getValue("totalCost");return value !== undefined ? (- <BreakdownTooltip details={row.original.costDetails} isCost>+ <BreakdownTooltip+ details={row.original.costDetails}+ isCost+ pricingTierName={row.original.usagePricingTierName ?? undefined}+ ><div className="flex items-center gap-1"><span>{usdFormatter(value)}</span><InfoIcon className="h-3 w-3" />@@ -631,7 +636,7 @@ export default function ObservationsEventsTable({return modelId ? (<TableIdOrName value={model} />) : (- <UpsertModelFormDrawer+ <UpsertModelFormDialogaction="create"projectId={projectId}prefilledModelData={{@@ -655,7 +660,7 @@ export default function ObservationsEventsTable({<span>{model}</span><PlusCircle className="h-3 w-3" /></span>- </UpsertModelFormDrawer>+ </UpsertModelFormDialog>);},},@@ -886,6 +891,7 @@ export default function ObservationsEventsTable({timestamp: observation.traceTimestamp ?? undefined,usageDetails: observation.usageDetails ?? {},costDetails: observation.costDetails ?? {},+ usagePricingTierName: observation.usagePricingTierName ?? undefined,environment: observation.environment ?? undefined,input: observation.input? typeof observation.input === "string"diff --git a/web/src/features/models/components/CloneModelButton.tsx b/web/src/features/models/components/CloneModelButton.tsxindex 5a32e91b7a..9e57d764de 100644--- a/web/src/features/models/components/CloneModelButton.tsx+++ b/web/src/features/models/components/CloneModelButton.tsx@@ -1,6 +1,6 @@import { Button } from "@/src/components/ui/button";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";import { type GetModelResult } from "@/src/features/models/validation";export const CloneModelButton = ({@@ -16,7 +16,7 @@ export const CloneModelButton = ({});return (- <UpsertModelFormDrawer {...{ modelData, projectId, action: "clone" }}>+ <UpsertModelFormDialog {...{ modelData, projectId, action: "clone" }}><Buttonvariant="outline"disabled={!hasAccess}@@ -25,6 +25,6 @@ export const CloneModelButton = ({><span>Clone</span></Button>- </UpsertModelFormDrawer>+ </UpsertModelFormDialog>);};diff --git a/web/src/features/models/components/EditModelButton.tsx b/web/src/features/models/components/EditModelButton.tsxindex b052d082c9..c301f79edb 100644--- a/web/src/features/models/components/EditModelButton.tsx+++ b/web/src/features/models/components/EditModelButton.tsx@@ -1,6 +1,6 @@import { Button } from "@/src/components/ui/button";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";import { type GetModelResult } from "@/src/features/models/validation";export const EditModelButton = ({@@ -16,7 +16,7 @@ export const EditModelButton = ({});return (- <UpsertModelFormDrawer {...{ modelData, projectId, action: "edit" }}>+ <UpsertModelFormDialog {...{ modelData, projectId, action: "edit" }}><Buttonvariant="outline"disabled={!hasAccess}@@ -25,6 +25,6 @@ export const EditModelButton = ({><span>Edit</span></Button>- </UpsertModelFormDrawer>+ </UpsertModelFormDialog>);};diff --git a/web/src/features/models/components/PriceBreakdownTooltip.tsx b/web/src/features/models/components/PriceBreakdownTooltip.tsxindex 81da765322..818c144b31 100644--- a/web/src/features/models/components/PriceBreakdownTooltip.tsx+++ b/web/src/features/models/components/PriceBreakdownTooltip.tsx@@ -46,7 +46,7 @@ export const PriceBreakdownTooltip = ({) : Object.keys(prices).length <= (rowHeight === "m" ? 4 : 2) ? (<div className="grid w-full grid-cols-[2fr,3fr] gap-x-2">{Object.entries(prices).map(([type, price]) => (- <>+ <span key={type}><spankey={`${type}-label`}className="truncate font-mono text-xs font-medium"@@ -63,7 +63,7 @@ export const PriceBreakdownTooltip = ({.mul(priceUnitMultiplier).toFixed(maxDecimals)}</span>- </>+ </span>))}</div>) : (diff --git a/web/src/features/models/components/UpsertModelFormDialog.tsx b/web/src/features/models/components/UpsertModelFormDialog.tsxnew file mode 100644index 0000000000..96eb7dc363--- /dev/null+++ b/web/src/features/models/components/UpsertModelFormDialog.tsx@@ -0,0 +1,466 @@+import Link from "next/link";+import { useEffect, useState, useMemo } from "react";+import { useForm, useFieldArray } from "react-hook-form";++import { CodeMirrorEditor } from "@/src/components/editor";+import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+ DialogBody,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import {+ type FormUpsertModel,+ FormUpsertModelSchema,+ type GetModelResult,+} from "@/src/features/models/validation";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { api } from "@/src/utils/api";+import { zodResolver } from "@hookform/resolvers/zod";+import { useRouter } from "next/router";++import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { PricingSection } from "./pricing-tiers/PricingSection";++type UpsertModelDialogProps =+ | {+ action: "create";+ children: React.ReactNode;+ projectId: string;+ prefilledModelData?: {+ modelName?: string;+ prices?: Record<string, number>;+ };+ className?: string;+ }+ | {+ action: "edit" | "clone";+ children: React.ReactNode;+ projectId: string;+ modelData: GetModelResult;+ className?: string;+ };++export const UpsertModelFormDialog = (({+ children,+ ...props+}: UpsertModelDialogProps) => {+ const capture = usePostHogClientCapture();+ const router = useRouter();+ const [formError, setFormError] = useState<string | null>(null);+ const utils = api.useUtils();+ const [open, setOpen] = useState(false);++ // Initialize form default values+ const defaultValues: FormUpsertModel = useMemo(() => {+ if (props.action !== "create") {+ // EDIT or CLONE: Load all tiers+ const loadedTiers = props.modelData.pricingTiers.map((tier) => ({+ id: tier.id,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ prices: tier.prices,+ }));++ return {+ modelName: props.modelData.modelName,+ matchPattern: props.modelData.matchPattern,+ tokenizerId: props.modelData.tokenizerId,+ tokenizerConfig: JSON.stringify(props.modelData.tokenizerConfig ?? {}),+ pricingTiers: loadedTiers,+ };+ } else {+ // CREATE: Start with 1 default tier+ return {+ modelName: props.prefilledModelData?.modelName ?? "",+ matchPattern: props.prefilledModelData?.modelName+ ? `(?i)^(${props.prefilledModelData?.modelName})$`+ : "",+ tokenizerId: null,+ tokenizerConfig: null,+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: props.prefilledModelData?.prices ?? {+ input: 0.000001,+ output: 0.000002,+ },+ },+ ],+ };+ }+ }, [props]);++ const form = useForm({+ resolver: zodResolver(FormUpsertModelSchema),+ defaultValues,+ });++ const modelName = form.watch("modelName");+ const matchPattern = form.watch("matchPattern");+ const tokenizerId = form.watch("tokenizerId");++ const { fields, append, remove } = useFieldArray({+ control: form.control,+ name: "pricingTiers",+ });++ // Watch default tier prices for syncing+ const defaultTierIndex = fields.findIndex((f) => f.isDefault);+ const defaultTierPrices =+ defaultTierIndex !== -1+ ? form.watch(`pricingTiers.${defaultTierIndex}.prices`)+ : undefined;++ // Compute keys signature - memoized to prevent unnecessary updates+ const defaultKeysSignature = useMemo(() => {+ if (!defaultTierPrices) return "";+ return Object.keys(defaultTierPrices).sort().join(",");+ }, [defaultTierPrices]);++ // Auto-assign priorities based on order+ useEffect(() => {+ fields.forEach((field, index) => {+ const tier = form.getValues(`pricingTiers.${index}`);+ const expectedPriority = tier.isDefault ? 0 : index;+ if (tier.priority !== expectedPriority) {+ form.setValue(`pricingTiers.${index}.priority`, expectedPriority);+ }+ });+ }, [fields, form]);++ // Sync usage keys from default tier to all non-default tiers+ useEffect(() => {+ if (!defaultTierPrices || defaultTierIndex === -1 || !defaultKeysSignature)+ return;++ const defaultKeys = defaultKeysSignature.split(",");++ fields.forEach((field, index) => {+ if (field.isDefault) return;++ const currentPrices = form.getValues(`pricingTiers.${index}.prices`);+ const currentKeys = Object.keys(currentPrices).sort();++ // Only update if keys don't match+ const keysMatch =+ defaultKeys.length === currentKeys.length &&+ defaultKeys.every((key, i) => key === currentKeys[i]);++ if (!keysMatch) {+ const newPrices: Record<string, number> = {};+ defaultKeys.forEach((key) => {+ newPrices[key] = currentPrices[key] ?? 0;+ });+ form.setValue(`pricingTiers.${index}.prices`, newPrices);+ }+ });+ }, [defaultKeysSignature, defaultTierPrices, defaultTierIndex, fields, form]);++ // prefill match pattern if model name changes+ useEffect(() => {+ const getRegexString = (modelName: string) => `(?i)^(${modelName})$`;++ if (+ modelName &&+ (!matchPattern ||+ matchPattern === `(?i)^(${modelName.slice(0, -1)})$` ||+ matchPattern === `(?i)^(${modelName})$`)+ ) {+ form.setValue("matchPattern", getRegexString(modelName));+ }+ }, [modelName, matchPattern, form]);++ const upsertModelMutation = api.models.upsert.useMutation({+ onSuccess: (upsertedModel) => {+ utils.models.invalidate();+ form.reset();+ setOpen(false);+ showSuccessToast({+ title: `Model ${props.action === "edit" ? "updated" : "created"}`,+ description: `The model '${upsertedModel.modelName}' has been successfully ${props.action === "edit" ? "updated" : "created"}. New generations will use these model prices.`,+ });+ router.push(+ `/project/${props.projectId}/settings/models/${upsertedModel.id}`,+ );+ },+ onError: (error) => setFormError(error.message),+ });++ const onSubmit = async (values: FormUpsertModel) => {+ capture("models:new_form_submit");++ // Transform FormPricingTier[] -> PricingTierInput[] (remove id field and filter prices)+ const pricingTiers = values.pricingTiers.map(({ id: _id, ...tier }) => ({+ ...tier,+ prices: Object.fromEntries(+ Object.entries(tier.prices).filter(([_, value]) => value != null),+ ) as Record<string, number>,+ }));++ await upsertModelMutation+ .mutateAsync({+ modelId: props.action === "edit" ? props.modelData.id : null,+ projectId: props.projectId,+ modelName:+ props.action === "edit"+ ? props.modelData.modelName+ : values.modelName,+ matchPattern: values.matchPattern,+ pricingTiers,+ tokenizerId: values.tokenizerId,+ tokenizerConfig:+ values.tokenizerConfig &&+ typeof JSON.parse(values.tokenizerConfig) === "object"+ ? (JSON.parse(values.tokenizerConfig) as Record<string, number>)+ : undefined,+ })+ .catch((error) => {+ setFormError(error.message);+ });+ };++ const addTier = () => {+ const defaultTier = fields.find((f) => f.isDefault);+ if (!defaultTier) return;++ append({+ name: `Custom Tier ${fields.length}`,+ isDefault: false,+ priority: fields.length,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 0,+ caseSensitive: false,+ },+ ],+ prices: { ...defaultTier.prices }, // Copy default tier prices+ });+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(newOpen) => {+ if (!newOpen) {+ form.reset();+ setFormError(null);+ }+ setOpen(newOpen);+ }}+ >+ <DialogTrigger+ asChild+ onClick={() => setOpen(true)}+ className={props.className}+ title={+ props.action === "create"+ ? "Create model definition"+ : "Edit model definition"+ }+ >+ {children}+ </DialogTrigger>+ <DialogContent size="lg">+ <DialogHeader>+ <DialogTitle>+ {props.action === "create"+ ? "Create Model"+ : props.action === "clone"+ ? "Clone Model"+ : "Edit Model"}+ </DialogTitle>+ {props.action === "edit" && (+ <DialogDescription>{props.modelData.modelName}</DialogDescription>+ )}+ {props.action === "create" && (+ <DialogDescription>+ Create a new model configuration to track generation costs.+ </DialogDescription>+ )}+ </DialogHeader>+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="flex flex-1 flex-col overflow-hidden"+ >+ <DialogBody className="space-y-6">+ <FormField+ control={form.control}+ name="modelName"+ disabled={props.action === "edit"}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Model Name</FormLabel>+ <FormDescription>+ The name of the model. This will be used to reference the+ model in the API. You can track price changes of models by+ using the same name and match pattern.+ </FormDescription>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="matchPattern"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Match pattern</FormLabel>+ <FormDescription>+ Regular expression (Postgres syntax) to match ingested+ generations (model attribute) to this model definition.+ For an exact, case-insensitive match to a model name, use+ the expression: (?i)^(modelname)$+ </FormDescription>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ {/* PRICING SECTION */}+ <PricingSection+ fields={fields}+ form={form}+ remove={remove}+ addTier={addTier}+ />++ <FormField+ control={form.control}+ name="tokenizerId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Tokenizer</FormLabel>+ <Select+ onValueChange={(tokenizerId) => {+ field.onChange(tokenizerId);+ if (tokenizerId === "None") {+ form.setValue("tokenizerConfig", "{}");+ }+ }}+ defaultValue={field.value ?? "None"}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a unit" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {["openai", "claude", "None"].map((unit) => (+ <SelectItem value={unit} key={unit}>+ {unit}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ Optionally, Langfuse can tokenize the input and output of+ a generation if no unit counts are ingested. This is+ useful for e.g. streamed OpenAI completions. For details+ on the supported tokenizers, see the{" "}+ <Link+ href="https://langfuse.com/docs/model-usage-and-cost"+ className="underline"+ target="_blank"+ >+ docs+ </Link>+ .+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ {tokenizerId && tokenizerId !== "None" && (+ <FormField+ control={form.control}+ name="tokenizerConfig"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Tokenizer Config</FormLabel>+ <CodeMirrorEditor+ mode="json"+ value={field.value ?? "{}"}+ onChange={field.onChange}+ minHeight="none"+ />+ <FormDescription>+ The config for the tokenizer. Required for openai. See+ the{" "}+ <Link+ href="https://langfuse.com/docs/model-usage-and-cost"+ className="underline"+ target="_blank"+ >+ docs+ </Link>{" "}+ for details.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ </DialogBody>++ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ >+ Cancel+ </Button>++ <Button type="submit" loading={upsertModelMutation.isPending}>+ Submit+ </Button>+ </DialogFooter>+ </form>+ {formError ? (+ <p className="my-2 text-center text-sm font-medium text-destructive">+ <span className="font-semibold">Error:</span> {formError}+ </p>+ ) : null}+ </Form>+ </DialogContent>+ </Dialog>+ );+}) as React.FC<UpsertModelDialogProps>;diff --git a/web/src/features/models/components/UpsertModelFormDrawer.tsx b/web/src/features/models/components/UpsertModelFormDrawer.tsxdeleted file mode 100644index a877d618ab..0000000000--- a/web/src/features/models/components/UpsertModelFormDrawer.tsx+++ /dev/null@@ -1,493 +0,0 @@-import { MinusCircle, PlusCircle, X } from "lucide-react";-import Link from "next/link";-import { useEffect, useState } from "react";-import { useForm } from "react-hook-form";-import * as z from "zod/v4";--import { CodeMirrorEditor } from "@/src/components/editor";-import { Button } from "@/src/components/ui/button";-import {- Drawer,- DrawerContent,- DrawerDescription,- DrawerFooter,- DrawerHeader,- DrawerTitle,- DrawerTrigger,-} from "@/src/components/ui/drawer";-import {- Form,- FormControl,- FormDescription,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/src/components/ui/form";-import { Input } from "@/src/components/ui/input";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/src/components/ui/select";-import {- type FormUpsertModel,- FormUpsertModelSchema,- type GetModelResult,-} from "@/src/features/models/validation";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { api } from "@/src/utils/api";-import { zodResolver } from "@hookform/resolvers/zod";-import { useRouter } from "next/router";--import { PricePreview } from "./PricePreview";-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";--type UpsertModelDrawerProps =- | {- action: "create";- children: React.ReactNode;- projectId: string;- prefilledModelData?: {- modelName?: string;- prices?: Record<string, number>;- };- className?: string;- }- | {- action: "edit" | "clone";- children: React.ReactNode;- projectId: string;- modelData: GetModelResult;- className?: string;- };--export const UpsertModelFormDrawer = ({- children,- ...props-}: UpsertModelDrawerProps) => {- const capture = usePostHogClientCapture();- const router = useRouter();- const [formError, setFormError] = useState<string | null>(null);- const utils = api.useUtils();- const [open, setOpen] = useState(false);-- let defaultValues: FormUpsertModel;- if (props.action !== "create") {- defaultValues = {- modelName: props.modelData.modelName,- matchPattern: props.modelData.matchPattern,- tokenizerId: props.modelData.tokenizerId,- tokenizerConfig: JSON.stringify(props.modelData.tokenizerConfig ?? {}),- prices: props.modelData.prices,- };- } else {- defaultValues = {- modelName: props.prefilledModelData?.modelName ?? "",- matchPattern: props.prefilledModelData?.modelName- ? `(?i)^(${props.prefilledModelData?.modelName})$`- : "",- tokenizerId: null,- tokenizerConfig: null,- prices: props.prefilledModelData?.prices ?? {- input: 0.000001,- output: 0.000002,- },- };- }-- const form = useForm({- resolver: zodResolver(- props.action === "edit"- ? FormUpsertModelSchema.omit({ modelName: true }).extend({- modelName: z.string().default(props.modelData.modelName),- })- : FormUpsertModelSchema,- ),- defaultValues,- });- const modelName = form.watch("modelName");- const matchPattern = form.watch("matchPattern");- const tokenizerId = form.watch("tokenizerId");-- // prefill match pattern if model name changes- useEffect(() => {- const getRegexString = (modelName: string) => `(?i)^(${modelName})$`;-- if (- modelName &&- (!matchPattern ||- matchPattern === `(?i)^(${modelName.slice(0, -1)})$` ||- matchPattern === `(?i)^(${modelName})$`)- ) {- form.setValue("matchPattern", getRegexString(modelName));- }- }, [modelName, matchPattern, form]);-- const upsertModelMutation = api.models.upsert.useMutation({- onSuccess: (upsertedModel) => {- utils.models.invalidate();- form.reset();- setOpen(false);- showSuccessToast({- title: `Model ${props.action === "edit" ? "updated" : "created"}`,- description: `The model '${upsertedModel.modelName}' has been successfully ${props.action === "edit" ? "updated" : "created"}. New generations will use these model prices.`,- });- router.push(- `/project/${props.projectId}/settings/models/${upsertedModel.id}`,- );- },- onError: (error) => setFormError(error.message),- });-- const onSubmit = async (values: FormUpsertModel) => {- capture("models:new_form_submit");-- await upsertModelMutation- .mutateAsync({- modelId: props.action === "edit" ? props.modelData.id : null,- projectId: props.projectId,- modelName:- props.action === "edit"- ? props.modelData.modelName- : values.modelName,- matchPattern: values.matchPattern,- prices: values.prices,- tokenizerId: values.tokenizerId,- tokenizerConfig:- values.tokenizerConfig &&- typeof JSON.parse(values.tokenizerConfig) === "object"- ? (JSON.parse(values.tokenizerConfig) as Record<string, number>)- : undefined,- })- .catch((error) => {- setFormError(error.message);- });- };-- return (- <Drawer- open={open}- onOpenChange={(open) => {- if (!open) return; // Only allow closing via cancel key- setOpen(open);- }}- dismissible={false}- onClose={() => {- form.reset();- setFormError(null);- }}- >- <DrawerTrigger- asChild- onClick={() => setOpen(true)}- className={props.className}- title={- props.action === "create"- ? "Create model definition"- : "Edit model definition"- }- >- {children}- </DrawerTrigger>- <DrawerContent>- <DrawerHeader>- <div className="flex items-center justify-between">- <DrawerTitle>- {props.action === "create"- ? "Create Model"- : props.action === "clone"- ? "Clone Model"- : "Edit Model"}- </DrawerTitle>- <Button- variant="ghost"- size="icon"- onClick={() => setOpen(false)}- type="button"- >- <X size={20} />- </Button>- </div>- <DrawerDescription>- {props.action === "edit"- ? props.modelData.modelName- : props.action === "create"- ? "Create a new model configuration to track generation costs."- : null}- </DrawerDescription>- </DrawerHeader>- <Form {...form}>- <form- // eslint-disable-next-line @typescript-eslint/no-misused-promises- onSubmit={form.handleSubmit(onSubmit)}- className="flex h-full max-h-[100vh] flex-col gap-6 overflow-y-auto p-4 pt-0"- >- <FormField- control={form.control}- name="modelName"- disabled={props.action === "edit"}- render={({ field }) => (- <FormItem>- <FormLabel>Model Name</FormLabel>- <FormDescription>- The name of the model. This will be used to reference the- model in the API. You can track price changes of models by- using the same name and match pattern.- </FormDescription>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="matchPattern"- render={({ field }) => (- <FormItem>- <FormLabel>Match pattern</FormLabel>- <FormDescription>- Regular expression (Postgres syntax) to match ingested- generations (model attribute) to this model definition. For- an exact, case-insensitive match to a model name, use the- expression: (?i)^(modelname)$- </FormDescription>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="prices"- render={({ field }) => (- <FormItem>- <FormLabel className="flex items-center gap-2">- Prices- </FormLabel>- <FormDescription>- Set prices per usage type for this model. Usage types must- exactly match the keys of the ingested usage details.- </FormDescription>- <span className="flex flex-col gap-2">- <FormDescription>- Prefill usage types from template:- </FormDescription>- <span className="flex gap-2">- <Button- type="button"- variant="outline"- size="sm"- onClick={() => {- field.onChange({- input: 0,- output: 0,- input_cached_tokens: 0,- output_reasoning_tokens: 0,- ...field.value,- });- }}- >- OpenAI- </Button>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => {- field.onChange({- input: 0,- input_tokens: 0,- output: 0,- output_tokens: 0,- cache_creation_input_tokens: 0,- cache_read_input_tokens: 0,- ...field.value,- });- }}- >- Anthropic- </Button>- </span>- </span>- <FormControl>- <span className="flex flex-col gap-2">- <FormDescription className="grid grid-cols-2 gap-1">- <span>Usage type</span>- <span>Price</span>- </FormDescription>- {Object.entries(field.value).map(- ([key, value], index) => (- <div key={index} className="grid grid-cols-2 gap-1">- <Input- placeholder="Key (e.g. input, output)"- value={key}- onChange={(e) => {- const newPrices = { ...field.value };- const oldValue = newPrices[key];- delete newPrices[key];- newPrices[e.target.value] = oldValue;- field.onChange(newPrices);- }}- />- <div className="flex gap-1">- <Input- type="number"- placeholder="Price per unit"- value={value}- step="0.000001"- onChange={(e) => {- field.onChange({- ...field.value,- [key]: parseFloat(e.target.value),- });- }}- />- <Button- type="button"- variant="outline"- title="Remove price"- size="icon"- onClick={() => {- const newPrices = { ...field.value };- delete newPrices[key];- field.onChange(newPrices);- }}- >- <MinusCircle className="h-4 w-4" />- </Button>- </div>- </div>- ),- )}- <Button- type="button"- variant="ghost"- onClick={() => {- field.onChange({- ...field.value,- new_usage_type: 0.000001,- });- }}- className="flex items-center gap-1"- >- <PlusCircle className="h-4 w-4" />- <span>Add Price</span>- </Button>- <PricePreview prices={field.value} />- </span>- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="tokenizerId"- render={({ field }) => (- <FormItem>- <FormLabel>Tokenizer</FormLabel>- <Select- onValueChange={(tokenizerId) => {- field.onChange(tokenizerId);- if (tokenizerId === "None") {- form.setValue("tokenizerConfig", "{}");- }- }}- defaultValue={field.value ?? "None"}- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select a unit" />- </SelectTrigger>- </FormControl>- <SelectContent>- {["openai", "claude", "None"].map((unit) => (- <SelectItem value={unit} key={unit}>- {unit}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormDescription>- Optionally, Langfuse can tokenize the input and output of a- generation if no unit counts are ingested. This is useful- for e.g. streamed OpenAI completions. For details on the- supported tokenizers, see the{" "}- <Link- href="https://langfuse.com/docs/model-usage-and-cost"- className="underline"- target="_blank"- >- docs- </Link>- .- </FormDescription>- <FormMessage />- </FormItem>- )}- />- {tokenizerId && tokenizerId !== "None" && (- <FormField- control={form.control}- name="tokenizerConfig"- render={({ field }) => (- <FormItem>- <FormLabel>Tokenizer Config</FormLabel>- <CodeMirrorEditor- mode="json"- value={field.value ?? "{}"}- onChange={field.onChange}- minHeight="none"- />- <FormDescription>- The config for the tokenizer. Required for openai. See the{" "}- <Link- href="https://langfuse.com/docs/model-usage-and-cost"- className="underline"- target="_blank"- >- docs- </Link>{" "}- for details.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- )}- <DrawerFooter className="flex-row gap-2">- <Button- type="button"- variant="outline"- onClick={() => setOpen(false)}- className="w-full"- >- Cancel- </Button>-- <Button- type="submit"- className="w-full"- loading={upsertModelMutation.isPending}- >- Submit- </Button>- </DrawerFooter>- </form>- {formError ? (- <p className="my-2 text-center text-sm font-medium text-destructive">- <span className="font-semibold">Error:</span> {formError}- </p>- ) : null}- </Form>- </DrawerContent>- </Drawer>- );-};diff --git a/web/src/features/models/components/pricing-tiers/PricingSection.tsx b/web/src/features/models/components/pricing-tiers/PricingSection.tsxnew file mode 100644index 0000000000..d38f01dae6--- /dev/null+++ b/web/src/features/models/components/pricing-tiers/PricingSection.tsx@@ -0,0 +1,90 @@+import { PlusCircle } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { FormDescription, FormLabel } from "@/src/components/ui/form";+import { Accordion } from "@/src/components/ui/accordion";+import { TierAccordionItem } from "./TierAccordionItem";+import { TierPriceEditor } from "./TierPriceEditor";+import { TierPrefillButtons } from "./TierPrefillButtons";+import type { UseFormReturn, UseFieldArrayReturn } from "react-hook-form";+import type { FormUpsertModel } from "../../validation";++type PricingSectionProps = {+ fields: UseFieldArrayReturn<FormUpsertModel, "pricingTiers">["fields"];+ form: UseFormReturn<FormUpsertModel>;+ remove: UseFieldArrayReturn<FormUpsertModel, "pricingTiers">["remove"];+ addTier: () => void;+};++export type { PricingSectionProps };++export function PricingSection({+ fields,+ form,+ remove,+ addTier,+}: PricingSectionProps) {+ const hasMultipleTiers = fields.length > 1;+ const defaultTierIndex = fields.findIndex((f) => f.isDefault);++ if (!hasMultipleTiers) {+ // SIMPLE VIEW: Just show prices for the single default tier+ return (+ <div className="space-y-4">+ <div>+ <FormLabel>Prices</FormLabel>+ <FormDescription>+ Set prices per usage type for this model. Usage types must exactly+ match the keys of the ingested usage details.+ </FormDescription>+ </div>++ <TierPrefillButtons tierIndex={defaultTierIndex} form={form} />+ <TierPriceEditor+ tierIndex={defaultTierIndex}+ form={form}+ isDefault={true}+ />++ <Button type="button" variant="ghost" onClick={addTier}>+ <PlusCircle className="mr-2 h-4 w-4" />+ Add Custom Pricing Tier+ </Button>+ </div>+ );+ }++ // ACCORDION VIEW: Multiple tiers+ return (+ <div className="space-y-4">+ <div>+ <FormLabel>Pricing Tiers</FormLabel>+ <FormDescription>+ Define pricing rules evaluated in priority order. Tiers are checked+ from top to bottom until conditions match.+ </FormDescription>+ </div>++ <Accordion+ type="multiple"+ defaultValue={fields.map((_, i) => `tier-${i}`)} // All expanded+ className="space-y-2"+ >+ {fields.map((field, index) => (+ <TierAccordionItem+ key={field.id}+ tier={field}+ index={index}+ form={form}+ remove={remove}+ isDefault={field.isDefault}+ />+ ))}+ </Accordion>++ <Button type="button" variant="outline" onClick={addTier}>+ <PlusCircle className="mr-2 h-4 w-4" />+ Add Custom Tier+ </Button>+ </div>+ );+}diff --git a/web/src/features/models/components/pricing-tiers/TierAccordionItem.tsx b/web/src/features/models/components/pricing-tiers/TierAccordionItem.tsxnew file mode 100644index 0000000000..1a099d35b8--- /dev/null+++ b/web/src/features/models/components/pricing-tiers/TierAccordionItem.tsx@@ -0,0 +1,95 @@+import { Trash2 } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { Badge } from "@/src/components/ui/badge";+import {+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/src/components/ui/accordion";+import {+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { TierConditionsEditor } from "./TierConditionsEditor";+import { TierPriceEditor } from "./TierPriceEditor";+import { TierPrefillButtons } from "./TierPrefillButtons";+import type { UseFormReturn, FieldArrayWithId } from "react-hook-form";+import type { FormUpsertModel } from "../../validation";++type TierAccordionItemProps = {+ tier: FieldArrayWithId<FormUpsertModel, "pricingTiers", "id">;+ index: number;+ form: UseFormReturn<FormUpsertModel>;+ remove: (index: number) => void;+ isDefault: boolean;+};++export type { TierAccordionItemProps };++export function TierAccordionItem({+ tier,+ index,+ form,+ remove,+ isDefault,+}: TierAccordionItemProps) {+ return (+ <AccordionItem+ value={`tier-${index}`}+ className="rounded-lg border bg-muted/30"+ >+ <AccordionTrigger className="px-4 hover:no-underline">+ <div className="flex w-full items-center justify-between">+ <div className="flex items-center gap-2">+ <span className="font-semibold">{tier.name}</span>+ {isDefault && <Badge variant="secondary">Default</Badge>}+ <span className="text-xs text-muted-foreground">+ Priority: {tier.priority}+ </span>+ </div>+ {!isDefault && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ remove(index);+ }}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}+ </div>+ </AccordionTrigger>++ <AccordionContent className="space-y-4 px-4 pb-4">+ {/* Tier Name */}+ <FormField+ control={form.control}+ name={`pricingTiers.${index}.name`}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Tier Name</FormLabel>+ <FormControl>+ <Input {...field} disabled={isDefault} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ {/* Conditions (only for non-default) */}+ {!isDefault && <TierConditionsEditor tierIndex={index} form={form} />}++ {/* Prices */}+ {isDefault && <TierPrefillButtons tierIndex={index} form={form} />}+ <TierPriceEditor tierIndex={index} form={form} isDefault={isDefault} />+ </AccordionContent>+ </AccordionItem>+ );+}diff --git a/web/src/features/models/components/pricing-tiers/TierConditionsEditor.tsx b/web/src/features/models/components/pricing-tiers/TierConditionsEditor.tsxnew file mode 100644index 0000000000..6b361785b8--- /dev/null+++ b/web/src/features/models/components/pricing-tiers/TierConditionsEditor.tsx@@ -0,0 +1,172 @@+import { PlusCircle, Trash2 } from "lucide-react";+import { useFieldArray } from "react-hook-form";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { Checkbox } from "@/src/components/ui/checkbox";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import type { UseFormReturn } from "react-hook-form";+import type { FormUpsertModel } from "../../validation";++type TierConditionsEditorProps = {+ tierIndex: number;+ form: UseFormReturn<FormUpsertModel>;+};++export type { TierConditionsEditorProps };++export function TierConditionsEditor({+ tierIndex,+ form,+}: TierConditionsEditorProps) {+ const { fields, append, remove } = useFieldArray({+ control: form.control,+ name: `pricingTiers.${tierIndex}.conditions`,+ });++ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <FormLabel>Conditions</FormLabel>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() =>+ append({+ usageDetailPattern: "",+ operator: "gt",+ value: 0,+ caseSensitive: false,+ })+ }+ >+ <PlusCircle className="mr-1 h-4 w-4" />+ Add Condition+ </Button>+ </div>++ {fields.length === 0 && (+ <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">+ <strong>Warning:</strong> Non-default tiers require at least one+ condition. This tier will fail validation.+ </div>+ )}++ {fields.map((condition, conditionIndex) => (+ <div key={condition.id} className="space-y-3 rounded-lg border p-3">+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium">+ Condition {conditionIndex + 1}+ </span>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => remove(conditionIndex)}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>++ {/* Pattern */}+ <FormField+ control={form.control}+ name={`pricingTiers.${tierIndex}.conditions.${conditionIndex}.usageDetailPattern`}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Usage Detail Pattern (Regex)</FormLabel>+ <FormControl>+ <Input {...field} placeholder="^input" />+ </FormControl>+ <FormDescription>+ Match usage type keys (e.g., ^input, .*cache.*, output_tokens)+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ {/* Operator + Value */}+ <div className="grid grid-cols-2 gap-2">+ <FormField+ control={form.control}+ name={`pricingTiers.${tierIndex}.conditions.${conditionIndex}.operator`}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Operator</FormLabel>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="gt">> (greater than)</SelectItem>+ <SelectItem value="gte">+ >= (greater or equal)+ </SelectItem>+ <SelectItem value="lt">< (less than)</SelectItem>+ <SelectItem value="lte"><= (less or equal)</SelectItem>+ <SelectItem value="eq">= (equals)</SelectItem>+ <SelectItem value="neq">!= (not equals)</SelectItem>+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name={`pricingTiers.${tierIndex}.conditions.${conditionIndex}.value`}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Value</FormLabel>+ <FormControl>+ <Input+ type="number"+ {...field}+ onChange={(e) =>+ field.onChange(parseFloat(e.target.value))+ }+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Case Sensitive */}+ <FormField+ control={form.control}+ name={`pricingTiers.${tierIndex}.conditions.${conditionIndex}.caseSensitive`}+ render={({ field }) => (+ <FormItem className="flex items-center gap-2">+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ <FormLabel className="!mt-0">Case sensitive</FormLabel>+ </FormItem>+ )}+ />+ </div>+ ))}+ </div>+ );+}diff --git a/web/src/features/models/components/pricing-tiers/TierPrefillButtons.tsx b/web/src/features/models/components/pricing-tiers/TierPrefillButtons.tsxnew file mode 100644index 0000000000..c0c17fb203--- /dev/null+++ b/web/src/features/models/components/pricing-tiers/TierPrefillButtons.tsx@@ -0,0 +1,60 @@+import { Button } from "@/src/components/ui/button";+import { FormDescription } from "@/src/components/ui/form";+import type { UseFormReturn } from "react-hook-form";+import type { FormUpsertModel } from "../../validation";++type TierPrefillButtonsProps = {+ tierIndex: number;+ form: UseFormReturn<FormUpsertModel>;+};++export type { TierPrefillButtonsProps };++export function TierPrefillButtons({+ tierIndex,+ form,+}: TierPrefillButtonsProps) {+ const prices = form.watch(`pricingTiers.${tierIndex}.prices`) || {};++ return (+ <div className="space-y-2">+ <FormDescription>Prefill usage types from template:</FormDescription>+ <div className="flex gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => {+ form.setValue(`pricingTiers.${tierIndex}.prices`, {+ input: 0,+ output: 0,+ input_cached_tokens: 0,+ output_reasoning_tokens: 0,+ ...prices,+ });+ }}+ >+ OpenAI+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => {+ form.setValue(`pricingTiers.${tierIndex}.prices`, {+ input: 0,+ input_tokens: 0,+ output: 0,+ output_tokens: 0,+ cache_creation_input_tokens: 0,+ cache_read_input_tokens: 0,+ ...prices,+ });+ }}+ >+ Anthropic+ </Button>+ </div>+ </div>+ );+}diff --git a/web/src/features/models/components/pricing-tiers/TierPriceEditor.tsx b/web/src/features/models/components/pricing-tiers/TierPriceEditor.tsxnew file mode 100644index 0000000000..75c2ec977c--- /dev/null+++ b/web/src/features/models/components/pricing-tiers/TierPriceEditor.tsx@@ -0,0 +1,103 @@+import { MinusCircle, PlusCircle } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { FormLabel } from "@/src/components/ui/form";+import { PricePreview } from "../PricePreview";+import type { UseFormReturn } from "react-hook-form";+import type { FormUpsertModel } from "../../validation";++type TierPriceEditorProps = {+ tierIndex: number;+ form: UseFormReturn<FormUpsertModel>;+ isDefault: boolean;+};++export type { TierPriceEditorProps };++export function TierPriceEditor({+ tierIndex,+ form,+ isDefault,+}: TierPriceEditorProps) {+ const prices = form.watch(`pricingTiers.${tierIndex}.prices`) || {};++ return (+ <div className="space-y-3">+ <FormLabel>Prices</FormLabel>+ <div className="grid grid-cols-2 gap-1 text-sm text-muted-foreground">+ <span>Usage type</span>+ <span>Price</span>+ </div>+ {Object.entries(prices).map(([key, value], priceIndex) => (+ <div key={priceIndex} className="grid grid-cols-2 gap-1">+ <Input+ placeholder="Key (e.g. input, output)"+ value={key}+ disabled={!isDefault}+ onChange={(e) => {+ const newPrices = { ...prices };+ const oldValue = newPrices[key];+ delete newPrices[key];+ newPrices[e.target.value] = oldValue;+ form.setValue(`pricingTiers.${tierIndex}.prices`, newPrices);+ }}+ className={!isDefault ? "cursor-not-allowed bg-muted" : ""}+ />+ <div className="flex gap-1">+ <Input+ type="number"+ placeholder="Price per unit"+ value={value as number}+ step="0.000001"+ onChange={(e) => {+ form.setValue(`pricingTiers.${tierIndex}.prices`, {+ ...prices,+ [key]: parseFloat(e.target.value),+ });+ }}+ />+ {isDefault && (+ <Button+ type="button"+ variant="outline"+ title="Remove price"+ size="icon"+ onClick={() => {+ const newPrices = { ...prices };+ delete newPrices[key];+ form.setValue(`pricingTiers.${tierIndex}.prices`, newPrices);+ }}+ >+ <MinusCircle className="h-4 w-4" />+ </Button>+ )}+ </div>+ </div>+ ))}+ {isDefault && (+ <Button+ type="button"+ variant="ghost"+ onClick={() => {+ // Generate unique key name+ let counter = 1;+ let newKey = "new_usage_type";+ while (prices[newKey] !== undefined) {+ newKey = `new_usage_type_${counter}`;+ counter++;+ }+ form.setValue(`pricingTiers.${tierIndex}.prices`, {+ ...prices,+ [newKey]: 0.000001,+ });+ }}+ className="flex items-center gap-1"+ >+ <PlusCircle className="h-4 w-4" />+ <span>Add Price</span>+ </Button>+ )}+ <PricePreview prices={prices} />+ </div>+ );+}diff --git a/web/src/features/models/components/test-match/MatchedModelCard.tsx b/web/src/features/models/components/test-match/MatchedModelCard.tsxnew file mode 100644index 0000000000..9c48838902--- /dev/null+++ b/web/src/features/models/components/test-match/MatchedModelCard.tsx@@ -0,0 +1,54 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import { Badge } from "@/src/components/ui/badge";++type MatchedModelCardProps = {+ projectId: string;+ model: {+ id: string;+ modelName: string;+ matchPattern: string;+ projectId: string | null;+ };+ pricingTierId: string;+};++export type { MatchedModelCardProps };++export function MatchedModelCard({ model }: MatchedModelCardProps) {+ const isLangfuseModel = !model.projectId;++ return (+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">+ Matched Model+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ <div className="flex items-center gap-2">+ <span className="font-mono text-base font-semibold">+ {model.modelName}+ </span>+ {isLangfuseModel && (+ <Badge variant="secondary" className="text-xs">+ Langfuse+ </Badge>+ )}+ </div>+ <div className="space-y-1">+ <div className="text-xs font-medium text-muted-foreground">+ Pattern:+ </div>+ <code className="block break-all rounded bg-muted/50 p-2 text-xs">+ {model.matchPattern}+ </code>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/web/src/features/models/components/test-match/MatchedTierCard.tsx b/web/src/features/models/components/test-match/MatchedTierCard.tsxnew file mode 100644index 0000000000..7b2155ac77--- /dev/null+++ b/web/src/features/models/components/test-match/MatchedTierCard.tsx@@ -0,0 +1,84 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import { Badge } from "@/src/components/ui/badge";+import { useMemo } from "react";+import { usePriceUnitMultiplier } from "@/src/features/models/hooks/usePriceUnitMultiplier";+import Decimal from "decimal.js";+import { getMaxDecimals } from "@/src/features/models/utils";++type MatchedTierCardProps = {+ tier: {+ id: string;+ name: string;+ priority: number;+ isDefault: boolean;+ prices: Record<string, number>;+ };+};++export type { MatchedTierCardProps };++export function MatchedTierCard({ tier }: MatchedTierCardProps) {+ const { priceUnit, priceUnitMultiplier } = usePriceUnitMultiplier();++ const maxDecimals = useMemo(+ () =>+ Math.max(+ ...Object.values(tier.prices).map((price) =>+ getMaxDecimals(price, priceUnitMultiplier),+ ),+ ),+ [tier.prices, priceUnitMultiplier],+ );++ return (+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">+ Matched Pricing Tier+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-4">+ <div className="flex items-center gap-2">+ <span className="text-base font-semibold">{tier.name}</span>+ {tier.isDefault && (+ <Badge variant="secondary" className="text-xs">+ Default+ </Badge>+ )}+ <span className="text-xs text-muted-foreground">+ Priority: {tier.priority}+ </span>+ </div>++ <div>+ <div className="mb-2 text-xs font-medium text-muted-foreground">+ Prices (per {priceUnit}):+ </div>+ <div className="space-y-1.5">+ {Object.entries(tier.prices).map(([usageType, price]) => (+ <div+ key={usageType}+ className="flex items-center justify-between rounded bg-muted/50 px-3 py-1.5"+ >+ <span className="font-mono text-xs text-muted-foreground">+ {usageType}:+ </span>+ <span className="font-mono text-sm font-semibold">+ $+ {new Decimal(price)+ .mul(priceUnitMultiplier)+ .toFixed(maxDecimals)}+ </span>+ </div>+ ))}+ </div>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/web/src/features/models/components/test-match/NoMatchDisplay.tsx b/web/src/features/models/components/test-match/NoMatchDisplay.tsxnew file mode 100644index 0000000000..e87cae4bba--- /dev/null+++ b/web/src/features/models/components/test-match/NoMatchDisplay.tsx@@ -0,0 +1,41 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import { AlertCircle } from "lucide-react";++type NoMatchDisplayProps = {+ modelName: string;+};++export type { NoMatchDisplayProps };++export function NoMatchDisplay({ modelName }: NoMatchDisplayProps) {+ return (+ <Card className="border-destructive/50 bg-destructive/5">+ <CardHeader>+ <CardTitle className="flex items-center gap-2 text-base text-destructive">+ <AlertCircle className="h-5 w-5" />+ No Match Found+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-4">+ <p className="text-sm">+ No model configuration matches "{modelName}" in this+ project.+ </p>++ <div>+ <p className="mb-2 text-sm font-medium">Suggestions:</p>+ <ul className="list-inside list-disc space-y-1 text-sm text-muted-foreground">+ <li>Check your model name spelling</li>+ <li>View existing models and their match patterns</li>+ <li>Create a new model definition</li>+ </ul>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/web/src/features/models/components/test-match/TestModelMatchButton.tsx b/web/src/features/models/components/test-match/TestModelMatchButton.tsxnew file mode 100644index 0000000000..0156a75a89--- /dev/null+++ b/web/src/features/models/components/test-match/TestModelMatchButton.tsx@@ -0,0 +1,38 @@+import { useState } from "react";+import { ActionButton } from "@/src/components/ActionButton";+import { TestModelMatchDialog } from "./TestModelMatchDialog";+import { FlaskConical } from "lucide-react";+import { type ButtonProps } from "@/src/components/ui/button";++type TestModelMatchButtonProps = {+ projectId: string;+ variant?: ButtonProps["variant"];+};++export type { TestModelMatchButtonProps };++export function TestModelMatchButton({+ projectId,+ variant,+}: TestModelMatchButtonProps) {+ const [open, setOpen] = useState(false);++ return (+ <>+ <ActionButton+ variant={variant ?? "secondary"}+ icon={<FlaskConical className="h-4 w-4" />}+ onClick={() => setOpen(true)}+ data-testid="test-model-match-button"+ >+ Test Model Match+ </ActionButton>++ <TestModelMatchDialog+ projectId={projectId}+ open={open}+ onOpenChange={setOpen}+ />+ </>+ );+}diff --git a/web/src/features/models/components/test-match/TestModelMatchDialog.tsx b/web/src/features/models/components/test-match/TestModelMatchDialog.tsxnew file mode 100644index 0000000000..1bed16a136--- /dev/null+++ b/web/src/features/models/components/test-match/TestModelMatchDialog.tsx@@ -0,0 +1,192 @@+import { useState, useEffect } from "react";+import Link from "next/link";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogBody,+} from "@/src/components/ui/dialog";+import { Input } from "@/src/components/ui/input";+import { Button } from "@/src/components/ui/button";+import { api } from "@/src/utils/api";+import { UsageDetailsEditor } from "./UsageDetailsEditor";+import { MatchedModelCard } from "./MatchedModelCard";+import { MatchedTierCard } from "./MatchedTierCard";+import { NoMatchDisplay } from "./NoMatchDisplay";+import { Loader2, CheckCircle, SquareArrowOutUpRight } from "lucide-react";++type TestModelMatchDialogProps = {+ projectId: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+};++export type { TestModelMatchDialogProps };++export function TestModelMatchDialog({+ projectId,+ open,+ onOpenChange,+}: TestModelMatchDialogProps) {+ const [modelName, setModelName] = useState("");+ const [usageDetails, setUsageDetails] = useState<Record<string, number>>({});+ const [hasSubmitted, setHasSubmitted] = useState(false);++ // Query for match result - only enabled after submit+ const { data, isLoading, error, refetch } = api.models.testMatch.useQuery(+ {+ projectId,+ modelName,+ usageDetails,+ },+ {+ enabled: false, // Manual trigger only+ },+ );++ // Handle form submission+ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ if (modelName.trim()) {+ setHasSubmitted(true);+ void refetch();+ }+ };++ // Reset state when dialog closes+ useEffect(() => {+ if (!open) {+ setModelName("");+ setUsageDetails({});+ setHasSubmitted(false);+ }+ }, [open]);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent size="lg" className="min-h-[62vh] overflow-y-auto">+ <form onSubmit={handleSubmit} className="flex flex-1 flex-col">+ <DialogHeader>+ <DialogTitle>Test Model Match</DialogTitle>+ <DialogDescription className="mt-1">+ Test which model and pricing tier your ingestion data would match+ against.+ </DialogDescription>+ </DialogHeader>++ <DialogBody className="grid grid-cols-[1fr,1px,1fr] gap-6">+ {/* Left Column: Input Form */}+ <div className="flex flex-col justify-between space-y-6">+ <div className="space-y-6">+ {/* Model Name Input */}+ <div className="space-y-2">+ <div className="text-sm font-medium">Model Name *</div>+ <div className="text-sm text-muted-foreground">+ The model name on your generations.+ </div>+ <Input+ placeholder="e.g. gpt-4-turbo"+ value={modelName}+ onChange={(e) => setModelName(e.target.value.trim())}+ autoFocus+ required+ />+ </div>++ {/* Usage Details Editor */}+ <UsageDetailsEditor+ usageDetails={usageDetails}+ onChange={setUsageDetails}+ />+ </div>++ {/* Buttons at bottom of left column */}+ <div className="flex gap-2 border-t pt-4">+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ className="flex-1"+ >+ Close+ </Button>+ <Button+ type="submit"+ disabled={!modelName.trim() || isLoading}+ className="flex-1"+ >+ Test Match+ </Button>+ </div>+ </div>++ {/* Vertical Divider */}+ <div className="bg-border" />++ {/* Right Column: Results Panel */}+ <div className="flex flex-col justify-between">+ <div className="space-y-4 overflow-y-auto pb-4">+ {hasSubmitted && (+ <>+ {isLoading && (+ <div className="flex min-h-[300px] items-center justify-center gap-2 rounded-lg border bg-muted/30 p-6 text-muted-foreground">+ <Loader2 className="h-5 w-5 animate-spin" />+ <span>Testing match...</span>+ </div>+ )}++ {error && (+ <div className="rounded-lg border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive">+ Error: {error.message}+ </div>+ )}++ {!isLoading && !error && data && (+ <>+ {data.matched ? (+ <>+ <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-2.5 dark:border-green-900 dark:bg-green-950">+ <CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400" />+ <span className="text-sm font-medium text-green-900 dark:text-green-100">+ Match Found+ </span>+ </div>+ <MatchedModelCard+ projectId={projectId}+ model={data.model}+ pricingTierId={data.matchedTier.id}+ />+ <MatchedTierCard tier={data.matchedTier} />+ </>+ ) : (+ <NoMatchDisplay modelName={modelName} />+ )}+ </>+ )}+ </>+ )}+ </div>++ {/* View Model Details button at bottom */}+ {hasSubmitted && !isLoading && !error && data?.matched && (+ <div className="border-t pt-4">+ <Button variant="outline" asChild className="w-full">+ <Link+ href={`/project/${projectId}/settings/models/${data.model.id}?pricingTier=${data.matchedTier.id}`}+ target="_blank"+ >+ View Model Details+ <SquareArrowOutUpRight className="ml-2 h-4 w-4" />+ </Link>+ </Button>+ </div>+ )}+ </div>+ </DialogBody>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/models/components/test-match/UsageDetailsEditor.tsx b/web/src/features/models/components/test-match/UsageDetailsEditor.tsxnew file mode 100644index 0000000000..b49b5ffd0a--- /dev/null+++ b/web/src/features/models/components/test-match/UsageDetailsEditor.tsx@@ -0,0 +1,152 @@+import { PlusCircle, Trash2 } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { useState } from "react";++type UsageDetailsEditorProps = {+ usageDetails: Record<string, number>;+ onChange: (usageDetails: Record<string, number>) => void;+};++export type { UsageDetailsEditorProps };++export function UsageDetailsEditor({+ usageDetails,+ onChange,+}: UsageDetailsEditorProps) {+ const [entries, setEntries] = useState<Array<{ key: string; value: number }>>(+ Object.entries(usageDetails).map(([key, value]) => ({ key, value })),+ );++ const handleUpdate = (newEntries: Array<{ key: string; value: number }>) => {+ setEntries(newEntries);+ const newUsageDetails = Object.fromEntries(+ newEntries+ .filter((e) => e.key.trim() !== "")+ .map((e) => [e.key, e.value]),+ );+ onChange(newUsageDetails);+ };++ const handleAddRow = () => {+ handleUpdate([...entries, { key: "", value: 0 }]);+ };++ const handleRemoveRow = (index: number) => {+ handleUpdate(entries.filter((_, i) => i !== index));+ };++ const handleKeyChange = (index: number, key: string) => {+ const newEntries = [...entries];+ newEntries[index] = { ...newEntries[index], key };+ handleUpdate(newEntries);+ };++ const handleValueChange = (index: number, value: number) => {+ const newEntries = [...entries];+ newEntries[index] = { ...newEntries[index], value };+ handleUpdate(newEntries);+ };++ const applyTemplate = (template: Record<string, number>) => {+ const newEntries = Object.entries(template).map(([key, value]) => ({+ key,+ value,+ }));+ handleUpdate(newEntries);+ };++ return (+ <div className="space-y-4">+ <div>+ <div className="pb-2 text-sm font-medium">Usage Details (optional)</div>+ <div className="text-sm text-muted-foreground">+ Add usage details to test pricing tier matching. Leave empty to match+ the default tier.+ </div>+ </div>++ {/* Template Buttons */}+ <div className="space-y-2">+ <div className="text-sm text-muted-foreground">+ Prefill from template:+ </div>+ <div className="flex gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() =>+ applyTemplate({+ input: 1000,+ output: 500,+ })+ }+ >+ OpenAI+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() =>+ applyTemplate({+ input_tokens: 1000,+ output_tokens: 500,+ cache_read_input_tokens: 0,+ })+ }+ >+ Anthropic+ </Button>+ </div>+ </div>++ {/* Usage Details Table */}+ {entries.length > 0 ? (+ <div className="space-y-2 rounded-lg border p-3">+ <div className="grid grid-cols-[1fr,1fr,auto] gap-2 text-sm font-medium">+ <div>Usage Type</div>+ <div>Value</div>+ <div className="w-10" />+ </div>+ {entries.map((entry, index) => (+ <div key={index} className="grid grid-cols-[1fr,1fr,auto] gap-2">+ <Input+ placeholder="e.g. input"+ value={entry.key}+ onChange={(e) => handleKeyChange(index, e.target.value)}+ />+ <Input+ type="number"+ placeholder="0"+ value={entry.value}+ onChange={(e) =>+ handleValueChange(index, parseFloat(e.target.value) || 0)+ }+ />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => handleRemoveRow(index)}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ ))}+ </div>+ ) : null}++ <Button+ type="button"+ variant="ghost"+ onClick={handleAddRow}+ className="w-full"+ >+ <PlusCircle className="mr-2 h-4 w-4" />+ Add Usage Type+ </Button>+ </div>+ );+}diff --git a/web/src/features/models/validation.ts b/web/src/features/models/validation.tsindex ba5762f4ce..3b9ee403c3 100644--- a/web/src/features/models/validation.ts+++ b/web/src/features/models/validation.ts@@ -1,16 +1,49 @@import { z } from "zod/v4";+import {+ PricingTierConditionSchema,+ PricingTierInputSchema,+ validatePricingTiers,+} from "@langfuse/shared";export const UsageTypeSchema = z.string().regex(/^[a-zA-Z0-9_-]+$/);export const PriceSchema = z.number().nonnegative();export const TokenizerSchema = z.enum(["openai", "claude"]).nullish();-export const PriceMapSchema = z- .record(UsageTypeSchema, PriceSchema.optional())- .transform((obj) => {- return Object.fromEntries(- Object.entries(obj).filter(([_, value]) => Boolean(value)),- );- })- .pipe(z.record(UsageTypeSchema, PriceSchema));+// Input version: allows optional prices for form+export const PriceMapInputSchema = z.record(+ UsageTypeSchema,+ PriceSchema.optional(),+);++// Output version: filtered to only defined prices+export const PriceMapSchema = PriceMapInputSchema.transform((obj) => {+ return Object.fromEntries(+ Object.entries(obj).filter(([_, value]) => Boolean(value)),+ ) as Record<string, number>;+}).pipe(z.record(UsageTypeSchema, PriceSchema));++export const PricingTierSchema = z.object({+ id: z.string(),+ name: z.string(),+ isDefault: z.boolean(),+ priority: z.number(),+ conditions: z.array(PricingTierConditionSchema),+ prices: PriceMapSchema,+});++export type PricingTier = z.infer<typeof PricingTierSchema>;++// Form-level tier schema (includes optional id for edit mode)+export const FormPricingTierSchema = z.object({+ id: z.string().optional(), // For existing tiers in edit mode+ name: z.string().min(1, "Tier name is required"),+ isDefault: z.boolean(),+ priority: z.number().int(),+ conditions: z.array(PricingTierConditionSchema),+ prices: PriceMapInputSchema, // Use input schema for form+});++// Use input type for form (allows optional/default fields)+export type FormPricingTier = z.input<typeof FormPricingTierSchema>;export const GetModelResultSchema = z.object({id: z.string(),@@ -22,29 +55,40 @@ export const GetModelResultSchema = z.object({z.string(),]),tokenizerId: TokenizerSchema,- prices: PriceMapSchema,+ pricingTiers: z.array(PricingTierSchema),lastUsed: z.date().nullish(),});export type GetModelResult = z.infer<typeof GetModelResultSchema>;-export const UpsertModelSchema = z.object({- modelId: z.string().nullable(),- projectId: z.string(),- modelName: z.string().min(1),- matchPattern: z.string().min(1),- tokenizerId: z- .enum(["openai", "claude", "None"])- .nullish()- .transform((value) => {- return value === "None" ? null : value;- })- .pipe(TokenizerSchema.nullish()),- tokenizerConfig: z- .record(z.string(), z.union([z.string(), z.coerce.number()]))- .optional(),- prices: PriceMapSchema,-});+export const UpsertModelSchema = z+ .object({+ modelId: z.string().nullable(),+ projectId: z.string(),+ modelName: z.string().min(1),+ matchPattern: z.string().min(1),+ tokenizerId: z+ .enum(["openai", "claude", "None"])+ .nullish()+ .transform((value) => {+ return value === "None" ? null : value;+ })+ .pipe(TokenizerSchema.nullish()),+ tokenizerConfig: z+ .record(z.string(), z.union([z.string(), z.coerce.number()]))+ .optional(),+ pricingTiers: z.array(PricingTierInputSchema),+ })+ .refine(+ (data) => {+ const result = validatePricingTiers(data.pricingTiers);+ return result.valid;+ },+ {+ message: "Invalid pricing tiers configuration",+ path: ["pricingTiers"],+ },+ );export type UpsertModel = z.infer<typeof UpsertModelSchema>;export const FormUpsertModelSchema = z.object({@@ -68,9 +112,11 @@ export const FormUpsertModelSchema = z.object({).transform((value) => (value === "{}" ? undefined : value)).nullish(),- prices: PriceMapSchema,+ pricingTiers: z.array(FormPricingTierSchema),});-export type FormUpsertModel = z.infer<typeof FormUpsertModelSchema>;++// Use input type for form (allows optional/default fields from Zod schemas)+export type FormUpsertModel = z.input<typeof FormUpsertModelSchema>;export enum PriceUnit {PerUnit = "per unit",diff --git a/web/src/features/public-api/types/models.ts b/web/src/features/public-api/types/models.tsindex 25900c3fea..7deeada67c 100644--- a/web/src/features/public-api/types/models.ts+++ b/web/src/features/public-api/types/models.ts@@ -7,6 +7,12 @@ import {} from "@langfuse/shared";import { z } from "zod/v4";import { type Decimal } from "decimal.js";+import {+ validatePricingTiers,+ PricingTierConditionSchema,+ PricingTierInputSchema,+ type PricingTierCondition,+} from "@langfuse/shared";/*** Objects@@ -21,6 +27,18 @@ const APIModelUsageUnit = z.enum(["IMAGES",]);+/**+ * API Pricing Tier Definition (response)+ */+const APIPricingTier = z.object({+ id: z.string(),+ name: z.string(),+ isDefault: z.boolean(),+ priority: z.number().int(),+ conditions: z.array(PricingTierConditionSchema),+ prices: z.record(z.string(), z.number()),+});+const APIModelDefinition = z.object({id: z.string(),@@ -36,6 +54,7 @@ const APIModelDefinition = zisLangfuseManaged: z.boolean(),createdAt: z.coerce.date(),prices: z.record(z.string(), z.object({ price: z.number() })),+ pricingTiers: z.array(APIPricingTier),}).strict();@@ -51,26 +70,59 @@ export function prismaToApiModelDefinition({unit,// eslint-disable-next-line @typescript-eslint/no-unused-varsupdatedAt,- Price,+ pricingTiers,...model-}: PrismaModel & { Price: { usageType: string; price: Decimal }[] }): z.infer<- typeof APIModelDefinition-> {- return {- ...model,- unit: unit as PrismaModelUsageUnit,- inputPrice: inputPrice?.toNumber() ?? null,- outputPrice: outputPrice?.toNumber() ?? null,- totalPrice: totalPrice?.toNumber() ?? null,- isLangfuseManaged: !Boolean(projectId),- prices: Price.reduce(+}: PrismaModel & {+ pricingTiers?: Array<{+ id: string;+ name: string;+ isDefault: boolean;+ priority: number;+ conditions: unknown; // JsonValue from Prisma+ prices: Array<{ usageType: string; price: Decimal }>;+ }>;+}): z.infer<typeof APIModelDefinition> {+ // Find default tier for backward compatibility fields+ const defaultTier = pricingTiers?.find((t) => t.isDefault);+ const defaultTierPrices = defaultTier?.prices;++ let flatPrices: Record<string, { price: number }> = {};++ if (defaultTierPrices) {+ // Build backward-compatible flat prices from default tier+ flatPrices = defaultTierPrices.reduce((acc, p) => {acc[p.usageType] = { price: p.price.toNumber() };return acc;},- {} as z.infer<typeof APIModelDefinition>["prices"],- ),+ {} as Record<string, { price: number }>,+ );+ }++ return {+ ...model,+ unit: unit as PrismaModelUsageUnit,+ inputPrice: flatPrices.input?.price ?? inputPrice?.toNumber() ?? null,+ outputPrice: flatPrices.output?.price ?? outputPrice?.toNumber() ?? null,+ totalPrice: flatPrices.total?.price ?? totalPrice?.toNumber() ?? null,+ prices: flatPrices,+ isLangfuseManaged: !Boolean(projectId),+ pricingTiers:+ pricingTiers?.map((tier) => ({+ id: tier.id,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions as PricingTierCondition[],+ prices: tier.prices.reduce(+ (acc, p) => {+ acc[p.usageType] = p.price.toNumber();+ return acc;+ },+ {} as Record<string, number>,+ ),+ })) ?? [],};}@@ -100,20 +152,59 @@ export const PostModelsV1Body = ztotalPrice: z.number().nonnegative().nullish(),unit: APIModelUsageUnit,tokenizerId: z.enum(["openai", "claude"]).nullish(),- tokenizerConfig: jsonSchema.nullish(), // Assuming Prisma.JsonValue is any type+ tokenizerConfig: jsonSchema.nullish(),+ pricingTiers: z.array(PricingTierInputSchema).nullish(),})- .refine(- ({ inputPrice, outputPrice, totalPrice }) => {- if (inputPrice || outputPrice) {- return !totalPrice;+ .superRefine((data, ctx) => {+ const hasFlatPrices =+ data.inputPrice != null ||+ data.outputPrice != null ||+ data.totalPrice != null;+ const hasTiers = data.pricingTiers && data.pricingTiers.length > 0;++ // Validation 1: Must provide either flat prices OR pricing tiers (not both, not neither)+ if (hasFlatPrices && hasTiers) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ "Must provide either flat prices (inputPrice/outputPrice/totalPrice) OR pricingTiers, not both",+ });+ return;+ }++ if (!hasFlatPrices && !hasTiers) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ "Must provide either flat prices (inputPrice/outputPrice/totalPrice) OR pricingTiers",+ });+ return;+ }++ // Validation 2: If using flat prices, validate totalPrice constraint+ if (hasFlatPrices) {+ if ((data.inputPrice || data.outputPrice) && data.totalPrice) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["totalPrice"],+ message:+ "If input and/or output price is set, total price must be null",+ });+ }+ }++ // Validation 3: If using pricing tiers, validate them+ if (hasTiers) {+ const result = validatePricingTiers(data.pricingTiers!);+ if (!result.valid) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["pricingTiers"],+ message: result.error,+ });}- return true;- },- {- path: ["totalPrice"],- message: "If input and/or output price is set, total price must be null",- },- );+ }+ });export const PostModelsV1Response = APIModelDefinition.strict();// GET /models/{modelId}diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.tsindex ed19880dd7..7cb95661e6 100644--- a/web/src/features/public-api/types/observations.ts+++ b/web/src/features/public-api/types/observations.ts@@ -80,6 +80,8 @@ export const APIObservation = zpromptTokens: z.number(), // backwards compatibilitycompletionTokens: z.number(), // backwards compatibilitytotalTokens: z.number(), // backwards compatibility+ usagePricingTierName: z.string().nullable(),+ usagePricingTierId: z.string().nullable(),// matched modelmodelId: z.string().nullable(),diff --git a/web/src/pages/api/public/models/[modelId]/index.ts b/web/src/pages/api/public/models/[modelId]/index.tsindex a802a75f17..e0e79987db 100644--- a/web/src/pages/api/public/models/[modelId]/index.ts+++ b/web/src/pages/api/public/models/[modelId]/index.ts@@ -37,17 +37,33 @@ export default withMiddlewares({],},include: {- Price: {- select: { usageType: true, price: true },+ pricingTiers: {+ select: {+ id: true,+ name: true,+ isDefault: true,+ priority: true,+ conditions: true,+ prices: {+ select: {+ usageType: true,+ price: true,+ },+ },+ },+ orderBy: { priority: "asc" },},},});+if (!model) {throw new LangfuseNotFoundError("No model with this id found.");}+return prismaToApiModelDefinition(model);},}),+DELETE: createAuthedProjectAPIRoute({name: "Delete model",querySchema: DeleteModelV1Query,diff --git a/web/src/pages/api/public/models/index.ts b/web/src/pages/api/public/models/index.tsindex baf3f2b82f..2d72c3ad83 100644--- a/web/src/pages/api/public/models/index.ts+++ b/web/src/pages/api/public/models/index.ts@@ -1,4 +1,4 @@-import { prisma } from "@langfuse/shared/src/db";+import { prisma, Prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { clearModelCacheForProject } from "@langfuse/shared/src/server";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";@@ -12,7 +12,6 @@ import {import { InvalidRequestError } from "@langfuse/shared";import { isValidPostgresRegex } from "@/src/features/models/server/isValidPostgresRegex";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { type Decimal } from "decimal.js";export default withMiddlewares({GET: createAuthedProjectAPIRoute({@@ -42,8 +41,21 @@ export default withMiddlewares({},],include: {- Price: {- select: { usageType: true, price: true },+ pricingTiers: {+ select: {+ id: true,+ name: true,+ isDefault: true,+ priority: true,+ conditions: true,+ prices: {+ select: {+ usageType: true,+ price: true,+ },+ },+ },+ orderBy: { priority: "asc" },},},take: query.limit,@@ -86,9 +98,23 @@ export default withMiddlewares({"matchPattern is not a valid regex pattern (Postgres)",);}- const { tokenizerConfig, ...rest } = body;+ const { tokenizerConfig, pricingTiers: tierData, ...rest } = body;const model = await prisma.$transaction(async (tx) => {+ const existingModelName = await tx.model.findFirst({+ where: {+ projectId: auth.scope.projectId,+ modelName: body.modelName,+ },+ });++ if (existingModelName) {+ throw new InvalidRequestError(+ `Model name '${body.modelName}' already exists in project`,+ );+ }++ // 1. Create modelconst createdModel = await tx.model.create({data: {...rest,@@ -97,26 +123,73 @@ export default withMiddlewares({},});- const prices = [- { usageType: "input", price: body.inputPrice },- { usageType: "output", price: body.outputPrice },- { usageType: "total", price: body.totalPrice },- ];-- await Promise.all(- prices- .filter(({ price }) => price != null)- .map(({ usageType, price }) =>- tx.price.create({- data: {- modelId: createdModel.id,- projectId: createdModel.projectId,- usageType,- price: price as number, // type guard checked in array filter- },- }),- ),- );+ // 2. Handle pricing: flat prices OR pricing tiers+ if (tierData && tierData.length > 0) {+ // NEW: Create pricing tiers+ for (const tier of tierData) {+ // Create tier (Prisma generates CUID)+ const createdTier = await tx.pricingTier.create({+ data: {+ modelId: createdModel.id,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ },+ });++ // Create prices for this tier+ await Promise.all(+ Object.entries(tier.prices).map(([usageType, price]) =>+ tx.price.create({+ data: {+ modelId: createdModel.id,+ projectId: createdModel.projectId,+ pricingTierId: createdTier.id,+ usageType,+ price: new Prisma.Decimal(price),+ },+ }),+ ),+ );+ }+ } else {+ // BACKWARD COMPATIBLE: Create default tier from flat prices+ const defaultTierId = `${createdModel.id}_tier_default`;++ const defaultTier = await tx.pricingTier.create({+ data: {+ id: defaultTierId,+ modelId: createdModel.id,+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ },+ });++ const prices = [+ { usageType: "input", price: body.inputPrice },+ { usageType: "output", price: body.outputPrice },+ { usageType: "total", price: body.totalPrice },+ ];++ await Promise.all(+ prices+ .filter(({ price }) => price != null)+ .map(({ usageType, price }) =>+ tx.price.create({+ data: {+ modelId: createdModel.id,+ projectId: createdModel.projectId,+ pricingTierId: defaultTier.id,+ usageType,+ price: new Prisma.Decimal(price as number), // type guard checked in array filter+ },+ }),+ ),+ );+ }await auditLog({action: "create",@@ -134,15 +207,34 @@ export default withMiddlewares({// Clear model cache for the project after successful creationawait clearModelCacheForProject(auth.scope.projectId);- return prismaToApiModelDefinition({- ...model,- Price: (["inputPrice", "outputPrice", "totalPrice"] as const)- .filter((key) => model[key] != null)- .map((key) => ({- usageType: key.split("Price")[0],- price: model[key] as Decimal,- })),+ // Fetch the created model with pricingTiers relation+ const modelWithTiers = await prisma.model.findUnique({+ where: { id: model.id },+ include: {+ pricingTiers: {+ select: {+ id: true,+ name: true,+ isDefault: true,+ priority: true,+ conditions: true,+ prices: {+ select: {+ usageType: true,+ price: true,+ },+ },+ },+ orderBy: { priority: "asc" },+ },+ },});++ if (!modelWithTiers) {+ throw new InvalidRequestError("Failed to fetch created model");+ }++ return prismaToApiModelDefinition(modelWithTiers);},}),});diff --git a/web/src/pages/project/[projectId]/settings/models/[modelId].tsx b/web/src/pages/project/[projectId]/settings/models/[modelId].tsxindex 8d0d1ac061..0eb2beb6ef 100644--- a/web/src/pages/project/[projectId]/settings/models/[modelId].tsx+++ b/web/src/pages/project/[projectId]/settings/models/[modelId].tsx@@ -10,23 +10,39 @@ import {import { DeleteModelButton } from "@/src/features/models/components/DeleteModelButton";import { EditModelButton } from "@/src/features/models/components/EditModelButton";import { CloneModelButton } from "@/src/features/models/components/CloneModelButton";+import { TestModelMatchButton } from "@/src/features/models/components/test-match/TestModelMatchButton";import { JSONView } from "@/src/components/ui/CodeJsonViewer";import Link from "next/link";import { Button } from "@/src/components/ui/button";import { getMaxDecimals } from "@/src/features/models/utils";import Decimal from "decimal.js";import { PriceUnitSelector } from "@/src/features/models/components/PriceUnitSelector";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { usePriceUnitMultiplier } from "@/src/features/models/hooks/usePriceUnitMultiplier";import Generations from "@/src/components/table/use-cases/observations";import Page from "@/src/components/layouts/page";-import { SquareArrowOutUpRight } from "lucide-react";+import { SquareArrowOutUpRight, Info as InfoIcon } from "lucide-react";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import { CodeMirrorEditor } from "@/src/components/editor";+import { useEffect } from "react";export default function ModelDetailPage() {const router = useRouter();const { priceUnit, priceUnitMultiplier } = usePriceUnitMultiplier();const projectId = router.query.projectId as string;const modelId = router.query.modelId as string;+ const pricingTierParam = router.query.pricingTier as string | undefined;const hasWriteAccess = useHasProjectAccess({projectId,scope: "models:CUD",@@ -37,14 +53,46 @@ export default function ModelDetailPage() {{ enabled: !!projectId && !!modelId },);+ // Get default tier or first tier by priority+ const defaultTier = useMemo(() => {+ if (!model?.pricingTiers || model.pricingTiers.length === 0) return null;+ return model.pricingTiers.find((t) => t.isDefault) || model.pricingTiers[0];+ }, [model?.pricingTiers]);++ // State for selected pricing tier - initialize from URL param+ const [selectedTierId, setSelectedTierId] = useState<string | null>(+ pricingTierParam ?? null,+ );++ // Sync with URL parameter when it changes+ useEffect(() => {+ if (pricingTierParam && model?.pricingTiers) {+ const tierExists = model.pricingTiers.some(+ (t) => t.id === pricingTierParam,+ );+ if (tierExists) {+ setSelectedTierId(pricingTierParam);+ }+ }+ }, [pricingTierParam, model?.pricingTiers]);++ // Get the active tier (selected or default)+ const activeTier = useMemo(() => {+ if (!model?.pricingTiers) return null;+ if (selectedTierId) {+ return model.pricingTiers.find((t) => t.id === selectedTierId) || null;+ }+ return defaultTier;+ }, [model?.pricingTiers, selectedTierId, defaultTier]);+const maxDecimals = useMemo(() =>Math.max(- ...Object.values(model?.prices ?? {}).map((price) =>+ ...Object.values(activeTier?.prices ?? {}).map((price) =>getMaxDecimals(price, priceUnitMultiplier),),),- [model?.prices, priceUnitMultiplier],+ [activeTier?.prices, priceUnitMultiplier],);// If not found, redirect to models page@@ -89,21 +137,27 @@ export default function ModelDetailPage() {],actionButtonsRight: (<div className="flex gap-2">- {hasWriteAccess &&- (!isLangfuseModel ? (- <>- <EditModelButton projectId={projectId} modelData={model} />- <DeleteModelButton- projectId={projectId}- modelData={model}- onSuccess={() => {- void router.push(`/project/${projectId}/settings/models`);- }}- />- </>- ) : (- <CloneModelButton projectId={projectId} modelData={model} />- ))}+ {hasWriteAccess && (+ <>+ <TestModelMatchButton projectId={projectId} variant="outline" />+ {!isLangfuseModel ? (+ <>+ <EditModelButton projectId={projectId} modelData={model} />+ <DeleteModelButton+ projectId={projectId}+ modelData={model}+ onSuccess={() => {+ void router.push(+ `/project/${projectId}/settings/models`,+ );+ }}+ />+ </>+ ) : (+ <CloneModelButton projectId={projectId} modelData={model} />+ )}+ </>+ )}</div>),}}@@ -150,9 +204,73 @@ export default function ModelDetailPage() {</CardContent></Card>- <Card>+ <Card id="pricing-section"><CardHeader>- <CardTitle>Pricing</CardTitle>+ <div className="flex flex-col gap-2">+ <CardTitle>Pricing</CardTitle>+ {model.pricingTiers.length > 1 && (+ <div className="flex items-center gap-4">+ <label className="text-sm font-medium text-muted-foreground">+ Pricing Tier+ </label>+ <Select+ value={activeTier?.id ?? ""}+ onValueChange={setSelectedTierId}+ >+ <SelectTrigger className="w-[200px]">+ <SelectValue placeholder="Select tier" />+ </SelectTrigger>+ <SelectContent>+ {model.pricingTiers.map((tier) => (+ <SelectItem key={tier.id} value={tier.id}>+ {tier.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {activeTier && !activeTier.isDefault && (+ <HoverCard openDelay={200} closeDelay={100}>+ <HoverCardTrigger asChild>+ <Button+ variant="ghost"+ className="inline-flex h-auto items-center gap-1.5 p-0 text-xs text-muted-foreground hover:bg-transparent hover:text-accent-foreground"+ size="sm"+ >+ <InfoIcon className="h-3 w-3" />+ <span>Conditions</span>+ </Button>+ </HoverCardTrigger>+ <HoverCardContent+ className="max-h-[80vh] w-[400px] overflow-auto"+ collisionPadding={20}+ >+ <p className="text-sm font-medium">+ Pricing Tier Conditions+ </p>+ <p className="pt-2 text-sm text-muted-foreground">+ This tier is applied when the following conditions are+ met:+ </p>+ <div className="mt-2">+ <CodeMirrorEditor+ mode="json"+ value={JSON.stringify(+ activeTier.conditions,+ null,+ 2,+ )}+ onChange={() => {}} // Read-only+ minHeight="none"+ className="max-h-[250px] overflow-y-auto"+ editable={false}+ />+ </div>+ </HoverCardContent>+ </HoverCard>+ )}+ </div>+ )}+ </div></CardHeader><CardContent><div className="flex flex-col gap-2">@@ -163,20 +281,24 @@ export default function ModelDetailPage() {<PriceUnitSelector /></span></div>- {Object.entries(model.prices).map(([usageType, price]) => (- <div- key={usageType}- className="grid grid-cols-2 gap-2 rounded px-1 py-0.5 text-sm"- >- <span className="break-all">{usageType}</span>- <span className="text-left font-mono">- $- {new Decimal(price)- .mul(priceUnitMultiplier)- .toFixed(maxDecimals)}- </span>- </div>- ))}+ {activeTier &&+ Object.entries(activeTier.prices)+ // Sort by price ascending+ .sort((a, b) => a[1] - b[1])+ .map(([usageType, price]) => (+ <div+ key={usageType}+ className="grid grid-cols-2 gap-2 rounded px-1 py-0.5 text-sm"+ >+ <span className="break-all">{usageType}</span>+ <span className="text-left font-mono">+ $+ {new Decimal(price)+ .mul(priceUnitMultiplier)+ .toFixed(maxDecimals)}+ </span>+ </div>+ ))}</div></CardContent></Card>diff --git a/web/src/server/api/routers/models.ts b/web/src/server/api/routers/models.tsindex fb9ca717d5..89940fb66a 100644--- a/web/src/server/api/routers/models.ts+++ b/web/src/server/api/routers/models.ts@@ -17,11 +17,14 @@ import { ModelUsageUnit, paginationZod } from "@langfuse/shared";import {clearModelCacheForProject,queryClickhouse,+ findModel,+ matchPricingTier,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";const ModelAllOptions = z.object({projectId: z.string(),+ searchString: z.string(),...paginationZod,});@@ -41,8 +44,8 @@ export const modelRouter = createTRPCRouter({getById: protectedProjectProcedure.input(z.object({ projectId: z.string(), modelId: z.string() })).query(async ({ input, ctx }) => {- const modelQueryResult = await ctx.prisma.$queryRaw`- SELECT+ const modelQueryResult = await ctx.prisma.$queryRaw`+ SELECTm.id,m.project_id as "projectId",m.model_name as "modelName",@@ -52,14 +55,34 @@ export const modelRouter = createTRPCRouter({COALESCE((SELECT- JSONB_OBJECT_AGG(usage_type, price)+ JSON_AGG(+ JSON_BUILD_OBJECT(+ 'id', mpt.id,+ 'name', mpt.name,+ 'isDefault', mpt.is_default,+ 'priority', mpt.priority,+ 'conditions', mpt.conditions,+ 'prices', COALESCE(+ (+ SELECT+ JSONB_OBJECT_AGG(p.usage_type, p.price)+ FROM+ prices p+ WHERE+ p.pricing_tier_id = mpt.id+ ),+ '{}'::jsonb+ )+ )+ ORDER BY mpt.priority ASC+ )FROM- prices+ pricing_tiers mptWHERE- model_id = m.id+ mpt.model_id = m.id),- '{}'::jsonb- ) AS prices+ '[]'::json+ ) AS "pricingTiers"FROMmodels mWHERE@@ -85,12 +108,13 @@ export const modelRouter = createTRPCRouter({getAll: protectedProjectProcedure.input(ModelAllOptions).query(async ({ input, ctx }) => {- const { projectId, page, limit } = input;+ const { projectId, page, limit, searchString } = input;+ const searchStringCondition = `%${searchString}%`;const [allModelsQueryResult, totalCountQuery] = await Promise.all([// All modelsctx.prisma.$queryRaw`- SELECT DISTINCT ON (project_id, model_name)+ SELECT DISTINCT ON (project_id, model_name)m.id,m.project_id as "projectId",m.model_name as "modelName",@@ -100,23 +124,43 @@ export const modelRouter = createTRPCRouter({COALESCE((SELECT- JSONB_OBJECT_AGG(usage_type, price)+ JSON_AGG(+ JSON_BUILD_OBJECT(+ 'id', mpt.id,+ 'name', mpt.name,+ 'isDefault', mpt.is_default,+ 'priority', mpt.priority,+ 'conditions', mpt.conditions,+ 'prices', COALESCE(+ (+ SELECT+ JSONB_OBJECT_AGG(p.usage_type, p.price)+ FROM+ prices p+ WHERE+ p.pricing_tier_id = mpt.id+ ),+ '{}'::jsonb+ )+ )+ ORDER BY mpt.priority ASC+ )FROM- prices+ pricing_tiers mptWHERE- model_id = m.id+ mpt.model_id = m.id),- '{}'::jsonb- ) AS prices+ '[]'::json+ ) AS "pricingTiers"FROMmodels mWHERE- project_id IS NULL- OR project_id = ${projectId}+ (project_id IS NULL OR project_id = ${projectId})+ AND model_name ILIKE ${searchStringCondition}ORDER BYproject_id,model_name,- m.created_at DESC NULLS LAST+ m.created_at DESC NULLS LAST`,// Total count@@ -127,8 +171,8 @@ export const modelRouter = createTRPCRouter({>`SELECT COUNT(DISTINCT (project_id, model_name))FROM models- WHERE project_id IS NULL- OR project_id = ${projectId};+ WHERE (project_id IS NULL OR project_id = ${projectId})+ AND model_name ILIKE ${searchStringCondition};`,]);@@ -201,6 +245,7 @@ export const modelRouter = createTRPCRouter({matchPattern,tokenizerConfig,tokenizerId,+ pricingTiers,} = input;throwIfNoProjectAccess({@@ -281,32 +326,47 @@ export const modelRouter = createTRPCRouter({},});- await tx.price.deleteMany({+ // Delete all existing pricing tiers+ await tx.pricingTier.deleteMany({where: {modelId: upsertedModel.id,},});- await tx.price.createMany({- data: Object.entries(input.prices)- .filter(- (priceEntry): priceEntry is [string, number] =>- priceEntry[1] != null,- )- .map(([usageType, price]) => ({+ // Create new pricing tiers+ for (const tier of pricingTiers) {+ const createdTier = await tx.pricingTier.create({+ data: {modelId: upsertedModel.id,- projectId: upsertedModel.projectId,- usageType,- price,- })),- });+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ },+ });++ // Create prices for this tier+ await Promise.all(+ Object.entries(tier.prices).map(([usageType, price]) =>+ tx.price.create({+ data: {+ modelId: upsertedModel.id,+ projectId: upsertedModel.projectId,+ pricingTierId: createdTier.id,+ usageType,+ price,+ },+ }),+ ),+ );+ }await auditLog({session: ctx.session,resourceType: "model",resourceId: upsertedModel.id,- action: modelId ? "update" : "create",- after: upsertedModel,+ action: providedModelId ? "update" : "create",+ after: { model: upsertedModel, pricingTiers },});return upsertedModel;@@ -351,4 +411,92 @@ export const modelRouter = createTRPCRouter({return deletedModel;}),+ testMatch: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ modelName: z.string().min(1),+ usageDetails: z.record(z.string(), z.number()).optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ const { projectId, modelName, usageDetails } = input;++ throwIfNoProjectAccess({+ session: ctx.session,+ projectId,+ scope: "models:CUD",+ });++ // Step 1: Use existing findModel from shared+ const { model, pricingTiers } = await findModel({+ projectId,+ model: modelName,+ });++ if (!model) {+ return { matched: false as const };+ }++ // Step 2: If no usage details provided, return default tier+ if (!usageDetails || Object.keys(usageDetails).length === 0) {+ const defaultTier = pricingTiers.find((t) => t.isDefault);+ if (!defaultTier) {+ return { matched: false as const };+ }++ return {+ matched: true as const,+ model: {+ id: model.id,+ modelName: model.modelName,+ matchPattern: model.matchPattern,+ projectId: model.projectId,+ },+ matchedTier: {+ id: defaultTier.id,+ name: defaultTier.name,+ priority: defaultTier.priority,+ isDefault: true,+ prices: Object.fromEntries(+ defaultTier.prices.map((p) => [p.usageType, p.price.toNumber()]),+ ),+ },+ };+ }++ // Step 3: Use matchPricingTier from shared+ const matchResult = matchPricingTier(pricingTiers, usageDetails);++ if (!matchResult) {+ return { matched: false as const };+ }++ // Step 4: Find the full tier details+ const matchedTier = pricingTiers.find(+ (t) => t.id === matchResult.pricingTierId,+ );+ if (!matchedTier) {+ return { matched: false as const };+ }++ return {+ matched: true as const,+ model: {+ id: model.id,+ modelName: model.modelName,+ matchPattern: model.matchPattern,+ projectId: model.projectId,+ },+ matchedTier: {+ id: matchedTier.id,+ name: matchedTier.name,+ priority: matchedTier.priority,+ isDefault: matchedTier.isDefault,+ prices: Object.fromEntries(+ matchedTier.prices.map((p) => [p.usageType, p.price.toNumber()]),+ ),+ },+ };+ }),});diff --git a/worker/src/__tests__/modelMatch.test.ts b/worker/src/__tests__/modelMatch.test.tsindex 58486a2896..d197cd477d 100644--- a/worker/src/__tests__/modelMatch.test.ts+++ b/worker/src/__tests__/modelMatch.test.ts@@ -1,4 +1,4 @@-import { expect, describe, it, beforeEach, afterEach } from "vitest";+import { expect, describe, it } from "vitest";import { prisma } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey, redis } from "@langfuse/shared/src/server";import {@@ -7,28 +7,37 @@ import {getRedisModelKey,clearModelCacheForProject,} from "@langfuse/shared/src/server";+import { v4 as uuidv4 } from "uuid";describe("modelMatch", () => {describe("findModel", () => {it("should return model with prices from Redis if available", async () => {const { projectId } = await createOrgProjectAndApiKey();// First create a model in Postgres+ const modelId = uuidv4();const mockModel = await prisma.model.create({data: {projectId,+ id: modelId,modelName: "gpt-4",matchPattern: "gpt-4",unit: "TOKENS",inputPrice: "1.0123",- },- });-- // Create prices for the model- const mockPrice = await prisma.price.create({- data: {- modelId: mockModel.id,- usageType: "input",- price: "0.03",+ pricingTiers: {+ create: {+ name: "Standard",+ isDefault: true,+ conditions: [],+ priority: 0,+ prices: {+ create: {+ modelId,+ usageType: "input",+ price: "0.03",+ },+ },+ },+ },},});@@ -63,12 +72,16 @@ describe("modelMatch", () => {mockModel.totalPrice?.toString(),);- // Verify prices are included- expect(result.prices).toHaveLength(1);- expect(result.prices[0].id).toEqual(mockPrice.id);- expect(result.prices[0].usageType).toEqual(mockPrice.usageType);+ // Verify pricing tiers are included+ expect(result.pricingTiers).toHaveLength(1);+ expect(result.pricingTiers[0].name).toEqual("Standard");+ expect(result.pricingTiers[0].isDefault).toBe(true);+ expect(result.pricingTiers[0].priority).toBe(0);+ expect(result.pricingTiers[0].prices).toHaveLength(1);+ expect(result.pricingTiers[0].prices[0].usageType).toEqual("input");+ expect(result.pricingTiers[0].prices[0].price.toString()).toEqual("0.03");- // Verify the model with prices exists in Redis+ // Verify the model with pricing tiers exists in Redisconst redisKey = getRedisModelKey({projectId,model: "gpt-4",@@ -79,8 +92,8 @@ describe("modelMatch", () => {const parsed = JSON.parse(cachedValue!);expect(parsed.model.id).toEqual(mockModel.id);expect(parsed.model.projectId).toEqual(mockModel.projectId);- expect(parsed.prices).toHaveLength(1);- expect(parsed.prices[0].id).toEqual(mockPrice.id);+ expect(parsed.pricingTiers).toHaveLength(1);+ expect(parsed.pricingTiers[0].name).toEqual("Standard");});it("should query Postgres if Redis cache misses", async () => {@@ -100,7 +113,7 @@ describe("modelMatch", () => {});expect(result.model).toEqual(mockModel);- expect(result.prices).toEqual([]);+ expect(result.pricingTiers).toEqual([]);});it("should cache not found models in Redis", async () => {@@ -113,7 +126,7 @@ describe("modelMatch", () => {model: nonExistentModel,});expect(result1.model).toBeNull();- expect(result1.prices).toEqual([]);+ expect(result1.pricingTiers).toEqual([]);// Second lookup should use the cached not-found resultconst result2 = await findModel({@@ -121,7 +134,7 @@ describe("modelMatch", () => {model: nonExistentModel,});expect(result2.model).toBeNull();- expect(result2.prices).toEqual([]);+ expect(result2.pricingTiers).toEqual([]);// Verify the not-found token exists in Redisconst redisKey = getRedisModelKey({diff --git a/worker/src/__tests__/pricing-tier-matcher.test.ts b/worker/src/__tests__/pricing-tier-matcher.test.tsnew file mode 100644index 0000000000..2b312191e4--- /dev/null+++ b/worker/src/__tests__/pricing-tier-matcher.test.ts@@ -0,0 +1,1102 @@+import { describe, expect, it } from "vitest";+import { Decimal } from "decimal.js";+import { z } from "zod/v4";+import { validateRegexPattern } from "@langfuse/shared";+import {+ matchPricingTier,+ type PricingTierWithPrices,+} from "@langfuse/shared/src/server";+import { DefaultModelPriceSchema } from "../scripts/upsertDefaultModelPrices";+import defaultModelPrices from "../constants/default-model-prices.json";++describe("default-model-prices.json", () => {+ it("should parse successfully with Zod schema (same validation as upsertDefaultModelPrices)", () => {+ expect(() =>+ z.array(DefaultModelPriceSchema).parse(defaultModelPrices),+ ).not.toThrow();+ });++ it("should have unique model IDs", () => {+ const ids = defaultModelPrices.map((model) => model.id);+ const uniqueIds = new Set(ids);+ expect(ids.length).toBe(uniqueIds.size);+ });++ it("should have unique pricing tier IDs globally", () => {+ const allTierIds: string[] = [];+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ allTierIds.push(tier.id);+ }+ }+ const uniqueTierIds = new Set(allTierIds);+ expect(allTierIds.length).toBe(uniqueTierIds.size);+ });++ it("should have unique model names", () => {+ const modelNames = defaultModelPrices.map((model) => model.modelName);+ const uniqueNames = new Set(modelNames);+ expect(modelNames.length).toBe(uniqueNames.size);+ });++ it("should have updatedAt greater than or equal to createdAt", () => {+ for (const model of defaultModelPrices) {+ const created = new Date(model.createdAt);+ const updated = new Date(model.updatedAt);+ expect(updated.getTime()).toBeGreaterThanOrEqual(created.getTime());+ }+ });++ it("should have valid date formats for all timestamps", () => {+ for (const model of defaultModelPrices) {+ const created = new Date(model.createdAt);+ const updated = new Date(model.updatedAt);+ expect(created.toString()).not.toBe("Invalid Date");+ expect(updated.toString()).not.toBe("Invalid Date");+ }+ });++ it("should have at least one pricing tier per model", () => {+ for (const model of defaultModelPrices) {+ expect(model.pricingTiers.length).toBeGreaterThan(0);+ }+ });++ it("should have exactly one default tier per model", () => {+ for (const model of defaultModelPrices) {+ const defaultTiers = model.pricingTiers.filter((t) => t.isDefault);+ expect(defaultTiers.length).toBe(1);+ }+ });++ it("should have default tier with priority 0 and no conditions", () => {+ for (const model of defaultModelPrices) {+ const defaultTier = model.pricingTiers.find((t) => t.isDefault);+ expect(defaultTier).toBeDefined();+ expect(defaultTier!.priority).toBe(0);+ expect(defaultTier!.conditions).toEqual([]);+ }+ });++ it("should have default tier IDs in the form of ${modelId}_tier_default", () => {+ for (const model of defaultModelPrices) {+ const defaultTier = model.pricingTiers.find((t) => t.isDefault);+ expect(defaultTier).toBeDefined();+ const expectedId = `${model.id}_tier_default`;+ expect(defaultTier!.id).toBe(expectedId);+ }+ });++ it("should have unique priorities within each model", () => {+ for (const model of defaultModelPrices) {+ const priorities = model.pricingTiers.map((t) => t.priority);+ const uniquePriorities = new Set(priorities);+ expect(priorities.length).toBe(uniquePriorities.size);+ }+ });++ it("should have unique tier names within each model", () => {+ for (const model of defaultModelPrices) {+ const names = model.pricingTiers.map((t) => t.name);+ const uniqueNames = new Set(names);+ expect(names.length).toBe(uniqueNames.size);+ }+ });++ it("should have non-negative priority values", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ expect(tier.priority).toBeGreaterThanOrEqual(0);+ }+ }+ });++ it("should have integer priority values", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ expect(Number.isInteger(tier.priority)).toBe(true);+ }+ }+ });++ it("should have at least one price per tier", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ expect(Object.keys(tier.prices).length).toBeGreaterThan(0);+ }+ }+ });++ it("should have non-negative price values", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ for (const [usageType, price] of Object.entries(tier.prices)) {+ expect(price).toBeGreaterThanOrEqual(0);+ }+ }+ }+ });++ it("should have valid number values for all prices (no NaN or Infinity)", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ for (const [usageType, price] of Object.entries(tier.prices)) {+ expect(Number.isFinite(price)).toBe(true);+ }+ }+ }+ });++ it("should have same price keys across all tiers within a model", () => {+ for (const model of defaultModelPrices) {+ if (model.pricingTiers.length <= 1) continue;++ const defaultTier = model.pricingTiers.find((t) => t.isDefault);+ expect(defaultTier).toBeDefined();++ const defaultKeys = Object.keys(defaultTier!.prices).sort();++ for (const tier of model.pricingTiers) {+ if (tier.isDefault) continue;++ const tierKeys = Object.keys(tier.prices).sort();+ expect(tierKeys).toEqual(defaultKeys);+ }+ }+ });++ it("should have valid condition structures for non-default tiers", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ if (tier.isDefault) continue;++ // Non-default tiers must have at least one condition+ expect(tier.conditions.length).toBeGreaterThan(0);++ for (const condition of tier.conditions) {+ expect(condition).toHaveProperty("usageDetailPattern");+ expect(condition).toHaveProperty("operator");+ expect(condition).toHaveProperty("value");+ expect(condition).toHaveProperty("caseSensitive");++ // Validate operator+ expect(["gt", "gte", "lt", "lte", "eq", "neq"]).toContain(+ condition.operator,+ );++ // Validate value is a number+ expect(typeof condition.value).toBe("number");++ // Validate caseSensitive is boolean+ expect(typeof condition.caseSensitive).toBe("boolean");++ // Validate pattern is a string+ expect(typeof condition.usageDetailPattern).toBe("string");+ expect(condition.usageDetailPattern.length).toBeGreaterThan(0);+ expect(condition.usageDetailPattern.length).toBeLessThanOrEqual(200);+ }+ }+ }+ });++ it("should have valid regex patterns in all conditions", () => {+ for (const model of defaultModelPrices) {+ for (const tier of model.pricingTiers) {+ for (const condition of tier.conditions) {+ expect(() =>+ validateRegexPattern(condition.usageDetailPattern),+ ).not.toThrow();+ }+ }+ }+ });++ it("should correctly match claude-sonnet-4-5 model with tiered pricing", () => {+ const claudeModel = defaultModelPrices.find(+ (m) => m.id === "c5qmrqolku82tra3vgdixmys",+ );+ expect(claudeModel).toBeDefined();+ expect(claudeModel!.modelName).toBe("claude-sonnet-4-5-20250929");+ expect(claudeModel!.pricingTiers.length).toBe(2);++ // Convert to PricingTierWithPrices format+ const tiers: PricingTierWithPrices[] = claudeModel!.pricingTiers.map(+ (tier) => ({+ id: tier.id,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ prices: Object.entries(tier.prices).map(([usageType, price]) => ({+ usageType,+ price: new Decimal(price),+ })),+ }),+ );++ // Test standard pricing (input <= 200K)+ const standardResult = matchPricingTier(tiers, {+ input: 150000,+ output: 5000,+ });+ expect(standardResult).not.toBeNull();+ expect(standardResult?.pricingTierName).toBe("Standard");+ expect(standardResult?.prices.input.toNumber()).toBe(0.000003);++ // Test large context pricing (input > 200K)+ const largeContextResult = matchPricingTier(tiers, {+ input: 250000,+ output: 5000,+ });+ expect(largeContextResult).not.toBeNull();+ expect(largeContextResult?.pricingTierName).toBe("Large Context");+ expect(largeContextResult?.prices.input.toNumber()).toBe(0.000006);+ });+});++describe("validateRegexPattern", () => {+ it("should accept valid regex patterns", () => {+ expect(() => validateRegexPattern("^input")).not.toThrow();+ expect(() => validateRegexPattern("^(input|output)")).not.toThrow();+ expect(() => validateRegexPattern(".*tokens.*")).not.toThrow();+ expect(() => validateRegexPattern("^input_[a-z]+$")).not.toThrow();+ });++ it("should reject empty patterns", () => {+ expect(() => validateRegexPattern("")).toThrow("Pattern cannot be empty");+ });++ it("should reject patterns exceeding max length", () => {+ const longPattern = "a".repeat(201);+ expect(() => validateRegexPattern(longPattern)).toThrow(+ "Pattern exceeds maximum length of 200 characters",+ );+ });++ it("should reject invalid regex syntax", () => {+ expect(() => validateRegexPattern("(unclosed")).toThrow(+ "Invalid regex syntax",+ );+ expect(() => validateRegexPattern("[unclosed")).toThrow(+ "Invalid regex syntax",+ );+ });++ it("should reject patterns with catastrophic backtracking", () => {+ // Classic catastrophic backtracking pattern+ const dangerousPattern = "(a+)+b";+ expect(() => validateRegexPattern(dangerousPattern)).toThrow(+ "catastrophic backtracking",+ );+ });++ it("should accept safe complex patterns", () => {+ expect(() => validateRegexPattern("^(input|prompt)_tokens$")).not.toThrow();+ expect(() =>+ validateRegexPattern("^(input|output)_(cached|regular)$"),+ ).not.toThrow();+ });+});++describe("matchPricingTier", () => {+ describe("Basic tier matching", () => {+ it("should return default tier when no conditions match", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [+ { usageType: "input", price: new Decimal("0.000003") },+ { usageType: "output", price: new Decimal("0.000015") },+ ],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 500000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000001") }],+ },+ ];++ const usageDetails = {+ input: 100000,+ output: 2000,+ };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result).not.toBeNull();+ expect(result?.pricingTierId).toBe("tier-default");+ expect(result?.pricingTierName).toBe("Standard");+ expect(result?.prices.input.toNumber()).toBe(0.000003);+ expect(result?.prices.output.toNumber()).toBe(0.000015);+ });++ it("should return matched tier when condition passes", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ const usageDetails = {+ input: 250000,+ output: 2000,+ };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result).not.toBeNull();+ expect(result?.pricingTierId).toBe("tier-high");+ expect(result?.pricingTierName).toBe("High Volume");+ expect(result?.prices.input.toNumber()).toBe(0.000006);+ });++ it("should return null when no tiers exist", () => {+ const tiers: PricingTierWithPrices[] = [];+ const usageDetails = { input: 1000 };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result).toBeNull();+ });++ it("should return null when no default tier exists and no conditions match", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 500000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000001") }],+ },+ ];++ const usageDetails = { input: 100000 };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result).toBeNull();+ });+ });++ describe("Pattern matching", () => {+ it("should sum values from multiple keys matching pattern", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input", // Matches input, input_cached, input_regular+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ const usageDetails = {+ input_cached: 150000,+ input_regular: 60000, // Total: 210K > 200K+ output: 2000,+ };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.pricingTierId).toBe("tier-high");+ expect(result?.pricingTierName).toBe("High Volume");+ });++ it("should be case-insensitive by default", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^INPUT",+ operator: "gt",+ value: 100000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ const usageDetails = {+ input_tokens: 150000, // Should match "^INPUT" case-insensitively+ };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.pricingTierId).toBe("tier-high");+ });++ it("should respect case-sensitive flag", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^INPUT",+ operator: "gt",+ value: 100000,+ caseSensitive: true, // Case-sensitive matching+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ const usageDetails = {+ input_tokens: 150000, // Should NOT match "^INPUT" with case-sensitive+ INPUT_TOKENS: 50000, // Should match but below threshold+ };++ const result = matchPricingTier(tiers, usageDetails);++ // Should fall back to default since INPUT_TOKENS (50K) < 100K+ expect(result?.pricingTierId).toBe("tier-default");+ });+ });++ describe("Operator evaluation", () => {+ const createTiers = (+ operator: "gt" | "gte" | "lt" | "lte" | "eq" | "neq",+ value: number,+ ): PricingTierWithPrices[] => [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-conditional",+ name: "Conditional",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator,+ value,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ it("should correctly evaluate 'gt' operator", () => {+ const tiers = createTiers("gt", 100);++ expect(matchPricingTier(tiers, { input: 101 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 100 })?.pricingTierId).toBe(+ "tier-default",+ );+ expect(matchPricingTier(tiers, { input: 99 })?.pricingTierId).toBe(+ "tier-default",+ );+ });++ it("should correctly evaluate 'gte' operator", () => {+ const tiers = createTiers("gte", 100);++ expect(matchPricingTier(tiers, { input: 101 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 100 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 99 })?.pricingTierId).toBe(+ "tier-default",+ );+ });++ it("should correctly evaluate 'lt' operator", () => {+ const tiers = createTiers("lt", 100);++ expect(matchPricingTier(tiers, { input: 99 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 100 })?.pricingTierId).toBe(+ "tier-default",+ );+ expect(matchPricingTier(tiers, { input: 101 })?.pricingTierId).toBe(+ "tier-default",+ );+ });++ it("should correctly evaluate 'lte' operator", () => {+ const tiers = createTiers("lte", 100);++ expect(matchPricingTier(tiers, { input: 99 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 100 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 101 })?.pricingTierId).toBe(+ "tier-default",+ );+ });++ it("should correctly evaluate 'eq' operator", () => {+ const tiers = createTiers("eq", 100);++ expect(matchPricingTier(tiers, { input: 100 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 99 })?.pricingTierId).toBe(+ "tier-default",+ );+ expect(matchPricingTier(tiers, { input: 101 })?.pricingTierId).toBe(+ "tier-default",+ );+ });++ it("should correctly evaluate 'neq' operator", () => {+ const tiers = createTiers("neq", 100);++ expect(matchPricingTier(tiers, { input: 99 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 101 })?.pricingTierId).toBe(+ "tier-conditional",+ );+ expect(matchPricingTier(tiers, { input: 100 })?.pricingTierId).toBe(+ "tier-default",+ );+ });+ });++ describe("Priority-based tier selection", () => {+ it("should select tier with lowest priority when multiple tiers match", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-medium",+ name: "Medium Volume",+ isDefault: false,+ priority: 2, // Higher priority number+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000002") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1, // Lower priority number (evaluated first)+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 100000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000001") }],+ },+ ];++ const usageDetails = { input: 250000 };++ const result = matchPricingTier(tiers, usageDetails);++ // Both tier-medium and tier-high match, but tier-high has priority 1 (evaluated first)+ expect(result?.pricingTierId).toBe("tier-high");+ expect(result?.pricingTierName).toBe("High Volume");+ });+ });++ describe("Multiple conditions (AND logic)", () => {+ it("should match only when ALL conditions pass", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-complex",+ name: "Complex Tier",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ {+ usageDetailPattern: "^output",+ operator: "lt",+ value: 10000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ // Both conditions match: input > 200K AND output < 10K+ const usageDetails1 = {+ input: 250000,+ output: 5000,+ };+ expect(matchPricingTier(tiers, usageDetails1)?.pricingTierId).toBe(+ "tier-complex",+ );++ // First condition matches, second doesn't: input > 200K but output >= 10K+ const usageDetails2 = {+ input: 250000,+ output: 15000,+ };+ expect(matchPricingTier(tiers, usageDetails2)?.pricingTierId).toBe(+ "tier-default",+ );++ // Second condition matches, first doesn't: input <= 200K but output < 10K+ const usageDetails3 = {+ input: 100000,+ output: 5000,+ };+ expect(matchPricingTier(tiers, usageDetails3)?.pricingTierId).toBe(+ "tier-default",+ );+ });+ });++ describe("Pattern matching edge cases", () => {+ it("should handle missing keys in usage details", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ // No keys matching "^input" pattern+ const usageDetails = {+ output: 2000,+ };++ const result = matchPricingTier(tiers, usageDetails);++ // Should fall back to default (sum of matching keys is 0)+ expect(result?.pricingTierId).toBe("tier-default");+ });++ it("should handle pattern matching no keys (sum = 0)", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-special",+ name: "Special",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^special",+ operator: "eq",+ value: 0, // Matches when sum is exactly 0+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000001") }],+ },+ ];++ const usageDetails = {+ input: 1000,+ output: 500,+ };++ const result = matchPricingTier(tiers, usageDetails);++ // No keys match "^special", so sum = 0, which equals 0+ expect(result?.pricingTierId).toBe("tier-special");+ });++ it("should handle complex regex patterns", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-cache",+ name: "Cache Tier",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "_(cached|cache)$", // Matches keys ending with _cached or _cache+ operator: "gt",+ value: 50000,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000001") }],+ },+ ];++ const usageDetails = {+ input_cached: 30000,+ output_cache: 25000, // Total: 55K > 50K+ input_regular: 100000,+ };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.pricingTierId).toBe("tier-cache");+ });+ });++ describe("Edge cases and error handling", () => {+ it("should handle zero values in usage details", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-high",+ name: "High Volume",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "eq",+ value: 0,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0") }],+ },+ ];++ const usageDetails = {+ input: 0,+ output: 100,+ };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.pricingTierId).toBe("tier-high");+ });++ it("should handle empty usage details object", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ ];++ const usageDetails = {};++ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.pricingTierId).toBe("tier-default");+ });++ it("should gracefully handle invalid regex at runtime (should not happen due to validation)", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [{ usageType: "input", price: new Decimal("0.000003") }],+ },+ {+ id: "tier-invalid",+ name: "Invalid Regex Tier",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ // This would be caught by validation, but testing runtime safety+ usageDetailPattern: "(unclosed",+ operator: "gt",+ value: 100,+ caseSensitive: false,+ },+ ],+ prices: [{ usageType: "input", price: new Decimal("0.000006") }],+ },+ ];++ const usageDetails = { input: 1000 };++ // Should fall back to default due to regex error+ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.pricingTierId).toBe("tier-default");+ });+ });++ describe("Real-world examples", () => {+ it("should match Anthropic Claude tiered pricing", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-standard",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [+ { usageType: "input", price: new Decimal("0.000003") },+ { usageType: "output", price: new Decimal("0.000015") },+ ],+ },+ {+ id: "tier-large-context",+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: [+ { usageType: "input", price: new Decimal("0.000006") },+ { usageType: "output", price: new Decimal("0.000015") },+ ],+ },+ ];++ // Below threshold+ const resultBelow = matchPricingTier(tiers, {+ input: 150000,+ output: 2000,+ });+ expect(resultBelow?.pricingTierName).toBe("Standard");+ expect(resultBelow?.prices.input.toNumber()).toBe(0.000003);++ // Above threshold+ const resultAbove = matchPricingTier(tiers, {+ input: 250000,+ output: 2000,+ });+ expect(resultAbove?.pricingTierName).toBe("Large Context (>200K)");+ expect(resultAbove?.prices.input.toNumber()).toBe(0.000006);+ });++ it("should match Google Gemini tiered pricing with multiple pattern options", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-standard",+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [+ { usageType: "input", price: new Decimal("0.00000125") },+ { usageType: "output", price: new Decimal("0.000005") },+ ],+ },+ {+ id: "tier-high-volume",+ name: "High Volume (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^(input|prompt)", // Matches input or prompt prefixes+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: [+ { usageType: "input", price: new Decimal("0.0000025") },+ { usageType: "output", price: new Decimal("0.00001") },+ ],+ },+ ];++ // Using "input" prefix+ const resultInput = matchPricingTier(tiers, {+ input_tokens: 250000,+ output_tokens: 5000,+ });+ expect(resultInput?.pricingTierName).toBe("High Volume (>200K)");++ // Using "prompt" prefix+ const resultPrompt = matchPricingTier(tiers, {+ prompt_tokens: 250000,+ completion_tokens: 5000,+ });+ expect(resultPrompt?.pricingTierName).toBe("High Volume (>200K)");+ });+ });++ describe("Decimal price handling", () => {+ it("should preserve Decimal precision in returned prices", () => {+ const tiers: PricingTierWithPrices[] = [+ {+ id: "tier-default",+ name: "Default",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: [+ { usageType: "input", price: new Decimal("0.000003123456789") },+ ],+ },+ ];++ const usageDetails = { input: 1000 };++ const result = matchPricingTier(tiers, usageDetails);++ expect(result?.prices.input).toBeInstanceOf(Decimal);+ expect(result?.prices.input.toString()).toBe("0.000003123456789");+ });+ });+});diff --git a/worker/src/constants/default-model-prices.json b/worker/src/constants/default-model-prices.jsonindex 3e11459839..5924f02c6e 100644--- a/worker/src/constants/default-model-prices.json+++ b/worker/src/constants/default-model-prices.json@@ -1,2206 +1,3361 @@[{"id": "b9854a5c92dc496b997d99d20",- "model_name": "gpt-4o",- "match_pattern": "(?i)^(gpt-4o)$",- "created_at": "2024-05-13T23:15:07.670Z",- "updated_at": "2024-12-03T10:12:31.000Z",- "prices": {- "input": 2.5e-6,- "input_cached_tokens": 1.25e-6,- "input_cache_read": 1.25e-6,- "output": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-4o",+ "matchPattern": "(?i)^(gpt-4o)$",+ "createdAt": "2024-05-13T23:15:07.670Z",+ "updatedAt": "2024-12-03T10:12:31.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "b9854a5c92dc496b997d99d20_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000025,+ "input_cached_tokens": 0.00000125,+ "input_cache_read": 0.00000125,+ "output": 0.00001+ }+ }+ ]},{"id": "b9854a5c92dc496b997d99d21",- "model_name": "gpt-4o-2024-05-13",- "match_pattern": "(?i)^(gpt-4o-2024-05-13)$",- "created_at": "2024-05-13T23:15:07.670Z",- "updated_at": "2024-05-13T23:15:07.670Z",- "prices": {- "input": 0.000005,- "output": 0.000015- },- "tokenizer_config": {+ "modelName": "gpt-4o-2024-05-13",+ "matchPattern": "(?i)^(gpt-4o-2024-05-13)$",+ "createdAt": "2024-05-13T23:15:07.670Z",+ "updatedAt": "2024-05-13T23:15:07.670Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o-2024-05-13","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "b9854a5c92dc496b997d99d21_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000005,+ "output": 0.000015+ }+ }+ ]},{"id": "clrkvq6iq000008ju6c16gynt",- "model_name": "gpt-4-1106-preview",- "match_pattern": "(?i)^(gpt-4-1106-preview)$",- "created_at": "2024-04-23T10:37:17.092Z",- "updated_at": "2024-04-23T10:37:17.092Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": "gpt-4-1106-preview",+ "matchPattern": "(?i)^(gpt-4-1106-preview)$",+ "createdAt": "2024-04-23T10:37:17.092Z",+ "updatedAt": "2024-04-23T10:37:17.092Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-1106-preview","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkvq6iq000008ju6c16gynt_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "clrkvx5gp000108juaogs54ea",- "model_name": "gpt-4-turbo-vision",- "match_pattern": "(?i)^(gpt-4(-\\d{4})?-vision-preview)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": "gpt-4-turbo-vision",+ "matchPattern": "(?i)^(gpt-4(-\\d{4})?-vision-preview)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-vision-preview","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkvx5gp000108juaogs54ea_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "clrkvyzgw000308jue4hse4j9",- "model_name": "gpt-4-32k",- "match_pattern": "(?i)^(gpt-4-32k)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00006,- "output": 0.00012- },- "tokenizer_config": {+ "modelName": "gpt-4-32k",+ "matchPattern": "(?i)^(gpt-4-32k)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-32k","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkvyzgw000308jue4hse4j9_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00006,+ "output": 0.00012+ }+ }+ ]},{"id": "clrkwk4cb000108l5hwwh3zdi",- "model_name": "gpt-4-32k-0613",- "match_pattern": "(?i)^(gpt-4-32k-0613)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00006,- "output": 0.00012- },- "tokenizer_config": {+ "modelName": "gpt-4-32k-0613",+ "matchPattern": "(?i)^(gpt-4-32k-0613)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-32k-0613","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkwk4cb000108l5hwwh3zdi_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00006,+ "output": 0.00012+ }+ }+ ]},{"id": "clrkwk4cb000208l59yvb9yq8",- "model_name": "gpt-3.5-turbo-1106",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-1106)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.000001,- "output": 0.000002- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-1106",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-1106)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo-1106","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkwk4cb000208l59yvb9yq8_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000001,+ "output": 0.000002+ }+ }+ ]},{"id": "clrkwk4cc000808l51xmk4uic",- "model_name": "gpt-3.5-turbo-0613",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-0613)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.0000015,- "output": 0.000002- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-0613",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-0613)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo-0613","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkwk4cc000808l51xmk4uic_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000015,+ "output": 0.000002+ }+ }+ ]},{"id": "clrkwk4cc000908l537kl0rx3",- "model_name": "gpt-4-0613",- "match_pattern": "(?i)^(gpt-4-0613)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00003,- "output": 0.00006- },- "tokenizer_config": {+ "modelName": "gpt-4-0613",+ "matchPattern": "(?i)^(gpt-4-0613)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-0613","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkwk4cc000908l537kl0rx3_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00003,+ "output": 0.00006+ }+ }+ ]},{"id": "clrkwk4cc000a08l562uc3s9g",- "model_name": "gpt-3.5-turbo-instruct",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-instruct)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.0000015,- "output": 0.000002- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-instruct",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-instruct)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrkwk4cc000a08l562uc3s9g_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000015,+ "output": 0.000002+ }+ }+ ]},{"id": "clrntjt89000108jwcou1af71",- "model_name": "text-ada-001",- "match_pattern": "(?i)^(text-ada-001)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 0.000004- },- "tokenizer_config": {+ "modelName": "text-ada-001",+ "matchPattern": "(?i)^(text-ada-001)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-ada-001"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000108jwcou1af71_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 0.000004+ }+ }+ ]},{"id": "clrntjt89000208jwawjr894q",- "model_name": "text-babbage-001",- "match_pattern": "(?i)^(text-babbage-001)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 5e-7- },- "tokenizer_config": {+ "modelName": "text-babbage-001",+ "matchPattern": "(?i)^(text-babbage-001)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-babbage-001"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000208jwawjr894q_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 5e-7+ }+ }+ ]},{"id": "clrntjt89000308jw0jtfa4rs",- "model_name": "text-curie-001",- "match_pattern": "(?i)^(text-curie-001)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 0.00002- },- "tokenizer_config": {+ "modelName": "text-curie-001",+ "matchPattern": "(?i)^(text-curie-001)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-curie-001"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000308jw0jtfa4rs_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 0.00002+ }+ }+ ]},{"id": "clrntjt89000408jwc2c93h6i",- "model_name": "text-davinci-001",- "match_pattern": "(?i)^(text-davinci-001)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 0.00002- },- "tokenizer_config": {+ "modelName": "text-davinci-001",+ "matchPattern": "(?i)^(text-davinci-001)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-davinci-001"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000408jwc2c93h6i_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 0.00002+ }+ }+ ]},{"id": "clrntjt89000508jw192m64qi",- "model_name": "text-davinci-002",- "match_pattern": "(?i)^(text-davinci-002)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 0.00002- },- "tokenizer_config": {+ "modelName": "text-davinci-002",+ "matchPattern": "(?i)^(text-davinci-002)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-davinci-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000508jw192m64qi_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 0.00002+ }+ }+ ]},{"id": "clrntjt89000608jw4m3x5s55",- "model_name": "text-davinci-003",- "match_pattern": "(?i)^(text-davinci-003)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 0.00002- },- "tokenizer_config": {+ "modelName": "text-davinci-003",+ "matchPattern": "(?i)^(text-davinci-003)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-davinci-003"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000608jw4m3x5s55_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 0.00002+ }+ }+ ]},{"id": "clrntjt89000908jwhvkz5crg",- "model_name": "text-embedding-ada-002-v2",- "match_pattern": "(?i)^(text-embedding-ada-002-v2)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 1e-7- },- "tokenizer_config": {+ "modelName": "text-embedding-ada-002-v2",+ "matchPattern": "(?i)^(text-embedding-ada-002-v2)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-embedding-ada-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000908jwhvkz5crg_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 1e-7+ }+ }+ ]},{"id": "clrntjt89000908jwhvkz5crm",- "model_name": "text-embedding-ada-002",- "match_pattern": "(?i)^(text-embedding-ada-002)$",- "created_at": "2024-01-24T18:18:50.861Z",- "updated_at": "2024-01-24T18:18:50.861Z",- "prices": {- "total": 1e-7- },- "tokenizer_config": {+ "modelName": "text-embedding-ada-002",+ "matchPattern": "(?i)^(text-embedding-ada-002)$",+ "createdAt": "2024-01-24T18:18:50.861Z",+ "updatedAt": "2024-01-24T18:18:50.861Z",+ "tokenizerConfig": {"tokenizerModel": "text-embedding-ada-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000908jwhvkz5crm_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 1e-7+ }+ }+ ]},{"id": "clrntjt89000a08jw0gcdbd5a",- "model_name": "gpt-3.5-turbo-16k-0613",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-16k-0613)$",- "created_at": "2024-02-03T17:29:57.350Z",- "updated_at": "2024-02-03T17:29:57.350Z",- "prices": {- "input": 0.000003,- "output": 0.000004- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-16k-0613",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-16k-0613)$",+ "createdAt": "2024-02-03T17:29:57.350Z",+ "updatedAt": "2024-02-03T17:29:57.350Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo-16k-0613","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntjt89000a08jw0gcdbd5a_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "output": 0.000004+ }+ }+ ]},{"id": "clrntkjgy000a08jx4e062mr0",- "model_name": "gpt-3.5-turbo-0301",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-0301)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.000002,- "output": 0.000002- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-0301",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-0301)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": -1,"tokenizerModel": "gpt-3.5-turbo-0301","tokensPerMessage": 4},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntkjgy000a08jx4e062mr0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000002,+ "output": 0.000002+ }+ }+ ]},{"id": "clrntkjgy000d08jx0p4y9h4l",- "model_name": "gpt-4-32k-0314",- "match_pattern": "(?i)^(gpt-4-32k-0314)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00006,- "output": 0.00012- },- "tokenizer_config": {+ "modelName": "gpt-4-32k-0314",+ "matchPattern": "(?i)^(gpt-4-32k-0314)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-32k-0314","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntkjgy000d08jx0p4y9h4l_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00006,+ "output": 0.00012+ }+ }+ ]},{"id": "clrntkjgy000e08jx4x6uawoo",- "model_name": "gpt-4-0314",- "match_pattern": "(?i)^(gpt-4-0314)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00003,- "output": 0.00006- },- "tokenizer_config": {+ "modelName": "gpt-4-0314",+ "matchPattern": "(?i)^(gpt-4-0314)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-0314","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntkjgy000e08jx4x6uawoo_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00003,+ "output": 0.00006+ }+ }+ ]},{"id": "clrntkjgy000f08jx79v9g1xj",- "model_name": "gpt-4",- "match_pattern": "(?i)^(gpt-4)$",- "created_at": "2024-01-24T10:19:21.693Z",- "updated_at": "2024-01-24T10:19:21.693Z",- "prices": {- "input": 0.00003,- "output": 0.00006- },- "tokenizer_config": {+ "modelName": "gpt-4",+ "matchPattern": "(?i)^(gpt-4)$",+ "createdAt": "2024-01-24T10:19:21.693Z",+ "updatedAt": "2024-01-24T10:19:21.693Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrntkjgy000f08jx79v9g1xj_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00003,+ "output": 0.00006+ }+ }+ ]},{"id": "clrnwb41q000308jsfrac9uh6",- "model_name": "claude-instant-1.2",- "match_pattern": "(?i)^(claude-instant-1.2)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.00000163,- "output": 0.00000551- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-instant-1.2",+ "matchPattern": "(?i)^(claude-instant-1.2)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwb41q000308jsfrac9uh6_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000163,+ "output": 0.00000551+ }+ }+ ]},{"id": "clrnwb836000408jsallr6u11",- "model_name": "claude-2.0",- "match_pattern": "(?i)^(claude-2.0)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.000008,- "output": 0.000024- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-2.0",+ "matchPattern": "(?i)^(claude-2.0)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwb836000408jsallr6u11_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000008,+ "output": 0.000024+ }+ }+ ]},{"id": "clrnwbd1m000508js4hxu6o7n",- "model_name": "claude-2.1",- "match_pattern": "(?i)^(claude-2.1)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.000008,- "output": 0.000024- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-2.1",+ "matchPattern": "(?i)^(claude-2.1)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwbd1m000508js4hxu6o7n_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000008,+ "output": 0.000024+ }+ }+ ]},{"id": "clrnwbg2b000608jse2pp4q2d",- "model_name": "claude-1.3",- "match_pattern": "(?i)^(claude-1.3)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.000008,- "output": 0.000024- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-1.3",+ "matchPattern": "(?i)^(claude-1.3)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwbg2b000608jse2pp4q2d_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000008,+ "output": 0.000024+ }+ }+ ]},{"id": "clrnwbi9d000708jseiy44k26",- "model_name": "claude-1.2",- "match_pattern": "(?i)^(claude-1.2)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.000008,- "output": 0.000024- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-1.2",+ "matchPattern": "(?i)^(claude-1.2)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwbi9d000708jseiy44k26_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000008,+ "output": 0.000024+ }+ }+ ]},{"id": "clrnwblo0000808jsc1385hdp",- "model_name": "claude-1.1",- "match_pattern": "(?i)^(claude-1.1)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.000008,- "output": 0.000024- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-1.1",+ "matchPattern": "(?i)^(claude-1.1)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwblo0000808jsc1385hdp_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000008,+ "output": 0.000024+ }+ }+ ]},{"id": "clrnwbota000908jsgg9mb1ml",- "model_name": "claude-instant-1",- "match_pattern": "(?i)^(claude-instant-1)$",- "created_at": "2024-01-30T15:44:13.447Z",- "updated_at": "2024-01-30T15:44:13.447Z",- "prices": {- "input": 0.00000163,- "output": 0.00000551- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-instant-1",+ "matchPattern": "(?i)^(claude-instant-1)$",+ "createdAt": "2024-01-30T15:44:13.447Z",+ "updatedAt": "2024-01-30T15:44:13.447Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clrnwbota000908jsgg9mb1ml_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000163,+ "output": 0.00000551+ }+ }+ ]},{"id": "clrs2dnql000108l46vo0gp2t",- "model_name": "babbage-002",- "match_pattern": "(?i)^(babbage-002)$",- "created_at": "2024-01-26T17:35:21.129Z",- "updated_at": "2024-01-26T17:35:21.129Z",- "prices": {- "input": 4e-7,- "output": 0.0000016- },- "tokenizer_config": {+ "modelName": "babbage-002",+ "matchPattern": "(?i)^(babbage-002)$",+ "createdAt": "2024-01-26T17:35:21.129Z",+ "updatedAt": "2024-01-26T17:35:21.129Z",+ "tokenizerConfig": {"tokenizerModel": "babbage-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrs2dnql000108l46vo0gp2t_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 4e-7,+ "output": 0.0000016+ }+ }+ ]},{"id": "clrs2ds35000208l4g4b0hi3u",- "model_name": "davinci-002",- "match_pattern": "(?i)^(davinci-002)$",- "created_at": "2024-01-26T17:35:21.129Z",- "updated_at": "2024-01-26T17:35:21.129Z",- "prices": {- "input": 0.000006,- "output": 0.000012- },- "tokenizer_config": {+ "modelName": "davinci-002",+ "matchPattern": "(?i)^(davinci-002)$",+ "createdAt": "2024-01-26T17:35:21.129Z",+ "updatedAt": "2024-01-26T17:35:21.129Z",+ "tokenizerConfig": {"tokenizerModel": "davinci-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clrs2ds35000208l4g4b0hi3u_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000006,+ "output": 0.000012+ }+ }+ ]},{"id": "clruwn3pc00010al7bl611c8o",- "model_name": "text-embedding-3-small",- "match_pattern": "(?i)^(text-embedding-3-small)$",- "created_at": "2024-01-26T17:35:21.129Z",- "updated_at": "2024-01-26T17:35:21.129Z",- "prices": {- "total": 2e-8- },- "tokenizer_config": {+ "modelName": "text-embedding-3-small",+ "matchPattern": "(?i)^(text-embedding-3-small)$",+ "createdAt": "2024-01-26T17:35:21.129Z",+ "updatedAt": "2024-01-26T17:35:21.129Z",+ "tokenizerConfig": {"tokenizerModel": "text-embedding-ada-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clruwn3pc00010al7bl611c8o_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 2e-8+ }+ }+ ]},{"id": "clruwn76700020al7gp8e4g4l",- "model_name": "text-embedding-3-large",- "match_pattern": "(?i)^(text-embedding-3-large)$",- "created_at": "2024-01-26T17:35:21.129Z",- "updated_at": "2024-01-26T17:35:21.129Z",- "prices": {- "total": 1.3e-7- },- "tokenizer_config": {+ "modelName": "text-embedding-3-large",+ "matchPattern": "(?i)^(text-embedding-3-large)$",+ "createdAt": "2024-01-26T17:35:21.129Z",+ "updatedAt": "2024-01-26T17:35:21.129Z",+ "tokenizerConfig": {"tokenizerModel": "text-embedding-ada-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clruwn76700020al7gp8e4g4l_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 1.3e-7+ }+ }+ ]},{"id": "clruwnahl00030al7ab9rark7",- "model_name": "gpt-3.5-turbo-0125",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-0125)$",- "created_at": "2024-01-26T17:35:21.129Z",- "updated_at": "2024-01-26T17:35:21.129Z",- "prices": {- "input": 5e-7,- "output": 0.0000015- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-0125",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-0125)$",+ "createdAt": "2024-01-26T17:35:21.129Z",+ "updatedAt": "2024-01-26T17:35:21.129Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clruwnahl00030al7ab9rark7_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 5e-7,+ "output": 0.0000015+ }+ }+ ]},{"id": "clruwnahl00040al78f1lb0at",- "model_name": "gpt-3.5-turbo",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo)$",- "created_at": "2024-02-13T12:00:37.424Z",- "updated_at": "2024-02-13T12:00:37.424Z",- "prices": {- "input": 5e-7,- "output": 0.0000015- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo)$",+ "createdAt": "2024-02-13T12:00:37.424Z",+ "updatedAt": "2024-02-13T12:00:37.424Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clruwnahl00040al78f1lb0at_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 5e-7,+ "output": 0.0000015+ }+ }+ ]},{"id": "clruwnahl00050al796ck3p44",- "model_name": "gpt-4-0125-preview",- "match_pattern": "(?i)^(gpt-4-0125-preview)$",- "created_at": "2024-01-26T17:35:21.129Z",- "updated_at": "2024-01-26T17:35:21.129Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": "gpt-4-0125-preview",+ "matchPattern": "(?i)^(gpt-4-0125-preview)$",+ "createdAt": "2024-01-26T17:35:21.129Z",+ "updatedAt": "2024-01-26T17:35:21.129Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clruwnahl00050al796ck3p44_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "cls08r8sq000308jq14ae96f0",- "model_name": "ft:gpt-3.5-turbo-1106",- "match_pattern": "(?i)^(ft:)(gpt-3.5-turbo-1106:)(.+)(:)(.*)(:)(.+)$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 0.000003,- "output": 0.000006- },- "tokenizer_config": {+ "modelName": "ft:gpt-3.5-turbo-1106",+ "matchPattern": "(?i)^(ft:)(gpt-3.5-turbo-1106:)(.+)(:)(.*)(:)(.+)$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo-1106","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cls08r8sq000308jq14ae96f0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "output": 0.000006+ }+ }+ ]},{"id": "cls08rp99000408jqepxoakjv",- "model_name": "ft:gpt-3.5-turbo-0613",- "match_pattern": "(?i)^(ft:)(gpt-3.5-turbo-0613:)(.+)(:)(.*)(:)(.+)$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 0.000012,- "output": 0.000016- },- "tokenizer_config": {+ "modelName": "ft:gpt-3.5-turbo-0613",+ "matchPattern": "(?i)^(ft:)(gpt-3.5-turbo-0613:)(.+)(:)(.*)(:)(.+)$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo-0613","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cls08rp99000408jqepxoakjv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000012,+ "output": 0.000016+ }+ }+ ]},{"id": "cls08rv9g000508jq5p4z4nlr",- "model_name": "ft:davinci-002",- "match_pattern": "(?i)^(ft:)(davinci-002:)(.+)(:)(.*)(:)(.+)$$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 0.000012,- "output": 0.000012- },- "tokenizer_config": {+ "modelName": "ft:davinci-002",+ "matchPattern": "(?i)^(ft:)(davinci-002:)(.+)(:)(.*)(:)(.+)$$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "tokenizerConfig": {"tokenizerModel": "davinci-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cls08rv9g000508jq5p4z4nlr_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000012,+ "output": 0.000012+ }+ }+ ]},{"id": "cls08s2bw000608jq57wj4un2",- "model_name": "ft:babbage-002",- "match_pattern": "(?i)^(ft:)(babbage-002:)(.+)(:)(.*)(:)(.+)$$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 0.0000016,- "output": 0.0000016- },- "tokenizer_config": {+ "modelName": "ft:babbage-002",+ "matchPattern": "(?i)^(ft:)(babbage-002:)(.+)(:)(.*)(:)(.+)$$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "tokenizerConfig": {"tokenizerModel": "babbage-002"},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cls08s2bw000608jq57wj4un2_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000016,+ "output": 0.0000016+ }+ }+ ]},{"id": "cls0iv12d000108l251gf3038",- "model_name": "chat-bison",- "match_pattern": "(?i)^(chat-bison)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "chat-bison",+ "matchPattern": "(?i)^(chat-bison)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0iv12d000108l251gf3038_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls0j33v1000008joagkc4lql",- "model_name": "codechat-bison-32k",- "match_pattern": "(?i)^(codechat-bison-32k)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "codechat-bison-32k",+ "matchPattern": "(?i)^(codechat-bison-32k)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0j33v1000008joagkc4lql_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls0jmc9v000008l8ee6r3gsd",- "model_name": "codechat-bison",- "match_pattern": "(?i)^(codechat-bison)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "codechat-bison",+ "matchPattern": "(?i)^(codechat-bison)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0jmc9v000008l8ee6r3gsd_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls0jmjt3000108l83ix86w0d",- "model_name": "text-bison-32k",- "match_pattern": "(?i)^(text-bison-32k)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "text-bison-32k",+ "matchPattern": "(?i)^(text-bison-32k)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0jmjt3000108l83ix86w0d_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls0jni4t000008jk3kyy803r",- "model_name": "chat-bison-32k",- "match_pattern": "(?i)^(chat-bison-32k)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "chat-bison-32k",+ "matchPattern": "(?i)^(chat-bison-32k)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0jni4t000008jk3kyy803r_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls0jungb000208jk12gm4gk1",- "model_name": "text-unicorn",- "match_pattern": "(?i)^(text-unicorn)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 0.0000025,- "output": 0.0000075- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "text-unicorn",+ "matchPattern": "(?i)^(text-unicorn)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0jungb000208jk12gm4gk1_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000025,+ "output": 0.0000075+ }+ }+ ]},{"id": "cls0juygp000308jk2a6x9my2",- "model_name": "text-bison",- "match_pattern": "(?i)^(text-bison)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "text-bison",+ "matchPattern": "(?i)^(text-bison)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls0juygp000308jk2a6x9my2_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls1nyj5q000208l33ne901d8",- "model_name": "textembedding-gecko",- "match_pattern": "(?i)^(textembedding-gecko)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "total": 1e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "textembedding-gecko",+ "matchPattern": "(?i)^(textembedding-gecko)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls1nyj5q000208l33ne901d8_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 1e-7+ }+ }+ ]},{"id": "cls1nyyjp000308l31gxy1bih",- "model_name": "textembedding-gecko-multilingual",- "match_pattern": "(?i)^(textembedding-gecko-multilingual)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "total": 1e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "textembedding-gecko-multilingual",+ "matchPattern": "(?i)^(textembedding-gecko-multilingual)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls1nyyjp000308l31gxy1bih_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "total": 1e-7+ }+ }+ ]},{"id": "cls1nzjt3000508l3dnwad3g0",- "model_name": "code-gecko",- "match_pattern": "(?i)^(code-gecko)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "code-gecko",+ "matchPattern": "(?i)^(code-gecko)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls1nzjt3000508l3dnwad3g0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls1nzwx4000608l38va7e4tv",- "model_name": "code-bison",- "match_pattern": "(?i)^(code-bison)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "code-bison",+ "matchPattern": "(?i)^(code-bison)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls1nzwx4000608l38va7e4tv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cls1o053j000708l39f8g4bgs",- "model_name": "code-bison-32k",- "match_pattern": "(?i)^(code-bison-32k)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-01-31T13:25:02.141Z",- "updated_at": "2024-01-31T13:25:02.141Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "code-bison-32k",+ "matchPattern": "(?i)^(code-bison-32k)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-01-31T13:25:02.141Z",+ "updatedAt": "2024-01-31T13:25:02.141Z",+ "pricingTiers": [+ {+ "id": "cls1o053j000708l39f8g4bgs_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "clsk9lntu000008jwfc51bbqv",- "model_name": "gpt-3.5-turbo-16k",- "match_pattern": "(?i)^(gpt-)(35|3.5)(-turbo-16k)$",- "created_at": "2024-02-13T12:00:37.424Z",- "updated_at": "2024-02-13T12:00:37.424Z",- "prices": {- "input": 5e-7,- "output": 0.0000015- },- "tokenizer_config": {+ "modelName": "gpt-3.5-turbo-16k",+ "matchPattern": "(?i)^(gpt-)(35|3.5)(-turbo-16k)$",+ "createdAt": "2024-02-13T12:00:37.424Z",+ "updatedAt": "2024-02-13T12:00:37.424Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-3.5-turbo-16k","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clsk9lntu000008jwfc51bbqv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 5e-7,+ "output": 0.0000015+ }+ }+ ]},{"id": "clsnq07bn000008l4e46v1ll8",- "model_name": "gpt-4-turbo-preview",- "match_pattern": "(?i)^(gpt-4-turbo-preview)$",- "created_at": "2024-02-15T21:21:50.947Z",- "updated_at": "2024-02-15T21:21:50.947Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": "gpt-4-turbo-preview",+ "matchPattern": "(?i)^(gpt-4-turbo-preview)$",+ "createdAt": "2024-02-15T21:21:50.947Z",+ "updatedAt": "2024-02-15T21:21:50.947Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clsnq07bn000008l4e46v1ll8_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "cltgy0iuw000008le3vod1hhy",- "model_name": "claude-3-opus-20240229",- "match_pattern": "(?i)^(claude-3-opus-20240229|anthropic\\.claude-3-opus-20240229-v1:0|claude-3-opus@20240229)$",- "created_at": "2024-03-07T17:55:38.139Z",- "updated_at": "2024-03-07T17:55:38.139Z",- "prices": {- "input": 0.000015,- "output": 0.000075- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3-opus-20240229",+ "matchPattern": "(?i)^(claude-3-opus-20240229|anthropic\\.claude-3-opus-20240229-v1:0|claude-3-opus@20240229)$",+ "createdAt": "2024-03-07T17:55:38.139Z",+ "updatedAt": "2024-03-07T17:55:38.139Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cltgy0iuw000008le3vod1hhy_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "output": 0.000075+ }+ }+ ]},{"id": "cltgy0pp6000108le56se7bl3",- "model_name": "claude-3-sonnet-20240229",- "match_pattern": "(?i)^(claude-3-sonnet-20240229|anthropic\\.claude-3-sonnet-20240229-v1:0|claude-3-sonnet@20240229)$",- "created_at": "2024-03-07T17:55:38.139Z",- "updated_at": "2024-12-03T12:20:04.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3-sonnet-20240229",+ "matchPattern": "(?i)^(claude-3-sonnet-20240229|anthropic\\.claude-3-sonnet-20240229-v1:0|claude-3-sonnet@20240229)$",+ "createdAt": "2024-03-07T17:55:38.139Z",+ "updatedAt": "2024-12-03T12:20:04.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cltgy0pp6000108le56se7bl3_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cltr0w45b000008k1407o9qv1",- "model_name": "claude-3-haiku-20240307",- "match_pattern": "(?i)^(claude-3-haiku-20240307|anthropic\\.claude-3-haiku-20240307-v1:0|claude-3-haiku@20240307)$",- "created_at": "2024-03-14T09:41:18.736Z",- "updated_at": "2024-03-14T09:41:18.736Z",- "prices": {- "input": 2.5e-7,- "output": 0.00000125- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3-haiku-20240307",+ "matchPattern": "(?i)^(claude-3-haiku-20240307|anthropic\\.claude-3-haiku-20240307-v1:0|claude-3-haiku@20240307)$",+ "createdAt": "2024-03-14T09:41:18.736Z",+ "updatedAt": "2024-03-14T09:41:18.736Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cltr0w45b000008k1407o9qv1_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 0.00000125+ }+ }+ ]},{"id": "cluv2sjeo000008ih0fv23hi0",- "model_name": "gemini-1.0-pro-latest",- "match_pattern": "(?i)^(gemini-1.0-pro-latest)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-04-11T10:27:46.517Z",- "updated_at": "2024-04-11T10:27:46.517Z",- "prices": {- "input": 2.5e-7,- "output": 5e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-1.0-pro-latest",+ "matchPattern": "(?i)^(gemini-1.0-pro-latest)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-04-11T10:27:46.517Z",+ "updatedAt": "2024-04-11T10:27:46.517Z",+ "pricingTiers": [+ {+ "id": "cluv2sjeo000008ih0fv23hi0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "output": 5e-7+ }+ }+ ]},{"id": "cluv2subq000108ih2mlrga6a",- "model_name": "gemini-1.0-pro",- "match_pattern": "(?i)^(gemini-1.0-pro)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-04-11T10:27:46.517Z",- "updated_at": "2024-04-11T10:27:46.517Z",- "prices": {- "input": 1.25e-7,- "output": 3.75e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-1.0-pro",+ "matchPattern": "(?i)^(gemini-1.0-pro)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-04-11T10:27:46.517Z",+ "updatedAt": "2024-04-11T10:27:46.517Z",+ "pricingTiers": [+ {+ "id": "cluv2subq000108ih2mlrga6a_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1.25e-7,+ "output": 3.75e-7+ }+ }+ ]},{"id": "cluv2sx04000208ihbek75lsz",- "model_name": "gemini-1.0-pro-001",- "match_pattern": "(?i)^(gemini-1.0-pro-001)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-04-11T10:27:46.517Z",- "updated_at": "2024-04-11T10:27:46.517Z",- "prices": {- "input": 1.25e-7,- "output": 3.75e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-1.0-pro-001",+ "matchPattern": "(?i)^(gemini-1.0-pro-001)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-04-11T10:27:46.517Z",+ "updatedAt": "2024-04-11T10:27:46.517Z",+ "pricingTiers": [+ {+ "id": "cluv2sx04000208ihbek75lsz_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1.25e-7,+ "output": 3.75e-7+ }+ }+ ]},{"id": "cluv2szw0000308ihch3n79x7",- "model_name": "gemini-pro",- "match_pattern": "(?i)^(gemini-pro)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-04-11T10:27:46.517Z",- "updated_at": "2024-04-11T10:27:46.517Z",- "prices": {- "input": 1.25e-7,- "output": 3.75e-7- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-pro",+ "matchPattern": "(?i)^(gemini-pro)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-04-11T10:27:46.517Z",+ "updatedAt": "2024-04-11T10:27:46.517Z",+ "pricingTiers": [+ {+ "id": "cluv2szw0000308ihch3n79x7_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1.25e-7,+ "output": 3.75e-7+ }+ }+ ]},{"id": "cluv2t2x0000408ihfytl45l1",- "model_name": "gemini-1.5-pro-latest",- "match_pattern": "(?i)^(gemini-1.5-pro-latest)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-04-11T10:27:46.517Z",- "updated_at": "2024-04-11T10:27:46.517Z",- "prices": {- "input": 0.0000025,- "output": 0.0000075- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-1.5-pro-latest",+ "matchPattern": "(?i)^(gemini-1.5-pro-latest)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2024-04-11T10:27:46.517Z",+ "updatedAt": "2024-04-11T10:27:46.517Z",+ "pricingTiers": [+ {+ "id": "cluv2t2x0000408ihfytl45l1_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000025,+ "output": 0.0000075+ }+ }+ ]},{"id": "cluv2t5k3000508ih5kve9zag",- "model_name": "gpt-4-turbo-2024-04-09",- "match_pattern": "(?i)^(gpt-4-turbo-2024-04-09)$",- "created_at": "2024-04-23T10:37:17.092Z",- "updated_at": "2024-04-23T10:37:17.092Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": "gpt-4-turbo-2024-04-09",+ "matchPattern": "(?i)^(gpt-4-turbo-2024-04-09)$",+ "createdAt": "2024-04-23T10:37:17.092Z",+ "updatedAt": "2024-04-23T10:37:17.092Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-turbo-2024-04-09","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cluv2t5k3000508ih5kve9zag_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "cluvpl4ls000008l6h2gx3i07",- "model_name": "gpt-4-turbo",- "match_pattern": "(?i)^(gpt-4-turbo)$",- "created_at": "2024-04-11T21:13:44.989Z",- "updated_at": "2024-04-11T21:13:44.989Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": "gpt-4-turbo",+ "matchPattern": "(?i)^(gpt-4-turbo)$",+ "createdAt": "2024-04-11T21:13:44.989Z",+ "updatedAt": "2024-04-11T21:13:44.989Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-1106-preview","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cluvpl4ls000008l6h2gx3i07_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "clv2o2x0p000008jsf9afceau",- "model_name": " gpt-4-preview",- "match_pattern": "(?i)^(gpt-4-preview)$",- "created_at": "2024-04-23T10:37:17.092Z",- "updated_at": "2024-04-23T10:37:17.092Z",- "prices": {- "input": 0.00001,- "output": 0.00003- },- "tokenizer_config": {+ "modelName": " gpt-4-preview",+ "matchPattern": "(?i)^(gpt-4-preview)$",+ "createdAt": "2024-04-23T10:37:17.092Z",+ "updatedAt": "2024-04-23T10:37:17.092Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4-turbo-preview","tokensPerMessage": 3},- "tokenizer_id": "openai"- },- {- "id": "clx30djsn0000w9mzebiv41we",- "model_name": "gemini-1.5-flash",- "match_pattern": "(?i)^(gemini-1.5-flash)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-06-12T17:09:36.206Z",- "updated_at": "2024-06-12T17:09:36.206Z",- "prices": {},- "tokenizer_config": null,- "tokenizer_id": null- },- {- "id": "clx30hkrx0000w9mz7lqi0ial",- "model_name": "gemini-1.5-pro",- "match_pattern": "(?i)^(gemini-1.5-pro)(@[a-zA-Z0-9]+)?$",- "created_at": "2024-06-12T17:09:36.206Z",- "updated_at": "2024-06-12T17:09:36.206Z",- "prices": {},- "tokenizer_config": null,- "tokenizer_id": null+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clv2o2x0p000008jsf9afceau_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00001,+ "output": 0.00003+ }+ }+ ]},{"id": "clxt0n0m60000pumz1j5b7zsf",- "model_name": "claude-3-5-sonnet-20240620",- "match_pattern": "(?i)^(claude-3-5-sonnet-20240620|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3-5-sonnet-20240620-v1:0|claude-3-5-sonnet@20240620)$",- "created_at": "2024-06-25T11:47:24.475Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3-5-sonnet-20240620",+ "matchPattern": "(?i)^(claude-3-5-sonnet-20240620|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3-5-sonnet-20240620-v1:0|claude-3-5-sonnet@20240620)$",+ "createdAt": "2024-06-25T11:47:24.475Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "clxt0n0m60000pumz1j5b7zsf_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "clyrjp56f0000t0mzapoocd7u",- "model_name": "gpt-4o-mini",- "match_pattern": "(?i)^(gpt-4o-mini)$",- "created_at": "2024-07-18T17:56:09.591Z",- "updated_at": "2024-12-03T10:28:30.000Z",- "prices": {- "input": 0.15e-6,- "output": 0.6e-6,- "input_cached_tokens": 0.075e-6,- "input_cache_read": 0.075e-6- },- "tokenizer_config": {+ "modelName": "gpt-4o-mini",+ "matchPattern": "(?i)^(gpt-4o-mini)$",+ "createdAt": "2024-07-18T17:56:09.591Z",+ "updatedAt": "2024-12-03T10:28:30.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clyrjp56f0000t0mzapoocd7u_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1.5e-7,+ "output": 6e-7,+ "input_cached_tokens": 7.5e-8,+ "input_cache_read": 7.5e-8+ }+ }+ ]},{"id": "clyrjpbe20000t0mzcbwc42rg",- "model_name": "gpt-4o-mini-2024-07-18",- "match_pattern": "(?i)^(gpt-4o-mini-2024-07-18)$",- "created_at": "2024-07-18T17:56:09.591Z",- "updated_at": "2024-12-03T10:31:11.000Z",- "prices": {- "input": 0.15e-6,- "input_cached_tokens": 0.075e-6,- "input_cache_read": 0.075e-6,- "output": 0.6e-6- },- "tokenizer_config": {+ "modelName": "gpt-4o-mini-2024-07-18",+ "matchPattern": "(?i)^(gpt-4o-mini-2024-07-18)$",+ "createdAt": "2024-07-18T17:56:09.591Z",+ "updatedAt": "2024-12-03T10:31:11.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clyrjpbe20000t0mzcbwc42rg_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1.5e-7,+ "input_cached_tokens": 7.5e-8,+ "input_cache_read": 7.5e-8,+ "output": 6e-7+ }+ }+ ]},{"id": "clzjr85f70000ymmzg7hqffra",- "model_name": "gpt-4o-2024-08-06",- "match_pattern": "(?i)^(gpt-4o-2024-08-06)$",- "created_at": "2024-08-07T11:54:31.298Z",- "updated_at": "2024-12-03T10:15:18.000Z",- "prices": {- "input": 2.5e-6,- "input_cached_tokens": 1.25e-6,- "input_cache_read": 1.25e-6,- "output": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-4o-2024-08-06",+ "matchPattern": "(?i)^(gpt-4o-2024-08-06)$",+ "createdAt": "2024-08-07T11:54:31.298Z",+ "updatedAt": "2024-12-03T10:15:18.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "clzjr85f70000ymmzg7hqffra_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000025,+ "input_cached_tokens": 0.00000125,+ "input_cache_read": 0.00000125,+ "output": 0.00001+ }+ }+ ]},{"id": "cm10ivcdp0000gix7lelmbw80",- "model_name": "o1-preview",- "match_pattern": "(?i)^(o1-preview)$",- "created_at": "2024-09-13T10:01:35.373Z",- "updated_at": "2024-12-03T10:34:05.000Z",- "prices": {- "input": 15e-6,- "input_cached_tokens": 7.5e-6,- "input_cache_read": 7.5e-6,- "output": 60e-6,- "output_reasoning_tokens": 60e-6,- "output_reasoning": 60e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-preview",+ "matchPattern": "(?i)^(o1-preview)$",+ "createdAt": "2024-09-13T10:01:35.373Z",+ "updatedAt": "2024-12-03T10:34:05.000Z",+ "pricingTiers": [+ {+ "id": "cm10ivcdp0000gix7lelmbw80_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "input_cached_tokens": 0.0000075,+ "input_cache_read": 0.0000075,+ "output": 0.00006,+ "output_reasoning_tokens": 0.00006,+ "output_reasoning": 0.00006+ }+ }+ ]},{"id": "cm10ivo130000n8x7qopcjjcg",- "model_name": "o1-preview-2024-09-12",- "match_pattern": "(?i)^(o1-preview-2024-09-12)$",- "created_at": "2024-09-13T10:01:35.373Z",- "updated_at": "2024-12-03T10:38:51.000Z",- "prices": {- "input": 15e-6,- "input_cached_tokens": 7.5e-6,- "input_cache_read": 7.5e-6,- "output": 60e-6,- "output_reasoning_tokens": 60e-6,- "output_reasoning": 60e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-preview-2024-09-12",+ "matchPattern": "(?i)^(o1-preview-2024-09-12)$",+ "createdAt": "2024-09-13T10:01:35.373Z",+ "updatedAt": "2024-12-03T10:38:51.000Z",+ "pricingTiers": [+ {+ "id": "cm10ivo130000n8x7qopcjjcg_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "input_cached_tokens": 0.0000075,+ "input_cache_read": 0.0000075,+ "output": 0.00006,+ "output_reasoning_tokens": 0.00006,+ "output_reasoning": 0.00006+ }+ }+ ]},{"id": "cm10ivwo40000r1x7gg3syjq0",- "model_name": "o1-mini",- "match_pattern": "(?i)^(o1-mini)$",- "created_at": "2024-09-13T10:01:35.373Z",- "updated_at": "2025-02-01T12:41:55.000Z",- "prices": {- "input": 1.1e-6,- "input_cached_tokens": 0.55e-6,- "input_cache_read": 0.55e-6,- "output": 4.4e-6,- "output_reasoning_tokens": 4.4e-6,- "output_reasoning": 4.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-mini",+ "matchPattern": "(?i)^(o1-mini)$",+ "createdAt": "2024-09-13T10:01:35.373Z",+ "updatedAt": "2025-02-01T12:41:55.000Z",+ "pricingTiers": [+ {+ "id": "cm10ivwo40000r1x7gg3syjq0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000011,+ "input_cached_tokens": 5.5e-7,+ "input_cache_read": 5.5e-7,+ "output": 0.0000044,+ "output_reasoning_tokens": 0.0000044,+ "output_reasoning": 0.0000044+ }+ }+ ]},{"id": "cm10iw6p20000wgx7it1hlb22",- "model_name": "o1-mini-2024-09-12",- "match_pattern": "(?i)^(o1-mini-2024-09-12)$",- "created_at": "2024-09-13T10:01:35.373Z",- "updated_at": "2025-02-01T12:41:55.000Z",- "prices": {- "input": 1.1e-6,- "input_cached_tokens": 0.55e-6,- "input_cache_read": 0.55e-6,- "output": 4.4e-6,- "output_reasoning_tokens": 4.4e-6,- "output_reasoning": 4.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-mini-2024-09-12",+ "matchPattern": "(?i)^(o1-mini-2024-09-12)$",+ "createdAt": "2024-09-13T10:01:35.373Z",+ "updatedAt": "2025-02-01T12:41:55.000Z",+ "pricingTiers": [+ {+ "id": "cm10iw6p20000wgx7it1hlb22_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000011,+ "input_cached_tokens": 5.5e-7,+ "input_cache_read": 5.5e-7,+ "output": 0.0000044,+ "output_reasoning_tokens": 0.0000044,+ "output_reasoning": 0.0000044+ }+ }+ ]},{"id": "cm2krz1uf000208jjg5653iud",- "model_name": "claude-3.5-sonnet-20241022",- "match_pattern": "(?i)^(claude-3-5-sonnet-20241022|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3-5-sonnet-20241022-v2:0|claude-3-5-sonnet-V2@20241022)$",- "created_at": "2024-10-22T18:48:01.676Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3.5-sonnet-20241022",+ "matchPattern": "(?i)^(claude-3-5-sonnet-20241022|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3-5-sonnet-20241022-v2:0|claude-3-5-sonnet-V2@20241022)$",+ "createdAt": "2024-10-22T18:48:01.676Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cm2krz1uf000208jjg5653iud_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cm2ks2vzn000308jjh4ze1w7q",- "model_name": "claude-3.5-sonnet-latest",- "match_pattern": "(?i)^(claude-3-5-sonnet-latest)$",- "created_at": "2024-10-22T18:48:01.676Z",- "updated_at": "2024-12-03T12:22:03.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3.5-sonnet-latest",+ "matchPattern": "(?i)^(claude-3-5-sonnet-latest)$",+ "createdAt": "2024-10-22T18:48:01.676Z",+ "updatedAt": "2024-12-03T12:22:03.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cm2ks2vzn000308jjh4ze1w7q_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cm34aq60d000207ml0j1h31ar",- "model_name": "claude-3-5-haiku-20241022",- "match_pattern": "(?i)^(claude-3-5-haiku-20241022|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3-5-haiku-20241022-v1:0|claude-3-5-haiku-V1@20241022)$",- "created_at": "2024-11-05T10:30:50.566Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 0.8e-6,- "input_tokens": 0.8e-6,- "output": 4e-6,- "output_tokens": 4e-6,- "cache_creation_input_tokens": 1e-6,- "input_cache_creation": 1e-6,- "cache_read_input_tokens": 0.08e-6,- "input_cache_read": 0.08e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3-5-haiku-20241022",+ "matchPattern": "(?i)^(claude-3-5-haiku-20241022|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3-5-haiku-20241022-v1:0|claude-3-5-haiku-V1@20241022)$",+ "createdAt": "2024-11-05T10:30:50.566Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cm34aq60d000207ml0j1h31ar_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 8e-7,+ "input_tokens": 8e-7,+ "output": 0.000004,+ "output_tokens": 0.000004,+ "cache_creation_input_tokens": 0.000001,+ "input_cache_creation": 0.000001,+ "cache_read_input_tokens": 8e-8,+ "input_cache_read": 8e-8+ }+ }+ ]},{"id": "cm34aqb9h000307ml6nypd618",- "model_name": "claude-3.5-haiku-latest",- "match_pattern": "(?i)^(claude-3-5-haiku-latest)$",- "created_at": "2024-11-05T10:30:50.566Z",- "updated_at": "2024-12-03T12:26:33.000Z",- "prices": {- "input": 0.8e-6,- "input_tokens": 0.8e-6,- "output": 4e-6,- "output_tokens": 4e-6,- "cache_creation_input_tokens": 1e-6,- "input_cache_creation": 1e-6,- "cache_read_input_tokens": 0.08e-6,- "input_cache_read": 0.08e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3.5-haiku-latest",+ "matchPattern": "(?i)^(claude-3-5-haiku-latest)$",+ "createdAt": "2024-11-05T10:30:50.566Z",+ "updatedAt": "2024-12-03T12:26:33.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cm34aqb9h000307ml6nypd618_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 8e-7,+ "input_tokens": 8e-7,+ "output": 0.000004,+ "output_tokens": 0.000004,+ "cache_creation_input_tokens": 0.000001,+ "input_cache_creation": 0.000001,+ "cache_read_input_tokens": 8e-8,+ "input_cache_read": 8e-8+ }+ }+ ]},{"id": "cm3x0p8ev000008kyd96800c8",- "model_name": "chatgpt-4o-latest",- "match_pattern": "(?i)^(chatgpt-4o-latest)$",- "created_at": "2024-11-25T12:47:17.504Z",- "updated_at": "2024-11-25T12:47:17.504Z",- "prices": {- "input": 0.000005,- "output": 0.000015- },- "tokenizer_config": {+ "modelName": "chatgpt-4o-latest",+ "matchPattern": "(?i)^(chatgpt-4o-latest)$",+ "createdAt": "2024-11-25T12:47:17.504Z",+ "updatedAt": "2024-11-25T12:47:17.504Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm3x0p8ev000008kyd96800c8_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000005,+ "output": 0.000015+ }+ }+ ]},{"id": "cm48akqgo000008ldbia24qg0",- "model_name": "gpt-4o-2024-11-20",- "match_pattern": "(?i)^(gpt-4o-2024-11-20)$",- "created_at": "2024-12-03T10:06:12.000Z",- "updated_at": "2024-12-03T10:06:12.000Z",- "prices": {- "input": 2.5e-6,- "input_cached_tokens": 1.25e-6,- "input_cache_read": 1.25e-6,- "output": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-4o-2024-11-20",+ "matchPattern": "(?i)^(gpt-4o-2024-11-20)$",+ "createdAt": "2024-12-03T10:06:12.000Z",+ "updatedAt": "2024-12-03T10:06:12.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4o","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm48akqgo000008ldbia24qg0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000025,+ "input_cached_tokens": 0.00000125,+ "input_cache_read": 0.00000125,+ "output": 0.00001+ }+ }+ ]},{"id": "cm48b2ksh000008l0hn3u0hl3",- "model_name": "gpt-4o-audio-preview",- "match_pattern": "(?i)^(gpt-4o-audio-preview)$",- "created_at": "2024-12-03T10:19:56.000Z",- "updated_at": "2024-12-03T10:19:56.000Z",- "prices": {- "input_text_tokens": 2.5e-6,- "output_text_tokens": 10e-6,- "input_audio_tokens": 100e-6,- "input_audio": 100e-6,- "output_audio_tokens": 200e-6,- "output_audio": 200e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gpt-4o-audio-preview",+ "matchPattern": "(?i)^(gpt-4o-audio-preview)$",+ "createdAt": "2024-12-03T10:19:56.000Z",+ "updatedAt": "2024-12-03T10:19:56.000Z",+ "pricingTiers": [+ {+ "id": "cm48b2ksh000008l0hn3u0hl3_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input_text_tokens": 0.0000025,+ "output_text_tokens": 0.00001,+ "input_audio_tokens": 0.0001,+ "input_audio": 0.0001,+ "output_audio_tokens": 0.0002,+ "output_audio": 0.0002+ }+ }+ ]},{"id": "cm48bbm0k000008l69nsdakwf",- "model_name": "gpt-4o-audio-preview-2024-10-01",- "match_pattern": "(?i)^(gpt-4o-audio-preview-2024-10-01)$",- "created_at": "2024-12-03T10:19:56.000Z",- "updated_at": "2024-12-03T10:19:56.000Z",- "prices": {- "input_text_tokens": 2.5e-6,- "output_text_tokens": 10e-6,- "input_audio_tokens": 100e-6,- "input_audio": 100e-6,- "output_audio_tokens": 200e-6,- "output_audio": 200e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gpt-4o-audio-preview-2024-10-01",+ "matchPattern": "(?i)^(gpt-4o-audio-preview-2024-10-01)$",+ "createdAt": "2024-12-03T10:19:56.000Z",+ "updatedAt": "2024-12-03T10:19:56.000Z",+ "pricingTiers": [+ {+ "id": "cm48bbm0k000008l69nsdakwf_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input_text_tokens": 0.0000025,+ "output_text_tokens": 0.00001,+ "input_audio_tokens": 0.0001,+ "input_audio": 0.0001,+ "output_audio_tokens": 0.0002,+ "output_audio": 0.0002+ }+ }+ ]},{"id": "cm48c2qh4000008mhgy4mg2qc",- "model_name": "gpt-4o-realtime-preview",- "match_pattern": "(?i)^(gpt-4o-realtime-preview)$",- "created_at": "2024-12-03T10:19:56.000Z",- "updated_at": "2024-12-03T10:19:56.000Z",- "prices": {- "input_text_tokens": 5e-6,- "input_cached_text_tokens": 2.5e-6,- "output_text_tokens": 20e-6,- "input_audio_tokens": 100e-6,- "input_audio": 100e-6,- "input_cached_audio_tokens": 20e-6,- "output_audio_tokens": 200e-6,- "output_audio": 200e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gpt-4o-realtime-preview",+ "matchPattern": "(?i)^(gpt-4o-realtime-preview)$",+ "createdAt": "2024-12-03T10:19:56.000Z",+ "updatedAt": "2024-12-03T10:19:56.000Z",+ "pricingTiers": [+ {+ "id": "cm48c2qh4000008mhgy4mg2qc_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input_text_tokens": 0.000005,+ "input_cached_text_tokens": 0.0000025,+ "output_text_tokens": 0.00002,+ "input_audio_tokens": 0.0001,+ "input_audio": 0.0001,+ "input_cached_audio_tokens": 0.00002,+ "output_audio_tokens": 0.0002,+ "output_audio": 0.0002+ }+ }+ ]},{"id": "cm48cjxtc000008jrcsso3avv",- "model_name": "gpt-4o-realtime-preview-2024-10-01",- "match_pattern": "(?i)^(gpt-4o-realtime-preview-2024-10-01)$",- "created_at": "2024-12-03T10:19:56.000Z",- "updated_at": "2024-12-03T10:19:56.000Z",- "prices": {- "input_text_tokens": 5e-6,- "input_cached_text_tokens": 2.5e-6,- "output_text_tokens": 20e-6,- "input_audio_tokens": 100e-6,- "input_audio": 100e-6,- "input_cached_audio_tokens": 20e-6,- "output_audio_tokens": 200e-6,- "output_audio": 200e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gpt-4o-realtime-preview-2024-10-01",+ "matchPattern": "(?i)^(gpt-4o-realtime-preview-2024-10-01)$",+ "createdAt": "2024-12-03T10:19:56.000Z",+ "updatedAt": "2024-12-03T10:19:56.000Z",+ "pricingTiers": [+ {+ "id": "cm48cjxtc000008jrcsso3avv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input_text_tokens": 0.000005,+ "input_cached_text_tokens": 0.0000025,+ "output_text_tokens": 0.00002,+ "input_audio_tokens": 0.0001,+ "input_audio": 0.0001,+ "input_cached_audio_tokens": 0.00002,+ "output_audio_tokens": 0.0002,+ "output_audio": 0.0002+ }+ }+ ]},{"id": "cm48cjxtc000108jrcsso3avv",- "model_name": "o1",- "match_pattern": "(?i)^(o1)$",- "created_at": "2025-01-17T00:01:35.373Z",- "updated_at": "2025-01-17T00:01:35.373Z",- "prices": {- "input": 15e-6,- "input_cached_tokens": 7.5e-6,- "input_cache_read": 7.5e-6,- "output": 60e-6,- "output_reasoning_tokens": 60e-6,- "output_reasoning": 60e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1",+ "matchPattern": "(?i)^(o1)$",+ "createdAt": "2025-01-17T00:01:35.373Z",+ "updatedAt": "2025-01-17T00:01:35.373Z",+ "pricingTiers": [+ {+ "id": "cm48cjxtc000108jrcsso3avv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "input_cached_tokens": 0.0000075,+ "input_cache_read": 0.0000075,+ "output": 0.00006,+ "output_reasoning_tokens": 0.00006,+ "output_reasoning": 0.00006+ }+ }+ ]},{"id": "cm48cjxtc000208jrcsso3avv",- "model_name": "o1-2024-12-17",- "match_pattern": "(?i)^(o1-2024-12-17)$",- "created_at": "2025-01-17T00:01:35.373Z",- "updated_at": "2025-01-17T00:01:35.373Z",- "prices": {- "input": 15e-6,- "input_cached_tokens": 7.5e-6,- "input_cache_read": 7.5e-6,- "output": 60e-6,- "output_reasoning_tokens": 60e-6,- "output_reasoning": 60e-6- },- "tokenizer_config": null,- "tokenizer_id": null- },- {- "id": "cm48cjxtc000308jrcsso3avv",- "model_name": "gemini-2.0-flash-exp",- "match_pattern": "(?i)^(gemini-2.0-flash-exp)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-01-17T11:11:35.241Z",- "updated_at": "2025-01-17T11:11:35.241Z",- "prices": {},- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-2024-12-17",+ "matchPattern": "(?i)^(o1-2024-12-17)$",+ "createdAt": "2025-01-17T00:01:35.373Z",+ "updatedAt": "2025-01-17T00:01:35.373Z",+ "pricingTiers": [+ {+ "id": "cm48cjxtc000208jrcsso3avv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "input_cached_tokens": 0.0000075,+ "input_cache_read": 0.0000075,+ "output": 0.00006,+ "output_reasoning_tokens": 0.00006,+ "output_reasoning": 0.00006+ }+ }+ ]},{"id": "cm6l8j7vs0000tymz9vk7ew8t",- "model_name": "o3-mini",- "match_pattern": "(?i)^(o3-mini)$",- "created_at": "2025-01-31T20:41:35.373Z",- "updated_at": "2025-01-31T20:41:35.373Z",- "prices": {- "input": 1.1e-6,- "input_cached_tokens": 0.55e-6,- "input_cache_read": 0.55e-6,- "output": 4.4e-6,- "output_reasoning_tokens": 4.4e-6,- "output_reasoning": 4.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o3-mini",+ "matchPattern": "(?i)^(o3-mini)$",+ "createdAt": "2025-01-31T20:41:35.373Z",+ "updatedAt": "2025-01-31T20:41:35.373Z",+ "pricingTiers": [+ {+ "id": "cm6l8j7vs0000tymz9vk7ew8t_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000011,+ "input_cached_tokens": 5.5e-7,+ "input_cache_read": 5.5e-7,+ "output": 0.0000044,+ "output_reasoning_tokens": 0.0000044,+ "output_reasoning": 0.0000044+ }+ }+ ]},{"id": "cm6l8jan90000tymz52sh0ql8",- "model_name": "o3-mini-2025-01-31",- "match_pattern": "(?i)^(o3-mini-2025-01-31)$",- "created_at": "2025-01-31T20:41:35.373Z",- "updated_at": "2025-01-31T20:41:35.373Z",- "prices": {- "input": 1.1e-6,- "input_cached_tokens": 0.55e-6,- "input_cache_read": 0.55e-6,- "output": 4.4e-6,- "output_reasoning_tokens": 4.4e-6,- "output_reasoning": 4.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null- },- {- "id": "cm6l8jbcd0000tymz52sh0ql9",- "model_name": "gemini-2.0-pro-exp-02-05",- "match_pattern": "(?i)^(gemini-2.0-pro-exp-02-05)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-02-06T11:11:35.241Z",- "updated_at": "2025-02-06T11:11:35.241Z",- "prices": {},- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o3-mini-2025-01-31",+ "matchPattern": "(?i)^(o3-mini-2025-01-31)$",+ "createdAt": "2025-01-31T20:41:35.373Z",+ "updatedAt": "2025-01-31T20:41:35.373Z",+ "pricingTiers": [+ {+ "id": "cm6l8jan90000tymz52sh0ql8_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000011,+ "input_cached_tokens": 5.5e-7,+ "input_cache_read": 5.5e-7,+ "output": 0.0000044,+ "output_reasoning_tokens": 0.0000044,+ "output_reasoning": 0.0000044+ }+ }+ ]},{"id": "cm6l8jdef0000tymz52sh0ql0",- "model_name": "gemini-2.0-flash-001",- "match_pattern": "(?i)^(gemini-2.0-flash-001)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-02-06T11:11:35.241Z",- "updated_at": "2025-02-10T10:11:35.241Z",- "prices": {- "input": 0.1e-6,- "output": 0.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-2.0-flash-001",+ "matchPattern": "(?i)^(gemini-2.0-flash-001)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2025-02-06T11:11:35.241Z",+ "updatedAt": "2025-02-10T10:11:35.241Z",+ "pricingTiers": [+ {+ "id": "cm6l8jdef0000tymz52sh0ql0_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1e-7,+ "output": 4e-7+ }+ }+ ]},{"id": "cm6l8jfgh0000tymz52sh0ql1",- "model_name": "gemini-2.0-flash-lite-preview-02-05",- "match_pattern": "(?i)^(gemini-2.0-flash-lite-preview-02-05)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-02-06T11:11:35.241Z",- "updated_at": "2025-02-10T10:11:35.241Z",- "prices": {- "input": 0.075e-6,- "output": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-2.0-flash-lite-preview-02-05",+ "matchPattern": "(?i)^(gemini-2.0-flash-lite-preview-02-05)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2025-02-06T11:11:35.241Z",+ "updatedAt": "2025-02-10T10:11:35.241Z",+ "pricingTiers": [+ {+ "id": "cm6l8jfgh0000tymz52sh0ql1_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 7.5e-8,+ "output": 3e-7+ }+ }+ ]},{"id": "cm7ka7561000108js3t9tb3at",- "model_name": "claude-3.7-sonnet-20250219",- "match_pattern": "(?i)^(claude-3.7-sonnet-20250219|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3.7-sonnet-20250219-v1:0|claude-3-7-sonnet-V1@20250219)$",- "created_at": "2025-02-25T09:35:39.000Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3.7-sonnet-20250219",+ "matchPattern": "(?i)^(claude-3.7-sonnet-20250219|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-3.7-sonnet-20250219-v1:0|claude-3-7-sonnet-V1@20250219)$",+ "createdAt": "2025-02-25T09:35:39.000Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cm7ka7561000108js3t9tb3at_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cm7ka7zob000208jsfs9h5ajj",- "model_name": "claude-3.7-sonnet-latest",- "match_pattern": "(?i)^(claude-3-7-sonnet-latest)$",- "created_at": "2025-02-25T09:35:39.000Z",- "updated_at": "2025-02-25T09:35:39.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-3.7-sonnet-latest",+ "matchPattern": "(?i)^(claude-3-7-sonnet-latest)$",+ "createdAt": "2025-02-25T09:35:39.000Z",+ "updatedAt": "2025-02-25T09:35:39.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cm7ka7zob000208jsfs9h5ajj_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cm7nusjvk0000tvmz71o85jwg",- "model_name": "gpt-4.5-preview",- "match_pattern": "(?i)^(gpt-4.5-preview)$",- "created_at": "2025-02-27T21:26:54.132Z",- "updated_at": "2025-02-27T21:26:54.132Z",- "prices": {- "input": 75e-6,- "input_cached_tokens": 37.5e-6,- "input_cached_text_tokens": 37.5e-6,- "input_cache_read": 37.5e-6,- "output": 150e-6- }+ "modelName": "gpt-4.5-preview",+ "matchPattern": "(?i)^(gpt-4.5-preview)$",+ "createdAt": "2025-02-27T21:26:54.132Z",+ "updatedAt": "2025-02-27T21:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cm7nusjvk0000tvmz71o85jwg_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000075,+ "input_cached_tokens": 0.0000375,+ "input_cached_text_tokens": 0.0000375,+ "input_cache_read": 0.0000375,+ "output": 0.00015+ }+ }+ ]},{"id": "cm7nusn640000tvmzf10z2x65",- "model_name": "gpt-4.5-preview-2025-02-27",- "match_pattern": "(?i)^(gpt-4.5-preview-2025-02-27)$",- "created_at": "2025-02-27T21:26:54.132Z",- "updated_at": "2025-02-27T21:26:54.132Z",- "prices": {- "input": 75e-6,- "input_cached_tokens": 37.5e-6,- "input_cached_text_tokens": 37.5e-6,- "input_cache_read": 37.5e-6,- "output": 150e-6- }+ "modelName": "gpt-4.5-preview-2025-02-27",+ "matchPattern": "(?i)^(gpt-4.5-preview-2025-02-27)$",+ "createdAt": "2025-02-27T21:26:54.132Z",+ "updatedAt": "2025-02-27T21:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cm7nusn640000tvmzf10z2x65_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000075,+ "input_cached_tokens": 0.0000375,+ "input_cached_text_tokens": 0.0000375,+ "input_cache_read": 0.0000375,+ "output": 0.00015+ }+ }+ ]},{"id": "cm7nusn643377tvmzh27m33kl",- "model_name": "gpt-4.1",- "match_pattern": "(?i)^(gpt-4.1)$",- "created_at": "2025-04-15T10:26:54.132Z",- "updated_at": "2025-04-15T10:26:54.132Z",- "prices": {- "input": 2e-6,- "input_cached_tokens": 0.5e-6,- "input_cached_text_tokens": 0.5e-6,- "input_cache_read": 0.5e-6,- "output": 8e-6- },- "tokenizer_config": {+ "modelName": "gpt-4.1",+ "matchPattern": "(?i)^(gpt-4.1)$",+ "createdAt": "2025-04-15T10:26:54.132Z",+ "updatedAt": "2025-04-15T10:26:54.132Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm7nusn643377tvmzh27m33kl_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000002,+ "input_cached_tokens": 5e-7,+ "input_cached_text_tokens": 5e-7,+ "input_cache_read": 5e-7,+ "output": 0.000008+ }+ }+ ]},{"id": "cm7qahw732891bpmzy45r3x70",- "model_name": "gpt-4.1-2025-04-14",- "match_pattern": "(?i)^(gpt-4.1-2025-04-14)$",- "created_at": "2025-04-15T10:26:54.132Z",- "updated_at": "2025-04-15T10:26:54.132Z",- "prices": {- "input": 2e-6,- "input_cached_tokens": 0.5e-6,- "input_cached_text_tokens": 0.5e-6,- "input_cache_read": 0.5e-6,- "output": 8e-6- },- "tokenizer_config": {+ "modelName": "gpt-4.1-2025-04-14",+ "matchPattern": "(?i)^(gpt-4.1-2025-04-14)$",+ "createdAt": "2025-04-15T10:26:54.132Z",+ "updatedAt": "2025-04-15T10:26:54.132Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm7qahw732891bpmzy45r3x70_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000002,+ "input_cached_tokens": 5e-7,+ "input_cached_text_tokens": 5e-7,+ "input_cache_read": 5e-7,+ "output": 0.000008+ }+ }+ ]},{"id": "cm7sglt825463kxnza72p6v81",- "model_name": "gpt-4.1-mini-2025-04-14",- "match_pattern": "(?i)^(gpt-4.1-mini-2025-04-14)$",- "created_at": "2025-04-15T10:26:54.132Z",- "updated_at": "2025-04-15T10:26:54.132Z",- "prices": {- "input": 0.4e-6,- "input_cached_tokens": 0.1e-6,- "input_cached_text_tokens": 0.1e-6,- "input_cache_read": 0.1e-6,- "output": 1.6e-6- },- "tokenizer_config": {+ "modelName": "gpt-4.1-mini-2025-04-14",+ "matchPattern": "(?i)^(gpt-4.1-mini-2025-04-14)$",+ "createdAt": "2025-04-15T10:26:54.132Z",+ "updatedAt": "2025-04-15T10:26:54.132Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm7sglt825463kxnza72p6v81_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 4e-7,+ "input_cached_tokens": 1e-7,+ "input_cached_text_tokens": 1e-7,+ "input_cache_read": 1e-7,+ "output": 0.0000016+ }+ }+ ]},{"id": "cm7vxpz967124dhjtb95w8f92",- "model_name": "gpt-4.1-nano-2025-04-14",- "match_pattern": "(?i)^(gpt-4.1-nano-2025-04-14)$",- "created_at": "2025-04-15T10:26:54.132Z",- "updated_at": "2025-04-15T10:26:54.132Z",- "prices": {- "input": 0.1e-6,- "input_cached_tokens": 0.025e-6,- "input_cached_text_tokens": 0.025e-6,- "input_cache_read": 0.025e-6,- "output": 0.4e-6- },- "tokenizer_config": {+ "modelName": "gpt-4.1-nano-2025-04-14",+ "matchPattern": "(?i)^(gpt-4.1-nano-2025-04-14)$",+ "createdAt": "2025-04-15T10:26:54.132Z",+ "updatedAt": "2025-04-15T10:26:54.132Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm7vxpz967124dhjtb95w8f92_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1e-7,+ "input_cached_tokens": 2.5e-8,+ "input_cached_text_tokens": 2.5e-8,+ "input_cache_read": 2.5e-8,+ "output": 4e-7+ }+ }+ ]},{"id": "cm7wmny967124dhjtb95w8f81",- "model_name": "o3",- "match_pattern": "(?i)^(o3)$",- "created_at": "2025-04-16T23:26:54.132Z",- "updated_at": "2025-06-10T23:26:54.132Z",- "prices": {- "input": 2e-6,- "input_cached_tokens": 0.5e-6,- "input_cache_read": 0.5e-6,- "output": 8e-6,- "output_reasoning_tokens": 8e-6,- "output_reasoning": 8e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o3",+ "matchPattern": "(?i)^(o3)$",+ "createdAt": "2025-04-16T23:26:54.132Z",+ "updatedAt": "2025-06-10T23:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cm7wmny967124dhjtb95w8f81_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000002,+ "input_cached_tokens": 5e-7,+ "input_cache_read": 5e-7,+ "output": 0.000008,+ "output_reasoning_tokens": 0.000008,+ "output_reasoning": 0.000008+ }+ }+ ]},{"id": "cm7wopq3327124dhjtb95w8f81",- "model_name": "o3-2025-04-16",- "match_pattern": "(?i)^(o3-2025-04-16)$",- "created_at": "2025-04-16T23:26:54.132Z",- "updated_at": "2025-06-10T23:26:54.132Z",- "prices": {- "input": 2e-6,- "input_cached_tokens": 0.5e-6,- "input_cache_read": 0.5e-6,- "output": 8e-6,- "output_reasoning_tokens": 8e-6,- "output_reasoning": 8e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o3-2025-04-16",+ "matchPattern": "(?i)^(o3-2025-04-16)$",+ "createdAt": "2025-04-16T23:26:54.132Z",+ "updatedAt": "2025-06-10T23:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cm7wopq3327124dhjtb95w8f81_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000002,+ "input_cached_tokens": 5e-7,+ "input_cache_read": 5e-7,+ "output": 0.000008,+ "output_reasoning_tokens": 0.000008,+ "output_reasoning": 0.000008+ }+ }+ ]},{"id": "cm7wqrs1327124dhjtb95w8f81",- "model_name": "o4-mini",- "match_pattern": "(?i)^(o4-mini)$",- "created_at": "2025-04-16T23:26:54.132Z",- "updated_at": "2025-04-16T23:26:54.132Z",- "prices": {- "input": 1.1e-6,- "input_cached_tokens": 0.275e-6,- "input_cache_read": 0.275e-6,- "output": 4.4e-6,- "output_reasoning_tokens": 4.4e-6,- "output_reasoning": 4.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o4-mini",+ "matchPattern": "(?i)^(o4-mini)$",+ "createdAt": "2025-04-16T23:26:54.132Z",+ "updatedAt": "2025-04-16T23:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cm7wqrs1327124dhjtb95w8f81_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000011,+ "input_cached_tokens": 2.75e-7,+ "input_cache_read": 2.75e-7,+ "output": 0.0000044,+ "output_reasoning_tokens": 0.0000044,+ "output_reasoning": 0.0000044+ }+ }+ ]},{"id": "cm7zqrs1327124dhjtb95w8f82",- "model_name": "o4-mini-2025-04-16",- "match_pattern": "(?i)^(o4-mini-2025-04-16)$",- "created_at": "2025-04-16T23:26:54.132Z",- "updated_at": "2025-04-16T23:26:54.132Z",- "prices": {- "input": 1.1e-6,- "input_cached_tokens": 0.275e-6,- "input_cache_read": 0.275e-6,- "output": 4.4e-6,- "output_reasoning_tokens": 4.4e-6,- "output_reasoning": 4.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null- },- {- "id": "cm7zrrs1327124dhjtb95w8f13",- "model_name": "gemini-2.0-pro-exp",- "match_pattern": "(?i)^(gemini-2.0-pro-exp)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-04-22T10:11:35.241Z",- "updated_at": "2025-04-22T10:11:35.241Z",- "prices": {},- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o4-mini-2025-04-16",+ "matchPattern": "(?i)^(o4-mini-2025-04-16)$",+ "createdAt": "2025-04-16T23:26:54.132Z",+ "updatedAt": "2025-04-16T23:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cm7zqrs1327124dhjtb95w8f82_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.0000011,+ "input_cached_tokens": 2.75e-7,+ "input_cache_read": 2.75e-7,+ "output": 0.0000044,+ "output_reasoning_tokens": 0.0000044,+ "output_reasoning": 0.0000044+ }+ }+ ]},{"id": "cm7zsrs1327124dhjtb95w8f74",- "model_name": "gemini-2.0-flash",- "match_pattern": "(?i)^(gemini-2.0-flash)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-04-22T10:11:35.241Z",- "updated_at": "2025-04-22T10:11:35.241Z",- "prices": {- "input": 0.1e-6,- "output": 0.4e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-2.0-flash",+ "matchPattern": "(?i)^(gemini-2.0-flash)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2025-04-22T10:11:35.241Z",+ "updatedAt": "2025-04-22T10:11:35.241Z",+ "pricingTiers": [+ {+ "id": "cm7zsrs1327124dhjtb95w8f74_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1e-7,+ "output": 4e-7+ }+ }+ ]},{"id": "cm7ztrs1327124dhjtb95w8f19",- "model_name": "gemini-2.0-flash-lite-preview",- "match_pattern": "(?i)^(gemini-2.0-flash-lite-preview)(@[a-zA-Z0-9]+)?$",- "created_at": "2025-04-22T10:11:35.241Z",- "updated_at": "2025-04-22T10:11:35.241Z",- "prices": {- "input": 0.075e-6,- "output": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-2.0-flash-lite-preview",+ "matchPattern": "(?i)^(gemini-2.0-flash-lite-preview)(@[a-zA-Z0-9]+)?$",+ "createdAt": "2025-04-22T10:11:35.241Z",+ "updatedAt": "2025-04-22T10:11:35.241Z",+ "pricingTiers": [+ {+ "id": "cm7ztrs1327124dhjtb95w8f19_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 7.5e-8,+ "output": 3e-7+ }+ }+ ]},{"id": "cm7zxrs1327124dhjtb95w8f45",- "model_name": "gpt-4.1-nano",- "match_pattern": "(?i)^(gpt-4.1-nano)$",- "created_at": "2025-04-22T10:11:35.241Z",- "updated_at": "2025-04-22T10:11:35.241Z",- "prices": {- "input": 0.1e-6,- "input_cached_tokens": 0.025e-6,- "input_cached_text_tokens": 0.025e-6,- "input_cache_read": 0.025e-6,- "output": 0.4e-6- },- "tokenizer_config": {+ "modelName": "gpt-4.1-nano",+ "matchPattern": "(?i)^(gpt-4.1-nano)$",+ "createdAt": "2025-04-22T10:11:35.241Z",+ "updatedAt": "2025-04-22T10:11:35.241Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm7zxrs1327124dhjtb95w8f45_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1e-7,+ "input_cached_tokens": 2.5e-8,+ "input_cached_text_tokens": 2.5e-8,+ "input_cache_read": 2.5e-8,+ "output": 4e-7+ }+ }+ ]},{"id": "cm7zzrs1327124dhjtb95w8p96",- "model_name": "gpt-4.1-mini",- "match_pattern": "(?i)^(gpt-4.1-mini)$",- "created_at": "2025-04-22T10:11:35.241Z",- "updated_at": "2025-04-22T10:11:35.241Z",- "prices": {- "input": 0.4e-6,- "input_cached_tokens": 0.1e-6,- "input_cached_text_tokens": 0.1e-6,- "input_cache_read": 0.1e-6,- "output": 1.6e-6- },- "tokenizer_config": {+ "modelName": "gpt-4.1-mini",+ "matchPattern": "(?i)^(gpt-4.1-mini)$",+ "createdAt": "2025-04-22T10:11:35.241Z",+ "updatedAt": "2025-04-22T10:11:35.241Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cm7zzrs1327124dhjtb95w8p96_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 4e-7,+ "input_cached_tokens": 1e-7,+ "input_cached_text_tokens": 1e-7,+ "input_cache_read": 1e-7,+ "output": 0.0000016+ }+ }+ ]},{"id": "c5qmrqolku82tra3vgdixmys",- "model_name": "claude-sonnet-4-5-20250929",- "match_pattern": "(?i)^(claude-sonnet-4-5-20250929|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-sonnet-4-5-20250929-v1:0|claude-sonnet-4-5-V1@20250929|claude-sonnet-4-5@20250929)$",- "created_at": "2025-09-29T00:00:00.000Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-sonnet-4-5-20250929",+ "matchPattern": "(?i)^(claude-sonnet-4-5-20250929|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-sonnet-4-5-20250929-v1:0|claude-sonnet-4-5-V1@20250929|claude-sonnet-4-5@20250929)$",+ "createdAt": "2025-09-29T00:00:00.000Z",+ "updatedAt": "2025-11-21T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "c5qmrqolku82tra3vgdixmys_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ },+ {+ "id": "00b65240-047b-4722-9590-808edbc2067f",+ "name": "Large Context",+ "isDefault": false,+ "priority": 1,+ "conditions": [+ {+ "usageDetailPattern": "input",+ "operator": "gt",+ "value": 200000,+ "caseSensitive": false+ }+ ],+ "prices": {+ "input": 0.000006,+ "input_tokens": 0.000006,+ "output": 0.0000225,+ "output_tokens": 0.0000225,+ "cache_creation_input_tokens": 0.0000075,+ "input_cache_creation": 0.0000075,+ "cache_read_input_tokens": 6e-7,+ "input_cache_read": 6e-7+ }+ }+ ]},{"id": "cmazmkzlm00000djp1e1qe4k4",- "model_name": "claude-sonnet-4-20250514",- "match_pattern": "(?i)^(claude-sonnet-4-20250514|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-sonnet-4-20250514-v1:0|claude-sonnet-4-V1@20250514|claude-sonnet-4@20250514)$",- "created_at": "2025-05-22T17:09:02.131Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-sonnet-4-20250514",+ "matchPattern": "(?i)^(claude-sonnet-4-20250514|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-sonnet-4-20250514-v1:0|claude-sonnet-4-V1@20250514|claude-sonnet-4@20250514)$",+ "createdAt": "2025-05-22T17:09:02.131Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cmazmkzlm00000djp1e1qe4k4_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cmazmlbnv00010djpazed91va",- "model_name": "claude-sonnet-4-latest",- "match_pattern": "(?i)^(claude-sonnet-4-latest)$",- "created_at": "2025-05-22T17:09:02.131Z",- "updated_at": "2025-05-22T17:09:02.131Z",- "prices": {- "input": 3e-6,- "input_tokens": 3e-6,- "output": 15e-6,- "output_tokens": 15e-6,- "cache_creation_input_tokens": 3.75e-6,- "input_cache_creation": 3.75e-6,- "cache_read_input_tokens": 0.3e-6,- "input_cache_read": 0.3e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-sonnet-4-latest",+ "matchPattern": "(?i)^(claude-sonnet-4-latest)$",+ "createdAt": "2025-05-22T17:09:02.131Z",+ "updatedAt": "2025-05-22T17:09:02.131Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cmazmlbnv00010djpazed91va_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000003,+ "input_tokens": 0.000003,+ "output": 0.000015,+ "output_tokens": 0.000015,+ "cache_creation_input_tokens": 0.00000375,+ "input_cache_creation": 0.00000375,+ "cache_read_input_tokens": 3e-7,+ "input_cache_read": 3e-7+ }+ }+ ]},{"id": "cmazmlm2p00020djpa9s64jw5",- "model_name": "claude-opus-4-20250514",- "match_pattern": "(?i)^(claude-opus-4-20250514|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-20250514-v1:0|claude-opus-4@20250514)$",- "created_at": "2025-05-22T17:09:02.131Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 15e-6,- "input_tokens": 15e-6,- "output": 75e-6,- "output_tokens": 75e-6,- "cache_creation_input_tokens": 18.75e-6,- "input_cache_creation": 18.75e-6,- "cache_read_input_tokens": 1.5e-6,- "input_cache_read": 1.5e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-opus-4-20250514",+ "matchPattern": "(?i)^(claude-opus-4-20250514|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-20250514-v1:0|claude-opus-4@20250514)$",+ "createdAt": "2025-05-22T17:09:02.131Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cmazmlm2p00020djpa9s64jw5_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "input_tokens": 0.000015,+ "output": 0.000075,+ "output_tokens": 0.000075,+ "cache_creation_input_tokens": 0.00001875,+ "input_cache_creation": 0.00001875,+ "cache_read_input_tokens": 0.0000015,+ "input_cache_read": 0.0000015+ }+ }+ ]},{"id": "cmz9x72kq55721pqrs83y4n2bx",- "model_name": "o3-pro",- "match_pattern": "(?i)^(o3-pro)$",- "created_at": "2025-06-10T22:26:54.132Z",- "updated_at": "2025-06-10T22:26:54.132Z",- "prices": {- "input": 20e-6,- "output": 80e-6,- "output_reasoning_tokens": 80e-6,- "output_reasoning": 80e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o3-pro",+ "matchPattern": "(?i)^(o3-pro)$",+ "createdAt": "2025-06-10T22:26:54.132Z",+ "updatedAt": "2025-06-10T22:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cmz9x72kq55721pqrs83y4n2bx_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00002,+ "output": 0.00008,+ "output_reasoning_tokens": 0.00008,+ "output_reasoning": 0.00008+ }+ }+ ]},{"id": "cmz9x72kq55721pqrs83y4n2by",- "model_name": "o3-pro-2025-06-10",- "match_pattern": "(?i)^(o3-pro-2025-06-10)$",- "created_at": "2025-06-10T22:26:54.132Z",- "updated_at": "2025-06-10T22:26:54.132Z",- "prices": {- "input": 20e-6,- "output": 80e-6,- "output_reasoning_tokens": 80e-6,- "output_reasoning": 80e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o3-pro-2025-06-10",+ "matchPattern": "(?i)^(o3-pro-2025-06-10)$",+ "createdAt": "2025-06-10T22:26:54.132Z",+ "updatedAt": "2025-06-10T22:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cmz9x72kq55721pqrs83y4n2by_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00002,+ "output": 0.00008,+ "output_reasoning_tokens": 0.00008,+ "output_reasoning": 0.00008+ }+ }+ ]},{"id": "cmbrold5b000107lbftb9fdoo",- "model_name": "o1-pro",- "match_pattern": "(?i)^(o1-pro)$",- "created_at": "2025-06-10T22:26:54.132Z",- "updated_at": "2025-06-10T22:26:54.132Z",- "prices": {- "input": 150e-6,- "output": 600e-6,- "output_reasoning_tokens": 600e-6,- "output_reasoning": 600e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-pro",+ "matchPattern": "(?i)^(o1-pro)$",+ "createdAt": "2025-06-10T22:26:54.132Z",+ "updatedAt": "2025-06-10T22:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cmbrold5b000107lbftb9fdoo_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00015,+ "output": 0.0006,+ "output_reasoning_tokens": 0.0006,+ "output_reasoning": 0.0006+ }+ }+ ]},{"id": "cmbrolpax000207lb3xkedysz",- "model_name": "o1-pro-2025-03-19",- "match_pattern": "(?i)^(o1-pro-2025-03-19)$",- "created_at": "2025-06-10T22:26:54.132Z",- "updated_at": "2025-06-10T22:26:54.132Z",- "prices": {- "input": 150e-6,- "output": 600e-6,- "output_reasoning_tokens": 600e-6,- "output_reasoning": 600e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "o1-pro-2025-03-19",+ "matchPattern": "(?i)^(o1-pro-2025-03-19)$",+ "createdAt": "2025-06-10T22:26:54.132Z",+ "updatedAt": "2025-06-10T22:26:54.132Z",+ "pricingTiers": [+ {+ "id": "cmbrolpax000207lb3xkedysz_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00015,+ "output": 0.0006,+ "output_reasoning_tokens": 0.0006,+ "output_reasoning": 0.0006+ }+ }+ ]},{"id": "cmcnjkfwn000107l43bf5e8ax",- "model_name": "gemini-2.5-flash",- "match_pattern": "(?i)^(gemini-2.5-flash)$",- "created_at": "2025-07-03T13:44:06.964Z",- "updated_at": "2025-11-14T13:15:31.034Z",- "prices": {- "input": 0.3e-6,- "input_modality_1": 0.3e-6,- "prompt_token_count": 0.3e-6,- "promptTokenCount": 0.3e-6,- "input_cached_tokens": 0.03e-6,- "cached_content_token_count": 0.03e-6,- "output": 2.5e-6,- "output_modality_1": 2.5e-6,- "candidates_token_count": 2.5e-6,- "candidatesTokenCount": 2.5e-6,- "thoughtsTokenCount": 2.5e-6,- "thoughts_token_count": 2.5e-6,- "output_reasoning": 2.5e-6,- "input_audio_tokens": 1e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-2.5-flash",+ "matchPattern": "(?i)^(gemini-2.5-flash)$",+ "createdAt": "2025-07-03T13:44:06.964Z",+ "updatedAt": "2025-11-14T13:15:31.034Z",+ "pricingTiers": [+ {+ "id": "cmcnjkfwn000107l43bf5e8ax_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 3e-7,+ "input_modality_1": 3e-7,+ "prompt_token_count": 3e-7,+ "promptTokenCount": 3e-7,+ "input_cached_tokens": 3e-8,+ "cached_content_token_count": 3e-8,+ "output": 0.0000025,+ "output_modality_1": 0.0000025,+ "candidates_token_count": 0.0000025,+ "candidatesTokenCount": 0.0000025,+ "thoughtsTokenCount": 0.0000025,+ "thoughts_token_count": 0.0000025,+ "output_reasoning": 0.0000025,+ "input_audio_tokens": 0.000001+ }+ }+ ]},{"id": "cmcnjkrfa000207l4fpnh5mnv",- "model_name": "gemini-2.5-flash-lite",- "match_pattern": "(?i)^(gemini-2.5-flash-lite)$",- "created_at": "2025-07-03T13:44:06.964Z",- "updated_at": "2025-11-14T13:15:31.034Z",- "prices": {- "input": 0.1e-6,- "input_modality_1": 0.1e-6,- "prompt_token_count": 0.1e-6,- "promptTokenCount": 0.1e-6,- "input_cached_tokens": 0.025e-6,- "cached_content_token_count": 0.025e-6,- "output": 0.4e-6,- "output_modality_1": 0.4e-6,- "candidates_token_count": 0.4e-6,- "candidatesTokenCount": 0.4e-6,- "thoughtsTokenCount": 0.4e-6,- "thoughts_token_count": 0.4e-6,- "output_reasoning": 0.4e-6,- "input_audio_tokens": 0.5e-6- },- "tokenizer_config": null,- "tokenizer_id": null+ "modelName": "gemini-2.5-flash-lite",+ "matchPattern": "(?i)^(gemini-2.5-flash-lite)$",+ "createdAt": "2025-07-03T13:44:06.964Z",+ "updatedAt": "2025-11-14T13:15:31.034Z",+ "pricingTiers": [+ {+ "id": "cmcnjkrfa000207l4fpnh5mnv_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1e-7,+ "input_modality_1": 1e-7,+ "prompt_token_count": 1e-7,+ "promptTokenCount": 1e-7,+ "input_cached_tokens": 2.5e-8,+ "cached_content_token_count": 2.5e-8,+ "output": 4e-7,+ "output_modality_1": 4e-7,+ "candidates_token_count": 4e-7,+ "candidatesTokenCount": 4e-7,+ "thoughtsTokenCount": 4e-7,+ "thoughts_token_count": 4e-7,+ "output_reasoning": 4e-7,+ "input_audio_tokens": 5e-7+ }+ }+ ]},{"id": "cmdysde5w0000rkmzbc1g5au3",- "model_name": "claude-opus-4-1-20250805",- "match_pattern": "(?i)^(claude-opus-4-1-20250805|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-1-20250805-v1:0|claude-opus-4-1@20250805)$",- "created_at": "2025-08-05T15:00:00.000Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 15e-6,- "input_tokens": 15e-6,- "output": 75e-6,- "output_tokens": 75e-6,- "cache_creation_input_tokens": 18.75e-6,- "input_cache_creation": 18.75e-6,- "cache_read_input_tokens": 1.5e-6,- "input_cache_read": 1.5e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-opus-4-1-20250805",+ "matchPattern": "(?i)^(claude-opus-4-1-20250805|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-1-20250805-v1:0|claude-opus-4-1@20250805)$",+ "createdAt": "2025-08-05T15:00:00.000Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cmdysde5w0000rkmzbc1g5au3_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "input_tokens": 0.000015,+ "output": 0.000075,+ "output_tokens": 0.000075,+ "cache_creation_input_tokens": 0.00001875,+ "input_cache_creation": 0.00001875,+ "cache_read_input_tokens": 0.0000015,+ "input_cache_read": 0.0000015+ }+ }+ ]},{"id": "38c3822a-09a3-457b-b200-2c6f17f7cf2f",- "model_name": "gpt-5",- "match_pattern": "(?i)^(gpt-5)$",- "created_at": "2025-08-07T16:00:00.000Z",- "updated_at": "2025-08-07T16:00:00.000Z",- "prices": {- "input": 1.25e-6,- "input_cached_tokens": 0.125e-6,- "output": 10.0e-6,- "input_cache_read": 0.125e-6,- "output_reasoning_tokens": 10e-6,- "output_reasoning": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-5",+ "matchPattern": "(?i)^(gpt-5)$",+ "createdAt": "2025-08-07T16:00:00.000Z",+ "updatedAt": "2025-08-07T16:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "38c3822a-09a3-457b-b200-2c6f17f7cf2f_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000125,+ "input_cached_tokens": 1.25e-7,+ "output": 0.00001,+ "input_cache_read": 1.25e-7,+ "output_reasoning_tokens": 0.00001,+ "output_reasoning": 0.00001+ }+ }+ ]},{"id": "12543803-2d5f-4189-addc-821ad71c8b55",- "model_name": "gpt-5-2025-08-07",- "match_pattern": "(?i)^(gpt-5-2025-08-07)$",- "created_at": "2025-08-11T08:00:00.000Z",- "updated_at": "2025-08-11T08:00:00.000Z",- "prices": {- "input": 1.25e-6,- "input_cached_tokens": 0.125e-6,- "output": 10.0e-6,- "input_cache_read": 0.125e-6,- "output_reasoning_tokens": 10e-6,- "output_reasoning": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-2025-08-07",+ "matchPattern": "(?i)^(gpt-5-2025-08-07)$",+ "createdAt": "2025-08-11T08:00:00.000Z",+ "updatedAt": "2025-08-11T08:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "12543803-2d5f-4189-addc-821ad71c8b55_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000125,+ "input_cached_tokens": 1.25e-7,+ "output": 0.00001,+ "input_cache_read": 1.25e-7,+ "output_reasoning_tokens": 0.00001,+ "output_reasoning": 0.00001+ }+ }+ ]},{"id": "3d6a975a-a42d-4ea2-a3ec-4ae567d5a364",- "model_name": "gpt-5-mini",- "match_pattern": "(?i)^(gpt-5-mini)$",- "created_at": "2025-08-07T16:00:00.000Z",- "updated_at": "2025-08-07T16:00:00.000Z",- "prices": {- "input": 0.25e-6,- "input_cached_tokens": 0.025e-6,- "output": 2.0e-6,- "input_cache_read": 0.025e-6,- "output_reasoning_tokens": 2e-6,- "output_reasoning": 2e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-mini",+ "matchPattern": "(?i)^(gpt-5-mini)$",+ "createdAt": "2025-08-07T16:00:00.000Z",+ "updatedAt": "2025-08-07T16:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "3d6a975a-a42d-4ea2-a3ec-4ae567d5a364_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "input_cached_tokens": 2.5e-8,+ "output": 0.000002,+ "input_cache_read": 2.5e-8,+ "output_reasoning_tokens": 0.000002,+ "output_reasoning": 0.000002+ }+ }+ ]},{"id": "03b83894-7172-4e1e-8e8b-37d792484efd",- "model_name": "gpt-5-mini-2025-08-07",- "match_pattern": "(?i)^(gpt-5-mini-2025-08-07)$",- "created_at": "2025-08-11T08:00:00.000Z",- "updated_at": "2025-08-11T08:00:00.000Z",- "prices": {- "input": 0.25e-6,- "input_cached_tokens": 0.025e-6,- "output": 2.0e-6,- "input_cache_read": 0.025e-6,- "output_reasoning_tokens": 2e-6,- "output_reasoning": 2e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-mini-2025-08-07",+ "matchPattern": "(?i)^(gpt-5-mini-2025-08-07)$",+ "createdAt": "2025-08-11T08:00:00.000Z",+ "updatedAt": "2025-08-11T08:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "03b83894-7172-4e1e-8e8b-37d792484efd_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2.5e-7,+ "input_cached_tokens": 2.5e-8,+ "output": 0.000002,+ "input_cache_read": 2.5e-8,+ "output_reasoning_tokens": 0.000002,+ "output_reasoning": 0.000002+ }+ }+ ]},{"id": "f0b40234-b694-4c40-9494-7b0efd860fb9",- "model_name": "gpt-5-nano",- "match_pattern": "(?i)^(gpt-5-nano)$",- "created_at": "2025-08-07T16:00:00.000Z",- "updated_at": "2025-08-07T16:00:00.000Z",- "prices": {- "input": 0.05e-6,- "input_cached_tokens": 0.005e-6,- "output": 0.4e-6,- "input_cache_read": 0.005e-6,- "output_reasoning_tokens": 0.4e-6,- "output_reasoning": 0.4e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-nano",+ "matchPattern": "(?i)^(gpt-5-nano)$",+ "createdAt": "2025-08-07T16:00:00.000Z",+ "updatedAt": "2025-08-07T16:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "f0b40234-b694-4c40-9494-7b0efd860fb9_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 5e-8,+ "input_cached_tokens": 5e-9,+ "output": 4e-7,+ "input_cache_read": 5e-9,+ "output_reasoning_tokens": 4e-7,+ "output_reasoning": 4e-7+ }+ }+ ]},{"id": "4489fde4-a594-4011-948b-526989300cd3",- "model_name": "gpt-5-nano-2025-08-07",- "match_pattern": "(?i)^(gpt-5-nano-2025-08-07)$",- "created_at": "2025-08-11T08:00:00.000Z",- "updated_at": "2025-08-11T08:00:00.000Z",- "prices": {- "input": 0.05e-6,- "input_cached_tokens": 0.005e-6,- "output": 0.4e-6,- "input_cache_read": 0.005e-6,- "output_reasoning_tokens": 0.4e-6,- "output_reasoning": 0.4e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-nano-2025-08-07",+ "matchPattern": "(?i)^(gpt-5-nano-2025-08-07)$",+ "createdAt": "2025-08-11T08:00:00.000Z",+ "updatedAt": "2025-08-11T08:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "4489fde4-a594-4011-948b-526989300cd3_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 5e-8,+ "input_cached_tokens": 5e-9,+ "output": 4e-7,+ "input_cache_read": 5e-9,+ "output_reasoning_tokens": 4e-7,+ "output_reasoning": 4e-7+ }+ }+ ]},{"id": "8ba72ee3-ebe8-4110-a614-bf81094447e5",- "model_name": "gpt-5-chat-latest",- "match_pattern": "(?i)^(gpt-5-chat-latest)$",- "created_at": "2025-08-07T16:00:00.000Z",- "updated_at": "2025-08-07T16:00:00.000Z",- "prices": {- "input": 1.25e-6,- "input_cached_tokens": 0.125e-6,- "output": 10.0e-6,- "input_cache_read": 0.125e-6,- "output_reasoning_tokens": 10e-6,- "output_reasoning": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-chat-latest",+ "matchPattern": "(?i)^(gpt-5-chat-latest)$",+ "createdAt": "2025-08-07T16:00:00.000Z",+ "updatedAt": "2025-08-07T16:00:00.000Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "8ba72ee3-ebe8-4110-a614-bf81094447e5_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000125,+ "input_cached_tokens": 1.25e-7,+ "output": 0.00001,+ "input_cache_read": 1.25e-7,+ "output_reasoning_tokens": 0.00001,+ "output_reasoning": 0.00001+ }+ }+ ]},{"id": "cmgg9zco3000004l258um9xk8",- "model_name": "gpt-5-pro",- "match_pattern": "(?i)^(gpt-5-pro)$",- "created_at": "2025-10-07T08:03:54.727Z",- "updated_at": "2025-10-07T08:03:54.727Z",- "prices": {- "input": 15e-6,- "output": 120e-6,- "output_reasoning_tokens": 120e-6,- "output_reasoning": 120e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-pro",+ "matchPattern": "(?i)^(gpt-5-pro)$",+ "createdAt": "2025-10-07T08:03:54.727Z",+ "updatedAt": "2025-10-07T08:03:54.727Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cmgg9zco3000004l258um9xk8_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "output": 0.00012,+ "output_reasoning_tokens": 0.00012,+ "output_reasoning": 0.00012+ }+ }+ ]},{"id": "cmgga0vh9000104l22qe4fes4",- "model_name": "gpt-5-pro-2025-10-06",- "match_pattern": "(?i)^(gpt-5-pro-2025-10-06)$",- "created_at": "2025-10-07T08:03:54.727Z",- "updated_at": "2025-10-07T08:03:54.727Z",- "prices": {- "input": 15e-6,- "output": 120e-6,- "output_reasoning_tokens": 120e-6,- "output_reasoning": 120e-6- },- "tokenizer_config": {+ "modelName": "gpt-5-pro-2025-10-06",+ "matchPattern": "(?i)^(gpt-5-pro-2025-10-06)$",+ "createdAt": "2025-10-07T08:03:54.727Z",+ "updatedAt": "2025-10-07T08:03:54.727Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cmgga0vh9000104l22qe4fes4_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000015,+ "output": 0.00012,+ "output_reasoning_tokens": 0.00012,+ "output_reasoning": 0.00012+ }+ }+ ]},{"id": "cmgt5gnkv000104jx171tbq4e",- "model_name": "claude-haiku-4-5-20251001",- "match_pattern": "(?i)^(claude-haiku-4-5-20251001|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-haiku-4-5-20251001-v1:0|claude-4-5-haiku@20251001)$",- "created_at": "2025-10-16T08:20:44.558Z",- "updated_at": "2025-11-18T00:00:00.000Z",- "prices": {- "input": 1e-6,- "input_tokens": 1e-6,- "output": 5e-6,- "output_tokens": 5e-6,- "cache_creation_input_tokens": 1.25e-6,- "input_cache_creation": 1.25e-6,- "cache_read_input_tokens": 0.1e-6,- "input_cache_read": 0.1e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "modelName": "claude-haiku-4-5-20251001",+ "matchPattern": "(?i)^(claude-haiku-4-5-20251001|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-haiku-4-5-20251001-v1:0|claude-4-5-haiku@20251001)$",+ "createdAt": "2025-10-16T08:20:44.558Z",+ "updatedAt": "2025-11-18T00:00:00.000Z",+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cmgt5gnkv000104jx171tbq4e_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.000001,+ "input_tokens": 0.000001,+ "output": 0.000005,+ "output_tokens": 0.000005,+ "cache_creation_input_tokens": 0.00000125,+ "input_cache_creation": 0.00000125,+ "cache_read_input_tokens": 1e-7,+ "input_cache_read": 1e-7+ }+ }+ ]},{"id": "cmhymgpym000d04ih34rndvhr",- "model_name": "gpt-5.1",- "match_pattern": "(?i)^(gpt-5.1)$",- "created_at": "2025-11-14T08:57:23.481Z",- "updated_at": "2025-11-14T08:57:23.481Z",- "prices": {- "input": 1.25e-6,- "input_cached_tokens": 0.125e-6,- "output": 10.0e-6,- "input_cache_read": 0.125e-6,- "output_reasoning_tokens": 10e-6,- "output_reasoning": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-5.1",+ "matchPattern": "(?i)^(gpt-5.1)$",+ "createdAt": "2025-11-14T08:57:23.481Z",+ "updatedAt": "2025-11-14T08:57:23.481Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cmhymgpym000d04ih34rndvhr_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000125,+ "input_cached_tokens": 1.25e-7,+ "output": 0.00001,+ "input_cache_read": 1.25e-7,+ "output_reasoning_tokens": 0.00001,+ "output_reasoning": 0.00001+ }+ }+ ]},{"id": "cmhymgxiw000e04ihh9pw12ef",- "model_name": "gpt-5.1-2025-11-13",- "match_pattern": "(?i)^(gpt-5.1-2025-11-13)$",- "created_at": "2025-11-14T08:57:23.481Z",- "updated_at": "2025-11-14T08:57:23.481Z",- "prices": {- "input": 1.25e-6,- "input_cached_tokens": 0.125e-6,- "output": 10.0e-6,- "input_cache_read": 0.125e-6,- "output_reasoning_tokens": 10e-6,- "output_reasoning": 10e-6- },- "tokenizer_config": {+ "modelName": "gpt-5.1-2025-11-13",+ "matchPattern": "(?i)^(gpt-5.1-2025-11-13)$",+ "createdAt": "2025-11-14T08:57:23.481Z",+ "updatedAt": "2025-11-14T08:57:23.481Z",+ "tokenizerConfig": {"tokensPerName": 1,"tokenizerModel": "gpt-4","tokensPerMessage": 3},- "tokenizer_id": "openai"- },- {- "id": "cmdysde5w0000rkmzbc1g5au3",- "model_name": "claude-opus-4-5-20251101",- "match_pattern": "(?i)^(claude-opus-4-5-20251101|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-5-20251101-v1:0|claude-opus-4-5@20251101)$",- "created_at": "2025-11-24T20:53:27.571Z",- "updated_at": "2025-11-24T20:53:27.571Z",- "prices": {- "input": 5e-6,- "input_tokens": 5e-6,- "output": 25e-6,- "output_tokens": 25e-6,- "cache_creation_input_tokens": 6.25e-6,- "input_cache_creation": 6.25e-6,- "cache_read_input_tokens": 0.5e-6,- "input_cache_read": 0.5e-6- },- "tokenizer_config": null,- "tokenizer_id": "claude"+ "tokenizerId": "openai",+ "pricingTiers": [+ {+ "id": "cmhymgxiw000e04ihh9pw12ef_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 0.00000125,+ "input_cached_tokens": 1.25e-7,+ "output": 0.00001,+ "input_cache_read": 1.25e-7,+ "output_reasoning_tokens": 0.00001,+ "output_reasoning": 0.00001+ }+ }+ ]+ },+ {+ "id": "cmieupdva000004l541kwae70",+ "modelName": "claude-opus-4-5-20251101",+ "matchPattern": "(?i)^(claude-opus-4-5-20251101|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-5-20251101-v1:0|claude-opus-4-5@20251101)$",+ "createdAt": "2025-11-24T20:53:27.571Z",+ "updatedAt": "2025-11-24T20:53:27.571Z",+ "tokenizerConfig": null,+ "tokenizerId": "claude",+ "pricingTiers": [+ {+ "id": "cmieupdva000004l541kwae70_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 5e-6,+ "input_tokens": 5e-6,+ "output": 25e-6,+ "output_tokens": 25e-6,+ "cache_creation_input_tokens": 6.25e-6,+ "input_cache_creation": 6.25e-6,+ "cache_read_input_tokens": 0.5e-6,+ "input_cache_read": 0.5e-6+ }+ }+ ]+ },+ {+ "id": "cmig1hb7i000104l72qrzgc6h",+ "modelName": "gemini-2.5-pro",+ "matchPattern": "(?i)^(gemini-2.5-pro)$",+ "createdAt": "2025-11-26T13:27:53.545Z",+ "updatedAt": "2025-11-26T13:27:53.545Z",+ "pricingTiers": [+ {+ "id": "cmig1hb7i000104l72qrzgc6h_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 1.25e-6,+ "input_modality_1": 1.25e-6,+ "prompt_token_count": 1.25e-6,+ "promptTokenCount": 1.25e-6,+ "input_cached_tokens": 0.125e-6,+ "cached_content_token_count": 0.125e-6,+ "output": 10e-6,+ "output_modality_1": 10e-6,+ "candidates_token_count": 10e-6,+ "candidatesTokenCount": 10e-6,+ "thoughtsTokenCount": 10e-6,+ "thoughts_token_count": 10e-6,+ "output_reasoning": 10e-6+ }+ },+ {+ "id": "bcf39e8f-9969-455f-be9a-541a00256092",+ "name": "Large Context",+ "isDefault": false,+ "priority": 1,+ "conditions": [+ {+ "usageDetailPattern": "(input|prompt|cached)",+ "operator": "gt",+ "value": 200000,+ "caseSensitive": false+ }+ ],+ "prices": {+ "input": 2.5e-6,+ "input_modality_1": 2.5e-6,+ "prompt_token_count": 2.5e-6,+ "promptTokenCount": 2.5e-6,+ "input_cached_tokens": 0.25e-6,+ "cached_content_token_count": 0.25e-6,+ "output": 15e-6,+ "output_modality_1": 15e-6,+ "candidates_token_count": 15e-6,+ "candidatesTokenCount": 15e-6,+ "thoughtsTokenCount": 15e-6,+ "thoughts_token_count": 15e-6,+ "output_reasoning": 15e-6+ }+ }+ ]+ },+ {+ "id": "cmig1wmep000404l7fh6q5uog",+ "modelName": "gemini-3-pro-preview",+ "matchPattern": "(?i)^(gemini-3-pro-preview)$",+ "createdAt": "2025-11-26T13:27:53.545Z",+ "updatedAt": "2025-11-26T13:27:53.545Z",+ "pricingTiers": [+ {+ "id": "cmig1wmep000404l7fh6q5uog_tier_default",+ "name": "Standard",+ "isDefault": true,+ "priority": 0,+ "conditions": [],+ "prices": {+ "input": 2e-6,+ "input_modality_1": 2e-6,+ "prompt_token_count": 2e-6,+ "promptTokenCount": 2e-6,+ "input_cached_tokens": 0.2e-6,+ "cached_content_token_count": 0.2e-6,+ "output": 12e-6,+ "output_modality_1": 12e-6,+ "candidates_token_count": 12e-6,+ "candidatesTokenCount": 12e-6,+ "thoughtsTokenCount": 12e-6,+ "thoughts_token_count": 12e-6,+ "output_reasoning": 12e-6+ }+ },+ {+ "id": "4da930c8-7146-4e27-b66c-b62f2c2ec357",+ "name": "Large Context",+ "isDefault": false,+ "priority": 1,+ "conditions": [+ {+ "usageDetailPattern": "(input|prompt|cached)",+ "operator": "gt",+ "value": 200000,+ "caseSensitive": false+ }+ ],+ "prices": {+ "input": 4e-6,+ "input_modality_1": 4e-6,+ "prompt_token_count": 4e-6,+ "promptTokenCount": 4e-6,+ "input_cached_tokens": 0.4e-6,+ "cached_content_token_count": 0.4e-6,+ "output": 18e-6,+ "output_modality_1": 18e-6,+ "candidates_token_count": 18e-6,+ "candidatesTokenCount": 18e-6,+ "thoughtsTokenCount": 18e-6,+ "thoughts_token_count": 18e-6,+ "output_reasoning": 18e-6+ }+ }+ ]}]diff --git a/worker/src/scripts/convertDefaultModelPricesToTiers.ts b/worker/src/scripts/convertDefaultModelPricesToTiers.tsnew file mode 100644index 0000000000..5158eb85db--- /dev/null+++ b/worker/src/scripts/convertDefaultModelPricesToTiers.ts@@ -0,0 +1,167 @@+#!/usr/bin/env ts-node+/**+ * Utility script to convert old default-model-prices.json format to new tiered pricing format.+ *+ * OLD FORMAT:+ * {+ * "id": "model_id",+ * "model_name": "gpt-4o",+ * "prices": { "input": 2.5e-6, "output": 10e-6 }+ * }+ *+ * NEW FORMAT:+ * {+ * "id": "model_id",+ * "model_name": "gpt-4o",+ * "pricing_tiers": [+ * {+ * "id": "tier_uuid",+ * "name": "Standard",+ * "is_default": true,+ * "priority": 0,+ * "conditions": [],+ * "prices": { "input": 2.5e-6, "output": 10e-6 }+ * }+ * ]+ * }+ *+ * USAGE:+ * pnpm --filter=worker exec ts-node src/scripts/convertDefaultModelPricesToTiers.ts+ */++import * as fs from "fs";+import * as path from "path";+import { z } from "zod/v4";++// OLD SCHEMA+const OldDefaultModelPriceSchema = z.object({+ id: z.string(),+ model_name: z.string(),+ match_pattern: z.string(),+ created_at: z.coerce.date(),+ updated_at: z.coerce.date(),+ prices: z.record(z.string(), z.number()),+ tokenizer_config: z+ .record(z.string(), z.union([z.string(), z.number()]))+ .nullish(),+ tokenizer_id: z.string().nullish(),+});++// NEW SCHEMA+const PricingTierSchema = z.object({+ id: z.string(),+ name: z.string(),+ is_default: z.boolean(),+ priority: z.number().int(),+ conditions: z.array(+ z.object({+ usageDetailPattern: z.string(),+ operator: z.enum(["gt", "gte", "lt", "lte", "eq", "neq"]),+ value: z.number(),+ caseSensitive: z.boolean(),+ }),+ ),+ prices: z.record(z.string(), z.number()),+});++const NewDefaultModelPriceSchema = z.object({+ id: z.string(),+ model_name: z.string(),+ match_pattern: z.string(),+ created_at: z.string(), // ISO string in JSON+ updated_at: z.string(), // ISO string in JSON+ tokenizer_config: z+ .record(z.string(), z.union([z.string(), z.number()]))+ .nullish(),+ tokenizer_id: z.string().nullish(),+ pricing_tiers: z.array(PricingTierSchema),+});++type OldModelPrice = z.infer<typeof OldDefaultModelPriceSchema>;+type NewModelPrice = z.infer<typeof NewDefaultModelPriceSchema>;++/**+ * Convert old format to new format+ * Uses deterministic default tier IDs: {model_id}_tier_default+ */+function convertToTieredFormat(oldModel: OldModelPrice): NewModelPrice {+ // Create deterministic default tier ID - MATCHES MIGRATION LOGIC+ const defaultTierId = `${oldModel.id}_tier_default`;++ // Create a single default tier from the old prices+ const defaultTier = {+ id: defaultTierId, // Deterministic!+ name: "Standard",+ is_default: true,+ priority: 0,+ conditions: [],+ prices: oldModel.prices,+ };++ return {+ id: oldModel.id,+ model_name: oldModel.model_name,+ match_pattern: oldModel.match_pattern,+ created_at: oldModel.created_at.toISOString(),+ updated_at: oldModel.updated_at.toISOString(),+ tokenizer_config: oldModel.tokenizer_config ?? undefined,+ tokenizer_id: oldModel.tokenizer_id ?? undefined,+ pricing_tiers: [defaultTier],+ };+}++/**+ * Main conversion function+ */+async function convertFile() {+ const inputPath = path.join(+ __dirname,+ "../constants/default-model-prices.json",+ );+ const outputPath = path.join(+ __dirname,+ "../constants/default-model-prices-new.json",+ );+ const backupPath = path.join(+ __dirname,+ "../constants/default-model-prices.backup.json",+ );++ console.log("Reading old format from:", inputPath);++ // Read and parse old format+ const oldData = JSON.parse(fs.readFileSync(inputPath, "utf-8"));+ const oldModels = z.array(OldDefaultModelPriceSchema).parse(oldData);++ console.log(`Found ${oldModels.length} models to convert`);++ // Convert to new format+ const newModels: NewModelPrice[] = oldModels.map(convertToTieredFormat);++ // Validate new format+ z.array(NewDefaultModelPriceSchema).parse(newModels);++ // Create backup of old file+ fs.copyFileSync(inputPath, backupPath);+ console.log("Backup created at:", backupPath);++ // Write new format+ fs.writeFileSync(outputPath, JSON.stringify(newModels, null, 2));+ console.log("New format written to:", outputPath);++ // Show sample conversion+ console.log("\n=== SAMPLE CONVERSION ===");+ console.log("OLD:", JSON.stringify(oldModels[0], null, 2));+ console.log("\nNEW:", JSON.stringify(newModels[0], null, 2));++ console.log("\n✅ Conversion complete!");+ console.log(+ `\nTo replace the original file, run:\n mv ${outputPath} ${inputPath}`,+ );+}++// Run conversion+convertFile().catch((error) => {+ console.error("❌ Conversion failed:", error);+ process.exit(1);+});diff --git a/worker/src/scripts/upsertDefaultModelPrices.ts b/worker/src/scripts/upsertDefaultModelPrices.tsindex f38a505952..84bfcab109 100644--- a/worker/src/scripts/upsertDefaultModelPrices.ts+++ b/worker/src/scripts/upsertDefaultModelPrices.ts@@ -1,52 +1,86 @@import { z } from "zod/v4";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, PrismaClient } from "@langfuse/shared/src/db";import defaultModelPrices from "../constants/default-model-prices.json";import { clearFullModelCache, logger } from "@langfuse/shared/src/server";+import {+ PricingTierConditionSchema,+ validatePricingTiers,+} from "@langfuse/shared";-const DefaultModelPriceSchema = z.object({+export const PricingTierSchema = z.object({id: z.string(),- model_name: z.string(),- match_pattern: z.string(),- created_at: z.coerce.date(),- updated_at: z.coerce.date(),+ name: z.string(),+ isDefault: z.boolean(),+ priority: z.number().int(),+ conditions: z.array(PricingTierConditionSchema),prices: z.record(z.string(), z.number()),- tokenizer_config: z- .record(z.string(), z.union([z.string(), z.number()]))- .nullish(),- tokenizer_id: z.string().nullish(),});-type DefaultModelPrice = z.infer<typeof DefaultModelPriceSchema>;-const ExistingModelPriceSchema = z.object({+export const DefaultModelPriceSchema = z+ .object({+ id: z.string(),+ modelName: z.string(),+ matchPattern: z.string(),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ pricingTiers: z.array(PricingTierSchema),+ tokenizerConfig: z+ .record(z.string(), z.union([z.string(), z.number()]))+ .nullish(),+ tokenizerId: z.string().nullish(),+ })+ .superRefine((data, ctx) => {+ const tierValidation = validatePricingTiers(data.pricingTiers);++ if (!tierValidation.valid) {+ ctx.addIssue({+ message: tierValidation.error,+ });+ }++ const defaultTiers = data.pricingTiers.filter((t) => t.isDefault);++ if (defaultTiers.length !== 1) {+ ctx.addIssue({+ message:+ "Each model must have exactly one default pricing tier (isDefault: true)",+ });+ }+ });++export type DefaultModelPrice = z.infer<typeof DefaultModelPriceSchema>;+export type PricingTier = z.infer<typeof PricingTierSchema>;++const ExistingModelTierSchema = z.object({modelId: z.string(),modelUpdatedAt: z.coerce.date(),- usageType: z.string(),- price: z.coerce.number(),+ tierId: z.string(),+ tierName: z.string(),+ tierPriority: z.number(),+ tierIsDefault: z.boolean(),});/**- * Upserts default model prices into the database into models and prices tables.+ * Upserts default model prices into the database with pricing tiers.** This function performs the following operations:- * 1. Fetches existing default models from the database (single query, not in transaction).- * 2. Parses and validates the default model prices from the JSON file in the constants folder.+ * 1. Fetches existing default models and their tiers from the database.+ * 2. Parses and validates the default model prices from the JSON file.* 3. Processes the default model prices in batches.** Transaction behavior:* - Each batch is processed in parallel- * - Within a batch, each model upsert and corresponding price upsert are in the same transaction+ * - Within a batch, each model upsert, tier upserts, and price upserts are in the same transaction** Batching:- * - Default model prices are processed in batches of 10 to optimize performance / not overwhelm the database+ * - Default model prices are processed in batches of 10 to optimize performance** Server start-time overhead:- * - If all models are up-to-date and 'force' is false, only the initial query to fetch- * existing model update dates will be executed.+ * - If all models are up-to-date and 'force' is false, only the initial query will be executed.** @param force - If true, updates all models regardless of their last update time.* If false, only updates models that are outdated.*/-export const upsertDefaultModelPrices = async (force = false) => {const startTime = Date.now();try {@@ -57,47 +91,53 @@ export const upsertDefaultModelPrices = async (force = false) => {.array(DefaultModelPriceSchema).parse(defaultModelPrices);- const existingModelPricesQuery = await prisma.$queryRaw`+ // Fetch existing models with their tiers+ const existingModelsQuery = await prisma.$queryRaw`SELECTm.id AS "modelId",- m.updated_at "modelUpdatedAt",- p.usage_type "usageType",- p.price "price"+ m.updated_at AS "modelUpdatedAt",+ t.id AS "tierId",+ t.name AS "tierName",+ t.priority AS "tierPriority",+ t.is_default AS "tierIsDefault"FROM- prices p- LEFT JOIN models m ON m.id = p.model_id+ models m+ INNER JOIN pricing_tiers t ON t.model_id = m.idWHEREm.project_id IS NULL`;- const existingModelPrices = ExistingModelPriceSchema.array().parse(- existingModelPricesQuery,- );+ const existingModels =+ ExistingModelTierSchema.array().parse(existingModelsQuery);- // Store in a map for O(1) lookup.- const existingModelPricesMap = new Map<+ // Build map of existing models with their tiers+ const existingModelsMap = new Map<string,- { updatedAt: Date; prices: Record<string, number> }- >(- existingModelPrices.map((em) => [- em.modelId,- {- updatedAt: em.modelUpdatedAt,- prices: {},- },- ]),- );+ {+ updatedAt: Date;+ tiers: Array<{+ id: string;+ name: string;+ priority: number;+ isDefault: boolean;+ }>;+ }+ >();- for (const existingModelPrice of existingModelPrices) {- const mapRecord = existingModelPricesMap.get(existingModelPrice.modelId);- if (mapRecord) {- mapRecord.prices[existingModelPrice.usageType] =- existingModelPrice.price;- } else {- logger.error(- `Existing model price for ${existingModelPrice.modelId} not found in map.`,- );+ for (const row of existingModels) {+ if (!existingModelsMap.has(row.modelId)) {+ existingModelsMap.set(row.modelId, {+ updatedAt: row.modelUpdatedAt,+ tiers: [],+ });}++ existingModelsMap.get(row.modelId)!.tiers.push({+ id: row.tierId,+ name: row.tierName,+ priority: row.tierPriority,+ isDefault: row.tierIsDefault,+ });}// Upsert in batches@@ -115,105 +155,38 @@ export const upsertDefaultModelPrices = async (force = false) => {const promises = [];for (const defaultModelPrice of batch) {- const existingModelUpdateDate = existingModelPricesMap.get(- defaultModelPrice.id,- );+ const existingModel = existingModelsMap.get(defaultModelPrice.id);+ // Skip if up-to-date (unless force=true)if (!force &&- existingModelUpdateDate &&- isExistingModelUpToDate(defaultModelPrice, existingModelUpdateDate)+ existingModel &&+ isModelUpToDate(defaultModelPrice, existingModel)) {logger.debug(- `Default model ${defaultModelPrice.model_name} (${defaultModelPrice.id}) already up to date. Skipping.`,+ `Default model ${defaultModelPrice.modelName} (${defaultModelPrice.id}) already up to date. Skipping.`,);continue;}- if (- !existingModelUpdateDate &&- Object.keys(defaultModelPrice.prices).length === 0- ) {+ // Skip if no tiers defined+ if (defaultModelPrice.pricingTiers.length === 0) {logger.debug(- `No new and existing prices for ${defaultModelPrice.model_name} (${defaultModelPrice.id}). Skipping.`,+ `No pricing tiers for ${defaultModelPrice.modelName} (${defaultModelPrice.id}). Skipping.`,);-continue;}- // Upsert model and prices in a transaction+ // Upsert model, tiers, and prices in a transactionpromises.push(- prisma- .$transaction(async (tx) => {- await tx.model.upsert({- where: {- projectId: null,- id: defaultModelPrice.id,- },- update: {- modelName: defaultModelPrice.model_name,- matchPattern: defaultModelPrice.match_pattern,- updatedAt: defaultModelPrice.updated_at,- tokenizerConfig:- defaultModelPrice.tokenizer_config ?? undefined,- tokenizerId: defaultModelPrice.tokenizer_id,- },- create: {- projectId: null,- id: defaultModelPrice.id,- modelName: defaultModelPrice.model_name,- matchPattern: defaultModelPrice.match_pattern,- tokenizerConfig:- defaultModelPrice.tokenizer_config ?? undefined,- tokenizerId: defaultModelPrice.tokenizer_id,- createdAt: defaultModelPrice.created_at,- updatedAt: defaultModelPrice.updated_at,- },- });-- const pricesToUpsert = [];-- for (const [usageType, price] of Object.entries(- defaultModelPrice.prices,- )) {- pricesToUpsert.push(- tx.price.upsert({- where: {- modelId_usageType: {- modelId: defaultModelPrice.id,- usageType,- },- },- update: {- price,- updatedAt: defaultModelPrice.updated_at,- },- create: {- modelId: defaultModelPrice.id,- projectId: null,- usageType,- price,- createdAt: defaultModelPrice.created_at,- updatedAt: defaultModelPrice.updated_at,- },- }),- );- }-- await Promise.all(pricesToUpsert);-- logger.info(- `Upserted default model ${defaultModelPrice.model_name} (${defaultModelPrice.id})`,- );- })- .catch((error) => {+ upsertModelWithTiers(defaultModelPrice, existingModel).catch(+ (error) => {logger.error(- `Error upserting default model ${defaultModelPrice.model_name} (${defaultModelPrice.id}): ${error.message}`,- {- error,- },+ `Error upserting default model ${defaultModelPrice.modelName} (${defaultModelPrice.id}): ${error.message}`,+ { error },);- }),+ },+ ),);}@@ -245,20 +218,236 @@ export const upsertDefaultModelPrices = async (force = false) => {}};-function isExistingModelUpToDate(+/**+ * Upserts a model with its pricing tiers in a transaction+ */+async function upsertModelWithTiers(defaultModelPrice: DefaultModelPrice,- existingModelPrices: { updatedAt: Date; prices: Record<string, number> },+ existingModel:+ | {+ updatedAt: Date;+ tiers: Array<{+ id: string;+ name: string;+ priority: number;+ isDefault: boolean;+ }>;+ }+ | undefined,) {- const isUpdatedAtSame =- existingModelPrices.updatedAt.getTime() ===- defaultModelPrice.updated_at.getTime();-- const isPriceSame =- Object.keys(defaultModelPrice.prices).length ===- Object.keys(existingModelPrices.prices).length &&- Object.entries(existingModelPrices.prices).every(([usageType, price]) => {- return price === defaultModelPrice.prices[usageType];+ await prisma.$transaction(async (tx) => {+ // 1. Upsert model+ await tx.model.upsert({+ where: {+ projectId: null,+ id: defaultModelPrice.id,+ },+ update: {+ modelName: defaultModelPrice.modelName,+ matchPattern: defaultModelPrice.matchPattern,+ updatedAt: defaultModelPrice.updatedAt,+ tokenizerConfig: defaultModelPrice.tokenizerConfig ?? undefined,+ tokenizerId: defaultModelPrice.tokenizerId,+ },+ create: {+ projectId: null,+ id: defaultModelPrice.id,+ modelName: defaultModelPrice.modelName,+ matchPattern: defaultModelPrice.matchPattern,+ tokenizerConfig: defaultModelPrice.tokenizerConfig ?? undefined,+ tokenizerId: defaultModelPrice.tokenizerId,+ createdAt: defaultModelPrice.createdAt,+ updatedAt: defaultModelPrice.updatedAt,+ },+ });++ // 2. Get tier IDs from JSON+ const jsonTierIds = new Set(+ defaultModelPrice.pricingTiers.map((t) => t.id),+ );++ // 3. Delete tiers that exist in DB but not in JSON (source of truth)+ if (existingModel) {+ const tiersToDelete = existingModel.tiers+ .filter((t) => !jsonTierIds.has(t.id))+ .map((t) => t.id);++ if (tiersToDelete.length > 0) {+ await tx.pricingTier.deleteMany({+ where: {+ id: { in: tiersToDelete },+ modelId: defaultModelPrice.id,+ },+ });+ logger.debug(+ `Deleted ${tiersToDelete.length} obsolete tiers for model ${defaultModelPrice.modelName}`,+ );+ }+ }++ // 4. Upsert each tier and its prices+ for (const tier of defaultModelPrice.pricingTiers) {+ await upsertTierWithPrices(+ tx,+ defaultModelPrice.id,+ defaultModelPrice.createdAt,+ defaultModelPrice.updatedAt,+ tier,+ );+ }++ logger.info(+ `Upserted default model ${defaultModelPrice.modelName} (${defaultModelPrice.id}) with ${defaultModelPrice.pricingTiers.length} tiers`,+ );+ });+}++/**+ * Upserts a single pricing tier with its prices+ */+async function upsertTierWithPrices(+ tx: Omit<+ PrismaClient,+ "$connect" | "$disconnect" | "$on" | "$transaction" | "$extends"+ >,+ modelId: string,+ createdAt: Date,+ updatedAt: Date,+ tier: PricingTier,+) {+ // Upsert tier+ await tx.pricingTier.upsert({+ where: { id: tier.id },+ update: {+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ updatedAt,+ },+ create: {+ id: tier.id,+ modelId,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ createdAt,+ updatedAt,+ },+ });++ // Get existing prices for this tier+ const existingPrices = await tx.price.findMany({+ where: {+ modelId,+ pricingTierId: tier.id,+ },+ select: { usageType: true },+ });++ const existingUsageTypes = new Set(existingPrices.map((p) => p.usageType));+ const jsonUsageTypes = new Set(Object.keys(tier.prices));++ // Delete prices that exist in DB but not in JSON+ const usageTypesToDelete = Array.from(existingUsageTypes).filter(+ (ut) => !jsonUsageTypes.has(ut),+ );++ if (usageTypesToDelete.length > 0) {+ await tx.price.deleteMany({+ where: {+ modelId,+ pricingTierId: tier.id,+ usageType: { in: usageTypesToDelete },+ },});+ }++ // Upsert each price+ const priceUpserts = [];+ for (const [usageType, price] of Object.entries(tier.prices)) {+ priceUpserts.push(+ tx.price.upsert({+ where: {+ modelId_usageType_pricingTierId: {+ modelId,+ usageType,+ pricingTierId: tier.id,+ },+ },+ update: {+ price,+ updatedAt,+ },+ create: {+ modelId,+ projectId: null,+ pricingTierId: tier.id,+ usageType,+ price,+ createdAt,+ updatedAt,+ },+ }),+ );+ }++ await Promise.all(priceUpserts);+}++/**+ * Checks if a model is up-to-date by comparing updated_at and tiers+ */+function isModelUpToDate(+ defaultModelPrice: DefaultModelPrice,+ existingModel: {+ updatedAt: Date;+ tiers: Array<{+ id: string;+ name: string;+ priority: number;+ isDefault: boolean;+ }>;+ },+): boolean {+ // Check if updated_at matches+ const isUpdatedAtSame =+ existingModel.updatedAt.getTime() === defaultModelPrice.updatedAt.getTime();++ if (!isUpdatedAtSame) {+ return false;+ }++ // Check if tiers match (same count and same IDs)+ const jsonTierIds = new Set(defaultModelPrice.pricingTiers.map((t) => t.id));+ const dbTierIds = new Set(existingModel.tiers.map((t) => t.id));++ if (jsonTierIds.size !== dbTierIds.size) {+ return false;+ }++ for (const id of jsonTierIds) {+ if (!dbTierIds.has(id)) {+ return false;+ }+ }++ // Check if tier properties match+ for (const jsonTier of defaultModelPrice.pricingTiers) {+ const dbTier = existingModel.tiers.find((t) => t.id === jsonTier.id);+ if (!dbTier) {+ return false;+ }++ if (+ dbTier.name !== jsonTier.name ||+ dbTier.priority !== jsonTier.priority ||+ dbTier.isDefault !== jsonTier.isDefault+ ) {+ return false;+ }+ }- return isUpdatedAtSame && isPriceSame;+ return true;}diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 2f2136ee2a..2605f84d8f 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -1,9 +1,9 @@import { Cluster, Redis } from "ioredis";import { v4 } from "uuid";+import { Decimal } from "decimal.js";import {Model,ObservationLevel,- Price,PrismaClient,Prompt,} from "@langfuse/shared";@@ -38,6 +38,7 @@ import {TraceUpsertQueue,UsageCostType,findModel,+ matchPricingTier,validateAndInflateScore,DatasetRunItemRecordInsertType,EventRecordInsertType,@@ -1080,23 +1081,53 @@ export class IngestionService {}): Promise<Pick<ObservationRecordInsertType,- "usage_details" | "cost_details" | "total_cost" | "internal_model_id"+ | "usage_details"+ | "cost_details"+ | "total_cost"+ | "internal_model_id"+ | "usage_pricing_tier_id"+ | "usage_pricing_tier_name">> {const { projectId, observationRecord } = params;- const { model: internalModel, prices: modelPrices } =+ const { model: internalModel, pricingTiers } =observationRecord.provided_model_name? await findModel({projectId,model: observationRecord.provided_model_name,})- : { model: null, prices: [] };+ : { model: null, pricingTiers: [] };const final_usage_details = await this.getUsageUnits(observationRecord,internalModel,);+ // Match pricing tier based on usage_details+ let modelPrices: Array<{ usageType: string; price: Decimal }> = [];+ let usage_pricing_tier_id: string | null = null;+ let usage_pricing_tier_name: string | null = null;++ if (pricingTiers.length > 0 && final_usage_details.usage_details) {+ const matchedTier = matchPricingTier(+ pricingTiers,+ final_usage_details.usage_details,+ );++ if (matchedTier) {+ usage_pricing_tier_id = matchedTier.pricingTierId;+ usage_pricing_tier_name = matchedTier.pricingTierName;++ // Convert matched tier prices to simple format for calculateUsageCosts+ modelPrices = Object.entries(matchedTier.prices).map(+ ([usageType, price]) => ({+ usageType,+ price,+ }),+ );+ }+ }+const final_cost_details = IngestionService.calculateUsageCosts(modelPrices,observationRecord,@@ -1108,6 +1139,7 @@ export class IngestionService {{cost: final_cost_details.cost_details,usage: final_usage_details.usage_details,+ pricingTier: usage_pricing_tier_name,},);@@ -1115,6 +1147,8 @@ export class IngestionService {...final_usage_details,...final_cost_details,internal_model_id: internalModel?.id,+ usage_pricing_tier_id,+ usage_pricing_tier_name,};}@@ -1249,7 +1283,10 @@ export class IngestionService {}static calculateUsageCosts(- modelPrices: Price[] | null | undefined,+ modelPrices:+ | Array<{ usageType: string; price: Decimal }>+ | null+ | undefined,observationRecord: Pick<ObservationRecordInsertType,"provided_cost_details"diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex d1cda24a53..5b477fb2c5 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { z } from "zod/v4";+import { uuid, z } from "zod/v4";import { prisma } from "@langfuse/shared/src/db";import {clickhouseClient,@@ -1404,9 +1404,12 @@ describe("Ingestion end-to-end tests", () => {}, 10_000);it("should merge observations and set negative tokens and cost to null", async () => {+ const modelId = "clyrjpbe20000t0mzcbwc42rg";+ const pricingTierId = "f94390ea-8d08-4bbb-b106-519f3eaf81bb";+await prisma.model.create({data: {- id: "clyrjpbe20000t0mzcbwc42rg",+ id: modelId,modelName: "gpt-4o-mini-2024-07-18",matchPattern: "(?i)^(gpt-4o-mini-2024-07-18)$",startDate: new Date("2021-01-01T00:00:00.000Z"),@@ -1422,9 +1425,21 @@ describe("Ingestion end-to-end tests", () => {},});+ await prisma.pricingTier.create({+ data: {+ id: pricingTierId,+ name: "Standard",+ conditions: [],+ isDefault: true,+ priority: 0,+ modelId: modelId,+ },+ });+await prisma.price.create({data: {id: "cm2uio8ef006mh6qlzc2mqa0e",+ pricingTierId,modelId: "clyrjpbe20000t0mzcbwc42rg",projectId: null,price: 0.00000015,@@ -1435,6 +1450,7 @@ describe("Ingestion end-to-end tests", () => {await prisma.price.create({data: {id: "cm2uio8ef006oh6qlldn36376",+ pricingTierId,modelId: "clyrjpbe20000t0mzcbwc42rg",projectId: null,price: 0.0000006,@@ -1522,6 +1538,9 @@ describe("Ingestion end-to-end tests", () => {});it("should merge observations and calculate cost", async () => {+ const modelId = "clyrjpbe20000t0mzcbwc42rg";+ const pricingTierId = "f94390ea-8d08-4bbb-b106-519f3eaf81bb";+await prisma.model.create({data: {id: "clyrjpbe20000t0mzcbwc42rg",@@ -1540,9 +1559,21 @@ describe("Ingestion end-to-end tests", () => {},});+ await prisma.pricingTier.create({+ data: {+ id: pricingTierId,+ name: "Standard",+ conditions: [],+ isDefault: true,+ priority: 0,+ modelId: modelId,+ },+ });+await prisma.price.create({data: {id: "cm2uio8ef006mh6qlzc2mqa0e",+ pricingTierId,modelId: "clyrjpbe20000t0mzcbwc42rg",projectId: null,price: 0.00000015,@@ -1553,6 +1584,7 @@ describe("Ingestion end-to-end tests", () => {await prisma.price.create({data: {id: "cm2uio8ef006oh6qlldn36376",+ pricingTierId,modelId: "clyrjpbe20000t0mzcbwc42rg",projectId: null,price: 0.0000006,@@ -2270,6 +2302,520 @@ describe("Ingestion end-to-end tests", () => {expect(generation.metadata).toEqual(output);});});++ describe("Tiered Pricing", () => {+ it("should apply default tier for usage below threshold (Anthropic Claude example)", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();+ const modelId = "claude-sonnet-test";++ // Create model with tiered pricing (Anthropic Claude pattern: $3/M tokens default, $6/M tokens >200K)+ await prisma.model.create({+ data: {+ id: modelId,+ modelName: "claude-sonnet-4.5",+ matchPattern: "(?i)^(claude-sonnet-4.5)$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: ModelUsageUnit.Tokens,+ pricingTiers: {+ create: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000003, // $3/M tokens+ modelId,+ },+ {+ usageType: "output",+ price: 0.000015, // $15/M tokens+ modelId,+ },+ ],+ },+ },+ {+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000006, // $6/M tokens+ modelId,+ },+ {+ usageType: "output",+ price: 0.000015, // $15/M tokens+ modelId,+ },+ ],+ },+ },+ ],+ },+ },+ });++ const generationEventList: ObservationEvent[] = [+ {+ id: randomUUID(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ traceId: traceId,+ type: "GENERATION",+ name: "generation-name",+ startTime: new Date().toISOString(),+ model: "claude-sonnet-4.5",+ usage: {+ input: 100000, // Below 200K threshold+ output: 2000,+ unit: ModelUsageUnit.Tokens,+ },+ environment,+ },+ },+ ];++ await Promise.all([+ ingestionService.processTraceEventList({+ projectId,+ entityId: traceId,+ createdAtTimestamp: new Date(),+ traceEventList: [+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name: "trace-name",+ timestamp: new Date().toISOString(),+ environment,+ },+ },+ ],+ }),+ ingestionService.processObservationEventList({+ projectId,+ entityId: generationId,+ createdAtTimestamp: new Date(),+ observationEventList: generationEventList,+ }),+ ]);++ await clickhouseWriter.flushAll(true);++ const generation = await getClickhouseRecord(+ TableName.Observations,+ generationId,+ );++ expect(generation.internal_model_id).toBe(modelId);+ expect(generation.usage_details.input).toBe(100000);+ expect(generation.usage_details.output).toBe(2000);++ // Verify default tier was used+ expect(generation.usage_pricing_tier_name).toBe("Standard");+ expect(generation.usage_pricing_tier_id).toBeDefined();++ // Verify cost calculation with default tier prices ($3/M input, $15/M output)+ expect(generation.cost_details.input).toBeCloseTo(0.3, 6); // 100K * $3/M+ expect(generation.cost_details.output).toBeCloseTo(0.03, 6); // 2K * $15/M+ expect(generation.cost_details.total).toBeCloseTo(0.33, 6);+ expect(generation.total_cost).toBeCloseTo(0.33, 6);+ });++ it("should apply large context tier for usage above threshold (Anthropic Claude example)", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();+ const modelId = "claude-sonnet-test-2";++ // Create model with tiered pricing+ await prisma.model.create({+ data: {+ id: modelId,+ modelName: "claude-sonnet-4.5-test",+ matchPattern: "(?i)^(claude-sonnet-4.5-test)$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: ModelUsageUnit.Tokens,+ pricingTiers: {+ create: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000003, // $3/M tokens+ modelId,+ },+ {+ usageType: "output",+ price: 0.000015, // $15/M tokens+ modelId,+ },+ ],+ },+ },+ {+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000006, // $6/M tokens+ modelId,+ },+ {+ usageType: "output",+ price: 0.000015, // $15/M tokens+ modelId,+ },+ ],+ },+ },+ ],+ },+ },+ });++ const generationEventList: ObservationEvent[] = [+ {+ id: randomUUID(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ traceId: traceId,+ type: "GENERATION",+ name: "generation-name",+ startTime: new Date().toISOString(),+ model: "claude-sonnet-4.5-test",+ usage: {+ input: 250000, // Above 200K threshold+ output: 2000,+ unit: ModelUsageUnit.Tokens,+ },+ environment,+ },+ },+ ];++ await Promise.all([+ ingestionService.processTraceEventList({+ projectId,+ entityId: traceId,+ createdAtTimestamp: new Date(),+ traceEventList: [+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name: "trace-name",+ timestamp: new Date().toISOString(),+ environment,+ },+ },+ ],+ }),+ ingestionService.processObservationEventList({+ projectId,+ entityId: generationId,+ createdAtTimestamp: new Date(),+ observationEventList: generationEventList,+ }),+ ]);++ await clickhouseWriter.flushAll(true);++ const generation = await getClickhouseRecord(+ TableName.Observations,+ generationId,+ );++ expect(generation.internal_model_id).toBe(modelId);+ expect(generation.usage_details.input).toBe(250000);+ expect(generation.usage_details.output).toBe(2000);++ // Verify large context tier was used+ expect(generation.usage_pricing_tier_name).toBe("Large Context (>200K)");+ expect(generation.usage_pricing_tier_id).toBeDefined();++ // Verify cost calculation with large context tier prices ($6/M input, $15/M output)+ expect(generation.cost_details.input).toBeCloseTo(1.5, 6); // 250K * $6/M+ expect(generation.cost_details.output).toBeCloseTo(0.03, 6); // 2K * $15/M+ expect(generation.cost_details.total).toBeCloseTo(1.53, 6);+ expect(generation.total_cost).toBeCloseTo(1.53, 6);+ });++ it("should match pattern with granular usage details (input_cached + input_regular)", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();+ const modelId = "claude-test-granular";++ // Create model with tiered pricing that sums all input* fields+ await prisma.model.create({+ data: {+ id: modelId,+ modelName: "claude-test-granular",+ matchPattern: "(?i)^(claude-test-granular)$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: ModelUsageUnit.Tokens,+ pricingTiers: {+ create: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000003,+ modelId,+ },+ ],+ },+ },+ {+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input", // Matches input_cached + input_regular+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000006,+ modelId,+ },+ ],+ },+ },+ ],+ },+ },+ });++ const generationEventList: ObservationEvent[] = [+ {+ id: randomUUID(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ traceId: traceId,+ type: "GENERATION",+ name: "generation-name",+ startTime: new Date().toISOString(),+ model: "claude-test-granular",+ usageDetails: {+ input_cached: 150000,+ input_regular: 60000, // Total: 210K > 200K+ },+ environment,+ },+ },+ ];++ await Promise.all([+ ingestionService.processTraceEventList({+ projectId,+ entityId: traceId,+ createdAtTimestamp: new Date(),+ traceEventList: [+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name: "trace-name",+ timestamp: new Date().toISOString(),+ environment,+ },+ },+ ],+ }),+ ingestionService.processObservationEventList({+ projectId,+ entityId: generationId,+ createdAtTimestamp: new Date(),+ observationEventList: generationEventList,+ }),+ ]);++ await clickhouseWriter.flushAll(true);++ const generation = await getClickhouseRecord(+ TableName.Observations,+ generationId,+ );++ expect(generation.internal_model_id).toBe(modelId);++ // Verify large context tier was used (150K + 60K = 210K > 200K)+ expect(generation.usage_pricing_tier_name).toBe("Large Context (>200K)");+ expect(generation.usage_pricing_tier_id).toBeDefined();+ });++ it("should handle exactly at threshold boundary (200K tokens)", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();+ const modelId = "claude-boundary-test";++ await prisma.model.create({+ data: {+ id: modelId,+ modelName: "claude-boundary",+ matchPattern: "(?i)^(claude-boundary)$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: ModelUsageUnit.Tokens,+ pricingTiers: {+ create: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000003,+ modelId,+ },+ ],+ },+ },+ {+ name: "Large Context (>200K)",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt", // Strictly greater than+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: {+ create: [+ {+ usageType: "input",+ price: 0.000006,+ modelId,+ },+ ],+ },+ },+ ],+ },+ },+ });++ const generationEventList: ObservationEvent[] = [+ {+ id: randomUUID(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ traceId: traceId,+ type: "GENERATION",+ name: "generation-name",+ startTime: new Date().toISOString(),+ model: "claude-boundary",+ usage: {+ input: 200000, // Exactly at threshold+ output: 100,+ unit: ModelUsageUnit.Tokens,+ },+ environment,+ },+ },+ ];++ await Promise.all([+ ingestionService.processTraceEventList({+ projectId,+ entityId: traceId,+ createdAtTimestamp: new Date(),+ traceEventList: [+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name: "trace-name",+ timestamp: new Date().toISOString(),+ environment,+ },+ },+ ],+ }),+ ingestionService.processObservationEventList({+ projectId,+ entityId: generationId,+ createdAtTimestamp: new Date(),+ observationEventList: generationEventList,+ }),+ ]);++ await clickhouseWriter.flushAll(true);++ const generation = await getClickhouseRecord(+ TableName.Observations,+ generationId,+ );++ // At exactly 200K, should use default tier (operator is "gt", not "gte")+ expect(generation.usage_pricing_tier_name).toBe("Standard");+ expect(generation.cost_details.input).toBeCloseTo(0.6, 6); // 200K * $3/M+ });+ });});async function getClickhouseRecord<T extends TableName>(diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.tsindex f907429537..6ebebd8ce6 100644--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts@@ -74,12 +74,25 @@ describe("Token Cost Calculation", () => {beforeEach(async () => {await pruneDatabase();- await prisma.model.create({+ const model = await prisma.model.create({data: tokenModelData,});+ const pricingTierId = uuidv4();+ await prisma.pricingTier.create({+ data: {+ id: pricingTierId,+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ modelId,+ },+ });+await Promise.all([prisma.price.createMany({data: modelPrices.map((price) => ({+ pricingTierId,modelId,projectId: null,usageType: price.usageType,@@ -87,6 +100,7 @@ describe("Token Cost Calculation", () => {})),}),]);+vi.clearAllMocks();});