Skip to content

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

perf: improve traces table performance (#1276)

Max Deichmanna4c8f0b70261
diff --git a/web/prisma/migrations/20240228123642_observations_view_fix/migration.sql b/web/prisma/migrations/20240228123642_observations_view_fix/migration.sql
new file mode 100644
index 0000000000..8aee34acc0
--- /dev/null
+++ b/web/prisma/migrations/20240228123642_observations_view_fix/migration.sql
@@ -0,0 +1,59 @@
+CREATE OR REPLACE 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",
+ 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
+LEFT JOIN LATERAL (
+ SELECT
+ models.*
+ FROM
+ models
+ WHERE (models.project_id = o.project_id OR models.project_id IS NULL)
+ AND models.model_name = o.internal_model
+ AND (models.start_date < o.start_time OR models.start_date IS NULL)
+ AND o.unit::TEXT = models.unit
+ ORDER BY
+ models.project_id ASC, -- in postgres, NULLs are sorted last when ordering ASC
+ models.start_date DESC NULLS LAST -- now, NULLs are sorted last when ordering DESC as well
+ LIMIT 1
+) m ON TRUE
+
+
+-- requirements:
+-- 1. The view should return all columns from the observations table
+-- 2. The view should match with only one model for each observation if:
+-- a. The model has the same project_id as the observation, otherwise the model without project_id.
+-- b. The model has the same model_name as the observation
+-- c. The model has a start_date that is less than the observation start_time, otherwise the model without start_date
+-- d. The model has the same unit as the observation
\ No newline at end of file
diff --git a/web/src/__tests__/cost.servertest.ts b/web/src/__tests__/cost.servertest.ts
index e9181988b4..c64cd31476 100644
--- a/web/src/__tests__/cost.servertest.ts
+++ b/web/src/__tests__/cost.servertest.ts
@@ -320,6 +320,85 @@ describe("cost retrieval tests", () => {
expect(view?.calculatedTotalCost?.toString()).toBe("0.0124");
});
+ it(`should take old model for old observations`, async () => {
+ await prisma.model.create({
+ data: {
+ id: "model-0",
+ modelName: "gpt-3.5-turbo",
+ inputPrice: "0.0000000",
+ outputPrice: "0.0000000",
+ totalPrice: "0.1",
+ matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
+ projectId: null,
+ startDate: null,
+ tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
+ unit: ModelUsageUnit.Tokens,
+ },
+ });
+
+ 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: ModelUsageUnit.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: ModelUsageUnit.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("2023-01-01T00:00:00.000Z"),
+ unit: ModelUsageUnit.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?.modelId).toBe("model-0");
+ expect(view?.calculatedInputCost?.toString()).toBe("0");
+ expect(view?.calculatedOutputCost?.toString()).toBe("0");
+ expect(view?.calculatedTotalCost?.toString()).toBe("0");
+ });
+
it(`should prioritize own models`, async () => {
await pruneDatabase();
await prisma.model.create({
@@ -385,8 +464,6 @@ describe("cost retrieval tests", () => {
});
it(`should prioritize old model if the latest model is not own one`, async () => {
- await pruneDatabase();
-
await prisma.model.create({
data: {
id: "model-1",
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index f8672319f7..8f2423ef87 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -463,63 +463,50 @@ function createTracesQuery(
orderByCondition: Sql,
) {
return Prisma.sql`
- WITH usage AS (
+ SELECT
+ ${select}
+ FROM
+ "traces" AS t
+ LEFT JOIN LATERAL (
SELECT
- trace_id,
- sum(prompt_tokens) AS "promptTokens",
- sum(completion_tokens) AS "completionTokens",
- sum(total_tokens) AS "totalTokens",
- sum(calculated_total_cost) AS "calculatedTotalCost"
+ SUM(prompt_tokens) AS "promptTokens",
+ SUM(completion_tokens) AS "completionTokens",
+ SUM(total_tokens) AS "totalTokens",
+ SUM(calculated_total_cost) AS "calculatedTotalCost"
FROM
- "observations_view"
+ "observations_view"
WHERE
- "trace_id" IS NOT NULL
- AND "type" = 'GENERATION'
- AND "project_id" = ${projectId}
- ${observationTimeseriesFilter}
- GROUP BY
- trace_id
- ),
- trace_latency AS (
+ trace_id = t.id
+ AND "type" = 'GENERATION'
+
+ AND "project_id" = ${projectId}
+ ${observationTimeseriesFilter}
+ ) AS u ON true
+ LEFT JOIN LATERAL (
SELECT
- trace_id,
- EXTRACT(EPOCH FROM COALESCE(MAX("end_time"), MAX("start_time"))) - EXTRACT(EPOCH FROM MIN("start_time"))::double precision AS "latency"
+ EXTRACT(EPOCH FROM COALESCE(MAX("end_time"), MAX("start_time"))) - EXTRACT(EPOCH FROM MIN("start_time"))::double precision AS "latency"
FROM
- "observations"
+ "observations"
WHERE
- "trace_id" IS NOT NULL
- AND "project_id" = ${projectId}
- ${observationTimeseriesFilter}
- GROUP BY
- trace_id
- ),
- -- used for filtering
- scores_avg AS (
+ trace_id = t.id
+ AND "project_id" = ${projectId}
+ ${observationTimeseriesFilter}
+ ) AS tl ON true
+ LEFT JOIN LATERAL (
SELECT
- trace_id,
- jsonb_object_agg(name::text, avg_value::double precision) AS scores_avg
+ jsonb_object_agg(name::text, avg_value::double precision) AS "scores_avg"
FROM (
- SELECT
- trace_id,
- name,
- avg(value) avg_value
- FROM
- scores
- GROUP BY
- 1,
- 2
- ORDER BY
- 1) tmp
- GROUP BY
- 1
- )
- SELECT
- ${select}
- FROM
- "traces" AS t
- LEFT JOIN trace_latency AS tl ON tl.trace_id = t.id
- LEFT JOIN usage AS u ON u.trace_id = t.id
- LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = t.id
+ SELECT
+ name,
+ AVG(value) avg_value
+ FROM
+ scores
+ WHERE
+ trace_id = t.id
+ GROUP BY
+ name
+ ) tmp
+ ) AS s_avg ON true
WHERE
t."project_id" = ${projectId}
${searchCondition}