🪢 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(api): add model definition upsert endpoint (#16516)
Hassieb Pakzad8ab6c9154370
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex 266c0d4faa..16e011d2ed 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -878,6 +878,27 @@ types:- model_parameters- metadata+ PricingTierConditionInput:+ docs: Condition input for matching a pricing tier.+ discriminated: false+ union:+ - PricingTierUsageConditionInput+ - PricingTierAttributeCondition++ PricingTierUsageConditionInput:+ docs: Input condition that sums usage details whose keys match a regex.+ properties:+ usageDetailPattern:+ docs: Regex pattern matched against usage detail keys.+ type: string+ operator: PricingTierOperator+ value:+ docs: Numeric threshold for the summed matching usage values.+ type: double+ caseSensitive:+ docs: Whether the usage-detail regex is case-sensitive. Defaults to false.+ type: optional<boolean>+PricingTier:docs: |Pricing tier definition with conditional pricing based on usage thresholds or observation attributes.@@ -973,8 +994,8 @@ types:- Must have priority=0- Must have empty conditions array (conditions=[])- The default tier acts as a fallback when no conditional tiers match.- type: boolean+ The default tier acts as a fallback when no conditional tiers match. Defaults to false when omitted.+ type: optional<boolean>priority:docs: |Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).@@ -990,7 +1011,7 @@ types:Conditional tiers should define one or more conditions that specify when this tier's pricing applies.Conditions can compare summed matching usage details to a numeric threshold, or exactly match a top-level model parameter or metadata value.- type: list<PricingTierCondition>+ type: list<PricingTierConditionInput>prices:docs: |Prices (USD) by usage type for this tier. At least one price must be defined.diff --git a/fern/apis/server/definition/models.yml b/fern/apis/server/definition/models.ymlindex 374c72a604..63f153dcd9 100644--- a/fern/apis/server/definition/models.yml+++ b/fern/apis/server/definition/models.yml@@ -12,6 +12,14 @@ service:path: /modelsrequest: CreateModelRequestresponse: commons.Model+ upsert:+ method: PUT+ docs: Create or replace a project-owned model using its id. Built-in models cannot be modified.+ path: /models/{id}+ path-parameters:+ id: string+ request: CreateModelRequest+ response: commons.Modellist:method: GETdocs: Get all models@@ -41,6 +49,12 @@ service:id: stringtypes:+ ModelTokenizerId:+ docs: Tokenizer supported by Langfuse for model usage inference.+ enum:+ - openai+ - claude+PaginatedModels:properties:data: list<commons.Model>@@ -55,19 +69,19 @@ types:type: stringstartDate:docs: Apply only to generations which are newer than this ISO date.- type: optional<datetime>+ type: optional<nullable<datetime>>unit:docs: Unit used by this model.- type: optional<commons.ModelUsageUnit>+ type: commons.ModelUsageUnitinputPrice:docs: Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit. Creates a default tier if pricingTiers not provided.- type: optional<double>+ type: optional<nullable<double>>outputPrice:docs: Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit. Creates a default tier if pricingTiers not provided.- type: optional<double>+ type: optional<nullable<double>>totalPrice: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>+ type: optional<nullable<double>>pricingTiers:docs: |Optional. Array of pricing tiers for this model.@@ -88,10 +102,10 @@ types: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>>+ type: optional<nullable<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>+ type: optional<nullable<ModelTokenizerId>>tokenizerConfig:docs: Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.- type: optional<unknown>+ type: optional<nullable<unknown>>diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex ea58dc6ecc..48a722972f 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -3286,6 +3286,58 @@ paths:schema: {}security: *ref_0/api/public/models/{id}:+ put:+ description: >-+ Create or replace a project-owned model using its id. Built-in models+ cannot be modified.+ operationId: models_upsert+ tags:+ - Models+ parameters:+ - name: id+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Model'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateModelRequest'get:description: Get a modeloperationId: models_get@@ -10770,6 +10822,34 @@ components:enum:- model_parameters- metadata+ PricingTierConditionInput:+ title: PricingTierConditionInput+ oneOf:+ - $ref: '#/components/schemas/PricingTierUsageConditionInput'+ - $ref: '#/components/schemas/PricingTierAttributeCondition'+ description: Condition input for matching a pricing tier.+ PricingTierUsageConditionInput:+ title: PricingTierUsageConditionInput+ type: object+ description: Input condition that sums usage details whose keys match a regex.+ properties:+ usageDetailPattern:+ type: string+ description: Regex pattern matched against usage detail keys.+ operator:+ $ref: '#/components/schemas/PricingTierOperator'+ value:+ type: number+ format: double+ description: Numeric threshold for the summed matching usage values.+ caseSensitive:+ type: boolean+ nullable: true+ description: Whether the usage-detail regex is case-sensitive. Defaults to false.+ required:+ - usageDetailPattern+ - operator+ - valuePricingTier:title: PricingTiertype: object@@ -10932,6 +11012,7 @@ components:Volume Tier", "Extended Context"isDefault:type: boolean+ nullable: truedescription: >-Whether this is the default tier. Exactly one tier per model must bemarked as default.@@ -10947,6 +11028,7 @@ components:The default tier acts as a fallback when no conditional tiers match.+ Defaults to false when omitted.priority:type: integerdescription: >-@@ -10962,7 +11044,7 @@ components:conditions:type: arrayitems:- $ref: '#/components/schemas/PricingTierCondition'+ $ref: '#/components/schemas/PricingTierConditionInput'description: >-Array of conditions that must ALL be met for this tier to match (ANDlogic).@@ -10996,7 +11078,6 @@ components:million input tokens and $15 per million output tokens.required:- name- - isDefault- priority- conditions- prices@@ -12579,6 +12660,13 @@ components:Histograms will return an array with [lower, upper, height] tuples.required:- data+ ModelTokenizerId:+ title: ModelTokenizerId+ type: string+ enum:+ - openai+ - claude+ description: Tokenizer supported by Langfuse for model usage inference.PaginatedModels:title: PaginatedModelstype: object@@ -12616,7 +12704,6 @@ components:description: Apply only to generations which are newer than this ISO date.unit:$ref: '#/components/schemas/ModelUsageUnit'- nullable: truedescription: Unit used by this model.inputPrice:type: number@@ -12680,7 +12767,7 @@ components:which will automatically create a single default tier named"Standard".tokenizerId:- type: string+ $ref: '#/components/schemas/ModelTokenizerId'nullable: truedescription: >-Optional. Tokenizer to be applied to observations which match to@@ -12693,6 +12780,7 @@ components:required:- modelName- matchPattern+ - unitObservationsV2Response:title: ObservationsV2Responsetype: objectdiff --git a/web/src/__tests__/server/model-definitions.servertest.ts b/web/src/__tests__/server/model-definitions.servertest.tsindex 990d6fa9f2..8c0b755f42 100644--- a/web/src/__tests__/server/model-definitions.servertest.ts+++ b/web/src/__tests__/server/model-definitions.servertest.ts@@ -8,8 +8,12 @@ import {GetModelV1Response,GetModelsV1Response,PostModelsV1Response,+ PutModelV1Response,} from "@/src/features/public-api/types/models";-import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import {+ createOrgProjectAndApiKey,+ findModel,+} from "@langfuse/shared/src/server";import { v4 } from "uuid";import type { z } from "zod";@@ -303,6 +307,220 @@ describe("/models API Endpoints", () => {);});+ it("Upserts a complete custom model definition using the path id", async () => {+ const modelId = v4();+ const modelName = `upserted-model-${v4()}`;++ const upsertedModel = await makeZodVerifiedAPICall(+ PutModelV1Response,+ "PUT",+ `/api/public/models/${modelId}`,+ {+ modelName,+ matchPattern: `(?i)^${modelName}$`,+ inputPrice: 0.001,+ outputPrice: 0.002,+ unit: "TOKENS",+ },+ auth,+ );++ expect(upsertedModel.status).toBe(200);+ expect(upsertedModel.body).toMatchObject({+ id: modelId,+ modelName,+ inputPrice: 0.001,+ outputPrice: 0.002,+ isLangfuseManaged: false,+ });+ await expect(+ prisma.model.count({ where: { id: modelId, projectId } }),+ ).resolves.toBe(1);+ });++ it("Updates a custom model and invalidates cached pricing", async () => {+ const customModelName = `custom-model-${v4()}`;+ const customModel = await makeZodVerifiedAPICall(+ PostModelsV1Response,+ "POST",+ "/api/public/models",+ {+ modelName: customModelName,+ matchPattern: `(?i)^${customModelName}$`,+ inputPrice: 0.002,+ outputPrice: 0.004,+ unit: "TOKENS",+ },+ auth,+ );++ const cachedModel = await findModel({+ projectId,+ model: customModelName,+ });+ expect(+ cachedModel.pricingTiers[0].prices+ .find((price) => price.usageType === "input")+ ?.price.toNumber(),+ ).toBe(0.002);++ const updatedModel = await makeZodVerifiedAPICall(+ PutModelV1Response,+ "PUT",+ `/api/public/models/${customModel.body.id}`,+ {+ modelName: customModelName,+ matchPattern: `(?i)^${customModelName}$`,+ totalPrice: 0.009,+ unit: "TOKENS",+ tokenizerId: "claude",+ },+ auth,+ );++ expect(updatedModel.body).toMatchObject({+ id: customModel.body.id,+ inputPrice: null,+ outputPrice: null,+ totalPrice: 0.009,+ tokenizerId: "claude",+ pricingTiers: [+ expect.objectContaining({+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { total: 0.009 },+ }),+ ],+ });++ const refreshedModel = await findModel({+ projectId,+ model: customModelName,+ });+ expect(+ refreshedModel.pricingTiers[0].prices+ .find((price) => price.usageType === "total")+ ?.price.toNumber(),+ ).toBe(0.009);+ });++ it("Rolls back the model and pricing replacement together", async () => {+ const modelName = `rollback-model-${v4()}`;+ const customModel = await makeZodVerifiedAPICall(+ PostModelsV1Response,+ "POST",+ "/api/public/models",+ {+ modelName,+ matchPattern: `(?i)^${modelName}$`,+ inputPrice: 0.001,+ unit: "TOKENS",+ },+ auth,+ );+ const originalTierIds = (+ await prisma.pricingTier.findMany({+ where: { modelId: customModel.body.id },+ select: { id: true },+ })+ ).map(({ id }) => id);++ const response = await makeAPICall(+ "PUT",+ `/api/public/models/${customModel.body.id}`,+ {+ modelName,+ matchPattern: `(?i)^${modelName}$`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Unstorable",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 1e40 },+ },+ ],+ },+ auth,+ );++ expect(response.status).toBe(500);+ await expect(+ prisma.pricingTier.findMany({+ where: { modelId: customModel.body.id },+ select: { id: true },+ }),+ ).resolves.toEqual(originalTierIds.map((id) => ({ id })));+ await expect(+ prisma.model.findUnique({ where: { id: customModel.body.id } }),+ ).resolves.toMatchObject({+ inputPrice: expect.anything(),+ totalPrice: null,+ });+ });++ it("Does not update a model owned by another project", async () => {+ const {+ auth: otherAuth,+ projectId: otherProjectId,+ orgId: otherOrgId,+ } = await createOrgProjectAndApiKey();+ const modelName = `other-project-model-${v4()}`;++ try {+ const otherModel = await makeZodVerifiedAPICall(+ PostModelsV1Response,+ "POST",+ "/api/public/models",+ {+ modelName,+ matchPattern: `(?i)^${modelName}$`,+ totalPrice: 0.001,+ unit: "TOKENS",+ },+ otherAuth,+ );++ const response = await makeAPICall(+ "PUT",+ `/api/public/models/${otherModel.body.id}`,+ {+ modelName: `${modelName}-changed`,+ matchPattern: `(?i)^${modelName}-changed$`,+ totalPrice: 0.002,+ unit: "TOKENS",+ },+ auth,+ );++ expect(response.status).toBe(404);+ await expect(+ prisma.model.findUnique({ where: { id: otherModel.body.id } }),+ ).resolves.toMatchObject({ projectId: otherProjectId, modelName });+ } finally {+ await prisma.organization.delete({ where: { id: otherOrgId } });+ }+ });++ it("Cannot update a built-in model", async () => {+ const response = await makeAPICall(+ "PUT",+ `/api/public/models/${modelOneId}`,+ {+ modelName: fixtureModelName,+ matchPattern: `(?i)^${fixtureModelName}$`,+ totalPrice: 0.003,+ unit: "TOKENS",+ },+ auth,+ );++ expect(response.status).toBe(404);+ });+it("Post model with invalid matchPattern", async () => {const customModel = await makeAPICall("POST",@@ -341,7 +559,7 @@ describe("/models API Endpoints", () => {"/api/public/models",{modelName: fixtureModelName,- matchPattern: "[][", // brackets not balanced+ matchPattern: `(?i)^${fixtureModelName}$`,startDate: "2023-12-01",inputPrice: 0.002,outputPrice: 0.004,@@ -354,6 +572,28 @@ describe("/models API Endpoints", () => {expect(customModel.status).toBe(400);});+ it.each([+ { inputPrice: 0, totalPrice: 0.1 },+ { outputPrice: 0.1, totalPrice: 0 },+ ])(+ "Rejects mutually exclusive flat prices containing zero",+ async (prices) => {+ const response = await makeAPICall(+ "POST",+ "/api/public/models",+ {+ modelName: fixtureModelName,+ matchPattern: `(?i)^${fixtureModelName}$`,+ unit: "TOKENS",+ ...prices,+ },+ auth,+ );++ expect(response.status).toBe(400);+ },+ );+it("Cannot delete built-in models", async () => {const getBuiltInModel = await makeZodVerifiedAPICall(GetModelV1Response,diff --git a/web/src/__tests__/server/model-pricing-tiers.servertest.ts b/web/src/__tests__/server/model-pricing-tiers.servertest.tsindex 612ed35684..e79f3e98ab 100644--- a/web/src/__tests__/server/model-pricing-tiers.servertest.ts+++ b/web/src/__tests__/server/model-pricing-tiers.servertest.ts@@ -9,6 +9,7 @@ import {GetModelV1Response,GetModelsV1Response,PostModelsV1Response,+ PutModelV1Response,} from "@/src/features/public-api/types/models";import {@@ -908,6 +909,123 @@ describe("/models API Endpoints - Pricing Tiers", () => {});});+ describe("PUT /models/{modelId} - with pricing tiers", () => {+ it("should atomically replace all pricing tiers and prices", async () => {+ const uniqueId = randomUUID();+ const { auth } = await createOrgProjectAndApiKey();+ const modelName = `aaa-test-model-${uniqueId}`;++ const createdModel = await makeZodVerifiedAPICall(+ PostModelsV1Response,+ "POST",+ "/api/public/models",+ {+ modelName,+ matchPattern: `^${modelName}$`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 3.0, output: 15.0, cache_read: 0.3 },+ },+ {+ name: "Large Context",+ isDefault: false,+ priority: 1,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gt",+ value: 200000,+ caseSensitive: false,+ },+ ],+ prices: { input: 6.0, output: 18.0, cache_read: 0.6 },+ },+ ],+ },+ auth,+ );++ const originalTiers = await prisma.pricingTier.findMany({+ where: { modelId: createdModel.body.id },+ include: { prices: true },+ });+ const originalTierIds = originalTiers.map(({ id }) => id);+ const originalPriceIds = originalTiers.flatMap(({ prices }) =>+ prices.map(({ id }) => id),+ );++ const updatedModel = await makeZodVerifiedAPICall(+ PutModelV1Response,+ "PUT",+ `/api/public/models/${createdModel.body.id}`,+ {+ modelName,+ matchPattern: `(?i)^${modelName}$`,+ unit: "TOKENS",+ pricingTiers: [+ {+ name: "Standard v2",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 4.0, output: 16.0 },+ },+ {+ name: "Batch",+ isDefault: false,+ priority: 2,+ conditions: [+ {+ usageDetailPattern: "^input",+ operator: "gte",+ value: 100000,+ caseSensitive: false,+ },+ ],+ prices: { input: 2.0, output: 8.0 },+ },+ ],+ },+ auth,+ );++ expect(updatedModel.body.pricingTiers).toEqual([+ expect.objectContaining({+ name: "Standard v2",+ isDefault: true,+ priority: 0,+ conditions: [],+ prices: { input: 4.0, output: 16.0 },+ }),+ expect.objectContaining({+ name: "Batch",+ isDefault: false,+ priority: 2,+ prices: { input: 2.0, output: 8.0 },+ }),+ ]);++ const replacementTiers = await prisma.pricingTier.findMany({+ where: { modelId: createdModel.body.id },+ include: { prices: true },+ });+ expect(replacementTiers).toHaveLength(2);+ expect(+ replacementTiers.some(({ id }) => originalTierIds.includes(id)),+ ).toBe(false);+ expect(+ replacementTiers.some(({ prices }) =>+ prices.some(({ id }) => originalPriceIds.includes(id)),+ ),+ ).toBe(false);+ });+ });+describe("POST /models - validation", () => {it("should reject model with both flat prices and pricing tiers", async () => {const uniqueId = randomUUID();diff --git a/web/src/features/models/server/publicApiModelService.ts b/web/src/features/models/server/publicApiModelService.tsindex f5be1a0941..4a5b91c0ea 100644--- a/web/src/features/models/server/publicApiModelService.ts+++ b/web/src/features/models/server/publicApiModelService.ts@@ -51,12 +51,93 @@ type CreateModelInput = {auditScope: ModelAuditScope;};+type UpsertModelInput = z.infer<typeof GetModelV1Query> & {+ projectId: string;+ input: z.infer<typeof PostModelsV1Body>;+ auditScope: ModelAuditScope;+};+type DeleteModelInput = z.infer<typeof DeleteModelV1Query> & ModelAuditScope;const visibleModelsWhere = (projectId: string) => ({OR: [{ projectId }, { projectId: null }],});+const createModelPricing = async ({+ tx,+ model,+ input,+}: {+ tx: Prisma.TransactionClient;+ model: { id: string; projectId: string | null };+ input: z.infer<typeof PostModelsV1Body>;+}) => {+ const tierData = input.pricingTiers;++ if (tierData && tierData.length > 0) {+ for (const tier of tierData) {+ const createdTier = await tx.pricingTier.create({+ data: {+ modelId: model.id,+ name: tier.name,+ isDefault: tier.isDefault,+ priority: tier.priority,+ conditions: tier.conditions,+ },+ });++ await Promise.all(+ Object.entries(tier.prices).map(([usageType, price]) =>+ tx.price.create({+ data: {+ modelId: model.id,+ projectId: model.projectId,+ pricingTierId: createdTier.id,+ usageType,+ price: new Prisma.Decimal(price),+ },+ }),+ ),+ );+ }++ return;+ }++ const defaultTier = await tx.pricingTier.create({+ data: {+ id: `${model.id}_tier_default`,+ modelId: model.id,+ name: "Standard",+ isDefault: true,+ priority: 0,+ conditions: [],+ },+ });++ const prices = [+ { usageType: "input", price: input.inputPrice },+ { usageType: "output", price: input.outputPrice },+ { usageType: "total", price: input.totalPrice },+ ];++ await Promise.all(+ prices.map(async ({ usageType, price }) => {+ if (price == null) return;++ await tx.price.create({+ data: {+ modelId: model.id,+ projectId: model.projectId,+ pricingTierId: defaultTier.id,+ usageType,+ price: new Prisma.Decimal(price),+ },+ });+ }),+ );+};+export const listModelsForApi = async ({projectId,page,@@ -122,7 +203,7 @@ export const createModelForApi = async ({);}- const { tokenizerConfig, pricingTiers: tierData, ...rest } = input;+ const { tokenizerConfig, pricingTiers: _pricingTiers, ...rest } = input;const model = await prisma.$transaction(async (tx) => {const existingModelName = await tx.model.findFirst({@@ -147,72 +228,7 @@ export const createModelForApi = async ({},});- // 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: input.inputPrice },- { usageType: "output", price: input.outputPrice },- { usageType: "total", price: input.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 createModelPricing({ tx, model: createdModel, input });await auditLog({action: "create",@@ -243,6 +259,98 @@ export const createModelForApi = async ({return prismaToApiModelDefinition(modelWithTiers);};+export const upsertModelForApi = async ({+ projectId,+ modelId,+ input,+ auditScope,+}: UpsertModelInput) => {+ const validRegex = await isValidPostgresRegex(input.matchPattern, prisma);+ if (!validRegex) {+ throw new InvalidRequestError(+ "matchPattern is not a valid regex pattern (Postgres)",+ );+ }++ const modelWithTiers = await prisma.$transaction(async (tx) => {+ const existingModel = await tx.model.findUnique({+ where: { id: modelId },+ include: modelPricingInclude,+ });++ if (existingModel && existingModel.projectId !== projectId) {+ throw new LangfuseNotFoundError("No model with this id found.");+ }++ const duplicateModelName = await tx.model.findFirst({+ where: {+ projectId,+ modelName: input.modelName,+ NOT: { id: modelId },+ },+ });++ if (duplicateModelName) {+ throw new InvalidRequestError(+ `Model name '${input.modelName}' already exists in project`,+ );+ }++ const modelData = {+ modelName: input.modelName,+ matchPattern: input.matchPattern,+ startDate: input.startDate ?? null,+ inputPrice: input.inputPrice ?? null,+ outputPrice: input.outputPrice ?? null,+ totalPrice: input.totalPrice ?? null,+ unit: input.unit,+ tokenizerId: input.tokenizerId ?? null,+ tokenizerConfig: input.tokenizerConfig ?? Prisma.DbNull,+ };++ const upsertedModel = await tx.model.upsert({+ where: { id: modelId },+ create: {+ id: modelId,+ projectId,+ ...modelData,+ },+ update: modelData,+ });++ await tx.pricingTier.deleteMany({+ where: { modelId: upsertedModel.id },+ });+ await createModelPricing({ tx, model: upsertedModel, input });++ const upsertedModelWithTiers = await tx.model.findUnique({+ where: { id: upsertedModel.id, projectId },+ include: modelPricingInclude,+ });++ if (!upsertedModelWithTiers) {+ throw new InvalidRequestError("Failed to fetch upserted model");+ }++ await auditLog({+ action: existingModel ? "update" : "create",+ resourceType: "model",+ resourceId: upsertedModel.id,+ projectId: auditScope.projectId,+ orgId: auditScope.orgId,+ apiKeyId: auditScope.apiKeyId,+ before: existingModel ?? undefined,+ after: upsertedModelWithTiers,+ });++ return upsertedModelWithTiers;+ });++ await clearModelCacheForProject(projectId);++ return prismaToApiModelDefinition(modelWithTiers);+};+export const deleteModelForApi = async ({projectId,orgId,diff --git a/web/src/features/public-api/types/models.ts b/web/src/features/public-api/types/models.tsindex 9d78bcf782..9f36df3816 100644--- a/web/src/features/public-api/types/models.ts+++ b/web/src/features/public-api/types/models.ts@@ -181,7 +181,10 @@ export const PostModelsV1Body = z// Validation 2: If using flat prices, validate totalPrice constraintif (hasFlatPrices) {- if ((data.inputPrice || data.outputPrice) && data.totalPrice) {+ if (+ (data.inputPrice != null || data.outputPrice != null) &&+ data.totalPrice != null+ ) {ctx.addIssue({code: "custom",path: ["totalPrice"],@@ -211,6 +214,9 @@ export const GetModelV1Query = z.object({});export const GetModelV1Response = APIModelDefinition.strict();+// PUT /models/{modelId}+export const PutModelV1Response = APIModelDefinition.strict();+// DELETE /models/{modelId}export const DeleteModelV1Query = z.object({modelId: z.string(),diff --git a/web/src/pages/api/public/models/[modelId]/index.ts b/web/src/pages/api/public/models/[modelId]/index.tsindex 39f96ac0b6..544928ab10 100644--- a/web/src/pages/api/public/models/[modelId]/index.ts+++ b/web/src/pages/api/public/models/[modelId]/index.ts@@ -5,10 +5,13 @@ import {DeleteModelV1Response,GetModelV1Query,GetModelV1Response,+ PostModelsV1Body,+ PutModelV1Response,} from "@/src/features/public-api/types/models";import {deleteModelForApi,getModelForApi,+ upsertModelForApi,} from "@/src/features/models/server/publicApiModelService";export default withMiddlewares({@@ -25,6 +28,22 @@ export default withMiddlewares({},}),+ PUT: createAuthedProjectAPIRoute({+ name: "Upsert custom model definition",+ isAdminApiKeyAuthAllowed: true,+ querySchema: GetModelV1Query,+ bodySchema: PostModelsV1Body,+ responseSchema: PutModelV1Response,+ fn: async ({ query, body, auth }) => {+ return await upsertModelForApi({+ projectId: auth.scope.projectId,+ modelId: query.modelId,+ input: body,+ auditScope: auth.scope,+ });+ },+ }),+DELETE: createAuthedProjectAPIRoute({name: "Delete model",isAdminApiKeyAuthAllowed: true,