Skip to content

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

refactor: improve usage/cost (#992)

Marc Klingen7e7bf99fac53
diff --git a/prisma/migrations/20240130100110_usage_unit_nullable/migration.sql b/prisma/migrations/20240130100110_usage_unit_nullable/migration.sql
new file mode 100644
index 0000000000..59f4bc82e1
--- /dev/null
+++ b/prisma/migrations/20240130100110_usage_unit_nullable/migration.sql
@@ -0,0 +1,6 @@
+-- AlterTable
+ALTER TABLE "models" ALTER COLUMN "unit" DROP DEFAULT;
+
+-- AlterTable
+ALTER TABLE "observations" ALTER COLUMN "unit" DROP NOT NULL,
+ALTER COLUMN "unit" DROP DEFAULT;
diff --git a/prisma/migrations/20240130160110_claude_models/migration.sql b/prisma/migrations/20240130160110_claude_models/migration.sql
new file mode 100644
index 0000000000..7bfe8f2cba
--- /dev/null
+++ b/prisma/migrations/20240130160110_claude_models/migration.sql
@@ -0,0 +1,40 @@
+-- This is an empty migration.
+
+DELETE FROM models
+WHERE id in (
+ 'clrnwbota000908jsgg9mb1ml',
+ 'clrnwb41q000308jsfrac9uh6',
+ 'clrnwbd1m000508js4hxu6o7n',
+ 'clrnwb836000408jsallr6u11',
+ 'clrnwbg2b000608jse2pp4q2d',
+ 'clrnwbi9d000708jseiy44k26',
+ 'clrnwblo0000808jsc1385hdp'
+);
+
+
+
+INSERT INTO models (
+ id,
+ project_id,
+ model_name,
+ match_pattern,
+ start_date,
+ input_price,
+ output_price,
+ total_price,
+ unit,
+ tokenizer_id,
+ tokenizer_config
+)
+VALUES
+ -- nothing earlier required for ada
+ ('clrnwbota000908jsgg9mb1ml', NULL, 'claude-instant-1', '(?i)^(claude-instant-1)$', NULL, 0.00000163, 0.00000551, NULL, 'TOKENS', 'claude', NULL),
+ ('clrnwb41q000308jsfrac9uh6', NULL, 'claude-instant-1.2', '(?i)^(claude-instant-1.2)$', NULL, 0.00000163, 0.00000551, NULL, 'TOKENS', 'claude', NULL),
+ ('clrnwbd1m000508js4hxu6o7n', NULL, 'claude-2.1', '(?i)^(claude-2.1)$', NULL, 0.000008, 0.000024, NULL, 'TOKENS', 'claude', NULL),
+ ('clrnwb836000408jsallr6u11', NULL, 'claude-2.0', '(?i)^(claude-2.0)$', NULL, 0.000008, 0.000024, NULL, 'TOKENS', 'claude', NULL),
+ ('clrnwbg2b000608jse2pp4q2d', NULL, 'claude-1.3', '(?i)^(claude-1.3)$', NULL, 0.000008, 0.000024, NULL, 'TOKENS', 'claude', NULL),
+ ('clrnwbi9d000708jseiy44k26', NULL, 'claude-1.2', '(?i)^(claude-1.2)$', NULL, 0.000008, 0.000024, NULL, 'TOKENS', 'claude', NULL),
+ ('clrnwblo0000808jsc1385hdp', NULL, 'claude-1.1', '(?i)^(claude-1.1)$', NULL, 0.000008, 0.000024, NULL, 'TOKENS', 'claude', NULL)
+
+
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 4a232fc183..e3f4f628b8 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -234,10 +234,10 @@ model Observation {
promptTokens Int @default(0) @map("prompt_tokens")
completionTokens Int @default(0) @map("completion_tokens")
totalTokens Int @default(0) @map("total_tokens")
+ unit String?
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[]
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
@@ -440,7 +440,7 @@ model Model {
inputPrice Decimal? @map("input_price")
outputPrice Decimal? @map("output_price")
totalPrice Decimal? @map("total_price")
- unit String @default("TOKENS")
+ unit String // TOKENS or CHARACTERS
tokenizerId String? @map("tokenizer_id")
tokenizerConfig Json? @map("tokenizer_config")
@@ -449,7 +449,7 @@ model Model {
@@map("models")
}
-// This view is a mix of the obsevation and model. Once prisma supports
+// This view is a mix of the observation and model. Once prisma supports
// inheritance, we should remove code duplication here.
view ObservationView {
id String @id @default(cuid())
@@ -474,7 +474,7 @@ view ObservationView {
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")
+ unit String?
completionStartTime DateTime? @map("completion_start_time")
promptId String? @map("prompt_id")
diff --git a/prisma/seed.ts b/prisma/seed.ts
index e7d0d8a0f0..6c854a567f 100755
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -487,11 +487,7 @@ async function main() {
? { prompt: { connect: { id: prompt.id } } }
: {}),
},
- unit: model
- ? model.includes("claude")
- ? "CHARACTERS"
- : "TOKENS"
- : undefined,
+ unit: "TOKENS",
},
});
if (Math.random() > 0.6)
diff --git a/scripts/model-match.ts b/scripts/model-match.ts
index d3266c222b..09eed30cf5 100644
--- a/scripts/model-match.ts
+++ b/scripts/model-match.ts
@@ -1,6 +1,6 @@
-// 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
+// Description: New model definitions in Langfuse are automatically applied to new observations.
+// You can optionally run this script to apply new model definitions to existing observations.
+// See docs: https://langfuse.com/docs/deployment/self-host#migrate-models
// Execute: `npm run models:migrate`
import "dotenv/config";
@@ -8,6 +8,8 @@ import "dotenv/config";
import { findModel } from "@/src/server/api/services/EventProcessor";
import { prisma } from "@/src/server/db";
import lodash from "lodash";
+import { tokenCount } from "@/src/features/ingest/lib/usage";
+import { type Prisma } from "@prisma/client";
async function main() {
return await modelMatch();
@@ -22,18 +24,24 @@ export async function modelMatch() {
console.log("Starting model match");
const start = Date.now();
- // while observations are not null, get the next 10000 observations
+ // while observations are not null, get the next 50_000 observations
+ const BATCH_SIZE = 50_000;
let continueLoop = true;
let index = 0;
let totalObservations = 0;
while (continueLoop) {
- type selectedType = {
+ type ObservationSelect = {
model: string | null;
id: string;
projectId: string;
startTime: Date;
- unit: string;
+ unit: string | null;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ input: Prisma.JsonValue;
+ output: Prisma.JsonValue;
};
const observations = await prisma.observation.findMany({
@@ -43,6 +51,11 @@ export async function modelMatch() {
model: true,
unit: true,
projectId: true,
+ promptTokens: true,
+ completionTokens: true,
+ totalTokens: true,
+ input: true,
+ output: true,
},
orderBy: {
startTime: "desc",
@@ -50,26 +63,35 @@ export async function modelMatch() {
where: {
internalModel: null,
type: "GENERATION",
- startTime: {
- lt: new Date("2020-01-24"),
- },
},
- take: 100_000,
- skip: index * 100_000,
+ take: BATCH_SIZE,
+ skip: index * BATCH_SIZE,
});
console.log("Observations: ", observations[0]?.id);
console.log(`Found ${observations.length} observations to migrate`);
+ type Config = {
+ startTime: Date;
+ model: string;
+ unit: string;
+ projectId: string | null;
+ };
+
interface GroupedObservations {
- [key: string]: selectedType[];
+ [key: string]: ObservationSelect[];
}
const groupedObservations = observations.reduce<GroupedObservations>(
(acc, observation) => {
- const key = `${observation.startTime.toISOString().slice(0, 10)}_${
- observation.model
- }_${observation.unit}_${observation.projectId}`;
+ const config = {
+ startTime: observation.startTime,
+ model: observation.model,
+ unit: observation.unit,
+ projectId: observation.projectId,
+ };
+
+ const key = JSON.stringify(config);
// Ensure the array is initialized before using it
acc[key] = acc[key] ?? [];
@@ -80,29 +102,22 @@ export async function modelMatch() {
{},
);
- const updatePromises: Array<Promise<unknown>> = [];
let updatedObservations = 0;
for (const [key, observationsGroup] of Object.entries(
groupedObservations,
)) {
- // Split the key into its components
- const [date, model, unit, projectId] = key.split("_");
+ const { startTime, model, unit, projectId } = JSON.parse(key) as Config;
- console.log("Execute key: ", date, model, unit, projectId);
+ console.log("Execute key: ", startTime, 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,
- );
+ const foundModel = await findModel({
+ event: { projectId, model, unit, startTime: startTime },
+ });
console.log(
"Found model: ",
@@ -114,11 +129,51 @@ export async function modelMatch() {
);
if (foundModel) {
- // Push the promise for updating observations into the array
+ // find all the observations with all tokens 0 and tokenize them individually
+ const observationsWithAllTokensZero = observationsGroup.filter(
+ (observation) =>
+ observation.promptTokens === 0 &&
+ observation.completionTokens === 0 &&
+ observation.totalTokens === 0,
+ );
+
+ for (const observation of observationsWithAllTokensZero) {
+ console.log("Tokenizing observation: ", observation.id);
+ const newInputCount = tokenCount({
+ model: foundModel,
+ text: observation.input,
+ });
+ const newOutputCount = tokenCount({
+ model: foundModel,
+ text: observation.output,
+ });
+
+ await prisma.observation.update({
+ where: {
+ id: observation.id,
+ },
+ data: {
+ promptTokens: newInputCount,
+ completionTokens: newOutputCount,
+ totalTokens: (newInputCount ?? 0) + (newOutputCount ?? 0),
+ internalModel: foundModel.modelName,
+ },
+ });
+ }
+
+ // for all remaining observations, batch update them with the model id
+ const observationsWithTokens = observationsGroup.filter(
+ (observation) =>
+ observation.promptTokens !== 0 ||
+ observation.completionTokens !== 0 ||
+ observation.totalTokens !== 0,
+ );
- lodash.chunk(observationsGroup, 32000).map((chunk) => {
- updatePromises.push(
- prisma.observation.updateMany({
+ // Push the promise for updating observations into the array
+ const promises = lodash
+ .chunk(observationsWithTokens, 32000)
+ .map(async (chunk) => {
+ await prisma.observation.updateMany({
where: {
id: {
in: chunk.map((observation) => observation.id),
@@ -127,26 +182,26 @@ export async function modelMatch() {
data: {
internalModel: foundModel.modelName,
},
- }),
- );
- });
-
+ });
+ });
+ await Promise.all(promises);
updatedObservations += observationsGroup.length;
} else {
- lodash.chunk(observationsGroup, 32000).map((chunk) => {
- updatePromises.push(
- prisma.observation.updateMany({
+ const promises = lodash
+ .chunk(observationsGroup, 32000)
+ .map(async (chunk) => {
+ await prisma.observation.updateMany({
where: {
id: {
in: chunk.map((observation) => observation.id),
},
},
data: {
- internalModel: "none",
+ internalModel: "LANGFUSETMPNOMODEL",
},
- }),
- );
- });
+ });
+ });
+ await Promise.all(promises);
updatedObservations += observationsGroup.length;
}
@@ -154,8 +209,8 @@ export async function modelMatch() {
totalObservations += updatedObservations;
// Wait for all update operations to complete
- await Promise.all(updatePromises);
- console.warn(
+
+ console.log(
"Updated observations count: ",
updatedObservations,
" in total: ",
@@ -176,7 +231,7 @@ export async function modelMatch() {
await prisma.observation.updateMany({
where: {
- internalModel: "none",
+ internalModel: "LANGFUSETMPNOMODEL",
},
data: {
internalModel: null,
diff --git a/src/__tests__/generations.servertest.ts b/src/__tests__/generations.servertest.ts
index 531c5c6bda..6cc9500b6d 100644
--- a/src/__tests__/generations.servertest.ts
+++ b/src/__tests__/generations.servertest.ts
@@ -34,7 +34,7 @@ describe("/api/public/generations API Endpoint", () => {
usage: {
total: 100,
},
- expectedUnit: "TOKENS",
+ expectedUnit: null,
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 100,
@@ -64,21 +64,21 @@ describe("/api/public/generations API Endpoint", () => {
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 0,
- expectedUnit: "TOKENS",
+ expectedUnit: null,
},
{
usage: null,
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 0,
- expectedUnit: "TOKENS",
+ expectedUnit: null,
},
{
usage: {},
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 0,
- expectedUnit: "TOKENS",
+ expectedUnit: null,
},
].forEach((testConfig) => {
it(`should create generation after trace 1 ${JSON.stringify(
diff --git a/src/__tests__/ingestion.servertest.ts b/src/__tests__/ingestion.servertest.ts
index 4d313fa141..3409d1fef6 100644
--- a/src/__tests__/ingestion.servertest.ts
+++ b/src/__tests__/ingestion.servertest.ts
@@ -38,7 +38,7 @@ describe("/api/public/ingestion API Endpoint", () => {
usage: {
total: 100,
},
- expectedUnit: "TOKENS",
+ expectedUnit: null,
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 100,
@@ -68,21 +68,21 @@ describe("/api/public/ingestion API Endpoint", () => {
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 0,
- expectedUnit: "TOKENS",
+ expectedUnit: null,
},
{
usage: null,
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 0,
- expectedUnit: "TOKENS",
+ expectedUnit: null,
},
{
usage: {},
expectedPromptTokens: 0,
expectedCompletionTokens: 0,
expectedTotalTokens: 0,
- expectedUnit: "TOKENS",
+ expectedUnit: null,
},
].forEach((testConfig) => {
it(`should create trace, generation and score without matching models ${JSON.stringify(
diff --git a/src/__tests__/model-match.servertest.ts b/src/__tests__/model-match.servertest.ts
new file mode 100644
index 0000000000..1eb83404be
--- /dev/null
+++ b/src/__tests__/model-match.servertest.ts
@@ -0,0 +1,95 @@
+/** @jest-environment node */
+
+import { modelMatch } from "@/scripts/model-match";
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import { prisma } from "@/src/server/db";
+
+describe("model match", () => {
+ beforeEach(async () => await pruneDatabase());
+
+ it("should match historic observations to models", async () => {
+ await prisma.model.create({
+ data: {
+ id: "model-1",
+ modelName: "gpt-3.5-turbo",
+ inputPrice: "0.0000010",
+ outputPrice: "0.0000020",
+ totalPrice: "0.1",
+ matchPattern: "(.*)(gpt-3.5-turbo)?(.*)",
+ projectId: null,
+ unit: "TOKENS",
+ tokenizerConfig: {
+ tokensPerMessage: 3,
+ tokensPerName: 1,
+ tokenizerModel: "gpt-3.5-turbo",
+ },
+ tokenizerId: "openai",
+ },
+ });
+ await prisma.model.create({
+ data: {
+ id: "model-2",
+ modelName: "claude-1.3",
+ inputPrice: "0.0000010",
+ outputPrice: "0.0000020",
+ totalPrice: "0.1",
+ matchPattern: "(.*)(claude-1.3)?(.*)",
+ projectId: null,
+ unit: "TOKENS",
+ tokenizerId: "claude",
+ },
+ });
+
+ await prisma.observation.createMany({
+ data: [
+ {
+ id: "observation-1",
+ type: "GENERATION",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ model: "gpt-3.5-turbo",
+ startTime: new Date("2024-01-01T00:00:00.000Z"),
+ unit: "TOKENS",
+ promptTokens: 200,
+ completionTokens: 3000,
+ input: "I am a prompt",
+ output: "I am a completion",
+ },
+ {
+ type: "GENERATION",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ model: "claude-1.3",
+ startTime: new Date("2024-01-01T00:00:00.000Z"),
+ unit: "TOKENS",
+ input: "I am a prompt",
+ output: "I am a completion",
+ },
+ {
+ type: "GENERATION",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ model: "claude-1.3",
+ startTime: new Date("2024-01-01T00:00:00.000Z"),
+ unit: "TOKENS",
+ input: "I am a prompt",
+ output: "I am a completion",
+ },
+ ],
+ });
+
+ await modelMatch();
+
+ const observations = await prisma.observation.findMany();
+
+ // check that tokens from observation-1 are not changed
+ const observation1 = observations.find((o) => o.id === "observation-1");
+ expect(observation1?.promptTokens).toEqual(200);
+ expect(observation1?.completionTokens).toEqual(3000);
+ expect(observation1?.totalTokens).toEqual(0);
+
+ expect(observations.length).toEqual(3);
+ observations.forEach((observation) => {
+ expect(observation.internalModel).toBeDefined();
+ expect(observation.promptTokens).toBeGreaterThan(0);
+ expect(observation.completionTokens).toBeGreaterThan(0);
+ });
+ });
+});
diff --git a/src/__tests__/observations.servertest.ts b/src/__tests__/observations.servertest.ts
index c8232aee2d..3ce251332a 100644
--- a/src/__tests__/observations.servertest.ts
+++ b/src/__tests__/observations.servertest.ts
@@ -59,6 +59,7 @@ describe("/api/public/observations API Endpoint", () => {
connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
},
internalModel: "gpt-3.5-turbo",
+ unit: "TOKENS",
},
});
@@ -71,7 +72,10 @@ describe("/api/public/observations API Endpoint", () => {
expect(fetchedObservations.status).toBe(200);
if (!isObservationList(fetchedObservations.body)) {
- throw new Error("Expected body to be an array of observations");
+ throw new Error(
+ "Expected body to be an array of observations" +
+ JSON.stringify(fetchedObservations.body),
+ );
}
expect(fetchedObservations.body.data.length).toBe(1);
diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.ts
index 0d0cc65278..33937c4dde 100644
--- a/src/features/ingest/lib/usage.ts
+++ b/src/features/ingest/lib/usage.ts
@@ -43,10 +43,7 @@ export function tokenCount(p: {
text: p.text,
});
} else if (p.model.tokenizerId === "claude") {
- return claudeTokenCount({
- internalModel: p.model.modelName,
- text: p.text,
- });
+ return claudeTokenCount(p.text);
} else {
console.error(`Unknown tokenizer ${p.model.tokenizerId}`);
return undefined;
@@ -97,10 +94,8 @@ function openAiTokenCount(p: { model: Model; text: unknown }) {
return result;
}
-function claudeTokenCount(p: { internalModel: string; text: unknown }) {
- return isString(p.text)
- ? countTokens(p.text)
- : countTokens(JSON.stringify(p.text));
+function claudeTokenCount(text: unknown) {
+ return isString(text) ? countTokens(text) : countTokens(JSON.stringify(text));
}
function openAiChatTokenCount(params: {
diff --git a/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.ts
index 62197ac723..955623700f 100644
--- a/src/features/public-api/server/ingestion-api-schema.ts
+++ b/src/features/public-api/server/ingestion-api-schema.ts
@@ -7,7 +7,7 @@ export const Usage = z.object({
input: z.number().int().nullish(),
output: z.number().int().nullish(),
total: z.number().int().nullish(),
- unit: z.enum(["TOKENS", "CHARACTERS"]).nullable(),
+ unit: z.enum(["TOKENS", "CHARACTERS"]).nullish(),
inputCost: z.number().nullish(),
outputCost: z.number().nullish(),
totalCost: z.number().nullish(),
@@ -34,6 +34,7 @@ export const usage = MixedUsage.nullish()
if (!v) {
return null;
}
+ // if we get the openai format, we default to TOKENS unit
if ("promptTokens" in v || "completionTokens" in v || "totalTokens" in v) {
return {
input: v.promptTokens,
@@ -42,17 +43,19 @@ export const usage = MixedUsage.nullish()
unit: "TOKENS",
};
}
+ // if we get the new generic format, we do not set a default
if ("input" in v || "output" in v || "total" in v || "unit" in v) {
- const unit = v.unit ?? "TOKENS";
+ const unit = v.unit;
return { ...v, unit };
}
+ // if the object is empty, we return undefined
if (lodash.isEmpty(v)) {
- return { unit: "TOKENS" };
+ return undefined;
}
})
// ensure output is always of new usage model
- .pipe(Usage.nullable());
+ .pipe(Usage.nullish());
export const TraceBody = z.object({
id: z.string().nullish(),
diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.ts
index ff87c09d90..013896f4b6 100644
--- a/src/server/api/services/EventProcessor.ts
+++ b/src/server/api/services/EventProcessor.ts
@@ -35,86 +35,80 @@ export interface EventProcessor {
): Promise<Trace | Observation | Score> | undefined;
}
-export const findModel = async (
- projectId: string,
- model?: string,
- unit?: string,
- startTime?: string,
- existingObservation?: Observation,
-) => {
+export async function findModel(p: {
+ event: {
+ projectId: string;
+ model?: string;
+ unit?: string;
+ startTime?: Date;
+ };
+ existingDbObservation?: Observation;
+}): Promise<Model | null> {
+ const { event, existingDbObservation } = p;
// 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}`
+ const modelCondition = event.model
+ ? Prisma.sql`AND ${event.model} ~ match_pattern`
+ : existingDbObservation?.internalModel
+ ? Prisma.sql`AND model_name = ${existingDbObservation.internalModel}`
: undefined;
+ if (!modelCondition) return null;
- // usage either from existing generation or from the current event
- const mergedUnit = unit ?? existingObservation?.unit;
+ // unit based on the current event or the existing observation, both can be undefined
+ const mergedUnit = event.unit ?? existingDbObservation?.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;
- }
-};
+ 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 = ${event.projectId}
+ OR project_id IS NULL)
+ ${modelCondition}
+ ${unitCondition}
+ AND (start_date IS NULL OR start_date <= ${
+ event.startTime ? new Date(event.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] ?? null;
+}
+
+type ObservationEvent =
+ | z.infer<typeof legacyObservationCreateEvent>
+ | z.infer<typeof legacyObservationUpdateEvent>
+ | z.infer<typeof eventCreateEvent>
+ | z.infer<typeof spanCreateEvent>
+ | z.infer<typeof spanUpdateEvent>
+ | z.infer<typeof generationCreateEvent>
+ | z.infer<typeof generationUpdateEvent>;
export class ObservationProcessor implements EventProcessor {
- event:
- | z.infer<typeof legacyObservationCreateEvent>
- | z.infer<typeof legacyObservationUpdateEvent>
- | z.infer<typeof eventCreateEvent>
- | z.infer<typeof spanCreateEvent>
- | z.infer<typeof spanUpdateEvent>
- | z.infer<typeof generationCreateEvent>
- | z.infer<typeof generationUpdateEvent>;
-
- constructor(
- event:
- | z.infer<typeof legacyObservationCreateEvent>
- | z.infer<typeof legacyObservationUpdateEvent>
- | z.infer<typeof eventCreateEvent>
- | z.infer<typeof spanCreateEvent>
- | z.infer<typeof spanUpdateEvent>
- | z.infer<typeof generationCreateEvent>
- | z.infer<typeof generationUpdateEvent>,
- ) {
+ event: ObservationEvent;
+
+ constructor(event: ObservationEvent) {
this.event = event;
}
@@ -126,9 +120,7 @@ export class ObservationProcessor implements EventProcessor {
create: Prisma.ObservationUncheckedCreateInput;
update: Prisma.ObservationUncheckedUpdateInput;
}> {
- const { body } = this.event;
-
- let type;
+ let type: "EVENT" | "SPAN" | "GENERATION";
switch (this.event.type) {
case eventTypes.OBSERVATION_CREATE:
case eventTypes.OBSERVATION_UPDATE:
@@ -147,8 +139,6 @@ export class ObservationProcessor implements EventProcessor {
break;
}
- const { id, traceId, name, startTime, metadata } = body;
-
if (
this.event.type === eventTypes.OBSERVATION_UPDATE &&
!existingObservation
@@ -156,37 +146,46 @@ 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 =
+ // find matching model definition based on event and existing observation in db
+ const internalModel: Model | undefined | null =
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,
- )
+ ? await findModel({
+ event: {
+ projectId: apiScope.projectId,
+ model:
+ "model" in this.event.body
+ ? this.event.body.model ?? undefined
+ : undefined,
+ unit:
+ "usage" in this.event.body
+ ? this.event.body.usage?.unit ?? undefined
+ : undefined,
+ startTime: this.event.body.startTime
+ ? new Date(this.event.body.startTime)
+ : undefined,
+ },
+ existingDbObservation: existingObservation ?? undefined,
+ })
: undefined;
- const finalTraceId =
- !traceId && !existingObservation
+ const traceId =
+ !this.event.body.traceId && !existingObservation
? // Create trace if no traceid
(
await prisma.trace.create({
data: {
projectId: apiScope.projectId,
- name: name,
+ name: this.event.body.name,
},
})
).id
- : traceId;
+ : this.event.body.traceId;
const [newInputCount, newOutputCount] =
- "usage" in body
+ "usage" in this.event.body
? this.calculateTokenCounts(
- body,
- internalModel,
+ this.event.body,
+ internalModel ?? undefined,
existingObservation ?? undefined,
)
: [undefined, undefined];
@@ -196,7 +195,7 @@ export class ObservationProcessor implements EventProcessor {
existingObservation?.metadata
? jsonSchema.parse(existingObservation.metadata)
: undefined,
- metadata ?? undefined,
+ this.event.body.metadata ?? undefined,
);
const prompt =
@@ -219,95 +218,121 @@ export class ObservationProcessor implements EventProcessor {
if (prompt === null)
console.warn("Prompt not found for observation", this.event.body);
- const observationId = id ?? v4();
+ const observationId = this.event.body.id ?? v4();
return {
id: observationId,
create: {
id: observationId,
- traceId: finalTraceId,
+ traceId: traceId,
type: type,
- name: name,
- startTime: startTime ? new Date(startTime) : undefined,
+ name: this.event.body.name,
+ startTime: this.event.body.startTime
+ ? new Date(this.event.body.startTime)
+ : undefined,
endTime:
- "endTime" in body && body.endTime
- ? new Date(body.endTime)
+ "endTime" in this.event.body && this.event.body.endTime
+ ? new Date(this.event.body.endTime)
: undefined,
completionStartTime:
- "completionStartTime" in body && body.completionStartTime
- ? new Date(body.completionStartTime)
+ "completionStartTime" in this.event.body &&
+ this.event.body.completionStartTime
+ ? new Date(this.event.body.completionStartTime)
: undefined,
- metadata: mergedMetadata ?? metadata ?? undefined,
- model: "model" in body ? body.model : undefined,
+ metadata: mergedMetadata ?? this.event.body.metadata ?? undefined,
+ model: "model" in this.event.body ? this.event.body.model : undefined,
modelParameters:
- "modelParameters" in body
- ? body.modelParameters ?? undefined
+ "modelParameters" in this.event.body
+ ? this.event.body.modelParameters ?? undefined
: undefined,
- input: body.input ?? undefined,
- output: body.output ?? undefined,
+ input: this.event.body.input ?? undefined,
+ output: this.event.body.output ?? undefined,
promptTokens: newInputCount,
completionTokens: newOutputCount,
totalTokens:
- "usage" in body
- ? body.usage?.total ?? (newInputCount ?? 0) + (newOutputCount ?? 0)
+ "usage" in this.event.body
+ ? this.event.body.usage?.total ??
+ (newInputCount ?? 0) + (newOutputCount ?? 0)
: undefined,
unit:
- "usage" in body
- ? body.usage?.unit ?? internalModel?.unit
+ "usage" in this.event.body
+ ? this.event.body.usage?.unit ?? internalModel?.unit
: internalModel?.unit,
- level: body.level ?? undefined,
- statusMessage: body.statusMessage ?? undefined,
- parentObservationId: body.parentObservationId ?? undefined,
- version: body.version ?? undefined,
+ level: this.event.body.level ?? undefined,
+ statusMessage: this.event.body.statusMessage ?? undefined,
+ parentObservationId: this.event.body.parentObservationId ?? undefined,
+ version: this.event.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,
+ inputCost:
+ "usage" in this.event.body
+ ? this.event.body.usage?.inputCost
+ : undefined,
+ outputCost:
+ "usage" in this.event.body
+ ? this.event.body.usage?.outputCost
+ : undefined,
+ totalCost:
+ "usage" in this.event.body
+ ? this.event.body.usage?.totalCost
+ : undefined,
},
update: {
- name,
- startTime: startTime ? new Date(startTime) : undefined,
+ name: this.event.body.name ?? undefined,
+ startTime: this.event.body.startTime
+ ? new Date(this.event.body.startTime)
+ : undefined,
endTime:
- "endTime" in body && body.endTime
- ? new Date(body.endTime)
+ "endTime" in this.event.body && this.event.body.endTime
+ ? new Date(this.event.body.endTime)
: undefined,
completionStartTime:
- "completionStartTime" in body && body.completionStartTime
- ? new Date(body.completionStartTime)
+ "completionStartTime" in this.event.body &&
+ this.event.body.completionStartTime
+ ? new Date(this.event.body.completionStartTime)
: undefined,
- metadata: mergedMetadata ?? metadata ?? undefined,
- model: "model" in body ? body.model : undefined,
+ metadata: mergedMetadata ?? this.event.body.metadata ?? undefined,
+ model: "model" in this.event.body ? this.event.body.model : undefined,
modelParameters:
- "modelParameters" in body
- ? body.modelParameters ?? undefined
+ "modelParameters" in this.event.body
+ ? this.event.body.modelParameters ?? undefined
: undefined,
- input: body.input ?? undefined,
- output: body.output ?? undefined,
+ input: this.event.body.input ?? undefined,
+ output: this.event.body.output ?? undefined,
promptTokens: newInputCount,
completionTokens: newOutputCount,
totalTokens:
- "usage" in body
- ? body.usage?.total ?? (newInputCount ?? 0) + (newOutputCount ?? 0)
+ "usage" in this.event.body
+ ? this.event.body.usage?.total ??
+ (newInputCount ?? 0) + (newOutputCount ?? 0)
: undefined,
unit:
- "usage" in body
- ? body.usage?.unit ?? internalModel?.unit
+ "usage" in this.event.body
+ ? this.event.body.usage?.unit ?? internalModel?.unit
: internalModel?.unit,
- level: body.level ?? undefined,
- statusMessage: body.statusMessage ?? undefined,
- parentObservationId: body.parentObservationId ?? undefined,
- version: body.version ?? undefined,
+ level: this.event.body.level ?? undefined,
+ statusMessage: this.event.body.statusMessage ?? undefined,
+ parentObservationId: this.event.body.parentObservationId ?? undefined,
+ version: this.event.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,
+ inputCost:
+ "usage" in this.event.body
+ ? this.event.body.usage?.inputCost
+ : undefined,
+ outputCost:
+ "usage" in this.event.body
+ ? this.event.body.usage?.outputCost
+ : undefined,
+ totalCost:
+ "usage" in this.event.body
+ ? this.event.body.usage?.totalCost
+ : undefined,
},
};
}
@@ -342,9 +367,7 @@ export class ObservationProcessor implements EventProcessor {
return [newPromptTokens, newCompletionTokens];
}
- async process(
- apiScope: ApiAccessScope,
- ): Promise<Trace | Observation | Score> {
+ async process(apiScope: ApiAccessScope): Promise<Observation> {
if (apiScope.accessLevel !== "all")
throw new AuthenticationError("Access denied for observation creation");