Skip to content

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

feat(api): add `GET metrics/daily` endpoint to fetch aggregate statistics (#1204)

Marc Klingen3e2f3f3d28e6
diff --git a/fern/apis/server/definition/metrics.yml b/fern/apis/server/definition/metrics.yml
new file mode 100644
index 0000000000..7423daa87c
--- /dev/null
+++ b/fern/apis/server/definition/metrics.yml
@@ -0,0 +1,48 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ pagination: ./utils/pagination.yml
+ commons: ./commons.yml
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ daily:
+ docs: Get daily metrics of the Langfuse project
+ method: GET
+ path: /metrics/daily
+ request:
+ name: GetDailyMetricsRequest
+ query-parameters:
+ page: optional<integer>
+ limit: optional<integer>
+ traceName:
+ type: optional<string>
+ docs: Optional filter by the name of the trace
+ userId:
+ type: optional<string>
+ docs: Optional filter by the userId associated with the trace
+ tags:
+ type: optional<string>
+ allow-multiple: true
+ docs: Optional filter for metrics where traces include all of these tags
+ response: DailyMetrics
+types:
+ DailyMetrics:
+ properties:
+ data:
+ type: list<DailyMetricsDetails>
+ docs: A list of daily metrics, only days with ingested data are included.
+ meta: pagination.MetaResponse
+ DailyMetricsDetails:
+ properties:
+ date: date
+ countTraces: integer
+ totalCost: double
+ usage: list<UsageByModel>
+ UsageByModel:
+ docs: Daily usage of a given model. Usage corresponds to the unit set for the specific model (e.g. tokens).
+ properties:
+ model: string
+ inputUsage: integer
+ outputUsage: integer
+ totalUsage: integer
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 36550c5fe3..71d3f1ec19 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -387,6 +387,81 @@ paths:
$ref: '#/components/schemas/IngestionEvent'
required:
- batch
+ /api/public/metrics/daily:
+ get:
+ description: Get daily metrics of the Langfuse project
+ operationId: metrics_daily
+ tags:
+ - Metrics
+ parameters:
+ - name: page
+ in: query
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ - name: limit
+ in: query
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ - name: traceName
+ in: query
+ description: Optional filter by the name of the trace
+ required: false
+ schema:
+ type: string
+ nullable: true
+ - name: userId
+ in: query
+ description: Optional filter by the userId associated with the trace
+ required: false
+ schema:
+ type: string
+ nullable: true
+ - name: tags
+ in: query
+ description: Optional filter for metrics where traces include all of these tags
+ required: false
+ schema:
+ type: array
+ items:
+ type: string
+ nullable: true
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DailyMetrics'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security: *ref_0
/api/public/observations/{observationId}:
get:
description: Get a specific observation
@@ -2000,6 +2075,60 @@ components:
required:
- successes
- errors
+ DailyMetrics:
+ title: DailyMetrics
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/DailyMetricsDetails'
+ description: A list of daily metrics, only days with ingested data are included.
+ meta:
+ $ref: '#/components/schemas/utilsMetaResponse'
+ required:
+ - data
+ - meta
+ DailyMetricsDetails:
+ title: DailyMetricsDetails
+ type: object
+ properties:
+ date:
+ type: string
+ countTraces:
+ type: integer
+ totalCost:
+ type: number
+ format: double
+ usage:
+ type: array
+ items:
+ $ref: '#/components/schemas/UsageByModel'
+ required:
+ - date
+ - countTraces
+ - totalCost
+ - usage
+ UsageByModel:
+ title: UsageByModel
+ type: object
+ description: >-
+ Daily usage of a given model. Usage corresponds to the unit set for the
+ specific model (e.g. tokens).
+ properties:
+ model:
+ type: string
+ inputUsage:
+ type: integer
+ outputUsage:
+ type: integer
+ totalUsage:
+ type: integer
+ required:
+ - model
+ - inputUsage
+ - outputUsage
+ - totalUsage
Observations:
title: Observations
type: object
diff --git a/generated/postman/collection.json b/generated/postman/collection.json
index 3f65a83b1a..ce87cf6561 100644
--- a/generated/postman/collection.json
+++ b/generated/postman/collection.json
@@ -332,6 +332,65 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Metrics",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Daily",
+ "request": {
+ "description": "Get daily metrics of the Langfuse project",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/metrics/daily?page=&limit=&traceName=&userId=&tags=",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "metrics",
+ "daily"
+ ],
+ "query": [
+ {
+ "key": "page",
+ "value": "",
+ "description": null
+ },
+ {
+ "key": "limit",
+ "value": "",
+ "description": null
+ },
+ {
+ "key": "traceName",
+ "value": "",
+ "description": "Optional filter by the name of the trace"
+ },
+ {
+ "key": "userId",
+ "value": "",
+ "description": "Optional filter by the userId associated with the trace"
+ },
+ {
+ "key": "tags",
+ "value": "",
+ "description": "Optional filter for metrics where traces include all of these tags"
+ }
+ ],
+ "variable": []
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
diff --git a/src/__tests__/metrics-api.servertest.ts b/src/__tests__/metrics-api.servertest.ts
new file mode 100644
index 0000000000..dc6a6d0816
--- /dev/null
+++ b/src/__tests__/metrics-api.servertest.ts
@@ -0,0 +1,94 @@
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { v4 as uuidv4 } from "uuid";
+
+describe("/api/public/metrics/daily API Endpoint", () => {
+ beforeEach(async () => await pruneDatabase());
+ afterEach(async () => await pruneDatabase());
+
+ it("should handle daily metrics correctly", async () => {
+ await pruneDatabase();
+
+ // Create traces with observations on different days
+ const traceId1 = uuidv4();
+ const traceId2 = uuidv4();
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId1,
+ timestamp: "2021-01-01T00:00:00.000Z",
+ name: "trace-day-1",
+ userId: "user-daily-metrics",
+ projectId: "project-daily-metrics",
+ });
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId2,
+ timestamp: "2021-01-02T00:00:00.000Z",
+ name: "trace-day-2",
+ userId: "user-daily-metrics",
+ projectId: "project-daily-metrics",
+ });
+
+ // Simulate observations with usage metrics on different days
+ await makeAPICall("POST", "/api/public/generations", {
+ traceId: traceId1,
+ model: "modelA",
+ usage: { input: 100, output: 200, total: 300 },
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:01:00.000Z",
+ });
+ await makeAPICall("POST", "/api/public/generations", {
+ traceId: traceId2,
+ model: "modelB",
+ usage: { input: 333 },
+ startTime: "2021-01-02T00:00:00.000Z",
+ endTime: "2021-01-02T00:02:00.000Z",
+ });
+ await makeAPICall("POST", "/api/public/generations", {
+ traceId: traceId2,
+ model: "modelC",
+ usage: { input: 666, output: 777, totalCost: 1024.22 },
+ startTime: "2021-01-02T00:00:00.000Z",
+ endTime: "2021-01-02T00:04:00.000Z",
+ });
+
+ // Retrieve the daily metrics
+ const dailyMetricsResponse = await makeAPICall<{
+ data: Array<Record<string, unknown>>;
+ }>("GET", `/api/public/metrics/daily`);
+ const dailyMetricsData = dailyMetricsResponse.body.data;
+
+ // Check if the daily metrics are calculated correctly
+ expect(dailyMetricsData).toHaveLength(2); // Two days of data
+ if (!dailyMetricsData[0])
+ throw new Error("dailyMetricsData[0] is undefined");
+ expect(dailyMetricsData[0].date).toBe("2021-01-02"); // Latest date first
+ expect(dailyMetricsData[0].countTraces).toBe(1);
+ expect(dailyMetricsData[0].totalCost).toEqual(1024.22);
+ expect(dailyMetricsData[0].usage).toEqual([
+ {
+ model: "modelB",
+ inputUsage: 333,
+ outputUsage: 0,
+ totalUsage: 333,
+ },
+ {
+ model: "modelC",
+ inputUsage: 666,
+ outputUsage: 777,
+ totalUsage: 1443,
+ },
+ ]);
+
+ if (!dailyMetricsData[1])
+ throw new Error("dailyMetricsData[1] is undefined");
+ expect(dailyMetricsData[1].date).toBe("2021-01-01");
+ expect(dailyMetricsData[1].countTraces).toBe(1);
+ expect(dailyMetricsData[1].totalCost).toEqual(0);
+ expect(dailyMetricsData[1].usage).toEqual([
+ {
+ model: "modelA",
+ inputUsage: 100,
+ outputUsage: 200,
+ totalUsage: 300,
+ },
+ ]);
+ });
+});
diff --git a/src/__tests__/test-utils.ts b/src/__tests__/test-utils.ts
index 954e20c81a..4e555e87ca 100644
--- a/src/__tests__/test-utils.ts
+++ b/src/__tests__/test-utils.ts
@@ -44,12 +44,12 @@ export type ErrorIngestion = {
error: string;
};
-export async function makeAPICall(
+export async function makeAPICall<T = IngestionAPIResponse>(
method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH",
url: string,
body?: unknown,
auth?: string,
-) {
+): Promise<{ body: T; status: number }> {
const finalUrl = `http://localhost:3000/${url}`;
const authorization =
auth || createBasicAuthHeader("pk-lf-1234567890", "sk-lf-1234567890");
@@ -60,14 +60,12 @@ export async function makeAPICall(
"Content-Type": "application/json;charset=UTF-8",
Authorization: authorization,
},
- // Conditionally include the body property if the method is not "GET"
...(method !== "GET" &&
body !== undefined && { body: JSON.stringify(body) }),
};
- const a = await fetch(finalUrl, options);
-
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- return { body: (await a.json()) as IngestionAPIResponse, status: a.status };
+ const response = await fetch(finalUrl, options);
+ const responseBody = (await response.json()) as T;
+ return { body: responseBody, status: response.status };
}
export const setupUserAndProject = async () => {
diff --git a/src/__tests__/traces.servertest.ts b/src/__tests__/traces.servertest.ts
index 1ff3ebbb0a..50ca6cde1b 100644
--- a/src/__tests__/traces.servertest.ts
+++ b/src/__tests__/traces.servertest.ts
@@ -2,6 +2,14 @@
import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { prisma } from "@/src/server/db";
+import { v4 as uuidv4 } from "uuid";
+
+interface TraceAPIResponse {
+ data: Array<{
+ id: string;
+ [key: string]: unknown;
+ }>;
+}
describe("/api/public/traces API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
@@ -108,34 +116,82 @@ describe("/api/public/traces API Endpoint", () => {
});
// multiple tags
- const traces = await makeAPICall(
+ const traces = await makeAPICall<TraceAPIResponse>(
"GET",
"/api/public/traces?tags=tag-2&tags=tag-3",
);
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
- const traceIds = traces.body.data.map((t: { id: string }) => t.id);
+ const traceIds = traces.body.data.map((t) => t.id);
// check for equality ok as ordered by timestamp
expect(traceIds).toEqual(["trace-3", "trace-1"]);
// single tag
- const traces2 = await makeAPICall("GET", "/api/public/traces?tags=tag-1");
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
- const traceIds2 = traces2.body.data.map((t: { id: string }) => t.id);
+ const traces2 = await makeAPICall<TraceAPIResponse>(
+ "GET",
+ "/api/public/traces?tags=tag-1",
+ );
+ const traceIds2 = traces2.body.data.map((t) => t.id);
// check for equality ok as ordered by timestamp
expect(traceIds2).toEqual(["trace-2", "trace-1"]);
// wrong tag
- const traces3 = await makeAPICall("GET", "/api/public/traces?tags=tag-10");
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
- const traceIds3 = traces3.body.data.map((t: { id: string }) => t.id);
+ const traces3 = await makeAPICall<TraceAPIResponse>(
+ "GET",
+ "/api/public/traces?tags=tag-10",
+ );
+ const traceIds3 = traces3.body.data.map((t) => t.id);
// check for equality ok as ordered by timestamp
expect(traceIds3).toEqual([]);
// no tag
- const traces4 = await makeAPICall("GET", "/api/public/traces?tags=");
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
- const traceIds4 = traces4.body.data.map((t: { id: string }) => t.id);
+ const traces4 = await makeAPICall<TraceAPIResponse>(
+ "GET",
+ "/api/public/traces?tags=",
+ );
+ const traceIds4 = traces4.body.data.map((t) => t.id);
// check for equality ok as ordered by timestamp
expect(traceIds4).toEqual(["trace-3", "trace-2", "trace-1"]);
});
+
+ it("should handle totalCost and latency correctly", async () => {
+ await pruneDatabase();
+
+ // Create a trace with some observations that have costs and latencies
+ const traceId = uuidv4();
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId,
+ name: "trace-with-costs",
+ userId: "user-costs",
+ projectId: "project-costs",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+ console.log(traceId);
+
+ // Simulate observations with costs and latencies
+ await makeAPICall("POST", "/api/public/generations", {
+ traceId: traceId,
+ usage: { totalCost: 10.5 },
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:10:00.000Z",
+ });
+ await makeAPICall("POST", "/api/public/generations", {
+ traceId: traceId,
+ usage: { totalCost: 5.25 },
+ startTime: "2021-01-01T00:10:00.000Z",
+ endTime: "2021-01-01T00:20:00.000Z",
+ });
+
+ // Retrieve the trace with totalCost and latency
+ const traces = await makeAPICall<TraceAPIResponse>(
+ "GET",
+ `/api/public/traces`,
+ );
+ const traceData = traces.body.data[0];
+ if (!traceData) throw new Error("traceData is undefined");
+
+ // Check if the totalCost and latency are calculated correctly
+ expect(traceData.totalCost).toBeCloseTo(15.75); // Sum of costs
+ expect(traceData.latency).toBeCloseTo(1200); // Difference in seconds between min startTime and max endTime
+ });
});
diff --git a/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.ts
index 40d18e95ee..4c35f36288 100644
--- a/src/features/public-api/server/ingestion-api-schema.ts
+++ b/src/features/public-api/server/ingestion-api-schema.ts
@@ -45,16 +45,13 @@ export const usage = MixedUsage.nullish()
unit: ModelUsageUnit.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;
- return { ...v, unit };
- }
// if the object is empty, we return undefined
if (lodash.isEmpty(v)) {
return undefined;
}
+
+ return v;
})
// ensure output is always of new usage model
.pipe(Usage.nullish());
diff --git a/src/pages/api/public/metrics/daily.ts b/src/pages/api/public/metrics/daily.ts
new file mode 100644
index 0000000000..076a5ffe4d
--- /dev/null
+++ b/src/pages/api/public/metrics/daily.ts
@@ -0,0 +1,159 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { z } from "zod";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { prisma } from "@/src/server/db";
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { Prisma } from "@prisma/client";
+import { paginationZod } from "@/src/utils/zod";
+
+const GetUsageSchema = z.object({
+ ...paginationZod,
+ traceName: z.string().nullish(),
+ userId: z.string().nullish(),
+ tags: z.union([z.array(z.string()), z.string()]).nullish(),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ // CHECK AUTH
+ const authCheck = await verifyAuthHeaderAndReturnScope(
+ req.headers.authorization,
+ );
+ if (!authCheck.validKey)
+ return res.status(401).json({
+ message: authCheck.error,
+ });
+ // END CHECK AUTH
+
+ try {
+ if (req.method === "GET") {
+ if (authCheck.scope.accessLevel !== "all") {
+ return res.status(401).json({
+ message:
+ "Access denied - need to use basic auth with secret key to GET scores",
+ });
+ }
+ const obj = GetUsageSchema.parse(req.query); // uses query and not body
+
+ const traceNameCondition = obj.traceName
+ ? Prisma.sql`AND t.name = ${obj.traceName}`
+ : Prisma.empty;
+ const userCondition = obj.userId
+ ? Prisma.sql`AND t."user_id" = ${obj.userId}`
+ : Prisma.empty;
+ const tagsCondition = obj.tags
+ ? Prisma.sql`AND ARRAY[${Prisma.join(
+ (Array.isArray(obj.tags) ? obj.tags : [obj.tags]).map(
+ (v) => Prisma.sql`${v}`,
+ ),
+ ", ",
+ )}] <@ t."tags"`
+ : Prisma.empty;
+
+ const usage = await prisma.$queryRaw`
+ WITH model_usage AS (
+ SELECT
+ DATE_TRUNC('DAY',
+ o.start_time) "date",
+ o.model,
+ SUM(o.prompt_tokens) inputUsage,
+ SUM(o.completion_tokens) outputUsage,
+ SUM(o.total_tokens) totalUsage
+ FROM
+ traces t
+ LEFT JOIN observations o ON o.trace_id = t.id AND o.project_id = t.project_id
+ WHERE o.start_time IS NOT NULL
+ AND t.project_id = ${authCheck.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ GROUP BY
+ 1,
+ 2
+ ORDER BY
+ 1,
+ 2
+ ),
+ daily_model_usage AS (
+ SELECT
+ "date",
+ json_agg(json_build_object('model',
+ model,
+ 'inputUsage',
+ inputUsage,
+ 'outputUsage',
+ outputUsage,
+ 'totalUsage',
+ totalUsage)) daily_usage_json
+ FROM
+ model_usage
+ GROUP BY
+ 1
+ ),
+ daily_stats AS (
+ SELECT
+ DATE_TRUNC('DAY', t.timestamp) "date",
+ count(distinct t.id)::integer count_traces,
+ SUM(o.calculated_total_cost)::DOUBLE PRECISION total_cost
+ FROM traces t
+ LEFT JOIN observations_view o ON o.project_id = t.project_id AND t.id = o.trace_id
+ WHERE t.project_id = ${authCheck.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ GROUP BY 1
+ )
+ SELECT
+ TO_CHAR(COALESCE(ds.date, daily_model_usage.date), 'YYYY-MM-DD') AS "date",
+ COALESCE(count_traces, 0) "countTraces",
+ COALESCE(total_cost, 0) "totalCost",
+ COALESCE(daily_usage_json, '[]'::JSON) usage
+ FROM
+ daily_stats ds
+ FULL OUTER JOIN
+ daily_model_usage ON daily_model_usage.date = ds.date
+ ORDER BY
+ 1 DESC
+ LIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}
+ `;
+
+ const totalItemsRes = await prisma.$queryRaw<{ count: number }[]>`
+ SELECT
+ COUNT(DISTINCT DATE_TRUNC('DAY', t.timestamp))::integer
+ FROM traces t
+ WHERE t.project_id = ${authCheck.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ `;
+
+ const totalItems =
+ totalItemsRes[0] !== undefined ? totalItemsRes[0].count : 0;
+
+ return res.status(200).json({
+ data: usage,
+ meta: {
+ page: obj.page,
+ limit: obj.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / obj.limit),
+ },
+ });
+ } else {
+ console.error(req.method, req.body);
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+ } catch (error: unknown) {
+ console.error(error);
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+}
diff --git a/src/pages/api/public/metrics/usage.ts b/src/pages/api/public/metrics/usage.ts
deleted file mode 100644
index ad90febf36..0000000000
--- a/src/pages/api/public/metrics/usage.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { prisma } from "@/src/server/db";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { Prisma } from "@prisma/client";
-import { paginationZod } from "@/src/utils/zod";
-
-const GetUsageSchema = z.object({
- ...paginationZod,
- group_by: z.enum(["trace_name"]).nullish(),
- trace_name: z.string().nullish(),
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- try {
- if (req.method === "GET") {
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message:
- "Access denied - need to use basic auth with secret key to GET scores",
- });
- }
- const obj = GetUsageSchema.parse(req.query); // uses query and not body
-
- const traceNameCondition = obj.trace_name
- ? Prisma.sql`AND t.name = ${obj.trace_name}`
- : Prisma.empty;
-
- if (obj.group_by === undefined) {
- const usage = await prisma.$queryRaw`
- WITH model_usage AS (
- SELECT
- DATE_TRUNC('DAY',
- o.start_time) observation_day,
- o.model,
- SUM(o.prompt_tokens) prompt_tokens,
- SUM(o.completion_tokens) completion_tokens,
- SUM(o.total_tokens) total_tokens
- FROM
- traces t
- LEFT JOIN observations o ON o.trace_id = t.id
- WHERE o.start_time IS NOT NULL
- AND o.project_id = ${authCheck.scope.projectId}
- AND t.project_id = ${authCheck.scope.projectId}
- ${traceNameCondition}
- GROUP BY 1,2
- order by 1,2
- ),
- daily_usage AS (
- SELECT
- observation_day,
- json_agg(json_build_object('model',
- model,
- 'prompt_tokens',
- prompt_tokens,
- 'completion_tokens',
- completion_tokens,
- 'total_tokens',
- total_tokens)) daily_usage_json
- FROM model_usage
- group by 1
- )
- SELECT
- observation_day "date",
- daily_usage_json usage
- FROM daily_usage
- ORDER BY 1 desc
- LIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}
- `;
- const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>`
- SELECT
- count(DISTINCT DATE_TRUNC('DAY', observations.start_time))
- FROM
- observations
- JOIN traces ON observations.trace_id = traces.id
- WHERE traces.project_id = ${authCheck.scope.projectId}
- `;
-
- const totalItems =
- totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
-
- return res.status(200).json({
- data: usage,
- meta: {
- page: obj.page,
- limit: obj.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / obj.limit),
- },
- });
- } else if (obj.group_by === "trace_name") {
- const usage = await prisma.$queryRaw`
- WITH model_usage AS (
- SELECT
- t."name" trace_name,
- DATE_TRUNC('DAY',
- o.start_time) observation_day,
- o.model,
- SUM(o.prompt_tokens) prompt_tokens,
- SUM(o.completion_tokens) completion_tokens,
- SUM(o.total_tokens) total_tokens
- FROM
- traces t
- LEFT JOIN observations o ON o.trace_id = t.id
- WHERE o.start_time IS NOT NULL
- AND t.project_id = ${authCheck.scope.projectId}
- AND o.project_id = ${authCheck.scope.projectId}
- ${traceNameCondition}
- GROUP BY 1,2,3
- order by 1,2,3
- ),
- daily_usage AS (
- SELECT
- trace_name,
- observation_day,
- json_agg(json_build_object('model',
- model,
- 'prompt_tokens',
- prompt_tokens,
- 'completion_tokens',
- completion_tokens,
- 'total_tokens',
- total_tokens)) daily_usage_json
- FROM model_usage
- WHERE prompt_tokens > 0
- OR completion_tokens > 0
- OR total_tokens > 0
- group by 1,2
- order by 1,2 desc
- ),
- all_trace_names AS (
- SELECT t."name" trace_name
- FROM traces t
- WHERE t.project_id = ${authCheck.scope.projectId}
- ${traceNameCondition}
- GROUP BY 1
- )
- SELECT
- all_trace_names.trace_name,
- json_agg(json_build_object(
- 'date',
- observation_day,
- 'usage',
- daily_usage_json
- )) metrics
- FROM all_trace_names
- LEFT JOIN daily_usage ON all_trace_names.trace_name = daily_usage.trace_name
- group by 1
- ORDER BY 1
- LIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}
- `;
- const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>`
- SELECT
- count(DISTINCT CASE WHEN "name" IS NULL THEN 'COUNT_NULL' ELSE "name" END)
- FROM
- traces
- WHERE project_id = ${authCheck.scope.projectId}
- `;
-
- const totalItems =
- totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
-
- return res.status(200).json({
- data: usage,
- meta: {
- page: obj.page,
- limit: obj.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / obj.limit),
- },
- });
- } else {
- return res.status(400).json({
- message: "Invalid group_by value",
- });
- }
- } else {
- console.error(req.method, req.body);
- return res.status(405).json({ message: "Method not allowed" });
- }
- } catch (error: unknown) {
- console.error(error);
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(400).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.ts
index 149dc3b384..deba05bcc0 100644
--- a/src/pages/api/public/traces.ts
+++ b/src/pages/api/public/traces.ts
@@ -124,8 +124,8 @@ export default async function handler(
t.release,
t.version,
t.tags,
- SUM(o.calculated_total_cost)::DOUBLE PRECISION AS "totalCost",
- EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time"))::double precision AS "latency",
+ COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION AS "totalCost",
+ COALESCE(EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time")), 0)::double precision AS "latency",
array_remove(array_agg(o.id), NULL) AS "observations",
array_remove(array_agg(s.id), NULL) AS "scores"
FROM "traces" AS t