Skip to content

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

feat: add traces, spans, generations latency tables (#1312)

Max Deichmann60e636e37d5e
diff --git a/web/prisma/migrations/20240304123642_traces_view/migration.sql b/web/prisma/migrations/20240304123642_traces_view/migration.sql
new file mode 100644
index 0000000000..78f429990b
--- /dev/null
+++ b/web/prisma/migrations/20240304123642_traces_view/migration.sql
@@ -0,0 +1,8 @@
+CREATE VIEW trace_metrics_view AS
+SELECT
+ t.id,
+ EXTRACT(EPOCH FROM COALESCE(MAX(o.end_time), MAX(o.start_time))) - EXTRACT(EPOCH FROM MIN(o.start_time))::double precision AS duration
+FROM
+ traces t
+ LEFT JOIN observations o ON t.id = o.trace_id
+group by t.project_id, t.id
\ No newline at end of file
diff --git a/web/src/__tests__/query-builder.servertest.ts b/web/src/__tests__/query-builder.servertest.ts
index 4efd73c2e8..81daa15c17 100644
--- a/web/src/__tests__/query-builder.servertest.ts
+++ b/web/src/__tests__/query-builder.servertest.ts
@@ -18,9 +18,26 @@ describe("Build valid SQL queries", () => {
values: ["project-id"],
strings: [' FROM traces t WHERE t."project_id" = ', ";"],
} as const,
+ {
+ table: "traces_metrics",
+ values: ["project-id"],
+ strings: [
+ ' FROM traces t LEFT JOIN trace_metrics_view tv ON t.id = tv.id 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: "traces_observationsview",
+ values: ["project-id", "project-id"],
strings: [
' FROM traces t LEFT JOIN observations_view o ON t.id = o.trace_id WHERE t."project_id" = ',
' AND o."project_id" = ',
@@ -142,7 +159,7 @@ describe("Build valid SQL queries", () => {
from: "traces",
select: [{ column: "unknown" }],
}),
- ).toThrow("Column unknown not found");
+ ).toThrow('Column "unknown" not found in table traces');
});
it("should not group by an unknown column", () => {
@@ -152,7 +169,7 @@ describe("Build valid SQL queries", () => {
groupBy: [{ column: "unknown", type: "string" }],
select: [],
}),
- ).toThrow("Column unknown not found");
+ ).toThrow('Column "unknown" not found in table traces');
});
it("should not order by an unknown column", () => {
@@ -162,7 +179,7 @@ describe("Build valid SQL queries", () => {
select: [],
orderBy: [{ column: "unknown", direction: "ASC" }],
}),
- ).toThrow("Column unknown not found");
+ ).toThrow('Column "unknown" not found in table traces');
});
});
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index 1dc6be233b..ace670ad19 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -16,7 +16,7 @@ import { TabComponent } from "@/src/features/dashboard/components/TabsComponent"
import { numberFormatter } from "@/src/utils/numbers";
import { NoData } from "@/src/features/dashboard/components/NoData";
-export const LatencyChart = ({
+export const GenerationLatencyChart = ({
className,
projectId,
globalFilterState,
diff --git a/web/src/features/dashboard/components/MetricTable.tsx b/web/src/features/dashboard/components/MetricTable.tsx
index 40c38fd2df..dbbf874693 100644
--- a/web/src/features/dashboard/components/MetricTable.tsx
+++ b/web/src/features/dashboard/components/MetricTable.tsx
@@ -20,7 +20,7 @@ export const MetricTable = ({
const metrics = api.dashboard.chart.useQuery(
{
projectId,
- from: "traces_observations",
+ from: "traces_observationsview",
select: [
{ column: "calculatedTotalCost", agg: "SUM" },
{ column: "totalTokens", agg: "SUM" },
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 94c4ec1e61..d5282df6a9 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -34,7 +34,7 @@ export const ModelUsageChart = ({
const tokens = api.dashboard.chart.useQuery(
{
projectId,
- from: "traces_observations",
+ from: "traces_observationsview",
select: [
{ column: "totalTokens", agg: "SUM" },
{ column: "calculatedTotalCost", agg: "SUM" },
diff --git a/web/src/features/dashboard/components/SpanLatencyTable.tsx b/web/src/features/dashboard/components/SpanLatencyTable.tsx
new file mode 100644
index 0000000000..283919ed94
--- /dev/null
+++ b/web/src/features/dashboard/components/SpanLatencyTable.tsx
@@ -0,0 +1,202 @@
+import { RightAlignedCell } from "@/src/features/dashboard/components/RightAlignedCell";
+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
+import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";
+import { type FilterState } from "@/src/features/filters/types";
+import { api } from "@/src/utils/api";
+
+import { type DatabaseRow } from "@/src/server/api/services/query-builder";
+import { formatIntervalSeconds } from "@/src/utils/dates";
+import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";
+import { truncate } from "@/src/utils/string";
+
+export const LatencyTables = ({
+ projectId,
+ globalFilterState,
+}: {
+ projectId: string;
+ globalFilterState: FilterState;
+}) => {
+ const generationsLatencies = api.dashboard.chart.useQuery(
+ {
+ projectId,
+ from: "observations",
+ select: [
+ { column: "duration", agg: "50thPercentile" },
+ { column: "duration", agg: "90thPercentile" },
+ { column: "duration", agg: "95thPercentile" },
+ { column: "duration", agg: "99thPercentile" },
+ { column: "name" },
+ ],
+ filter: [
+ ...globalFilterState,
+ {
+ type: "string",
+ column: "type",
+ operator: "=",
+ value: "GENERATION",
+ },
+ ],
+ groupBy: [{ type: "string", column: "name" }],
+ orderBy: [
+ { column: "duration", agg: "95thPercentile", direction: "DESC" },
+ ],
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const spansLatencies = api.dashboard.chart.useQuery(
+ {
+ projectId,
+ from: "observations",
+ select: [
+ { column: "duration", agg: "50thPercentile" },
+ { column: "duration", agg: "90thPercentile" },
+ { column: "duration", agg: "95thPercentile" },
+ { column: "duration", agg: "99thPercentile" },
+ { column: "name" },
+ ],
+ filter: [
+ ...globalFilterState,
+ {
+ type: "string",
+ column: "type",
+ operator: "=",
+ value: "SPAN",
+ },
+ ],
+ groupBy: [{ type: "string", column: "name" }],
+ orderBy: [
+ { column: "duration", agg: "95thPercentile", direction: "DESC" },
+ ],
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const tracesLatencies = api.dashboard.chart.useQuery(
+ {
+ projectId,
+ from: "traces_metrics",
+ select: [
+ { column: "duration", agg: "50thPercentile" },
+ { column: "duration", agg: "90thPercentile" },
+ { column: "duration", agg: "95thPercentile" },
+ { column: "duration", agg: "99thPercentile" },
+ { column: "traceName" },
+ ],
+ filter: [...createTracesTimeFilter(globalFilterState)],
+ groupBy: [{ type: "string", column: "traceName" }],
+ orderBy: [
+ { column: "duration", agg: "95thPercentile", direction: "DESC" },
+ ],
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const generateLatencyData = (data?: DatabaseRow[]) => {
+ return data
+ ? data
+ .filter((item) => item.name !== null)
+ .map((item, i) => [
+ truncate(item.name as string),
+ ...[
+ "percentile50Duration",
+ "percentile90Duration",
+ "percentile95Duration",
+ "percentile99Duration",
+ ].map((percentile) => (
+ <RightAlignedCell key={`${i}-${percentile}`}>
+ {item[percentile]
+ ? formatIntervalSeconds(item[percentile] as number, 3)
+ : "-"}
+ </RightAlignedCell>
+ )),
+ ])
+ : [];
+ };
+
+ return (
+ <>
+ <DashboardCard
+ className="col-span-1 xl:col-span-2"
+ title="Trace latencies"
+ isLoading={tracesLatencies.isLoading}
+ >
+ <DashboardTable
+ headers={[
+ "Trace Name",
+ <RightAlignedCell key="50th">50th</RightAlignedCell>,
+ <RightAlignedCell key="90th">90th</RightAlignedCell>,
+ <RightAlignedCell key="95th">
+ 95th<span className="ml-1">â–¼</span>
+ </RightAlignedCell>,
+ <RightAlignedCell key="99th">99th</RightAlignedCell>,
+ ]}
+ rows={generateLatencyData(
+ tracesLatencies.data
+ ?.filter((item) => item.traceName !== null)
+ .map((item) => {
+ return { ...item, name: item.traceName as string };
+ }),
+ )}
+ collapse={{ collapsed: 5, expanded: 20 }}
+ />
+ </DashboardCard>
+ <DashboardCard
+ className="col-span-1 xl:col-span-2"
+ title="Generation latencies"
+ isLoading={generationsLatencies.isLoading}
+ >
+ <DashboardTable
+ headers={[
+ "Generation Name",
+ <RightAlignedCell key="50th">50th</RightAlignedCell>,
+ <RightAlignedCell key="90th">90th</RightAlignedCell>,
+ <RightAlignedCell key="95th">
+ 95th<span className="ml-1">â–¼</span>
+ </RightAlignedCell>,
+ <RightAlignedCell key="99th">99th</RightAlignedCell>,
+ ]}
+ rows={generateLatencyData(generationsLatencies.data)}
+ collapse={{ collapsed: 5, expanded: 20 }}
+ />
+ </DashboardCard>
+ <DashboardCard
+ className="col-span-1 xl:col-span-2"
+ title="Span latencies"
+ isLoading={spansLatencies.isLoading}
+ >
+ <DashboardTable
+ headers={[
+ "Span Name",
+ <RightAlignedCell key="50th">50th</RightAlignedCell>,
+ <RightAlignedCell key="90th">90th</RightAlignedCell>,
+ <RightAlignedCell key="95th">
+ 95th<span className="ml-1">â–¼</span>
+ </RightAlignedCell>,
+ <RightAlignedCell key="99th">99th</RightAlignedCell>,
+ ]}
+ rows={generateLatencyData(spansLatencies.data)}
+ collapse={{ collapsed: 5, expanded: 20 }}
+ />
+ </DashboardCard>
+ </>
+ );
+};
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index d7b19ca49f..6bb90a45fb 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -34,7 +34,7 @@ export const UserChart = ({
const user = api.dashboard.chart.useQuery(
{
projectId,
- from: "traces_observations",
+ from: "traces_observationsview",
select: [
{ column: "calculatedTotalCost", agg: "SUM" },
{ column: "user" },
diff --git a/web/src/features/filters/server/filterToPrisma.ts b/web/src/features/filters/server/filterToPrisma.ts
index 267ab81488..5893c43fd0 100644
--- a/web/src/features/filters/server/filterToPrisma.ts
+++ b/web/src/features/filters/server/filterToPrisma.ts
@@ -21,6 +21,9 @@ const arrayOperatorReplacements = {
"none of": "&&",
};
+/**
+ * SECURITY: This function must only be used, when all its inputs were verified with zod.
+ */
export function tableColumnsToSqlFilterAndPrefix(
filters: FilterState,
tableColumns: ColumnDefinition[],
@@ -33,6 +36,10 @@ export function tableColumnsToSqlFilterAndPrefix(
return Prisma.join([Prisma.raw("AND "), sql], "");
}
+/**
+ * SECURITY: This function must only be used, when all its inputs were verified with zod.
+ * Converts filter state and table columns to a Prisma SQL filter.
+ */
export function tableColumnsToSqlFilter(
filters: FilterState,
tableColumns: ColumnDefinition[],
@@ -138,7 +145,9 @@ export function tableColumnsToSqlFilter(
if (statements.length === 0) {
return Prisma.empty;
}
-
+ // FOR SECURITY: We join the statements with " AND " to prevent SQL injection.
+ // IF WE EVER CHANGE THIS, WE MUST ENSURE THAT USERS ONLY ACCESS THE DATA THEY ARE ALLOWED TO.
+ // Example: Or condition on charts API on projectId would break this.
return Prisma.join(statements, " AND ");
}
@@ -149,6 +158,7 @@ const castValueToPostgresTypes = (
return column.name === "type" &&
(table === "observations" ||
table === "traces_observations" ||
+ table === "traces_observationsview" ||
table === "traces_parent_observation_scores")
? Prisma.sql`::"ObservationType"`
: Prisma.empty;
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index f997be8ff3..610bb4c00d 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import Header from "@/src/components/layouts/header";
import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";
import { useRouter } from "next/router";
-import { LatencyChart } from "@/src/features/dashboard/components/LatencyChart";
+import { GenerationLatencyChart } from "@/src/features/dashboard/components/LatencyChart";
import { ChartScores } from "@/src/features/dashboard/components/ChartScores";
import { TracesBarListChart } from "@/src/features/dashboard/components/TracesBarListChart";
import { MetricTable } from "@/src/features/dashboard/components/MetricTable";
@@ -32,6 +32,7 @@ import { FilterBuilder } from "@/src/features/filters/components/filter-builder"
import { type FilterState } from "@/src/features/filters/types";
import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { LatencyTables } from "@/src/features/dashboard/components/SpanLatencyTable";
export type DashboardDateRange = {
from: Date;
@@ -127,7 +128,7 @@ export default function Start() {
<div className="md:container">
<Header title={project?.name ?? "Dashboard"} />
<div className="my-3 flex flex-wrap items-center justify-between gap-2">
- <div className=" flex flex-col gap-2 lg:flex-row">
+ <div className=" flex flex-col gap-2 lg:flex-row">
<DatePickerWithRange
dateRange={dateRange}
setAgg={setAgg}
@@ -164,7 +165,7 @@ export default function Start() {
</div>
<div className="grid w-full grid-cols-1 gap-4 overflow-hidden lg:grid-cols-2 xl:grid-cols-6">
<TracesBarListChart
- className="col-span-1 xl:col-span-2 "
+ className="col-span-1 xl:col-span-2"
projectId={projectId}
globalFilterState={mergedFilterState}
/>
@@ -202,7 +203,11 @@ export default function Start() {
projectId={projectId}
globalFilterState={mergedFilterState}
/>
- <LatencyChart
+ <LatencyTables
+ projectId={projectId}
+ globalFilterState={mergedFilterState}
+ />
+ <GenerationLatencyChart
className="col-span-1 flex-auto justify-between xl:col-span-full"
projectId={projectId}
agg={agg}
diff --git a/web/src/server/api/interfaces/tableDefinition.ts b/web/src/server/api/interfaces/tableDefinition.ts
index 6f5a5331fa..b961086bf8 100644
--- a/web/src/server/api/interfaces/tableDefinition.ts
+++ b/web/src/server/api/interfaces/tableDefinition.ts
@@ -35,8 +35,10 @@ export type ColumnDefinition =
export const tableNames = [
"traces",
"traces_observations",
+ "traces_observationsview",
"observations",
"traces_scores",
+ "traces_metrics",
"traces_parent_observation_scores",
"sessions",
] as const;
diff --git a/web/src/server/api/services/query-builder.ts b/web/src/server/api/services/query-builder.ts
index 7ee3cb3564..8dadaf7986 100644
--- a/web/src/server/api/services/query-builder.ts
+++ b/web/src/server/api/services/query-builder.ts
@@ -31,7 +31,6 @@ export const executeQuery = async (
) => {
const query = sqlInterface.parse(unsafeQuery);
const sql = enrichAndCreateQuery(projectId, query);
-
const response = await prisma.$queryRaw<InternalDatabaseRow[]>(sql);
const parsedResult = outputParser(response);
@@ -335,8 +334,8 @@ const getColumnDefinition = (
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}`);
+ console.error(`Column "${column}" not found in table ${table}`);
+ throw new Error(`Column "${column}" not found in table ${table}`);
}
return foundColumn;
};
@@ -399,8 +398,10 @@ const getMandatoryFilter = (
switch (table) {
case "traces":
case "traces_scores":
+ case "traces_metrics":
return [traceFilter];
case "traces_observations":
+ case "traces_observationsview":
case "traces_parent_observation_scores":
return [traceFilter, observationFilter];
case "observations":
diff --git a/web/src/server/api/services/sqlInterface.ts b/web/src/server/api/services/sqlInterface.ts
index e3d32ff139..ca2205bb02 100644
--- a/web/src/server/api/services/sqlInterface.ts
+++ b/web/src/server/api/services/sqlInterface.ts
@@ -54,6 +54,8 @@ export const sqlInterface = z.object({
"observations",
"traces_scores",
"traces_parent_observation_scores",
+ "traces_observationsview",
+ "traces_metrics",
]),
filter: filterInterface.optional(),
groupBy: groupByInterface.optional(),
diff --git a/web/src/server/api/services/tableDefinitions.ts b/web/src/server/api/services/tableDefinitions.ts
index f75dfe73e3..c02fb18fff 100644
--- a/web/src/server/api/services/tableDefinitions.ts
+++ b/web/src/server/api/services/tableDefinitions.ts
@@ -1,4 +1,7 @@
-import { type TableDefinitions } from "@/src/server/api/interfaces/tableDefinition";
+import {
+ type ColumnDefinition,
+ type TableDefinitions,
+} from "@/src/server/api/interfaces/tableDefinition";
export const completionTokens = {
name: "completionTokens",
@@ -93,36 +96,44 @@ export const calculatedTotalCost = {
internal: 'o."calculated_total_cost"',
} as const;
+const tracesObservationsColumns: ColumnDefinition[] = [
+ traceId,
+ observationId,
+ { name: "type", type: "string", internal: 'o."type"' },
+ tracesProjectId,
+ observationsProjectId,
+ duration,
+ totalTokens,
+ model,
+ traceTimestamp,
+ traceUser,
+ startTime,
+ traceName,
+ observationName,
+];
+
+const tracesColumns = [
+ tracesProjectId,
+ traceVersion,
+ release,
+ traceId,
+ traceTimestamp,
+ traceName,
+ traceUser,
+];
+
export const tableDefinitions: TableDefinitions = {
traces: {
table: ` traces t`,
- columns: [
- tracesProjectId,
- traceVersion,
- release,
- traceId,
- traceTimestamp,
- traceName,
- traceUser,
- ],
+ columns: tracesColumns,
},
traces_observations: {
+ table: ` traces t LEFT JOIN observations o ON t.id = o.trace_id`,
+ columns: tracesObservationsColumns,
+ },
+ traces_observationsview: {
table: ` traces t LEFT JOIN observations_view o ON t.id = o.trace_id`,
- columns: [
- traceId,
- observationId,
- { name: "type", type: "string", internal: 'o."type"' },
- tracesProjectId,
- observationsProjectId,
- duration,
- calculatedTotalCost,
- totalTokens,
- model,
- traceTimestamp,
- traceUser,
- startTime,
- traceName,
- ],
+ columns: [...tracesObservationsColumns, calculatedTotalCost],
},
observations: {
table: ` observations_view o`,
@@ -146,6 +157,13 @@ export const tableDefinitions: TableDefinitions = {
duration,
],
},
+ traces_metrics: {
+ table: `traces t LEFT JOIN trace_metrics_view tv ON t.id = tv.id`,
+ columns: [
+ ...tracesColumns,
+ { name: "duration", type: "number", internal: '"duration"' },
+ ],
+ },
traces_scores: {
table: ` traces t JOIN scores s ON t.id = s.trace_id`,
columns: [
@@ -165,6 +183,7 @@ export const tableDefinitions: TableDefinitions = {
traceName,
],
},
+
traces_parent_observation_scores: {
table: ` traces t LEFT JOIN observations_view 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: [
diff --git a/web/src/utils/dates.ts b/web/src/utils/dates.ts
index 74401a6424..1755afe190 100644
--- a/web/src/utils/dates.ts
+++ b/web/src/utils/dates.ts
@@ -18,7 +18,7 @@ export const setEndOfDay = (date: Date) => {
export const intervalInSeconds = (start: Date, end: Date | null) =>
end ? (end.getTime() - start.getTime()) / 1000 : 0;
-export const formatIntervalSeconds = (seconds: number) => {
+export const formatIntervalSeconds = (seconds: number, scale: number = 2) => {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
@@ -26,5 +26,5 @@ export const formatIntervalSeconds = (seconds: number) => {
if (hrs > 0) return `${hrs}h ${pad(mins)}m ${pad(secs)}s`;
if (mins > 0) return `${mins}m ${pad(secs)}s`;
- return `${seconds.toFixed(2)}s`;
+ return `${seconds.toFixed(scale)}s`;
};
diff --git a/web/src/utils/string.ts b/web/src/utils/string.ts
index d3c6a336c1..1efce89279 100644
--- a/web/src/utils/string.ts
+++ b/web/src/utils/string.ts
@@ -2,6 +2,14 @@ export function lastCharacters(str: string, n: number) {
return str.substring(str.length - n);
}
+export function truncate(str: string, n: number = 10) {
+ // '...' suffix if the string is longer than n
+ if (str.length > n) {
+ return str.substring(0, n) + "...";
+ }
+ return str;
+}
+
export function extractVariables(mustacheString: string): string[] {
// Regular expression to match Mustache variables
const regex: RegExp = /\{\{(.*?)\}\}/g;