🪢 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
add USD cost calculation (#111)
Maximilian Deichmann01d66238de0e
diff --git a/package-lock.json b/package-lock.jsonindex d39fdf9869..2024399cc5 100644--- a/package-lock.json+++ b/package-lock.json@@ -49,6 +49,7 @@"clsx": "^1.2.1","cmdk": "^0.2.0","cors": "^2.8.5",+ "decimal.js": "^10.4.3","js-yaml": "^4.1.0","lodash": "^4.17.21","lucide-react": "^0.257.0",@@ -5745,8 +5746,7 @@"node_modules/decimal.js": {"version": "10.4.3","resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz",- "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==",- "dev": true+ "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA=="},"node_modules/decimal.js-light": {"version": "2.5.1",diff --git a/package.json b/package.jsonindex 66c3bb6872..9d6c41e3c2 100644--- a/package.json+++ b/package.json@@ -61,6 +61,7 @@"clsx": "^1.2.1","cmdk": "^0.2.0","cors": "^2.8.5",+ "decimal.js": "^10.4.3","js-yaml": "^4.1.0","lodash": "^4.17.21","lucide-react": "^0.257.0",diff --git a/prisma/migrations/20230901155252_add_pricings_table/migration.sql b/prisma/migrations/20230901155252_add_pricings_table/migration.sqlnew file mode 100644index 0000000000..da763584ec--- /dev/null+++ b/prisma/migrations/20230901155252_add_pricings_table/migration.sql@@ -0,0 +1,17 @@+-- CreateEnum+CREATE TYPE "PricingUnit" AS ENUM ('PER_1000_TOKENS');++-- CreateEnum+CREATE TYPE "TokenType" AS ENUM ('PROMPT', 'COMPLETION', 'TOTAL');++-- CreateTable+CREATE TABLE "pricings" (+ "id" TEXT NOT NULL,+ "model_name" TEXT NOT NULL,+ "pricing_unit" "PricingUnit" NOT NULL DEFAULT 'PER_1000_TOKENS',+ "price" DECIMAL(65,30) NOT NULL,+ "currency" TEXT NOT NULL DEFAULT 'USD',+ "token_type" "TokenType" NOT NULL,++ CONSTRAINT "pricings_pkey" PRIMARY KEY ("id")+);diff --git a/prisma/migrations/20230901155336_add_pricing_data/migration.sql b/prisma/migrations/20230901155336_add_pricing_data/migration.sqlnew file mode 100644index 0000000000..5e0ca3da70--- /dev/null+++ b/prisma/migrations/20230901155336_add_pricing_data/migration.sql@@ -0,0 +1,58 @@++-- This migration adds default prices for the models that are currently available on the LANGCHAIN platform.+-- https://github.com/langchain-ai/langchain/blob/e60e1cdf23ad73b2e0a40034c0ddfc3c8b0c9c4d/libs/langchain/langchain/callbacks/openai_info.py#L7++INSERT INTO pricings (+ id,+ model_name,+ pricing_unit,+ price,+ currency,+ token_type+)+VALUES+ ('clm0obv1u00003b6lc9etkzfg','gpt-4', 'PER_1000_TOKENS', 0.03, 'USD', 'PROMPT'),+ ('clm0obv1u00013b6l4jdl83vs','gpt-4-0314', 'PER_1000_TOKENS', 0.03, 'USD', 'PROMPT'),+ ('clm0obv1u00023b6lsi1d24dh','gpt-4-0613', 'PER_1000_TOKENS', 0.03, 'USD', 'PROMPT'),+ ('clm0obv1u00033b6lvv4h0iex','gpt-4-32k', 'PER_1000_TOKENS', 0.06, 'USD', 'PROMPT'),+ ('clm0obv1u00043b6ln5pleunh','gpt-4-32k-0314', 'PER_1000_TOKENS', 0.06, 'USD', 'PROMPT'),+ ('clm0obv1u00053b6l0g4zo5oe','gpt-4-32k-0613', 'PER_1000_TOKENS', 0.06, 'USD', 'PROMPT'),+ ('clm0obv1u00063b6lv7y80efe','gpt-4', 'PER_1000_TOKENS', 0.06, 'USD', 'COMPLETION'),+ ('clm0obv1u00073b6l302roky7','gpt-4-0314', 'PER_1000_TOKENS', 0.06, 'USD', 'COMPLETION'),+ ('clm0obv1u00083b6laz822qt4','gpt-4-0613', 'PER_1000_TOKENS', 0.06, 'USD', 'COMPLETION'),+ ('clm0obv1u00093b6l9ivm2fbs','gpt-4-32k', 'PER_1000_TOKENS', 0.12, 'USD', 'COMPLETION'),+ ('clm0obv1u000a3b6l7ou8mq4o','gpt-4-32k-0314', 'PER_1000_TOKENS', 0.12, 'USD', 'COMPLETION'),+ ('clm0obv1u000b3b6lym69vmpx','gpt-4-32k-0613', 'PER_1000_TOKENS', 0.12, 'USD', 'COMPLETION'),+ ('clm0obv1u000c3b6lfeg8e6gh','gpt-3.5-turbo', 'PER_1000_TOKENS', 0.0015, 'USD', 'PROMPT'),+ ('clm0obv1u000d3b6lb8ww3uj2','gpt-3.5-turbo-0301', 'PER_1000_TOKENS', 0.0015, 'USD', 'PROMPT'),+ ('clm0obv1u000e3b6lznniclze','gpt-3.5-turbo-0613', 'PER_1000_TOKENS', 0.0015, 'USD', 'PROMPT'),+ ('clm0obv1u000f3b6lr2bxjnxr','gpt-3.5-turbo-16k', 'PER_1000_TOKENS', 0.003, 'USD', 'PROMPT'),+ ('clm0obv1u000g3b6lo3rqrgpj','gpt-3.5-turbo-16k-0613', 'PER_1000_TOKENS', 0.003, 'USD', 'PROMPT'),+ ('clm0obv1u000h3b6lt1l33gpm','gpt-3.5-turbo', 'PER_1000_TOKENS', 0.002, 'USD', 'COMPLETION'),+ ('clm0obv1u000i3b6lgfs7pi5b','gpt-3.5-turbo-0301', 'PER_1000_TOKENS', 0.002, 'USD', 'COMPLETION'),+ ('clm0obv1u000j3b6lg1jokl07','gpt-3.5-turbo-0613', 'PER_1000_TOKENS', 0.002, 'USD', 'COMPLETION'),+ ('clm0obv1u000k3b6lgfntsm74','gpt-3.5-turbo-16k', 'PER_1000_TOKENS', 0.004, 'USD', 'COMPLETION'),+ ('clm0obv1u000l3b6l8wjhn0ie','gpt-3.5-turbo-16k-0613', 'PER_1000_TOKENS', 0.004, 'USD', 'COMPLETION'),+ ('clm0obv1u000m3b6lgrcel0ce','gpt-35-turbo', 'PER_1000_TOKENS', 0.0015, 'USD', 'PROMPT'),+ ('clm0obv1u000n3b6lw3bc6q70','gpt-35-turbo-0301', 'PER_1000_TOKENS', 0.0015, 'USD', 'PROMPT'),+ ('clm0obv1u000o3b6luimelud7','gpt-35-turbo-0613', 'PER_1000_TOKENS', 0.0015, 'USD', 'PROMPT'),+ ('clm0obv1u000p3b6lft9rfj1h','gpt-35-turbo-16k', 'PER_1000_TOKENS', 0.003, 'USD', 'PROMPT'),+ ('clm0obv1u000q3b6l1zh6x8lu','gpt-35-turbo-16k-0613', 'PER_1000_TOKENS', 0.003, 'USD', 'PROMPT'),+ ('clm0obv1v000r3b6llobngoj3','gpt-35-turbo', 'PER_1000_TOKENS', 0.002, 'USD', 'COMPLETION'),+ ('clm0obv1v000s3b6lgcjqu15e','gpt-35-turbo-0301', 'PER_1000_TOKENS', 0.002, 'USD', 'COMPLETION'),+ ('clm0obv1v000t3b6l6ijo29gd','gpt-35-turbo-0613', 'PER_1000_TOKENS', 0.002, 'USD', 'COMPLETION'),+ ('clm0obv1v000u3b6lo16c29a1','gpt-35-turbo-16k', 'PER_1000_TOKENS', 0.004, 'USD', 'COMPLETION'),+ ('clm0obv1v000v3b6leqypomnv','gpt-35-turbo-16k-0613', 'PER_1000_TOKENS', 0.004, 'USD', 'COMPLETION'),+ ('clm0obv1v000w3b6l6y0ojr1j','text-ada-001', 'PER_1000_TOKENS', 0.0004, 'USD', 'TOTAL'),+ ('clm0obv1v000x3b6lwdjl5os6','ada', 'PER_1000_TOKENS', 0.0004, 'USD', 'TOTAL'),+ ('clm0obv1v000y3b6lsap2cbkj','text-babbage-001', 'PER_1000_TOKENS', 0.0005, 'USD', 'TOTAL'),+ ('clm0obv1v000z3b6lto21j3xd','babbage', 'PER_1000_TOKENS', 0.0005, 'USD', 'TOTAL'),+ ('clm0obv1v00103b6lges5uumn','text-curie-001', 'PER_1000_TOKENS', 0.002, 'USD', 'TOTAL'),+ ('clm0obv1v00113b6l2vizhjhc','curie', 'PER_1000_TOKENS', 0.002, 'USD', 'TOTAL'),+ ('clm0obv1v00123b6lqb7mfrzr','text-davinci-003', 'PER_1000_TOKENS', 0.02, 'USD', 'TOTAL'),+ ('clm0obv1v00133b6lnqa8ecal','text-davinci-002', 'PER_1000_TOKENS', 0.02, 'USD', 'TOTAL'),+ ('clm0obv1v00143b6l6z5s44sf','code-davinci-002', 'PER_1000_TOKENS', 0.02, 'USD', 'TOTAL'),+ ('clm0obv1v00153b6lyntq7lx0','ada-finetuned', 'PER_1000_TOKENS', 0.0016, 'USD', 'TOTAL'),+ ('clm0obv1v00163b6l5fsheo7p','babbage-finetuned', 'PER_1000_TOKENS', 0.0024, 'USD', 'TOTAL'),+ ('clm0obv1v00173b6lly0887fz','curie-finetuned', 'PER_1000_TOKENS', 0.012, 'USD', 'TOTAL'),+ ('clm0obv1v00183b6lg20tw4g4','davinci-finetuned', 'PER_1000_TOKENS', 0.12, 'USD', 'TOTAL')\ No newline at end of filediff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 0e57555453..5c9a4c5ac8 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -201,3 +201,24 @@ model Score {@@index([value])@@map("scores")}++enum PricingUnit {+ PER_1000_TOKENS+}++enum TokenType {+ PROMPT+ COMPLETION+ TOTAL+}++model Pricing {+ id String @id @default(cuid())+ modelName String @map("model_name")+ pricingUnit PricingUnit @default(PER_1000_TOKENS) @map("pricing_unit")+ price Decimal+ currency String @default("USD")+ tokenType TokenType @map("token_type")++ @@map("pricings")+}diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsxindex 9661c654f9..8746f5a326 100644--- a/src/components/trace/ObservationPreview.tsx+++ b/src/components/trace/ObservationPreview.tsx@@ -17,9 +17,10 @@ import {TableRow,} from "@/src/components/ui/table";import { ManualScoreButton } from "@/src/features/manualScoring/components";+import type Decimal from "decimal.js";export const ObservationPreview = (props: {- observations: Array<Observation & { traceId: string }>;+ observations: Array<Observation & { traceId: string } & { price?: Decimal }>;projectId: string;scores: Score[];currentObservationId: string | undefined;@@ -60,6 +61,11 @@ export const ObservationPreview = (props: {{observation.model ? (<Badge variant="outline">{observation.model}</Badge>) : null}+ {observation.price ? (+ <Badge variant="outline">+ {observation.price.toString()} USD+ </Badge>+ ) : undefined}{observation.modelParameters &&typeof observation.modelParameters === "object"? Object.entries(observation.modelParameters)diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.tsindex d2395c168f..422443a27d 100644--- a/src/features/ingest/lib/usage.ts+++ b/src/features/ingest/lib/usage.ts@@ -1,5 +1,7 @@import { type TiktokenEncoding, get_encoding } from "tiktoken";import { countTokens } from "@anthropic-ai/tokenizer";+import { type Pricing } from "@prisma/client";+import { Decimal } from "decimal.js";export function tokenCount(p: {model: string;@@ -26,3 +28,60 @@ const getTokens = (name: TiktokenEncoding, text: string) => {encoding.free();return tokens.length;};++export function calculateTokenCost(+ pricingList: Pricing[],+ input: {+ model: string;+ totalTokens: Decimal;+ promptTokens: Decimal;+ completionTokens: Decimal;+ }+): Decimal | undefined {+ const pricing = pricingList.filter((p) => p.modelName === input.model);++ if (!pricing || pricing.length === 0) {+ return undefined;+ } else {+ if (pricing.length === 1 && pricing[0]?.tokenType === "TOTAL") {+ return calculateValue(pricing[0].price, input.totalTokens);+ }++ 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, input.promptTokens);+ }++ if (completionPricing) {+ completionPrice = calculateValue(+ completionPricing.price,+ input.completionTokens+ );+ }++ if (+ promptPrice.equals(new Decimal(0)) ||+ completionPrice.equals(new Decimal(0))+ ) {+ throw new Error(+ `Multiple pricing entries found for model ${input.model}`+ );+ }++ return promptPrice.plus(completionPrice);+ }+ }+ throw new Error(`Unexpected pricing configuration for model ${input.model}`);+}++const calculateValue = (price: Decimal, tokens: Decimal) => {+ return price.times(tokens.dividedBy(new Decimal(1000))).toDecimalPlaces(5);+};diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsxindex 269eb640b7..c3ba5708d9 100644--- a/src/pages/project/[projectId]/traces/[traceId].tsx+++ b/src/pages/project/[projectId]/traces/[traceId].tsx@@ -4,6 +4,7 @@ import { api } from "@/src/utils/api";import { Trace } from "@/src/components/trace";import { Badge } from "@/src/components/ui/badge";import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";+import Decimal from "decimal.js";export default function TracePage() {const router = useRouter();@@ -11,6 +12,12 @@ export default function TracePage() {const projectId = router.query.projectId as string;const trace = api.traces.byId.useQuery(traceId);++ const totalCost = trace.data?.observations.reduce(+ (acc, o) => acc.plus(o.price ? o.price : new Decimal(0)),+ new Decimal(0)+ );+return (<div className="flex flex-col overflow-hidden xl:container lg:h-[calc(100vh-100px)] xl:h-[calc(100vh-50px)]"><Header@@ -28,6 +35,11 @@ export default function TracePage() {<Badge variant="outline">User ID: {trace.data.userId}</Badge>) : null}<TraceAggUsageBadge observations={trace.data?.observations ?? []} />+ {totalCost ? (+ <Badge variant="outline">+ Total cost: {totalCost.toString()} USD+ </Badge>+ ) : undefined}</div>{trace.data ? (<div className="mt-5 flex-1 overflow-hidden border-t pt-5">diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.tsindex 5ca27e8dfb..0eabb354da 100644--- a/src/server/api/routers/traces.ts+++ b/src/server/api/routers/traces.ts@@ -6,6 +6,8 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";import { Prisma, type Score, type Trace } from "@prisma/client";+import { calculateTokenCost } from "@/src/features/ingest/lib/usage";+import Decimal from "decimal.js";const ScoreFilter = z.object({name: z.string(),@@ -237,7 +239,7 @@ export const traceRouter = createTRPCRouter({}),byId: protectedProcedure.input(z.string()).query(async ({ input, ctx }) => {- const [trace, observations] = await Promise.all([+ const [trace, observations, pricings] = await Promise.all([ctx.prisma.trace.findFirstOrThrow({where: {id: input,@@ -268,12 +270,27 @@ export const traceRouter = createTRPCRouter({},},}),+ ctx.prisma.pricing.findMany(),]);+ const enrichedObservations = observations.map((observation) => {+ return {+ ...observation,+ price: observation.model+ ? calculateTokenCost(pricings, {+ model: observation.model,+ totalTokens: new Decimal(observation.totalTokens),+ promptTokens: new Decimal(observation.promptTokens),+ completionTokens: new Decimal(observation.completionTokens),+ })+ : undefined,+ };+ });+return {...trace,- observations: observations as Array<- (typeof observations)[0] & { traceId: string }+ observations: enrichedObservations as Array<+ (typeof observations)[0] & { traceId: string } & { price?: Decimal }>,};}),