🪢 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: revamp pricing and cost (#901)
Max Deichmannf2405f156134
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex 7f3144af8e..9bdb5bf36f 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -67,6 +67,9 @@ types:output: optional<integer>total: optional<integer>unit: optional<ModelUsageUnit>+ inputCost: optional<double>+ outputCost: optional<double>+ totalCost: optional<double>Score:properties:id: stringdiff --git a/fern/fern.config.json b/fern/fern.config.jsonindex 0d37ac4603..91d00f7b1c 100644--- a/fern/fern.config.json+++ b/fern/fern.config.json@@ -1,4 +1,4 @@{"organization": "finto",- "version": "0.16.22"+ "version": "0.16.36"}\ No newline at end of filediff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.ymlindex a6b7e7169f..6a82131834 100644--- a/generated/openapi-server/openapi.yml+++ b/generated/openapi-server/openapi.yml@@ -1119,6 +1119,18 @@ components:unit:$ref: '#/components/schemas/ModelUsageUnit'nullable: true+ inputCost:+ type: number+ format: double+ nullable: true+ outputCost:+ type: number+ format: double+ nullable: true+ totalCost:+ type: number+ format: double+ nullable: trueScore:title: Scoretype: objectdiff --git a/package-lock.json b/package-lock.jsonindex d1e71b8363..765339068d 100644--- a/package-lock.json+++ b/package-lock.json@@ -118,6 +118,7 @@"tailwindcss": "^3.4.1","ts-node": "^10.9.2","tsconfig-paths": "^4.2.0",+ "tsx": "^4.7.0","typescript": "^5.3.3"},"optionalDependencies": {@@ -1652,6 +1653,374 @@"@jridgewell/sourcemap-codec": "^1.4.10"}},+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.11.tgz",+ "integrity": "sha512-FnzU0LyE3ySQk7UntJO4+qIiQgI7KoODnZg5xzXIrFJlKd2P2gwHsHY4927xj9y5PJmJSzULiUCWmv7iWnNa7g==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.11.tgz",+ "integrity": "sha512-5OVapq0ClabvKvQ58Bws8+wkLCV+Rxg7tUVbo9xu034Nm536QTII4YzhaFriQ7rMrorfnFKUsArD2lqKbFY4vw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.11.tgz",+ "integrity": "sha512-aiu7K/5JnLj//KOnOfEZ0D90obUkRzDMyqd/wNAUQ34m4YUPVhRZpnqKV9uqDGxT7cToSDnIHsGooyIczu9T+Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.11.tgz",+ "integrity": "sha512-eccxjlfGw43WYoY9QgB82SgGgDbibcqyDTlk3l3C0jOVHKxrjdc9CTwDUQd0vkvYg5um0OH+GpxYvp39r+IPOg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.11.tgz",+ "integrity": "sha512-ETp87DRWuSt9KdDVkqSoKoLFHYTrkyz2+65fj9nfXsaV3bMhTCjtQfw3y+um88vGRKRiF7erPrh/ZuIdLUIVxQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.11.tgz",+ "integrity": "sha512-fkFUiS6IUK9WYUO/+22omwetaSNl5/A8giXvQlcinLIjVkxwTLSktbF5f/kJMftM2MJp9+fXqZ5ezS7+SALp4g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.11.tgz",+ "integrity": "sha512-lhoSp5K6bxKRNdXUtHoNc5HhbXVCS8V0iZmDvyWvYq9S5WSfTIHU2UGjcGt7UeS6iEYp9eeymIl5mJBn0yiuxA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.11.tgz",+ "integrity": "sha512-JkUqn44AffGXitVI6/AbQdoYAq0TEullFdqcMY/PCUZ36xJ9ZJRtQabzMA+Vi7r78+25ZIBosLTOKnUXBSi1Kw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.11.tgz",+ "integrity": "sha512-3CRkr9+vCV2XJbjwgzjPtO8T0SZUmRZla+UL1jw+XqHZPkPgZiyWvbDvl9rqAN8Zl7qJF0O/9ycMtjU67HN9/Q==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.11.tgz",+ "integrity": "sha512-LneLg3ypEeveBSMuoa0kwMpCGmpu8XQUh+mL8XXwoYZ6Be2qBnVtcDI5azSvh7vioMDhoJFZzp9GWp9IWpYoUg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.11.tgz",+ "integrity": "sha512-caHy++CsD8Bgq2V5CodbJjFPEiDPq8JJmBdeyZ8GWVQMjRD0sU548nNdwPNvKjVpamYYVL40AORekgfIubwHoA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.11.tgz",+ "integrity": "sha512-ppZSSLVpPrwHccvC6nQVZaSHlFsvCQyjnvirnVjbKSHuE5N24Yl8F3UwYUUR1UEPaFObGD2tSvVKbvR+uT1Nrg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.11.tgz",+ "integrity": "sha512-B5x9j0OgjG+v1dF2DkH34lr+7Gmv0kzX6/V0afF41FkPMMqaQ77pH7CrhWeR22aEeHKaeZVtZ6yFwlxOKPVFyg==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.11.tgz",+ "integrity": "sha512-MHrZYLeCG8vXblMetWyttkdVRjQlQUb/oMgBNurVEnhj4YWOr4G5lmBfZjHYQHHN0g6yDmCAQRR8MUHldvvRDA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.11.tgz",+ "integrity": "sha512-f3DY++t94uVg141dozDu4CCUkYW+09rWtaWfnb3bqe4w5NqmZd6nPVBm+qbz7WaHZCoqXqHz5p6CM6qv3qnSSQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.11.tgz",+ "integrity": "sha512-A5xdUoyWJHMMlcSMcPGVLzYzpcY8QP1RtYzX5/bS4dvjBGVxdhuiYyFwp7z74ocV7WDc0n1harxmpq2ePOjI0Q==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.11.tgz",+ "integrity": "sha512-grbyMlVCvJSfxFQUndw5mCtWs5LO1gUlwP4CDi4iJBbVpZcqLVT29FxgGuBJGSzyOxotFG4LoO5X+M1350zmPA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.11.tgz",+ "integrity": "sha512-13jvrQZJc3P230OhU8xgwUnDeuC/9egsjTkXN49b3GcS5BKvJqZn86aGM8W9pd14Kd+u7HuFBMVtrNGhh6fHEQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.11.tgz",+ "integrity": "sha512-ysyOGZuTp6SNKPE11INDUeFVVQFrhcNDVUgSQVDzqsqX38DjhPEPATpid04LCoUr2WXhQTEZ8ct/EgJCUDpyNw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.11.tgz",+ "integrity": "sha512-Hf+Sad9nVwvtxy4DXCZQqLpgmRTQqyFyhT3bZ4F2XlJCjxGmRFF0Shwn9rzhOYRB61w9VMXUkxlBy56dk9JJiQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.11.tgz",+ "integrity": "sha512-0P58Sbi0LctOMOQbpEOvOL44Ne0sqbS0XWHMvvrg6NE5jQ1xguCSSw9jQeUk2lfrXYsKDdOe6K+oZiwKPilYPQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.11.tgz",+ "integrity": "sha512-6YOrWS+sDJDmshdBIQU+Uoyh7pQKrdykdefC1avn76ss5c+RN6gut3LZA4E2cH5xUEp5/cA0+YxRaVtRAb0xBg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.11.tgz",+ "integrity": "sha512-vfkhltrjCAb603XaFhqhAF4LGDi2M4OrCRrFusyQ+iTLQ/o60QQXxc9cZC/FFpihBI9N1Grn6SMKVJ4KP7Fuiw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },"node_modules/@eslint-community/eslint-utils": {"version": "4.4.0","resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz",@@ -9514,6 +9883,44 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/esbuild": {+ "version": "0.19.11",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz",+ "integrity": "sha512-HJ96Hev2hX/6i5cDVwcqiJBBtuo9+FeIJOtZ9W1kA5M6AMJRHUZlpYZ1/SbEwtO0ioNAW8rUooVpC/WehY2SfA==",+ "dev": true,+ "hasInstallScript": true,+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=12"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.19.11",+ "@esbuild/android-arm": "0.19.11",+ "@esbuild/android-arm64": "0.19.11",+ "@esbuild/android-x64": "0.19.11",+ "@esbuild/darwin-arm64": "0.19.11",+ "@esbuild/darwin-x64": "0.19.11",+ "@esbuild/freebsd-arm64": "0.19.11",+ "@esbuild/freebsd-x64": "0.19.11",+ "@esbuild/linux-arm": "0.19.11",+ "@esbuild/linux-arm64": "0.19.11",+ "@esbuild/linux-ia32": "0.19.11",+ "@esbuild/linux-loong64": "0.19.11",+ "@esbuild/linux-mips64el": "0.19.11",+ "@esbuild/linux-ppc64": "0.19.11",+ "@esbuild/linux-riscv64": "0.19.11",+ "@esbuild/linux-s390x": "0.19.11",+ "@esbuild/linux-x64": "0.19.11",+ "@esbuild/netbsd-x64": "0.19.11",+ "@esbuild/openbsd-x64": "0.19.11",+ "@esbuild/sunos-x64": "0.19.11",+ "@esbuild/win32-arm64": "0.19.11",+ "@esbuild/win32-ia32": "0.19.11",+ "@esbuild/win32-x64": "0.19.11"+ }+ },"node_modules/escalade": {"version": "3.1.1","resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz",@@ -17534,6 +17941,25 @@"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz","integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="},+ "node_modules/tsx": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.7.0.tgz",+ "integrity": "sha512-I+t79RYPlEYlHn9a+KzwrvEwhJg35h/1zHsLC2JXvhC2mdynMv6Zxzvhv5EMV6VF5qJlLlkSnMVvdZV3PSIGcg==",+ "dev": true,+ "dependencies": {+ "esbuild": "~0.19.10",+ "get-tsconfig": "^4.7.2"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },"node_modules/type-check": {"version": "0.4.0","resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",diff --git a/package.json b/package.jsonindex 83db606480..460c69243b 100644--- a/package.json+++ b/package.json@@ -20,7 +20,8 @@"db:reset": "npx prisma migrate reset","db:seed": "npx prisma db seed","db:seed:examples": "npx prisma db seed -- --environment examples",- "release": "release-it"+ "release": "release-it",+ "models:migrate": "tsx scripts/model-match.ts"},"prisma": {"seed": "ts-node -r tsconfig-paths/register --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"@@ -135,6 +136,7 @@"tailwindcss": "^3.4.1","ts-node": "^10.9.2","tsconfig-paths": "^4.2.0",+ "tsx": "^4.7.0","typescript": "^5.3.3"},"ct3aMetadata": {diff --git a/prisma/migrations/20240117165747_add_cost_to_observations/migration.sql b/prisma/migrations/20240117165747_add_cost_to_observations/migration.sqlnew file mode 100644index 0000000000..233ea9ff8e--- /dev/null+++ b/prisma/migrations/20240117165747_add_cost_to_observations/migration.sql@@ -0,0 +1,4 @@+-- AlterTable+ALTER TABLE "observations" ADD COLUMN "input_cost" DECIMAL(65,30),+ADD COLUMN "output_cost" DECIMAL(65,30),+ADD COLUMN "total_cost" DECIMAL(65,30);diff --git a/prisma/migrations/20240118204639_add_models_table/migration.sql b/prisma/migrations/20240118204639_add_models_table/migration.sqlnew file mode 100644index 0000000000..e51a802591--- /dev/null+++ b/prisma/migrations/20240118204639_add_models_table/migration.sql@@ -0,0 +1,20 @@+-- CreateTable+CREATE TABLE "models" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT,+ "model_name" TEXT NOT NULL,+ "match_pattern" TEXT NOT NULL,+ "start_date" TIMESTAMP(3),+ "input_price" DECIMAL(65,30),+ "output_price" DECIMAL(65,30),+ "total_price" DECIMAL(65,30),+ "unit" TEXT NOT NULL DEFAULT 'TOKENS',+ "tokenizer_config" JSONB NOT NULL,++ CONSTRAINT "models_pkey" PRIMARY KEY ("id")+);++-- AddForeignKey+ALTER TABLE "models" ADD CONSTRAINT "models_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/prisma/migrations/20240118204936_add_internal_model/migration.sql b/prisma/migrations/20240118204936_add_internal_model/migration.sqlnew file mode 100644index 0000000000..51098ce2c7--- /dev/null+++ b/prisma/migrations/20240118204936_add_internal_model/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "observations" ADD COLUMN "internal_model" TEXT;diff --git a/prisma/migrations/20240118204937_add_observations_view/migration.sql b/prisma/migrations/20240118204937_add_observations_view/migration.sqlnew file mode 100644index 0000000000..d97bb0d016--- /dev/null+++ b/prisma/migrations/20240118204937_add_observations_view/migration.sql@@ -0,0 +1,49 @@+CREATE VIEW "observations_view" AS+SELECT+ o.*,+ m.id AS "model_id",+ m.start_date AS "model_start_date",+ m.input_price,+ m.output_price,+ m.total_price,+ m.tokenizer_config AS "tokenizer_config",+ CASE+ WHEN o.input_cost IS NULL AND o.output_cost IS NULL AND o.total_cost IS NULL THEN+ o.prompt_tokens::decimal * m.input_price+ ELSE+ o.input_cost+ END AS "calculated_input_cost",+ CASE+ WHEN o.input_cost IS NULL AND o.output_cost IS NULL AND o.total_cost IS NULL THEN+ o.completion_tokens::decimal * m.output_price+ ELSE+ o.output_cost+ END AS "calculated_output_cost",+ CASE+ WHEN o.input_cost IS NULL AND o.output_cost IS NULL AND o.total_cost IS NULL THEN+ CASE+ WHEN m.total_price IS NOT NULL AND o.total_tokens IS NOT NULL THEN+ m.total_price * o.total_tokens+ ELSE+ o.prompt_tokens::decimal * m.input_price ++ o.completion_tokens::decimal * m.output_price+ END+ ELSE+ o.total_cost+ END AS "calculated_total_cost"+FROM+ observations o+LEFT JOIN models m ON m.id = (+ SELECT+ id+ FROM+ models+ WHERE (project_id = o.project_id OR project_id IS NULL)+ AND model_name = o.internal_model+ AND (start_date < o.start_time OR start_date is NULL)+ AND o.unit::TEXT = unit+ ORDER BY+ project_id ASC, -- in postgres, NULLs are sorted first+ start_date DESC+ LIMIT 1+)diff --git a/prisma/migrations/20240118235424_add_index_to_models/migration.sql b/prisma/migrations/20240118235424_add_index_to_models/migration.sqlnew file mode 100644index 0000000000..5fa72dd3ff--- /dev/null+++ b/prisma/migrations/20240118235424_add_index_to_models/migration.sql@@ -0,0 +1,11 @@+/*+ Warnings:++ - A unique constraint covering the columns `[project_id,model_name,start_date,unit]` on the table `models` will be added. If there are existing duplicate values, this will fail.++*/+-- CreateIndex+CREATE INDEX "models_project_id_model_name_idx" ON "models"("project_id", "model_name");++-- CreateIndex+CREATE UNIQUE INDEX "models_project_id_model_name_start_date_unit_key" ON "models"("project_id", "model_name", "start_date", "unit");diff --git a/prisma/migrations/20240119140941_add_tokenizer_id/migration.sql b/prisma/migrations/20240119140941_add_tokenizer_id/migration.sqlnew file mode 100644index 0000000000..b6a2828c39--- /dev/null+++ b/prisma/migrations/20240119140941_add_tokenizer_id/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "models" ADD COLUMN "tokenizer_id" TEXT;diff --git a/prisma/migrations/20240119164147_make_model_params_nullable/migration.sql b/prisma/migrations/20240119164147_make_model_params_nullable/migration.sqlnew file mode 100644index 0000000000..04735822d2--- /dev/null+++ b/prisma/migrations/20240119164147_make_model_params_nullable/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "models" ALTER COLUMN "tokenizer_config" DROP NOT NULL;diff --git a/prisma/migrations/20240119164148_add_models/migration.sql b/prisma/migrations/20240119164148_add_models/migration.sqlnew file mode 100644index 0000000000..99b94c40cb--- /dev/null+++ b/prisma/migrations/20240119164148_add_models/migration.sql@@ -0,0 +1,84 @@+-- This is an empty migration.+++INSERT INTO models (+ id,+ project_id,+ model_name,+ match_pattern,+ start_date,+ input_price,+ output_price,+ total_price,+ unit,+ tokenizer_id,+ tokenizer_config+)+VALUES+ --project_id, model_name, match_pattern, start_date, input_price, output_price, total_price, unit, tokenizer_id, tokenizer_config+ --https://openai.com/pricing+ -- GPT-4 Turbo+ ('clrkvq6iq000008ju6c16gynt', NULL, 'gpt-4-turbo', '(?i)^(gpt-4-1106-preview)$', NULL, 0.00001, 0.00003, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-1106-preview" }'),+ ('clrkvx5gp000108juaogs54ea', NULL, 'gpt-4-turbo-vision', '(?i)^(gpt-4-vision-preview)$', NULL, 0.00001, 0.00003, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-vision-preview" }'),++ -- GPT-4+ ('clrntkjgy000f08jx79v9g1xj', NULL, 'gpt-4', '(?i)^(gpt-4)$', NULL, 0.00003, 0.00006, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4" }'),+ ('clrkwk4cc000908l537kl0rx3', NULL, 'gpt-4-0613', '(?i)^(gpt-4-0613)$', NULL, 0.00003, 0.00006, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-0613" }'),+ ('clrntkjgy000e08jx4x6uawoo', NULL, 'gpt-4-0314', '(?i)^(gpt-4-0314)$', NULL, 0.00003, 0.00006, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-0314" }'),++ ('clrkvyzgw000308jue4hse4j9', NULL, 'gpt-4-32k', '(?i)^(gpt-4-32k)$', NULL, 0.00006, 0.00012, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-32k" }'),+ ('clrkwk4cb000108l5hwwh3zdi', NULL, 'gpt-4-32k-0613', '(?i)^(gpt-4-32k-0613)$', NULL, 0.00006, 0.00012, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-32k-0613" }'),+ ('clrntkjgy000d08jx0p4y9h4l', NULL, 'gpt-4-32k-0314', '(?i)^(gpt-4-32k-0314)$', NULL, 0.00006, 0.00012, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-4-32k-0314" }'),++ -- GPT 3++ ('clrkwk4cc000a08l562uc3s9g', NULL, 'gpt-3.5-turbo-instruct', '(?i)^(gpt-)(35|3.5)(-turbo-instruct)$', NULL, 0.0000015, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo" }'),+ ('clrkwk4cb000408l576jl7koo', NULL, 'gpt-3.5-turbo', '(?i)^(gpt-)(35|3.5)(-turbo)$', '2023-11-06', 0.000001, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo" }'),+ ('clrkwk4cb000208l59yvb9yq8', NULL, 'gpt-3.5-turbo-1106', '(?i)^(gpt-)(35|3.5)(-turbo-1106)$', NULL, 0.000001, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo-1106" }'),++ ('clrntkjgy000c08jxesb30p3f', NULL, 'gpt-3.5-turbo', '(?i)^(gpt-)(35|3.5)(-turbo)$', '2023-06-27', 0.0000015, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo" }'),+ ('clrkwk4cc000808l51xmk4uic', NULL, 'gpt-3.5-turbo-0613', '(?i)^(gpt-)(35|3.5)(-turbo-0613)$', NULL, 0.0000015, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo-0613" }'),++ ('clrntkjgy000b08jx769q1bah', NULL, 'gpt-3.5-turbo', '(?i)^(gpt-)(35|3.5)(-turbo)$', NULL, 0.000002, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 4, "tokensPerName": -1, "tokenizerModel": "gpt-3.5-turbo" }'),+ ('clrntkjgy000a08jx4e062mr0', NULL, 'gpt-3.5-turbo-0301', '(?i)^(gpt-)(35|3.5)(-turbo-0301)$', NULL, 0.000002, 0.000002, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 4, "tokensPerName": -1, "tokenizerModel": "gpt-3.5-turbo-0301" }'),+++ ('clrkwk4cb000308l5go4b6otm', NULL, 'gpt-3.5-turbo-16k', '(?i)^(gpt-)(35|3.5)(-turbo-16k)$', NULL, 0.00003, 0.00004, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo-16k" }'),+ ('clrntjt89000a08jw0gcdbd5a', NULL, 'gpt-3.5-turbo-16k-0613', '(?i)^(gpt-)(35|3.5)(-turbo-16k-0613)$', NULL, 0.00003, 0.00004, NULL, 'TOKENS', 'openai', '{ "tokensPerMessage": 3, "tokensPerName": 1, "tokenizerModel": "gpt-3.5-turbo-16k-0613" }'),+++++ -- nothing earlier required for ada+ ('clrntjt89000908jwhvkz5crm', NULL, 'text-embedding-ada-002', '(?i)^(text-embedding-ada-002)$', '2022-12-06', NULL, NULL, 0.0000001, 'TOKENS', 'openai', NULL),+ ('clrntjt89000908jwhvkz5crg', NULL, 'text-embedding-ada-002-v2', '(?i)^(text-embedding-ada-002-v2)$', '2022-12-06', NULL, NULL, 0.0000001, 'TOKENS', 'openai', NULL),+++++ -- legacy price 2023-08-22 https://platform.openai.com/docs/deprecations/2023-07-06-gpt-and-embeddings+ ('clrntjt89000108jwcou1af71', NULL, 'text-ada-001', '(?i)^(text-ada-001)$', NULL, NULL, NULL, 0.000004, 'TOKENS', 'openai', NULL),+ ('clrntjt89000208jwawjr894q', NULL, 'text-babbage-001', '(?i)^(text-babbage-001)$', NULL, NULL, NULL, 0.0000005, 'TOKENS', 'openai', NULL),+ ('clrp1wopz000708l079w02hkc', NULL, 'text-babbage-002', '(?i)^(text-babbage-002)$', NULL, NULL, NULL, 0.0000005, 'TOKENS', 'openai', NULL),+ ('clrntjt89000308jw0jtfa4rs', NULL, 'text-curie-001', '(?i)^(text-curie-001)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', NULL),+ ('clrntjt89000408jwc2c93h6i', NULL, 'text-davinci-001', '(?i)^(text-davinci-001)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', NULL),+ ('clrntjt89000508jw192m64qi', NULL, 'text-davinci-002', '(?i)^(text-davinci-002)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', NULL),+ ('clrntjt89000608jw4m3x5s55', NULL, 'text-davinci-003', '(?i)^(text-davinci-003)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', NULL),+++ -- claude+ ('clrnwbota000908jsgg9mb1ml', NULL, 'claude-instant-1', '(?i)^(claude-instant-1)$', NULL, 0.00000163, 0.00000551, NULL, 'CHARACTERS', 'claude', NULL),+ ('clrnwb41q000308jsfrac9uh6', NULL, 'claude-instant-1.2', '(?i)^(claude-instant-1.2)$', NULL, 0.00000163, 0.00000551, NULL, 'CHARACTERS', 'claude', NULL),+ ('clrnwbd1m000508js4hxu6o7n', NULL, 'claude-2.1', '(?i)^(claude-2.1)$', NULL, 0.000008, 0.000024, NULL, 'CHARACTERS', 'claude', NULL),+ ('clrnwb836000408jsallr6u11', NULL, 'claude-2.0', '(?i)^(claude-2.0)$', NULL, 0.000008, 0.000024, NULL, 'CHARACTERS', 'claude', NULL),+ ('clrnwbg2b000608jse2pp4q2d', NULL, 'claude-1.3', '(?i)^(claude-1.3)$', NULL, 0.000008, 0.000024, NULL, 'CHARACTERS', 'claude', NULL),+ ('clrnwbi9d000708jseiy44k26', NULL, 'claude-1.2', '(?i)^(claude-1.2)$', NULL, 0.000008, 0.000024, NULL, 'CHARACTERS', 'claude', NULL),+ ('clrnwblo0000808jsc1385hdp', NULL, 'claude-1.1', '(?i)^(claude-1.1)$', NULL, 0.000008, 0.000024, NULL, 'CHARACTERS', 'claude', NULL),+++ -- vertex+ ('clrp1wopz000808l09nwy32xh', NULL, 'codechat-bison-32k', '(?i)^(codechat-bison-32k)$', NULL, 0.0000005, 0.0000025, NULL, 'TOKENS', 'vertex', NULL),+ ('clrp1wopz000408l05xcycki1', NULL, 'chat-bison-32k', '(?i)^(chat-bison-32k)$', NULL, 0.0000005, 0.0000025, NULL, 'TOKENS', 'vertex', NULL)+++diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 547a937312..1722c9f221 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -3,7 +3,7 @@generator client {provider = "prisma-client-js"- previewFeatures = ["tracing"]+ previewFeatures = ["tracing", "views"]}datasource db {@@ -100,6 +100,7 @@ model Project {invitations MembershipInvitation[]sessions TraceSession[]Prompt Prompt[]+ Model Model[]@@map("projects")}@@ -226,12 +227,16 @@ model Observation {// GENERATION ONLYmodel String?+ internalModel String? @map("internal_model")modelParameters Json?input Json?output Json?promptTokens Int @default(0) @map("prompt_tokens")completionTokens Int @default(0) @map("completion_tokens")totalTokens Int @default(0) @map("total_tokens")+ inputCost Decimal? @map("input_cost")+ outputCost Decimal? @map("output_cost")+ totalCost Decimal? @map("total_cost")unit String @default("TOKENS")completionStartTime DateTime? @map("completion_start_time")scores Score[]@@ -420,3 +425,70 @@ model Prompt {@@index([projectId, name, version])@@map("prompts")}++model Model {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ projectId String? @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)++ modelName String @map("model_name")+ matchPattern String @map("match_pattern")+ startDate DateTime? @map("start_date")+ inputPrice Decimal? @map("input_price")+ outputPrice Decimal? @map("output_price")+ totalPrice Decimal? @map("total_price")+ unit String @default("TOKENS")+ tokenizerId String? @map("tokenizer_id")+ tokenizerConfig Json? @map("tokenizer_config")++ @@unique([projectId, modelName, startDate, unit])+ @@index([projectId, modelName])+ @@map("models")+}++// This view is a mix of the obsevation and model. Once prisma supports+// inheritance, we should remove code duplication here.+view ObservationView {+ id String @id @default(cuid())+ traceId String? @map("trace_id")+ projectId String @map("project_id")+ type ObservationType+ startTime DateTime @default(now()) @map("start_time")+ endTime DateTime? @map("end_time")+ name String?+ metadata Json?+ parentObservationId String? @map("parent_observation_id")+ level ObservationLevel @default(DEFAULT)+ statusMessage String? @map("status_message")+ version String?+ createdAt DateTime @default(now()) @map("created_at")++ // GENERATION ONLY+ model String?+ modelParameters Json?+ input Json?+ output Json?+ promptTokens Int @default(0) @map("prompt_tokens")+ completionTokens Int @default(0) @map("completion_tokens")+ totalTokens Int @default(0) @map("total_tokens")+ unit String @default("TOKENS")+ completionStartTime DateTime? @map("completion_start_time")++ promptId String? @map("prompt_id")++ // Model+ model_id String? @map("model_id")+ inputPrice Decimal? @map("input_price")+ outputPrice Decimal? @map("output_price")+ totalPrice Decimal? @map("total_price")++ // calculated fields+ calculatedInputCost Decimal? @map("calculated_input_cost")+ calculatedOutputCost Decimal? @map("calculated_output_cost")+ calculatedTotalCost Decimal? @map("calculated_total_cost")++ @@map("observations_view")+}diff --git a/prisma/seed.ts b/prisma/seed.tsindex 5db1b8bf66..2a830edac4 100755--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -98,9 +98,9 @@ async function main() {// Do not run the following for local docker compose setupif (environment === "examples") {- const project2 = await prisma.project.create({- data: {- id: "239ad00f-562f-411d-af14-831c75ddd875",+ const project2 = await prisma.project.upsert({+ where: { id: "239ad00f-562f-411d-af14-831c75ddd875" },+ create: {name: "demo-app",apiKeys: {create: [@@ -119,6 +119,7 @@ async function main() {},},},+ update: {},});const generationIds: string[] = [];@@ -268,6 +269,19 @@ async function main() {const promptTokens = Math.floor(Math.random() * 1000) + 300;const completionTokens = Math.floor(Math.random() * 500) + 100;+ const models = [+ "gpt-3.5-turbo",+ "gpt-4",+ "gpt-4-32k-0613",+ "gpt-3.5-turbo-16k-0613",+ "claude-instant-1",+ "claude-2.1",+ "gpt-4-vision-preview",+ "MIXTRAL-8X7B",+ ];++ const model = models[Math.floor(Math.random() * models.length)];+const generation = await prisma.observation.create({data: {type: "GENERATION",@@ -334,7 +348,8 @@ async function main() {Remember to import React at the top of your file whenever you're creating a component, because JSX transpiles to 'React.createElement' calls under the hood.`,},- model: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",+ model: model,+ internalModel: model,modelParameters: {temperature:Math.random() > 0.9 ? undefined : Math.random().toFixed(2),@@ -358,6 +373,11 @@ async function main() {? { prompt: { connect: { id: prompt.id } } }: {}),},+ unit: model+ ? model.includes("claude")+ ? "CHARACTERS"+ : "TOKENS"+ : undefined,},});if (Math.random() > 0.6)diff --git a/scripts/model-match.ts b/scripts/model-match.tsnew file mode 100644index 0000000000..66ba9d5ab9--- /dev/null+++ b/scripts/model-match.ts@@ -0,0 +1,141 @@+// Description: This script is used to match observations with their internal model. This is needed+// to be able to calculate the cost of the observation.+// See docs: https://langfuse.com/docs/deployment/self-host#updating-the-application+// Execute: `npm run model:match`++import "dotenv/config";++import { findModel } from "@/src/server/api/services/EventProcessor";+import { prisma } from "@/src/server/db";+import { type Observation } from "@prisma/client";++async function main() {+ return await modelMatch();+}++// Call the function+main().catch((err) => {+ console.error("An error occurred:", err);+});++export async function modelMatch() {+ console.log("Starting model match");+ const start = Date.now();++ // while observations are not null, get the next 10000 observations+ let continueLoop = true;+ let index = 0;+ let totalObservations = 0;++ while (continueLoop) {+ const observations = await prisma.observation.findMany({+ orderBy: {+ startTime: "desc",+ },+ where: {+ internalModel: null,+ type: "GENERATION",+ },+ take: 10_000,+ skip: index * 10_000,+ });+ console.log("Observations: ", observations[0]?.id);++ console.log(`Found ${observations.length} observations to migrate`);++ interface GroupedObservations {+ [key: string]: Observation[];+ }++ const groupedObservations = observations.reduce<GroupedObservations>(+ (acc, observation) => {+ const key = `${observation.startTime.toISOString().slice(0, 10)}_${+ observation.model+ }_${observation.unit}_${observation.projectId}`;++ // Ensure the array is initialized before using it+ acc[key] = acc[key] ?? [];+ acc[key]?.push(observation);++ return acc;+ },+ {},+ );++ const updatePromises = [];+ let updatedObservations = 0;++ for (const [key, observationsGroup] of Object.entries(+ groupedObservations,+ )) {+ // Split the key into its components+ const [date, model, unit, projectId] = key.split("_");++ console.log("Execute key: ", date, model, unit, projectId);++ if (!projectId) {+ throw new Error("No project id");+ }++ // Note: The findModel function is assumed to be asynchronous.+ const foundModel = await findModel(+ projectId,+ model,+ unit,+ date,+ undefined,+ );++ console.log(+ "Found model: ",+ foundModel?.id,+ " for key: ",+ key,+ " with observations: ",+ observationsGroup.length,+ );++ if (foundModel) {+ // Push the promise for updating observations into the array+ updatePromises.push(+ prisma.observation.updateMany({+ where: {+ id: {+ in: observationsGroup.map((observation) => observation.id),+ },+ },+ data: {+ internalModel: foundModel.modelName,+ },+ }),+ );++ updatedObservations += observationsGroup.length;+ }+ }++ totalObservations += updatedObservations;+ // Wait for all update operations to complete+ await Promise.all(updatePromises);+ console.warn(+ "Updated observations count: ",+ updatedObservations,+ " in total: ",+ totalObservations,+ );++ console.log(updatedObservations, observations.length);++ if (updatedObservations === 0) {+ index++;+ }++ if (observations.length === 0) {+ console.log("No more observations to migrate");+ continueLoop = false;+ }+ }+ const end = Date.now();++ console.log(`Model match took ${end - start} ms`);+}diff --git a/src/__tests__/cost.servertest.ts b/src/__tests__/cost.servertest.tsnew file mode 100644index 0000000000..38eb5799d6--- /dev/null+++ b/src/__tests__/cost.servertest.ts@@ -0,0 +1,441 @@+/** @jest-environment node */++import { pruneDatabase } from "@/src/__tests__/test-utils";+import { prisma } from "@/src/server/db";++describe("cost retrieval tests", () => {+ beforeEach(async () => await pruneDatabase());++ [+ {+ testDescription: "prompt and completion tokens",+ promptTokens: 200,+ completionTokens: 3000,+ totalTokens: undefined,+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: undefined,+ expectedPromptTokens: 200,+ expectedCompletionTokens: 3000,+ expectedTotalTokens: 0,+ expectedInputCost: "0.0002", // 200 / 1000 * 0.0010+ expectedOutputCost: "0.006", // 3000 / 1000 * 0.0020+ expectedTotalCost: "0.0062", // 0.0002 + 0.006+ },+ {+ testDescription: "missing completion tokens",+ promptTokens: 200,+ completionTokens: undefined,+ totalTokens: undefined,+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: undefined,+ expectedPromptTokens: 200,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 0,+ expectedInputCost: "0.0002",+ expectedOutputCost: "0", // completionTokens are set to 0 when ingesting undefined, hence 0 cost+ expectedTotalCost: "0.0002",+ },+ {+ testDescription: "missing prompt tokens",+ promptTokens: undefined,+ completionTokens: 3000,+ totalTokens: undefined,+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: undefined,+ expectedPromptTokens: 0,+ expectedCompletionTokens: 3000,+ expectedTotalTokens: 0,+ expectedInputCost: "0", // promptTokens are set to 0 when ingesting undefined, hence 0 cost+ expectedOutputCost: "0.006",+ expectedTotalCost: "0.006",+ },+ {+ testDescription: "prompt and completion and total",+ promptTokens: 200,+ completionTokens: 3000,+ totalTokens: 3200,+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: undefined,+ expectedPromptTokens: 200,+ expectedCompletionTokens: 3000,+ expectedTotalTokens: 3200,+ expectedInputCost: "0.0002", // 200 / 1000 * 0.0010+ expectedOutputCost: "0.006", // 3000 / 1000 * 0.0020+ expectedTotalCost: "0.0062", // 0.0002 + 0.006+ },+ {+ testDescription: "total only without price",+ promptTokens: undefined,+ completionTokens: undefined,+ totalTokens: 3200,+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: undefined,+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 3200,+ expectedInputCost: "0",+ expectedOutputCost: "0",+ expectedTotalCost: "0",+ },+ {+ testDescription: "total only",+ promptTokens: undefined,+ completionTokens: undefined,+ totalTokens: 3200,+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: "0.1",+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 3200,+ expectedInputCost: "0",+ expectedOutputCost: "0",+ expectedTotalCost: "320",+ },+ ].forEach((input) => {+ it(`should calculate cost correctly ${input.testDescription}`, async () => {+ await pruneDatabase();++ await prisma.model.create({+ data: {+ modelName: "gpt-3.5-turbo",+ inputPrice: input.inputPrice,+ outputPrice: input.outputPrice,+ totalPrice: input.totalPrice,+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",+ projectId: null,+ startDate: new Date("2023-12-01"),+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },+ unit: "TOKENS",+ },+ });++ const dbTrace = await prisma.trace.create({+ data: {+ name: "trace-name",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ },+ });++ await prisma.observation.create({+ data: {+ traceId: dbTrace.id,+ type: "GENERATION",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ model: "gpt-3.5-turbo",+ internalModel: "gpt-3.5-turbo",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ promptTokens: input.promptTokens,+ completionTokens: input.completionTokens,+ totalTokens: input.totalTokens,+ },+ });++ const view = await prisma.observationView.findFirst({+ where: { traceId: dbTrace.id },+ });++ expect(view?.promptTokens).toBe(input.expectedPromptTokens);+ expect(view?.completionTokens).toBe(input.expectedCompletionTokens);+ expect(view?.totalTokens).toBe(input.expectedTotalTokens);++ // calculated cost fields+ expect(view?.calculatedInputCost?.toString()).toBe(+ input.expectedInputCost,+ );+ expect(view?.calculatedOutputCost?.toString()).toBe(+ input.expectedOutputCost,+ );+ expect(view?.calculatedTotalCost?.toString()).toBe(+ input.expectedTotalCost,+ );+ });+ });++ [+ {+ testDescription: "overwriting project specific model",+ expectedInputCost: "0.0004", // 200 / 1000 * 0.0010+ expectedOutputCost: "0.012", // 3000 / 1000 * 0.0020+ expectedTotalCost: "0.0124", // 0.0002 + 0.006+ expectedModelId: "model-2",+ },+ ].forEach((input) => {+ it(`should calculate cost correctly with multiple models ${input.testDescription}`, async () => {+ await pruneDatabase();++ await prisma.model.create({+ data: {+ id: "model-1",+ modelName: "gpt-3.5-turbo",+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: "0.1",+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",+ projectId: null,+ startDate: new Date("2023-12-01"),+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },+ unit: "TOKENS",+ },+ });+ await prisma.model.create({+ data: {+ id: "model-2",+ modelName: "gpt-3.5-turbo",+ inputPrice: "0.0000020",+ outputPrice: "0.0000040",+ totalPrice: undefined,+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",+ startDate: new Date("2023-12-01"),+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },+ unit: "TOKENS",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ },+ });++ const dbTrace = await prisma.trace.create({+ data: {+ name: "trace-name",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ },+ });++ await prisma.observation.create({+ data: {+ traceId: dbTrace.id,+ type: "GENERATION",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ model: "gpt-3.5-turbo",+ internalModel: "gpt-3.5-turbo",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ promptTokens: 200,+ completionTokens: 3000,+ totalTokens: undefined,+ },+ });++ const view = await prisma.observationView.findFirst({+ where: { traceId: dbTrace.id },+ });++ // calculated cost fields+ expect(view?.model_id).toBe(input.expectedModelId);+ expect(view?.calculatedInputCost?.toString()).toBe(+ input.expectedInputCost,+ );+ expect(view?.calculatedOutputCost?.toString()).toBe(+ input.expectedOutputCost,+ );+ expect(view?.calculatedTotalCost?.toString()).toBe(+ input.expectedTotalCost,+ );+ });+ });+ it(`should prioritize latest models`, async () => {+ await pruneDatabase();++ await prisma.model.create({+ data: {+ id: "model-1",+ modelName: "gpt-3.5-turbo",+ inputPrice: "0.0000010",+ outputPrice: "0.0000020",+ totalPrice: "0.1",+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",+ projectId: null,+ startDate: new Date("2023-12-01"),+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },+ unit: "TOKENS",+ },+ });+ await prisma.model.create({+ data: {+ id: "model-2",+ modelName: "gpt-3.5-turbo",+ inputPrice: "0.0000020",+ outputPrice: "0.0000040",+ totalPrice: undefined,+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",+ startDate: new Date("2023-12-02"),+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },+ unit: "TOKENS",+ },+ });++ const dbTrace = await prisma.trace.create({+ data: {+ name: "trace-name",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ },+ });++ await prisma.observation.create({+ data: {+ traceId: dbTrace.id,+ type: "GENERATION",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ model: "gpt-3.5-turbo",+ internalModel: "gpt-3.5-turbo",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ promptTokens: 200,+ completionTokens: 3000,+ totalTokens: undefined,+ },+ });++ const view = await prisma.observationView.findFirst({+ where: { traceId: dbTrace.id },+ });++ console.log(view);++ // calculated cost fields+ expect(view?.model_id).toBe("model-2");+ expect(view?.calculatedInputCost?.toString()).toBe("0.0004");+ expect(view?.calculatedOutputCost?.toString()).toBe("0.012");+ expect(view?.calculatedTotalCost?.toString()).toBe("0.0124");+ });++ it(`should prioritize old model if the latest model is not own one`, async () => {+ await pruneDatabase();++ 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.0000020",+ outputPrice: "0.0000040",+ totalPrice: undefined,+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",+ startDate: new Date("2023-12-01"),+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ unit: "TOKENS",+ },+ });++ const dbTrace = await prisma.trace.create({+ data: {+ name: "trace-name",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ },+ });++ await prisma.observation.create({+ data: {+ traceId: dbTrace.id,+ type: "GENERATION",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ model: "gpt-3.5-turbo",+ internalModel: "gpt-3.5-turbo",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ promptTokens: 200,+ completionTokens: 3000,+ totalTokens: undefined,+ },+ });++ const view = await prisma.observationView.findFirst({+ where: { traceId: dbTrace.id },+ });++ console.log(view);++ // calculated cost fields+ expect(view?.model_id).toBe("model-2");+ expect(view?.calculatedInputCost?.toString()).toBe("0.0004");+ expect(view?.calculatedOutputCost?.toString()).toBe("0.012");+ expect(view?.calculatedTotalCost?.toString()).toBe("0.0124");+ });++ it(`should prioritize user provided cost`, async () => {+ await pruneDatabase();++ 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 },+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ unit: "TOKENS",+ },+ });++ const dbTrace = await prisma.trace.create({+ data: {+ name: "trace-name",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ },+ });++ await prisma.observation.create({+ data: {+ traceId: dbTrace.id,+ type: "GENERATION",+ project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },+ model: "gpt-3.5-turbo",+ internalModel: "gpt-3.5-turbo",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ promptTokens: 200,+ completionTokens: 3000,+ totalTokens: undefined,+ inputCost: "1",+ outputCost: "2",+ totalCost: "3",+ },+ });++ const view = await prisma.observationView.findFirst({+ where: { traceId: dbTrace.id },+ });++ console.log(view);++ // calculated cost fields+ expect(view?.model_id).toBe("model-2");+ expect(view?.calculatedInputCost?.toString()).toBe("1");+ expect(view?.calculatedOutputCost?.toString()).toBe("2");+ expect(view?.calculatedTotalCost?.toString()).toBe("3");+ });+});diff --git a/src/__tests__/ingestion.servertest.ts b/src/__tests__/ingestion.servertest.tsindex 064ae36d0b..4d313fa141 100644--- a/src/__tests__/ingestion.servertest.ts+++ b/src/__tests__/ingestion.servertest.ts@@ -15,6 +15,9 @@ describe("/api/public/ingestion API Endpoint", () => {output: 200,total: 100,unit: "CHARACTERS",+ inputCost: 123,+ outputCost: 456,+ totalCost: 789,},expectedUnit: "CHARACTERS",expectedPromptTokens: 100,@@ -82,7 +85,7 @@ describe("/api/public/ingestion API Endpoint", () => {expectedUnit: "TOKENS",},].forEach((testConfig) => {- it(`should create trace and generation ${JSON.stringify(+ it(`should create trace, generation and score without matching models ${JSON.stringify(testConfig,)}`, async () => {const traceId = v4();@@ -208,6 +211,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(dbGeneration?.input).toEqual({ key: "value" });expect(dbGeneration?.metadata).toEqual({ key: "value" });expect(dbGeneration?.version).toBe("2.0.0");+ expect(dbGeneration?.internalModel).toBeNull();expect(dbGeneration?.promptTokens).toEqual(testConfig.expectedPromptTokens,);@@ -248,6 +252,231 @@ describe("/api/public/ingestion API Endpoint", () => {});});+ [+ {+ observationExternalModel: "gpt-3.5",+ observationStartTime: new Date("2021-01-01T00:00:00.000Z"),+ modelUnit: "TOKENS",+ expectedInternalModel: "gpt-3.5-turbo",+ expectedPromptTokens: 5,+ expectedCompletionTokens: 7,+ models: [+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ ],+ },+ {+ observationExternalModel: "gpt-3.5",+ observationStartTime: new Date("2021-01-01T00:00:00.000Z"),+ modelUnit: "TOKENS",+ expectedInternalModel: "gpt-3.5-turbo",+ expectedPromptTokens: 5,+ expectedCompletionTokens: 7,+ models: [+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: null,+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ ],+ },+ {+ observationExternalModel: "GPT-3.5",+ observationStartTime: new Date("2021-01-01T00:00:00.000Z"),+ modelUnit: "TOKENS",+ expectedInternalModel: "gpt-3.5-turbo",+ expectedPromptTokens: 5,+ expectedCompletionTokens: 7,+ models: [+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ ],+ },+ {+ observationExternalModel: "GPT-3.5",+ observationStartTime: new Date("2021-01-01T00:00:00.000Z"),+ modelUnit: "TOKENS",+ expectedInternalModel: "gpt-3.5-turbo",+ expectedPromptTokens: 5,+ expectedCompletionTokens: 7,+ models: [+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ {+ modelName: "gpt-3.5-turbo-new",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T10:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ ],+ },+ {+ observationExternalModel: "GPT-3.5",+ observationStartTime: new Date("2021-01-02T00:00:00.000Z"),+ modelUnit: "TOKENS",+ expectedInternalModel: "gpt-3.5-turbo",+ expectedPromptTokens: 5,+ expectedCompletionTokens: 7,+ models: [+ {+ modelName: "gpt-3.5-turbo-new",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T10:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ tokenizerModel: "gpt-3.5-turbo",+ },+ ],+ },+ {+ observationExternalModel: "GPT-4",+ observationStartTime: new Date("2021-01-01T00:00:00.000Z"),+ modelUnit: "TOKENS",+ expectedInternalModel: null,+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ models: [+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ ],+ },+ {+ observationExternalModel: "GPT-3",+ observationStartTime: new Date("2021-01-01T00:00:00.000Z"),+ modelUnit: "CHARACTERS",+ expectedInternalModel: null,+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ models: [+ {+ modelName: "gpt-3.5-turbo",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ },+ ],+ },+ ].forEach((testConfig) => {+ it(`should match observations to internal models ${JSON.stringify(+ testConfig,+ )}`, async () => {+ const traceId = v4();+ const generationId = v4();++ await Promise.all(+ testConfig.models.map(async (model) =>+ prisma.model.create({+ data: {+ modelName: model.modelName,+ matchPattern: model.matchPattern,+ startDate: model.startDate,+ unit: model.unit,+ tokenizerId: model.tokenizerId,+ tokenizerConfig: {+ tokensPerMessage: 3,+ tokensPerName: 1,+ tokenizerModel:+ "tokenizerModel" in model+ ? model.tokenizerModel+ : model.modelName,+ },+ },+ }),+ ),+ );++ const response = await makeAPICall("POST", "/api/public/ingestion", {+ metadata: {+ sdk_verion: "1.0.0",+ sdk_name: "python",+ },+ batch: [+ {+ id: v4(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name: "trace-name",+ },+ },+ {+ id: v4(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ traceId: traceId,+ type: "GENERATION",+ name: "generation-name",+ startTime: testConfig.observationStartTime.toISOString(),+ model: testConfig.observationExternalModel,+ usage: {+ unit: testConfig.modelUnit,+ },+ input: "This is a great prompt",+ output: "This is a great gpt output",+ },+ },+ ],+ });++ expect(response.status).toBe(207);++ console.log("response body", response.body);++ const dbGeneration = await prisma.observation.findUnique({+ where: {+ id: generationId,+ },+ });++ expect(dbGeneration?.id).toBe(generationId);+ expect(dbGeneration?.traceId).toBe(traceId);+ expect(dbGeneration?.name).toBe("generation-name");+ expect(dbGeneration?.startTime).toEqual(testConfig.observationStartTime);+ expect(dbGeneration?.model).toBe(testConfig.observationExternalModel);+ expect(dbGeneration?.promptTokens).toBe(testConfig.expectedPromptTokens);+ expect(dbGeneration?.completionTokens).toBe(+ testConfig.expectedCompletionTokens,+ );+ expect(dbGeneration?.internalModel).toBe(+ testConfig.expectedInternalModel,+ );+ });+ });+it("should create and update all events", async () => {const traceId = v4();const generationId = v4();@@ -618,6 +847,21 @@ describe("/api/public/ingestion API Endpoint", () => {const traceId = v4();const generationId = v4();+ await prisma.model.create({+ data: {+ modelName: "gpt-3.5",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ tokenizerConfig: {+ tokensPerMessage: 3,+ tokensPerName: 1,+ tokenizerModel: "gpt-3.5-turbo",+ },+ },+ });+const responseOne = await makeAPICall("POST", "/api/public/ingestion", {batch: [{@@ -685,6 +929,21 @@ describe("/api/public/ingestion API Endpoint", () => {const traceId = v4();const generationId = v4();+ await prisma.model.create({+ data: {+ modelName: "gpt-3.5",+ matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",+ startDate: new Date("2021-01-01T00:00:00.000Z"),+ unit: "TOKENS",+ tokenizerId: "openai",+ tokenizerConfig: {+ tokensPerMessage: 3,+ tokensPerName: 1,+ tokenizerModel: "gpt-3.5-turbo",+ },+ },+ });+const responseOne = await makeAPICall("POST", "/api/public/ingestion", {batch: [{diff --git a/src/__tests__/prompts.servertest.ts b/src/__tests__/prompts.servertest.tsindex 70d27531c6..b00f891542 100644--- a/src/__tests__/prompts.servertest.ts+++ b/src/__tests__/prompts.servertest.ts@@ -255,8 +255,6 @@ describe("/api/public/prompts API Endpoint", () => {expect(response.status).toBe(207);- console.log("response body", response.body);-const dbGeneration = await prisma.observation.findUnique({where: {id: generationId,diff --git a/src/__tests__/query-builder.servertest.ts b/src/__tests__/query-builder.servertest.tsindex 4dcc72ffe5..58b4bd94ab 100644--- a/src/__tests__/query-builder.servertest.ts+++ b/src/__tests__/query-builder.servertest.ts@@ -22,7 +22,7 @@ describe("Build valid SQL queries", () => {table: "traces_observations",values: ["project-id", "project-id"],strings: [- ' FROM traces t LEFT JOIN observations o ON t.id = o.trace_id WHERE t."project_id" = ',+ ' FROM traces t LEFT JOIN observations_view o ON t.id = o.trace_id WHERE t."project_id" = ',' AND o."project_id" = '," ;",],@@ -30,7 +30,7 @@ describe("Build valid SQL queries", () => {{table: "observations",values: ["project-id"],- strings: [' FROM observations o WHERE o."project_id" = ', " ;"],+ strings: [' FROM observations_view o WHERE o."project_id" = ', " ;"],} as const,{table: "traces_scores",diff --git a/src/__tests__/test-utils.ts b/src/__tests__/test-utils.tsindex ce6edc519f..e20d459f04 100644--- a/src/__tests__/test-utils.ts+++ b/src/__tests__/test-utils.ts@@ -14,6 +14,7 @@ export const pruneDatabase = async () => {await prisma.datasetRuns.deleteMany();await prisma.prompt.deleteMany();await prisma.events.deleteMany();+ await prisma.model.deleteMany();};export function createBasicAuthHeader(diff --git a/src/__tests__/usage.servertest.ts b/src/__tests__/usage.servertest.tsindex 45f599fba6..aec3323386 100644--- a/src/__tests__/usage.servertest.ts+++ b/src/__tests__/usage.servertest.ts@@ -1,20 +1,40 @@import { tokenCount } from "@/src/features/ingest/lib/usage";describe("Token Count Functions", () => {+ const generateModel = (model: string, tokenizer: string) => {+ return {+ id: "1",+ modelName: model,+ tokenizerId: tokenizer,+ tokenizerConfig: {+ tokensPerMessage: 3,+ tokensPerName: 1,+ tokenizerModel: model,+ },+ createdAt: new Date(),+ updatedAt: new Date(),+ matchPattern: "",+ projectId: null,+ startDate: null,+ inputPrice: null,+ outputPrice: null,+ totalPrice: null,+ unit: "TOKENS",+ };+ };+describe("token count for strings", () => {[- { model: "gpt-3.5", tokens: 114 },- { model: "gpt-35", tokens: 114 },- { model: "gpt-4-1106-preview", tokens: 114 },- { model: "gpt-4-vision-preview", tokens: 114 },- { model: "claude", tokens: 118 },- { model: "claude-instant-1.2", tokens: 118 },- { model: "gpt-3.5-turbo-1106", tokens: 114 },- { model: "gpt-35-turbo-1106", tokens: 114 },- ].forEach(({ model, tokens }) => {+ { model: "gpt-3.5-turbo", tokenizer: "openai", tokens: 114 },+ { model: "gpt-4-1106-preview", tokenizer: "openai", tokens: 114 },+ { model: "gpt-4-vision-preview", tokenizer: "openai", tokens: 114 },+ { model: "claude", tokenizer: "claude", tokens: 118 },+ { model: "claude-instant-1.2", tokenizer: "claude", tokens: 118 },+ { model: "gpt-3.5-turbo-1106", tokenizer: "openai", tokens: 114 },+ ].forEach(({ model, tokens, tokenizer }) => {it(`should return token count ${tokens} for ${model}`, () => {const result = tokenCount({- model: model,+ model: generateModel(model, tokenizer),text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",});expect(result).toBeDefined();@@ -24,20 +44,23 @@ describe("Token Count Functions", () => {it("should return undefined for unknown model", () => {const result = tokenCount({- model: "unknown-model",+ model: generateModel("unknown-model", "unknown-tokenizer"),text: "Hello, World!",});expect(result).toBeUndefined();});it("should return for invalid text type", () => {- const result = tokenCount({ model: "gpt-4", text: 1234 });+ const result = tokenCount({+ model: generateModel("gpt-4", "openai"),+ text: 1234,+ });expect(result).toBe(2);});it("should return correct token count for empty string", () => {const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: "",});expect(result).toBe(0);@@ -46,7 +69,7 @@ describe("Token Count Functions", () => {it("should return correct token count for very long string", () => {const longString = "A".repeat(10000);const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: longString,});expect(result).toBeDefined();@@ -55,14 +78,14 @@ describe("Token Count Functions", () => {it("should return undefined for null text input", () => {const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: null,});expect(result).toBeUndefined();});it("should return undefined for undefined text input", () => {const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: undefined,});expect(result).toBeUndefined();@@ -71,14 +94,14 @@ describe("Token Count Functions", () => {describe("token count for chat messages", () => {[- { model: "gpt-4", tokens: 44 },- { model: "gpt-3.5-turbo-16k-0613", tokens: 44 },- { model: "gpt-35-turbo-16k-0613", tokens: 44 },- { model: "claude-instant-1.2", tokens: 48 },- ].forEach(({ model, tokens }) => {+ { model: "gpt-4", tokenizer: "openai", tokens: 44 },+ { model: "gpt-3.5-turbo-16k-0613", tokenizer: "openai", tokens: 44 },+ { model: "gpt-3.5-turbo-16k-0613", tokenizer: "openai", tokens: 44 },+ { model: "claude-instant-1.2", tokenizer: "claude", tokens: 48 },+ ].forEach(({ model, tokens, tokenizer }) => {it(`should return token count ${tokens} for ${model}`, () => {const result = tokenCount({- model: model,+ model: generateModel(model, tokenizer),text: [{ role: "system", content: "You are a helpful assistant." },{ role: "user", content: "Who won the world series in 2020?" },@@ -95,7 +118,7 @@ describe("Token Count Functions", () => {it("should return for non array", () => {const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: { role: "Helo world" },});expect(result).toBe(7);@@ -103,7 +126,7 @@ describe("Token Count Functions", () => {it("should return for empty array", () => {const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: [],});expect(result).toBeUndefined();@@ -111,7 +134,7 @@ describe("Token Count Functions", () => {it("should return for array of invalid object", () => {const result = tokenCount({- model: "gpt-4",+ model: generateModel("gpt-4", "openai"),text: [{ role: "Helo world" }],});expect(result).toBe(9);diff --git a/src/components/layouts/routes.ts b/src/components/layouts/routes.tsindex f51e9d5c48..d798a65ec1 100644--- a/src/components/layouts/routes.ts+++ b/src/components/layouts/routes.ts@@ -47,6 +47,10 @@ export const ROUTES: Route[] = [name: "Scores",pathname: `/project/[projectId]/scores`,},+ {+ name: "Models",+ pathname: `/project/[projectId]/models`,+ },],},{diff --git a/src/components/table/use-cases/generations.tsx b/src/components/table/use-cases/generations.tsxindex c68f0f8cf9..bdd8379eec 100644--- a/src/components/table/use-cases/generations.tsx+++ b/src/components/table/use-cases/generations.tsx@@ -333,7 +333,7 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {startTime: generation.startTime.toLocaleString(),endTime: generation.endTime?.toLocaleString() ?? undefined,latency: generation.latency === null ? undefined : generation.latency,- cost: generation.cost,+ cost: generation.calculatedTotalCost,name: generation.name ?? undefined,version: generation.version ?? "",model: generation.model ?? "",diff --git a/src/components/table/use-cases/models.tsx b/src/components/table/use-cases/models.tsxnew file mode 100644index 0000000000..87ca2d9a32--- /dev/null+++ b/src/components/table/use-cases/models.tsx@@ -0,0 +1,202 @@+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";+import { api } from "@/src/utils/api";+import { usdFormatter } from "@/src/utils/numbers";+import { type Prisma, type Model } from "@prisma/client";+import Decimal from "decimal.js";+import { useQueryParams, withDefault, NumberParam } from "use-query-params";++export type ModelTableRow = {+ maintainer: string;+ modelName: string;+ matchPattern: string;+ startDate?: Date;+ inputPrice?: Decimal;+ outputPrice?: Decimal;+ totalPrice?: Decimal;+ unit: string;+ tokenizerId?: string;+ config?: Prisma.JsonValue;+};++export default function ModelTable({ projectId }: { projectId: string }) {+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });++ const models = api.models.all.useQuery({+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ projectId,+ });+ const totalCount = models.data?.totalCount ?? 0;++ const columns: LangfuseColumnDef<ModelTableRow>[] = [+ {+ accessorKey: "maintainer",+ id: "maintainer",+ enableColumnFilter: true,+ header: "Maintainer",+ },+ {+ accessorKey: "modelName",+ id: "modelName",+ header: "Model Name",+ },+ {+ accessorKey: "matchPattern",+ id: "matchPattern",+ header: "Match Pattern",+ cell: ({ row }) => {+ const value: string = row.getValue("matchPattern");++ return (+ <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs ">+ {value}+ </code>+ );+ },+ },+ {+ accessorKey: "startDate",+ id: "startDate",+ header: "Start Date",+ cell: ({ row }) => {+ const value: Date | undefined = row.getValue("startDate");++ return value ? (+ <span className="text-xs">{value.toLocaleDateString()} </span>+ ) : (+ <span className="text-xs">-</span>+ );+ },+ },+ {+ accessorKey: "inputPrice",+ id: "inputPrice",+ header: "Input Price",+ cell: ({ row }) => {+ const value: Decimal | undefined = row.getValue("inputPrice");++ return value ? (+ <span className="text-xs">+ {usdFormatter(value.toNumber(), 2, 8)}+ </span>+ ) : (+ <span className="text-xs">-</span>+ );+ },+ },+ {+ accessorKey: "outputPrice",+ id: "outputPrice",+ header: "Output Price",+ cell: ({ row }) => {+ const value: Decimal | undefined = row.getValue("outputPrice");++ return value ? (+ <span className="text-xs">+ {usdFormatter(value.toNumber(), 2, 8)}+ </span>+ ) : (+ <span className="text-xs">-</span>+ );+ },+ },+ {+ accessorKey: "totalPrice",+ id: "totalPrice",+ header: "Total Price",+ cell: ({ row }) => {+ const value: Decimal | undefined = row.getValue("totalPrice");++ return value ? (+ <span className="text-xs">+ {usdFormatter(value.toNumber(), 2, 8)}+ </span>+ ) : (+ <span className="text-xs">-</span>+ );+ },+ },+ {+ accessorKey: "unit",+ id: "unit",+ header: "Unit",+ enableHiding: true,+ },+ {+ accessorKey: "tokenizerId",+ id: "tokenizerId",+ header: "Tokenizer",+ enableHiding: true,+ },+ {+ accessorKey: "config",+ id: "config",+ header: "Tokenizer",+ enableHiding: true,+ cell: ({ row }) => {+ const value: Prisma.JsonValue | undefined = row.getValue("config");++ return value ? (+ <span className="text-xs">{JSON.stringify(value)}</span>+ ) : (+ <span className="text-xs">-</span>+ );+ },+ },+ ];++ const [columnVisibility, setColumnVisibility] =+ useColumnVisibility<ModelTableRow>("scoresColumnVisibility", columns);++ const convertToTableRow = (model: Model): ModelTableRow => {+ return {+ maintainer: model.projectId ? "User" : "Langfuse",+ modelName: model.modelName,+ matchPattern: model.matchPattern,+ startDate: model.startDate ? new Date(model.startDate) : undefined,+ inputPrice: model.inputPrice ? new Decimal(model.inputPrice) : undefined,+ outputPrice: model.outputPrice+ ? new Decimal(model.outputPrice)+ : undefined,+ totalPrice: model.totalPrice ? new Decimal(model.totalPrice) : undefined,+ unit: model.unit,+ tokenizerId: model.tokenizerId ?? undefined,+ config: model.tokenizerConfig,+ };+ };++ return (+ <div>+ <DataTable+ columns={columns}+ data={+ models.isLoading+ ? { isLoading: true, isError: false }+ : models.isError+ ? {+ isLoading: false,+ isError: true,+ error: models.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: models.data.models.map((t) => convertToTableRow(t)),+ }+ }+ pagination={{+ pageCount: Math.ceil(totalCount / paginationState.pageSize),+ onChange: setPaginationState,+ state: paginationState,+ }}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={setColumnVisibility}+ />+ </div>+ );+}diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsxindex 24848306bd..b6111113c9 100644--- a/src/components/table/use-cases/traces.tsx+++ b/src/components/table/use-cases/traces.tsx@@ -29,6 +29,8 @@ import {useQueryParams,withDefault,} from "use-query-params";+import type Decimal from "decimal.js";+import { usdFormatter } from "@/src/utils/numbers";export type TracesTableRow = {bookmarked: boolean;@@ -50,6 +52,7 @@ export type TracesTableRow = {completionTokens: number;totalTokens: number;};+ cost?: Decimal;};export type TracesTableProps = {@@ -159,6 +162,7 @@ export default function TracesTable({completionTokens: trace.completionTokens,totalTokens: trace.totalTokens,},+ cost: trace.calculatedTotalCost ?? undefined,};};@@ -305,6 +309,25 @@ export default function TracesTable({},enableHiding: true,},+ {+ accessorKey: "cost",+ id: "cost",+ header: "Cost",+ cell: ({ row }) => {+ const cost: Decimal | undefined = row.getValue("cost");+ return (+ <div>+ {cost ? (+ <span>{usdFormatter(cost.toNumber())}</span>+ ) : (+ <span>Not Available</span>+ )}+ </div>+ );+ },+ enableHiding: true,+ enableSorting: true,+ },{accessorKey: "scores",id: "scores",diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsxindex adaeb45d4c..1cfa8accff 100644--- a/src/components/trace/ObservationPreview.tsx+++ b/src/components/trace/ObservationPreview.tsx@@ -97,9 +97,11 @@ export const ObservationPreview = (props: {{preloadedObservation.model ? (<Badge variant="outline">{preloadedObservation.model}</Badge>) : null}- {preloadedObservation.price ? (+ {preloadedObservation.calculatedTotalCost ? (<Badge variant="outline">- {usdFormatter(preloadedObservation.price.toNumber())}+ {usdFormatter(+ preloadedObservation.calculatedTotalCost.toNumber(),+ )}</Badge>) : undefined}diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsxindex fa6486efda..be4132fb41 100644--- a/src/components/trace/index.tsx+++ b/src/components/trace/index.tsx@@ -136,9 +136,11 @@ export function TracePage({ traceId }: { traceId: string }) {const totalCost: Decimal | undefined = trace.data?.observations.reduce((prev: Decimal | undefined, curr: ObservationReturnType) => {- if (!curr.price) return prev;+ if (!curr.calculatedTotalCost) return prev;- return prev ? prev.plus(curr.price) : curr.price;+ return prev+ ? prev.plus(curr.calculatedTotalCost)+ : curr.calculatedTotalCost;},undefined,);diff --git a/src/features/dashboard/components/MetricTable.tsx b/src/features/dashboard/components/MetricTable.tsxindex e1c39d7ec4..4b6eeb9b1d 100644--- a/src/features/dashboard/components/MetricTable.tsx+++ b/src/features/dashboard/components/MetricTable.tsx@@ -26,13 +26,15 @@ export const MetricTable = ({projectId,from: "traces_observations",select: [- { column: "totalTokenCost" },+ { column: "calculatedTotalCost", agg: "SUM" },{ column: "totalTokens", agg: "SUM" },{ column: "model" },],filter: localFilters,groupBy: [{ type: "string", column: "model" }],- orderBy: [{ column: "totalTokenCost", direction: "DESC" }],+ orderBy: [+ { column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },+ ],},{trpc: {@@ -45,7 +47,10 @@ export const MetricTable = ({const totalTokens = metrics.data?.reduce((acc, curr) =>- acc + (curr.totalTokenCost ? (curr.totalTokenCost as number) : 0),+ acc ++ (curr.sumCalculatedTotalCost+ ? (curr.sumCalculatedTotalCost as number)+ : 0),0,);@@ -60,8 +65,8 @@ export const MetricTable = ({: "0"}</RightAlignedCell>,<RightAlignedCell key={`${i}-cost`}>- {item.totalTokenCost- ? usdFormatter(item.totalTokenCost as number, 2, 2)+ {item.sumCalculatedTotalCost+ ? usdFormatter(item.sumCalculatedTotalCost as number, 2, 2): "$0"}</RightAlignedCell>,])diff --git a/src/features/dashboard/components/ModelUsageChart.tsx b/src/features/dashboard/components/ModelUsageChart.tsxindex 9ef158ebb7..646ad80c61 100644--- a/src/features/dashboard/components/ModelUsageChart.tsx+++ b/src/features/dashboard/components/ModelUsageChart.tsx@@ -36,7 +36,7 @@ export const ModelUsageChart = ({from: "observations",select: [{ column: "totalTokens", agg: "SUM" },- { column: "totalTokenCost" },+ { column: "calculatedTotalCost", agg: "SUM" },{ column: "model" },],filter: globalFilterState,@@ -51,7 +51,9 @@ export const ModelUsageChart = ({column: "model",},],- orderBy: [{ column: "totalTokenCost", direction: "DESC" }],+ orderBy: [+ { column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },+ ],},{trpc: {@@ -78,19 +80,22 @@ export const ModelUsageChart = ({tokens.data && allModels.length > 0? fillMissingValuesAndTransform(extractTimeSeriesData(tokens.data, "startTime", [- { labelColumn: "model", valueColumn: "totalTokenCost" },+ {+ labelColumn: "model",+ valueColumn: "sumCalculatedTotalCost",+ },]),allModels,): [];const totalCost = tokens.data?.reduce(- (acc, curr) => acc + (curr.totalTokenCost as number),+ (acc, curr) => acc + (curr.sumCalculatedTotalCost as number),0,);const totalTokens = tokens.data?.reduce(- (acc, curr) => acc + (curr.sumTotalTokens as number),+ (acc, curr) => acc + (curr.sumCalculatedTotalCost as number),0,);diff --git a/src/features/dashboard/components/TracesBarListChart.tsx b/src/features/dashboard/components/TracesBarListChart.tsxindex 65334e7260..c882c109f7 100644--- a/src/features/dashboard/components/TracesBarListChart.tsx+++ b/src/features/dashboard/components/TracesBarListChart.tsx@@ -7,6 +7,7 @@ import { DashboardCard } from "@/src/features/dashboard/components/cards/Dashboaimport { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";import { BarList } from "@tremor/react";import { NoData } from "@/src/features/dashboard/components/NoData";+import { compactNumberFormatter } from "@/src/utils/numbers";export const TracesBarListChart = ({className,@@ -80,7 +81,9 @@ export const TracesBarListChart = ({><><TotalMetric- metric={totalTraces.data?.[0]?.countTraceId as number}+ metric={compactNumberFormatter(+ totalTraces.data?.[0]?.countTraceId as number,+ )}description={"Total traces tracked"}/>{adjustedData.length > 0 ? (diff --git a/src/features/dashboard/components/UserChart.tsx b/src/features/dashboard/components/UserChart.tsxindex ad2736f28e..68d6778ffa 100644--- a/src/features/dashboard/components/UserChart.tsx+++ b/src/features/dashboard/components/UserChart.tsx@@ -32,7 +32,7 @@ export const UserChart = ({projectId,from: "traces_observations",select: [- { column: "totalTokenCost" },+ { column: "calculatedTotalCost", agg: "SUM" },{ column: "user" },{ column: "traceId", agg: "COUNT" },],@@ -43,7 +43,9 @@ export const UserChart = ({column: "user",},],- orderBy: [{ column: "totalTokenCost", direction: "DESC" }],+ orderBy: [+ { column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },+ ],},{trpc: {@@ -97,13 +99,15 @@ export const UserChart = ({.map((item) => {return {name: (item.user as string | null | undefined) ?? "Unknown",- value: item.totalTokenCost ? (item.totalTokenCost as number) : 0,+ value: item.sumCalculatedTotalCost+ ? (item.sumCalculatedTotalCost as number)+ : 0,};}): [];const totalCost = user.data?.reduce(- (acc, curr) => acc + (curr.totalTokenCost as number),+ (acc, curr) => acc + (curr.sumCalculatedTotalCost as number),0,);diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.tsindex 9a948f999e..f738dd54e1 100644--- a/src/features/ingest/lib/usage.ts+++ b/src/features/ingest/lib/usage.ts@@ -1,13 +1,54 @@+import { isTiktokenModel } from "@/src/utils/types";+import { countTokens } from "@anthropic-ai/tokenizer";+import { type Model } from "@prisma/client";import {+ type TiktokenModel,+ type Tiktoken,type TiktokenEncoding,get_encoding,encoding_for_model,- type TiktokenModel,- type Tiktoken,} from "tiktoken";-import { countTokens } from "@anthropic-ai/tokenizer";-import { type PricingUnit, type Pricing } from "@prisma/client";-import { Decimal } from "decimal.js";+import { z } from "zod";++export function tokenCount(p: {+ model: Model;+ text: unknown;+}): number | undefined {+ if (+ p.text === null ||+ p.text === undefined ||+ (Array.isArray(p.text) && p.text.length === 0)+ ) {+ return undefined;+ }++ if (p.model.tokenizerId === "openai") {+ // check if the tokenizerConfig is a valid OpenAiTokenConfig+ const parsedConfig = OpenAiTokenConfig.safeParse(p.model.tokenizerConfig);+ if (!parsedConfig.success) {+ console.error(+ `Invalid tokenizer config for model ${p.model.id}: ${JSON.stringify(+ p.model.tokenizerConfig,+ )}`,+ );+ return undefined;+ }++ return openAiTokenCount({+ internalModel: p.model.modelName,+ config: parsedConfig.data,+ text: p.text,+ });+ } else if (p.model.tokenizerId === "claude") {+ return claudeTokenCount({+ internalModel: p.model.modelName,+ text: p.text,+ });+ } else {+ console.error(`Unknown tokenizer ${p.model.tokenizerId}`);+ return undefined;+ }+}type ChatMessage = {role: string;@@ -18,91 +59,61 @@ type ChatMessage = {type TokenCalculationParams = {messages: ChatMessage[];model: TiktokenModel;+ config: z.infer<typeof OpenAiTokenConfig>;};-export function tokenCount(p: {- model: string;+function openAiTokenCount(p: {+ internalModel: string;text: unknown;-}): number | undefined {- const model = cleanModelString(p.model);- if (- p.text === null ||- p.text === undefined ||- (Array.isArray(p.text) && p.text.length === 0)- ) {- return undefined;- } else if (isOpenAiModel(model)) {- return isChatMessageArray(p.text)- ? openAiChatTokenCount({- model: model,- messages: p.text,- })- : isString(p.text)- ? openAiStringTokenCount({ model: model, text: p.text })- : openAiStringTokenCount({- model: model,- text: JSON.stringify(p.text),- });- } else if (isClaudeModel(model)) {- return isString(p.text)- ? claudeStringTokenCount({ model: model, text: p.text })- : claudeStringTokenCount({- model: model,+ config: z.infer<typeof OpenAiTokenConfig>;+}) {+ if (!isOpenAiModel(p.internalModel)) return undefined;++ return isChatMessageArray(p.text)+ ? openAiChatTokenCount({+ model: p.internalModel,+ messages: p.text,+ config: p.config,+ })+ : isString(p.text)+ ? openAiStringTokenCount({ model: p.internalModel, text: p.text })+ : openAiStringTokenCount({+ model: p.internalModel,text: JSON.stringify(p.text),});- } else {- console.log("Unknown model provider", p.model);- return undefined;- }+}+function claudeTokenCount(p: { internalModel: string; text: unknown }) {+ return isString(p.text)+ ? countTokens(p.text)+ : countTokens(JSON.stringify(p.text));}-function openAiChatTokenCount(params: TokenCalculationParams) {- let tokens_per_message = 0;- let tokens_per_name = 0;+const OpenAiTokenConfig = z.object({+ tokensPerMessage: z.number(),+ tokensPerName: z.number(),+ tokenizerModel: z.string().refine(isTiktokenModel, {+ message: "Unknown model",+ }),+});- if (- [- "gpt-3.5-turbo-0613",- "gpt-3.5-turbo-16k-0613",- "gpt-4-0314",- "gpt-4-32k-0314",- "gpt-4-0613",- "gpt-4-32k-0613",- ].includes(params.model)- ) {- tokens_per_message = 3;- tokens_per_name = 1;- } else if (params.model === "gpt-3.5-turbo-0301") {- tokens_per_message = 4; // every message follows <|start|>{role/name}\n{content}<|end|>\n- tokens_per_name = -1; // if there's a name, the role is omitted- } else if (- params.model.includes("gpt-3.5-turbo") ||- params.model.startsWith("gpt-3.5")- ) {- return openAiChatTokenCount({ ...params, model: "gpt-3.5-turbo-0613" });- } else if (params.model.includes("gpt-4")) {- return openAiChatTokenCount({ ...params, model: "gpt-4-0613" });- } else {- console.error(`Not implemented for model ${params.model}`);- throw new Error(`Not implemented for model ${params.model}`);- }- let num_tokens = 0;+function openAiChatTokenCount(params: TokenCalculationParams) {+ let numTokens = 0;params.messages.forEach((message) => {- num_tokens += tokens_per_message;+ numTokens += params.config.tokensPerMessage;Object.keys(message).forEach((key) => {const value = message[key as keyof typeof message];if (value) {- num_tokens += getTokensByModel(params.model, value);+ numTokens += getTokensByModel(params.config.tokenizerModel, value);}if (key === "name") {- num_tokens += tokens_per_name;+ numTokens += params.config.tokensPerName;}});});- num_tokens += 3; // every reply is primed with <| start |> assistant <| message |>+ numTokens += 3; // every reply is primed with <| start |> assistant <| message |>- return num_tokens;+ return numTokens;}const openAiStringTokenCount = (p: { model: string; text: string }) => {@@ -110,25 +121,19 @@ const openAiStringTokenCount = (p: { model: string; text: string }) => {p.model.toLowerCase().startsWith("gpt") ||p.model.toLowerCase().includes("ada")) {- return getTokens("cl100k_base", p.text);+ return getTokensByEncoding("cl100k_base", p.text);}if (p.model.toLowerCase().startsWith("text-davinci")) {- return getTokens("p50k_base", p.text);+ return getTokensByEncoding("p50k_base", p.text);}console.log("Unknown model", p.model);return undefined;};-const claudeStringTokenCount = (p: { model: string; text: string }) => {- return countTokens(p.text);-};--const getTokens = (name: TiktokenEncoding, text: string) => {+const getTokensByEncoding = (name: TiktokenEncoding, text: string) => {const encoding = get_encoding(name);const tokens = encoding.encode(text);- // https://github.com/dqbd/tiktoken/issues/72- // we need to ensure to deallocate memory from the encoder- encoding.free();+return tokens.length;};@@ -141,72 +146,15 @@ const getTokensByModel = (model: TiktokenModel, text: string) => {encoding = get_encoding("cl100k_base");}- const length = encoding.encode(text).length;-- // https://github.com/dqbd/tiktoken/issues/72- // we need to ensure to deallocate memory from the encoder- encoding.free();- return length;+ return encoding.encode(text).length;};function isString(value: unknown): value is string {return typeof value === "string";}-function isClaudeModel(model: string) {- return model.toLowerCase().startsWith("claude");-}-function isOpenAiModel(model: string): model is TiktokenModel {- return (- [- "text-davinci-003",- "text-davinci-002",- "text-davinci-001",- "text-curie-001",- "text-babbage-001",- "text-ada-001",- "davinci",- "curie",- "babbage",- "ada",- "code-davinci-002",- "code-davinci-001",- "code-cushman-002",- "code-cushman-001",- "davinci-codex",- "cushman-codex",- "text-davinci-edit-001",- "code-davinci-edit-001",- "text-embedding-ada-002",- "text-similarity-davinci-001",- "text-similarity-curie-001",- "text-similarity-babbage-001",- "text-similarity-ada-001",- "text-search-davinci-doc-001",- "text-search-curie-doc-001",- "text-search-babbage-doc-001",- "text-search-ada-doc-001",- "code-search-babbage-code-001",- "code-search-ada-code-001",- "gpt2",- "gpt-4",- "gpt-4-0314",- "gpt-4-0613",- "gpt-4-32k",- "gpt-4-32k-0314",- "gpt-4-32k-0613",- "gpt-4-1106-preview",- "gpt-4-vision-preview",- "gpt-3.5",- "gpt-3.5-turbo",- "gpt-3.5-turbo-0301",- "gpt-3.5-turbo-0613",- "gpt-3.5-turbo-16k",- "gpt-3.5-turbo-16k-0613",- "gpt-3.5-turbo-1106",- ].find((m) => m === model) !== undefined- );+ return !!model.includes(model as TiktokenModel);}function isChatMessageArray(value: unknown): value is ChatMessage[] {@@ -225,94 +173,3 @@ function isChatMessageArray(value: unknown): value is ChatMessage[] {(!("name" in item) || typeof item.name === "string"),);}--export function calculateTokenCost(- pricingList: Pricing[],- input: {- model: string;- input: unknown;- output: unknown;- totalTokens: Decimal;- promptTokens: Decimal;- completionTokens: Decimal;- },-): Decimal | undefined {- const model = cleanModelString(input.model);- const pricing = pricingList.filter((p) => p.modelName === model);-- if (pricing.length === 0) {- console.log("no pricing found for model", input.model);- return undefined;- } else {- if (pricing.length === 1 && pricing[0]?.tokenType === "TOTAL") {- return calculateValue(- pricing[0].price,- pricing[0].pricingUnit,- input.totalTokens,- JSON.stringify(input.input) + JSON.stringify(input.output),- );- }-- if (pricing.length === 2) {- let promptPrice: Decimal = new Decimal(0);- let completionPrice: Decimal = new Decimal(0);-- const promptPricing = pricing.find((p) => p.tokenType === "PROMPT");- const completionPricing = pricing.find(- (p) => p.tokenType === "COMPLETION",- );-- if (promptPricing) {- promptPrice =- calculateValue(- promptPricing.price,- promptPricing.pricingUnit,- input.promptTokens,- JSON.stringify(input.input),- ) ?? new Decimal(0);- }-- if (completionPricing) {- completionPrice =- calculateValue(- completionPricing.price,- completionPricing.pricingUnit,- input.completionTokens,- JSON.stringify(input.output),- ) ?? new Decimal(0);- }-- return promptPrice.plus(completionPrice);- }- console.log("unknown model", input.model);- return undefined;- }-}--const calculateValue = (- price: Decimal,- unit: PricingUnit,- tokens: Decimal,- characters: string,-) => {- switch (unit) {- case "PER_1000_TOKENS":- return price- .times(tokens.dividedBy(new Decimal(1000)))- .toDecimalPlaces(5);- case "PER_1000_CHARS":- return (- price- // strip whitespace, default for google bison, only character based model for now- .times(new Decimal(characters.replace(/\s/g, "").length))- .dividedBy(new Decimal(1000))- .toDecimalPlaces(5)- );- default:- console.log("unknown pricing unit", unit);- return undefined;- }-};--const cleanModelString = (model: string) =>- model.toLowerCase().replaceAll("gpt-35", "gpt-3.5");diff --git a/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.tsindex 05951dfe1c..62197ac723 100644--- a/src/features/public-api/server/ingestion-api-schema.ts+++ b/src/features/public-api/server/ingestion-api-schema.ts@@ -8,6 +8,9 @@ export const Usage = z.object({output: z.number().int().nullish(),total: z.number().int().nullish(),unit: z.enum(["TOKENS", "CHARACTERS"]).nullable(),+ inputCost: z.number().nullish(),+ outputCost: z.number().nullish(),+ totalCost: z.number().nullish(),});const MixedUsage = z.object({@@ -18,8 +21,13 @@ const MixedUsage = z.object({promptTokens: z.number().int().nullish(),completionTokens: z.number().int().nullish(),totalTokens: z.number().int().nullish(),+ inputCost: z.number().nullish(),+ outputCost: z.number().nullish(),+ totalCost: z.number().nullish(),});+export const stringDate = z.string().datetime({ offset: true }).nullish();+export const usage = MixedUsage.nullish()// transform mixed usage model input to new one.transform((v) => {@@ -64,7 +72,7 @@ export const TraceBody = z.object({export const OptionalObservationBody = z.object({traceId: z.string().nullish(),name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),+ startTime: stringDate,metadata: jsonSchema.nullish(),input: jsonSchema.nullish(),output: jsonSchema.nullish(),@@ -83,15 +91,15 @@ export const UpdateEventEvent = OptionalObservationBody.extend({});export const CreateSpanBody = CreateEventEvent.extend({- endTime: z.string().datetime({ offset: true }).nullish(),+ endTime: stringDate,});export const UpdateSpanBody = UpdateEventEvent.extend({- endTime: z.string().datetime({ offset: true }).nullish(),+ endTime: stringDate,});export const CreateGenerationBody = CreateSpanBody.extend({- completionStartTime: z.string().datetime({ offset: true }).nullish(),+ completionStartTime: stringDate,model: z.string().nullish(),modelParameters: z.record(@@ -113,7 +121,7 @@ export const CreateGenerationBody = CreateSpanBody.extend({});export const UpdateGenerationBody = UpdateSpanBody.extend({- completionStartTime: z.string().datetime({ offset: true }).nullish(),+ completionStartTime: stringDate,model: z.string().nullish(),modelParameters: z.record(@@ -148,8 +156,8 @@ export const LegacySpanPostSchema = z.object({id: z.string().nullish(),traceId: z.string().nullish(),name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),- endTime: z.string().datetime({ offset: true }).nullish(),+ startTime: stringDate,+ endTime: stringDate,metadata: jsonSchema.nullish(),input: jsonSchema.nullish(),output: jsonSchema.nullish(),@@ -163,8 +171,8 @@ export const LegacySpanPatchSchema = z.object({spanId: z.string(),traceId: z.string().nullish(),name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),- endTime: z.string().datetime({ offset: true }).nullish(),+ startTime: stringDate,+ endTime: stringDate,metadata: jsonSchema.nullish(),input: jsonSchema.nullish(),output: jsonSchema.nullish(),@@ -177,9 +185,9 @@ export const LegacyGenerationsCreateSchema = z.object({id: z.string().nullish(),traceId: z.string().nullish(),name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),- endTime: z.string().datetime({ offset: true }).nullish(),- completionStartTime: z.string().datetime({ offset: true }).nullish(),+ startTime: stringDate,+ endTime: stringDate,+ completionStartTime: stringDate,model: z.string().nullish(),modelParameters: z.record(@@ -201,9 +209,9 @@ export const LegacyGenerationPatchSchema = z.object({generationId: z.string(),traceId: z.string().nullish(),name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),- endTime: z.string().datetime({ offset: true }).nullish(),- completionStartTime: z.string().datetime({ offset: true }).nullish(),+ startTime: stringDate,+ endTime: stringDate,+ completionStartTime: stringDate,model: z.string().nullish(),modelParameters: z.record(@@ -225,9 +233,9 @@ export const LegacyObservationBody = z.object({traceId: z.string().nullish(),type: z.enum(["GENERATION", "SPAN", "EVENT"]),name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),- endTime: z.string().datetime({ offset: true }).nullish(),- completionStartTime: z.string().datetime({ offset: true }).nullish(),+ startTime: stringDate,+ endTime: stringDate,+ completionStartTime: stringDate,model: z.string().nullish(),modelParameters: z.record(diff --git a/src/pages/project/[projectId]/models.tsx b/src/pages/project/[projectId]/models.tsxnew file mode 100644index 0000000000..8100902ea6--- /dev/null+++ b/src/pages/project/[projectId]/models.tsx@@ -0,0 +1,23 @@+import Header from "@/src/components/layouts/header";++import { useRouter } from "next/router";+import ModelTable from "@/src/components/table/use-cases/models";++export default function ModelsPage() {+ const router = useRouter();+ const projectId = router.query.projectId as string;++ return (+ <div>+ <Header+ title="Models"+ help={{+ description:+ "A model represents a LLM model. It is used to calculate tokens and cost.",+ href: "https://langfuse.com/docs/token-usage",+ }}+ />+ <ModelTable projectId={projectId} />+ </div>+ );+}diff --git a/src/server/api/definitions/observationsTable.ts b/src/server/api/definitions/observationsTable.tsindex b790c6af99..c24722812e 100644--- a/src/server/api/definitions/observationsTable.ts+++ b/src/server/api/definitions/observationsTable.ts@@ -46,6 +46,11 @@ export const observationsTableCols: ColumnDefinition[] = [type: "number",internal: '"latency"',},+ {+ name: "Cost ($)",+ type: "number",+ internal: 'o."calculated_total_cost"',+ },{name: "level",id: "level",diff --git a/src/server/api/definitions/tracesTable.ts b/src/server/api/definitions/tracesTable.tsindex bf5579bfe6..fea79c585a 100644--- a/src/server/api/definitions/tracesTable.ts+++ b/src/server/api/definitions/tracesTable.ts@@ -38,6 +38,12 @@ export const tracesTableCols: ColumnDefinition[] = [type: "number",internal: "tl.latency",},+ {+ name: "Cost ($)",+ id: "cost",+ type: "number",+ internal: '"calculatedTotalCost"',+ },{name: "version",id: "version",diff --git a/src/server/api/root.ts b/src/server/api/root.tsindex 94b669f433..68f734ca50 100644--- a/src/server/api/root.ts+++ b/src/server/api/root.ts@@ -13,6 +13,7 @@ import { usageMeteringRouter } from "@/src/features/usage-metering/server/usageMimport { observationsRouter } from "@/src/server/api/routers/observations";import { sessionRouter } from "@/src/server/api/routers/sessions";import { promptRouter } from "@/src/features/prompts/server/prompt-router";+import { modelRouter } from "@/src/server/api/routers/models";/*** This is the primary router for your server.@@ -34,6 +35,7 @@ export const appRouter = createTRPCRouter({usageMetering: usageMeteringRouter,observations: observationsRouter,prompts: promptRouter,+ models: modelRouter,});// export type definition of APIdiff --git a/src/server/api/routers/generations.ts b/src/server/api/routers/generations.tsindex ef80f01dad..4eca65623a 100644--- a/src/server/api/routers/generations.ts+++ b/src/server/api/routers/generations.ts@@ -5,7 +5,7 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";-import { type Observation, Prisma } from "@prisma/client";+import { Prisma, type ObservationView } from "@prisma/client";import { jsonSchema, paginationZod } from "@/src/utils/zod";import { singleFilter } from "@/src/server/api/interfaces/filters";import {@@ -16,8 +16,6 @@ import {type ObservationOptions,observationsTableCols,} from "@/src/server/api/definitions/observationsTable";-import { calculateTokenCost } from "@/src/features/ingest/lib/usage";-import Decimal from "decimal.js";import { usdFormatter } from "@/src/utils/numbers";import { env } from "@/src/env.mjs";import {@@ -87,10 +85,9 @@ export const generationsRouter = createTRPCRouter({const generations = await ctx.prisma.$queryRaw<Array<- Observation & {+ ObservationView & {traceId: string;traceName: string;- totalCount: number;latency: number | null;}>@@ -100,7 +97,7 @@ export const generationsRouter = createTRPCRouter({SELECTo.*,CASE WHEN o.end_time IS NULL THEN NULL ELSE (EXTRACT(EPOCH FROM o."end_time") - EXTRACT(EPOCH FROM o."start_time"))::double precision END AS "latency"- FROM observations o+ FROM observations_view oWHERE o.type = 'GENERATION'AND o.project_id = ${input.projectId}${datetimeFilter}@@ -123,7 +120,14 @@ export const generationsRouter = createTRPCRouter({o.total_tokens as "totalTokens",o.level,o.status_message as "statusMessage",- o.version+ o.version,+ o.model_id as "modelId",+ o.input_price as "inputPrice",+ o.output_price as "outputPrice",+ o.total_price as "totalPrice",+ o.calculated_input_cost as "calculatedInputCost",+ o.calculated_output_cost as "calculatedOutputCost",+ o.calculated_total_cost as "calculatedTotalCost"FROM observations_with_latency oJOIN traces t ON t.id = o.trace_idWHERE@@ -144,7 +148,7 @@ export const generationsRouter = createTRPCRouter({SELECTo.*,CASE WHEN o.end_time IS NULL THEN NULL ELSE (EXTRACT(EPOCH FROM o."end_time") - EXTRACT(EPOCH FROM o."start_time"))::double precision END AS "latency"- FROM observations o+ FROM observations_view oWHERE o.type = 'GENERATION'AND o.project_id = ${input.projectId}${datetimeFilter}@@ -160,27 +164,10 @@ export const generationsRouter = createTRPCRouter({`,);- const pricings = await ctx.prisma.pricing.findMany();const count = totalGenerations[0]?.count;return {totalCount: count ? Number(count) : undefined,- generations: generations.map(({ input, output, ...rest }) => {- return {- ...rest,- input,- output,- cost: rest.model- ? calculateTokenCost(pricings, {- model: rest.model,- totalTokens: new Decimal(rest.totalTokens),- promptTokens: new Decimal(rest.promptTokens),- completionTokens: new Decimal(rest.completionTokens),- input: input,- output: output,- })- : undefined,- };- }),+ generations: generations,};}),@@ -204,7 +191,7 @@ export const generationsRouter = createTRPCRouter({const generations = await ctx.prisma.$queryRaw<Array<- Observation & {+ ObservationView & {traceId: string;traceName: string;}@@ -226,8 +213,15 @@ export const generationsRouter = createTRPCRouter({o.prompt_tokens as "promptTokens",o.completion_tokens as "completionTokens",o.total_tokens as "totalTokens",- o.version- FROM observations o+ o.version,+ o.model_id as "modelId",+ o.input_price as "inputPrice",+ o.output_price as "outputPrice",+ o.total_price as "totalPrice",+ o.calculated_input_cost as "calculatedInputCost",+ o.calculated_output_cost as "calculatedOutputCost",+ o.calculated_total_cost as "calculatedTotalCost"+ FROM observations_view oJOIN traces t ON t.id = o.trace_idWHERE o.type = 'GENERATION'AND o.project_id = ${input.projectId}@@ -238,28 +232,6 @@ export const generationsRouter = createTRPCRouter({`,);- const pricings = await ctx.prisma.pricing.findMany();-- const enrichedGenerations = generations.map(- ({ input, output, ...rest }) => {- return {- ...rest,- input,- output,- cost: rest.model- ? calculateTokenCost(pricings, {- model: rest.model,- totalTokens: new Decimal(rest.totalTokens),- promptTokens: new Decimal(rest.promptTokens),- completionTokens: new Decimal(rest.completionTokens),- input: input,- output: output,- })- : undefined,- };- },- );-let output: string = "";// create file@@ -279,15 +251,19 @@ export const generationsRouter = createTRPCRouter({],].concat(- enrichedGenerations.map((generation) =>+ generations.map((generation) =>[generation.traceId,generation.name ?? "",generation.model ?? "",generation.startTime.toISOString(),generation.endTime?.toISOString() ?? "",- generation.cost- ? usdFormatter(generation.cost.toNumber(), 2, 8)+ generation.calculatedTotalCost+ ? usdFormatter(+ generation.calculatedTotalCost.toNumber(),+ 2,+ 8,+ ): "",JSON.stringify(generation.input),JSON.stringify(generation.output),@@ -302,7 +278,7 @@ export const generationsRouter = createTRPCRouter({.join("\n");break;case "JSON":- output = JSON.stringify(enrichedGenerations);+ output = JSON.stringify(generations);break;case "OPENAI-JSONL":const inputSchemaOpenAI = z.array(@@ -316,7 +292,7 @@ export const generationsRouter = createTRPCRouter({completion: jsonSchema,}).or(jsonSchema);- output = enrichedGenerations+ output = generations.map((generation) => ({parsedInput: inputSchemaOpenAI.safeParse(generation.input),parsedOutput: outputSchema.safeParse(generation.output),@@ -346,7 +322,7 @@ export const generationsRouter = createTRPCRouter({// to jsonl.map((row) => JSON.stringify(row)).join("\n");- console.log(output);+break;default:throw new Error("Invalid export file format");diff --git a/src/server/api/routers/models.ts b/src/server/api/routers/models.tsnew file mode 100644index 0000000000..f16d18765d--- /dev/null+++ b/src/server/api/routers/models.ts@@ -0,0 +1,38 @@+import { z } from "zod";++import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { paginationZod } from "@/src/utils/zod";++const ModelAllOptions = z.object({+ projectId: z.string(),+ ...paginationZod,+});++export const modelRouter = createTRPCRouter({+ all: protectedProjectProcedure+ .input(ModelAllOptions)+ .query(async ({ input, ctx }) => {+ const models = await ctx.prisma.model.findMany({+ where: {+ OR: [{ projectId: input.projectId }, { projectId: null }],+ },+ skip: input.page * input.limit,+ orderBy: [{ modelName: "asc" }, { startDate: "desc" }],+ take: input.limit,+ });++ const totalAmount = await ctx.prisma.model.count({+ where: {+ OR: [{ projectId: input.projectId }, { projectId: null }],+ },+ });++ return {+ models,+ totalCount: totalAmount,+ };+ }),+});diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.tsindex f3e2dfc49f..1b1222e8ae 100644--- a/src/server/api/routers/traces.ts+++ b/src/server/api/routers/traces.ts@@ -5,9 +5,7 @@ import {protectedGetTraceProcedure,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { type Observation, Prisma, type Trace } from "@prisma/client";-import { calculateTokenCost } from "@/src/features/ingest/lib/usage";-import Decimal from "decimal.js";+import { Prisma, type Trace, type ObservationView } from "@prisma/client";import { paginationZod } from "@/src/utils/zod";import { singleFilter } from "@/src/server/api/interfaces/filters";import {@@ -23,6 +21,8 @@ import { TRPCError } from "@trpc/server";import { orderBy } from "@/src/server/api/interfaces/orderBy";import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";import { type Sql } from "@prisma/client/runtime/library";+import { instrumentAsync } from "@/src/utils/instrumentation";+import type Decimal from "decimal.js";const TraceFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -32,9 +32,12 @@ const TraceFilterOptions = z.object({...paginationZod,});-export type ObservationReturnType = Omit<Observation, "input" | "output"> & {+export type ObservationReturnType = Omit<+ ObservationView,+ "input" | "output"+> & {traceId: string;-} & { price?: Decimal };+};export const traceRouter = createTRPCRouter({all: protectedProjectProcedure@@ -80,7 +83,10 @@ export const traceRouter = createTRPCRouter({COALESCE(u."promptTokens", 0)::int AS "promptTokens",COALESCE(u."completionTokens", 0)::int AS "completionTokens",COALESCE(u."totalTokens", 0)::int AS "totalTokens",- tl.latency AS "latency"`,+ tl.latency AS "latency",+ COALESCE(u."calculatedTotalCost", 0)::numeric AS "calculatedTotalCost"+ `,+input.projectId,observationTimeseriesFilter,input.page,@@ -90,17 +96,22 @@ export const traceRouter = createTRPCRouter({orderByCondition,);- const traces = await ctx.prisma.$queryRaw<- Array<- Trace & {- promptTokens: number;- completionTokens: number;- totalTokens: number;- totalCount: number;- latency: number | null;- }- >- >(tracesQuery);+ const traces = await instrumentAsync(+ { name: "get-all-traces" },+ async () =>+ await ctx.prisma.$queryRaw<+ Array<+ Trace & {+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+ totalCount: number;+ latency: number | null;+ calculatedTotalCost: Decimal | null;+ }+ >+ >(tracesQuery),+ );const countQyery = createTracesQuery(Prisma.sql`count(*)`,@@ -196,7 +207,7 @@ export const traceRouter = createTRPCRouter({scores: true,},});- const observations = await ctx.prisma.observation.findMany({+ const observations = await ctx.prisma.observationView.findMany({where: {traceId: {equals: input.traceId,@@ -204,7 +215,6 @@ export const traceRouter = createTRPCRouter({},},});- const pricings = await ctx.prisma.pricing.findMany();const obsStartTimes = observations.map((o) => o.startTime)@@ -224,28 +234,14 @@ export const traceRouter = createTRPCRouter({: undefined: undefined;- const enrichedObservations = observations.map(- ({ input, output, ...rest }) => {- return {- ...rest,- price: rest.model- ? calculateTokenCost(pricings, {- model: rest.model,- totalTokens: new Decimal(rest.totalTokens),- promptTokens: new Decimal(rest.promptTokens),- completionTokens: new Decimal(rest.completionTokens),- input: input,- output: output,- })- : undefined,- };- },- );-return {...trace,latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,- observations: enrichedObservations as ObservationReturnType[],+ observations: observations.map(+ ({ input: _input, output: _output, ...rest }) => {+ return { ...rest };+ },+ ) as ObservationReturnType[],};}),deleteMany: protectedProjectProcedure@@ -414,9 +410,10 @@ function createTracesQuery(trace_id,sum(prompt_tokens) AS "promptTokens",sum(completion_tokens) AS "completionTokens",- sum(total_tokens) AS "totalTokens"+ sum(total_tokens) AS "totalTokens",+ sum(calculated_total_cost) AS "calculatedTotalCost"FROM- "observations"+ "observations_view"WHERE"trace_id" IS NOT NULLAND "type" = 'GENERATION'diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.tsindex 1aafffec82..9cab8d49af 100644--- a/src/server/api/services/EventProcessor.ts+++ b/src/server/api/services/EventProcessor.ts@@ -22,7 +22,8 @@ import {type Trace,type Observation,type Score,- type Prisma,+ Prisma,+ type Model,} from "@prisma/client";import { v4 } from "uuid";import { type z } from "zod";@@ -34,6 +35,66 @@ export interface EventProcessor {): Promise<Trace | Observation | Score> | undefined;}+export const findModel = async (+ projectId: string,+ model?: string,+ unit?: string,+ startTime?: string,+ existingObservation?: Observation,+) => {+ // either get the model from the existing observation+ // or match pattern on the user provided model name+ const modelCondition = model+ ? Prisma.sql`AND ${model} ~ match_pattern`+ : existingObservation?.internalModel+ ? Prisma.sql`AND model_name = ${existingObservation.internalModel}`+ : undefined;++ // usage either from existing generation or from the current event+ const mergedUnit = unit ?? existingObservation?.unit;++ const unitCondition = mergedUnit+ ? Prisma.sql`AND unit = ${mergedUnit}`+ : Prisma.empty;++ if (!modelCondition) {+ return;+ } else {+ const sql = Prisma.sql`+ SELECT+ id,+ created_at AS "createdAt",+ updated_at AS "updatedAt",+ project_id AS "projectId",+ model_name AS "modelName",+ match_pattern AS "matchPattern",+ start_date AS "startDate",+ input_price AS "inputPrice",+ output_price AS "outputPrice",+ total_price AS "totalPrice",+ unit,+ tokenizer_id AS "tokenizerId",+ tokenizer_config AS "tokenizerConfig"+ FROM+ models+ WHERE (project_id = ${projectId}+ OR project_id IS NULL)+ ${modelCondition}+ ${unitCondition}+ AND (start_date IS NULL OR start_date <= ${+ startTime ? new Date(startTime) : new Date()+ }::timestamp with time zone at time zone 'UTC')+ ORDER BY+ project_id ASC,+ start_date DESC+ LIMIT 1;`;++ const foundModels = await prisma.$queryRaw<Array<Model>>(sql);++ return foundModels[0] ?? undefined;+ }+};+export class ObservationProcessor implements EventProcessor {event:| z.infer<typeof legacyObservationCreateEvent>@@ -95,6 +156,19 @@ export class ObservationProcessor implements EventProcessor {throw new ResourceNotFoundError(this.event.id, "Observation not found");}+ // we need to get the matching model on each generation+ // to be able to calculate the token counts+ const internalModel: Model | undefined =+ type === "GENERATION"+ ? await findModel(+ apiScope.projectId,+ "model" in body ? body.model ?? undefined : undefined,+ "usage" in body ? body.usage?.unit ?? undefined : undefined,+ startTime ?? undefined,+ existingObservation ?? undefined,+ )+ : undefined;+const finalTraceId =!traceId && !existingObservation? // Create trace if no traceid@@ -110,7 +184,11 @@ export class ObservationProcessor implements EventProcessor {const [newInputCount, newOutputCount] ="usage" in body- ? this.calculateTokenCounts(body, existingObservation ?? undefined)+ ? this.calculateTokenCounts(+ body,+ internalModel,+ existingObservation ?? undefined,+ ): [undefined, undefined];// merge metadata from existingObservation.metadata and metadata@@ -142,6 +220,7 @@ export class ObservationProcessor implements EventProcessor {console.warn("Prompt not found for observation", this.event.body);const observationId = id ?? v4();+return {id: observationId,create: {@@ -172,13 +251,22 @@ export class ObservationProcessor implements EventProcessor {"usage" in body? body.usage?.total ?? (newInputCount ?? 0) + (newOutputCount ?? 0): undefined,- unit: "usage" in body ? body.usage?.unit ?? undefined : undefined,+ unit:+ "usage" in body+ ? body.usage?.unit ?? internalModel?.unit+ : internalModel?.unit,level: body.level ?? undefined,statusMessage: body.statusMessage ?? undefined,parentObservationId: body.parentObservationId ?? undefined,version: body.version ?? undefined,projectId: apiScope.projectId,promptId: prompt ? prompt.id : undefined,+ ...(internalModel+ ? { internalModel: internalModel.modelName }+ : undefined),+ inputCost: "usage" in body ? body.usage?.inputCost : undefined,+ outputCost: "usage" in body ? body.usage?.outputCost : undefined,+ totalCost: "usage" in body ? body.usage?.totalCost : undefined,},update: {name,@@ -205,12 +293,21 @@ export class ObservationProcessor implements EventProcessor {"usage" in body? body.usage?.total ?? (newInputCount ?? 0) + (newOutputCount ?? 0): undefined,- unit: "usage" in body ? body.usage?.unit ?? undefined : undefined,+ unit:+ "usage" in body+ ? body.usage?.unit ?? internalModel?.unit+ : internalModel?.unit,level: body.level ?? undefined,statusMessage: body.statusMessage ?? undefined,parentObservationId: body.parentObservationId ?? undefined,version: body.version ?? undefined,promptId: prompt ? prompt.id : undefined,+ ...(internalModel+ ? { internalModel: internalModel.modelName }+ : undefined),+ inputCost: "usage" in body ? body.usage?.inputCost : undefined,+ outputCost: "usage" in body ? body.usage?.outputCost : undefined,+ totalCost: "usage" in body ? body.usage?.totalCost : undefined,},};}@@ -219,27 +316,30 @@ export class ObservationProcessor implements EventProcessor {body:| z.infer<typeof legacyObservationCreateEvent>["body"]| z.infer<typeof generationCreateEvent>["body"],+ model?: Model,existingObservation?: Observation,) {- const mergedModel = body.model ?? existingObservation?.model;-+ console.log("calculate tokens for ", model);const newPromptTokens =body.usage?.input ??- ((body.input || existingObservation?.input) && mergedModel+ ((body.input || existingObservation?.input) && model && model.tokenizerId? tokenCount({- model: mergedModel,+ model: model,text: body.input ?? existingObservation?.input,}): undefined);const newCompletionTokens =body.usage?.output ??- ((body.output || existingObservation?.output) && mergedModel+ ((body.output || existingObservation?.output) &&+ model &&+ model.tokenizerId? tokenCount({- model: mergedModel,+ model: model,text: body.output ?? existingObservation?.output,}): undefined);+return [newPromptTokens, newCompletionTokens];}diff --git a/src/server/api/services/tableDefinitions.ts b/src/server/api/services/tableDefinitions.tsindex 7942f0a7a9..f44ea409a3 100644--- a/src/server/api/services/tableDefinitions.ts+++ b/src/server/api/services/tableDefinitions.ts@@ -87,41 +87,10 @@ export const traceUser = {internal: 't."user_id"',} as const;-export const totalTokenCost = {- name: "totalTokenCost",+export const calculatedTotalCost = {+ name: "calculatedTotalCost",type: "number",- internal: `- sum(- CASE- -- Finetuned- WHEN (o."model" LIKE '%ada:%') THEN 0.0016 * o."prompt_tokens" + 0.0016 * o."completion_tokens"- WHEN (o."model" LIKE '%babbage:%') THEN 0.0024 * o."prompt_tokens" + 0.0024 * o."completion_tokens"- WHEN (o."model" LIKE '%curie:%') THEN 0.012 * o."prompt_tokens" + 0.012 * o."completion_tokens"- WHEN (o."model" LIKE '%davinci:%') THEN 0.12 * o."prompt_tokens" + 0.12 * o."completion_tokens"- -- Non-finetuned- WHEN (o."model" LIKE '%gpt-4-1106-preview%') THEN 0.01 * o."prompt_tokens" + 0.03 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-4-1106-vision-preview%') THEN 0.01 * o."prompt_tokens" + 0.03 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-4-32k%') THEN 0.06 * o."prompt_tokens" + 0.12 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-3.5-turbo-0613%') THEN 0.0015 * o."prompt_tokens" + 0.002 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-3.5-turbo-16k-0613%') THEN 0.003 * o."prompt_tokens" + 0.004 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-3.5-turbo-1106%') THEN 0.001 * o."prompt_tokens" + 0.002 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-3.5-turbo-instruct%') THEN 0.0015 * o."prompt_tokens" + 0.002 * o."completion_tokens"- WHEN (o."model" LIKE '%text-embedding-ada-002%') THEN 0.0001 * o."prompt_tokens" + 0.0001 * coalesce(o."completion_tokens", 0)- WHEN (o."model" LIKE '%ada%') THEN 0.0001 * o."prompt_tokens" + 0.0001 * o."completion_tokens"- WHEN (o."model" LIKE '%babbage%') THEN 0.0005 * o."prompt_tokens" + 0.0005 * o."completion_tokens"- WHEN (o."model" LIKE '%curie%') THEN 0.002 * o."prompt_tokens" + 0.002 * o."completion_tokens"- WHEN (o."model" LIKE '%davinci%') THEN 0.02 * o."prompt_tokens" + 0.02 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-3.5-turbo%') THEN 0.0015 * o."prompt_tokens" + 0.002 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-35-turbo%') THEN 0.0015 * o."prompt_tokens" + 0.002 * o."completion_tokens"- WHEN (o."model" LIKE '%gpt-4%') THEN 0.03 * o."prompt_tokens" + 0.06 * o."completion_tokens"- WHEN (o."model" LIKE '%claude-1%') THEN 0.01102 * o."prompt_tokens" + 0.03268 * o."completion_tokens"- WHEN (o."model" LIKE '%claude-2%') THEN 0.01102 * o."prompt_tokens" + 0.03268 * o."completion_tokens"- WHEN (o."model" LIKE '%claude-instant-1%') THEN 0.00163 * o."prompt_tokens" + 0.00551 * o."completion_tokens"- WHEN (o."model" LIKE '%bison%') THEN 0.0005 * LENGTH(REPLACE(o."input"::text, ' ', '')) + 0.0005 * LENGTH(REPLACE(o."output"::text, ' ', ''))- ELSE 0- END- ) / 1000- `,+ internal: 'o."calculated_total_cost"',} as const;export const tableDefinitions: TableDefinitions = {@@ -138,7 +107,7 @@ export const tableDefinitions: TableDefinitions = {],},traces_observations: {- table: ` traces t LEFT JOIN observations o ON t.id = o.trace_id`,+ table: ` traces t LEFT JOIN observations_view o ON t.id = o.trace_id`,columns: [traceId,observationId,@@ -146,7 +115,7 @@ export const tableDefinitions: TableDefinitions = {tracesProjectId,observationsProjectId,duration,- totalTokenCost,+ calculatedTotalCost,totalTokens,model,traceTimestamp,@@ -155,10 +124,10 @@ export const tableDefinitions: TableDefinitions = {],},observations: {- table: ` observations o`,+ table: ` observations_view o`,columns: [traceId,- totalTokenCost,+ calculatedTotalCost,observationName,{ name: "type", type: "string", internal: 'o."type"' },completionTokens,@@ -195,7 +164,7 @@ export const tableDefinitions: TableDefinitions = {],},traces_parent_observation_scores: {- table: ` traces t LEFT JOIN observations o on t."id" = o."trace_id" and o."parent_observation_id" is NULL LEFT JOIN scores s ON t."id" = s."trace_id"`,+ table: ` traces t LEFT JOIN observations_view o on t."id" = o."trace_id" and o."parent_observation_id" is NULL LEFT JOIN scores s ON t."id" = s."trace_id"`,columns: [{ name: "projectId", type: "string", internal: 't."project_id"' },{ name: "value", type: "number", internal: 's."value"' },diff --git a/src/utils/types.ts b/src/utils/types.tsindex fbbe8d1e65..8dd70f4db7 100644--- a/src/utils/types.ts+++ b/src/utils/types.ts@@ -6,6 +6,7 @@ import {dateTimeAggregationOptions,} from "@/src/features/dashboard/lib/timeseries-aggregation";import { type ObservationReturnType } from "@/src/server/api/routers/traces";+import { type TiktokenModel } from "tiktoken";export type NestedObservation = ObservationReturnType & {children: NestedObservation[];@@ -52,3 +53,55 @@ export function isValidOption(dateTimeAggregationOptions.includes(value as DateTimeAggregationOption));}++export const isTiktokenModel = (model: string): model is TiktokenModel => {+ return [+ "davinci-002",+ "babbage-002",+ "text-davinci-003",+ "text-davinci-002",+ "text-davinci-001",+ "text-curie-001",+ "text-babbage-001",+ "text-ada-001",+ "davinci",+ "curie",+ "babbage",+ "ada",+ "code-davinci-002",+ "code-davinci-001",+ "code-cushman-002",+ "code-cushman-001",+ "davinci-codex",+ "cushman-codex",+ "text-davinci-edit-001",+ "code-davinci-edit-001",+ "text-embedding-ada-002",+ "text-similarity-davinci-001",+ "text-similarity-curie-001",+ "text-similarity-babbage-001",+ "text-similarity-ada-001",+ "text-search-davinci-doc-001",+ "text-search-curie-doc-001",+ "text-search-babbage-doc-001",+ "text-search-ada-doc-001",+ "code-search-babbage-code-001",+ "code-search-ada-code-001",+ "gpt2",+ "gpt-4",+ "gpt-4-0314",+ "gpt-4-0613",+ "gpt-4-32k",+ "gpt-4-32k-0314",+ "gpt-4-32k-0613",+ "gpt-3.5-turbo",+ "gpt-35-turbo",+ "gpt-3.5-turbo-0301",+ "gpt-3.5-turbo-0613",+ "gpt-3.5-turbo-1106",+ "gpt-3.5-turbo-16k",+ "gpt-3.5-turbo-16k-0613",+ "gpt-4-1106-preview",+ "gpt-4-vision-preview",+ ].includes(model);+};