Skip to content

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

Revamped dashboard and table filters (#277)

Maximilian Deichmann6f06336a0150
diff --git a/package-lock.json b/package-lock.json
index 4227fce08d..e20e83f418 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -51,6 +51,7 @@
"clsx": "^2.0.0",
"cmdk": "^0.2.0",
"cors": "^2.8.5",
+ "date-fns": "^2.30.0",
"decimal.js": "^10.4.3",
"exponential-backoff": "^3.1.1",
"js-yaml": "^4.1.0",
@@ -63,6 +64,7 @@
"posthog-js": "^1.81.3",
"posthog-node": "^3.1.2",
"react": "18.2.0",
+ "react-day-picker": "^8.8.2",
"react-dom": "18.2.0",
"react-hook-form": "^7.46.2",
"react-icons": "^4.11.0",
@@ -11397,9 +11399,9 @@
}
},
"node_modules/react-day-picker": {
- "version": "8.8.1",
- "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-8.8.1.tgz",
- "integrity": "sha512-U7RsRoRI5pyMXhKq54hS9yM11WEGkPf8hIdrxIM/sefgmQjuxazqgwcZFMiPZW/K9vtmzLZFf9bLW0wVsGYd5w==",
+ "version": "8.8.2",
+ "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-8.8.2.tgz",
+ "integrity": "sha512-sK5M5PNZaLiszmACUKUpVu1eX3eFDVV+WLdWQ3BxTPbEC9jhuawmlgpbSXX5dIIQQwJpZ4wwP5+vsMVOwa1IRw==",
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/gpbl"
diff --git a/package.json b/package.json
index 74d346a205..3919c2c668 100644
--- a/package.json
+++ b/package.json
@@ -64,6 +64,7 @@
"clsx": "^2.0.0",
"cmdk": "^0.2.0",
"cors": "^2.8.5",
+ "date-fns": "^2.30.0",
"decimal.js": "^10.4.3",
"exponential-backoff": "^3.1.1",
"js-yaml": "^4.1.0",
@@ -76,6 +77,7 @@
"posthog-js": "^1.81.3",
"posthog-node": "^3.1.2",
"react": "18.2.0",
+ "react-day-picker": "^8.8.2",
"react-dom": "18.2.0",
"react-hook-form": "^7.46.2",
"react-icons": "^4.11.0",
diff --git a/src/__tests__/events.servertest.ts b/src/__tests__/events.servertest.ts
index 9093c3c20f..c63772ee26 100644
--- a/src/__tests__/events.servertest.ts
+++ b/src/__tests__/events.servertest.ts
@@ -1,16 +1,10 @@
/** @jest-environment node */
import { prisma } from "@/src/server/db";
-import { makeAPICall } from "@/src/__tests__/test-utils";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
describe("/api/public/events API Endpoint", () => {
- const pruneDatabase = async () => {
- await prisma.observation.deleteMany();
- await prisma.score.deleteMany();
- await prisma.trace.deleteMany();
- };
-
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
diff --git a/src/__tests__/generations.servertest.ts b/src/__tests__/generations.servertest.ts
index 6a561dec52..99bc48958d 100644
--- a/src/__tests__/generations.servertest.ts
+++ b/src/__tests__/generations.servertest.ts
@@ -1,16 +1,10 @@
/** @jest-environment node */
import { prisma } from "@/src/server/db";
-import { makeAPICall } from "@/src/__tests__/test-utils";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
describe("/api/public/generations API Endpoint", () => {
- const pruneDatabase = async () => {
- await prisma.observation.deleteMany();
- await prisma.score.deleteMany();
- await prisma.trace.deleteMany();
- };
-
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
diff --git a/src/__tests__/query-builder.servertest.ts b/src/__tests__/query-builder.servertest.ts
new file mode 100644
index 0000000000..aefac64590
--- /dev/null
+++ b/src/__tests__/query-builder.servertest.ts
@@ -0,0 +1,472 @@
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ createQuery,
+ enrichAndCreateQuery,
+ executeQuery,
+} from "@/src/server/api/services/query-builder";
+import { prisma } from "@/src/server/db";
+
+describe("Build valid SQL queries", () => {
+ beforeEach(async () => await pruneDatabase());
+
+ describe("should enrich mandatory filters", () => {
+ [
+ {
+ table: "traces",
+ values: ["project-id"],
+ strings: [' FROM traces t WHERE t."project_id" = ', " ;"],
+ } as const,
+ {
+ 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" = ',
+ ' AND o."project_id" = ',
+ " ;",
+ ],
+ } as const,
+ {
+ table: "observations",
+ values: ["project-id"],
+ strings: [' FROM observations o WHERE o."project_id" = ', " ;"],
+ } as const,
+ {
+ table: "traces_scores",
+ values: ["project-id"],
+ strings: [
+ ' FROM traces t JOIN scores s ON t.id = s.trace_id WHERE t."project_id" = ',
+ " ;",
+ ],
+ } as const,
+ ].forEach((prop) => {
+ it(`should enrich mandatory filters ${prop.table}`, () => {
+ const preparedQuery = enrichAndCreateQuery("project-id", {
+ from: prop.table,
+ filter: [],
+ groupBy: [],
+ select: [],
+ orderBy: [],
+ });
+ expect(preparedQuery.values).toEqual(prop.values);
+ expect(preparedQuery.strings).toEqual(prop.strings);
+ });
+ });
+ });
+
+ describe("should build safe SQL", () => {
+ it("should build a simple filter query", () => {
+ const preparedQuery = createQuery({
+ from: "traces",
+ filter: [
+ {
+ type: "string" as const,
+ column: "tracesProjectId",
+ operator: "=" as const,
+ value: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ ],
+ groupBy: [],
+ select: [{ column: "traceId", agg: null }],
+ orderBy: [],
+ });
+
+ expect(preparedQuery.values).toEqual([
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ ]);
+ });
+
+ it("should build a simple group by and filter query", () => {
+ const preparedQuery = createQuery({
+ from: "traces",
+ filter: [
+ {
+ type: "string" as const,
+ column: "tracesProjectId",
+ operator: "=" as const,
+ value: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ ],
+ groupBy: [{ type: "string", column: "version" }],
+ select: [{ column: "traceId", agg: null }],
+ orderBy: [],
+ });
+
+ expect(preparedQuery.values).toEqual([
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ ]);
+ });
+
+ it("should build a time series group", () => {
+ const preparedQuery = createQuery({
+ from: "observations",
+ filter: [
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: ">=",
+ value: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: "<=",
+ value: new Date("2021-01-04T00:00:00.000Z"),
+ },
+ ],
+ groupBy: [
+ { type: "datetime", column: "startTime", temporalUnit: "day" },
+ ],
+ select: [{ column: "completionTokens", agg: "SUM" }],
+ orderBy: [],
+ });
+
+ expect(preparedQuery.values).toEqual([
+ new Date("2021-01-01T00:00:00.000Z"),
+ new Date("2021-01-04T00:00:00.000Z"),
+ new Date("2021-01-01T00:00:00.000Z"),
+ new Date("2021-01-04T00:00:00.000Z"),
+ ]);
+ });
+
+ it("should not filter an unknown column", () => {
+ expect(() =>
+ createQuery({
+ from: "traces",
+ filter: [
+ { type: "string", column: "unknown", operator: "=", value: "" },
+ ],
+ groupBy: [],
+ select: [],
+ orderBy: [],
+ }),
+ ).toThrow("Column unknown not found");
+ });
+
+ it("should not select an unknown column", () => {
+ expect(() =>
+ createQuery({
+ from: "traces",
+ filter: [],
+ groupBy: [],
+ select: [{ column: "unknown", agg: null }],
+ orderBy: [],
+ }),
+ ).toThrow("Column unknown not found");
+ });
+
+ it("should not group by an unknown column", () => {
+ expect(() =>
+ createQuery({
+ from: "traces",
+ filter: [],
+ groupBy: [{ column: "unknown", type: "string" }],
+ select: [],
+ orderBy: [],
+ }),
+ ).toThrow("Column unknown not found");
+ });
+
+ it("should not order by an unknown column", () => {
+ expect(() =>
+ createQuery({
+ from: "traces",
+ filter: [],
+ groupBy: [],
+ select: [],
+ orderBy: [{ column: "unknown", direction: "ASC" }],
+ }),
+ ).toThrow("Column unknown not found");
+ });
+ });
+
+ describe("should retrieve data", () => {
+ it("should get a simple trace", async () => {
+ await prisma.project.upsert({
+ where: { id: "different-project-id" },
+ create: {
+ id: "different-project-id",
+ name: "test-project",
+ },
+ update: {},
+ });
+
+ await prisma.trace.createMany({
+ data: [
+ {
+ id: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ {
+ id: "trace-2",
+ name: "trace-1",
+ projectId: "different-project-id",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ ],
+ });
+
+ const result = await executeQuery(
+ prisma,
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ {
+ from: "traces",
+ filter: [],
+ groupBy: [],
+ select: [{ column: "traceId", agg: null }],
+ orderBy: [],
+ },
+ );
+
+ expect(result).toEqual([{ traceId: "trace-1" }]);
+ });
+
+ [
+ {
+ agg: "SUM",
+ first: { sumCompletionTokens: 8, name: "trace-1" },
+ second: { sumCompletionTokens: 4, name: "trace-2" },
+ },
+ {
+ agg: "AVG",
+ first: { avgCompletionTokens: 4, name: "trace-1" },
+ second: { avgCompletionTokens: 4, name: "trace-2" },
+ },
+ {
+ agg: "MIN",
+ first: { minCompletionTokens: 3, name: "trace-1" },
+ second: { minCompletionTokens: 4, name: "trace-2" },
+ },
+ {
+ agg: "MAX",
+ first: { maxCompletionTokens: 5, name: "trace-1" },
+ second: { maxCompletionTokens: 4, name: "trace-2" },
+ },
+ {
+ agg: "COUNT",
+ first: { countCompletionTokens: 2, name: "trace-1" },
+ second: { countCompletionTokens: 1, name: "trace-2" },
+ },
+ ].forEach((prop) => {
+ it(`should group by name and aggregate ${prop.agg}`, async () => {
+ await prisma.trace.create({
+ data: {
+ id: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ await prisma.observation.createMany({
+ data: [
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 5,
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 3,
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-2",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 4,
+ },
+ ],
+ });
+
+ const result = await executeQuery(
+ prisma,
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ {
+ from: "observations",
+ filter: [],
+ groupBy: [{ type: "string", column: "name" }],
+ select: [
+ { column: "completionTokens", agg: prop.agg as "SUM" | "AVG" },
+ { column: "name", agg: null },
+ ],
+ orderBy: [],
+ },
+ );
+
+ expect(result[0]!).toStrictEqual(prop.first);
+ expect(result[1]!).toStrictEqual(prop.second);
+ });
+ });
+
+ it("should order by a column", async () => {
+ await prisma.trace.create({
+ data: {
+ id: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ await prisma.observation.createMany({
+ data: [
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 5,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 3,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-2",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 4,
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ },
+ ],
+ });
+
+ const result = await executeQuery(
+ prisma,
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ {
+ from: "observations",
+ filter: [
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: ">=",
+ value: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: "<=",
+ value: new Date("2021-01-04T00:00:00.000Z"),
+ },
+ ],
+ groupBy: [],
+ select: [{ column: "completionTokens", agg: null }],
+ orderBy: [{ column: "completionTokens", direction: "ASC" }],
+ },
+ );
+
+ expect(result).toStrictEqual([
+ { completionTokens: 3 },
+ { completionTokens: 4 },
+ { completionTokens: 5 },
+ ]);
+ });
+
+ [{ agg: "SUM", one: 8, two: 4 }].forEach((prop) => {
+ it(`should aggregate time series ${prop.agg}`, async () => {
+ await prisma.trace.create({
+ data: {
+ id: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ await prisma.observation.createMany({
+ data: [
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 5,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 3,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-2",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 4,
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ },
+ ],
+ });
+
+ const result = await executeQuery(
+ prisma,
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ {
+ from: "observations",
+ filter: [
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: ">=",
+ value: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: "<=",
+ value: new Date("2021-01-04T00:00:00.000Z"),
+ },
+ ],
+ groupBy: [
+ { type: "datetime", column: "startTime", temporalUnit: "day" },
+ ],
+ select: [
+ { column: "completionTokens", agg: prop.agg as "SUM" | "AVG" },
+ ],
+ orderBy: [],
+ },
+ );
+
+ expect(result).toStrictEqual([
+ {
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ sumCompletionTokens: 8,
+ },
+ {
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ sumCompletionTokens: 4,
+ },
+ {
+ startTime: new Date("2021-01-03T00:00:00.000Z"),
+ sumCompletionTokens: null,
+ },
+ {
+ startTime: new Date("2021-01-04T00:00:00.000Z"),
+ sumCompletionTokens: null,
+ },
+ ]);
+ });
+ });
+ });
+});
diff --git a/src/__tests__/scores.servertest.ts b/src/__tests__/scores.servertest.ts
index efdf06912a..99335e7a96 100644
--- a/src/__tests__/scores.servertest.ts
+++ b/src/__tests__/scores.servertest.ts
@@ -1,16 +1,10 @@
/** @jest-environment node */
import { prisma } from "@/src/server/db";
-import { makeAPICall } from "@/src/__tests__/test-utils";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
describe("/api/public/scores API Endpoint", () => {
- const pruneDatabase = async () => {
- await prisma.observation.deleteMany();
- await prisma.score.deleteMany();
- await prisma.trace.deleteMany();
- };
-
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
diff --git a/src/__tests__/spans.servertest.ts b/src/__tests__/spans.servertest.ts
index c66a7dd899..66c3500942 100644
--- a/src/__tests__/spans.servertest.ts
+++ b/src/__tests__/spans.servertest.ts
@@ -1,16 +1,10 @@
/** @jest-environment node */
import { prisma } from "@/src/server/db";
-import { makeAPICall } from "@/src/__tests__/test-utils";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
describe("/api/public/spans API Endpoint", () => {
- const pruneDatabase = async () => {
- await prisma.observation.deleteMany();
- await prisma.score.deleteMany();
- await prisma.trace.deleteMany();
- };
-
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
diff --git a/src/__tests__/test-utils.ts b/src/__tests__/test-utils.ts
index 6eb7dbc162..ade688cdaa 100644
--- a/src/__tests__/test-utils.ts
+++ b/src/__tests__/test-utils.ts
@@ -5,6 +5,12 @@ import {
import { prisma } from "@/src/server/db";
import { hash } from "bcryptjs";
+export const pruneDatabase = async () => {
+ await prisma.score.deleteMany();
+ await prisma.observation.deleteMany();
+ await prisma.trace.deleteMany();
+};
+
export function createBasicAuthHeader(
username: string,
password: string,
diff --git a/src/__tests__/traces.servertest.ts b/src/__tests__/traces.servertest.ts
index f242670a8d..92470a6002 100644
--- a/src/__tests__/traces.servertest.ts
+++ b/src/__tests__/traces.servertest.ts
@@ -1,15 +1,9 @@
/** @jest-environment node */
-import { makeAPICall } from "@/src/__tests__/test-utils";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { prisma } from "@/src/server/db";
describe("/api/public/traces API Endpoint", () => {
- const pruneDatabase = async () => {
- await prisma.observation.deleteMany();
- await prisma.score.deleteMany();
- await prisma.trace.deleteMany();
- };
-
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
diff --git a/src/components/date-picker.tsx b/src/components/date-picker.tsx
new file mode 100644
index 0000000000..f0e74d5045
--- /dev/null
+++ b/src/components/date-picker.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import * as React from "react";
+import { format } from "date-fns";
+import { Calendar as CalendarIcon } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { Calendar } from "@/src/components/ui/calendar";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { cn } from "@/src/utils/tailwind";
+
+export function DatePicker({
+ date,
+ onChange,
+ className,
+}: {
+ date?: Date | undefined;
+ onChange: (date: Date | undefined) => void;
+ className?: string;
+}) {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant={"outline"}
+ className={cn(
+ "justify-start text-left font-normal",
+ !date && "text-muted-foreground",
+ className,
+ )}
+ >
+ <CalendarIcon className="mr-2 h-4 w-4" />
+ {date ? format(date, "PPP") : <span>Pick a date</span>}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0">
+ <Calendar
+ mode="single"
+ selected={date}
+ onSelect={(d) => onChange(d)}
+ initialFocus
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/components/grouped-score-badge.tsx b/src/components/grouped-score-badge.tsx
index bf3ce2ec10..17a34d45c0 100644
--- a/src/components/grouped-score-badge.tsx
+++ b/src/components/grouped-score-badge.tsx
@@ -32,7 +32,7 @@ export const GroupedScoreBadges = ({
.map(([name, scores]) => (
<div key={name}>
<div className="text-xs text-gray-500">{name}</div>
- <div className="text-sm">
+ <div className="text-xs">
{scores.map((s) => s.value.toFixed(2)).join(", ")}
</div>
</div>
diff --git a/src/components/table/data-table-toolbar.tsx b/src/components/table/data-table-toolbar.tsx
index be5510af2d..80719d8d3c 100644
--- a/src/components/table/data-table-toolbar.tsx
+++ b/src/components/table/data-table-toolbar.tsx
@@ -1,13 +1,9 @@
-import { type ColumnDef } from "@tanstack/react-table";
-import { X } from "lucide-react";
-
import { Button } from "@/src/components/ui/button";
-import { type TableRowOptions } from "@/src/components/table/types";
-import { DataTableSelectFilter } from "@/src/components/table/data-table-select-filter";
-import { DataTableNumberFilter } from "@/src/components/table/data-table-number-filter";
-import React, { useState } from "react";
+import React, { type Dispatch, type SetStateAction, useState } from "react";
import { Input } from "@/src/components/ui/input";
-import { DataTableKeyValueFilter } from "@/src/components/table/data-table-key-value-filter";
+import { type FilterState } from "@/src/features/filters/types";
+import { FilterBuilder } from "@/src/features/filters/components/filter-builder";
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
interface SearchConfig {
placeholder: string;
@@ -15,84 +11,35 @@ interface SearchConfig {
currentQuery?: string;
}
-interface DataTableToolbarProps<TData, TValue> {
- columnDefs: ColumnDef<TData, TValue>[];
- options: TableRowOptions[];
+interface DataTableToolbarProps {
+ filterColumnDefinition: ColumnDefinition[];
searchConfig?: SearchConfig;
- resetFilters: () => void;
- isFiltered: () => boolean;
actionButtons?: React.ReactNode;
+ filterState: FilterState;
+ setFilterState: Dispatch<SetStateAction<FilterState>>;
}
-export function DataTableToolbar<TData, TValue>({
- columnDefs,
- options,
+export function DataTableToolbar({
+ filterColumnDefinition,
searchConfig,
- resetFilters,
- isFiltered,
actionButtons,
-}: DataTableToolbarProps<TData, TValue>) {
+ filterState,
+ setFilterState,
+}: DataTableToolbarProps) {
const [searchString, setSearchString] = useState(
searchConfig?.currentQuery ?? "",
);
- const renderFilter = (
- column: ColumnDef<TData, TValue>,
- columnOptions: TableRowOptions | undefined,
- ) => {
- if (
- !column ||
- !column.enableColumnFilter ||
- !columnOptions ||
- !column?.meta?.filter
- )
- return undefined;
-
- const filter = column.meta.filter;
- const label = column.meta?.label;
- const type = filter.type;
-
- if (type === "select") {
- return (
- <DataTableSelectFilter
- key={label}
- title={label}
- meta={filter}
- options={columnOptions}
- />
- );
- }
-
- if (type === "number-comparison") {
- return (
- <DataTableNumberFilter
- key={label}
- title={label}
- meta={filter}
- options={columnOptions}
- />
- );
- }
-
- if (type === "key-value") {
- return (
- <DataTableKeyValueFilter key={label} title={label} meta={filter} />
- );
- }
-
- return undefined;
- };
-
return (
<div className="my-2 flex max-w-full items-center justify-between overflow-x-auto">
<div className="flex flex-1 items-center space-x-2">
{searchConfig ? (
- <div className="flex w-full max-w-md items-center space-x-2">
+ <div className="flex max-w-md items-center space-x-2">
<Input
autoFocus
placeholder={searchConfig.placeholder}
value={searchString}
- className="h-8 w-[350px]"
+ className="h-10 w-[200px] lg:w-[350px]"
onChange={(event) => {
setSearchString(event.currentTarget.value);
}}
@@ -106,26 +53,11 @@ export function DataTableToolbar<TData, TValue>({
</Button>
</div>
) : undefined}
- {options
- ? columnDefs.map((column) => {
- const columnOptions = options.find(
- (o) =>
- o.columnId.toLowerCase() ===
- column.meta?.label?.toLowerCase(),
- );
- return renderFilter(column, columnOptions);
- })
- : undefined}
- {isFiltered() && (
- <Button
- variant="ghost"
- onClick={() => resetFilters()}
- className="h-8 px-2 lg:px-3"
- >
- Reset
- <X className="ml-2 h-4 w-4" />
- </Button>
- )}
+ <FilterBuilder
+ columns={filterColumnDefinition}
+ filterState={filterState}
+ onChange={setFilterState}
+ />
<div className="flex-1" />
{actionButtons ? actionButtons : null}
</div>
diff --git a/src/components/table/data-table.tsx b/src/components/table/data-table.tsx
index 6f97889c34..19b4b8d141 100644
--- a/src/components/table/data-table.tsx
+++ b/src/components/table/data-table.tsx
@@ -19,13 +19,11 @@ import {
TableRow,
} from "@/src/components/ui/table";
import { useState } from "react";
-import { type TableRowOptions } from "@/src/components/table/types";
import { DataTablePagination } from "@/src/components/table/data-table-pagination";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: AsyncTableData<TData[]>;
- options: AsyncTableData<TableRowOptions[]>;
pagination?: {
pageCount: number;
onChange: OnChangeFn<PaginationState>;
diff --git a/src/components/table/use-cases/scores.tsx b/src/components/table/use-cases/scores.tsx
index c6febeba8f..c1473462ff 100644
--- a/src/components/table/use-cases/scores.tsx
+++ b/src/components/table/use-cases/scores.tsx
@@ -1,12 +1,12 @@
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import TableLink from "@/src/components/table/table-link";
-import { type TableRowOptions } from "@/src/components/table/types";
+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { scoresTableColsWithOptions } from "@/src/server/api/definitions/scoresTable";
import { api } from "@/src/utils/api";
-import { type RouterOutput, type RouterInput } from "@/src/utils/types";
+import { type RouterInput } from "@/src/utils/types";
import { type Score } from "@prisma/client";
import { type ColumnDef } from "@tanstack/react-table";
-import { useState } from "react";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
type RowData = {
@@ -31,27 +31,32 @@ export default function ScoresTable({
projectId: string;
userId?: string;
}) {
- const [queryOptions, setQueryOptions] = useState<ScoreFilterInput>({
- traceId: null,
- });
-
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
});
+ const [userFilterState, setUserFilterState] = useQueryFilterState([]);
+ const filterState = userId
+ ? userFilterState.concat([
+ {
+ column: "userId",
+ type: "string",
+ operator: "=",
+ value: userId,
+ },
+ ])
+ : userFilterState;
+
const scores = api.scores.all.useQuery({
- ...queryOptions,
page: paginationState.pageIndex,
limit: paginationState.pageSize,
- userId: userId || null,
projectId,
+ filter: filterState,
});
const totalCount = scores.data?.slice(1)[0]?.totalCount ?? 0;
- const scoresOptions = api.scores.availableFilterOptions.useQuery({
- ...queryOptions,
- userId: userId || null,
+ const filterOptions = api.scores.filterOptions.useQuery({
projectId,
});
@@ -71,16 +76,6 @@ export default function ScoresTable({
</>
) : undefined;
},
- meta: {
- label: "TraceID",
- filter: {
- type: "select",
- values: queryOptions.traceId,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, traceId: newValues });
- },
- },
- },
},
{
accessorKey: "observationId",
@@ -115,33 +110,6 @@ export default function ScoresTable({
},
];
- const convertToOptions = (
- options: RouterOutput["scores"]["availableFilterOptions"],
- ): TableRowOptions[] => {
- return options.map((o) => {
- return {
- columnId: o.key,
- options: o.occurrences.map((o) => {
- return { label: o.key, value: o.count._all };
- }),
- };
- });
- };
-
- const tableOptions = scoresOptions.isLoading
- ? { isLoading: true, isError: false }
- : scoresOptions.isError
- ? {
- isLoading: false,
- isError: true,
- error: scoresOptions.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: convertToOptions(scoresOptions.data),
- };
-
const convertToTableRow = (score: Score): RowData => {
return {
id: score.id,
@@ -154,24 +122,13 @@ export default function ScoresTable({
};
};
- const isFiltered = () =>
- Object.entries(queryOptions).filter(([_k, v]) => v !== null).length > 0;
-
- const resetFilters = () =>
- setQueryOptions({
- traceId: null,
- });
-
return (
<div>
- {tableOptions.data ? (
- <DataTableToolbar
- columnDefs={columns}
- options={tableOptions.data}
- resetFilters={resetFilters}
- isFiltered={isFiltered}
- />
- ) : undefined}
+ <DataTableToolbar
+ filterColumnDefinition={scoresTableColsWithOptions(filterOptions.data)}
+ filterState={userFilterState}
+ setFilterState={setUserFilterState}
+ />
<DataTable
columns={columns}
data={
@@ -189,7 +146,6 @@ export default function ScoresTable({
data: scores.data?.map((t) => convertToTableRow(t)),
}
}
- options={{ isLoading: true, isError: false }}
pagination={{
pageCount: Math.ceil(totalCount / paginationState.pageSize),
onChange: setPaginationState,
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index 93b7c9eeea..d7cd3742fd 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -2,21 +2,21 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import TableLink from "@/src/components/table/table-link";
-import { type TableRowOptions } from "@/src/components/table/types";
import { TokenUsageBadge } from "@/src/components/token-usage-badge";
+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { tracesTableColsWithOptions } from "@/src/server/api/definitions/tracesTable";
import { api } from "@/src/utils/api";
import { lastCharacters } from "@/src/utils/string";
-import {
- type SelectedScoreFilter,
- type ScoreFilter,
- type KeyValue,
-} from "@/src/utils/tanstack";
import { type RouterInput, type RouterOutput } from "@/src/utils/types";
import { type Score } from "@prisma/client";
import { type ColumnDef } from "@tanstack/react-table";
-import router from "next/router";
-import { useState } from "react";
-import { NumberParam, useQueryParams, withDefault } from "use-query-params";
+import {
+ NumberParam,
+ StringParam,
+ useQueryParam,
+ useQueryParams,
+ withDefault,
+} from "use-query-params";
export type TraceTableRow = {
id: string;
@@ -46,33 +46,22 @@ export default function TracesTable({
userId,
omittedFilter = [],
}: TraceTableProps) {
- const filters = router.query.filter
- ? (JSON.parse(
- decodeURIComponent(router.query.filter as string),
- ) as TraceFilterInput)
- : {
- scores: null,
- name: null,
- userId: userId ? [userId] : null,
- searchQuery: null,
- metadata: null,
- };
-
- const [queryOptions, setQuery] = useState<TraceFilterInput>(filters);
-
- const setQueryOptions = (filter?: TraceFilterInput) => {
- filter ? setQuery(filter) : undefined;
- setFilterInParams(filter);
- setPaginationState({ pageIndex: 0, pageSize: paginationState.pageSize });
- };
-
- const [selectedScore, setSelectedScores] = useState<SelectedScoreFilter>({
- name: null,
- value: null,
- operator: null,
- });
+ const [searchQuery, setSearchQuery] = useQueryParam(
+ "search",
+ withDefault(StringParam, null),
+ );
- const [selectedMetadata, setSelectedMetadata] = useState<KeyValue[]>([]);
+ const [userFilterState, setUserFilterState] = useQueryFilterState([]);
+ const filterState = userId
+ ? userFilterState.concat([
+ {
+ column: "userId",
+ type: "string",
+ operator: "=",
+ value: userId,
+ },
+ ])
+ : userFilterState;
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
@@ -80,32 +69,18 @@ export default function TracesTable({
});
const traces = api.traces.all.useQuery({
- ...queryOptions,
page: paginationState.pageIndex,
limit: paginationState.pageSize,
projectId,
+ filter: filterState,
+ searchQuery,
});
const totalCount = traces.data?.slice(1)[0]?.totalCount ?? 0;
- const options = api.traces.availableFilterOptions.useQuery({
- ...queryOptions,
- projectId: projectId,
+ const traceFilterOptions = api.traces.filterOptions.useQuery({
+ projectId,
});
- const setFilterInParams = (filter?: TraceFilterInput) => {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { ...query } = router.query;
- void router.push({
- pathname: router.pathname,
- query: {
- ...query,
- ...(filter
- ? { filter: encodeURIComponent(JSON.stringify(filter)) }
- : {}),
- },
- });
- };
-
const convertToTableRow = (
trace: RouterOutput["traces"]["all"][0],
): TraceTableRow => {
@@ -125,19 +100,6 @@ export default function TracesTable({
};
};
- const convertToOptions = (
- options: RouterOutput["traces"]["availableFilterOptions"],
- ): TableRowOptions[] => {
- return options.map((o) => {
- return {
- columnId: o.key,
- options: o.occurrences.map((o) => {
- return { label: o.key, value: o.count._all };
- }),
- };
- });
- };
-
const columns: ColumnDef<TraceTableRow>[] = [
{
accessorKey: "id",
@@ -169,35 +131,11 @@ export default function TracesTable({
{
accessorKey: "name",
header: "Name",
- enableColumnFilter: !omittedFilter.find((f) => f === "name"),
- meta: {
- label: "Name",
- filter: {
- type: "select",
- values: queryOptions.name,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, name: newValues });
- },
- },
- },
},
{
accessorKey: "userId",
enableColumnFilter: !omittedFilter.find((f) => f === "userId"),
header: "User ID",
- meta: {
- label: "userId",
- filter: {
- type: "select",
- values: queryOptions.userId,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({
- ...queryOptions,
- userId: newValues,
- });
- },
- },
- },
cell: ({ row }) => {
const value = row.getValue("userId");
return value && typeof value === "string" ? (
@@ -232,21 +170,6 @@ export default function TracesTable({
accessorKey: "scores",
header: "Scores",
enableColumnFilter: !omittedFilter.find((f) => f === "scores"),
- meta: {
- label: "Scores",
- filter: {
- type: "number-comparison",
- values: queryOptions.scores,
- selectedValues: selectedScore,
- updateSelectedScores: setSelectedScores,
- updateFunction: (newValues: ScoreFilter | null) => {
- setQueryOptions({
- ...queryOptions,
- scores: newValues,
- });
- },
- },
- },
cell: ({ row }) => {
const values: Score[] = row.getValue("scores");
return <GroupedScoreBadges scores={values} variant="headings" />;
@@ -255,39 +178,6 @@ export default function TracesTable({
{
accessorKey: "metadata",
header: "Metadata",
- enableColumnFilter: !omittedFilter.find((f) => f === "metadata"),
- meta: {
- label: "Metadata",
- filter: {
- type: "key-value",
- values: queryOptions.metadata,
- removeSelectedValue: (value: KeyValue) => {
- const newValues = selectedMetadata.filter(
- (v) => v.key !== value.key && v.value !== value.value,
- );
- setQueryOptions({
- ...queryOptions,
- metadata: newValues,
- });
- setSelectedMetadata(newValues);
- },
- updateFunction: (newValue: KeyValue | null) => {
- const mergedValues = newValue
- ? selectedMetadata.filter(
- (v) => v.key === newValue.key && v.value === newValue.value,
- ).length > 0
- ? selectedMetadata
- : selectedMetadata.concat(newValue)
- : [];
- console.log("mergedValues", mergedValues);
- setQueryOptions({
- ...queryOptions,
- metadata: mergedValues,
- });
- setSelectedMetadata(mergedValues);
- },
- },
- },
cell: ({ row }) => {
const values: string = row.getValue("metadata");
return <div className="flex flex-wrap gap-x-3 gap-y-1">{values}</div>;
@@ -295,63 +185,20 @@ export default function TracesTable({
},
];
- const tableOptions = options.isLoading
- ? { isLoading: true, isError: false }
- : options.isError
- ? {
- isLoading: false,
- isError: true,
- error: options.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: convertToOptions(options.data),
- };
-
- const isFiltered = () => {
- return (
- Object.entries(queryOptions).filter(
- ([k, v]) => v !== null && !omittedFilter.find((f) => f === k),
- ).length > 0
- );
- };
-
- const resetFilters = () => {
- setQueryOptions({
- scores: null,
- name: null,
- userId: null,
- searchQuery: null,
- metadata: null,
- });
- setSelectedScores({
- name: null,
- value: null,
- operator: null,
- });
- setSelectedMetadata([]);
- };
-
- const updateSearchQuery = (searchQuery: string) => {
- setQueryOptions({ ...queryOptions, searchQuery });
- };
-
return (
<div>
- {tableOptions.data ? (
- <DataTableToolbar
- columnDefs={columns}
- options={tableOptions.data}
- searchConfig={{
- placeholder: "Search by id, name, user id",
- updateQuery: updateSearchQuery,
- currentQuery: queryOptions.searchQuery ?? undefined,
- }}
- resetFilters={resetFilters}
- isFiltered={isFiltered}
- />
- ) : undefined}
+ <DataTableToolbar
+ filterColumnDefinition={tracesTableColsWithOptions(
+ traceFilterOptions.data,
+ )}
+ searchConfig={{
+ placeholder: "Search by id, name, user id",
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ }}
+ filterState={userFilterState}
+ setFilterState={setUserFilterState}
+ />
<DataTable
columns={columns}
data={
@@ -369,7 +216,6 @@ export default function TracesTable({
data: traces.data?.map((t) => convertToTableRow(t)),
}
}
- options={tableOptions}
pagination={{
pageCount: Math.ceil(totalCount / paginationState.pageSize),
onChange: setPaginationState,
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index f4b30057bb..052f8f7dfc 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -26,6 +26,7 @@ const buttonVariants = cva(
xs: "h-7 px-2 rounded-sm",
sm: "h-9 px-3 rounded-md",
lg: "h-11 px-8 rounded-md",
+ icon: "h-9 w-9",
},
},
defaultVariants: {
diff --git a/src/components/ui/calendar.tsx b/src/components/ui/calendar.tsx
new file mode 100644
index 0000000000..d5d6c1bb5e
--- /dev/null
+++ b/src/components/ui/calendar.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import * as React from "react";
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import { DayPicker } from "react-day-picker";
+
+import { cn } from "@/src/utils/tailwind";
+import { buttonVariants } from "@/src/components/ui/button";
+
+export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ ...props
+}: CalendarProps) {
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn("p-3", className)}
+ classNames={{
+ months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
+ month: "space-y-4",
+ caption: "flex justify-center pt-1 relative items-center",
+ caption_label: "text-sm font-medium",
+ nav: "space-x-1 flex items-center",
+ nav_button: cn(
+ buttonVariants({ variant: "outline" }),
+ "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
+ ),
+ nav_button_previous: "absolute left-1",
+ nav_button_next: "absolute right-1",
+ table: "w-full border-collapse space-y-1",
+ head_row: "flex",
+ head_cell:
+ "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
+ row: "flex w-full mt-2",
+ cell: "text-center text-sm p-0 relative [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
+ day: cn(
+ buttonVariants({ variant: "ghost" }),
+ "h-9 w-9 p-0 font-normal aria-selected:opacity-100",
+ ),
+ day_selected:
+ "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
+ day_today: "bg-accent text-accent-foreground",
+ day_outside: "text-muted-foreground opacity-50",
+ day_disabled: "text-muted-foreground opacity-50",
+ day_range_middle:
+ "aria-selected:bg-accent aria-selected:text-accent-foreground",
+ day_hidden: "invisible",
+ ...classNames,
+ }}
+ components={{
+ IconLeft: () => <ChevronLeft className="h-4 w-4" />,
+ IconRight: () => <ChevronRight className="h-4 w-4" />,
+ }}
+ {...props}
+ />
+ );
+}
+Calendar.displayName = "Calendar";
+
+export { Calendar };
diff --git a/src/features/dashboard/components/BaseTimeSeriesChart.tsx b/src/features/dashboard/components/BaseTimeSeriesChart.tsx
index a127a288f3..538adcd607 100644
--- a/src/features/dashboard/components/BaseTimeSeriesChart.tsx
+++ b/src/features/dashboard/components/BaseTimeSeriesChart.tsx
@@ -4,17 +4,20 @@ import { AreaChart } from "@tremor/react";
export function BaseTimeSeriesChart(props: {
agg: DateTimeAggregationOption;
- data: { ts: number; values: { label: string; value: number }[] }[];
+ data: { ts: number; values: { label: string; value?: number }[] }[];
+ showLegend?: boolean;
connectNulls?: boolean;
}) {
const labels = new Set(
props.data.flatMap((d) => d.values.map((v) => v.label)),
);
- type ChartInput = { timestamp: string } & { [key: string]: number };
+ type ChartInput = { timestamp: string } & {
+ [key: string]: number | undefined;
+ };
function transformArray(
- array: { ts: number; values: { label: string; value: number }[] }[],
+ array: { ts: number; values: { label: string; value?: number }[] }[],
): ChartInput[] {
return array.map((item) => {
const outputObject: ChartInput = {
@@ -39,14 +42,12 @@ export function BaseTimeSeriesChart(props: {
minute: "2-digit",
});
}
-
return new Date(date).toLocaleDateString("en-US", {
year: "2-digit",
month: "numeric",
day: "numeric",
});
};
-
return (
<AreaChart
className="mt-4 h-72"
@@ -56,7 +57,8 @@ export function BaseTimeSeriesChart(props: {
connectNulls={props.connectNulls}
colors={["indigo", "cyan"]}
valueFormatter={numberFormatter}
- noDataText="Loading ..."
+ noDataText="No data"
+ showLegend={props.showLegend}
/>
);
}
diff --git a/src/features/dashboard/components/EventsCard.tsx b/src/features/dashboard/components/EventsCard.tsx
new file mode 100644
index 0000000000..a00c73d2a2
--- /dev/null
+++ b/src/features/dashboard/components/EventsCard.tsx
@@ -0,0 +1,189 @@
+import {
+ Card,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+ CardContent,
+} from "@/src/components/ui/card";
+import { api } from "@/src/utils/api";
+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
+import {
+ dateTimeAggregationSettings,
+ type DateTimeAggregationOption,
+} from "@/src/features/dashboard/lib/timeseries-aggregation";
+import { type FilterState } from "@/src/features/filters/types";
+import { Loader } from "lucide-react";
+
+export const EventsCard = ({
+ projectId,
+ globalFilterState,
+ agg,
+}: {
+ projectId: string;
+ globalFilterState: FilterState;
+ agg: DateTimeAggregationOption;
+}) => {
+ const observations = api.dashboard.chart.useQuery({
+ projectId,
+ from: "observations",
+ select: [{ column: "observationId", agg: "COUNT" }],
+ filter: globalFilterState ?? [],
+ groupBy: [
+ {
+ type: "datetime",
+ column: "startTime",
+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,
+ },
+ ],
+ orderBy: [],
+ });
+
+ const traces = api.dashboard.chart.useQuery({
+ projectId,
+ from: "traces",
+ select: [{ column: "traceId", agg: "COUNT" }],
+ filter:
+ globalFilterState.map((f) =>
+ f.type === "datetime" ? { ...f, column: "timestamp" } : f,
+ ) ?? [],
+ groupBy: [
+ {
+ type: "datetime",
+ column: "timestamp",
+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,
+ },
+ ],
+ orderBy: [],
+ });
+
+ const scores = api.dashboard.chart.useQuery({
+ projectId,
+ from: "traces_scores",
+ select: [{ column: "scoreId", agg: "COUNT" }],
+ filter:
+ globalFilterState.map((f) =>
+ f.type === "datetime" ? { ...f, column: "timestamp" } : f,
+ ) ?? [],
+ groupBy: [
+ {
+ type: "datetime",
+ column: "timestamp",
+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,
+ },
+ ],
+ orderBy: [],
+ });
+
+ const transformedObservations = observations.data
+ ? observations.data.map((item) => {
+ return {
+ ts: (item.startTime as Date).getTime(),
+ values: [
+ {
+ label: "Observations",
+ value:
+ typeof item.countObservationId === "number"
+ ? item.countObservationId
+ : undefined,
+ },
+ ],
+ };
+ })
+ : [];
+
+ const transformedTraces = traces.data
+ ? traces.data.map((item) => {
+ return {
+ ts: (item.timestamp as Date).getTime(),
+ values: [
+ {
+ label: "Traces",
+ value:
+ typeof item.countTraceId === "number"
+ ? item.countTraceId
+ : undefined,
+ },
+ ],
+ };
+ })
+ : [];
+
+ const transformedScores = scores.data
+ ? scores.data.map((item) => {
+ return {
+ ts: (item.timestamp as Date).getTime(),
+ values: [
+ {
+ label: "Scores",
+ value:
+ typeof item.countScoreId === "number"
+ ? item.countScoreId
+ : undefined,
+ },
+ ],
+ };
+ })
+ : [];
+
+ return (
+ <div className="grid gap-4 xl:grid-cols-3">
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Number of traces</CardTitle>
+ <CardDescription>Count</CardDescription>
+ {traces.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={transformedTraces ?? []}
+ connectNulls={true}
+ showLegend={false}
+ />
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Number of observations</CardTitle>
+ <CardDescription>Count</CardDescription>
+ {observations.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={transformedObservations ?? []}
+ connectNulls={true}
+ showLegend={false}
+ />
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Number of scores</CardTitle>
+ <CardDescription>Count</CardDescription>
+ {scores.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={transformedScores ?? []}
+ connectNulls={true}
+ showLegend={false}
+ />
+ </CardContent>
+ </Card>
+ </div>
+ );
+};
diff --git a/src/features/dashboard/components/LatencyChart.tsx b/src/features/dashboard/components/LatencyChart.tsx
new file mode 100644
index 0000000000..12e8bf69be
--- /dev/null
+++ b/src/features/dashboard/components/LatencyChart.tsx
@@ -0,0 +1,86 @@
+import {
+ Card,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+ CardContent,
+} from "@/src/components/ui/card";
+import { api } from "@/src/utils/api";
+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
+import {
+ dateTimeAggregationSettings,
+ type DateTimeAggregationOption,
+} from "@/src/features/dashboard/lib/timeseries-aggregation";
+import { type FilterState } from "@/src/features/filters/types";
+import { Loader } from "lucide-react";
+import {
+ getAllModels,
+ reduceData,
+ transformMapAndFillZeroValues,
+} from "@/src/features/dashboard/components/hooks";
+
+export const LatencyChart = ({
+ projectId,
+ globalFilterState,
+ agg,
+}: {
+ projectId: string;
+ globalFilterState: FilterState;
+ agg: DateTimeAggregationOption;
+}) => {
+ const data = api.dashboard.chart.useQuery({
+ projectId,
+ from: "observations",
+ select: [
+ { column: "duration", agg: "AVG" },
+ { column: "model", agg: null },
+ ],
+ filter:
+ [
+ ...globalFilterState,
+ { type: "string", column: "type", operator: "=", value: "GENERATION" },
+ ] ?? [],
+ groupBy: [
+ {
+ type: "datetime",
+ column: "startTime",
+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,
+ },
+ { type: "string", column: "model" },
+ ],
+ orderBy: [],
+ });
+
+ const allModels = getAllModels(projectId, globalFilterState);
+
+ const transformedData =
+ data.data && allModels
+ ? transformMapAndFillZeroValues(
+ reduceData(data.data, "avgDuration"),
+ allModels,
+ )
+ : [];
+
+ return (
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Model latencies</CardTitle>
+ <CardDescription>
+ Average latency (ms) per LLM generation
+ </CardDescription>
+ {data.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={transformedData ?? []}
+ connectNulls={true}
+ />
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/src/features/dashboard/components/ReleaseTable.tsx b/src/features/dashboard/components/ReleaseTable.tsx
new file mode 100644
index 0000000000..19f8c9b977
--- /dev/null
+++ b/src/features/dashboard/components/ReleaseTable.tsx
@@ -0,0 +1,105 @@
+import Header from "@/src/components/layouts/header";
+import {
+ Card,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+ CardContent,
+} from "@/src/components/ui/card";
+import { api } from "@/src/utils/api";
+import { type FilterState } from "@/src/features/filters/types";
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import { Loader } from "lucide-react";
+import { numberFormatter } from "@/src/utils/numbers";
+
+export const ReleaseTable = ({
+ projectId,
+ globalFilterState,
+}: {
+ projectId: string;
+ globalFilterState: FilterState;
+}) => {
+ const data = api.dashboard.chart.useQuery({
+ projectId,
+ from: "traces_parent_observation_scores",
+ select: [
+ { column: "value", agg: "AVG" },
+ { column: "release", agg: null },
+ { column: "value", agg: "COUNT" },
+ { column: "scoreName", agg: null },
+ { column: "duration", agg: "AVG" },
+ ],
+ filter:
+ globalFilterState.map((f) => ({
+ ...f,
+ column: "timestamp",
+ })) ?? [],
+ groupBy: [
+ { type: "string", column: "release" },
+ { type: "string", column: "scoreName" },
+ ],
+ orderBy: [{ column: "release", direction: "DESC" }],
+ });
+
+ return (
+ <div className="md:container">
+ <Header title="Releases" />
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Releases</CardTitle>
+ <CardDescription>Count</CardDescription>
+ {data.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <Table>
+ <TableCaption>A list of your recent releases.</TableCaption>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[100px]">Release</TableHead>
+ <TableHead className="w-[100px]">Score Name</TableHead>
+ <TableHead>Average Score</TableHead>
+ <TableHead>Number of traces</TableHead>
+ <TableHead className="text-right">
+ Average duration (ms)
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {data.data?.map((row) => (
+ <TableRow
+ key={(row.release as string) + "-" + (row.name as string)}
+ >
+ <TableCell className="font-medium">
+ {row.release ? (row.release as string) : "-"}
+ </TableCell>
+ <TableCell className="font-medium">
+ {row.name as string}
+ </TableCell>
+ <TableCell>
+ {numberFormatter(row.avgValue as number)}
+ </TableCell>
+ <TableCell>{row.countValue as number}</TableCell>
+ <TableCell className="text-right">
+ {numberFormatter(row.avgDuration as number)}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ </div>
+ );
+};
diff --git a/src/features/dashboard/components/TokenChart.tsx b/src/features/dashboard/components/TokenChart.tsx
new file mode 100644
index 0000000000..af730e1347
--- /dev/null
+++ b/src/features/dashboard/components/TokenChart.tsx
@@ -0,0 +1,133 @@
+import {
+ Card,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+ CardContent,
+} from "@/src/components/ui/card";
+import { api } from "@/src/utils/api";
+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
+import {
+ dateTimeAggregationSettings,
+ type DateTimeAggregationOption,
+} from "@/src/features/dashboard/lib/timeseries-aggregation";
+import { type FilterState } from "@/src/features/filters/types";
+import { Loader } from "lucide-react";
+import {
+ getAllModels,
+ reduceData,
+ transformMapAndFillZeroValues,
+} from "@/src/features/dashboard/components/hooks";
+
+export const TokenChart = ({
+ projectId,
+ globalFilterState,
+ agg,
+}: {
+ projectId: string;
+ globalFilterState: FilterState;
+ agg: DateTimeAggregationOption;
+}) => {
+ const totalTokens = api.dashboard.chart.useQuery({
+ projectId,
+ from: "observations",
+ select: [
+ { column: "totalTokens", agg: "SUM" },
+ { column: "model", agg: null },
+ ],
+ filter: globalFilterState ?? [],
+ groupBy: [
+ {
+ type: "datetime",
+ column: "startTime",
+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,
+ },
+ {
+ type: "string",
+ column: "model",
+ },
+ ],
+ orderBy: [],
+ });
+
+ const modelCost = api.dashboard.chart.useQuery({
+ projectId,
+ from: "observations",
+ select: [
+ { column: "totalTokenCost", agg: null },
+ { column: "model", agg: null },
+ ],
+ filter: globalFilterState ?? [],
+ groupBy: [
+ {
+ type: "datetime",
+ column: "startTime",
+ temporalUnit: dateTimeAggregationSettings[agg].date_trunc,
+ },
+ {
+ type: "string",
+ column: "model",
+ },
+ ],
+ orderBy: [],
+ });
+
+ const allModels = getAllModels(projectId, globalFilterState);
+
+ const transformedTotalTokens =
+ totalTokens.data && allModels
+ ? transformMapAndFillZeroValues(
+ reduceData(totalTokens.data, "sumTotalTokens"),
+ allModels,
+ )
+ : [];
+
+ const transformedModelCost =
+ modelCost.data && allModels
+ ? transformMapAndFillZeroValues(
+ reduceData(modelCost.data, "totalTokenCost"),
+ allModels,
+ )
+ : [];
+
+ return (
+ <div className="grid gap-4 xl:grid-cols-2">
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Number of tokens</CardTitle>
+ <CardDescription>Count</CardDescription>
+ {totalTokens.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={transformedTotalTokens ?? []}
+ connectNulls={true}
+ />
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Model cost</CardTitle>
+ <CardDescription>USD</CardDescription>
+ {totalTokens.isLoading ? (
+ <div className="absolute right-5 top-5 ">
+ <Loader className="h-5 w-5 animate-spin" />
+ </div>
+ ) : null}
+ </CardHeader>
+ <CardContent>
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={transformedModelCost ?? []}
+ connectNulls={true}
+ />
+ </CardContent>
+ </Card>
+ </div>
+ );
+};
diff --git a/src/features/dashboard/components/charts.tsx b/src/features/dashboard/components/charts.tsx
index c799bb72d4..5a2e922308 100644
--- a/src/features/dashboard/components/charts.tsx
+++ b/src/features/dashboard/components/charts.tsx
@@ -9,68 +9,6 @@ import {
import { BaseTimeSeriesChart } from "./BaseTimeSeriesChart";
import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";
import { Loader } from "lucide-react";
-import { useState } from "react";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-
-export function ChartGenerations(props: {
- agg: DateTimeAggregationOption;
- projectId: string;
-}) {
- const data = api.dashboard.generations.useQuery({
- agg: props.agg,
- projectId: props.projectId,
- });
-
- return (
- <Card>
- <CardHeader className="relative">
- <CardTitle>Generations</CardTitle>
- <CardDescription>Count</CardDescription>
- {data.isLoading ? (
- <div className="absolute right-5 top-5 ">
- <Loader className="h-5 w-5 animate-spin" />
- </div>
- ) : null}
- </CardHeader>
- <CardContent>
- <BaseTimeSeriesChart agg={props.agg} data={data.data ?? []} />
- </CardContent>
- </Card>
- );
-}
-
-export function ChartTraces(props: {
- agg: DateTimeAggregationOption;
- projectId: string;
-}) {
- const data = api.dashboard.traces.useQuery({
- agg: props.agg,
- projectId: props.projectId,
- });
-
- return (
- <Card>
- <CardHeader className="relative">
- <CardTitle>Traces</CardTitle>
- <CardDescription>Count</CardDescription>
- {data.isLoading ? (
- <div className="absolute right-5 top-5 ">
- <Loader className="h-5 w-5 animate-spin" />
- </div>
- ) : null}
- </CardHeader>
- <CardContent>
- <BaseTimeSeriesChart agg={props.agg} data={data.data ?? []} />
- </CardContent>
- </Card>
- );
-}
export function ChartScores(props: {
agg: DateTimeAggregationOption;
@@ -102,82 +40,3 @@ export function ChartScores(props: {
</Card>
);
}
-
-const metricOptions = [
- { label: "Total Tokens", value: "totalTokens" },
- { label: "Prompt Tokens", value: "promptTokens" },
- { label: "Completion Tokens", value: "completionTokens" },
-] as const;
-
-export function ChartUsage(props: {
- agg: DateTimeAggregationOption;
- projectId: string;
-}) {
- const data = api.dashboard.tokenUsage.useQuery({
- agg: props.agg,
- projectId: props.projectId,
- });
-
- const [metric, setMetric] =
- useState<(typeof metricOptions)[number]["value"]>("totalTokens");
-
- // Typesafe selection of metric
- const filteredData =
- (metric === "totalTokens"
- ? data.data?.map((row) => ({
- ts: row.ts,
- values: row.totalTokens,
- }))
- : metric === "promptTokens"
- ? data.data?.map((row) => ({
- ts: row.ts,
- values: row.promptTokens,
- }))
- : data.data?.map((row) => ({
- ts: row.ts,
- values: row.completionTokens,
- }))) ?? [];
-
- return (
- <Card>
- <CardHeader className="relative">
- <CardTitle>Token Usage</CardTitle>
- <CardDescription></CardDescription>
- <div className="absolute right-5 top-5 ">
- {data.isLoading ? (
- <Loader className="h-5 w-5 animate-spin" />
- ) : (
- <Select
- onValueChange={(value) => setMetric(value as typeof metric)}
- value={metric}
- >
- <SelectTrigger className="w-[180px]">
- <SelectValue placeholder="Metric" />
- </SelectTrigger>
- <SelectContent>
- {metricOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- </div>
- </CardHeader>
- <CardContent>
- <BaseTimeSeriesChart
- agg={props.agg}
- data={
- filteredData.map((row) => ({
- ts: row.ts,
- values: Object.entries(row.values ?? []).map(
- ([label, value]) => ({ label, value }),
- ),
- })) ?? []
- }
- />
- </CardContent>
- </Card>
- );
-}
diff --git a/src/features/dashboard/components/hooks.ts b/src/features/dashboard/components/hooks.ts
new file mode 100644
index 0000000000..b3998bb5e2
--- /dev/null
+++ b/src/features/dashboard/components/hooks.ts
@@ -0,0 +1,88 @@
+import { type FilterState } from "@/src/features/filters/types";
+import { type DatabaseRow } from "@/src/server/api/services/query-builder";
+import { api } from "@/src/utils/api";
+
+export const getAllModels = (
+ projectId: string,
+ globalFilterState: FilterState,
+) => {
+ const allModels = api.dashboard.chart.useQuery({
+ projectId,
+ from: "observations",
+ select: [{ column: "model", agg: null }],
+ filter:
+ [
+ ...globalFilterState,
+ { type: "string", column: "type", operator: "=", value: "GENERATION" },
+ ] ?? [],
+ groupBy: [{ type: "string", column: "model" }],
+ orderBy: [],
+ });
+
+ return allModels.data ? extractAllModels(allModels.data) : [];
+};
+
+const extractAllModels = (data: DatabaseRow[]): string[] => {
+ return data.map((item) => item.model as string);
+};
+
+type Field = string;
+
+type ChartData = {
+ model: string;
+ value?: number;
+};
+
+type Result = {
+ ts: number;
+ values: { label: string; value?: number }[];
+};
+export function reduceData(
+ data: DatabaseRow[],
+ field: Field,
+): Map<number, ChartData[]> {
+ return data.reduce((acc: Map<number, ChartData[]>, curr: DatabaseRow) => {
+ const date = new Date(curr.startTime as Date).getTime();
+
+ const reducedData: ChartData | undefined = curr.model
+ ? {
+ model: curr.model as string,
+ value: typeof curr[field] === "number" ? (curr[field] as number) : 0,
+ }
+ : undefined;
+
+ if (acc.has(date)) {
+ reducedData ? acc.get(date)!.push(reducedData) : null;
+ } else {
+ acc.set(date, reducedData ? [reducedData] : []);
+ }
+
+ return acc;
+ }, new Map<number, ChartData[]>());
+}
+
+export function transformMapAndFillZeroValues(
+ map: Map<number, ChartData[]>,
+ allModels: string[],
+): Result[] {
+ const result: Result[] = [];
+
+ for (const [date, items] of map) {
+ const values = items.map((item) => ({
+ label: item.model,
+ value: item.value,
+ }));
+
+ for (const model of allModels) {
+ if (!values.find((value) => value.label === model)) {
+ values.push({ label: model, value: 0 });
+ }
+ }
+ result.push({
+ ts: date,
+ values: values,
+ });
+ }
+
+ return result;
+}
diff --git a/src/features/dashboard/lib/timeseries-aggregation.ts b/src/features/dashboard/lib/timeseries-aggregation.ts
index 4a61cda027..c51d6223e0 100644
--- a/src/features/dashboard/lib/timeseries-aggregation.ts
+++ b/src/features/dashboard/lib/timeseries-aggregation.ts
@@ -13,7 +13,7 @@ export type DateTimeAggregationOption =
export const dateTimeAggregationSettings: Record<
DateTimeAggregationOption,
{
- date_trunc: string;
+ date_trunc: "year" | "month" | "week" | "day" | "hour" | "minute";
date_formatter: (date: Date) => string;
}
> = {
diff --git a/src/features/dashboard/server/dashboard-router.ts b/src/features/dashboard/server/dashboard-router.ts
index f17493f6e1..cdab057223 100644
--- a/src/features/dashboard/server/dashboard-router.ts
+++ b/src/features/dashboard/server/dashboard-router.ts
@@ -8,132 +8,16 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
+import { executeQuery } from "@/src/server/api/services/query-builder";
+import { sqlInterface } from "@/src/server/api/services/sqlInterface";
export const dashboardRouter = createTRPCRouter({
- generations: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- agg: z.enum(dateTimeAggregationOptions),
- }),
- )
+ chart: protectedProjectProcedure
+ .input(sqlInterface.extend({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- // queryRawUnsafe to add input.agg to the WHERE clause
- const output = await ctx.prisma.$queryRawUnsafe<
- {
- date_trunc: Date;
- value: number;
- }[]
- >(`
- WITH timeseries AS (
- SELECT
- date_trunc('${
- dateTimeAggregationSettings[input.agg].date_trunc
- }', dt) as date_trunc,
- 0 as value
- FROM generate_series(
- NOW() - INTERVAL '${input.agg}', NOW(), INTERVAL '1 minute'
- ) as dt
- WHERE dt > NOW() - INTERVAL '${input.agg}'
- GROUP BY 1
- ),
- metrics AS (
- SELECT
- date_trunc('${
- dateTimeAggregationSettings[input.agg].date_trunc
- }', start_time) as date_trunc,
- count(*)::integer as value
- FROM observations
- LEFT JOIN traces ON observations.trace_id = traces.id
-
- WHERE
- type = 'GENERATION'
- AND start_time > NOW() - INTERVAL '${input.agg}'
- AND traces.project_id = '${input.projectId}'
- AND observations.project_id = '${input.projectId}'
-
- GROUP BY 1
- )
-
- SELECT
- timeseries.date_trunc,
- COALESCE(sum(metrics.value), 0)::integer as value
- FROM timeseries
- LEFT JOIN metrics ON timeseries.date_trunc = metrics.date_trunc
- GROUP BY 1
- ORDER BY 1
- `);
-
- return output.map((row) => ({
- ...row,
- values: [
- {
- label: "count",
- value: row.value,
- },
- ],
- ts: row.date_trunc.getTime(),
- }));
+ return await executeQuery(ctx.prisma, input.projectId, input);
}),
- traces: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- agg: z.enum(dateTimeAggregationOptions),
- }),
- )
- .query(async ({ input, ctx }) => {
- // queryRawUnsafe to add input.agg to the WHERE clause
- const output = await ctx.prisma.$queryRawUnsafe<
- {
- date_trunc: Date;
- value: number;
- }[]
- >(`
- WITH timeseries AS (
- SELECT
- date_trunc('${
- dateTimeAggregationSettings[input.agg].date_trunc
- }', dt) as date_trunc,
- 0 as value
- FROM generate_series(
- NOW() - INTERVAL '${input.agg}', NOW(), INTERVAL '1 minute'
- ) as dt
- WHERE dt > NOW() - INTERVAL '${input.agg}'
- GROUP BY 1
- ),
- metrics AS (
- SELECT
- date_trunc('${
- dateTimeAggregationSettings[input.agg].date_trunc
- }', timestamp) as date_trunc,
- count(*)::integer as value
- FROM traces
- WHERE timestamp > NOW() - INTERVAL '${input.agg}'
- AND traces.project_id = '${input.projectId}'
- GROUP BY 1
- )
-
- SELECT
- timeseries.date_trunc,
- COALESCE(sum(metrics.value), 0)::integer as value
- FROM timeseries
- LEFT JOIN metrics ON timeseries.date_trunc = metrics.date_trunc
- GROUP BY 1
- ORDER BY 1
- `);
- return output.map((row) => ({
- ...row,
- values: [
- {
- label: "count",
- value: row.value,
- },
- ],
- ts: row.date_trunc.getTime(),
- }));
- }),
scores: protectedProjectProcedure
.input(
z.object({
@@ -201,70 +85,4 @@ export const dashboardRouter = createTRPCRouter({
ts: row.date_trunc.getTime(),
}));
}),
- tokenUsage: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- agg: z.enum(dateTimeAggregationOptions),
- }),
- )
- .query(async ({ input, ctx }) => {
- const output = await ctx.prisma.$queryRawUnsafe<
- {
- date: Date;
- promptTokens: { [model: string]: number } | null;
- completionTokens: { [model: string]: number } | null;
- totalTokens: { [model: string]: number } | null;
- }[]
- >(`
- WITH timeseries AS (
- SELECT
- date_trunc('${
- dateTimeAggregationSettings[input.agg].date_trunc
- }', dt) as date_trunc
- FROM generate_series(
- NOW() - INTERVAL '${input.agg}', NOW(), INTERVAL '1 minute'
- ) as dt
- WHERE dt > NOW() - INTERVAL '${input.agg}'
- GROUP BY 1
- ),
- token_usage AS (
- SELECT
- date_trunc('${
- dateTimeAggregationSettings[input.agg].date_trunc
- }', start_time) as date_trunc,
- COALESCE(model, 'undefined') model,
- sum(prompt_tokens) prompt_tokens,
- sum(completion_tokens) completion_tokens,
- sum(total_tokens) total_tokens
- from observations
- WHERE start_time > NOW() - INTERVAL '${input.agg}'
- AND project_id = '${input.projectId}'
- GROUP BY 1,2
- HAVING sum(prompt_tokens) > 0 OR sum(completion_tokens) > 0 or sum(total_tokens) > 0
- ORDER BY 1,2
- ),
- json_metrics as (
- SELECT
- date_trunc,
- jsonb_object_agg(model, prompt_tokens) as prompt_tokens,
- jsonb_object_agg(model, completion_tokens) as completion_tokens,
- jsonb_object_agg(model, total_tokens) as total_tokens
- from token_usage
- GROUP BY 1
- )
- SELECT
- timeseries.date_trunc as "date",
- prompt_tokens "promptTokens",
- completion_tokens "completionTokens",
- total_tokens "totalTokens"
- FROM timeseries
- LEFT JOIN json_metrics ON timeseries.date_trunc = json_metrics.date_trunc
- `);
-
- return output.map((row) => ({
- ...row,
- ts: row.date.getTime(),
- }));
- }),
});
diff --git a/src/features/datasets/components/DatasetItemsTable.tsx b/src/features/datasets/components/DatasetItemsTable.tsx
index 13d61d1ae4..ae42ce65cc 100644
--- a/src/features/datasets/components/DatasetItemsTable.tsx
+++ b/src/features/datasets/components/DatasetItemsTable.tsx
@@ -160,7 +160,6 @@ export function DatasetItemsTable({
data: items.data?.map((t) => convertToTableRow(t)),
}
}
- options={{ isLoading: true, isError: false }}
/>
<NewDatasetItemButton
projectId={projectId}
diff --git a/src/features/datasets/components/DatasetRunItemsTable.tsx b/src/features/datasets/components/DatasetRunItemsTable.tsx
index 155f99293e..921ce91c41 100644
--- a/src/features/datasets/components/DatasetRunItemsTable.tsx
+++ b/src/features/datasets/components/DatasetRunItemsTable.tsx
@@ -107,7 +107,6 @@ export function DatasetRunItemsTable(
data: runItems.data?.map((t) => convertToTableRow(t)),
}
}
- options={{ isLoading: true, isError: false }}
/>
);
}
diff --git a/src/features/datasets/components/DatasetRunsTable.tsx b/src/features/datasets/components/DatasetRunsTable.tsx
index c415e1d602..ac232318fe 100644
--- a/src/features/datasets/components/DatasetRunsTable.tsx
+++ b/src/features/datasets/components/DatasetRunsTable.tsx
@@ -52,7 +52,6 @@ export function DatasetRunsTable(props: {
header: "Scores (avg)",
cell: ({ row }) => {
const scores: RowData["scores"] = row.getValue("scores");
- console.log(scores);
return (
<GroupedScoreBadges
scores={Object.entries(scores).map(([k, v]) => ({
@@ -95,7 +94,6 @@ export function DatasetRunsTable(props: {
data: runs.data?.map((t) => convertToTableRow(t)),
}
}
- options={{ isLoading: true, isError: false }}
/>
);
}
diff --git a/src/features/datasets/components/DatasetsTable.tsx b/src/features/datasets/components/DatasetsTable.tsx
index a4c6fabce1..23bde3b873 100644
--- a/src/features/datasets/components/DatasetsTable.tsx
+++ b/src/features/datasets/components/DatasetsTable.tsx
@@ -157,7 +157,6 @@ export function DatasetsTable(props: { projectId: string }) {
data: datasets.data?.map((t) => convertToTableRow(t)),
}
}
- options={{ isLoading: true, isError: false }}
/>
<NewDatasetButton projectId={props.projectId} className="mt-4" />
</div>
diff --git a/src/features/filters/components/filter-builder.tsx b/src/features/filters/components/filter-builder.tsx
new file mode 100644
index 0000000000..880154e65c
--- /dev/null
+++ b/src/features/filters/components/filter-builder.tsx
@@ -0,0 +1,368 @@
+import { Button } from "@/src/components/ui/button";
+import { Input } from "@/src/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { DatePicker } from "@/src/components/date-picker";
+import { useState, type Dispatch, type SetStateAction } from "react";
+import { Filter, Plus, X } from "lucide-react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { MultiSelect } from "@/src/features/filters/components/multi-select";
+import {
+ type WipFilterState,
+ type FilterState,
+ type WipFilterCondition,
+} from "@/src/features/filters/types";
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
+import {
+ filterOperators,
+ singleFilter,
+} from "@/src/server/api/interfaces/filters";
+
+// Has WipFilterState, passes all valid filters to parent onChange
+export function FilterBuilder({
+ columns,
+ filterState,
+ onChange,
+}: {
+ columns: ColumnDefinition[];
+ filterState: FilterState;
+ onChange: Dispatch<SetStateAction<FilterState>>;
+}) {
+ const [wipFilterState, _setWipFilterState] =
+ useState<WipFilterState>(filterState);
+
+ const addNewFilter = () => {
+ setWipFilterState((prev) => [
+ ...prev,
+ {
+ column: undefined,
+ type: undefined,
+ operator: undefined,
+ value: undefined,
+ key: undefined,
+ },
+ ]);
+ };
+
+ const setWipFilterState = (
+ state: ((prev: WipFilterState) => WipFilterState) | WipFilterState,
+ ) => {
+ _setWipFilterState((prev) => {
+ const newState = state instanceof Function ? state(prev) : state;
+ onChange(
+ newState.filter(
+ (f) => singleFilter.safeParse(f).success,
+ ) as FilterState,
+ );
+ return newState;
+ });
+ };
+
+ return (
+ <div className="flex items-center">
+ <Popover
+ onOpenChange={(open) => {
+ // Create empty filter when opening popover
+ if (open && filterState.length === 0) addNewFilter();
+ // Discard all wip filters when closing popover
+ if (!open) setWipFilterState(filterState);
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button variant="outline">
+ <Filter className="mr-3 h-4 w-4" />
+ <span>Filter</span>
+ {filterState.length > 0
+ ? filterState.map((filter, i) => {
+ return (
+ <span
+ key={i}
+ className="ml-3 whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs"
+ >
+ {filter.column}
+ {filter.type === "stringObject" ||
+ filter.type === "numberObject"
+ ? `.${filter.key}`
+ : ""}{" "}
+ {filter.operator}{" "}
+ {filter.type === "datetime"
+ ? new Date(filter.value).toLocaleDateString()
+ : filter.type === "stringOptions"
+ ? filter.value.join(", ")
+ : filter.type === "number" ||
+ filter.type === "numberObject"
+ ? filter.value
+ : `"${filter.value}"`}
+ </span>
+ );
+ })
+ : null}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-fit max-w-[90vw] overflow-x-auto"
+ align="start"
+ >
+ <FilterBuilderForm
+ columns={columns}
+ filterState={wipFilterState}
+ onChange={setWipFilterState}
+ />
+ </PopoverContent>
+ </Popover>
+ {filterState.length > 0 ? (
+ <Button
+ onClick={() => setWipFilterState([])}
+ variant="ghost"
+ size="icon"
+ className="ml-2"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
+function FilterBuilderForm({
+ columns,
+ filterState,
+ onChange,
+}: {
+ columns: ColumnDefinition[];
+ filterState: WipFilterState;
+ onChange: Dispatch<SetStateAction<WipFilterState>>;
+}) {
+ const handleFilterChange = (filter: WipFilterCondition, i: number) => {
+ onChange((prev) => {
+ const newState = [...prev];
+ newState[i] = filter;
+ return newState;
+ });
+ };
+
+ const addNewFilter = () => {
+ onChange((prev) => [
+ ...prev,
+ {
+ column: undefined,
+ operator: undefined,
+ value: undefined,
+ type: undefined,
+ key: undefined,
+ },
+ ]);
+ };
+
+ const removeFilter = (i: number) => {
+ onChange((prev) => {
+ const newState = [...prev];
+ newState.splice(i, 1);
+ return newState;
+ });
+ };
+
+ return (
+ <>
+ <table className="table-auto">
+ <tbody>
+ {filterState.map((filter, i) => {
+ const column = columns.find((c) => c.name === filter.column);
+ return (
+ <tr key={i}>
+ <td className="p-1 text-sm">{i === 0 ? "Where" : "And"}</td>
+ <td className="flex gap-2 p-1">
+ <Select
+ value={filter.column ?? ""}
+ onValueChange={(value) =>
+ handleFilterChange(
+ {
+ column: value,
+ type: columns.find((c) => c.name === value)?.type,
+ operator: undefined,
+ value: undefined,
+ key: undefined,
+ },
+ i,
+ )
+ }
+ >
+ <SelectTrigger className="min-w-[100px]">
+ <SelectValue placeholder="Column" />
+ </SelectTrigger>
+ <SelectContent>
+ {columns.map((option) => (
+ <SelectItem key={option.name} value={option.name}>
+ {option.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {filter.type &&
+ (filter.type === "numberObject" ||
+ filter.type === "stringObject") &&
+ (column?.type === "numberObject" ||
+ column?.type === "stringObject") ? (
+ column.keyOptions ? (
+ <Select
+ disabled={!filter.column}
+ onValueChange={(value) => {
+ handleFilterChange({ ...filter, key: value }, i);
+ }}
+ value={filter.key ?? ""}
+ >
+ <SelectTrigger className="min-w-[60px]">
+ <SelectValue placeholder="" />
+ </SelectTrigger>
+ <SelectContent>
+ {column.keyOptions.map((option) => (
+ <SelectItem key={option} value={option}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <Input
+ value={filter.key ?? ""}
+ placeholder="key"
+ onChange={(e) =>
+ handleFilterChange(
+ { ...filter, key: e.target.value },
+ i,
+ )
+ }
+ />
+ )
+ ) : null}
+ </td>
+ <td className="p-1">
+ <Select
+ disabled={!filter.column}
+ onValueChange={(value) => {
+ handleFilterChange(
+ {
+ ...filter,
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
+ operator: value as any,
+ },
+ i,
+ );
+ }}
+ value={filter.operator ?? ""}
+ >
+ <SelectTrigger className="min-w-[60px]">
+ <SelectValue placeholder="" />
+ </SelectTrigger>
+ <SelectContent>
+ {filter.type !== undefined
+ ? filterOperators[filter.type].map((option) => (
+ <SelectItem key={option} value={option}>
+ {option}
+ </SelectItem>
+ ))
+ : null}
+ </SelectContent>
+ </Select>
+ </td>
+ <td className="p-1">
+ {filter.type === "string" ||
+ filter.type === "stringObject" ? (
+ <Input
+ value={filter.value ?? ""}
+ placeholder="string"
+ onChange={(e) =>
+ handleFilterChange(
+ { ...filter, value: e.target.value },
+ i,
+ )
+ }
+ />
+ ) : filter.type === "number" ||
+ filter.type === "numberObject" ? (
+ <Input
+ value={filter.value?.toString() ?? ""}
+ placeholder="number"
+ onChange={(e) =>
+ handleFilterChange(
+ {
+ ...filter,
+ value:
+ isNaN(Number(e.target.value)) ||
+ e.target.value.endsWith(".")
+ ? e.target.value
+ : Number(e.target.value),
+ },
+ i,
+ )
+ }
+ />
+ ) : filter.type === "datetime" ? (
+ <DatePicker
+ className="min-w-[100px]"
+ date={filter.value ? new Date(filter.value) : undefined}
+ onChange={(date) => {
+ handleFilterChange(
+ {
+ ...filter,
+ value: date,
+ },
+ i,
+ );
+ }}
+ />
+ ) : filter.type === "stringOptions" ? (
+ <MultiSelect
+ title="Value"
+ className="min-w-[100px]"
+ options={
+ column?.type === "stringOptions" ? column.options : []
+ }
+ onValueChange={(value) =>
+ handleFilterChange({ ...filter, value }, i)
+ }
+ values={Array.isArray(filter.value) ? filter.value : []}
+ />
+ ) : (
+ <Input disabled />
+ )}
+ </td>
+
+ <td>
+ <Button
+ onClick={() => removeFilter(i)}
+ variant="ghost"
+ size="xs"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ <Button
+ onClick={() => addNewFilter()}
+ className="mt-2"
+ variant="ghost"
+ size="sm"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add filter
+ </Button>
+ {/* <pre>
+ <code>{JSON.stringify(filterState, null, 2)}</code>
+ </pre> */}
+ </>
+ );
+}
diff --git a/src/features/filters/components/multi-select.tsx b/src/features/filters/components/multi-select.tsx
new file mode 100644
index 0000000000..8e2c71df4a
--- /dev/null
+++ b/src/features/filters/components/multi-select.tsx
@@ -0,0 +1,146 @@
+import * as React from "react";
+import { Check, ChevronDown } from "lucide-react";
+
+import { cn } from "@/src/utils/tailwind";
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/src/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { Separator } from "@/src/components/ui/separator";
+import { type FilterOption } from "@/src/features/filters/types";
+
+export function MultiSelect({
+ title,
+ values,
+ onValueChange,
+ options,
+ className,
+}: {
+ title?: string;
+ values: string[];
+ onValueChange: (values: string[]) => void;
+ options: FilterOption[] | readonly FilterOption[];
+ className?: string;
+}) {
+ const selectedValues = new Set(values ?? []);
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className={cn(
+ "flex h-10 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ className,
+ )}
+ >
+ Select
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ {selectedValues?.size > 0 && (
+ <>
+ <Separator orientation="vertical" className="mx-2 h-4" />
+ <Badge
+ variant="secondary"
+ className="rounded-sm px-1 font-normal lg:hidden"
+ >
+ {selectedValues.size}
+ </Badge>
+ <div className="hidden space-x-1 lg:flex">
+ {selectedValues.size > 2 ? (
+ <Badge
+ variant="secondary"
+ className="rounded-sm px-1 font-normal"
+ >
+ {selectedValues.size} selected
+ </Badge>
+ ) : (
+ options
+ .filter((option) => selectedValues.has(option.value))
+ .map((option) => (
+ <Badge
+ variant="secondary"
+ key={option.value}
+ className="rounded-sm px-1 font-normal"
+ >
+ {option.value}
+ </Badge>
+ ))
+ )}
+ </div>
+ </>
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[200px] p-0" align="center">
+ <Command>
+ <CommandInput placeholder={title} />
+ <CommandList>
+ <CommandEmpty>No results found.</CommandEmpty>
+ <CommandGroup>
+ {options.map((option) => {
+ const isSelected = selectedValues.has(option.value);
+ return (
+ <CommandItem
+ key={option.value}
+ onSelect={() => {
+ if (isSelected) {
+ selectedValues.delete(option.value);
+ } else {
+ selectedValues.add(option.value);
+ }
+ const filterValues = Array.from(selectedValues);
+
+ onValueChange(filterValues.length ? filterValues : []);
+ }}
+ >
+ <div
+ className={cn(
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
+ isSelected
+ ? "bg-primary text-primary-foreground"
+ : "opacity-50 [&_svg]:invisible",
+ )}
+ >
+ <Check className={cn("h-4 w-4")} />
+ </div>
+ <span>{option.value}</span>
+ {option.count !== undefined ? (
+ <span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs">
+ {option.count}
+ </span>
+ ) : null}
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ {selectedValues.size > 0 && (
+ <>
+ <CommandSeparator />
+ <CommandGroup>
+ <CommandItem
+ onSelect={() => onValueChange([])}
+ className="justify-center text-center"
+ >
+ Clear filters
+ </CommandItem>
+ </CommandGroup>
+ </>
+ )}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/features/filters/hooks/useFilterState.ts b/src/features/filters/hooks/useFilterState.ts
new file mode 100644
index 0000000000..33a6259c07
--- /dev/null
+++ b/src/features/filters/hooks/useFilterState.ts
@@ -0,0 +1,78 @@
+import { type FilterState } from "@/src/features/filters/types";
+import { singleFilter } from "@/src/server/api/interfaces/filters";
+import { useState } from "react";
+import {
+ useQueryParam,
+ encodeDelimitedArray,
+ decodeDelimitedArray,
+ withDefault,
+} from "use-query-params";
+
+const DEBUG_QUERY_STATE = false;
+
+const CommaArrayParam = {
+ encode: (state: FilterState) =>
+ encodeDelimitedArray(
+ state.map((f) => {
+ const stringified = `${f.column};${f.type};${
+ f.type === "numberObject" || f.type === "stringObject"
+ ? f.key ?? ""
+ : ""
+ };${f.operator};${
+ f.type === "datetime"
+ ? f.value.toISOString()
+ : f.type === "stringOptions"
+ ? f.value.join("|")
+ : f.value
+ }`;
+ if (DEBUG_QUERY_STATE) console.log("stringified", stringified);
+ return stringified;
+ }),
+ ",",
+ ),
+
+ decode: (arrayStr: string | (string | null)[] | null | undefined) =>
+ (decodeDelimitedArray(arrayStr, ",")
+ ?.map((f) => {
+ if (!f) return null;
+ const [column, type, key, operator, value] = f.split(";");
+ if (DEBUG_QUERY_STATE)
+ console.log("values", [column, type, key, operator, value]);
+ const parsedValue =
+ value === undefined || type === undefined
+ ? undefined
+ : type === "datetime"
+ ? new Date(value)
+ : type === "number" || type === "numberObject"
+ ? Number(value)
+ : type === "stringOptions"
+ ? value.split("|")
+ : value;
+ if (DEBUG_QUERY_STATE) console.log("parsedValue", parsedValue);
+ const parsed = singleFilter.safeParse({
+ column,
+ key: key !== "" ? key : undefined,
+ operator,
+ value: parsedValue,
+ type,
+ });
+ if (!parsed.success) return null;
+ return parsed.data;
+ })
+ .filter((v) => v !== null) as FilterState) ?? [],
+};
+
+// manage state with hook
+export const useQueryFilterState = (initialState: FilterState = []) => {
+ const [filterState, setFilterState] = useQueryParam(
+ "filter",
+ withDefault(CommaArrayParam, initialState),
+ );
+
+ return [filterState, setFilterState] as const;
+};
+
+export const useMemoryFilterState = (initialState: FilterState = []) => {
+ const [filterState, setFilterState] = useState(initialState);
+ return [filterState, setFilterState] as const;
+};
diff --git a/src/features/filters/server/filterToPrisma.ts b/src/features/filters/server/filterToPrisma.ts
new file mode 100644
index 0000000000..94fb28ab94
--- /dev/null
+++ b/src/features/filters/server/filterToPrisma.ts
@@ -0,0 +1,76 @@
+import { type FilterState } from "@/src/features/filters/types";
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
+import { Prisma } from "@prisma/client";
+
+const operatorReplacements = {
+ "any of": "IN",
+ "none of": "NOT IN",
+};
+
+export function filterToPrismaSql(
+ filters: FilterState,
+ tableColumns: ColumnDefinition[],
+): Prisma.Sql {
+ const statements = filters.map((filter) => {
+ // Get column definition to map column to internal name, e.g. "t.id"
+ const col = tableColumns.find((c) => c.name === filter.column);
+ if (!col) {
+ console.error("Invalid filter column", filter.column);
+ throw new Error("Invalid filter column: " + filter.column);
+ }
+
+ const colPrisma = Prisma.raw(col.internal);
+ const operatorPrisma =
+ filter.operator in operatorReplacements
+ ? Prisma.raw(
+ operatorReplacements[
+ filter.operator as keyof typeof operatorReplacements
+ ],
+ )
+ : Prisma.raw(filter.operator); //checked by zod
+
+ // Get prisma value
+ let valuePrisma: Prisma.Sql;
+ switch (filter.type) {
+ case "datetime":
+ valuePrisma = Prisma.sql`${
+ filter.value
+ .toISOString()
+ .split(".")[0]! // remove milliseconds
+ .replace("T", " ") // to Postgres datetime
+ }::TIMESTAMP`;
+ break;
+ case "number":
+ case "numberObject":
+ valuePrisma = Prisma.sql`${filter.value}::DOUBLE PRECISION`;
+ break;
+ case "string":
+ case "stringObject":
+ valuePrisma = Prisma.sql`${filter.value}`;
+ break;
+ case "stringOptions":
+ valuePrisma = Prisma.sql`(${Prisma.join(
+ filter.value.map((v) => Prisma.sql`${v}`),
+ )})`;
+ break;
+ }
+ const jsonKeyPrisma =
+ filter.type === "stringObject" || filter.type === "numberObject"
+ ? Prisma.sql`->>${filter.key}`
+ : Prisma.empty;
+ const [cast1, cast2] =
+ filter.type === "numberObject"
+ ? [Prisma.raw("cast("), Prisma.raw(" as double precision)")]
+ : [Prisma.empty, Prisma.empty];
+
+ return Prisma.sql`${cast1}${colPrisma}${jsonKeyPrisma}${cast2} ${operatorPrisma} ${valuePrisma}`;
+ });
+ if (statements.length === 0) {
+ return Prisma.empty;
+ }
+
+ return Prisma.join(
+ [Prisma.raw("AND "), Prisma.join(statements, " AND ")],
+ "",
+ );
+}
diff --git a/src/features/filters/types.ts b/src/features/filters/types.ts
new file mode 100644
index 0000000000..074318b3b4
--- /dev/null
+++ b/src/features/filters/types.ts
@@ -0,0 +1,25 @@
+import { type singleFilter } from "@/src/server/api/interfaces/filters";
+import { type z } from "zod";
+
+// to be sent to the server
+export type FilterCondition = z.infer<typeof singleFilter>;
+export type FilterState = FilterCondition[];
+
+// to be used in the client during editing
+type MakeOptional<T> = {
+ [K in keyof T]?: T[K];
+};
+// if key is value, add string as value
+type AllowStringAsValue<T> = {
+ [K in keyof T]: K extends "value" ? string | T[K] : T[K];
+};
+
+export type WipFilterCondition = AllowStringAsValue<
+ MakeOptional<FilterCondition>
+>;
+export type WipFilterState = WipFilterCondition[];
+
+export type FilterOption = {
+ value: string;
+ count?: number;
+};
diff --git a/src/pages/project/[projectId]/filter.tsx b/src/pages/project/[projectId]/filter.tsx
new file mode 100644
index 0000000000..1b2e128520
--- /dev/null
+++ b/src/pages/project/[projectId]/filter.tsx
@@ -0,0 +1,47 @@
+import { FilterBuilder } from "@/src/features/filters/components/filter-builder";
+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
+
+const cols: ColumnDefinition[] = [
+ {
+ name: "col1",
+ type: "string",
+ internal: "col1",
+ },
+ {
+ name: "col2",
+ type: "number",
+ internal: "col2",
+ },
+ {
+ name: "col3",
+ type: "datetime",
+ internal: "col3",
+ },
+ {
+ name: "col4",
+ type: "stringOptions",
+ internal: "col4",
+ options: ["option1", "option2", "option3"].map((o, i) => ({
+ value: o,
+ count: i,
+ })),
+ },
+];
+
+const FilterPage = () => {
+ const [filterState, setFilterState] = useQueryFilterState([]);
+
+ return (
+ <>
+ <FilterBuilder
+ columns={cols}
+ filterState={filterState}
+ onChange={setFilterState}
+ />
+ <pre>{JSON.stringify(filterState, null, 2)}</pre>
+ </>
+ );
+};
+
+export default FilterPage;
diff --git a/src/pages/project/[projectId]/generations.tsx b/src/pages/project/[projectId]/generations.tsx
index 30cd1bcbf6..932bce843c 100644
--- a/src/pages/project/[projectId]/generations.tsx
+++ b/src/pages/project/[projectId]/generations.tsx
@@ -4,9 +4,7 @@ import { type ColumnDef } from "@tanstack/react-table";
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
-import { type RouterOutput, type RouterInput } from "@/src/utils/types";
import { useState } from "react";
-import { type TableRowOptions } from "@/src/components/table/types";
import { useRouter } from "next/router";
import { TokenUsageBadge } from "@/src/components/token-usage-badge";
import {
@@ -20,12 +18,14 @@ import { ChevronDownIcon, Loader } from "lucide-react";
import { type ExportFileFormats } from "@/src/server/api/routers/generations";
import { usePostHog } from "posthog-js/react";
import {
- DelimitedArrayParam,
NumberParam,
StringParam,
+ useQueryParam,
useQueryParams,
withDefault,
} from "use-query-params";
+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { observationsTableColsWithOptions } from "@/src/server/api/definitions/observationsTable";
type GenerationTableRow = {
id: string;
@@ -42,11 +42,6 @@ type GenerationTableRow = {
};
};
-export type GenerationFilterInput = Omit<
- RouterInput["generations"]["all"],
- "projectId"
->;
-
const exportOptions: Record<
ExportFileFormats,
{
@@ -70,37 +65,28 @@ export default function Generations() {
const projectId = router.query.projectId as string;
const [isExporting, setIsExporting] = useState(false);
- const [rawQueryOptions, setQueryOptions] = useQueryParams({
- traceId: withDefault(DelimitedArrayParam, null),
- name: withDefault(DelimitedArrayParam, null),
- model: withDefault(DelimitedArrayParam, null),
- traceName: withDefault(DelimitedArrayParam, null),
- searchQuery: withDefault(StringParam, ""),
- });
- // Fix typings of useQueryParams
- const queryOptions: GenerationFilterInput & { searchQuery: string } = {
- traceId: rawQueryOptions.traceId as string[] | null,
- name: rawQueryOptions.name as string[] | null,
- model: rawQueryOptions.model as string[] | null,
- traceName: rawQueryOptions.traceName as string[] | null,
- searchQuery: rawQueryOptions.searchQuery,
- };
+ const [searchQuery, setSearchQuery] = useQueryParam(
+ "search",
+ withDefault(StringParam, null),
+ );
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
});
+ const [filterState, setFilterState] = useQueryFilterState([]);
+
const generations = api.generations.all.useQuery({
- ...queryOptions,
page: paginationState.pageIndex,
limit: paginationState.pageSize,
projectId,
+ filter: filterState,
+ searchQuery,
});
const totalCount = generations.data?.slice(1)[0]?.totalCount ?? 0;
- const generationOptions = api.generations.availableFilterOptions.useQuery({
- ...queryOptions,
+ const filterOptions = api.generations.filterOptions.useQuery({
projectId,
});
@@ -110,9 +96,10 @@ export default function Generations() {
setIsExporting(true);
posthog.capture("generations:export", { file_format: fileFormat });
const fileData = await directApi.generations.export.query({
- ...queryOptions,
projectId,
fileFormat,
+ filter: filterState,
+ searchQuery,
});
if (fileData) {
@@ -159,22 +146,10 @@ export default function Generations() {
},
{
accessorKey: "name",
- enableColumnFilter: true,
header: "name",
- meta: {
- label: "Name",
- filter: {
- type: "select",
- values: queryOptions.name,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, name: newValues });
- },
- },
- },
},
{
accessorKey: "traceId",
- enableColumnFilter: true,
header: "Trace ID",
cell: ({ row }) => {
const value = row.getValue("traceId");
@@ -185,31 +160,10 @@ export default function Generations() {
/>
) : undefined;
},
- meta: {
- label: "TraceId",
- filter: {
- type: "select",
- values: queryOptions.traceId,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, traceId: newValues });
- },
- },
- },
},
{
accessorKey: "traceName",
- enableColumnFilter: true,
header: "Trace Name",
- meta: {
- label: "TraceName",
- filter: {
- type: "select",
- values: queryOptions.traceName,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, traceName: newValues });
- },
- },
- },
},
{
accessorKey: "startTime",
@@ -222,17 +176,6 @@ export default function Generations() {
{
accessorKey: "model",
header: "Model",
- enableColumnFilter: true,
- meta: {
- label: "Model",
- filter: {
- type: "select",
- values: queryOptions.model,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, model: newValues });
- },
- },
- },
},
{
accessorKey: "usage",
@@ -255,33 +198,6 @@ export default function Generations() {
},
];
- const convertToOptions = (
- options: RouterOutput["generations"]["availableFilterOptions"],
- ): TableRowOptions[] => {
- return options.map((o) => {
- return {
- columnId: o.key,
- options: o.occurrences.map((o) => {
- return { label: o.key, value: o.count };
- }),
- };
- });
- };
-
- const tableOptions = generationOptions.isLoading
- ? { isLoading: true, isError: false }
- : generationOptions.isError
- ? {
- isLoading: false,
- isError: true,
- error: generationOptions.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: convertToOptions(generationOptions.data),
- };
-
const rows: GenerationTableRow[] = generations.isSuccess
? generations.data.map((generation) => ({
id: generation.id,
@@ -299,65 +215,52 @@ export default function Generations() {
}))
: [];
- const resetFilters = () =>
- setQueryOptions({
- traceId: null,
- name: null,
- model: null,
- traceName: null,
- });
-
- const isFiltered = () =>
- Object.entries(queryOptions).filter(
- ([k, v]) => k !== "searchQuery" && v !== null,
- ).length > 0;
-
return (
<div>
<Header title="Generations" />
- {tableOptions.data ? (
- <DataTableToolbar
- columnDefs={columns}
- options={tableOptions.data}
- resetFilters={resetFilters}
- isFiltered={isFiltered}
- searchConfig={{
- placeholder: "Search by id, name, traceName, model",
- updateQuery: (newQuery) =>
- setQueryOptions({ searchQuery: newQuery }),
- currentQuery: queryOptions.searchQuery,
- }}
- actionButtons={
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- className="ml-auto whitespace-nowrap"
- size="sm"
+ <DataTableToolbar
+ filterColumnDefinition={observationsTableColsWithOptions(
+ filterOptions.data,
+ )}
+ filterState={filterState}
+ setFilterState={setFilterState}
+ searchConfig={{
+ placeholder: "Search by id, name, traceName, model",
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ }}
+ actionButtons={
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ className="ml-auto whitespace-nowrap"
+ size="sm"
+ >
+ {filterState.length > 0 || searchQuery
+ ? "Export selection"
+ : "Export all"}{" "}
+ {isExporting ? (
+ <Loader className="ml-2 h-4 w-4 animate-spin" />
+ ) : (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {Object.entries(exportOptions).map(([key, options]) => (
+ <DropdownMenuItem
+ key={key}
+ className="capitalize"
+ onClick={() => void handleExport(key as ExportFileFormats)}
>
- {isFiltered() ? "Export selection" : "Export all"}{" "}
- {isExporting ? (
- <Loader className="ml-2 h-4 w-4 animate-spin" />
- ) : (
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- )}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {Object.entries(exportOptions).map(([key, options]) => (
- <DropdownMenuItem
- key={key}
- className="capitalize"
- onClick={() => void handleExport(key as ExportFileFormats)}
- >
- as {options.label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- }
- />
- ) : undefined}
+ as {options.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ }
+ />
<DataTable
columns={columns}
data={
@@ -375,7 +278,6 @@ export default function Generations() {
data: rows,
}
}
- options={{ isLoading: true, isError: false }}
pagination={{
pageCount: Math.ceil(totalCount / paginationState.pageSize),
onChange: setPaginationState,
diff --git a/src/pages/project/[projectId]/index.tsx b/src/pages/project/[projectId]/index.tsx
index 3698090ead..0495a9f398 100644
--- a/src/pages/project/[projectId]/index.tsx
+++ b/src/pages/project/[projectId]/index.tsx
@@ -5,20 +5,50 @@ import {
dateTimeAggregationOptions,
type DateTimeAggregationOption,
} from "@/src/features/dashboard/lib/timeseries-aggregation";
-import {
- ChartScores,
- ChartTraces,
- ChartUsage,
-} from "@/src/features/dashboard/components/charts";
import { useRouter } from "next/router";
+import { TokenChart } from "@/src/features/dashboard/components/TokenChart";
+import { LatencyChart } from "@/src/features/dashboard/components/LatencyChart";
+import { ChartScores } from "@/src/features/dashboard/components/charts";
+import { EventsCard } from "@/src/features/dashboard/components/EventsCard";
export default function Start() {
const [agg, setAgg] = useState<DateTimeAggregationOption>("7 days");
const router = useRouter();
const projectId = router.query.projectId as string;
+ const convertAggToDateTime = (agg: DateTimeAggregationOption) => {
+ const [num, unit] = agg.split(" ");
+
+ if (!num || !unit) throw new Error("Invalid agg");
+ const now = new Date();
+ switch (unit) {
+ case "minutes":
+ return new Date(now.getTime() - parseInt(num) * 60 * 1000);
+ case "hours":
+ case "hour":
+ return new Date(now.getTime() - parseInt(num) * 60 * 60 * 1000);
+ case "days":
+ return new Date(now.getTime() - parseInt(num) * 24 * 60 * 60 * 1000);
+ case "weeks":
+ return new Date(
+ now.getTime() - parseInt(num) * 7 * 24 * 60 * 60 * 1000,
+ );
+ case "months":
+ case "month":
+ return new Date(
+ now.getTime() - parseInt(num) * 30 * 24 * 60 * 60 * 1000,
+ );
+ case "year":
+ case "years":
+ return new Date(
+ now.getTime() - parseInt(num) * 365 * 24 * 60 * 60 * 1000,
+ );
+ }
+ throw new Error("Invalid agg");
+ };
+
return (
- <>
+ <div className="md:container">
<Header title="Dashboard" />
<Tabs
value={agg}
@@ -34,13 +64,70 @@ export default function Start() {
</TabsList>
</Tabs>
<div className="grid gap-4 xl:grid-cols-2">
- <ChartTraces agg={agg} projectId={projectId} />
- {/* <ChartGenerations agg={agg} projectId={projectId} /> */}
- <ChartUsage agg={agg} projectId={projectId} />
+ <div className="col-span-2">
+ <EventsCard
+ projectId={projectId}
+ agg={agg}
+ globalFilterState={[
+ {
+ column: "startTime",
+ operator: ">",
+ type: "datetime",
+ value: convertAggToDateTime(agg),
+ },
+ {
+ column: "startTime",
+ operator: "<",
+ type: "datetime",
+ value: new Date(),
+ },
+ ]}
+ />
+ </div>
+ <div className="col-span-2">
+ <TokenChart
+ projectId={projectId}
+ agg={agg}
+ globalFilterState={[
+ {
+ column: "startTime",
+ operator: ">",
+ type: "datetime",
+ value: convertAggToDateTime(agg),
+ },
+ {
+ column: "startTime",
+ operator: "<",
+ type: "datetime",
+ value: new Date(),
+ },
+ ]}
+ />
+ </div>
+ <div className="col-span-2">
+ <LatencyChart
+ projectId={projectId}
+ agg={agg}
+ globalFilterState={[
+ {
+ column: "startTime",
+ operator: ">",
+ type: "datetime",
+ value: convertAggToDateTime(agg),
+ },
+ {
+ column: "startTime",
+ operator: "<",
+ type: "datetime",
+ value: new Date(),
+ },
+ ]}
+ />
+ </div>
<div className="col-span-full">
<ChartScores agg={agg} projectId={projectId} />
</div>
</div>
- </>
+ </div>
);
}
diff --git a/src/pages/project/[projectId]/users.tsx b/src/pages/project/[projectId]/users.tsx
index 54dbd658ae..2cf828b9e2 100644
--- a/src/pages/project/[projectId]/users.tsx
+++ b/src/pages/project/[projectId]/users.tsx
@@ -134,7 +134,6 @@ export default function UsersPage() {
}),
}
}
- options={{ isLoading: true, isError: false }}
pagination={{
pageCount: Math.ceil(totalCount / paginationState.pageSize),
onChange: setPaginationState,
diff --git a/src/server/api/definitions/observationsTable.ts b/src/server/api/definitions/observationsTable.ts
new file mode 100644
index 0000000000..facc63d64c
--- /dev/null
+++ b/src/server/api/definitions/observationsTable.ts
@@ -0,0 +1,68 @@
+import {
+ type OptionsDefinition,
+ type ColumnDefinition,
+} from "@/src/server/api/interfaces/tableDefinition";
+
+// to be used server side
+export const observationsTableCols: ColumnDefinition[] = [
+ {
+ name: "id",
+ type: "string",
+ internal: 'o."id"',
+ },
+ {
+ name: "name",
+ type: "stringOptions",
+ internal: 'o."name"',
+ options: [], // to be added at runtime
+ },
+ { name: "traceId", type: "string", internal: 't."id"' },
+ {
+ name: "traceName",
+ type: "stringOptions",
+ internal: 't."name"',
+ options: [], // to be added at runtime
+ },
+ { name: "userId", type: "string", internal: 't."user_id"' },
+ {
+ name: "start_time",
+ type: "datetime",
+ internal: 'o."start_time"',
+ },
+ {
+ name: "end_time",
+ type: "datetime",
+ internal: 'o."end_time"',
+ },
+ {
+ name: "model",
+ type: "stringOptions",
+ internal: 'o."model"',
+ options: [], // to be added at runtime
+ },
+];
+
+// to be used client side, insert options for use in filter-builder
+// allows for undefined options, to offer filters while options are still loading
+export type ObservationOptions = {
+ model: Array<OptionsDefinition>;
+ name: Array<OptionsDefinition>;
+ traceName: Array<OptionsDefinition>;
+};
+
+export function observationsTableColsWithOptions(
+ options?: ObservationOptions,
+): ColumnDefinition[] {
+ return observationsTableCols.map((col) => {
+ if (col.name === "model") {
+ return { ...col, options: options?.model ?? [] };
+ }
+ if (col.name === "name") {
+ return { ...col, options: options?.name ?? [] };
+ }
+ if (col.name === "traceName") {
+ return { ...col, options: options?.traceName ?? [] };
+ }
+ return col;
+ });
+}
diff --git a/src/server/api/definitions/scoresTable.ts b/src/server/api/definitions/scoresTable.ts
new file mode 100644
index 0000000000..73b80e7ca1
--- /dev/null
+++ b/src/server/api/definitions/scoresTable.ts
@@ -0,0 +1,33 @@
+import {
+ type OptionsDefinition,
+ type ColumnDefinition,
+} from "@/src/server/api/interfaces/tableDefinition";
+
+export const scoresTableCols: ColumnDefinition[] = [
+ { name: "trace_id", type: "string", internal: 's."trace_id"' },
+ { name: "observation_id", type: "string", internal: 's."observation_id"' },
+ { name: "timestamp", type: "datetime", internal: 's."timestamp"' },
+ {
+ name: "name",
+ type: "stringOptions",
+ internal: 's."name"',
+ options: [], // to be added at runtime
+ },
+ { name: "value", type: "number", internal: 's."value"' },
+ { name: "userId", type: "string", internal: 't."user_id"' },
+];
+
+export type ScoreOptions = {
+ name: Array<OptionsDefinition>;
+};
+
+export function scoresTableColsWithOptions(
+ options?: ScoreOptions,
+): ColumnDefinition[] {
+ return scoresTableCols.map((col) => {
+ if (col.name === "name") {
+ return { ...col, options: options?.name ?? [] };
+ }
+ return col;
+ });
+}
diff --git a/src/server/api/definitions/tracesTable.ts b/src/server/api/definitions/tracesTable.ts
new file mode 100644
index 0000000000..e7c43f1f6a
--- /dev/null
+++ b/src/server/api/definitions/tracesTable.ts
@@ -0,0 +1,49 @@
+import {
+ type OptionsDefinition,
+ type ColumnDefinition,
+} from "@/src/server/api/interfaces/tableDefinition";
+
+export const tracesTableCols: ColumnDefinition[] = [
+ { name: "id", type: "string", internal: "t.id" },
+ {
+ name: "name",
+ type: "stringOptions",
+ internal: 't."name"',
+ options: [], // to be filled in at runtime
+ },
+ {
+ name: "timestamp",
+ type: "datetime",
+ internal: 't."timestamp"',
+ },
+ { name: "userId", type: "string", internal: 't."user_id"' },
+ {
+ name: "metadata",
+ type: "stringObject",
+ internal: 't."metadata"',
+ },
+ {
+ name: "scores_avg",
+ type: "numberObject",
+ internal: "scores_avg",
+ },
+];
+
+export type TraceOptions = {
+ scores_avg: Array<string>;
+ name: Array<OptionsDefinition>;
+};
+
+export function tracesTableColsWithOptions(
+ options?: TraceOptions,
+): ColumnDefinition[] {
+ return tracesTableCols.map((col) => {
+ if (col.name === "scores_avg") {
+ return { ...col, keyOptions: options?.scores_avg ?? [] };
+ }
+ if (col.name === "name") {
+ return { ...col, options: options?.name ?? [] };
+ }
+ return col;
+ });
+}
diff --git a/src/server/api/interfaces/filters.ts b/src/server/api/interfaces/filters.ts
new file mode 100644
index 0000000000..454e32ec61
--- /dev/null
+++ b/src/server/api/interfaces/filters.ts
@@ -0,0 +1,58 @@
+import { z } from "zod";
+
+export const filterOperators = {
+ datetime: ["=", ">", "<", ">=", "<="],
+ string: ["="],
+ stringOptions: ["any of", "none of"],
+ number: ["=", ">", "<", ">=", "<="],
+ stringObject: ["="],
+ numberObject: ["=", ">", "<", ">=", "<="],
+} as const;
+
+export const timeFilter = z.object({
+ column: z.string(),
+ operator: z.enum(filterOperators.datetime),
+ value: z.date(),
+ type: z.literal("datetime"),
+});
+export const stringFilter = z.object({
+ column: z.string(),
+ operator: z.enum(filterOperators.string),
+ value: z.string(),
+ type: z.literal("string"),
+});
+export const numberFilter = z.object({
+ column: z.string(),
+ operator: z.enum(filterOperators.number),
+ value: z.number(),
+ type: z.literal("number"),
+});
+export const stringOptionsFilter = z.object({
+ column: z.string(),
+ operator: z.enum(filterOperators.stringOptions),
+ // do not filter on empty arrays, use refine to check this only at runtime (no type checking)
+ value: z.array(z.string()).refine((v) => v.length > 0),
+ type: z.literal("stringOptions"),
+});
+export const stringObjectFilter = z.object({
+ type: z.literal("stringObject"),
+ column: z.string(),
+ key: z.string(), // eg metadata --> "environment"
+ operator: z.enum(filterOperators.string),
+ value: z.string(),
+});
+export const numberObjectFilter = z.object({
+ type: z.literal("numberObject"),
+ column: z.string(),
+ key: z.string(), // eg scores --> "accuracy"
+ operator: z.enum(filterOperators.number),
+ value: z.number(),
+});
+export const singleFilter = z.discriminatedUnion("type", [
+ timeFilter,
+ stringFilter,
+ numberFilter,
+ stringOptionsFilter,
+ stringObjectFilter,
+ numberObjectFilter,
+]);
diff --git a/src/server/api/interfaces/tableDefinition.ts b/src/server/api/interfaces/tableDefinition.ts
new file mode 100644
index 0000000000..0a9f201862
--- /dev/null
+++ b/src/server/api/interfaces/tableDefinition.ts
@@ -0,0 +1,30 @@
+export type OptionsDefinition = {
+ value: string;
+ count?: number;
+};
+
+export type ColumnDefinition =
+ | {
+ name: string;
+ type: "number" | "string" | "datetime";
+ internal: string;
+ }
+ | {
+ name: string;
+ type: "stringOptions";
+ options: Array<OptionsDefinition>;
+ internal: string;
+ }
+ | {
+ name: string;
+ type: "stringObject" | "numberObject";
+ internal: string;
+ keyOptions?: Array<string>;
+ };
+
+export type TableDefinitions = {
+ [tableName: string]: {
+ table: string;
+ columns: ColumnDefinition[];
+ };
+};
diff --git a/src/server/api/routers/generations.ts b/src/server/api/routers/generations.ts
index a240befe7e..eb74031318 100644
--- a/src/server/api/routers/generations.ts
+++ b/src/server/api/routers/generations.ts
@@ -8,63 +8,22 @@ import {
import { type Generation } from "@/src/utils/types";
import { type Observation, Prisma } from "@prisma/client";
import { paginationZod } from "@/src/utils/zod";
+import { singleFilter } from "@/src/server/api/interfaces/filters";
+import { filterToPrismaSql } from "@/src/features/filters/server/filterToPrisma";
+import {
+ type ObservationOptions,
+ observationsTableCols,
+} from "@/src/server/api/definitions/observationsTable";
const exportFileFormats = ["CSV", "JSON", "OPENAI-JSONL"] as const;
export type ExportFileFormats = (typeof exportFileFormats)[number];
const GenerationFilterOptions = z.object({
- traceId: z.array(z.string()).nullable(),
projectId: z.string(), // Required for protectedProjectProcedure
- name: z.array(z.string()).nullable(),
- model: z.array(z.string()).nullable(),
- traceName: z.array(z.string()).nullable(),
+ filter: z.array(singleFilter),
searchQuery: z.string().nullable(),
});
-const generationsFilterPrismaCondition = (
- filter: z.infer<typeof GenerationFilterOptions>,
-) => {
- const traceIdCondition =
- filter.traceId !== null
- ? Prisma.sql`AND o.trace_id IN (${Prisma.join(filter.traceId)})`
- : Prisma.empty;
-
- const nameCondition =
- filter.name !== null
- ? Prisma.sql`AND o.name IN (${Prisma.join(filter.name)})`
- : Prisma.empty;
-
- const modelCondition =
- filter.model !== null
- ? Prisma.sql`AND o.model IN (${Prisma.join(filter.model)})`
- : Prisma.empty;
-
- const traceNameCondition =
- filter.traceName !== null
- ? Prisma.sql`AND t.name IN (${Prisma.join(filter.traceName)})`
- : Prisma.empty;
-
- const searchCondition = filter.searchQuery
- ? Prisma.sql`AND (
- o."id" ILIKE ${`%${filter.searchQuery}%`} OR
- o."name" ILIKE ${`%${filter.searchQuery}%`} OR
- o."model" ILIKE ${`%${filter.searchQuery}%`} OR
- t."name" ILIKE ${`%${filter.searchQuery}%`}
- )`
- : Prisma.empty;
-
- return Prisma.join(
- [
- traceIdCondition,
- nameCondition,
- modelCondition,
- traceNameCondition,
- searchCondition,
- ],
- " ",
- );
-};
-
const ListInputs = GenerationFilterOptions.extend({
...paginationZod,
});
@@ -78,6 +37,21 @@ export const generationsRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(ListInputs)
.query(async ({ input, ctx }) => {
+ const searchCondition = input.searchQuery
+ ? Prisma.sql`AND (
+ o."id" ILIKE ${`%${input.searchQuery}%`} OR
+ o."name" ILIKE ${`%${input.searchQuery}%`} OR
+ o."model" ILIKE ${`%${input.searchQuery}%`} OR
+ t."name" ILIKE ${`%${input.searchQuery}%`}
+ )`
+ : Prisma.empty;
+
+ const filterCondition = filterToPrismaSql(
+ input.filter ?? [],
+ observationsTableCols,
+ );
+ console.log("filters: ", filterCondition);
+
const generations = await ctx.prisma.$queryRaw<
Array<
Observation & {
@@ -110,7 +84,8 @@ export const generationsRouter = createTRPCRouter({
WHERE o.type = 'GENERATION'
AND o.project_id = ${input.projectId}
AND t.project_id = ${input.projectId}
- ${generationsFilterPrismaCondition(input)}
+ ${searchCondition}
+ ${filterCondition}
ORDER BY o.start_time DESC
LIMIT ${input.limit}
OFFSET ${input.page * input.limit}
@@ -123,41 +98,56 @@ export const generationsRouter = createTRPCRouter({
export: protectedProjectProcedure
.input(ExportInputs)
.query(async ({ input, ctx }) => {
- const generations = (await ctx.prisma.observation.findMany({
- where: {
- type: "GENERATION",
- projectId: input.projectId,
- ...(input.name
- ? {
- name: {
- in: input.name,
- },
- }
- : undefined),
- ...(input.model
- ? {
- model: {
- in: input.model,
- },
- }
- : undefined),
- traceId: {
- not: null,
- ...(input.traceId
- ? {
- in: input.traceId,
- }
- : undefined),
- },
- },
- orderBy: {
- startTime: "desc",
- },
- })) as Array<
- Generation & {
- traceId: string;
- }
- >;
+ const searchCondition = input.searchQuery
+ ? Prisma.sql`AND (
+ o."id" ILIKE ${`%${input.searchQuery}%`} OR
+ o."name" ILIKE ${`%${input.searchQuery}%`} OR
+ o."model" ILIKE ${`%${input.searchQuery}%`} OR
+ t."name" ILIKE ${`%${input.searchQuery}%`}
+ )`
+ : Prisma.empty;
+
+ const filterCondition = filterToPrismaSql(
+ input.filter ?? [],
+ observationsTableCols,
+ );
+ console.log("filters: ", filterCondition);
+
+ const generations = await ctx.prisma.$queryRaw<
+ Array<
+ Observation & {
+ traceId: string;
+ traceName: string;
+ }
+ >
+ >(
+ Prisma.sql`
+ SELECT
+ o.id,
+ o.name,
+ o.model,
+ o.start_time as "startTime",
+ o.end_time as "endTime",
+ o.input,
+ o.output,
+ o.metadata,
+ o.trace_id as "traceId",
+ t.name as "traceName",
+ o.completion_start_time as "completionStartTime",
+ o.prompt_tokens as "promptTokens",
+ o.completion_tokens as "completionTokens",
+ o.total_tokens as "totalTokens",
+ o.version
+ FROM observations o
+ JOIN traces t ON t.id = o.trace_id
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId}
+ ${searchCondition}
+ ${filterCondition}
+ ORDER BY o.start_time DESC
+ `,
+ );
// create csv
switch (input.fileFormat) {
@@ -233,115 +223,64 @@ export const generationsRouter = createTRPCRouter({
);
}
}),
-
- availableFilterOptions: protectedProjectProcedure
- .input(GenerationFilterOptions)
+ filterOptions: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const [traceIds, names, models, traceNames] = await Promise.all([
- ctx.prisma.$queryRaw<
- Array<{
- traceId: string | null;
- count: number;
- }>
- >(Prisma.sql`
- SELECT
- t.id as "traceId",
- count(*)::int AS count
- FROM traces t
- JOIN observations o ON o.trace_id = t.id
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId}
- ${generationsFilterPrismaCondition(input)}
- GROUP BY 1
- `),
- ctx.prisma.$queryRaw<
- Array<{
- name: string | null;
- count: number;
- }>
- >(Prisma.sql`
- SELECT
- o.name,
- count(*)::int AS count
- FROM traces t
- JOIN observations o ON o.trace_id = t.id
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId}
- ${generationsFilterPrismaCondition(input)}
- GROUP BY 1
- `),
- ctx.prisma.$queryRaw<
- Array<{
- model: string | null;
- count: number;
- }>
- >(Prisma.sql`
- SELECT
- o.model,
- count(*)::int AS count
- FROM traces t
- JOIN observations o ON o.trace_id = t.id
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId}
- ${generationsFilterPrismaCondition(input)}
- GROUP BY 1
- `),
+ const queryFilter = {
+ projectId: input.projectId,
+ type: "GENERATION",
+ } as const;
+
+ const [model, name, traceName] = await Promise.all([
+ ctx.prisma.observation.groupBy({
+ by: ["model"],
+ where: queryFilter,
+ _count: { _all: true },
+ }),
+ ctx.prisma.observation.groupBy({
+ by: ["name"],
+ where: queryFilter,
+ _count: { _all: true },
+ }),
ctx.prisma.$queryRaw<
Array<{
- name: string | null;
+ traceName: string | null;
count: number;
}>
>(Prisma.sql`
SELECT
- t.name,
+ t.name "traceName",
count(*)::int AS count
FROM traces t
JOIN observations o ON o.trace_id = t.id
WHERE o.type = 'GENERATION'
AND o.project_id = ${input.projectId}
AND t.project_id = ${input.projectId}
- ${generationsFilterPrismaCondition(input)}
GROUP BY 1
`),
]);
-
- return [
- {
- key: "traceId",
- occurrences: traceIds
- .filter((i) => i.traceId !== null)
- .map((i) => {
- return { key: i.traceId ?? "null", count: i.count };
- }),
- },
- {
- key: "name",
- occurrences: names
- .filter((i) => i.name !== null)
- .map((i) => {
- return { key: i.name ?? "null", count: i.count };
- }),
- },
- {
- key: "model",
- occurrences: models
- .filter((i) => i.model !== null)
- .map((i) => {
- return { key: i.model ?? "null", count: i.count };
- }),
- },
- {
- key: "traceName",
- occurrences: traceNames
- .filter((i) => i.name !== null)
- .map((i) => {
- return { key: i.name ?? "null", count: i.count };
- }),
- },
- ];
+ // typecheck filter options, needs to include all columns with options
+ const res: ObservationOptions = {
+ model: model
+ .filter((i) => i.model !== null)
+ .map((i) => ({
+ value: i.model as string,
+ count: i._count._all,
+ })),
+ name: name
+ .filter((i) => i.name !== null)
+ .map((i) => ({
+ value: i.name as string,
+ count: i._count._all,
+ })),
+ traceName: traceName
+ .filter((i) => i.traceName !== null)
+ .map((i) => ({
+ value: i.traceName as string,
+ count: i.count,
+ })),
+ };
+ return res;
}),
byId: protectedProcedure.input(z.string()).query(async ({ input, ctx }) => {
diff --git a/src/server/api/routers/scores.ts b/src/server/api/routers/scores.ts
index 954350c604..42f653f022 100644
--- a/src/server/api/routers/scores.ts
+++ b/src/server/api/routers/scores.ts
@@ -8,23 +8,18 @@ import {
import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
import { Prisma, type Score } from "@prisma/client";
import { paginationZod } from "@/src/utils/zod";
+import { singleFilter } from "@/src/server/api/interfaces/filters";
+import { filterToPrismaSql } from "@/src/features/filters/server/filterToPrisma";
+import {
+ type ScoreOptions,
+ scoresTableCols,
+} from "@/src/server/api/definitions/scoresTable";
const ScoreFilterOptions = z.object({
- traceId: z.array(z.string()).nullable(),
projectId: z.string(), // Required for protectedProjectProcedure
- userId: z.string().nullable(),
+ filter: z.array(singleFilter),
});
-const scoresFilterPrismaCondition = (
- filter: z.infer<typeof ScoreFilterOptions>,
-) => {
- const traceIdCondition = filter.traceId
- ? Prisma.sql`AND s.trace_id IN (${Prisma.join(filter.traceId)})`
- : Prisma.empty;
-
- return Prisma.join([traceIdCondition], " ");
-};
-
const ScoreAllOptions = ScoreFilterOptions.extend({
...paginationZod,
});
@@ -33,9 +28,11 @@ export const scoresRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(ScoreAllOptions)
.query(async ({ input, ctx }) => {
- const userIdCondition = input.userId
- ? Prisma.sql`AND t.user_id = ${input.userId}`
- : Prisma.empty;
+ const filterCondition = filterToPrismaSql(
+ input.filter ?? [],
+ scoresTableCols,
+ );
+ console.log("filters: ", filterCondition);
const scores = await ctx.prisma.$queryRaw<
Array<Score & { traceName: string; totalCount: number }>
@@ -53,62 +50,39 @@ export const scoresRouter = createTRPCRouter({
FROM scores s
JOIN traces t ON t.id = s.trace_id
WHERE t.project_id = ${input.projectId}
- ${userIdCondition}
- ${scoresFilterPrismaCondition(input)}
+ ${filterCondition}
ORDER BY s.timestamp DESC
LIMIT ${input.limit}
OFFSET ${input.page * input.limit}
`);
return scores;
}),
- availableFilterOptions: protectedProjectProcedure
- .input(ScoreFilterOptions)
+ filterOptions: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ }),
+ )
.query(async ({ input, ctx }) => {
- const filter = {
- trace: {
- projectId: input.projectId,
- ...(input.userId ? { userId: input.userId } : undefined),
- },
- ...(input.traceId
- ? {
- traceId: {
- in: input.traceId,
- },
- }
- : undefined),
- };
-
- const [ids, traceIds] = await Promise.all([
+ const [names] = await Promise.all([
ctx.prisma.score.groupBy({
- where: filter,
- by: ["id"],
- _count: {
- _all: true,
+ where: {
+ trace: {
+ projectId: input.projectId,
+ },
},
- }),
- ctx.prisma.score.groupBy({
- where: filter,
- by: ["traceId"],
+ by: ["name"],
_count: {
_all: true,
},
}),
]);
- return [
- {
- key: "id",
- occurrences: ids.map((i) => {
- return { key: i.id, count: i._count };
- }),
- },
- {
- key: "traceId",
- occurrences: traceIds.map((i) => {
- return { key: i.traceId, count: i._count };
- }),
- },
- ];
+ const res: ScoreOptions = {
+ name: names.map((i) => ({ value: i.name, count: i._count._all })),
+ };
+
+ return res;
}),
byId: protectedProcedure.input(z.string()).query(({ input, ctx }) =>
ctx.prisma.score.findFirstOrThrow({
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 0d9bc98248..687a5d3278 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -10,24 +10,17 @@ import { Prisma, type Score, type Trace } from "@prisma/client";
import { calculateTokenCost } from "@/src/features/ingest/lib/usage";
import Decimal from "decimal.js";
import { paginationZod } from "@/src/utils/zod";
-
-const ScoreFilter = z.object({
- name: z.string(),
- operator: z.enum(["lt", "gt", "equals", "lte", "gte"]),
- value: z.number(),
-});
-
-type ScoreFilter = z.infer<typeof ScoreFilter>;
+import { singleFilter } from "@/src/server/api/interfaces/filters";
+import {
+ type TraceOptions,
+ tracesTableCols,
+} from "@/src/server/api/definitions/tracesTable";
+import { filterToPrismaSql } from "@/src/features/filters/server/filterToPrisma";
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
- userId: z.array(z.string()).nullable(),
- name: z.array(z.string()).nullable(),
- scores: ScoreFilter.nullable(),
searchQuery: z.string().nullable(),
- metadata: z
- .array(z.object({ key: z.string(), value: z.string() }))
- .nullable(),
+ filter: z.array(singleFilter).nullable(),
...paginationZod,
});
@@ -35,48 +28,11 @@ export const traceRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(TraceFilterOptions)
.query(async ({ input, ctx }) => {
- const metadataCondition = input.metadata
- ? input.metadata.map(
- (m) => Prisma.sql`AND t."metadata"->>${m.key} = ${m.value}`,
- )
- : undefined;
-
- const joinedMetadataCondition =
- metadataCondition && metadataCondition.length > 0
- ? Prisma.join(metadataCondition, " ")
- : Prisma.empty;
-
- const userIdCondition =
- input.userId !== null && input.userId.length
- ? Prisma.sql`AND t."user_id" IN (${Prisma.join(input.userId)})`
- : Prisma.empty;
-
- const nameCondition =
- input.name !== null && input.name.length
- ? Prisma.sql`AND t."name" IN (${Prisma.join(input.name)})`
- : Prisma.empty;
-
- let scoreCondition = Prisma.empty;
- if (input.scores) {
- const base = Prisma.sql`AND "trace_id" in (SELECT distinct trace_id from scores WHERE trace_id IS NOT NULL AND scores.name = ${input.scores.name}`;
- switch (input.scores.operator) {
- case "lt":
- scoreCondition = Prisma.sql`${base} AND scores.value < ${input.scores.value})`;
- break;
- case "gt":
- scoreCondition = Prisma.sql`${base} AND scores.value > ${input.scores.value})`;
- break;
- case "equals":
- scoreCondition = Prisma.sql`${base} AND scores.value = ${input.scores.value})`;
- break;
- case "lte":
- scoreCondition = Prisma.sql`${base} AND scores.value <= ${input.scores.value})`;
- break;
- case "gte":
- scoreCondition = Prisma.sql`${base} AND scores.value >= ${input.scores.value})`;
- break;
- }
- }
+ const filterCondition = filterToPrismaSql(
+ input.filter ?? [],
+ tracesTableCols,
+ );
+ console.log("filters: ", filterCondition);
const searchCondition = input.searchQuery
? Prisma.sql`AND (
@@ -94,20 +50,66 @@ export const traceRouter = createTRPCRouter({
completionTokens: number;
totalTokens: number;
totalCount: number;
+ scores: Score[];
}
>
>(Prisma.sql`
- WITH usage as (
- SELECT
+ WITH usage AS (
+ SELECT
trace_id,
sum(prompt_tokens) AS "promptTokens",
sum(completion_tokens) AS "completionTokens",
sum(total_tokens) AS "totalTokens"
- FROM "observations"
- WHERE "trace_id" IS NOT NULL AND "type" = 'GENERATION' AND "project_id" = ${
- input.projectId
- }
- GROUP BY trace_id
+ FROM
+ "observations"
+ WHERE
+ "trace_id" IS NOT NULL
+ AND "type" = 'GENERATION'
+ AND "project_id" = ${input.projectId}
+ GROUP BY
+ trace_id
+ ),
+ -- used for filtering
+ scores_avg AS (
+ SELECT
+ trace_id,
+ 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
+ ),
+ scores_json AS (
+ SELECT
+ trace_id,
+ json_agg(json_build_object('id',
+ "id",
+ 'timestamp',
+ "timestamp",
+ 'name',
+ "name",
+ 'value',
+ "value",
+ 'traceId',
+ "trace_id",
+ 'observationId',
+ "observation_id",
+ 'comment',
+ "comment")) AS scores
+ FROM
+ scores
+ GROUP BY
+ 1
)
SELECT
t.*,
@@ -117,137 +119,58 @@ 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",
- (count(*) OVER())::int AS "totalCount"
- FROM "traces" AS t
- LEFT JOIN usage AS u ON u.trace_id = t.id
+ COALESCE(s_json.scores, '[]'::json) AS "scores",
+ (count(*) OVER ())::int AS "totalCount"
+ FROM
+ "traces" AS t
+ LEFT JOIN usage AS u ON u.trace_id = t.id
+ -- used for filtering
+ LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = t.id
+ LEFT JOIN scores_json AS s_json ON s_json.trace_id = t.id
WHERE
t."project_id" = ${input.projectId}
- ${userIdCondition}
- ${nameCondition}
${searchCondition}
- ${scoreCondition}
- ${joinedMetadataCondition}
- ORDER BY t."timestamp" DESC
+ ${filterCondition}
+ ORDER BY
+ t."timestamp" DESC
LIMIT ${input.limit}
- OFFSET ${input.page * input.limit};
+ OFFSET ${input.page * input.limit}
`);
-
- const scores = traces.length
- ? await ctx.prisma.$queryRaw<Score[]>(
- Prisma.sql`
- SELECT
- s.*,
- s."trace_id" AS "traceId",
- s."observation_id" AS "observationId"
- FROM "scores" s
- WHERE s."trace_id" IN (${Prisma.join(
- traces.map((trace) => trace.id),
- )})`,
- )
- : [];
-
- return traces.map((trace) => ({
- ...trace,
- scores: scores.filter((score) => score.traceId === trace.id),
- }));
+ return traces;
}),
- availableFilterOptions: protectedProjectProcedure
- .input(TraceFilterOptions)
+ filterOptions: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const metadataConditions = input.metadata
- ? input.metadata.map((m) => ({
- metadata: { path: [m.key], equals: m.value },
- }))
- : undefined;
-
- const filter = {
- AND: [
- {
- projectId: input.projectId,
- ...(input.name ? { name: { in: input.name } } : undefined),
- ...(input.userId ? { userId: { in: input.userId } } : undefined),
- ...(input.scores
- ? { scores: { some: createScoreCondition(input.scores) } }
- : undefined),
- },
- ...(metadataConditions ? metadataConditions : []),
- input.searchQuery
- ? {
- OR: [
- { id: { contains: input.searchQuery } },
- { externalId: { contains: input.searchQuery } },
- { userId: { contains: input.searchQuery } },
- { name: { contains: input.searchQuery } },
- ],
- }
- : {},
- ],
- };
-
- const [scores, names, userIds] = await Promise.all([
+ const [scores, names] = await Promise.all([
ctx.prisma.score.groupBy({
where: {
- trace: filter,
- },
- by: ["name", "traceId"],
- _count: {
- _all: true,
+ trace: {
+ projectId: input.projectId,
+ },
},
- }),
- ctx.prisma.trace.groupBy({
- where: filter,
by: ["name"],
- _count: {
- _all: true,
- },
}),
ctx.prisma.trace.groupBy({
- where: filter,
- by: ["userId"],
+ where: {
+ projectId: input.projectId,
+ },
+ by: ["name"],
_count: {
_all: true,
},
}),
]);
-
- let groupedCounts: Map<string, number> = new Map();
-
- for (const item of scores) {
- const current = groupedCounts.get(item.name);
- groupedCounts = groupedCounts.set(item.name, current ? current + 1 : 1);
- }
-
- const scoresArray: { key: string; value: number }[] = [];
- for (const [key, value] of groupedCounts) {
- scoresArray.push({ key, value });
- }
-
- return [
- {
- key: "name",
- occurrences: names.map((i) => {
- return { key: i.name ?? "undefined", count: i._count };
- }),
- },
- {
- key: "userId",
- occurrences: userIds.map((i) => {
- return { key: i.userId ?? "undefined", count: i._count };
- }),
- },
- {
- key: "scores",
- occurrences: scoresArray.map((i) => {
- return { key: i.key, count: { _all: i.value } };
- }),
- },
- {
- key: "metadata",
- occurrences: [],
- },
- ];
+ const res: TraceOptions = {
+ scores_avg: scores.map((score) => score.name),
+ name: names
+ .filter((n) => n.name !== null)
+ .map((name) => ({
+ value: name.name ?? "undefined",
+ count: name._count._all,
+ })),
+ };
+ return res;
}),
-
byId: protectedProcedure.input(z.string()).query(async ({ input, ctx }) => {
const [trace, observations, pricings] = await Promise.all([
ctx.prisma.trace.findFirstOrThrow({
@@ -357,29 +280,3 @@ export const traceRouter = createTRPCRouter({
};
}),
});
-
-function createScoreCondition(score: ScoreFilter) {
- let filter = {};
- switch (score.operator) {
- case "lt":
- filter = { lt: score.value };
- break;
- case "gt":
- filter = { gt: score.value };
- break;
- case "equals":
- filter = { equals: score.value };
- break;
- case "lte":
- filter = { lte: score.value };
- break;
- case "gte":
- filter = { gte: score.value };
- break;
- }
-
- return {
- name: score.name,
- value: filter,
- };
-}
diff --git a/src/server/api/services/query-builder.ts b/src/server/api/services/query-builder.ts
new file mode 100644
index 0000000000..e8c8665417
--- /dev/null
+++ b/src/server/api/services/query-builder.ts
@@ -0,0 +1,333 @@
+import {
+ type singleFilter,
+ type timeFilter,
+} from "@/src/server/api/interfaces/filters";
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
+import { Prisma, type PrismaClient } from "@prisma/client";
+import { type Sql } from "@prisma/client/runtime/library";
+import Decimal from "decimal.js";
+import { type z } from "zod";
+import { type sqlInterface } from "./sqlInterface";
+import { tableDefinitions } from "./tableDefinitions";
+
+export type InternalDatabaseRow = {
+ [key: string]: bigint | number | Decimal | string | Date;
+};
+
+export type DatabaseRow = {
+ [key: string]: string | number | Date;
+};
+
+export const executeQuery = async (
+ prisma: PrismaClient,
+ projectId: string,
+ query: z.TypeOf<typeof sqlInterface>,
+) => {
+ const sql = enrichAndCreateQuery(projectId, query);
+
+ const response = await prisma.$queryRaw<InternalDatabaseRow[]>(sql);
+
+ const parsedResult = outputParser(response);
+
+ return parsedResult;
+};
+
+export const enrichAndCreateQuery = (
+ projectId: string,
+ query: z.TypeOf<typeof sqlInterface>,
+) => {
+ return createQuery({
+ ...query,
+ filter: [...query.filter, ...getMandatoryFilter(query.from, projectId)],
+ });
+};
+
+export const createQuery = (query: z.TypeOf<typeof sqlInterface>) => {
+ const cte = createDateRangeCte(query.from, query.filter, query.groupBy);
+
+ const fromString = cte?.from ?? Prisma.sql` FROM ${getTableSql(query.from)}`;
+
+ const selectFields = query.select.map((field) =>
+ // raw mandatory everywhere here as this creates the selection
+ // agg is typed via zod
+ // column names come from our defs via the table definitions
+ field.agg
+ ? Prisma.sql`${Prisma.raw(field.agg)}(${getInternalSql(
+ getColumnSql(query.from, field.column),
+ )}) as "${Prisma.raw(field.agg.toLowerCase())}${Prisma.raw(
+ capitalizeFirstLetter(field.column),
+ )}"`
+ : Prisma.sql`${getInternalSql(
+ getColumnSql(query.from, field.column),
+ )} as "${Prisma.raw(getColumnSql(query.from, field.column).name)}"`,
+ );
+
+ if (cte)
+ // raw mandatory here
+ selectFields.unshift(
+ Prisma.sql`date_series."date" as "${Prisma.raw(cte.column.name)}"`,
+ );
+
+ let groupString = Prisma.empty;
+
+ if (query.groupBy.length > 0 || cte) {
+ const groupByFields = query.groupBy.map((groupBy) =>
+ prepareGroupBy(query.from, groupBy),
+ );
+ groupString =
+ groupByFields.length > 0
+ ? Prisma.sql` GROUP BY ${Prisma.join(groupByFields, ", ")}`
+ : Prisma.empty;
+ }
+ const selectString =
+ selectFields.length > 0
+ ? Prisma.sql` SELECT ${Prisma.join(selectFields, ", ")}`
+ : Prisma.empty;
+
+ const orderByString = prepareOrderByString(
+ query.orderBy,
+ tableDefinitions[query.from]!.columns,
+ cte ? true : false,
+ );
+
+ const filterString =
+ query.filter.length > 0
+ ? Prisma.sql` ${
+ cte ? Prisma.sql` AND ` : Prisma.sql` WHERE `
+ } ${prepareFilterString(
+ query.from,
+ query.filter,
+ tableDefinitions[query.from]!.columns,
+ )}`
+ : Prisma.empty;
+
+ return Prisma.sql`${
+ cte?.cte ?? Prisma.empty
+ }${selectString}${fromString}${filterString}${groupString}${orderByString};`;
+};
+
+const prepareOrderByString = (
+ orderBy: z.infer<typeof sqlInterface>["orderBy"],
+ columnDefinitions: ColumnDefinition[],
+ hasCte: boolean,
+): Prisma.Sql => {
+ const orderBys = orderBy.map((orderBy) => {
+ const column = columnDefinitions.find((x) => x.name === orderBy.column);
+ if (!column) {
+ console.error(`Column ${orderBy.column} not found`);
+ throw new Error(`Column ${orderBy.column} not found`);
+ }
+
+ // raw mandatory here
+ return Prisma.sql`${getInternalSql(column)} ${Prisma.raw(
+ orderBy.direction,
+ )}`;
+ });
+ const addedCte = hasCte
+ ? [Prisma.sql`date_series."date" ASC`, ...orderBys]
+ : orderBys;
+
+ return addedCte.length > 0
+ ? Prisma.sql` ORDER BY ${Prisma.join(addedCte, ", ")}`
+ : Prisma.empty;
+};
+
+const prepareFilterString = (
+ table: z.infer<typeof sqlInterface>["from"],
+ filter: z.infer<typeof sqlInterface>["filter"],
+ columnDefinitions: ColumnDefinition[],
+): Prisma.Sql => {
+ const filters = filter.map((filter) => {
+ const column = columnDefinitions.find((x) => x.name === filter.column);
+ if (!column) {
+ console.error(`Column ${filter.column} not found`);
+ throw new Error(`Column ${filter.column} not found`);
+ }
+ // raw manfatory for column defs and operator
+ // non raw for value, which will go into parameterised string
+ if (filter.type === "datetime") {
+ return Prisma.sql`${getInternalSql(column)} ${Prisma.raw(
+ filter.operator,
+ )} ${filter.value}`;
+ } else {
+ return Prisma.sql`${getInternalSql(column)} ${Prisma.raw(
+ filter.operator,
+ )} ${filter.value} ${
+ column.name === "type" && table === "observations"
+ ? Prisma.sql`::"ObservationType"`
+ : Prisma.empty
+ }`;
+ }
+ });
+ return Prisma.join(filters, " AND ");
+};
+
+const prepareGroupBy = (
+ table: z.infer<typeof sqlInterface>["from"],
+ groupBy: z.infer<typeof sqlInterface>["groupBy"][number],
+) => {
+ const internalColumn = getInternalSql(getColumnSql(table, groupBy.column));
+ if (groupBy.type === "datetime") {
+ return Prisma.sql`date_series."date"`;
+ } else {
+ return internalColumn;
+ }
+};
+
+function isTimeRangeFilter(
+ filter: z.infer<typeof sqlInterface>["filter"][number],
+): filter is z.infer<typeof timeFilter> {
+ return filter.type === "datetime";
+}
+
+const createDateRangeCte = (
+ from: z.infer<typeof sqlInterface>["from"],
+ filters: z.infer<typeof singleFilter>[],
+ groupBy: z.infer<typeof sqlInterface>["groupBy"],
+) => {
+ const groupByColumns = groupBy.filter((x) => x.type === "datetime");
+
+ if (groupByColumns.length === 0) return undefined;
+ if (groupByColumns.length > 1)
+ throw new Error("Only one datetime group by is supported");
+
+ const groupByColumn = groupByColumns[0];
+
+ const dateTimeFilters = filters.filter(isTimeRangeFilter);
+
+ const minDateColumn =
+ dateTimeFilters.length > 1
+ ? dateTimeFilters.find((x) => x.operator === ">" || x.operator === ">=")
+ : undefined;
+
+ const maxDateColumn =
+ dateTimeFilters.length > 1
+ ? dateTimeFilters.find((x) => x.operator === "<" || x.operator === "<=")
+ : undefined;
+
+ if (
+ groupByColumn &&
+ "temporalUnit" in groupByColumn &&
+ minDateColumn &&
+ maxDateColumn
+ ) {
+ if (
+ minDateColumn?.column !== groupByColumn?.column ||
+ maxDateColumn?.column !== groupByColumn?.column
+ ) {
+ throw new Error(
+ "Min date column, max date column must match group by column",
+ );
+ }
+
+ const startColumn = getColumnSql(from, minDateColumn.column);
+
+ // raw mandatory for temporal unit. From and to are parameterised values
+ // temporal unit is typed
+ const cteString = Prisma.sql`
+ WITH date_series AS (
+ SELECT generate_series(${minDateColumn.value}, ${
+ maxDateColumn.value
+ }, '1 ${Prisma.raw(groupByColumn.temporalUnit)}') as date
+ )
+ `;
+
+ // as above, raw is mandatory for columns and temporal unit
+ const modifiedFrom = Prisma.sql` FROM date_series LEFT JOIN ${getTableSql(
+ from,
+ )} ON DATE_TRUNC('${Prisma.raw(
+ groupByColumn.temporalUnit,
+ )}', ${getInternalSql(startColumn)}) = DATE_TRUNC('${Prisma.raw(
+ groupByColumn.temporalUnit,
+ )}', date_series."date")`;
+
+ return { cte: cteString, from: modifiedFrom, column: startColumn };
+ }
+
+ return undefined;
+};
+
+const getTableSql = (
+ table: z.infer<typeof sqlInterface>["from"],
+): Prisma.Sql => {
+ // raw required here, everyrhing is typed
+ return Prisma.raw(tableDefinitions[table]!.table);
+};
+
+const getColumnSql = (
+ table: z.infer<typeof sqlInterface>["from"],
+ column: string,
+): ColumnDefinition => {
+ const foundColumn = tableDefinitions[table]!.columns.find((c) => {
+ return c.name === column;
+ });
+ if (!foundColumn) {
+ console.error(`Column ${column} not found in table ${table}`);
+ throw new Error(`Column ${column} not found in table ${table}`);
+ }
+ return foundColumn;
+};
+
+const getInternalSql = (colDef: ColumnDefinition): Sql =>
+ // raw required here, everything is typed
+ Prisma.raw(colDef.internal);
+
+const outputParser = (output: InternalDatabaseRow[]): DatabaseRow[] => {
+ return output.map((row) => {
+ const newRow: DatabaseRow = {};
+ for (const key in row) {
+ const val = row[key];
+ if (typeof val === "bigint") {
+ newRow[key] = Number(val);
+ } else if (typeof val === "number") {
+ newRow[key] = val;
+ } else if (Decimal.isDecimal(val)) {
+ newRow[key] = val.toNumber();
+ } else if (typeof val === "string") {
+ newRow[key] = val;
+ } else if (val instanceof Date) {
+ newRow[key] = val;
+ } else if (val === null) {
+ newRow[key] = val;
+ } else {
+ console.log(`Unknown type ${typeof val} for ${val}`);
+ throw new Error(`Unknown type ${typeof val}`);
+ }
+ }
+ return newRow;
+ });
+};
+
+function capitalizeFirstLetter(str: string) {
+ return str.charAt(0).toUpperCase() + str.slice(1);
+}
+
+const getMandatoryFilter = (
+ table: z.infer<typeof sqlInterface>["from"],
+ projectId: string,
+) => {
+ const observationFilter = {
+ type: "string" as const,
+ column: "observationsProjectId",
+ operator: "=" as const,
+ value: projectId,
+ };
+
+ const traceFilter = {
+ type: "string" as const,
+ column: "tracesProjectId",
+ operator: "=" as const,
+ value: projectId,
+ };
+
+ switch (table) {
+ case "traces":
+ case "traces_scores":
+ return [traceFilter];
+ case "traces_observations":
+ case "traces_parent_observation_scores":
+ return [traceFilter, observationFilter];
+ case "observations":
+ return [observationFilter];
+ }
+};
diff --git a/src/server/api/services/sqlInterface.ts b/src/server/api/services/sqlInterface.ts
new file mode 100644
index 0000000000..c19ccd01ba
--- /dev/null
+++ b/src/server/api/services/sqlInterface.ts
@@ -0,0 +1,45 @@
+import { singleFilter } from "@/src/server/api/interfaces/filters";
+import { z } from "zod";
+
+export const temporalUnit = z.enum([
+ "year",
+ "month",
+ "week",
+ "day",
+ "hour",
+ "minute",
+]);
+
+export const sqlInterface = z.object({
+ from: z.enum([
+ "traces",
+ "traces_observations",
+ "observations",
+ "traces_scores",
+ "traces_parent_observation_scores",
+ ]),
+ filter: z.array(singleFilter),
+ groupBy: z.array(
+ z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("datetime"),
+ column: z.string(),
+ temporalUnit: temporalUnit,
+ }),
+ z.object({ type: z.literal("number"), column: z.string() }),
+ z.object({ type: z.literal("string"), column: z.string() }),
+ ]),
+ ),
+ select: z.array(
+ z.object({
+ column: z.string(),
+ agg: z.enum(["SUM", "AVG", "COUNT"]).nullable(),
+ }),
+ ),
+ orderBy: z.array(
+ z.object({
+ column: z.string(),
+ direction: z.enum(["ASC", "DESC"]),
+ }),
+ ),
+});
diff --git a/src/server/api/services/tableDefinitions.ts b/src/server/api/services/tableDefinitions.ts
new file mode 100644
index 0000000000..621d6c0f3d
--- /dev/null
+++ b/src/server/api/services/tableDefinitions.ts
@@ -0,0 +1,180 @@
+import { type TableDefinitions } from "@/src/server/api/interfaces/tableDefinition";
+
+export const completionTokens = {
+ name: "completionTokens",
+ type: "number",
+ internal: 'o."completion_tokens"',
+} as const;
+export const observationId = {
+ name: "observationId",
+ type: "string",
+ internal: 'o."id"',
+} as const;
+export const observationName = {
+ name: "name",
+ type: "string",
+ internal: 'o."name"',
+} as const;
+export const startTime = {
+ name: "startTime",
+ type: "datetime",
+ internal: 'o."start_time"',
+} as const;
+export const traceId = {
+ name: "traceId",
+ type: "string",
+ internal: 't."id"',
+} as const;
+export const traceVersion = {
+ name: "version",
+ type: "string",
+ internal: 't."version"',
+} as const;
+export const traceTimestamp = {
+ name: "timestamp",
+ type: "string",
+ internal: 't."timestamp"',
+} as const;
+export const scoreName = {
+ name: "scoreName",
+ type: "string",
+ internal: 's."name"',
+} as const;
+export const duration = {
+ name: "duration",
+ type: "number",
+ internal:
+ 'EXTRACT(EPOCH FROM o."end_time") * 1000 - EXTRACT(EPOCH FROM o."start_time") * 1000',
+} as const;
+export const release = {
+ name: "release",
+ type: "string",
+ internal: 't."release"',
+} as const;
+export const tracesProjectId = {
+ name: "tracesProjectId",
+ type: "string",
+ internal: 't."project_id"',
+} as const;
+export const observationsProjectId = {
+ name: "observationsProjectId",
+ type: "string",
+ internal: 'o."project_id"',
+} as const;
+export const scoreId = {
+ name: "scoreId",
+ type: "string",
+ internal: 's."id"',
+} as const;
+
+export const totalTokenCost = {
+ name: "totalTokenCost",
+ 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-32k-0314%') THEN 0.06 * o."prompt_tokens" + 0.12 * o."completion_tokens"
+ WHEN (o."model" LIKE '%gpt-4-32k-0613%') 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 '%text-embedding-ada-002-v2%') THEN 0.0001 * o."prompt_tokens" + 0.0001 * coalesce(o."completion_tokens", 0)
+ WHEN (o."model" LIKE '%ada%') THEN 0.0004 * o."prompt_tokens" + 0.0004 * 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.002 * 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-v1%') THEN 0.0163 * o."prompt_tokens" + 0.0551 * o."completion_tokens"
+ WHEN (o."model" LIKE '%claude-instant-v1%') THEN 0.01102 * o."prompt_tokens" + 0.03268 * o."completion_tokens"
+ ELSE 0
+ END
+ ) / 1000
+ `,
+} as const;
+
+export const tableDefinitions: TableDefinitions = {
+ traces: {
+ table: ` traces t`,
+ columns: [tracesProjectId, traceVersion, release, traceId, traceTimestamp],
+ },
+ traces_observations: {
+ table: ` traces t LEFT JOIN observations o ON t.id = o.trace_id`,
+ columns: [
+ traceId,
+ observationId,
+ { name: "type", type: "string", internal: 'o."type"' },
+ tracesProjectId,
+ observationsProjectId,
+ duration,
+ totalTokenCost,
+ ],
+ },
+ observations: {
+ table: ` observations o`,
+ columns: [
+ traceId,
+ totalTokenCost,
+ observationName,
+ { name: "type", type: "string", internal: 'o."type"' },
+ completionTokens,
+ {
+ name: "promptTokens",
+ type: "number",
+ internal: 'o."prompt_tokens"',
+ },
+ {
+ name: "totalTokens",
+ type: "number",
+ internal: 'o."total_tokens"',
+ },
+ observationId,
+ { name: "model", type: "string", internal: 'o."model"' },
+ observationsProjectId,
+ startTime,
+ { name: "endTime", type: "datetime", internal: 'o."end_time"' },
+ duration,
+ ],
+ },
+ traces_scores: {
+ table: ` traces t JOIN scores s ON t.id = s.trace_id`,
+ columns: [
+ tracesProjectId,
+ { name: "value", type: "number", internal: 's."value"' },
+ {
+ name: "name",
+ type: "number",
+ internal: 's."name"',
+ },
+ scoreId,
+ traceVersion,
+ traceTimestamp,
+ scoreName,
+ tracesProjectId,
+ ],
+ },
+ 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"`,
+ columns: [
+ { name: "projectId", type: "string", internal: 't."project_id"' },
+ { name: "value", type: "number", internal: 's."value"' },
+ {
+ name: "name",
+ type: "number",
+ internal: 's."name"',
+ },
+ traceVersion,
+ traceTimestamp,
+ scoreName,
+ duration,
+ release,
+ tracesProjectId,
+ observationsProjectId,
+ ],
+ },
+};
diff --git a/src/utils/types.ts b/src/utils/types.ts
index b9bdc9f95e..5bc646c4b6 100644
--- a/src/utils/types.ts
+++ b/src/utils/types.ts
@@ -31,3 +31,7 @@ export type Generation = Observation & {
export type RouterInput = inferRouterInputs<AppRouter>;
export type RouterOutput = inferRouterOutputs<AppRouter>;
+
+export const isNotUndefinedOrNull = <T>(
+ val?: T | null,
+): val is undefined | null => val !== undefined || val !== null;