Skip to content

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

Share traces via public link (#142)

Marc Klingen829c8dba8408
diff --git a/package-lock.json b/package-lock.json
index a5539b1c85..330c265984 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -29,6 +29,7 @@
"@radix-ui/react-separator": "^1.0.3",
"@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-toggle": "^1.0.3",
"@sentry/nextjs": "^7.68.0",
@@ -2771,6 +2772,35 @@
}
}
},
+ "node_modules/@radix-ui/react-switch": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.0.3.tgz",
+ "integrity": "sha512-mxm87F88HyHztsI7N+ZUmEoARGkC22YVW5CaC+Byc+HRpuvCrOBPTAnXgf+tZ/7i0Sg/eOePGdMhUKhPaQEqow==",
+ "dependencies": {
+ "@babel/runtime": "^7.13.10",
+ "@radix-ui/primitive": "1.0.1",
+ "@radix-ui/react-compose-refs": "1.0.1",
+ "@radix-ui/react-context": "1.0.1",
+ "@radix-ui/react-primitive": "1.0.3",
+ "@radix-ui/react-use-controllable-state": "1.0.1",
+ "@radix-ui/react-use-previous": "1.0.1",
+ "@radix-ui/react-use-size": "1.0.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-tabs": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.0.4.tgz",
diff --git a/package.json b/package.json
index 439c3401bd..358dbc1b97 100644
--- a/package.json
+++ b/package.json
@@ -41,6 +41,7 @@
"@radix-ui/react-separator": "^1.0.3",
"@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-toggle": "^1.0.3",
"@sentry/nextjs": "^7.68.0",
diff --git a/prisma/migrations/20230912115644_add_trace_public_bool/migration.sql b/prisma/migrations/20230912115644_add_trace_public_bool/migration.sql
new file mode 100644
index 0000000000..56abbaaaf7
--- /dev/null
+++ b/prisma/migrations/20230912115644_add_trace_public_bool/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "traces" ADD COLUMN "public" BOOLEAN NOT NULL DEFAULT false;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 2dbcee2b8b..0ac74c01dc 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -132,6 +132,7 @@ model Trace {
version String?
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ public Boolean @default(false)
scores Score[]
diff --git a/src/components/layouts/header.tsx b/src/components/layouts/header.tsx
index 96a0a63dfe..4a498bd3ec 100644
--- a/src/components/layouts/header.tsx
+++ b/src/components/layouts/header.tsx
@@ -59,7 +59,7 @@ export default function Header(props: {
</nav>
) : null}
</div>
- <div className="mt-2 md:flex md:items-center md:justify-between md:gap-5">
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-5">
<div className="flex items-center gap-3 md:gap-5">
<div className="min-w-0">
<h2 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
diff --git a/src/components/layouts/layout.tsx b/src/components/layouts/layout.tsx
index 39d8de75f8..c8c869856f 100644
--- a/src/components/layouts/layout.tsx
+++ b/src/components/layouts/layout.tsx
@@ -68,7 +68,8 @@ export default function Layout(props: PropsWithChildren) {
if (
session.data &&
session.data.user === null &&
- !unauthenticatedPaths.includes(router.pathname)
+ !unauthenticatedPaths.includes(router.pathname) &&
+ !router.pathname.startsWith("/public/")
) {
void signOut({
callbackUrl: "/auth/sign-in",
@@ -78,7 +79,8 @@ export default function Layout(props: PropsWithChildren) {
if (
session.status === "unauthenticated" &&
- !unauthenticatedPaths.includes(router.pathname)
+ !unauthenticatedPaths.includes(router.pathname) &&
+ !router.pathname.startsWith("/public/")
) {
void router.push("/auth/sign-in");
return <Spinner message="Redirecting" />;
@@ -95,7 +97,8 @@ export default function Layout(props: PropsWithChildren) {
const hideNavigation =
session.status === "unauthenticated" ||
projects.data?.length === 0 ||
- pathsWithoutNavigation.includes(router.pathname);
+ pathsWithoutNavigation.includes(router.pathname) ||
+ router.pathname.startsWith("/public/");
if (hideNavigation)
return (
<main className="h-full bg-gray-50 px-4 py-4 sm:px-6 lg:px-8">
diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsx
index 055f6b9930..6b7c0174e1 100644
--- a/src/components/trace/index.tsx
+++ b/src/components/trace/index.tsx
@@ -1,34 +1,26 @@
import { type Trace, type Observation, type Score } from "@prisma/client";
-import { useRouter } from "next/router";
import { ObservationTree } from "./ObservationTree";
import { ObservationPreview } from "./ObservationPreview";
import { TracePreview } from "./TracePreview";
+import Header from "@/src/components/layouts/header";
+import { Badge } from "@/src/components/ui/badge";
+import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
+import Decimal from "decimal.js";
+import { type RouterOutput } from "@/src/utils/types";
+import { StringParam, useQueryParam } from "use-query-params";
+import { PublishTraceSwitch } from "@/src/features/publicTraces/components/PublishTraceSwitch";
+
export function Trace(props: {
observations: Array<Observation & { traceId: string }>;
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,
- },
- );
- };
+ const [currentObservationId, setCurrentObservationId] = useQueryParam(
+ "observation",
+ StringParam,
+ );
return (
<div className="grid h-full gap-4 md:grid-cols-3">
@@ -37,7 +29,7 @@ export function Trace(props: {
observations={props.observations}
trace={props.trace}
scores={props.scores}
- currentObservationId={currentObservationId}
+ currentObservationId={currentObservationId ?? undefined}
setCurrentObservationId={setCurrentObservationId}
/>
</div>
@@ -53,7 +45,7 @@ export function Trace(props: {
observations={props.observations}
scores={props.scores}
projectId={props.projectId}
- currentObservationId={currentObservationId}
+ currentObservationId={currentObservationId ?? undefined}
/>
)}
</div>
@@ -62,10 +54,65 @@ export function Trace(props: {
observations={props.observations}
trace={props.trace}
scores={props.scores}
- currentObservationId={currentObservationId}
+ currentObservationId={currentObservationId ?? undefined}
setCurrentObservationId={setCurrentObservationId}
/>
</div>
</div>
);
}
+
+export function TracePage({
+ trace,
+}: {
+ trace: RouterOutput["traces"]["byId"];
+}) {
+ const totalCost = trace.observations.reduce(
+ (acc, o) => {
+ if (!o.price) return acc;
+
+ return acc
+ ? acc.plus(o.price ? o.price : new Decimal(0))
+ : new Decimal(0).plus(o.price ? o.price : new Decimal(0));
+ },
+ undefined as Decimal | undefined,
+ );
+
+ return (
+ <div className="flex flex-col overflow-hidden xl:container lg:h-[calc(100vh-100px)] xl:h-[calc(100vh-50px)]">
+ <Header
+ title="Trace Detail"
+ actionButtons={
+ <PublishTraceSwitch
+ traceId={trace.id}
+ projectId={trace.projectId}
+ isPublic={trace.public}
+ />
+ }
+ />
+ <div className="flex gap-2">
+ {trace.externalId ? (
+ <Badge variant="outline">External ID: {trace.externalId}</Badge>
+ ) : null}
+ {trace.userId ? (
+ <Badge variant="outline">User ID: {trace.userId}</Badge>
+ ) : null}
+ <TraceAggUsageBadge observations={trace.observations ?? []} />
+ {totalCost ? (
+ <Badge variant="outline">
+ Total cost: {totalCost.toString()} USD
+ </Badge>
+ ) : undefined}
+ </div>
+ <div className="mt-5 flex-1 overflow-hidden border-t pt-5">
+ <Trace
+ key={trace.id}
+ trace={trace}
+ scores={trace.scores}
+ projectId={trace.projectId}
+ observations={trace.observations ?? []}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsx
new file mode 100644
index 0000000000..285807e91a
--- /dev/null
+++ b/src/components/ui/switch.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import * as React from "react";
+import * as SwitchPrimitives from "@radix-ui/react-switch";
+
+import { cn } from "@/src/utils/tailwind";
+
+const Switch = React.forwardRef<
+ React.ElementRef<typeof SwitchPrimitives.Root>,
+ React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
+>(({ className, ...props }, ref) => (
+ <SwitchPrimitives.Root
+ className={cn(
+ "peer inline-flex h-[24px] w-[44px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
+ className,
+ )}
+ {...props}
+ ref={ref}
+ >
+ <SwitchPrimitives.Thumb
+ className={cn(
+ "pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",
+ )}
+ />
+ </SwitchPrimitives.Root>
+));
+Switch.displayName = SwitchPrimitives.Root.displayName;
+
+export { Switch };
diff --git a/src/features/publicTraces/components/PublishTraceSwitch.tsx b/src/features/publicTraces/components/PublishTraceSwitch.tsx
new file mode 100644
index 0000000000..ff7e7a805a
--- /dev/null
+++ b/src/features/publicTraces/components/PublishTraceSwitch.tsx
@@ -0,0 +1,68 @@
+import { Switch } from "@/src/components/ui/switch";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
+import { Link, Lock } from "lucide-react";
+import { useState } from "react";
+
+export const PublishTraceSwitch = (props: {
+ traceId: string;
+ projectId: string;
+ isPublic: boolean;
+}) => {
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "traces:publish",
+ });
+ const utils = api.useContext();
+ const mut = api.publishTraces.update.useMutation({
+ onSuccess: () => utils.traces.invalidate(),
+ });
+
+ const [isCopied, setIsCopied] = useState(false);
+
+ const handleCopy = (text: string) => {
+ setIsCopied(true);
+ void navigator.clipboard.writeText(text);
+ setTimeout(() => setIsCopied(false), 1500);
+ };
+
+ return (
+ <div className="flex items-center gap-3">
+ <div className="text-sm font-semibold">
+ {mut.isLoading ? (
+ "Loading.."
+ ) : props.isPublic ? (
+ <div
+ className="flex cursor-pointer items-center gap-1 text-green-800"
+ onClick={() =>
+ handleCopy(
+ window.location.origin + "/public/traces/" + props.traceId,
+ )
+ }
+ >
+ {isCopied ? "Link copied ..." : "Public"}
+ <Link size={16} />
+ </div>
+ ) : (
+ <div className="flex items-center gap-1">
+ Private
+ <Lock size={16} />
+ </div>
+ )}
+ </div>
+ <Switch
+ id="publish-trace"
+ checked={props.isPublic}
+ onCheckedChange={() => {
+ if (mut.isLoading) return;
+ mut.mutate({
+ traceId: props.traceId,
+ public: !props.isPublic,
+ projectId: props.projectId,
+ });
+ }}
+ disabled={!hasAccess}
+ />
+ </div>
+ );
+};
diff --git a/src/features/publicTraces/server/publishTracesRouter.ts b/src/features/publicTraces/server/publishTracesRouter.ts
new file mode 100644
index 0000000000..d97ca6e561
--- /dev/null
+++ b/src/features/publicTraces/server/publishTracesRouter.ts
@@ -0,0 +1,30 @@
+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
+import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";
+import * as z from "zod";
+
+export const publishTracesRouter = createTRPCRouter({
+ update: protectedProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ traceId: z.string(),
+ public: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "traces:publish",
+ });
+ return ctx.prisma.trace.update({
+ where: {
+ id: input.traceId,
+ projectId: input.projectId,
+ },
+ data: {
+ public: input.public,
+ },
+ });
+ }),
+});
diff --git a/src/features/rbac/constants/roleAccessRights.ts b/src/features/rbac/constants/roleAccessRights.ts
index 3b45be237c..a6d8d4a337 100644
--- a/src/features/rbac/constants/roleAccessRights.ts
+++ b/src/features/rbac/constants/roleAccessRights.ts
@@ -9,6 +9,8 @@ const scopes = [
"apiKeys:create",
"apiKeys:delete",
+ "traces:publish",
+
"scores:CUD",
] as const;
@@ -23,6 +25,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"apiKeys:read",
"apiKeys:create",
"apiKeys:delete",
+ "traces:publish",
"scores:CUD",
],
ADMIN: [
@@ -32,8 +35,9 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"apiKeys:read",
"apiKeys:create",
"apiKeys:delete",
+ "traces:publish",
"scores:CUD",
],
- MEMBER: ["members:read", "scores:CUD"],
+ MEMBER: ["members:read", "traces:publish", "scores:CUD"],
VIEWER: [],
};
diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsx
index d62938fbed..0da933ce1a 100644
--- a/src/pages/project/[projectId]/traces/[traceId].tsx
+++ b/src/pages/project/[projectId]/traces/[traceId].tsx
@@ -1,63 +1,15 @@
import { useRouter } from "next/router";
-import Header from "@/src/components/layouts/header";
import { api } from "@/src/utils/api";
-import { Trace } from "@/src/components/trace";
-import { Badge } from "@/src/components/ui/badge";
-import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
-import Decimal from "decimal.js";
+import { TracePage } from "@/src/components/trace";
-export default function TracePage() {
+export default function Trace() {
const router = useRouter();
const traceId = router.query.traceId as string;
- const projectId = router.query.projectId as string;
-
const trace = api.traces.byId.useQuery(traceId);
- const totalCost = trace.data?.observations.reduce(
- (acc, o) => {
- if (!o.price) return acc;
-
- return acc
- ? acc.plus(o.price ? o.price : new Decimal(0))
- : new Decimal(0).plus(o.price ? o.price : new Decimal(0));
- },
- undefined as Decimal | undefined,
- );
-
- return (
- <div className="flex flex-col overflow-hidden xl:container lg:h-[calc(100vh-100px)] xl:h-[calc(100vh-50px)]">
- <Header
- title="Trace Detail"
- breadcrumb={[
- { name: "Traces", href: `/project/${projectId}/traces` },
- { name: traceId },
- ]}
- />
- <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 ?? []} />
- {totalCost ? (
- <Badge variant="outline">
- Total cost: {totalCost.toString()} USD
- </Badge>
- ) : undefined}
- </div>
- {trace.data ? (
- <div className="mt-5 flex-1 overflow-hidden border-t pt-5">
- <Trace
- key={trace.data.id}
- projectId={projectId}
- trace={trace.data}
- scores={trace.data.scores}
- observations={trace.data.observations ?? []}
- />
- </div>
- ) : null}
- </div>
- );
+ if (trace.data) {
+ return <TracePage trace={trace.data} />;
+ } else {
+ return <div>loading...</div>;
+ }
}
diff --git a/src/pages/public/traces/[traceId].tsx b/src/pages/public/traces/[traceId].tsx
new file mode 100644
index 0000000000..420a1a9c26
--- /dev/null
+++ b/src/pages/public/traces/[traceId].tsx
@@ -0,0 +1,21 @@
+import { useRouter } from "next/router";
+import { api } from "@/src/utils/api";
+import { TracePage } from "@/src/components/trace";
+
+export default function PublicTracePage() {
+ const router = useRouter();
+ const traceId = router.query.traceId as string;
+
+ const trace = api.traces.byIdPublic.useQuery(traceId);
+
+ if (trace.isLoading) return <div>loading...</div>;
+ if (trace.data) {
+ return (
+ <div className="py-5">
+ <TracePage trace={trace.data} />
+ </div>
+ );
+ } else {
+ return <div>Not available</div>;
+ }
+}
diff --git a/src/server/api/root.ts b/src/server/api/root.ts
index 08bd627149..6dbd0cdbaa 100644
--- a/src/server/api/root.ts
+++ b/src/server/api/root.ts
@@ -7,6 +7,7 @@ import { projectsRouter } from "@/src/features/projects/server/projectsRouter";
import { apiKeysRouter } from "@/src/features/publicApi/server/apiKeyRouter";
import { projectMembersRouter } from "@/src/features/rbac/server/projectMembersRouter";
import { userRouter } from "@/src/server/api/routers/users";
+import { publishTracesRouter } from "@/src/features/publicTraces/server/publishTracesRouter";
/**
* This is the primary router for your server.
@@ -22,6 +23,7 @@ export const appRouter = createTRPCRouter({
users: userRouter,
apiKeys: apiKeysRouter,
projectMembers: projectMembersRouter,
+ publishTraces: publishTracesRouter,
});
// export type definition of API
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 2bce7adefa..8a2456cdfd 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -4,6 +4,7 @@ import {
createTRPCRouter,
protectedProcedure,
protectedProjectProcedure,
+ publicProcedure,
} from "@/src/server/api/trpc";
import { Prisma, type Score, type Trace } from "@prisma/client";
import { calculateTokenCost } from "@/src/features/ingest/lib/usage";
@@ -301,6 +302,58 @@ export const traceRouter = createTRPCRouter({
>,
};
}),
+
+ // exact copy of previoud byId, but without the project member check
+ // output must be the same as consumed by the same component
+ byIdPublic: publicProcedure
+ .input(z.string())
+ .query(async ({ input, ctx }) => {
+ const [trace, observations, pricings] = await Promise.all([
+ ctx.prisma.trace.findFirst({
+ where: {
+ id: input,
+ public: true,
+ },
+ include: {
+ scores: true,
+ },
+ }),
+ ctx.prisma.observation.findMany({
+ where: {
+ traceId: {
+ equals: input,
+ not: null,
+ },
+ },
+ }),
+ ctx.prisma.pricing.findMany(),
+ ]);
+
+ if (!trace) {
+ return null;
+ }
+
+ const enrichedObservations = observations.map((observation) => {
+ return {
+ ...observation,
+ price: observation.model
+ ? calculateTokenCost(pricings, {
+ model: observation.model,
+ totalTokens: new Decimal(observation.totalTokens),
+ promptTokens: new Decimal(observation.promptTokens),
+ completionTokens: new Decimal(observation.completionTokens),
+ })
+ : undefined,
+ };
+ });
+
+ return {
+ ...trace,
+ observations: enrichedObservations as Array<
+ (typeof observations)[0] & { traceId: string } & { price?: Decimal }
+ >,
+ };
+ }),
});
function createScoreCondition(score: ScoreFilter) {