Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(api): add `models` api routes (#2531)

Marc Klingen42c12b7ce76b
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 530bec8a08..b037c3dd85 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -185,6 +185,39 @@ types:
extends: DatasetRun
properties:
datasetRunItems: list<DatasetRunItem>
+ Model:
+ docs: Model definition used for transforming usage into USD cost and/or tokenization.
+ properties:
+ id: string
+ modelName:
+ docs: "Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime"
+ type: string
+ matchPattern:
+ docs: "Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use `(?i)^modelname$`"
+ type: string
+ startDate:
+ docs: Apply only to generations which are newer than this ISO date.
+ type: optional<date>
+ unit:
+ docs: Unit used by this model.
+ type: ModelUsageUnit
+ inputPrice:
+ docs: Price (USD) per input unit
+ type: optional<double>
+ outputPrice:
+ docs: Price (USD) per output unit
+ type: optional<double>
+ totalPrice:
+ docs: Price (USD) per total unit. Cannot be set if input or output price is set.
+ type: optional<double>
+ tokenizerId:
+ docs: Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.
+ type: optional<string>
+ tokenizerConfig:
+ docs: Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.
+ type: optional<unknown>
+ isLangfuseManaged:
+ type: boolean
# Utilities
ModelUsageUnit:
diff --git a/fern/apis/server/definition/models.yml b/fern/apis/server/definition/models.yml
new file mode 100644
index 0000000000..d34e10149a
--- /dev/null
+++ b/fern/apis/server/definition/models.yml
@@ -0,0 +1,76 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ commons: ./commons.yml
+ pagination: ./utils/pagination.yml
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ create:
+ method: POST
+ docs: Create a model
+ path: /models
+ request: CreateModelRequest
+ response: commons.Model
+ list:
+ method: GET
+ docs: Get all models
+ path: /models
+ request:
+ name: GetModelsRequest
+ query-parameters:
+ page:
+ type: optional<integer>
+ docs: page number, starts at 1
+ limit:
+ type: optional<integer>
+ docs: limit of items per page
+ response: PaginatedModels
+ get:
+ method: GET
+ docs: Get a model
+ path: /models/{id}
+ path-parameters:
+ id: string
+ response: commons.Model
+ delete:
+ method: DELETE
+ docs: Create a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though.
+ path: /models/{id}
+ path-parameters:
+ id: string
+
+types:
+ PaginatedModels:
+ properties:
+ data: list<commons.Model>
+ meta: pagination.MetaResponse
+ CreateModelRequest:
+ properties:
+ modelName:
+ docs: "Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime"
+ type: string
+ matchPattern:
+ docs: "Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use `(?i)^modelname$`"
+ type: string
+ startDate:
+ docs: Apply only to generations which are newer than this ISO date.
+ type: optional<date>
+ unit:
+ docs: Unit used by this model.
+ type: commons.ModelUsageUnit
+ inputPrice:
+ docs: Price (USD) per input unit
+ type: optional<double>
+ outputPrice:
+ docs: Price (USD) per output unit
+ type: optional<double>
+ totalPrice:
+ docs: Price (USD) per total units. Cannot be set if input or output price is set.
+ type: optional<double>
+ tokenizerId:
+ docs: Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.
+ type: optional<string>
+ tokenizerConfig:
+ docs: Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.
+ type: optional<unknown>
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 8c536ebcd3..1785bd575d 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -699,6 +699,193 @@ paths:
application/json:
schema: {}
security: *ref_0
+ /api/public/models:
+ post:
+ description: Create a model
+ operationId: models_create
+ tags:
+ - Models
+ parameters: []
+ 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 all models
+ operationId: models_list
+ tags:
+ - Models
+ parameters:
+ - name: page
+ in: query
+ description: page number, starts at 1
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ - name: limit
+ in: query
+ description: limit of items per page
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PaginatedModels'
+ '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
+ /api/public/models/{id}:
+ get:
+ description: Get a model
+ operationId: models_get
+ 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
+ delete:
+ description: >-
+ Create a model. Cannot delete models managed by Langfuse. You can create
+ your own definition with the same modelName to override the definition
+ though.
+ operationId: models_delete
+ tags:
+ - Models
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '204':
+ description: ''
+ '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
/api/public/observations/{observationId}:
get:
description: Get a observation
@@ -2086,6 +2273,71 @@ components:
- datasetRunItems
allOf:
- $ref: '#/components/schemas/DatasetRun'
+ Model:
+ title: Model
+ type: object
+ description: >-
+ Model definition used for transforming usage into USD cost and/or
+ tokenization.
+ properties:
+ id:
+ type: string
+ modelName:
+ type: string
+ description: >-
+ Name of the model definition. If multiple with the same name exist,
+ they are applied in the following order: (1) custom over built-in,
+ (2) newest according to startTime where
+ model.startTime<observation.startTime
+ matchPattern:
+ type: string
+ description: >-
+ Regex pattern which matches this model definition to
+ generation.model. Useful in case of fine-tuned models. If you want
+ to exact match, use `(?i)^modelname$`
+ startDate:
+ type: string
+ nullable: true
+ description: Apply only to generations which are newer than this ISO date.
+ unit:
+ $ref: '#/components/schemas/ModelUsageUnit'
+ description: Unit used by this model.
+ inputPrice:
+ type: number
+ format: double
+ nullable: true
+ description: Price (USD) per input unit
+ outputPrice:
+ type: number
+ format: double
+ nullable: true
+ description: Price (USD) per output unit
+ totalPrice:
+ type: number
+ format: double
+ nullable: true
+ description: >-
+ Price (USD) per total unit. Cannot be set if input or output price
+ is set.
+ tokenizerId:
+ type: string
+ nullable: true
+ description: >-
+ Optional. Tokenizer to be applied to observations which match to
+ this model. See docs for more details.
+ tokenizerConfig:
+ nullable: true
+ description: >-
+ Optional. Configuration for the selected tokenizer. Needs to be
+ JSON. See docs for more details.
+ isLangfuseManaged:
+ type: boolean
+ required:
+ - id
+ - modelName
+ - matchPattern
+ - unit
+ - isLangfuseManaged
ModelUsageUnit:
title: ModelUsageUnit
type: string
@@ -2888,6 +3140,75 @@ components:
- countTraces
- countObservations
- totalCost
+ PaginatedModels:
+ title: PaginatedModels
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/Model'
+ meta:
+ $ref: '#/components/schemas/utilsMetaResponse'
+ required:
+ - data
+ - meta
+ CreateModelRequest:
+ title: CreateModelRequest
+ type: object
+ properties:
+ modelName:
+ type: string
+ description: >-
+ Name of the model definition. If multiple with the same name exist,
+ they are applied in the following order: (1) custom over built-in,
+ (2) newest according to startTime where
+ model.startTime<observation.startTime
+ matchPattern:
+ type: string
+ description: >-
+ Regex pattern which matches this model definition to
+ generation.model. Useful in case of fine-tuned models. If you want
+ to exact match, use `(?i)^modelname$`
+ startDate:
+ type: string
+ nullable: true
+ description: Apply only to generations which are newer than this ISO date.
+ unit:
+ $ref: '#/components/schemas/ModelUsageUnit'
+ description: Unit used by this model.
+ inputPrice:
+ type: number
+ format: double
+ nullable: true
+ description: Price (USD) per input unit
+ outputPrice:
+ type: number
+ format: double
+ nullable: true
+ description: Price (USD) per output unit
+ totalPrice:
+ type: number
+ format: double
+ nullable: true
+ description: >-
+ Price (USD) per total units. Cannot be set if input or output price
+ is set.
+ tokenizerId:
+ type: string
+ nullable: true
+ description: >-
+ Optional. Tokenizer to be applied to observations which match to
+ this model. See docs for more details.
+ tokenizerConfig:
+ nullable: true
+ description: >-
+ Optional. Configuration for the selected tokenizer. Needs to be
+ JSON. See docs for more details.
+ required:
+ - modelName
+ - matchPattern
+ - unit
Observations:
title: Observations
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 03acbb3821..932a9c842f 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -535,6 +535,146 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Models",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Create",
+ "request": {
+ "description": "Create a model",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/models",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "models"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "POST",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"modelName\": \"example\",\n \"matchPattern\": \"example\",\n \"startDate\": \"1994-11-05\",\n \"unit\": \"CHARACTERS\",\n \"inputPrice\": 0,\n \"outputPrice\": 0,\n \"totalPrice\": 0,\n \"tokenizerId\": \"example\",\n \"tokenizerConfig\": \"UNKNOWN\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "List",
+ "request": {
+ "description": "Get all models",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/models?page=&limit=",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "models"
+ ],
+ "query": [
+ {
+ "key": "page",
+ "value": "",
+ "description": "page number, starts at 1"
+ },
+ {
+ "key": "limit",
+ "value": "",
+ "description": "limit of items per page"
+ }
+ ],
+ "variable": []
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Get",
+ "request": {
+ "description": "Get a model",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/models/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "models",
+ ":id"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "id",
+ "value": "",
+ "description": null
+ }
+ ]
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Delete",
+ "request": {
+ "description": "Create a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though.",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/models/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "models",
+ ":id"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "id",
+ "value": "",
+ "description": null
+ }
+ ]
+ },
+ "header": [],
+ "method": "DELETE",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
diff --git a/web/src/__tests__/model-definitions.servertest.ts b/web/src/__tests__/model-definitions.servertest.ts
new file mode 100644
index 0000000000..297d3beaf3
--- /dev/null
+++ b/web/src/__tests__/model-definitions.servertest.ts
@@ -0,0 +1,221 @@
+/** @jest-environment node */
+
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
+import {
+ DeleteModelV1Response,
+ GetModelV1Response,
+ GetModelsV1Response,
+ PostModelsV1Response,
+} from "@/src/features/public-api/types/models";
+
+describe("/models API Endpoints", () => {
+ beforeEach(async () => {
+ await pruneDatabase();
+ // create some default models that do not belong to a project
+ await prisma.model.create({
+ data: {
+ id: "model-1",
+ modelName: "gpt-3.5-turbo",
+ inputPrice: "0.0010",
+ outputPrice: "0.0020",
+ totalPrice: "0.1",
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ startDate: new Date("2023-12-02"),
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ unit: "TOKENS",
+ },
+ });
+ await prisma.model.create({
+ data: {
+ id: "model-2",
+ modelName: "gpt-3.5-turbo",
+ inputPrice: "0.0020",
+ outputPrice: "0.0040",
+ totalPrice: undefined,
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ startDate: new Date("2023-12-01"),
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ unit: "TOKENS",
+ },
+ });
+ });
+ afterEach(async () => await pruneDatabase());
+
+ it("GET /models", async () => {
+ const models = await makeZodVerifiedAPICall(
+ GetModelsV1Response,
+ "GET",
+ "/api/public/models",
+ );
+ expect(models.status).toBe(200);
+ expect(models.body.data.length).toBe(2);
+ expect(models.body.data[0]).toMatchObject({
+ isLangfuseManaged: true,
+ modelName: "gpt-3.5-turbo",
+ });
+ });
+
+ it("GET /models pagination", async () => {
+ const models = await makeZodVerifiedAPICall(
+ GetModelsV1Response,
+ "GET",
+ "/api/public/models?page=2&limit=1",
+ );
+ expect(models.status).toBe(200);
+ expect(models.body.data.length).toBe(1);
+ expect(models.body.meta).toMatchObject({
+ page: 2,
+ totalPages: 2,
+ limit: 1,
+ totalItems: 2,
+ });
+ });
+
+ it("Create and get custom model", async () => {
+ const customModel = await makeZodVerifiedAPICall(
+ PostModelsV1Response,
+ "POST",
+ "/api/public/models",
+ {
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ startDate: "2023-12-01",
+ inputPrice: 0.002,
+ outputPrice: 0.004,
+ unit: "TOKENS",
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ },
+ );
+ expect(customModel.body.isLangfuseManaged).toBe(false);
+
+ const models = await makeZodVerifiedAPICall(
+ GetModelsV1Response,
+ "GET",
+ "/api/public/models",
+ );
+ expect(models.body.data.length).toBe(3);
+
+ const getModel = await makeZodVerifiedAPICall(
+ GetModelV1Response,
+ "GET",
+ `/api/public/models/${customModel.body.id}`,
+ );
+ expect(getModel.body.id).toBe(customModel.body.id);
+ expect(getModel.body).toMatchObject({
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ startDate: new Date("2023-12-01").toISOString(),
+ inputPrice: 0.002,
+ outputPrice: 0.004,
+ unit: "TOKENS",
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ isLangfuseManaged: false,
+ });
+ });
+
+ it("Post model with invalid matchPattern", async () => {
+ const customModel = await makeAPICall("POST", "/api/public/models", {
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "[][", // brackets not balanced
+ startDate: "2023-12-01",
+ inputPrice: 0.002,
+ outputPrice: 0.004,
+ unit: "TOKENS",
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ });
+ 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",
+ },
+ );
+ });
+
+ it("Post model with missing fields", async () => {
+ const { status } = await makeAPICall("POST", "/api/public/models", {
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ // missing unit
+ });
+ expect(status).toBe(400);
+ });
+
+ it("Post model with invalid price (input and total cost)", async () => {
+ const customModel = await makeAPICall("POST", "/api/public/models", {
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "[][", // brackets not balanced
+ startDate: "2023-12-01",
+ inputPrice: 0.002,
+ outputPrice: 0.004,
+ totalPrice: 0.1,
+ unit: "TOKENS",
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ });
+ expect(customModel.status).toBe(400);
+ });
+
+ it("Cannot delete built-in models", async () => {
+ const models = await makeZodVerifiedAPICall(
+ GetModelsV1Response,
+ "GET",
+ "/api/public/models",
+ );
+ expect(models.body.data.length).toBe(2);
+
+ const deleteModel = await makeAPICall(
+ "DELETE",
+ `/api/public/models/${models.body.data[0].id}`,
+ );
+ expect(deleteModel.status).toBe(404);
+ });
+
+ it("Delete custom model", async () => {
+ const customModel = await makeZodVerifiedAPICall(
+ PostModelsV1Response,
+ "POST",
+ "/api/public/models",
+ {
+ modelName: "gpt-3.5-turbo",
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ startDate: "2023-12-01",
+ inputPrice: 0.002,
+ outputPrice: 0.004,
+ unit: "TOKENS",
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ },
+ );
+
+ const models = await makeZodVerifiedAPICall(
+ GetModelsV1Response,
+ "GET",
+ "/api/public/models",
+ );
+ expect(models.body.data.length).toBe(3);
+
+ await makeZodVerifiedAPICall(
+ DeleteModelV1Response,
+ "DELETE",
+ `/api/public/models/${customModel.body.id}`,
+ );
+
+ const modelsAfterDelete = await makeZodVerifiedAPICall(
+ GetModelsV1Response,
+ "GET",
+ "/api/public/models",
+ );
+ expect(modelsAfterDelete.body.data.length).toBe(2);
+ });
+});
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index ea41c49772..46814b8dbd 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -82,10 +82,22 @@ export async function makeZodVerifiedAPICall<T extends z.ZodTypeAny>(
auth?: string,
): Promise<{ body: z.infer<T>; status: number }> {
const { body: resBody, status } = await makeAPICall(method, url, body, auth);
- if (responseZodSchema instanceof ZodObject) {
- responseZodSchema.strict().parse(resBody);
- } else {
- responseZodSchema.parse(resBody);
+ if (status !== 200) {
+ throw new Error(
+ `API call did not return 200, returned status ${status}, body ${JSON.stringify(resBody)}`,
+ );
+ }
+ try {
+ if (responseZodSchema instanceof ZodObject) {
+ responseZodSchema.strict().parse(resBody);
+ } else {
+ responseZodSchema.parse(resBody);
+ }
+ } catch (e) {
+ console.error(e);
+ throw new Error(
+ `API call (${method} ${url}) did not return valid response, returned status ${status}, body ${JSON.stringify(resBody)}, error ${e}`,
+ );
}
return { body: resBody, status };
}
diff --git a/web/src/features/models/server/isValidPostgresRegex.ts b/web/src/features/models/server/isValidPostgresRegex.ts
new file mode 100644
index 0000000000..a3c4c392f2
--- /dev/null
+++ b/web/src/features/models/server/isValidPostgresRegex.ts
@@ -0,0 +1,13 @@
+import { Prisma, type prisma as _prisma } from "@langfuse/shared/src/db";
+
+export const isValidPostgresRegex = async (
+ regex: string,
+ prisma: typeof _prisma,
+): Promise<boolean> => {
+ try {
+ await prisma.$queryRaw(Prisma.sql`SELECT 'test_string' ~ ${regex}`);
+ return true;
+ } catch {
+ return false;
+ }
+};
diff --git a/web/src/features/public-api/types/models.ts b/web/src/features/public-api/types/models.ts
new file mode 100644
index 0000000000..7faa056bd7
--- /dev/null
+++ b/web/src/features/public-api/types/models.ts
@@ -0,0 +1,105 @@
+import {
+ type ModelUsageUnit,
+ paginationMetaResponseZod,
+ paginationZod,
+ type Model as PrismaModel,
+ jsonSchema,
+} from "@langfuse/shared";
+import { z } from "zod";
+
+/**
+ * Objects
+ */
+
+const ModelDefinition = z.object({
+ id: z.string(),
+ modelName: z.string(),
+ matchPattern: z.string(),
+ startDate: z.coerce.date().nullable(),
+ inputPrice: z.number().nonnegative().nullable(),
+ outputPrice: z.number().nonnegative().nullable(),
+ totalPrice: z.number().nonnegative().nullable(),
+ unit: z.enum(["TOKENS", "CHARACTERS", "MILLISECONDS", "SECONDS", "IMAGES"]),
+ tokenizerId: z.string().nullable(),
+ tokenizerConfig: z.any(), // Assuming Prisma.JsonValue is any type
+ isLangfuseManaged: z.boolean(),
+ createdAt: z.coerce.date(),
+});
+
+/**
+ * Transforms
+ */
+
+export function prismaToApiModelDefinition({
+ projectId,
+ inputPrice,
+ outputPrice,
+ totalPrice,
+ unit,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ updatedAt,
+ ...model
+}: PrismaModel): z.infer<typeof ModelDefinition> {
+ return {
+ ...model,
+ unit: unit as ModelUsageUnit,
+ inputPrice: inputPrice?.toNumber() ?? null,
+ outputPrice: outputPrice?.toNumber() ?? null,
+ totalPrice: totalPrice?.toNumber() ?? null,
+ isLangfuseManaged: !Boolean(projectId),
+ };
+}
+
+/**
+ * Endpoints
+ */
+
+// GET /models
+export const GetModelsV1Query = z.object({
+ ...paginationZod,
+});
+export const GetModelsV1Response = z.object({
+ data: z.array(ModelDefinition),
+ meta: paginationMetaResponseZod,
+});
+
+// POST /models
+export const PostModelsV1Body = z
+ .object({
+ modelName: z.string(),
+ matchPattern: z.string(),
+ startDate: z.coerce.date().nullish(),
+ inputPrice: z.number().nonnegative().nullish(),
+ outputPrice: z.number().nonnegative().nullish(),
+ totalPrice: z.number().nonnegative().nullish(),
+ unit: z.enum(["TOKENS", "CHARACTERS", "MILLISECONDS", "SECONDS", "IMAGES"]),
+ tokenizerId: z.enum(["openai", "claude"]).nullish(),
+ tokenizerConfig: jsonSchema.nullish(), // Assuming Prisma.JsonValue is any type
+ })
+ .refine(
+ ({ inputPrice, outputPrice, totalPrice }) => {
+ if (inputPrice || outputPrice) {
+ return !totalPrice;
+ }
+ return true;
+ },
+ {
+ path: ["totalPrice"],
+ message: "If input and/or output price is set, total price must be null",
+ },
+ );
+export const PostModelsV1Response = ModelDefinition;
+
+// GET /models/{modelId}
+export const GetModelV1Query = z.object({
+ modelId: z.string(),
+});
+export const GetModelV1Response = ModelDefinition;
+
+// DELETE /models/{modelId}
+export const DeleteModelV1Query = z.object({
+ modelId: z.string(),
+});
+export const DeleteModelV1Response = z.object({
+ message: z.literal("Model successfully deleted"),
+});
diff --git a/web/src/pages/api/public/models/[modelId]/index.ts b/web/src/pages/api/public/models/[modelId]/index.ts
new file mode 100644
index 0000000000..52fb4b3c5c
--- /dev/null
+++ b/web/src/pages/api/public/models/[modelId]/index.ts
@@ -0,0 +1,71 @@
+import { prisma } from "@langfuse/shared/src/db";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import {
+ DeleteModelV1Query,
+ DeleteModelV1Response,
+ GetModelV1Query,
+ GetModelV1Response,
+ prismaToApiModelDefinition,
+} from "@/src/features/public-api/types/models";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get model definitions",
+ querySchema: GetModelV1Query,
+ responseSchema: GetModelV1Response,
+ fn: async ({ query, auth }) => {
+ const model = await prisma.model.findFirst({
+ where: {
+ AND: [
+ {
+ id: query.modelId,
+ },
+ {
+ OR: [
+ {
+ projectId: auth.scope.projectId,
+ },
+ {
+ projectId: null,
+ },
+ ],
+ },
+ ],
+ },
+ });
+ if (!model) {
+ throw new LangfuseNotFoundError("No model with this id found.");
+ }
+ return prismaToApiModelDefinition(model);
+ },
+ }),
+ DELETE: createAuthedAPIRoute({
+ name: "Delete model",
+ querySchema: DeleteModelV1Query,
+ responseSchema: DeleteModelV1Response,
+ fn: async ({ query, auth }) => {
+ const model = await prisma.model.findFirst({
+ where: {
+ id: query.modelId,
+ projectId: auth.scope.projectId,
+ },
+ });
+ if (!model) {
+ throw new LangfuseNotFoundError(
+ "No model with this id found. Note: You cannot delete built-in models, override them with a model with the same name.",
+ );
+ }
+ await prisma.model.delete({
+ where: {
+ id: query.modelId,
+ projectId: auth.scope.projectId,
+ },
+ });
+ return {
+ message: "Model successfully deleted" as const,
+ };
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/models/index.ts b/web/src/pages/api/public/models/index.ts
new file mode 100644
index 0000000000..750c45510f
--- /dev/null
+++ b/web/src/pages/api/public/models/index.ts
@@ -0,0 +1,91 @@
+import { prisma } from "@langfuse/shared/src/db";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import {
+ GetModelsV1Query,
+ GetModelsV1Response,
+ PostModelsV1Body,
+ PostModelsV1Response,
+ prismaToApiModelDefinition,
+} from "@/src/features/public-api/types/models";
+import { InvalidRequestError } from "@langfuse/shared";
+import { isValidPostgresRegex } from "@/src/features/models/server/isValidPostgresRegex";
+
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get model definitions",
+ querySchema: GetModelsV1Query,
+ responseSchema: GetModelsV1Response,
+ fn: async ({ query, auth }) => {
+ const models = await prisma.model.findMany({
+ where: {
+ OR: [
+ {
+ projectId: auth.scope.projectId,
+ },
+ {
+ projectId: null,
+ },
+ ],
+ },
+ orderBy: [
+ { modelName: "asc" },
+ { unit: "asc" },
+ {
+ startDate: {
+ sort: "desc",
+ nulls: "last",
+ },
+ },
+ ],
+ take: query.limit,
+ skip: (query.page - 1) * query.limit,
+ });
+
+ const totalItems = await prisma.model.count({
+ where: {
+ OR: [
+ {
+ projectId: auth.scope.projectId,
+ },
+ {
+ projectId: null,
+ },
+ ],
+ },
+ });
+
+ return {
+ data: models.map(prismaToApiModelDefinition),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / query.limit),
+ },
+ };
+ },
+ }),
+ POST: createAuthedAPIRoute({
+ name: "Create custom model definition",
+ bodySchema: PostModelsV1Body,
+ responseSchema: PostModelsV1Response,
+ fn: async ({ body, auth }) => {
+ const validRegex = await isValidPostgresRegex(body.matchPattern, prisma);
+ if (!validRegex) {
+ throw new InvalidRequestError(
+ "matchPattern is not a valid regex pattern (Postgres)",
+ );
+ }
+ const { tokenizerConfig, ...rest } = body;
+ const model = await prisma.model.create({
+ data: {
+ ...rest,
+ tokenizerConfig: tokenizerConfig ?? undefined,
+ projectId: auth.scope.projectId,
+ },
+ });
+ return prismaToApiModelDefinition(model);
+ },
+ }),
+});
diff --git a/web/src/server/api/routers/models.ts b/web/src/server/api/routers/models.ts
index aa063ac0b8..7f9c020f14 100644
--- a/web/src/server/api/routers/models.ts
+++ b/web/src/server/api/routers/models.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { ModelUsageUnit, Prisma } from "@langfuse/shared";
+import { ModelUsageUnit } from "@langfuse/shared";
import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
import {
createTRPCRouter,
@@ -9,6 +9,7 @@ import {
import { paginationZod } from "@langfuse/shared";
import { TRPCError } from "@trpc/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { isValidPostgresRegex } from "@/src/features/models/server/isValidPostgresRegex";
const ModelAllOptions = z.object({
projectId: z.string(),
@@ -119,11 +120,12 @@ export const modelRouter = createTRPCRouter({
// Check if regex is valid POSIX regex
// Use DB to check, because JS regex is not POSIX compliant
- try {
- await ctx.prisma.$queryRaw(
- Prisma.sql`SELECT 'test_string' ~ ${input.matchPattern}`,
- );
- } catch (error) {
+
+ const isValidRegex = await isValidPostgresRegex(
+ input.matchPattern,
+ ctx.prisma,
+ );
+ if (!isValidRegex) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Invalid regex, needs to be Postgres syntax",