Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

Nested trace ui (#58)

Marc Klingen4e0856e83cf2
diff --git a/next.config.mjs b/next.config.mjs
index c55188b9e8..d3cb9f3c14 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -9,7 +9,6 @@ import { withSentryConfig } from "@sentry/nextjs";
/** @type {import("next").NextConfig} */
const nextConfig = {
reactStrictMode: true,
- // trailingSlash: true, // used to parse dynamic routes in logs/analytics
/**
* If you have `experimental: { appDir: true }` set, then you must comment the below `i18n` config
diff --git a/src/components/grouped-score-badge.tsx b/src/components/grouped-score-badge.tsx
new file mode 100644
index 0000000000..b747a17185
--- /dev/null
+++ b/src/components/grouped-score-badge.tsx
@@ -0,0 +1,23 @@
+import { Badge } from "@/src/components/ui/badge";
+import { type Score } from "@prisma/client";
+
+export const GroupedScoreBadges = (props: { scores: Score[] }) => {
+ const groupedScores = props.scores.reduce((acc, score) => {
+ if (!acc[score.name] || !Array.isArray(acc[score.name])) {
+ acc[score.name] = [score];
+ } else {
+ (acc[score.name] as Score[]).push(score);
+ }
+ return acc;
+ }, {} as Record<string, Score[]>);
+
+ return (
+ <>
+ {Object.entries(groupedScores).map(([name, scores]) => (
+ <Badge variant="outline" key={name} className="break-all font-normal">
+ {name}: {scores.map((s) => s.value).join(", ")}
+ </Badge>
+ ))}
+ </>
+ );
+};
diff --git a/src/components/layouts/header.tsx b/src/components/layouts/header.tsx
index fcc3ceba8f..96a0a63dfe 100644
--- a/src/components/layouts/header.tsx
+++ b/src/components/layouts/header.tsx
@@ -32,7 +32,7 @@ export default function Header(props: {
<nav className="hidden sm:flex" aria-label="Breadcrumb">
<ol role="list" className="flex items-center space-x-4">
{props.breadcrumb.map(({ name, href }, index) => (
- <li key={href}>
+ <li key={index}>
<div className="flex items-center">
{index !== 0 && (
<ChevronRightIcon
diff --git a/src/components/observation-display.tsx b/src/components/observation-display.tsx
deleted file mode 100644
index fefe848f4d..0000000000
--- a/src/components/observation-display.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import { type NestedObservation } from "@/src/utils/types";
-import { JSONView } from "@/src/components/ui/code";
-import { formatDate } from "@/src/utils/dates";
-import Link from "next/link";
-import { Fragment } from "react";
-import { cn } from "@/src/utils/tailwind";
-
-export default function ObservationDisplay(props: {
- observations: NestedObservation[];
- projectId: string;
-}) {
- return (
- <div className="flex flex-col">
- <Observation
- observations={props.observations}
- projectId={props.projectId}
- indentationLevel={0}
- />
- </div>
- );
-}
-
-const Observation = (props: {
- observations: NestedObservation[];
- projectId: string;
- indentationLevel: number;
-}) => (
- <>
- {props.observations
- .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
- .map((observation) => (
- <Fragment key={observation.id}>
- <div className="flex items-start border-t py-1" key={observation.id}>
- <div className="flex w-1/4">
- <ObservationInfo
- observation={observation}
- projectId={props.projectId}
- />
- </div>
-
- <div className="ml-4 grid w-3/4 grid-cols-12">
- <div className={`col-span-${props.indentationLevel}`}> </div>
-
- <div
- className={`flex flex-col col-span-${
- 12 - props.indentationLevel
- } gap-1`}
- >
- {observation.input ? (
- <JSONView
- json={observation.input}
- defaultCollapsed
- label="Input"
- className={cn(LevelColor[observation.level].bg)}
- />
- ) : null}
- {observation.statusMessage ? (
- <JSONView
- json={observation.statusMessage}
- defaultCollapsed
- label="Status Message"
- className={cn(LevelColor[observation.level].bg)}
- />
- ) : null}
- {observation.children.length === 0 && observation.output ? (
- <JSONView
- json={observation.output}
- defaultCollapsed
- label="Output"
- className={cn(LevelColor[observation.level].bg)}
- />
- ) : null}
- </div>
- </div>
- </div>
-
- <Observation
- observations={observation.children}
- projectId={props.projectId}
- indentationLevel={props.indentationLevel + 1}
- />
-
- {observation.children.length > 0 && observation.output ? (
- <div
- className="flex items-start border-t py-1"
- key={observation.id}
- >
- <div className="flex w-1/4" />
- <div className="ml-4 grid w-3/4 grid-cols-12">
- <div className={`col-span-${props.indentationLevel}`}> </div>
- <div className={`col-span-${12 - props.indentationLevel}`}>
- <JSONView
- json={observation.output}
- defaultCollapsed
- label="Output"
- className={cn(LevelColor[observation.level].bg)}
- />
- </div>
- </div>
- </div>
- ) : null}
- </Fragment>
- ))}
- </>
-);
-
-const ObservationInfo = (props: {
- observation: NestedObservation;
- projectId: string;
-}) => {
- return (
- <>
- <div className="flex-auto overflow-hidden break-all ">
- <div className="relative flex flex-col gap-x-4">
- <div className="relative flex py-0.5 text-xs leading-5 text-gray-500">
- {props.observation.type === "GENERATION" ? (
- <Link
- href={`/project/${props.projectId}/generations/${props.observation.id}`}
- className="overflow-hidden font-medium text-gray-900 hover:text-gray-500"
- >
- {props.observation.type}: {props.observation.name} β†—
- </Link>
- ) : (
- <span className="overflow-hidden font-medium text-gray-900">
- {props.observation.type}: {props.observation.name}
- </span>
- )}
- </div>
- {props.observation.startTime ? (
- <div className="flex">
- <time
- dateTime={props.observation.startTime.toString()}
- className="flex-none py-0.5 text-xs leading-5 text-gray-500"
- >
- {formatDate(props.observation.startTime)}
- </time>
- {props.observation.endTime ? (
- <p className="whitespace-nowrap py-0.5 text-xs leading-5 text-gray-500">
- &nbsp;-&nbsp;
- {props.observation.endTime.getTime() -
- props.observation.startTime.getTime()}{" "}
- ms
- </p>
- ) : undefined}
- </div>
- ) : undefined}
- </div>
- {props.observation.type === "GENERATION" ? (
- <p className="text-xs leading-5 text-gray-500">
- {`${props.observation.promptTokens} β†’ ${props.observation.completionTokens} (βˆ‘ ${props.observation.totalTokens})`}
- </p>
- ) : undefined}
- {props.observation.level !== "DEFAULT" ? (
- <div
- className={cn(
- "text-xs leading-5",
- LevelColor[props.observation.level].text
- )}
- >
- {props.observation.level}
- </div>
- ) : null}
- </div>
- </>
- );
-};
-
-const LevelColor = {
- DEFAULT: { text: "", bg: "" },
- DEBUG: { text: "text-gray-500", bg: "bg-gray-50" },
- WARNING: { text: "text-yellow-800", bg: "bg-yellow-50" },
- ERROR: { text: "text-red-800", bg: "bg-red-50" },
-};
diff --git a/src/components/table/data-table-toolbar.tsx b/src/components/table/data-table-toolbar.tsx
index f1076d364b..71e9a32ffc 100644
--- a/src/components/table/data-table-toolbar.tsx
+++ b/src/components/table/data-table-toolbar.tsx
@@ -65,12 +65,14 @@ export function DataTableToolbar<TData, TValue>({
return column.enableColumnFilter && columnOptions ? (
column.meta?.filter?.type === "select" ? (
<DataTableSelectFilter
+ key={column.meta.label}
title={column.meta?.label}
meta={column.meta?.filter}
options={columnOptions}
/>
) : column.meta?.filter?.type === "number-comparison" ? (
<DataTableNumberFilter
+ key={column.meta.label}
title={column.meta?.label}
meta={column.meta?.filter}
options={columnOptions}
diff --git a/src/components/token-usage-badge.tsx b/src/components/token-usage-badge.tsx
new file mode 100644
index 0000000000..98111189fa
--- /dev/null
+++ b/src/components/token-usage-badge.tsx
@@ -0,0 +1,44 @@
+import { Badge } from "@/src/components/ui/badge";
+import { type Observation } from "@prisma/client";
+
+export const TraceAggUsageBadge = (props: { observations: Observation[] }) => {
+ const usage = {
+ promptTokens: props.observations
+ .map((o) => o.promptTokens)
+ .reduce((a, b) => a + b, 0),
+ completionTokens: props.observations
+ .map((o) => o.completionTokens)
+ .reduce((a, b) => a + b, 0),
+ totalTokens: props.observations
+ .map((o) => o.totalTokens)
+ .reduce((a, b) => a + b, 0),
+ };
+ return <TokenUsageBadge {...usage} />;
+};
+
+export const TokenUsageBadge = (
+ props:
+ | {
+ observation: Observation;
+ }
+ | {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ }
+) => {
+ const usage =
+ "observation" in props
+ ? {
+ promptTokens: props.observation.promptTokens,
+ completionTokens: props.observation.completionTokens,
+ totalTokens: props.observation.totalTokens,
+ }
+ : props;
+
+ return (
+ <Badge variant="outline">
+ {usage.promptTokens} β†’ {usage.completionTokens} (βˆ‘ {usage.totalTokens})
+ </Badge>
+ );
+};
diff --git a/src/components/trace-display.tsx b/src/components/trace-display.tsx
new file mode 100644
index 0000000000..009003405c
--- /dev/null
+++ b/src/components/trace-display.tsx
@@ -0,0 +1,420 @@
+import { type NestedObservation } from "@/src/utils/types";
+import { JSONView } from "@/src/components/ui/code";
+import { formatDate } from "@/src/utils/dates";
+import { cn } from "@/src/utils/tailwind";
+import { type Trace, type Observation, type Score } from "@prisma/client";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/src/components/ui/card";
+import { Badge } from "@/src/components/ui/badge";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import { useRouter } from "next/router";
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
+import { Fragment } from "react";
+
+export default function TraceDisplay(props: {
+ observations: Observation[];
+ trace: Trace;
+ scores: Score[];
+ projectId: string;
+}) {
+ const router = useRouter();
+ const currentObservationId = router.query.observation as string | undefined;
+ const setCurrentObservationId = (id: string | undefined) => {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { observation, ...query } = router.query;
+ void router.replace(
+ {
+ pathname: router.pathname,
+ query: {
+ ...query,
+ ...(id !== undefined ? { observation: id } : {}),
+ },
+ },
+ undefined,
+ {
+ scroll: false,
+ }
+ );
+ };
+
+ console.log("currentObservationId", currentObservationId);
+
+ return (
+ <div className="flex flex-col gap-8 md:flex-row-reverse">
+ <ObservationTree
+ observations={props.observations}
+ trace={props.trace}
+ scores={props.scores}
+ currentObservationId={currentObservationId}
+ setCurrentObservationId={setCurrentObservationId}
+ />
+
+ {currentObservationId === undefined || currentObservationId === "" ? (
+ <TracePreview
+ trace={props.trace}
+ observations={props.observations}
+ scores={props.scores}
+ />
+ ) : (
+ <ObservationPreview
+ observations={props.observations}
+ scores={props.scores}
+ projectId={props.projectId}
+ currentObservationId={currentObservationId}
+ />
+ )}
+ </div>
+ );
+}
+
+const ObservationTree = (props: {
+ observations: Observation[];
+ trace: Trace;
+ scores: Score[];
+ currentObservationId: string | undefined;
+ setCurrentObservationId: (id: string | undefined) => void;
+}) => {
+ const nestedObservations = nestObservations(props.observations);
+ return (
+ <div className="flex flex-col">
+ <ObservationTreeTraceNode
+ trace={props.trace}
+ scores={props.scores}
+ currentObservationId={props.currentObservationId}
+ setCurrentObservationId={props.setCurrentObservationId}
+ />
+ <ObservationTreeNode
+ observations={nestedObservations}
+ scores={props.scores}
+ indentationLevel={1}
+ currentObservationId={props.currentObservationId}
+ setCurrentObservationId={props.setCurrentObservationId}
+ />
+ </div>
+ );
+};
+
+const ObservationTreeTraceNode = (props: {
+ trace: Trace;
+ scores: Score[];
+ currentObservationId: string | undefined;
+ setCurrentObservationId: (id: string | undefined) => void;
+}) => (
+ <div
+ className={cn(
+ "group my-1 flex cursor-pointer flex-col gap-1 rounded-sm p-2",
+ props.currentObservationId === undefined ||
+ props.currentObservationId === ""
+ ? "bg-gray-100"
+ : "hover:bg-gray-50"
+ )}
+ onClick={() => props.setCurrentObservationId(undefined)}
+ >
+ <div className="flex gap-2">
+ <span className={cn("rounded-sm bg-gray-200 p-1 text-xs")}>TRACE</span>
+ <span>{props.trace.name}</span>
+ </div>
+ <div className="flex gap-2">
+ <span className="text-xs text-gray-500">
+ {formatDate(props.trace.timestamp)}
+ </span>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {props.scores.find((s) => s.observationId === null) ? (
+ <GroupedScoreBadges
+ scores={props.scores.filter((s) => s.observationId === null)}
+ />
+ ) : null}
+ </div>
+ </div>
+);
+
+const ObservationTreeNode = (props: {
+ observations: NestedObservation[];
+ scores: Score[];
+ indentationLevel: number;
+ currentObservationId: string | undefined;
+ setCurrentObservationId: (id: string | undefined) => void;
+}) => (
+ <>
+ {props.observations
+ .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
+ .map((observation) => (
+ <Fragment key={observation.id}>
+ <div className="flex">
+ {Array.from({ length: props.indentationLevel }, (_, i) => (
+ <div className="mx-2 border-r" key={i} />
+ ))}
+ <div
+ className={cn(
+ "group my-1 flex flex-1 cursor-pointer flex-col gap-1 rounded-sm p-2 ",
+ props.currentObservationId === observation.id
+ ? "bg-gray-100"
+ : "hover:bg-gray-50"
+ )}
+ onClick={() => props.setCurrentObservationId(observation.id)}
+ >
+ <div className="flex gap-2">
+ <span className={cn("rounded-sm bg-gray-200 p-1 text-xs")}>
+ {observation.type}
+ </span>
+ <span>{observation.name}</span>
+ </div>
+ <div className="flex gap-2">
+ {observation.endTime ? (
+ <span className="text-xs text-gray-500">
+ {observation.endTime.getTime() -
+ observation.startTime.getTime()}{" "}
+ ms
+ </span>
+ ) : null}
+ <span className="text-xs text-gray-500">
+ {observation.promptTokens} β†’ {observation.completionTokens} (βˆ‘{" "}
+ {observation.totalTokens})
+ </span>
+ </div>
+ {observation.level !== "DEFAULT" ? (
+ <div className="flex">
+ <span
+ className={cn(
+ "rounded-sm text-xs",
+ LevelColor[observation.level].bg,
+ LevelColor[observation.level].text
+ )}
+ >
+ {observation.level}
+ </span>
+ </div>
+ ) : null}
+ {props.scores.find((s) => s.observationId === observation.id) ? (
+ <div className="flex flex-wrap gap-2">
+ <GroupedScoreBadges
+ scores={props.scores.filter(
+ (s) => s.observationId === observation.id
+ )}
+ />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ <ObservationTreeNode
+ observations={observation.children}
+ scores={props.scores}
+ indentationLevel={props.indentationLevel + 1}
+ currentObservationId={props.currentObservationId}
+ setCurrentObservationId={props.setCurrentObservationId}
+ />
+ </Fragment>
+ ))}
+ </>
+);
+
+const ObservationPreview = (props: {
+ observations: Observation[];
+ projectId: string;
+ scores: Score[];
+ currentObservationId: string | undefined;
+}) => {
+ const observation = props.observations.find(
+ (o) => o.id === props.currentObservationId
+ );
+ if (!observation) return <div className="flex-1">Not found</div>;
+ return (
+ <Card className="flex-1">
+ <CardHeader>
+ <CardTitle>
+ <span className="mr-2 rounded-sm bg-gray-200 p-1 text-xs">
+ {observation.type}
+ </span>
+ <span>{observation.name}</span>
+ </CardTitle>
+ <CardDescription className="flex gap-2">
+ {observation.startTime.toLocaleString()}
+ </CardDescription>
+ <div className="flex flex-wrap gap-2">
+ {observation.endTime ? (
+ <Badge variant="outline">
+ {`${
+ observation.endTime.getTime() - observation.startTime.getTime()
+ } ms`}
+ </Badge>
+ ) : null}
+ <Badge variant="outline">
+ {observation.promptTokens} prompt β†’ {observation.completionTokens}{" "}
+ completion (βˆ‘ {observation.totalTokens})
+ </Badge>
+ {observation.model ? (
+ <Badge variant="outline">{observation.model}</Badge>
+ ) : null}
+ {observation.modelParameters &&
+ typeof observation.modelParameters === "object"
+ ? Object.entries(observation.modelParameters)
+ .filter(Boolean)
+ .map(([key, value]) => (
+ <Badge variant="outline" key={key}>
+ {key}: {value?.toString()}
+ </Badge>
+ ))
+ : null}
+ </div>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <JSONView
+ title={observation.type === "GENERATION" ? "Prompt" : "Input"}
+ json={observation.input}
+ scrollable
+ />
+ <JSONView
+ title={observation.type === "GENERATION" ? "Completion" : "Output"}
+ json={observation.output}
+ scrollable
+ />
+ <JSONView title="Status Message" json={observation.statusMessage} />
+ <JSONView title="Metadata" json={observation.metadata} />
+ {props.scores.find((s) => s.observationId === observation.id) ? (
+ <div className="flex flex-col gap-2">
+ <h3>Scores</h3>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[100px]">Timestamp</TableHead>
+ <TableHead>Name</TableHead>
+ <TableHead className="text-right">Value</TableHead>
+ <TableHead>Comment</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {props.scores
+ .filter((s) => s.observationId === observation.id)
+ .map((s) => (
+ <TableRow key={s.id}>
+ <TableCell className="text-xs">
+ {s.timestamp.toLocaleString()}
+ </TableCell>
+ <TableCell className="text-xs">{s.name}</TableCell>
+ <TableCell className="text-right text-xs">
+ {s.value}
+ </TableCell>
+ <TableCell className="text-xs">{s.comment}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ ) : null}
+ </CardContent>
+ </Card>
+ );
+};
+
+const TracePreview = ({
+ trace,
+ observations,
+ scores,
+}: {
+ trace: Trace;
+ observations: Observation[];
+ scores: Score[];
+}) => {
+ return (
+ <Card className="flex-1">
+ <CardHeader>
+ <CardTitle>
+ <span className="mr-2 rounded-sm bg-gray-200 p-1 text-xs">TRACE</span>
+ <span>{trace.name}</span>
+ </CardTitle>
+ <CardDescription>{trace.timestamp.toLocaleString()}</CardDescription>
+ <div className="flex flex-wrap gap-2">
+ <TraceAggUsageBadge observations={observations} />
+ </div>
+ </CardHeader>
+ <CardContent>
+ <JSONView title="Metadata" json={trace.metadata} scrollable />
+ {scores.find((s) => s.observationId === null) ? (
+ <div className="mt-5 flex flex-col gap-2">
+ <h3>Scores</h3>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[100px]">Timestamp</TableHead>
+ <TableHead>Name</TableHead>
+ <TableHead className="text-right">Value</TableHead>
+ <TableHead>Comment</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {scores
+ .filter((s) => s.observationId === null)
+ .map((s) => (
+ <TableRow key={s.id}>
+ <TableCell className="text-xs">
+ {s.timestamp.toLocaleString()}
+ </TableCell>
+ <TableCell className="text-xs">{s.name}</TableCell>
+ <TableCell className="text-right text-xs">
+ {s.value}
+ </TableCell>
+ <TableCell className="text-xs">{s.comment}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ ) : null}
+ </CardContent>
+ <CardFooter></CardFooter>
+ </Card>
+ );
+};
+
+const LevelColor = {
+ DEFAULT: { text: "", bg: "" },
+ DEBUG: { text: "text-gray-500", bg: "bg-gray-50" },
+ WARNING: { text: "text-yellow-800", bg: "bg-yellow-50" },
+ ERROR: { text: "text-red-800", bg: "bg-red-50" },
+};
+
+function nestObservations(list: Observation[]): NestedObservation[] {
+ if (list.length === 0) return [];
+
+ // Step 1: Create a map where the keys are object IDs, and the values are
+ // the corresponding objects with an added 'children' property.
+ const map = new Map<string, NestedObservation>();
+ for (const obj of list) {
+ map.set(obj.id, { ...obj, children: [] });
+ }
+
+ // Step 2: Create another map for the roots of all trees.
+ const roots = new Map<string, NestedObservation>();
+
+ // Step 3: Populate the 'children' arrays and root map.
+ for (const obj of map.values()) {
+ if (obj.parentObservationId) {
+ const parent = map.get(obj.parentObservationId);
+ if (parent) {
+ parent.children.push(obj);
+ }
+ } else {
+ roots.set(obj.id, obj);
+ }
+ }
+
+ // TODO sum token amounts per level
+
+ // Step 4: Return the roots.
+ return Array.from(roots.values());
+}
diff --git a/src/components/ui/code.tsx b/src/components/ui/code.tsx
index 31ed006a11..1a8774f84a 100644
--- a/src/components/ui/code.tsx
+++ b/src/components/ui/code.tsx
@@ -6,7 +6,8 @@ import { cn } from "@/src/utils/tailwind";
export function JSONView(props: {
json: string | unknown;
defaultCollapsed?: boolean;
- label?: string;
+ scrollable?: boolean;
+ title?: string;
className?: string;
}) {
const text =
@@ -18,7 +19,8 @@ export function JSONView(props: {
<CodeView
content={text}
defaultCollapsed={props.defaultCollapsed}
- label={props.label}
+ scrollable={props.scrollable}
+ title={props.title}
className={props.className}
/>
);
@@ -28,7 +30,8 @@ export function CodeView(props: {
content: string | undefined | null;
className?: string;
defaultCollapsed?: boolean;
- label?: string;
+ scrollable?: boolean;
+ title?: string;
}) {
const [isCopied, setIsCopied] = useState(false);
const [isCollapsed, setCollapsed] = useState(props.defaultCollapsed);
@@ -42,49 +45,41 @@ export function CodeView(props: {
const handleShowAll = () => setCollapsed(!isCollapsed);
return (
- <div
- className={cn(
- "relative max-w-full rounded-md border px-4 py-3 pr-12",
- props.className
- )}
- >
- {props.label ? (
- <div className="text-xs font-medium">{props.label}</div>
+ <div className={cn("max-w-full rounded-md border ", props.className)}>
+ {props.title ? (
+ <div className="border-b px-4 py-1 text-xs font-medium">
+ {props.title}
+ </div>
) : undefined}
- <code
- className={cn(
- "whitespace-pre-wrap break-words font-mono text-xs",
- isCollapsed ? `line-clamp-4` : "block"
- )}
- >
- {props.content}
- {props.defaultCollapsed ? (
- <Button
- className="absolute right-12 top-2"
- variant="secondary"
- size="xs"
- onClick={handleShowAll}
- >
- {isCollapsed ? (
- <ChevronsUpDown className="h-3 w-3" />
+ <div className="flex gap-2">
+ <code
+ className={cn(
+ "relative flex-1 whitespace-pre-wrap break-words px-4 py-3 font-mono text-xs",
+ isCollapsed ? `line-clamp-4` : "block",
+ props.scrollable ? "max-h-60 overflow-y-scroll" : undefined
+ )}
+ >
+ {props.content}
+ </code>
+ <div className="flex gap-2 py-2 pr-2">
+ {props.defaultCollapsed ? (
+ <Button variant="secondary" size="xs" onClick={handleShowAll}>
+ {isCollapsed ? (
+ <ChevronsUpDown className="h-3 w-3" />
+ ) : (
+ <ChevronsDownUp className="h-3 w-3" />
+ )}
+ </Button>
+ ) : undefined}
+ <Button variant="secondary" size="xs" onClick={handleCopy}>
+ {isCopied ? (
+ <Check className="h-3 w-3" />
) : (
- <ChevronsDownUp className="h-3 w-3" />
+ <Copy className="h-3 w-3" />
)}
</Button>
- ) : undefined}
- <Button
- className="absolute right-2 top-2"
- variant="secondary"
- size="xs"
- onClick={handleCopy}
- >
- {isCopied ? (
- <Check className="h-3 w-3" />
- ) : (
- <Copy className="h-3 w-3" />
- )}
- </Button>
- </code>
+ </div>
+ </div>
</div>
);
}
diff --git a/src/components/ui/description-lists.tsx b/src/components/ui/description-lists.tsx
index bf33ab405a..733a120a52 100644
--- a/src/components/ui/description-lists.tsx
+++ b/src/components/ui/description-lists.tsx
@@ -31,7 +31,7 @@ export default function DescriptionList(props: {
{props.items.map((item) => (
<div
key={item.label}
- className={`sm:grid-cols-${totalColumns} px-4 py-6 sm:grid sm:gap-4 sm:px-0`}
+ className={`sm:grid-cols-${totalColumns} px-4 py-3 sm:grid sm:gap-4 sm:px-0`}
>
<dt className="text-sm font-medium leading-6 text-gray-900">
{item.label}
diff --git a/src/pages/project/[projectId]/generations.tsx b/src/pages/project/[projectId]/generations.tsx
index 97fddc08a3..d0c7fefc23 100644
--- a/src/pages/project/[projectId]/generations.tsx
+++ b/src/pages/project/[projectId]/generations.tsx
@@ -8,8 +8,8 @@ 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";
-// TODO Marc
type GenerationTableRow = {
id: string;
traceId: string;
@@ -17,6 +17,11 @@ type GenerationTableRow = {
endTime?: string;
name?: string;
model?: string;
+ usage: {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ };
};
export type GenerationFilterInput = Omit<
@@ -47,13 +52,15 @@ export default function Generations() {
accessorKey: "id",
header: "ID",
cell: ({ row }) => {
- const value = row.getValue("id");
- return typeof value === "string" ? (
+ const observationId = row.getValue("id");
+ const traceId = row.getValue("traceId");
+ return typeof observationId === "string" &&
+ typeof traceId === "string" ? (
<TableLink
- path={`/project/${projectId}/generations/${value}`}
- value={value}
+ path={`/project/${projectId}/traces/${traceId}?observation=${observationId}`}
+ value={observationId}
/>
- ) : undefined;
+ ) : null;
},
},
{
@@ -84,10 +91,6 @@ export default function Generations() {
accessorKey: "startTime",
header: "Start Time",
},
- {
- accessorKey: "endTime",
- header: "End Time",
- },
{
accessorKey: "name",
header: "Name",
@@ -96,6 +99,24 @@ export default function Generations() {
accessorKey: "model",
header: "Model",
},
+ {
+ accessorKey: "usage",
+ header: "Usage",
+ cell: ({ row }) => {
+ const value: {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ } = row.getValue("usage");
+ return (
+ <TokenUsageBadge
+ promptTokens={value.promptTokens}
+ completionTokens={value.completionTokens}
+ totalTokens={value.totalTokens}
+ />
+ );
+ },
+ },
];
const convertToOptions = (
@@ -132,9 +153,12 @@ export default function Generations() {
startTime: generation.startTime.toISOString(),
endTime: generation.endTime?.toISOString() ?? undefined,
name: generation.name ?? undefined,
- // prompt: JSON.stringify(generation.prompt),
- // completion: generation.completion ?? undefined,
model: JSON.stringify(generation.model),
+ usage: {
+ promptTokens: generation.promptTokens,
+ completionTokens: generation.completionTokens,
+ totalTokens: generation.totalTokens,
+ },
}))
: [];
diff --git a/src/pages/project/[projectId]/generations/[generationId].tsx b/src/pages/project/[projectId]/generations/[generationId].tsx
deleted file mode 100644
index 1f26abab23..0000000000
--- a/src/pages/project/[projectId]/generations/[generationId].tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import { Button } from "@/src/components/ui/button";
-import { CodeView, JSONView } from "@/src/components/ui/code";
-import DescriptionList from "@/src/components/ui/description-lists";
-import { ArrowUpRight } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/router";
-import Header from "@/src/components/layouts/header";
-
-import { api } from "@/src/utils/api";
-import StatsCards from "@/src/components/stats-cards";
-import { type Prisma } from "@prisma/client";
-
-export default function GenerationPage() {
- const router = useRouter();
- const generationId = router.query.generationId as string;
- const projectId = router.query.projectId as string;
-
- const generation = api.generations.byId.useQuery(generationId, {
- enabled: generationId !== undefined,
- });
-
- const obsMetrics =
- generation.data?.scores.filter(
- (score) => score.observationId === generation.data.id
- ) ?? [];
- const traceScores =
- generation.data?.scores.filter((score) => !obsMetrics?.includes(score)) ??
- [];
-
- const statProps = [
- { name: "Model", stat: generation.data?.model ?? "-" },
- {
- name: "Temperature",
- stat: generation.data?.modelParameters?.temperature?.toString() ?? "-",
- },
- {
- name: "Max Tokens",
- stat: generation.data?.modelParameters?.maxTokens?.toString() ?? "-",
- },
- {
- name: "Top P",
- stat: generation.data?.modelParameters?.topP?.toString() ?? "-",
- },
- ];
-
- const jsonOutput = generation.data?.output as Prisma.JsonObject;
-
- return (
- <div className="container">
- <Header
- title="Generation"
- breadcrumb={[
- { name: "Generations", href: `/project/${projectId}/generations` },
- { name: generationId },
- ]}
- />
- <div className="my-10">
- <StatsCards stats={statProps} />
- </div>
- {generation.data ? (
- <DescriptionList
- items={[
- {
- label: "Trace",
- value: (
- <Button variant="secondary" asChild>
- <Link
- href={`/project/${projectId}/traces/${generation.data.traceId}`}
- >
- {generation.data.traceId}
- <ArrowUpRight className="ml-2 h-4 w-4" />
- </Link>
- </Button>
- ),
- },
- {
- label: "Time",
- value: (
- <CodeView
- content={[
- `Start:\n${generation.data.startTime.toISOString()}`,
- generation.data.completionStartTime !== null
- ? "Completion start:\n" +
- generation.data.completionStartTime.toISOString()
- : null,
- generation.data.endTime
- ? "End:\n" + generation.data.endTime.toISOString()
- : null,
- "---",
- generation.data.startTime !== null &&
- generation.data.completionStartTime !== null
- ? `First completion token:\n${
- generation.data.completionStartTime.getTime() -
- generation.data.startTime.getTime()
- } ms`
- : null,
- generation.data.endTime !== null &&
- generation.data.completionStartTime !== null
- ? `Completion:\n${
- generation.data.endTime.getTime() -
- generation.data.completionStartTime.getTime()
- } ms`
- : null,
- generation.data.endTime
- ? "Total:\n" +
- `${
- generation.data.endTime.getTime() -
- generation.data.startTime.getTime()
- } ms`
- : null,
- ]
- .filter((s) => s !== null)
- .join("\n\n")}
- />
- ),
- },
- {
- label: "Name",
- value: generation.data.name,
- },
- {
- label: "Tokens",
- value: `${generation.data.promptTokens} prompt β†’ ${generation.data.completionTokens} completion (${generation.data.totalTokens} in total)`,
- },
- {
- label: "Prompt",
- value: generation.data.input ? (
- <JSONView json={generation.data.input as string} />
- ) : undefined,
- },
- {
- label: "Completion",
- value: jsonOutput ? (
- <CodeView
- content={(jsonOutput["completion"] as string) ?? undefined}
- />
- ) : (
- <></>
- ),
- },
- {
- label: "Metadata",
- value: <JSONView json={generation.data.metadata} />,
- },
- {
- label: "Metrics (observation)",
- value: (
- <DescriptionList
- items={obsMetrics.map((metric) => ({
- label: metric.name,
- value: (
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-5">
- <div className="text-sm font-bold">
- {metric.value.toString()}
- </div>
- {metric.comment !== null ? (
- <div>
- <div className="text-xs font-semibold text-gray-500">
- Comment
- </div>
- <div className="text-sm">{metric.comment}</div>
- </div>
- ) : null}
- </div>
- ),
- }))}
- />
- ),
- },
- {
- label: "Metrics (trace)",
- value: (
- <DescriptionList
- items={traceScores.map((metric) => ({
- label: metric.name,
- value: (
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-5">
- <div className="text-sm font-bold">
- {metric.value.toString()}
- </div>
- {metric.comment !== null ? (
- <div>
- <div className="text-xs font-semibold text-gray-500">
- Comment
- </div>
- <div className="text-sm">{metric.comment}</div>
- </div>
- ) : null}
- </div>
- ),
- }))}
- />
- ),
- },
- ]}
- />
- ) : null}
- </div>
- );
-}
diff --git a/src/pages/project/[projectId]/scores.tsx b/src/pages/project/[projectId]/scores.tsx
index e0cd5b0675..1eac22debc 100644
--- a/src/pages/project/[projectId]/scores.tsx
+++ b/src/pages/project/[projectId]/scores.tsx
@@ -42,27 +42,6 @@ export default function ScoresPage() {
});
const columns: ColumnDef<RowData>[] = [
- {
- accessorKey: "id",
- header: "ID",
- enableColumnFilter: true,
- cell: ({ row }) => {
- const value = row.getValue("id");
- return typeof value === "string" ? (
- <div key=".">...{lastCharacters(value, 7)}</div>
- ) : undefined;
- },
- meta: {
- label: "Id",
- filter: {
- type: "select",
- values: queryOptions.id,
- updateFunction: (newValues: string[] | null) => {
- setQueryOptions({ ...queryOptions, id: newValues });
- },
- },
- },
- },
{
accessorKey: "traceId",
enableColumnFilter: true,
@@ -89,6 +68,21 @@ export default function ScoresPage() {
},
},
},
+ {
+ accessorKey: "observationId",
+ header: "Observation ID",
+ cell: ({ row }) => {
+ const observationId = row.getValue("observationId");
+ const traceId = row.getValue("traceId");
+ return typeof observationId === "string" &&
+ typeof traceId === "string" ? (
+ <TableLink
+ path={`/project/${projectId}/traces/${traceId}?observation=${observationId}`}
+ value={observationId}
+ />
+ ) : null;
+ },
+ },
{
accessorKey: "timestamp",
header: "Timestamp",
@@ -105,10 +99,6 @@ export default function ScoresPage() {
accessorKey: "comment",
header: "Comment",
},
- {
- accessorKey: "observationId",
- header: "Observation ID",
- },
];
const convertToOptions = (
@@ -192,7 +182,3 @@ export default function ScoresPage() {
</div>
);
}
-
-function lastCharacters(str: string, n: number) {
- return str.substring(str.length - n);
-}
diff --git a/src/pages/project/[projectId]/traces.tsx b/src/pages/project/[projectId]/traces.tsx
index 136b5f9bcc..7c8723ae33 100644
--- a/src/pages/project/[projectId]/traces.tsx
+++ b/src/pages/project/[projectId]/traces.tsx
@@ -12,14 +12,10 @@ import {
type SelectedScoreFilter,
type ScoreFilter,
} from "@/src/utils/tanstack";
-import { type Trace, type Score } from "@prisma/client";
+import { type Score } from "@prisma/client";
import { lastCharacters } from "@/src/utils/string";
-
-export type TableScore = {
- id: string;
- name: string;
- value: number;
-};
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { TokenUsageBadge } from "@/src/components/token-usage-badge";
export type TraceTableRow = {
id: string;
@@ -28,7 +24,12 @@ export type TraceTableRow = {
name: string;
userId: string;
metadata?: string;
- scores: TableScore[];
+ scores: Score[];
+ usage: {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ };
};
export type TraceFilterInput = Omit<RouterInput["traces"]["all"], "projectId">;
@@ -60,7 +61,7 @@ export default function Traces() {
});
const convertToTableRow = (
- trace: Trace & { scores: Score[] }
+ trace: RouterOutput["traces"]["all"][0]
): TraceTableRow => {
return {
id: trace.id,
@@ -69,13 +70,8 @@ export default function Traces() {
name: trace.name ?? "",
metadata: JSON.stringify(trace.metadata),
userId: trace.userId ?? "",
- scores: trace.scores.map((score) => {
- return {
- name: score.name,
- value: score.value,
- id: score.id,
- };
- }),
+ scores: trace.scores,
+ usage: trace.usage,
};
};
@@ -139,8 +135,22 @@ export default function Traces() {
header: "User ID",
},
{
- accessorKey: "metadata",
- header: "Metadata",
+ accessorKey: "usage",
+ header: "Usage",
+ cell: ({ row }) => {
+ const value: {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ } = row.getValue("usage");
+ return (
+ <TokenUsageBadge
+ promptTokens={value.promptTokens}
+ completionTokens={value.completionTokens}
+ totalTokens={value.totalTokens}
+ />
+ );
+ },
},
{
accessorKey: "scores",
@@ -162,25 +172,10 @@ export default function Traces() {
},
},
cell: ({ row }) => {
- const values: TableScore[] = row.getValue("scores");
+ const values: Score[] = row.getValue("scores");
return (
- <div className="flex flex-col gap-2">
- {values.map((value) => (
- <div
- key={value.id}
- className="relative flex-row items-center rounded-lg border border-gray-300 shadow-sm"
- >
- <div className="min-w-1 flex flex-1 items-center gap-2 p-2">
- {/* <span className="absolute inset-0" aria-hidden="true" /> */}
- <p className=" text-xs font-medium text-gray-900">
- {value.name}
- </p>
- <p className="inline-flex items-baseline rounded-full bg-gray-100 px-2.5 py-0.5 text-lg font-medium text-gray-500 md:mt-2 lg:mt-0">
- {value.value}
- </p>
- </div>
- </div>
- ))}
+ <div className="flex">
+ <GroupedScoreBadges scores={values} />
</div>
);
},
diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsx
index 51894022c8..c414501130 100644
--- a/src/pages/project/[projectId]/traces/[traceId].tsx
+++ b/src/pages/project/[projectId]/traces/[traceId].tsx
@@ -1,9 +1,9 @@
import { useRouter } from "next/router";
import Header from "@/src/components/layouts/header";
import { api } from "@/src/utils/api";
-import DescriptionList from "@/src/components/ui/description-lists";
-import { JSONView } from "@/src/components/ui/code";
-import ObservationDisplay from "@/src/components/observation-display";
+import TraceDisplay from "@/src/components/trace-display";
+import { Badge } from "@/src/components/ui/badge";
+import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
export default function TracePage() {
const router = useRouter();
@@ -21,73 +21,28 @@ export default function TracePage() {
{ name: traceId },
]}
/>
- {trace.data ? (
- <DescriptionList
- descriptionColumns={1}
- valueColumns={5}
- items={[
- {
- label: "Timestamp",
- value: trace.data.timestamp.toLocaleString(),
- },
- ...(trace.data.externalId
- ? [
- {
- label: "External ID",
- value: trace.data.externalId,
- },
- ]
- : []),
- {
- label: "Name",
- value: trace.data.name,
- },
- {
- label: "User ID",
- value: trace.data.userId,
- },
- {
- label: "Metrics",
- value: (
- <DescriptionList
- items={trace.data.scores.map((metric) => ({
- label: metric.name,
- value: (
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-5">
- <div className="text-sm font-bold">
- {metric.value.toString()}
- </div>
- {metric.comment !== null ? (
- <div>
- <div className="text-xs font-semibold text-gray-500">
- Comment
- </div>
- <div className="text-sm">{metric.comment}</div>
- </div>
- ) : null}
- </div>
- ),
- }))}
- />
- ),
- },
- {
- label: "Metadata",
- value: <JSONView json={trace.data.metadata} />,
- },
- ]}
- />
- ) : null}
+ <div className="flex gap-2">
+ {trace.data?.externalId ? (
+ <Badge variant="outline">External ID: {trace.data.externalId}</Badge>
+ ) : null}
+ {trace.data?.userId ? (
+ <Badge variant="outline">User ID: {trace.data.userId}</Badge>
+ ) : null}
+ <TraceAggUsageBadge observations={trace.data?.observations ?? []} />
+ </div>
- {trace.data?.nestedObservation ? (
- <div className="mt-5 border-t pt-5">
- <h2>Detailed trace</h2>
- <ObservationDisplay
- key={trace.data.id}
- projectId={projectId}
- observations={trace.data.nestedObservation}
- />
- </div>
+ {trace.data ? (
+ <>
+ <div className="mt-5 border-t pt-5">
+ <TraceDisplay
+ key={trace.data.id}
+ projectId={projectId}
+ trace={trace.data}
+ scores={trace.data.scores}
+ observations={trace.data.observations ?? []}
+ />
+ </div>
+ </>
) : null}
</div>
);
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 9804b42e40..5754b016e5 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -1,4 +1,3 @@
-import { type NestedObservation } from "@/src/utils/types";
import { z } from "zod";
import {
@@ -6,7 +5,6 @@ import {
protectedProcedure,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { type Observation } from "@prisma/client";
const ScoreFilter = z.object({
name: z.string(),
@@ -27,7 +25,7 @@ export const traceRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(TraceFilterOptions)
.query(async ({ input, ctx }) => {
- return await ctx.prisma.trace.findMany({
+ const traces = await ctx.prisma.trace.findMany({
where: {
AND: [
{
@@ -54,9 +52,39 @@ export const traceRouter = createTRPCRouter({
},
include: {
scores: true,
+ observations: {
+ select: {
+ promptTokens: true,
+ completionTokens: true,
+ totalTokens: true,
+ },
+ },
},
take: 50, // TODO: pagination
});
+
+ const res = traces.map((trace) => {
+ const { observations, ...t } = trace;
+ return {
+ ...t,
+ usage: {
+ promptTokens: observations.reduce(
+ (acc, cur) => acc + cur.promptTokens,
+ 0
+ ),
+ completionTokens: observations.reduce(
+ (acc, cur) => acc + cur.completionTokens,
+ 0
+ ),
+ totalTokens: observations.reduce(
+ (acc, cur) => acc + cur.totalTokens,
+ 0
+ ),
+ },
+ };
+ });
+
+ return res;
}),
availableFilterOptions: protectedProjectProcedure
.input(TraceFilterOptions)
@@ -165,40 +193,11 @@ export const traceRouter = createTRPCRouter({
return {
...trace,
- nestedObservation: nestObservations(observations),
+ observations,
};
}),
});
-function nestObservations(list: Observation[]): NestedObservation[] | null {
- if (list.length === 0) return null;
-
- // Step 1: Create a map where the keys are object IDs, and the values are
- // the corresponding objects with an added 'children' property.
- const map = new Map<string, NestedObservation>();
- for (const obj of list) {
- map.set(obj.id, { ...obj, children: [] });
- }
-
- // Step 2: Create another map for the roots of all trees.
- const roots = new Map<string, NestedObservation>();
-
- // Step 3: Populate the 'children' arrays and root map.
- for (const obj of map.values()) {
- if (obj.parentObservationId) {
- const parent = map.get(obj.parentObservationId);
- if (parent) {
- parent.children.push(obj);
- }
- } else {
- roots.set(obj.id, obj);
- }
- }
-
- // Step 4: Return the roots.
- return Array.from(roots.values());
-}
-
function createScoreCondition(score: ScoreFilter) {
let filter = {};
switch (score.operator) {
diff --git a/src/utils/types.ts b/src/utils/types.ts
index 48c9202957..b9bdc9f95e 100644
--- a/src/utils/types.ts
+++ b/src/utils/types.ts
@@ -19,15 +19,11 @@ export type Span = Observation & {
export type LLMChatMessages = { role: string; content: string };
-export type GenerationUsage = {
- promptTokens?: number;
- completionTokens?: number;
- totalTokens?: number;
-};
-
export type Generation = Observation & {
type: "GENERATION";
- usage: GenerationUsage;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
modelParameters: {
[key: string]: string | number | boolean;
};