Skip to content

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

feat: add sessions and i/o on traces (#588)

Marc Klingen4e520f7e521f
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 9387503183..eaec1eeeb3 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -35,6 +35,9 @@ types:
docs: The unique identifier of a trace
timestamp: datetime
name: optional<string>
+ input: optional<unknown>
+ output: optional<unknown>
+ sessionId: optional<string>
release: optional<string>
version: optional<string>
userId: optional<string>
@@ -56,6 +59,15 @@ types:
properties:
observations: list<Observation>
scores: list<Score>
+ Session:
+ properties:
+ id: string
+ createdAt: datetime
+ projectId: string
+ SessionWithTraces:
+ extends: Session
+ properties:
+ traces: list<Trace>
Observation:
properties:
id: string
diff --git a/fern/apis/server/definition/sessions.yml b/fern/apis/server/definition/sessions.yml
new file mode 100644
index 0000000000..3e77624e91
--- /dev/null
+++ b/fern/apis/server/definition/sessions.yml
@@ -0,0 +1,17 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ pagination: ./utils/pagination.yml
+ commons: ./commons.yml
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ get:
+ docs: Get a session
+ method: GET
+ path: /sessions/{sessionId}
+ path-parameters:
+ sessionId:
+ type: string
+ docs: The unique id of a session
+ response: commons.SessionWithTraces
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index 52ac6f5d00..6973289880 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -41,6 +41,9 @@ types:
name: optional<string>
userId: optional<string>
externalId: optional<string>
+ input: optional<unknown>
+ output: optional<unknown>
+ sessionId: optional<string>
release: optional<string>
version: optional<string>
metadata: optional<unknown>
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 7f06bed67b..7ba79de35e 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -785,6 +785,52 @@ paths:
application/json:
schema: {}
security: *ref_0
+ /api/public/sessions/{sessionId}:
+ get:
+ description: Get a session
+ operationId: sessions_get
+ tags:
+ - Sessions
+ parameters:
+ - name: sessionId
+ in: path
+ description: The unique id of a session
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SessionWithTraces'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security: *ref_0
/api/public/spans:
post:
description: Add a span to the database
@@ -1116,6 +1162,13 @@ components:
name:
type: string
nullable: true
+ input:
+ nullable: true
+ output:
+ nullable: true
+ sessionId:
+ type: string
+ nullable: true
release:
type: string
nullable: true
@@ -1170,6 +1223,33 @@ components:
- scores
allOf:
- $ref: '#/components/schemas/Trace'
+ Session:
+ title: Session
+ type: object
+ properties:
+ id:
+ type: string
+ createdAt:
+ type: string
+ format: date-time
+ projectId:
+ type: string
+ required:
+ - id
+ - createdAt
+ - projectId
+ SessionWithTraces:
+ title: SessionWithTraces
+ type: object
+ properties:
+ traces:
+ type: array
+ items:
+ $ref: '#/components/schemas/Trace'
+ required:
+ - traces
+ allOf:
+ - $ref: '#/components/schemas/Session'
Observation:
title: Observation
type: object
@@ -1730,6 +1810,13 @@ components:
externalId:
type: string
nullable: true
+ input:
+ nullable: true
+ output:
+ nullable: true
+ sessionId:
+ type: string
+ nullable: true
release:
type: string
nullable: true
diff --git a/generated/postman/collection.json b/generated/postman/collection.json
index 5090fcd3c5..3ab17dc4d0 100644
--- a/generated/postman/collection.json
+++ b/generated/postman/collection.json
@@ -433,7 +433,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"batch\": [\n {\n \"type\": \"trace-create\",\n \"id\": \"example\",\n \"timestamp\": \"example\",\n \"body\": {\n \"id\": \"example\",\n \"timestamp\": \"1994-11-05T13:15:30Z\",\n \"name\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"userId\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n }\n }\n ]\n}",
+ "raw": "{\n \"batch\": [\n {\n \"type\": \"trace-create\",\n \"id\": \"example\",\n \"timestamp\": \"example\",\n \"body\": {\n \"id\": \"example\",\n \"timestamp\": \"1994-11-05T13:15:30Z\",\n \"name\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"userId\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n }\n }\n ]\n}",
"options": {
"raw": {
"language": "json"
@@ -663,6 +663,45 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Sessions",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Get",
+ "request": {
+ "description": "Get a session",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/sessions/:sessionId",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "sessions",
+ ":sessionId"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "sessionId",
+ "value": "",
+ "description": "The unique id of a session"
+ }
+ ]
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
@@ -764,7 +803,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"id\": \"example\",\n \"name\": \"example\",\n \"userId\": \"example\",\n \"externalId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n}",
+ "raw": "{\n \"id\": \"example\",\n \"name\": \"example\",\n \"userId\": \"example\",\n \"externalId\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n}",
"options": {
"raw": {
"language": "json"
diff --git a/prisma/migrations/20231130003317_trace_session_input_output/migration.sql b/prisma/migrations/20231130003317_trace_session_input_output/migration.sql
new file mode 100644
index 0000000000..ebdceb2e87
--- /dev/null
+++ b/prisma/migrations/20231130003317_trace_session_input_output/migration.sql
@@ -0,0 +1,34 @@
+-- AlterTable
+ALTER TABLE "traces" ADD COLUMN "input" JSONB,
+ADD COLUMN "output" JSONB,
+ADD COLUMN "session_id" TEXT;
+
+-- CreateTable
+CREATE TABLE "trace_sessions" (
+ "id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "project_id" TEXT NOT NULL,
+ "bookmarked" BOOLEAN NOT NULL DEFAULT false,
+ "public" BOOLEAN NOT NULL DEFAULT false,
+
+ CONSTRAINT "trace_sessions_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "trace_sessions_project_id_idx" ON "trace_sessions"("project_id");
+
+-- CreateIndex
+CREATE INDEX "trace_sessions_created_at_idx" ON "trace_sessions"("created_at");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "trace_sessions_id_project_id_key" ON "trace_sessions"("id", "project_id");
+
+-- CreateIndex
+CREATE INDEX "traces_session_id_idx" ON "traces"("session_id");
+
+-- AddForeignKey
+ALTER TABLE "trace_sessions" ADD CONSTRAINT "trace_sessions_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "traces" ADD CONSTRAINT "traces_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "trace_sessions"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 081fda106a..561a35bcdd 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -86,6 +86,7 @@ model Project {
dataset Dataset[]
RawEvents Events[]
invitations MembershipInvitation[]
+ sessions TraceSession[]
@@map("projects")
}
@@ -147,24 +148,45 @@ enum MembershipRole {
VIEWER
}
-model Trace {
+model TraceSession {
id String @id @default(cuid())
- externalId String? @map("external_id")
- timestamp DateTime @default(now())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ bookmarked Boolean @default(false)
+ public Boolean @default(false)
+ traces Trace[]
+
+ @@unique([id, projectId])
+ @@index([projectId])
+ @@index([createdAt])
+ @@map("trace_sessions")
+}
+
+model Trace {
+ id String @id @default(cuid())
+ externalId String? @map("external_id")
+ timestamp DateTime @default(now())
name String?
- userId String? @map("user_id")
+ userId String? @map("user_id")
metadata Json?
release String?
version String?
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- public Boolean @default(false)
- bookmarked Boolean @default(false)
+ input Json?
+ output Json?
+ sessionId String? @map("session_id")
+ session TraceSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull)
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ public Boolean @default(false)
+ bookmarked Boolean @default(false)
scores Score[]
@@unique([projectId, externalId])
@@index([projectId])
+ @@index([sessionId])
@@index([name])
@@index([userId])
@@index([externalId])
diff --git a/prisma/seed.ts b/prisma/seed.ts
index 83a2a86bf0..657da621c3 100755
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -133,19 +133,42 @@ async function main() {
},
},
userId: `user-${i % 10}`,
+ session:
+ Math.random() > 0.3
+ ? {
+ connectOrCreate: {
+ where: {
+ id: `session-${i % 10}`,
+ },
+ create: {
+ id: `session-${i % 10}`,
+ project: {
+ connect: { id: [project1.id, project2.id][i % 2] },
+ },
+ },
+ },
+ }
+ : undefined,
+ input:
+ Math.random() > 0.3
+ ? "I'm looking for a React component"
+ : undefined,
+ output:
+ Math.random() > 0.3
+ ? "What kind of component are you looking for?"
+ : undefined,
scores: {
createMany: {
data: [
- {
- name: "latency",
- value: Math.floor(Math.random() * 20),
- timestamp: traceTs,
- },
- {
- name: "feedback",
- value: Math.floor(Math.random() * 3) - 1,
- timestamp: traceTs,
- },
+ ...(Math.random() > 0.5
+ ? [
+ {
+ name: "feedback",
+ value: Math.floor(Math.random() * 3) - 1,
+ timestamp: traceTs,
+ },
+ ]
+ : []),
...(Math.random() > 0.7
? [
{
@@ -305,23 +328,24 @@ async function main() {
traceId: trace.id,
},
});
-
- await prisma.score.create({
- data: {
- name: "quality",
- value: Math.random() * 2 - 1,
- observationId: generation.id,
- traceId: trace.id,
- },
- });
- await prisma.score.create({
- data: {
- name: "conciseness",
- value: Math.random() * 2 - 1,
- observationId: generation.id,
- traceId: trace.id,
- },
- });
+ if (Math.random() > 0.6)
+ await prisma.score.create({
+ data: {
+ name: "quality",
+ value: Math.random() * 2 - 1,
+ observationId: generation.id,
+ traceId: trace.id,
+ },
+ });
+ if (Math.random() > 0.6)
+ await prisma.score.create({
+ data: {
+ name: "conciseness",
+ value: Math.random() * 2 - 1,
+ observationId: generation.id,
+ traceId: trace.id,
+ },
+ });
generationIds.push(generation.id);
diff --git a/src/__tests__/sessions.servertest.ts b/src/__tests__/sessions.servertest.ts
new file mode 100644
index 0000000000..b159d31ae3
--- /dev/null
+++ b/src/__tests__/sessions.servertest.ts
@@ -0,0 +1,62 @@
+/** @jest-environment node */
+
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { prisma } from "@/src/server/db";
+
+describe("/api/public/traces API Endpoint", () => {
+ beforeEach(async () => await pruneDatabase());
+ afterEach(async () => await pruneDatabase());
+
+ it("should create a session via a trace", async () => {
+ await pruneDatabase();
+
+ await makeAPICall("POST", "/api/public/traces", {
+ name: "trace-name",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ sessionId: "session-id",
+ });
+
+ const dbSession = await prisma.traceSession.findFirst({
+ where: {
+ id: "session-id",
+ },
+ });
+
+ expect(dbSession).not.toBeNull();
+ expect(dbSession).toMatchObject({
+ id: "session-id",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+ });
+
+ it("should get session including traces", async () => {
+ await pruneDatabase();
+
+ await makeAPICall("POST", "/api/public/traces", {
+ name: "trace-name",
+ id: "trace-id",
+ input: { hello: "world" },
+ output: "hi",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ sessionId: "session-id",
+ });
+
+ const response = await makeAPICall(
+ "GET",
+ "/api/public/sessions/session-id",
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({
+ id: "session-id",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traces: [
+ {
+ id: "trace-id",
+ input: { hello: "world" },
+ output: "hi",
+ },
+ ],
+ });
+ });
+});
diff --git a/src/components/bookmark-trace.tsx b/src/components/bookmark-trace.tsx
deleted file mode 100644
index 339097e716..0000000000
--- a/src/components/bookmark-trace.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { StarIcon } from "lucide-react";
-
-import { Button } from "@/src/components/ui/button";
-import { api } from "@/src/utils/api";
-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
-import { useEffect, useState } from "react";
-
-export function BookmarkTrace({
- traceId,
- projectId,
- isBookmarked,
- size = "sm",
-}: {
- traceId: string;
- projectId: string;
- isBookmarked: boolean;
- size?: "sm" | "xs";
-}) {
- const utils = api.useUtils();
- const [cacheIsBookmarked, setCacheIsBookmarked] = useState<boolean | null>(
- null,
- );
- const localIsBookmarked = cacheIsBookmarked ?? isBookmarked;
- const hasAccess = useHasAccess({ projectId, scope: "traces:bookmark" });
- const mutBookmarkTrace = api.traces.bookmark.useMutation({
- onSuccess: () => {
- setCacheIsBookmarked(!localIsBookmarked);
- void utils.traces.invalidate();
- },
- });
-
- useEffect(() => {
- setCacheIsBookmarked(null);
- }, [isBookmarked]);
-
- const handleBookmarkClick = () => {
- if (!hasAccess) return;
- void mutBookmarkTrace.mutateAsync({
- traceId,
- projectId,
- bookmarked: !localIsBookmarked,
- });
- };
-
- return (
- <Button
- variant="ghost"
- size={size}
- onClick={handleBookmarkClick}
- disabled={!hasAccess}
- loading={mutBookmarkTrace.isLoading}
- >
- <StarIcon
- className={`h-4 w-4 ${
- localIsBookmarked ? "fill-current text-yellow-500" : "text-gray-500"
- }`}
- />
- </Button>
- );
-}
diff --git a/src/components/delete-trace.tsx b/src/components/delete-trace.tsx
index 3eb001a28b..d571d656df 100644
--- a/src/components/delete-trace.tsx
+++ b/src/components/delete-trace.tsx
@@ -51,7 +51,7 @@ export function DeleteTrace({
<TrashIcon className="h-4 w-4" />
</Button>
) : (
- <Button variant="outline" type="button">
+ <Button variant="outline" type="button" size="sm">
<TrashIcon className="h-4 w-4" />
</Button>
)}
diff --git a/src/components/layouts/header.tsx b/src/components/layouts/header.tsx
index f134ec120c..48e8f4d093 100644
--- a/src/components/layouts/header.tsx
+++ b/src/components/layouts/header.tsx
@@ -2,11 +2,13 @@ import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/20/solid";
import Link from "next/link";
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
+import DocPopup from "@/src/components/layouts/doc-popup";
export default function Header(props: {
title: string;
breadcrumb?: { name: string; href?: string }[];
live?: boolean;
+ help?: { description: string; href: string };
actionButtons?: React.ReactNode;
}) {
const router = useRouter();
@@ -79,12 +81,19 @@ export default function Header(props: {
</nav>
) : null}
</div>
- <div className="mt-2 flex flex-wrap items-center justify-between gap-5">
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-3 md:gap-5">
- <div className="min-w-0">
+ <div className="flex min-w-0 flex-row">
<h2 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
{props.title}
</h2>
+ {props.help ? (
+ <DocPopup
+ description={props.help.description}
+ href={props.help.href}
+ size="sm"
+ />
+ ) : null}
</div>
{props.live ? (
<div className="flex items-center gap-2 rounded-sm bg-green-100 px-3 text-green-600">
@@ -96,8 +105,9 @@ export default function Header(props: {
</div>
) : null}
</div>
- <div className="md:flex-1" />
- {props.actionButtons ?? null}
+ <div className="flex items-center gap-3">
+ {props.actionButtons ?? null}
+ </div>
</div>
</div>
);
diff --git a/src/components/layouts/layout.tsx b/src/components/layouts/layout.tsx
index f65fa2cf7d..21f215c578 100644
--- a/src/components/layouts/layout.tsx
+++ b/src/components/layouts/layout.tsx
@@ -36,6 +36,10 @@ const userNavigation = [
const pathsWithoutNavigation: string[] = [];
const unauthenticatedPaths = ["/auth/sign-in", "/auth/sign-up"];
+const publishablePaths = [
+ "/project/[projectId]/sessions/[sessionId]",
+ "/project/[projectId]/traces/[traceId]",
+];
export default function Layout(props: PropsWithChildren) {
const [sidebarOpen, setSidebarOpen] = useState(false);
@@ -76,6 +80,7 @@ export default function Layout(props: PropsWithChildren) {
session.data &&
session.data.user === null &&
!unauthenticatedPaths.includes(router.pathname) &&
+ !publishablePaths.includes(router.pathname) &&
!router.pathname.startsWith("/public/")
) {
void signOut({
@@ -87,9 +92,10 @@ export default function Layout(props: PropsWithChildren) {
if (
session.status === "unauthenticated" &&
!unauthenticatedPaths.includes(router.pathname) &&
+ !publishablePaths.includes(router.pathname) &&
!router.pathname.startsWith("/public/")
) {
- void router.push("/auth/sign-in");
+ void router.replace("/auth/sign-in");
return <Spinner message="Redirecting" />;
}
@@ -97,7 +103,7 @@ export default function Layout(props: PropsWithChildren) {
session.status === "authenticated" &&
unauthenticatedPaths.includes(router.pathname)
) {
- void router.push("/");
+ void router.replace("/");
return <Spinner message="Redirecting" />;
}
@@ -218,6 +224,18 @@ export default function Layout(props: PropsWithChildren) {
aria-hidden="true"
/>
{item.name}
+ {item.label && (
+ <span
+ className={cn(
+ "self-center whitespace-nowrap break-keep rounded-sm border px-1 py-0.5 text-xs",
+ item.current
+ ? "border-indigo-600 text-indigo-600"
+ : "border-gray-200 text-gray-400 group-hover:border-indigo-600 group-hover:text-indigo-600",
+ )}
+ >
+ {item.label}
+ </span>
+ )}
</Link>
</li>
))}
@@ -267,7 +285,7 @@ export default function Layout(props: PropsWithChildren) {
{project.role === "VIEWER" ? (
<span
className={cn(
- "whitespace-nowrap break-keep rounded-sm border p-1 text-xs",
+ "self-center whitespace-nowrap break-keep rounded-sm border px-1 py-0.5 text-xs",
projectId === project.id
? "border-indigo-600 text-indigo-600"
: "border-gray-200 text-gray-400 group-hover:border-indigo-600 group-hover:text-indigo-600",
@@ -320,6 +338,18 @@ export default function Layout(props: PropsWithChildren) {
aria-hidden="true"
/>
{item.name}
+ {item.label && (
+ <span
+ className={cn(
+ "self-center whitespace-nowrap break-keep rounded-sm border px-1 py-0.5 text-xs",
+ item.current
+ ? "border-indigo-600 text-indigo-600"
+ : "border-gray-200 text-gray-400 group-hover:border-indigo-600 group-hover:text-indigo-600",
+ )}
+ >
+ {item.label}
+ </span>
+ )}
</Link>
</li>
))}
@@ -373,7 +403,7 @@ export default function Layout(props: PropsWithChildren) {
{project.role === "VIEWER" ? (
<span
className={cn(
- "whitespace-nowrap break-keep rounded-sm border p-1 text-xs",
+ "self-center whitespace-nowrap break-keep rounded-sm border px-1 py-0.5 text-xs",
projectId === project.id
? "border-indigo-600 text-indigo-600"
: "border-gray-200 text-gray-400 group-hover:border-indigo-600 group-hover:text-indigo-600",
diff --git a/src/components/layouts/routes.ts b/src/components/layouts/routes.ts
index 63be175200..0690a91408 100644
--- a/src/components/layouts/routes.ts
+++ b/src/components/layouts/routes.ts
@@ -9,6 +9,7 @@ import {
Settings,
TextSelect,
UsersIcon,
+ Route,
} from "lucide-react";
export const ROUTES: Array<{
@@ -16,12 +17,19 @@ export const ROUTES: Array<{
pathname: string;
icon: LucideIcon;
featureFlag?: Flag;
+ label?: string;
}> = [
{
name: "Dashboard",
pathname: `/project/[projectId]`,
icon: LayoutDashboard,
},
+ {
+ name: "Sessions",
+ pathname: `/project/[projectId]/sessions`,
+ icon: Route,
+ label: "beta",
+ },
{
name: "Traces",
pathname: `/project/[projectId]/traces`,
diff --git a/src/components/no-access.tsx b/src/components/no-access.tsx
new file mode 100644
index 0000000000..1d2e3f5cc7
--- /dev/null
+++ b/src/components/no-access.tsx
@@ -0,0 +1,22 @@
+import { Button } from "@/src/components/ui/button";
+import { AlertCircle } from "lucide-react";
+import { useSession } from "next-auth/react";
+import { useRouter } from "next/router";
+
+export const NoAccessError = () => {
+ const session = useSession();
+ const router = useRouter();
+
+ return (
+ <div className="flex h-screen flex-col items-center justify-center">
+ <AlertCircle className="mb-4 h-12 w-12 text-red-500" />
+ <h1 className="mb-4 text-xl font-bold">Error</h1>
+ <p className="mb-8 text-center">
+ You do not have access to this resource.
+ </p>
+ {session.status === "unauthenticated" ? (
+ <Button onClick={() => void router.push("/")}>Sign In</Button>
+ ) : null}
+ </div>
+ );
+};
diff --git a/src/components/publish-object-switch.tsx b/src/components/publish-object-switch.tsx
new file mode 100644
index 0000000000..0f78604257
--- /dev/null
+++ b/src/components/publish-object-switch.tsx
@@ -0,0 +1,120 @@
+import { Switch } from "@/src/components/ui/switch";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
+import { Link, LockIcon } from "lucide-react";
+import { usePostHog } from "posthog-js/react";
+import { useState } from "react";
+
+export const PublishTraceSwitch = (props: {
+ traceId: string;
+ projectId: string;
+ isPublic: boolean;
+}) => {
+ const posthog = usePostHog();
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "objects:publish",
+ });
+ const utils = api.useUtils();
+ const mut = api.traces.publish.useMutation({
+ onSuccess: () => utils.traces.invalidate(),
+ });
+
+ return (
+ <Base
+ id={props.traceId}
+ isPublic={props.isPublic}
+ onChange={(val) => {
+ mut.mutate({
+ projectId: props.projectId,
+ traceId: props.traceId,
+ public: val,
+ });
+ posthog.capture("trace_detail:publish_trace_button_click");
+ }}
+ isLoading={mut.isLoading}
+ disabled={!hasAccess}
+ />
+ );
+};
+
+export const PublishSessionSwitch = (props: {
+ sessionId: string;
+ projectId: string;
+ isPublic: boolean;
+}) => {
+ const posthog = usePostHog();
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "objects:publish",
+ });
+ const utils = api.useUtils();
+ const mut = api.sessions.publish.useMutation({
+ onSuccess: () => utils.sessions.invalidate(),
+ });
+
+ return (
+ <Base
+ id={props.sessionId}
+ isPublic={props.isPublic}
+ onChange={(val) => {
+ mut.mutate({
+ projectId: props.projectId,
+ sessionId: props.sessionId,
+ public: val,
+ });
+ posthog.capture("session_detail:publish_session_button_click");
+ }}
+ isLoading={mut.isLoading}
+ disabled={!hasAccess}
+ />
+ );
+};
+
+const Base = (props: {
+ id: string;
+ onChange: (value: boolean) => void;
+ isLoading: boolean;
+ isPublic: boolean;
+ disabled?: boolean;
+}) => {
+ const [isCopied, setIsCopied] = useState(false);
+
+ const copyUrl = () => {
+ setIsCopied(true);
+ void navigator.clipboard.writeText(window.location.href);
+ setTimeout(() => setIsCopied(false), 1500);
+ };
+
+ return (
+ <div className="flex items-center gap-3">
+ <div className="text-sm font-semibold">
+ {props.isLoading ? (
+ "Loading.."
+ ) : props.isPublic ? (
+ <div
+ className="flex cursor-pointer items-center gap-1 text-green-800"
+ onClick={() => copyUrl()}
+ >
+ {isCopied ? "Link copied ..." : "Public"}
+ <Link size={16} />
+ </div>
+ ) : (
+ <div className="flex items-center gap-1">
+ Private
+ <LockIcon size={16} />
+ </div>
+ )}
+ </div>
+ <Switch
+ id="publish-trace"
+ checked={props.isPublic}
+ onCheckedChange={() => {
+ if (props.isLoading) return;
+ void props.onChange(!props.isPublic);
+ }}
+ disabled={props.disabled}
+ />
+ </div>
+ );
+};
diff --git a/src/components/session/index.tsx b/src/components/session/index.tsx
new file mode 100644
index 0000000000..be23950419
--- /dev/null
+++ b/src/components/session/index.tsx
@@ -0,0 +1,119 @@
+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import Header from "@/src/components/layouts/header";
+import { NoAccessError } from "@/src/components/no-access";
+import { PublishSessionSwitch } from "@/src/components/publish-object-switch";
+import { StarSessionToggle } from "@/src/components/star-toggle";
+import { IOPreview } from "@/src/components/trace/IOPreview";
+import { Badge } from "@/src/components/ui/badge";
+import { Card } from "@/src/components/ui/card";
+import { ManualScoreButton } from "@/src/features/manual-scoring/components/ManualScoreButton";
+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import { api } from "@/src/utils/api";
+import Link from "next/link";
+
+export const SessionPage: React.FC<{
+ sessionId: string;
+ projectId: string;
+}> = ({ sessionId, projectId }) => {
+ const session = api.sessions.byId.useQuery(
+ {
+ sessionId,
+ projectId: projectId,
+ },
+ {
+ retry(failureCount, error) {
+ if (error.data?.code === "UNAUTHORIZED") return false;
+ return failureCount < 3;
+ },
+ },
+ );
+
+ if (session.error?.data?.code === "UNAUTHORIZED") return <NoAccessError />;
+
+ return (
+ <div className="flex flex-col overflow-hidden xl:container">
+ <Header
+ title="Session"
+ breadcrumb={[
+ {
+ name: "Sessions",
+ href: `/project/${projectId}/sessions`,
+ },
+ { name: sessionId },
+ ]}
+ actionButtons={[
+ <StarSessionToggle
+ key="star"
+ projectId={projectId}
+ sessionId={sessionId}
+ value={session.data?.bookmarked ?? false}
+ />,
+ <PublishSessionSwitch
+ projectId={projectId}
+ sessionId={sessionId}
+ isPublic={session.data?.public ?? false}
+ key="publish"
+ />,
+ <DetailPageNav
+ key="nav"
+ currentId={sessionId}
+ path={(id) => `/project/${projectId}/sessions/${id}`}
+ listKey="sessions"
+ />,
+ ]}
+ />
+ <div className="flex flex-wrap gap-2">
+ {session.data?.users.map((userId) => (
+ <Link key={userId} href={`/project/${projectId}/users/${userId}`}>
+ <Badge>User ID: {userId}</Badge>
+ </Link>
+ ))}
+ <Badge variant="outline">Traces: {session.data?.traces.length}</Badge>
+ </div>
+ <div className="mt-5 flex flex-col gap-2 border-t pt-5">
+ {session.data?.traces.map((trace) => (
+ <Card
+ className="border-border-gray-150 group grid gap-3 p-2 shadow-none hover:border-gray-300 md:grid-cols-3"
+ key={trace.id}
+ >
+ <div className="col-span-2 flex flex-col gap-2 p-0">
+ {trace.input || trace.output ? (
+ <IOPreview
+ key={trace.id}
+ input={trace.input}
+ output={trace.output}
+ hideIfNull
+ />
+ ) : (
+ <div className="p-2 text-xs text-gray-500">
+ This trace has no input or output.
+ </div>
+ )}
+ </div>
+ <div className="-mt-1 p-1 opacity-50 transition-opacity group-hover:opacity-100">
+ <Link
+ href={`/project/${projectId}/traces/${trace.id}`}
+ className="text-xs hover:underline"
+ >
+ Trace: {trace.name} ({trace.id})&nbsp;↗
+ </Link>
+ <div className="text-xs text-gray-500">
+ {trace.timestamp.toLocaleString()}
+ </div>
+ <div className="mb-1 mt-2 text-xs text-gray-500">Scores</div>
+ <div className="flex flex-wrap content-start items-start gap-1">
+ <GroupedScoreBadges scores={trace.scores} />
+ </div>
+ <ManualScoreButton
+ projectId={projectId}
+ traceId={trace.id}
+ scores={trace.scores}
+ variant="badge"
+ />
+ </div>
+ </Card>
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/star-toggle.tsx b/src/components/star-toggle.tsx
new file mode 100644
index 0000000000..dc4ab2da71
--- /dev/null
+++ b/src/components/star-toggle.tsx
@@ -0,0 +1,120 @@
+import { StarIcon } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { useEffect, useState } from "react";
+import { api } from "@/src/utils/api";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+
+export function StarToggle({
+ value,
+ disabled = false,
+ onClick,
+ size = "sm",
+}: {
+ value: boolean;
+ disabled?: boolean;
+ onClick: (value: boolean) => Promise<unknown>;
+ size?: "sm" | "xs";
+}) {
+ const [cachedValue, setCachedValue] = useState<boolean | null>(null);
+ const [loading, setLoading] = useState(false);
+ const optimisticValue = cachedValue ?? value;
+
+ useEffect(() => {
+ setCachedValue(null);
+ }, [value]);
+
+ const handleBookmarkClick = async () => {
+ if (disabled) return;
+ setLoading(true);
+ setCachedValue(!optimisticValue);
+ await onClick(!optimisticValue);
+ setLoading(false);
+ };
+
+ return (
+ <Button
+ variant="ghost"
+ size={size}
+ onClick={() => void handleBookmarkClick()}
+ disabled={disabled}
+ loading={loading}
+ >
+ <StarIcon
+ className={`h-4 w-4 ${
+ optimisticValue ? "fill-current text-yellow-500" : "text-gray-500"
+ }`}
+ />
+ </Button>
+ );
+}
+
+export function StarTraceToggle({
+ projectId,
+ traceId,
+ value,
+ size = "sm",
+}: {
+ projectId: string;
+ traceId: string;
+ value: boolean;
+ size?: "sm" | "xs";
+}) {
+ const utils = api.useUtils();
+ const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });
+ const mutBookmarkTrace = api.traces.bookmark.useMutation({
+ onSuccess: () => {
+ void utils.traces.invalidate();
+ },
+ });
+
+ return (
+ <StarToggle
+ value={value}
+ size={size}
+ disabled={!hasAccess}
+ onClick={(value) =>
+ mutBookmarkTrace.mutateAsync({
+ projectId,
+ traceId,
+ bookmarked: value,
+ })
+ }
+ />
+ );
+}
+
+export function StarSessionToggle({
+ projectId,
+ sessionId,
+ value,
+ size = "sm",
+}: {
+ projectId: string;
+ sessionId: string;
+ value: boolean;
+ size?: "sm" | "xs";
+}) {
+ const utils = api.useUtils();
+ const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });
+ const mutBookmarkSession = api.sessions.bookmark.useMutation({
+ onSuccess: () => {
+ void utils.sessions.invalidate();
+ },
+ });
+
+ return (
+ <StarToggle
+ value={value}
+ size={size}
+ disabled={!hasAccess}
+ onClick={(value) =>
+ mutBookmarkSession.mutateAsync({
+ projectId,
+ sessionId,
+ bookmarked: value,
+ })
+ }
+ />
+ );
+}
diff --git a/src/components/table/data-table-column-visibility-filter.tsx b/src/components/table/data-table-column-visibility-filter.tsx
index 2d8ba0c5f4..7628825ebf 100644
--- a/src/components/table/data-table-column-visibility-filter.tsx
+++ b/src/components/table/data-table-column-visibility-filter.tsx
@@ -11,11 +11,12 @@ import {
DropdownMenuTrigger,
DropdownMenuCheckboxItem,
} from "@/src/components/ui/dropdown-menu";
-import { type ColumnDef, type VisibilityState } from "@tanstack/react-table";
+import { type VisibilityState } from "@tanstack/react-table";
import { ChevronDownIcon } from "lucide-react";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
interface DataTableColumnVisibilityFilterProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
+ columns: LangfuseColumnDef<TData, TValue>[];
columnVisibility: VisibilityState;
setColumnVisibility: Dispatch<SetStateAction<VisibilityState>>;
}
diff --git a/src/components/table/data-table-toolbar.tsx b/src/components/table/data-table-toolbar.tsx
index fcfe86621a..866ea4981d 100644
--- a/src/components/table/data-table-toolbar.tsx
+++ b/src/components/table/data-table-toolbar.tsx
@@ -5,7 +5,8 @@ import { DataTableColumnVisibilityFilter } from "@/src/components/table/data-tab
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";
-import { type ColumnDef, type VisibilityState } from "@tanstack/react-table";
+import { type VisibilityState } from "@tanstack/react-table";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
interface SearchConfig {
placeholder: string;
@@ -14,7 +15,7 @@ interface SearchConfig {
}
interface DataTableToolbarProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
+ columns: LangfuseColumnDef<TData, TValue>[];
filterColumnDefinition: ColumnDefinition[];
searchConfig?: SearchConfig;
actionButtons?: React.ReactNode;
diff --git a/src/components/table/data-table.tsx b/src/components/table/data-table.tsx
index edc272cc66..4c2e867d66 100644
--- a/src/components/table/data-table.tsx
+++ b/src/components/table/data-table.tsx
@@ -1,7 +1,6 @@
"use client";
import {
- type ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
@@ -21,9 +20,10 @@ import {
} from "@/src/components/ui/table";
import { useState } from "react";
import { DataTablePagination } from "@/src/components/table/data-table-pagination";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
+ columns: LangfuseColumnDef<TData, TValue>[];
data: AsyncTableData<TData[]>;
pagination?: {
pageCount: number;
diff --git a/src/components/table/types.ts b/src/components/table/types.ts
index 988bdf1f9b..029273a949 100644
--- a/src/components/table/types.ts
+++ b/src/components/table/types.ts
@@ -1,6 +1,12 @@
+import { type RowData, type ColumnDef } from "@tanstack/react-table";
import { type LucideIcon } from "lucide-react";
export type TableRowOptions = {
columnId: string;
options: { label: string; value: number; icon?: LucideIcon }[];
};
+
+export type LangfuseColumnDef<
+ TData extends RowData,
+ TValue = unknown,
+> = ColumnDef<TData, TValue> & { defaultHidden?: boolean };
diff --git a/src/components/table/use-cases/generations.tsx b/src/components/table/use-cases/generations.tsx
index 30446b60e6..2601b255c7 100644
--- a/src/components/table/use-cases/generations.tsx
+++ b/src/components/table/use-cases/generations.tsx
@@ -1,5 +1,4 @@
import { api, directApi } from "@/src/utils/api";
-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";
@@ -24,8 +23,10 @@ import {
} from "use-query-params";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { observationsTableColsWithOptions } from "@/src/server/api/definitions/observationsTable";
-import { utcDateOffsetByDays } from "@/src/utils/dates";
+import { formatInterval, utcDateOffsetByDays } from "@/src/utils/dates";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
+import { JSONView } from "@/src/components/ui/code";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
import { type ObservationLevel } from "@prisma/client";
import { cn } from "@/src/utils/tailwind";
import { LevelColors } from "@/src/components/level-colors";
@@ -40,6 +41,8 @@ export type GenerationsTableRow = {
latency?: number;
name?: string;
model?: string;
+ input?: unknown;
+ output?: unknown;
traceName?: string;
metadata?: string;
usage: {
@@ -143,7 +146,7 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {
setIsExporting(false);
};
- const columns: ColumnDef<GenerationsTableRow>[] = [
+ const columns: LangfuseColumnDef<GenerationsTableRow>[] = [
{
accessorKey: "id",
header: "ID",
@@ -192,7 +195,7 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {
cell: ({ row }) => {
const value: number | undefined = row.getValue("latency");
return value !== undefined ? (
- <span>{value.toFixed(2)} sec</span>
+ <span>{formatInterval(value)}</span>
) : undefined;
},
enableHiding: true,
@@ -220,8 +223,8 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {
accessorKey: "statusMessage",
header: "Status Message",
enableHiding: true,
+ defaultHidden: true,
},
-
{
accessorKey: "model",
header: "Model",
@@ -247,6 +250,26 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {
},
enableHiding: true,
},
+ {
+ accessorKey: "input",
+ header: "Input",
+ cell: ({ row }) => {
+ const value: unknown = row.getValue("input");
+ return <JSONView json={value} className="w-[500px]" />;
+ },
+ enableHiding: true,
+ defaultHidden: true,
+ },
+ {
+ accessorKey: "output",
+ header: "Output",
+ cell: ({ row }) => {
+ const value: unknown = row.getValue("output");
+ return <JSONView json={value} className="w-[500px] bg-green-50" />;
+ },
+ enableHiding: true,
+ defaultHidden: true,
+ },
{
accessorKey: "metadata",
header: "Metadata",
@@ -255,6 +278,7 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {
return <div className="flex flex-wrap gap-x-3 gap-y-1">{values}</div>;
},
enableHiding: true,
+ defaultHidden: true,
},
{
accessorKey: "version",
@@ -279,6 +303,8 @@ export default function GenerationsTable({ projectId }: GenerationsTableProps) {
name: generation.name ?? undefined,
version: generation.version ?? "",
model: generation.model ?? "",
+ input: generation.input,
+ output: generation.output,
level: generation.level,
metadata: generation.metadata
? JSON.stringify(generation.metadata)
diff --git a/src/components/table/use-cases/scores.tsx b/src/components/table/use-cases/scores.tsx
index 099cd4e7af..30700f7f54 100644
--- a/src/components/table/use-cases/scores.tsx
+++ b/src/components/table/use-cases/scores.tsx
@@ -1,13 +1,13 @@
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 LangfuseColumnDef } from "@/src/components/table/types";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { scoresTableColsWithOptions } from "@/src/server/api/definitions/scoresTable";
import { api } from "@/src/utils/api";
import { type RouterInput } from "@/src/utils/types";
import { type Score } from "@prisma/client";
-import { type ColumnDef } from "@tanstack/react-table";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
export type ScoresTableRow = {
@@ -61,7 +61,7 @@ export default function ScoresTable({
projectId,
});
- const columns: ColumnDef<ScoresTableRow>[] = [
+ const columns: LangfuseColumnDef<ScoresTableRow>[] = [
{
accessorKey: "traceId",
enableColumnFilter: true,
diff --git a/src/components/table/use-cases/sessions.tsx b/src/components/table/use-cases/sessions.tsx
new file mode 100644
index 0000000000..793cfed7d4
--- /dev/null
+++ b/src/components/table/use-cases/sessions.tsx
@@ -0,0 +1,213 @@
+import { StarSessionToggle } from "@/src/components/star-toggle";
+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 LangfuseColumnDef } from "@/src/components/table/types";
+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { type FilterState } from "@/src/features/filters/types";
+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
+import { sessionsViewCols } from "@/src/server/api/definitions/sessionsView";
+import { api } from "@/src/utils/api";
+import { formatInterval, utcDateOffsetByDays } from "@/src/utils/dates";
+import { type RouterOutput } from "@/src/utils/types";
+import { useEffect } from "react";
+import { NumberParam, useQueryParams, withDefault } from "use-query-params";
+
+export type SessionTableRow = {
+ id: string;
+ createdAt: string;
+ userIds: string[];
+ countTraces: number;
+ bookmarked: boolean;
+ sessionDuration: number | null;
+};
+
+export type SessionTableProps = {
+ projectId: string;
+ userId?: string;
+ omittedFilter?: string[];
+};
+
+export default function SessionsTable({
+ projectId,
+ userId,
+ omittedFilter = [],
+}: SessionTableProps) {
+ const { setDetailPageList } = useDetailPageLists();
+
+ const [userFilterState, setUserFilterState] = useQueryFilterState([
+ {
+ column: "createdAt",
+ type: "datetime",
+ operator: ">",
+ value: utcDateOffsetByDays(-14),
+ },
+ ]);
+
+ const userIdFilter: FilterState = userId
+ ? [
+ {
+ column: "userId",
+ type: "string",
+ operator: "=",
+ value: userId,
+ },
+ ]
+ : [];
+
+ const filterState = userFilterState.concat(userIdFilter);
+
+ const [paginationState, setPaginationState] = useQueryParams({
+ pageIndex: withDefault(NumberParam, 0),
+ pageSize: withDefault(NumberParam, 50),
+ });
+
+ const sessions = api.sessions.all.useQuery({
+ page: paginationState.pageIndex,
+ limit: paginationState.pageSize,
+ projectId,
+ filter: filterState,
+ searchQuery: null,
+ });
+ const totalCount = sessions.data?.slice(1)[0]?.totalCount ?? 0;
+ useEffect(() => {
+ if (sessions.isSuccess && sessions.data) {
+ setDetailPageList(
+ "sessions",
+ sessions.data.map((t) => t.id),
+ );
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [sessions.isSuccess, sessions.data]);
+
+ const convertToTableRow = (
+ session: RouterOutput["sessions"]["all"][0],
+ ): SessionTableRow => {
+ return {
+ id: session.id,
+ createdAt: session.createdAt.toLocaleString(),
+ userIds: session.userIds ?? [],
+ countTraces: session.countTraces,
+ bookmarked: session.bookmarked,
+ sessionDuration: session.sessionDuration,
+ };
+ };
+
+ const columns: LangfuseColumnDef<SessionTableRow>[] = [
+ {
+ accessorKey: "bookmarked",
+ header: undefined,
+ cell: ({ row }) => {
+ const bookmarked = row.getValue("bookmarked");
+ const sessionId = row.getValue("id");
+
+ return typeof sessionId === "string" &&
+ typeof bookmarked === "boolean" ? (
+ <StarSessionToggle
+ sessionId={sessionId}
+ projectId={projectId}
+ value={bookmarked}
+ size="xs"
+ />
+ ) : undefined;
+ },
+ },
+ {
+ accessorKey: "id",
+ header: "ID",
+ cell: ({ row }) => {
+ const value = row.getValue("id");
+ return value && typeof value === "string" ? (
+ <TableLink
+ path={`/project/${projectId}/sessions/${value}`}
+ value={value}
+ />
+ ) : undefined;
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ enableHiding: true,
+ },
+ {
+ accessorKey: "sessionDuration",
+ header: "Duration",
+ enableHiding: true,
+ cell: ({ row }) => {
+ const value = row.getValue("sessionDuration");
+ return value && typeof value === "number"
+ ? formatInterval(value)
+ : undefined;
+ },
+ },
+ {
+ accessorKey: "userIds",
+ enableColumnFilter: !omittedFilter.find((f) => f === "userIds"),
+ header: "User ID",
+ enableHiding: true,
+ cell: ({ row }) => {
+ const value = row.getValue("userIds");
+ return value && Array.isArray(value) ? (
+ <div className="flex gap-1">
+ {(value as string[]).map((user) => (
+ <TableLink
+ key={user}
+ path={`/project/${projectId}/users/${user}`}
+ value={user}
+ truncateAt={40}
+ />
+ ))}
+ </div>
+ ) : undefined;
+ },
+ },
+ {
+ accessorKey: "countTraces",
+ header: "Traces",
+ enableHiding: true,
+ },
+ ];
+
+ const [columnVisibility, setColumnVisibility] =
+ useColumnVisibility<SessionTableRow>("sessionsColumnVisibility", columns);
+
+ return (
+ <div>
+ <DataTableToolbar
+ filterColumnDefinition={sessionsViewCols}
+ filterState={userFilterState}
+ setFilterState={setUserFilterState}
+ columns={columns}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibility}
+ />
+ <DataTable
+ columns={columns}
+ data={
+ sessions.isLoading
+ ? { isLoading: true, isError: false }
+ : sessions.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: sessions.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: sessions.data?.map((t) => convertToTableRow(t)),
+ }
+ }
+ pagination={{
+ pageCount: Math.ceil(totalCount / paginationState.pageSize),
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ />
+ </div>
+ );
+}
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index c7fb8978d8..fae423a621 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -10,10 +10,9 @@ import { type FilterState } from "@/src/features/filters/types";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { tracesTableColsWithOptions } from "@/src/server/api/definitions/tracesTable";
import { api } from "@/src/utils/api";
-import { utcDateOffsetByDays } from "@/src/utils/dates";
+import { formatInterval, utcDateOffsetByDays } from "@/src/utils/dates";
import { type RouterInput, type RouterOutput } from "@/src/utils/types";
import { type Score } from "@prisma/client";
-import { type ColumnDef } from "@tanstack/react-table";
import { useEffect } from "react";
import {
NumberParam,
@@ -22,7 +21,9 @@ import {
useQueryParams,
withDefault,
} from "use-query-params";
-import { BookmarkTrace } from "@/src/components/bookmark-trace";
+import { StarTraceToggle } from "@/src/components/star-toggle";
+import { JSONView } from "@/src/components/ui/code";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
export type TracesTableRow = {
bookmarked: boolean;
@@ -34,6 +35,9 @@ export type TracesTableRow = {
latency?: number;
release?: string;
version?: string;
+ input?: unknown;
+ output?: unknown;
+ sessionId?: string;
scores: Score[];
usage: {
promptTokens: number;
@@ -121,6 +125,9 @@ export default function TracesTable({
version: trace.version ?? undefined,
userId: trace.userId ?? "",
scores: trace.scores,
+ sessionId: trace.sessionId ?? undefined,
+ input: trace.input,
+ output: trace.output,
latency: trace.latency === null ? undefined : trace.latency,
usage: {
promptTokens: trace.promptTokens,
@@ -130,20 +137,20 @@ export default function TracesTable({
};
};
- const columns: ColumnDef<TracesTableRow>[] = [
+ const columns: LangfuseColumnDef<TracesTableRow>[] = [
{
accessorKey: "bookmarked",
header: undefined,
cell: ({ row }) => {
- const isBookmarked = row.getValue("bookmarked");
+ const bookmarked = row.getValue("bookmarked");
const traceId = row.getValue("id");
return typeof traceId === "string" &&
- typeof isBookmarked === "boolean" ? (
- <BookmarkTrace
+ typeof bookmarked === "boolean" ? (
+ <StarTraceToggle
traceId={traceId}
projectId={projectId}
- isBookmarked={isBookmarked}
+ value={bookmarked}
size="xs"
/>
) : undefined;
@@ -188,13 +195,29 @@ export default function TracesTable({
},
enableHiding: true,
},
+ {
+ accessorKey: "sessionId",
+ enableColumnFilter: !omittedFilter.find((f) => f === "sessionId"),
+ header: "Session ID",
+ cell: ({ row }) => {
+ const value = row.getValue("sessionId");
+ return value && typeof value === "string" ? (
+ <TableLink
+ path={`/project/${projectId}/sessions/${value}`}
+ value={value}
+ truncateAt={40}
+ />
+ ) : undefined;
+ },
+ enableHiding: true,
+ },
{
accessorKey: "latency",
header: "Latency",
// add seconds to the end of the latency
cell: ({ row }) => {
const value: number | undefined = row.getValue("latency");
- return value !== undefined ? `${value.toFixed(2)} sec` : undefined;
+ return value !== undefined ? formatInterval(value) : undefined;
},
enableHiding: true,
},
@@ -228,6 +251,26 @@ export default function TracesTable({
},
enableHiding: true,
},
+ {
+ accessorKey: "input",
+ header: "Input",
+ cell: ({ row }) => {
+ const value: unknown = row.getValue("input");
+ return <JSONView json={value} className="w-[500px]" />;
+ },
+ enableHiding: true,
+ defaultHidden: true,
+ },
+ {
+ accessorKey: "output",
+ header: "Output",
+ cell: ({ row }) => {
+ const value: unknown = row.getValue("output");
+ return <JSONView json={value} className="w-[500px] bg-green-50" />;
+ },
+ enableHiding: true,
+ defaultHidden: true,
+ },
{
accessorKey: "metadata",
header: "Metadata",
diff --git a/src/components/trace/IOPreview.tsx b/src/components/trace/IOPreview.tsx
new file mode 100644
index 0000000000..1b25581aff
--- /dev/null
+++ b/src/components/trace/IOPreview.tsx
@@ -0,0 +1,155 @@
+import { JSONView } from "@/src/components/ui/code";
+import { z } from "zod";
+import { deepParseJson } from "@/src/utils/json";
+import { cn } from "@/src/utils/tailwind";
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
+import { Fragment } from "react";
+
+export const IOPreview: React.FC<{
+ input?: unknown;
+ output?: unknown;
+ isLoading?: boolean;
+ hideIfNull?: boolean;
+}> = ({ isLoading = false, hideIfNull = false, ...props }) => {
+ const [currentView, setCurrentView] = useState<"pretty" | "json">("pretty");
+
+ const input = deepParseJson(props.input);
+ const output = deepParseJson(props.output);
+
+ // parse old completions: { completion: string } -> string
+ const outLegacyCompletionSchema = z
+ .object({
+ completion: z.string(),
+ })
+ .refine((value) => Object.keys(value).length === 1);
+ const outLegacyCompletionSchemaParsed =
+ outLegacyCompletionSchema.safeParse(output);
+ const outputClean = outLegacyCompletionSchemaParsed.success
+ ? outLegacyCompletionSchemaParsed.data
+ : props.output ?? null;
+
+ // OpenAI messages
+ let inOpenAiMessageArray = OpenAiMessageArraySchema.safeParse(input);
+ if (!inOpenAiMessageArray.success) {
+ // check if input is an array of length 1 including an array of OpenAiMessageSchema
+ // this is the case for some integrations
+ const inputArray = z.array(OpenAiMessageArraySchema).safeParse(input);
+ if (inputArray.success && inputArray.data.length === 1) {
+ inOpenAiMessageArray = OpenAiMessageArraySchema.safeParse(
+ inputArray.data[0],
+ );
+ }
+ }
+ const outOpenAiMessage = OpenAiMessageSchema.safeParse(output);
+
+ // Pretty view available
+ const isPrettyViewAvailable = inOpenAiMessageArray.success;
+
+ // default I/O
+ return (
+ <>
+ {isPrettyViewAvailable ? (
+ <Tabs
+ value={currentView}
+ onValueChange={(v) => setCurrentView(v as "pretty" | "json")}
+ >
+ <TabsList>
+ <TabsTrigger value="pretty">Pretty ✨</TabsTrigger>
+ <TabsTrigger value="json">JSON</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ ) : null}
+ {isPrettyViewAvailable && currentView === "pretty" ? (
+ inOpenAiMessageArray.success ? (
+ <OpenAiMessageView
+ messages={inOpenAiMessageArray.data.concat(
+ outOpenAiMessage.success
+ ? {
+ ...outOpenAiMessage.data,
+ role: outOpenAiMessage.data.role ?? "assistant",
+ }
+ : {
+ role: "assistant",
+ content: JSON.stringify(outputClean) ?? null,
+ },
+ )}
+ />
+ ) : null
+ ) : null}
+ {currentView === "json" || !isPrettyViewAvailable ? (
+ <>
+ {!(hideIfNull && !input) ? (
+ <JSONView
+ title="Input"
+ json={input ?? null}
+ isLoading={isLoading}
+ className="flex-1"
+ />
+ ) : null}
+ {!(hideIfNull && !output) ? (
+ <JSONView
+ title="Output"
+ json={outputClean}
+ isLoading={isLoading}
+ className="flex-1 bg-green-50"
+ />
+ ) : null}
+ </>
+ ) : null}
+ </>
+ );
+};
+
+const OpenAiMessageSchema = z
+ .object({
+ role: z.enum(["system", "user", "assistant"]).optional(),
+ content: z.string().nullable(),
+ })
+ .refine((value) => value.content !== null || value.role !== undefined);
+
+const OpenAiMessageArraySchema = z.array(OpenAiMessageSchema).min(1);
+
+const OpenAiMessageView: React.FC<{
+ messages: z.infer<typeof OpenAiMessageArraySchema>;
+}> = ({ messages }) => {
+ const COLLAPSE_THRESHOLD = 3;
+ const [isCollapsed, setCollapsed] = useState(
+ messages.length > COLLAPSE_THRESHOLD ? true : null,
+ );
+
+ return (
+ <div className="flex flex-col gap-2 rounded-md border p-3">
+ {messages
+ .filter(
+ (_, i) =>
+ // show all if not collapsed or null; show first and last n if collapsed
+ !isCollapsed || i == 0 || i > messages.length - COLLAPSE_THRESHOLD,
+ )
+ .map((message, index) => (
+ <Fragment key={index}>
+ <JSONView
+ title={message.role}
+ json={message.content}
+ className={cn(
+ message.role === "system" && "bg-gray-100",
+ message.role === "assistant" && "bg-green-50",
+ )}
+ />
+ {isCollapsed !== null && index === 0 ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => setCollapsed((v) => !v)}
+ >
+ {isCollapsed
+ ? `Show ${messages.length - COLLAPSE_THRESHOLD} more ...`
+ : "Hide history"}
+ </Button>
+ ) : null}
+ </Fragment>
+ ))}
+ </div>
+ );
+};
diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsx
index 17aa001eb0..4db7bfbf34 100644
--- a/src/components/trace/ObservationPreview.tsx
+++ b/src/components/trace/ObservationPreview.tsx
@@ -16,16 +16,12 @@ import {
TableHeader,
TableRow,
} from "@/src/components/ui/table";
-import { ManualScoreButton } from "@/src/features/manual-scoring/components";
+import { ManualScoreButton } from "@/src/features/manual-scoring/components/ManualScoreButton";
import { NewDatasetItemFromObservationButton } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
-import { z } from "zod";
-import { deepParseJson } from "@/src/utils/json";
-import { cn } from "@/src/utils/tailwind";
-import { useState } from "react";
-import { Button } from "@/src/components/ui/button";
-import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
+import { IOPreview } from "@/src/components/trace/IOPreview";
+import { formatInterval } from "@/src/utils/dates";
export const ObservationPreview = (props: {
observations: Array<ObservationReturnType>;
@@ -60,18 +56,20 @@ export const ObservationPreview = (props: {
<div className="flex flex-wrap gap-2">
{preloadedObservation.endTime ? (
<Badge variant="outline">
- {`${(
+ {formatInterval(
(preloadedObservation.endTime.getTime() -
preloadedObservation.startTime.getTime()) /
- 1000
- ).toFixed(2)} sec`}
+ 1000,
+ )}
</Badge>
) : null}
- <Badge variant="outline">
- {preloadedObservation.promptTokens} prompt →{" "}
- {preloadedObservation.completionTokens} completion (∑{" "}
- {preloadedObservation.totalTokens})
- </Badge>
+ {preloadedObservation.type === "GENERATION" && (
+ <Badge variant="outline">
+ {preloadedObservation.promptTokens} prompt →{" "}
+ {preloadedObservation.completionTokens} completion (∑{" "}
+ {preloadedObservation.totalTokens})
+ </Badge>
+ )}
{preloadedObservation.version ? (
<Badge variant="outline">
Version: {preloadedObservation.version}
@@ -116,14 +114,12 @@ export const ObservationPreview = (props: {
</div>
</CardHeader>
<CardContent className="flex flex-col gap-4">
- <ObservationIO
+ <IOPreview
key={preloadedObservation.id + "-input"}
- observationType={preloadedObservation.type}
input={observationWithInputAndOutput.data?.input ?? undefined}
output={observationWithInputAndOutput.data?.output ?? undefined}
isLoading={observationWithInputAndOutput.isLoading}
/>
-
{preloadedObservation.statusMessage ? (
<JSONView
key={preloadedObservation.id + "-status"}
@@ -177,147 +173,3 @@ export const ObservationPreview = (props: {
</Card>
);
};
-
-const ObservationIO: React.FC<{
- observationType: string;
- input?: unknown;
- output?: unknown;
- isLoading: boolean;
-}> = ({ isLoading, ...props }) => {
- const [currentView, setCurrentView] = useState<"pretty" | "json">("pretty");
-
- const input = deepParseJson(props.input);
- const output = deepParseJson(props.output);
-
- // parse old completions: { completion: string } -> string
- const outLegacyCompletionSchema = z
- .object({
- completion: z.string(),
- })
- .refine((value) => Object.keys(value).length === 1);
- const outLegacyCompletionSchemaParsed =
- outLegacyCompletionSchema.safeParse(output);
- const outputClean = outLegacyCompletionSchemaParsed.success
- ? outLegacyCompletionSchemaParsed.data
- : props.output ?? null;
-
- // OpenAI messages
- let inOpenAiMessageArray = OpenAiMessageArraySchema.safeParse(input);
- if (!inOpenAiMessageArray.success) {
- // check if input is an array of length 1 including an array of OpenAiMessageSchema
- // this is the case for some integrations
- const inputArray = z.array(OpenAiMessageArraySchema).safeParse(input);
- if (inputArray.success && inputArray.data.length === 1) {
- inOpenAiMessageArray = OpenAiMessageArraySchema.safeParse(
- inputArray.data[0],
- );
- }
- }
- const outOpenAiMessage = OpenAiMessageSchema.safeParse(output);
-
- // Pretty view available
- const isPrettyViewAvailable = inOpenAiMessageArray.success;
-
- // default I/O
- return (
- <>
- {isPrettyViewAvailable ? (
- <Tabs
- value={currentView}
- onValueChange={(v) => setCurrentView(v as "pretty" | "json")}
- >
- <TabsList>
- <TabsTrigger value="pretty">Pretty ✨</TabsTrigger>
- <TabsTrigger value="json">JSON</TabsTrigger>
- </TabsList>
- </Tabs>
- ) : null}
- {isPrettyViewAvailable && currentView === "pretty" ? (
- inOpenAiMessageArray.success ? (
- <OpenAiMessageView
- messages={inOpenAiMessageArray.data.concat(
- outOpenAiMessage.success
- ? {
- ...outOpenAiMessage.data,
- role: outOpenAiMessage.data.role ?? "assistant",
- }
- : {
- role: "assistant",
- content: JSON.stringify(outputClean) ?? null,
- },
- )}
- />
- ) : null
- ) : null}
- {currentView === "json" || !isPrettyViewAvailable ? (
- <>
- <JSONView
- title="Input"
- json={input ?? null}
- isLoading={isLoading}
- className="flex-1"
- />
- <JSONView
- title="Output"
- json={outputClean}
- isLoading={isLoading}
- className="flex-1"
- />
- </>
- ) : null}
- </>
- );
-};
-
-const OpenAiMessageSchema = z
- .object({
- role: z.enum(["system", "user", "assistant"]).optional(),
- content: z.string().nullable(),
- })
- .refine((value) => value.content !== null || value.role !== undefined);
-
-const OpenAiMessageArraySchema = z.array(OpenAiMessageSchema).min(1);
-
-const OpenAiMessageView: React.FC<{
- messages: z.infer<typeof OpenAiMessageArraySchema>;
-}> = ({ messages }) => {
- const COLLAPSE_THRESHOLD = 3;
- const [isCollapsed, setCollapsed] = useState(
- messages.length > COLLAPSE_THRESHOLD ? true : null,
- );
-
- return (
- <div className="flex flex-col gap-2 rounded-md border p-3">
- {messages
- .filter(
- (_, i) =>
- // show all if not collapsed or null; show first and last n if collapsed
- !isCollapsed || i == 0 || i > messages.length - COLLAPSE_THRESHOLD,
- )
- .map((message, index) => (
- <>
- <JSONView
- title={message.role}
- json={message.content}
- key={index}
- className={cn(
- message.role === "system" && "bg-gray-100",
- message.role === "assistant" && "bg-green-50",
- )}
- />
- {isCollapsed !== null && index === 0 ? (
- <Button
- variant="ghost"
- size="xs"
- onClick={() => setCollapsed((v) => !v)}
- >
- {isCollapsed
- ? `Show ${messages.length - COLLAPSE_THRESHOLD} more ...`
- : "Hide history"}
- </Button>
- ) : null}
- </>
- ))}
- </div>
- );
-};
diff --git a/src/components/trace/ObservationTree.tsx b/src/components/trace/ObservationTree.tsx
index f59f3ee007..bb7d6ed00a 100644
--- a/src/components/trace/ObservationTree.tsx
+++ b/src/components/trace/ObservationTree.tsx
@@ -5,6 +5,7 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { Fragment } from "react";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { LevelColors } from "@/src/components/level-colors";
+import { formatInterval } from "@/src/utils/dates";
export const ObservationTree = (props: {
observations: ObservationReturnType[];
@@ -56,7 +57,7 @@ const ObservationTreeTraceNode = (props: {
{props.trace.latency ? (
<div className="flex gap-2">
<span className="text-xs text-gray-500">
- {props.trace.latency.toFixed(2)} sec
+ {formatInterval(props.trace.latency)}
</span>
</div>
) : null}
@@ -107,12 +108,11 @@ const ObservationTreeNode = (props: {
<div className="flex gap-2">
{observation.endTime ? (
<span className="text-xs text-gray-500">
- {(
+ {formatInterval(
(observation.endTime.getTime() -
observation.startTime.getTime()) /
- 1000
- ).toFixed(2)}{" "}
- sec
+ 1000,
+ )}
</span>
) : null}
{observation.promptTokens ||
diff --git a/src/components/trace/TracePreview.tsx b/src/components/trace/TracePreview.tsx
index 14cf90000f..dc88cb7c18 100644
--- a/src/components/trace/TracePreview.tsx
+++ b/src/components/trace/TracePreview.tsx
@@ -17,16 +17,18 @@ import {
TableRow,
} from "@/src/components/ui/table";
import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
-import { ManualScoreButton } from "@/src/features/manual-scoring/components";
+import { ManualScoreButton } from "@/src/features/manual-scoring/components/ManualScoreButton";
import { Badge } from "@/src/components/ui/badge";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
+import { IOPreview } from "@/src/components/trace/IOPreview";
+import { formatInterval } from "@/src/utils/dates";
export const TracePreview = ({
trace,
observations,
scores,
}: {
- trace: Trace;
+ trace: Trace & { latency?: number };
observations: ObservationReturnType[];
scores: Score[];
}) => {
@@ -42,13 +44,16 @@ export const TracePreview = ({
</CardTitle>
<CardDescription>{trace.timestamp.toLocaleString()}</CardDescription>
<div className="flex flex-wrap gap-2">
+ {!!trace.latency && (
+ <Badge variant="outline">{formatInterval(trace.latency)}</Badge>
+ )}
<TraceAggUsageBadge observations={observations} />
- {trace.release ? (
+ {!!trace.release && (
<Badge variant="outline">Release: {trace.release}</Badge>
- ) : undefined}
- {trace.version ? (
+ )}
+ {!!trace.version && (
<Badge variant="outline">Version: {trace.version}</Badge>
- ) : undefined}
+ )}
</div>
</div>
<ManualScoreButton
@@ -57,7 +62,12 @@ export const TracePreview = ({
scores={scores}
/>
</CardHeader>
- <CardContent>
+ <CardContent className="flex flex-col gap-4">
+ <IOPreview
+ key={trace.id + "-io"}
+ input={trace.input ?? undefined}
+ output={trace.output ?? undefined}
+ />
<JSONView
key={trace.id + "-metadata"}
title="Metadata"
diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsx
index c5b7412143..6d5e908166 100644
--- a/src/components/trace/index.tsx
+++ b/src/components/trace/index.tsx
@@ -8,13 +8,15 @@ import { Badge } from "@/src/components/ui/badge";
import { TraceAggUsageBadge } from "@/src/components/token-usage-badge";
import Decimal from "decimal.js";
import { StringParam, useQueryParam } from "use-query-params";
-import { PublishTraceSwitch } from "@/src/features/public-traces/components/PublishTraceSwitch";
+import { PublishTraceSwitch } from "@/src/components/publish-object-switch";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
import { useRouter } from "next/router";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
import { DeleteTrace } from "@/src/components/delete-trace";
-import { BookmarkTrace } from "@/src/components/bookmark-trace";
+import { StarTraceToggle } from "@/src/components/star-toggle";
+import Link from "next/link";
+import { NoAccessError } from "@/src/components/no-access";
export function Trace(props: {
observations: Array<ObservationReturnType>;
@@ -72,7 +74,15 @@ export function Trace(props: {
export function TracePage({ traceId }: { traceId: string }) {
const router = useRouter();
- const trace = api.traces.byId.useQuery({ traceId });
+ const trace = api.traces.byId.useQuery(
+ { traceId },
+ {
+ retry(failureCount, error) {
+ if (error.data?.code === "UNAUTHORIZED") return false;
+ return failureCount < 3;
+ },
+ },
+ );
const totalCost = trace.data?.observations.reduce(
(acc, o) => {
if (!o.price) return acc;
@@ -84,10 +94,11 @@ export function TracePage({ traceId }: { traceId: string }) {
undefined as Decimal | undefined,
);
+ if (trace.error?.data?.code === "UNAUTHORIZED") return <NoAccessError />;
if (!trace.data) return <div>loading...</div>;
return (
- <div className="flex flex-col overflow-hidden xl:container lg:h-[calc(100vh-100px)] xl:h-[calc(100vh-50px)]">
+ <div className="flex flex-col overflow-hidden xl:container">
<Header
title="Trace Detail"
breadcrumb={[
@@ -99,10 +110,10 @@ export function TracePage({ traceId }: { traceId: string }) {
]}
actionButtons={
<>
- <BookmarkTrace
+ <StarTraceToggle
traceId={trace.data.id}
projectId={trace.data.projectId}
- isBookmarked={trace.data.bookmarked}
+ value={trace.data.bookmarked}
/>
<PublishTraceSwitch
traceId={trace.data.id}
@@ -123,9 +134,24 @@ export function TracePage({ traceId }: { traceId: string }) {
</>
}
/>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2">
+ {trace.data.sessionId ? (
+ <Link
+ href={`/project/${router.query.projectId as string}/sessions/${
+ trace.data.sessionId
+ }`}
+ >
+ <Badge>Session: {trace.data.sessionId}</Badge>
+ </Link>
+ ) : null}
{trace.data.userId ? (
- <Badge variant="outline">User ID: {trace.data.userId}</Badge>
+ <Link
+ href={`/project/${router.query.projectId as string}/users/${
+ trace.data.userId
+ }`}
+ >
+ <Badge>User ID: {trace.data.userId}</Badge>
+ </Link>
) : null}
<TraceAggUsageBadge observations={trace.data.observations ?? []} />
{totalCost ? (
diff --git a/src/features/column-visibility/hooks/useColumnVisibility.ts b/src/features/column-visibility/hooks/useColumnVisibility.ts
index d017404ffc..d6f8703b6c 100644
--- a/src/features/column-visibility/hooks/useColumnVisibility.ts
+++ b/src/features/column-visibility/hooks/useColumnVisibility.ts
@@ -1,16 +1,35 @@
import { useState, useEffect } from "react";
-import { type ColumnDef, type VisibilityState } from "@tanstack/react-table";
+import { type VisibilityState } from "@tanstack/react-table";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
function useColumnVisibility<TData>(
localStorageKey: string,
- columns: ColumnDef<TData>[],
+ columns: LangfuseColumnDef<TData>[],
) {
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(
() => {
- const savedVisibility = localStorage.getItem(localStorageKey);
- return savedVisibility
- ? (JSON.parse(savedVisibility) as VisibilityState)
- : {};
+ try {
+ const savedVisibility = localStorage.getItem(localStorageKey);
+ const visibilityState: VisibilityState = savedVisibility
+ ? (JSON.parse(savedVisibility) as VisibilityState)
+ : {};
+ // set default visibility for columns that are not in the saved state
+ columns.forEach((column) => {
+ if (
+ "accessorKey" in column &&
+ typeof column.accessorKey === "string"
+ ) {
+ if (!(column.accessorKey in visibilityState)) {
+ visibilityState[column.accessorKey] =
+ column.defaultHidden === true ? false : true;
+ }
+ }
+ });
+ return visibilityState;
+ } catch (e) {
+ console.error("Error while loading saved column visibility", e);
+ return {};
+ }
},
);
@@ -21,10 +40,22 @@ function useColumnVisibility<TData>(
const initialVisibility: VisibilityState = {};
columns.forEach((column) => {
if ("accessorKey" in column && typeof column.accessorKey === "string") {
- initialVisibility[column.accessorKey] = true;
+ initialVisibility[column.accessorKey] =
+ column.defaultHidden === true ? false : true;
}
});
setColumnVisibility(initialVisibility);
+ } else {
+ // make sure all columns are in the visibility state
+ const visibilityState = JSON.parse(localStorageItem) as VisibilityState;
+ columns.forEach((column) => {
+ if ("accessorKey" in column && typeof column.accessorKey === "string") {
+ if (!(column.accessorKey in visibilityState)) {
+ visibilityState[column.accessorKey] =
+ column.defaultHidden === true ? false : true;
+ }
+ }
+ });
}
}, [columns, localStorageKey]);
diff --git a/src/features/datasets/components/DatasetItemsTable.tsx b/src/features/datasets/components/DatasetItemsTable.tsx
index be98393c6f..e18e87e51c 100644
--- a/src/features/datasets/components/DatasetItemsTable.tsx
+++ b/src/features/datasets/components/DatasetItemsTable.tsx
@@ -3,7 +3,6 @@ import TableLink from "@/src/components/table/table-link";
import { NewDatasetItemButton } from "@/src/features/datasets/components/NewDatasetItemButton";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
-import { type ColumnDef } from "@tanstack/react-table";
import {
DropdownMenu,
DropdownMenuContent,
@@ -15,6 +14,7 @@ import { Archive, MoreVertical } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { DatasetStatus, type DatasetItem } from "@prisma/client";
import { cn } from "@/src/utils/tailwind";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
type RowData = {
id: string;
@@ -41,7 +41,7 @@ export function DatasetItemsTable({
onSuccess: () => utils.datasets.invalidate(),
});
- const columns: ColumnDef<RowData>[] = [
+ const columns: LangfuseColumnDef<RowData>[] = [
{
accessorKey: "id",
header: "Item id",
diff --git a/src/features/datasets/components/DatasetRunItemsTable.tsx b/src/features/datasets/components/DatasetRunItemsTable.tsx
index a908c23d2c..c82c6965be 100644
--- a/src/features/datasets/components/DatasetRunItemsTable.tsx
+++ b/src/features/datasets/components/DatasetRunItemsTable.tsx
@@ -1,10 +1,10 @@
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
import { api } from "@/src/utils/api";
-import { intervalInSeconds } from "@/src/utils/dates";
+import { formatInterval, intervalInSeconds } from "@/src/utils/dates";
import { type RouterOutput } from "@/src/utils/types";
-import { type ColumnDef } from "@tanstack/react-table";
type RowData = {
id: string;
@@ -30,7 +30,7 @@ export function DatasetRunItemsTable(
) {
const runItems = api.datasets.runitemsByRunIdOrItemId.useQuery(props);
- const columns: ColumnDef<RowData>[] = [
+ const columns: LangfuseColumnDef<RowData>[] = [
{
accessorKey: "runAt",
header: "Run At",
@@ -68,7 +68,7 @@ export function DatasetRunItemsTable(
header: "Latency",
cell: ({ row }) => {
const latency: RowData["latency"] = row.getValue("latency");
- return <>{latency.toFixed(2)} sec</>;
+ return <>{formatInterval(latency)}</>;
},
},
{
diff --git a/src/features/datasets/components/DatasetRunsTable.tsx b/src/features/datasets/components/DatasetRunsTable.tsx
index 87de905fed..08ef57fd1d 100644
--- a/src/features/datasets/components/DatasetRunsTable.tsx
+++ b/src/features/datasets/components/DatasetRunsTable.tsx
@@ -1,9 +1,10 @@
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
import { api } from "@/src/utils/api";
+import { formatInterval } from "@/src/utils/dates";
import { type RouterOutput } from "@/src/utils/types";
-import { type ColumnDef } from "@tanstack/react-table";
type RowData = {
key: {
@@ -25,7 +26,7 @@ export function DatasetRunsTable(props: {
datasetId: props.datasetId,
});
- const columns: ColumnDef<RowData>[] = [
+ const columns: LangfuseColumnDef<RowData>[] = [
{
accessorKey: "key",
header: "Name",
@@ -53,7 +54,7 @@ export function DatasetRunsTable(props: {
header: "Latency (avg)",
cell: ({ row }) => {
const avgLatency: RowData["avgLatency"] = row.getValue("avgLatency");
- return <>{avgLatency.toFixed(2)} sec</>;
+ return <>{formatInterval(avgLatency)}</>;
},
},
{
diff --git a/src/features/datasets/components/DatasetsTable.tsx b/src/features/datasets/components/DatasetsTable.tsx
index f1236bf484..472adbbd83 100644
--- a/src/features/datasets/components/DatasetsTable.tsx
+++ b/src/features/datasets/components/DatasetsTable.tsx
@@ -1,5 +1,6 @@
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
import { Button } from "@/src/components/ui/button";
import {
DropdownMenu,
@@ -13,7 +14,6 @@ import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
import { type RouterOutput } from "@/src/utils/types";
import { DatasetStatus } from "@prisma/client";
-import { type ColumnDef } from "@tanstack/react-table";
import { Archive, MoreVertical } from "lucide-react";
type RowData = {
@@ -37,7 +37,7 @@ export function DatasetsTable(props: { projectId: string }) {
onSuccess: () => utils.datasets.invalidate(),
});
- const columns: ColumnDef<RowData>[] = [
+ const columns: LangfuseColumnDef<RowData>[] = [
{
accessorKey: "key",
header: "Name",
diff --git a/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx b/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
index 67387f6bc3..41732aef26 100644
--- a/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
+++ b/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
@@ -20,6 +20,7 @@ import Link from "next/link";
import { NewDatasetItemForm } from "@/src/features/datasets/components/NewDatasetItemForm";
import { type Prisma } from "@prisma/client";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { useSession } from "next-auth/react";
export const NewDatasetItemFromObservationButton = (props: {
projectId: string;
@@ -28,10 +29,16 @@ export const NewDatasetItemFromObservationButton = (props: {
observationOutput: Prisma.JsonValue;
}) => {
const [open, setOpen] = useState(false);
- const observationInDatasets = api.datasets.observationInDatasets.useQuery({
- projectId: props.projectId,
- observationId: props.observationId,
- });
+ const session = useSession();
+ const observationInDatasets = api.datasets.observationInDatasets.useQuery(
+ {
+ projectId: props.projectId,
+ observationId: props.observationId,
+ },
+ {
+ enabled: session.status === "authenticated",
+ },
+ );
const hasAccess = useHasAccess({
projectId: props.projectId,
scope: "datasets:CUD",
@@ -91,7 +98,7 @@ export const NewDatasetItemFromObservationButton = (props: {
</Button>
)}
<Dialog open={hasAccess && open} onOpenChange={setOpen}>
- <DialogContent className="sm:w-3xl lg:h-[calc(100vh-100px)] lg:w-[calc(100vw-100px)] lg:max-w-none">
+ <DialogContent className="sm:w-3xl lg:max-w-none">
<DialogHeader>
<DialogTitle className="mb-5">Add to dataset</DialogTitle>
</DialogHeader>
diff --git a/src/features/manual-scoring/components/index.tsx b/src/features/manual-scoring/components/ManualScoreButton.tsx
similarity index 88%
rename from src/features/manual-scoring/components/index.tsx
rename to src/features/manual-scoring/components/ManualScoreButton.tsx
index dcbe77be6b..9d4c59bb63 100644
--- a/src/features/manual-scoring/components/index.tsx
+++ b/src/features/manual-scoring/components/ManualScoreButton.tsx
@@ -26,6 +26,7 @@ import { useForm } from "react-hook-form";
import { Slider } from "@/src/components/ui/slider";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { LockIcon } from "lucide-react";
+import { Badge } from "@/src/components/ui/badge";
const SCORE_NAME = "manual-score";
@@ -39,11 +40,13 @@ export function ManualScoreButton({
scores,
observationId,
projectId,
+ variant = "button",
}: {
traceId: string;
scores: Score[];
observationId?: string;
projectId: string;
+ variant?: "button" | "badge";
}) {
const hasAccess = useHasAccess({
projectId,
@@ -60,7 +63,11 @@ export function ManualScoreButton({
const utils = api.useUtils();
const onSuccess = async () => {
- await Promise.all([utils.scores.invalidate(), utils.traces.invalidate()]);
+ await Promise.all([
+ utils.scores.invalidate(),
+ utils.traces.invalidate(),
+ utils.sessions.invalidate(),
+ ]);
};
const mutCreateScore = api.scores.create.useMutation({ onSuccess });
const mutUpdateScore = api.scores.update.useMutation({ onSuccess });
@@ -114,13 +121,21 @@ export function ManualScoreButton({
onOpenChange(false);
};
+ if (!hasAccess && variant === "badge") return null;
+
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
- <Button variant="secondary" disabled={!hasAccess}>
- <span>{score ? `Update score: ${score.value}` : "Add score"}</span>
- {!hasAccess ? <LockIcon className="ml-2 h-3 w-3" /> : null}
- </Button>
+ {variant === "button" ? (
+ <Button variant="secondary" disabled={!hasAccess}>
+ <span>{score ? `Update score: ${score.value}` : "Add score"}</span>
+ {!hasAccess ? <LockIcon className="ml-2 h-3 w-3" /> : null}
+ </Button>
+ ) : (
+ <Badge className="cursor-pointer">
+ {score ? "Update score" : "Add score"}
+ </Badge>
+ )}
</DialogTrigger>
<DialogContent>
<DialogHeader>
diff --git a/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.ts
index 5fe0ef07ae..06935f6e01 100644
--- a/src/features/public-api/server/ingestion-api-schema.ts
+++ b/src/features/public-api/server/ingestion-api-schema.ts
@@ -6,6 +6,9 @@ export const TraceSchema = z.object({
id: z.string().nullish(),
name: z.string().nullish(),
externalId: z.string().nullish(),
+ input: jsonSchema.nullish(),
+ output: jsonSchema.nullish(),
+ sessionId: z.string().nullish(),
userId: z.string().nullish(),
metadata: jsonSchema.nullish(),
release: z.string().nullish(),
diff --git a/src/features/public-traces/components/PublishTraceSwitch.tsx b/src/features/public-traces/components/PublishTraceSwitch.tsx
deleted file mode 100644
index bec656a1f8..0000000000
--- a/src/features/public-traces/components/PublishTraceSwitch.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { Switch } from "@/src/components/ui/switch";
-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
-import { api } from "@/src/utils/api";
-import { Link, LockIcon } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
-import { useState } from "react";
-
-export const PublishTraceSwitch = (props: {
- traceId: string;
- projectId: string;
- isPublic: boolean;
-}) => {
- const posthog = usePostHog();
- const hasAccess = useHasAccess({
- projectId: props.projectId,
- scope: "traces:publish",
- });
- const utils = api.useUtils();
- 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
- <LockIcon 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,
- });
- posthog.capture("trace_detail:publish_trace_button_click");
- }}
- disabled={!hasAccess}
- />
- </div>
- );
-};
diff --git a/src/features/public-traces/server/publishTracesRouter.ts b/src/features/public-traces/server/publishTracesRouter.ts
deleted file mode 100644
index 12141149c5..0000000000
--- a/src/features/public-traces/server/publishTracesRouter.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
-import {
- createTRPCRouter,
- protectedProjectProcedure,
-} from "@/src/server/api/trpc";
-import * as z from "zod";
-
-export const publishTracesRouter = createTRPCRouter({
- update: protectedProjectProcedure
- .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 3978b0747f..c76d02e5fd 100644
--- a/src/features/rbac/constants/roleAccessRights.ts
+++ b/src/features/rbac/constants/roleAccessRights.ts
@@ -9,8 +9,9 @@ const scopes = [
"apiKeys:create",
"apiKeys:delete",
- "traces:publish",
- "traces:bookmark",
+ "objects:publish",
+ "objects:bookmark",
+
"traces:delete",
"scores:CUD",
@@ -33,8 +34,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"apiKeys:read",
"apiKeys:create",
"apiKeys:delete",
- "traces:publish",
- "traces:bookmark",
+ "objects:publish",
+ "objects:bookmark",
"traces:delete",
"scores:CUD",
"project:delete",
@@ -50,16 +51,16 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"apiKeys:read",
"apiKeys:create",
"apiKeys:delete",
- "traces:publish",
- "traces:bookmark",
+ "objects:publish",
+ "objects:bookmark",
"traces:delete",
"scores:CUD",
"datasets:CUD",
],
MEMBER: [
"members:read",
- "traces:publish",
- "traces:bookmark",
+ "objects:publish",
+ "objects:bookmark",
"scores:CUD",
"datasets:CUD",
],
diff --git a/src/pages/api/public/sessions/[sessionId].ts b/src/pages/api/public/sessions/[sessionId].ts
new file mode 100644
index 0000000000..67e6e5b25a
--- /dev/null
+++ b/src/pages/api/public/sessions/[sessionId].ts
@@ -0,0 +1,71 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { z } from "zod";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { prisma } from "@/src/server/db";
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+
+const GetSessionSchema = z.object({
+ sessionId: z.string(),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ if (req.method !== "GET") {
+ console.error(req.method, req.body, req.query);
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ // CHECK AUTH
+ const authCheck = await verifyAuthHeaderAndReturnScope(
+ req.headers.authorization,
+ );
+ if (!authCheck.validKey)
+ return res.status(401).json({
+ message: authCheck.error,
+ });
+ // END CHECK AUTH
+
+ try {
+ console.log("Trying to get session:", req.body, req.query);
+
+ const { sessionId } = GetSessionSchema.parse(req.query);
+
+ // CHECK ACCESS SCOPE
+ if (authCheck.scope.accessLevel !== "all") {
+ return res.status(401).json({
+ message:
+ "Access denied - need to use basic auth with secret key to GET traces",
+ });
+ }
+ // END CHECK ACCESS SCOPE
+
+ const session = await prisma.traceSession.findUnique({
+ where: {
+ id: sessionId,
+ projectId: authCheck.scope.projectId,
+ },
+ include: {
+ traces: true,
+ },
+ });
+
+ if (!session) {
+ return res.status(404).json({
+ message: "Session not found within authorized project",
+ });
+ }
+ return res.status(200).json(session);
+ } catch (error: unknown) {
+ console.error(error);
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+}
diff --git a/src/pages/project/[projectId]/sessions.tsx b/src/pages/project/[projectId]/sessions.tsx
new file mode 100644
index 0000000000..90f55ef3a0
--- /dev/null
+++ b/src/pages/project/[projectId]/sessions.tsx
@@ -0,0 +1,23 @@
+import Header from "@/src/components/layouts/header";
+import { useRouter } from "next/router";
+import SessionsTable from "@/src/components/table/use-cases/sessions";
+
+export default function Sessions() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+
+ return (
+ <div className="xl:container">
+ <Header
+ title="Sessions"
+ help={{
+ description:
+ "A session is a collection of related traces, such as a conversation or thread. To begin, add a sessionId to the trace.",
+ href: "https://langfuse.com/docs/sessions",
+ }}
+ />
+
+ <SessionsTable projectId={projectId} />
+ </div>
+ );
+}
diff --git a/src/pages/project/[projectId]/sessions/[sessionId].tsx b/src/pages/project/[projectId]/sessions/[sessionId].tsx
new file mode 100644
index 0000000000..849e6c293f
--- /dev/null
+++ b/src/pages/project/[projectId]/sessions/[sessionId].tsx
@@ -0,0 +1,10 @@
+import { useRouter } from "next/router";
+import { SessionPage } from "@/src/components/session";
+
+export default function Trace() {
+ const router = useRouter();
+ const sessionId = router.query.sessionId as string;
+ const projectId = router.query.projectId as string;
+
+ return <SessionPage sessionId={sessionId} projectId={projectId} />;
+}
diff --git a/src/pages/project/[projectId]/users.tsx b/src/pages/project/[projectId]/users.tsx
index b927d37690..6fad57ca32 100644
--- a/src/pages/project/[projectId]/users.tsx
+++ b/src/pages/project/[projectId]/users.tsx
@@ -1,7 +1,6 @@
import Header from "@/src/components/layouts/header";
import { api } from "@/src/utils/api";
-import { type ColumnDef } from "@tanstack/react-table";
import { type RouterInput } from "@/src/utils/types";
import { useEffect, useState } from "react";
import TableLink from "@/src/components/table/table-link";
@@ -12,6 +11,7 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { type Score } from "@prisma/client";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
type RowData = {
userId: string;
@@ -53,7 +53,7 @@ export default function UsersPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [users.isSuccess, users.data]);
- const columns: ColumnDef<RowData>[] = [
+ const columns: LangfuseColumnDef<RowData>[] = [
{
accessorKey: "userId",
enableColumnFilter: true,
diff --git a/src/pages/project/[projectId]/users/[userId].tsx b/src/pages/project/[projectId]/users/[userId].tsx
index 7b676b36be..b4b2d08566 100644
--- a/src/pages/project/[projectId]/users/[userId].tsx
+++ b/src/pages/project/[projectId]/users/[userId].tsx
@@ -8,8 +8,9 @@ import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import TableLink from "@/src/components/table/table-link";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import SessionsTable from "@/src/components/table/use-cases/sessions";
-const tabs = ["Details", "Traces", "Scores"] as const;
+const tabs = ["Details", "Sessions", "Traces", "Scores"] as const;
export default function TracePage() {
const router = useRouter();
@@ -29,6 +30,8 @@ export default function TracePage() {
switch (currentTab as (typeof tabs)[number]) {
case "Details":
return <DetailsTab userId={userId} projectId={projectId} />;
+ case "Sessions":
+ return <SessionsTab userId={userId} projectId={projectId} />;
case "Traces":
return <TracesTab userId={userId} projectId={projectId} />;
case "Scores":
@@ -202,3 +205,15 @@ function TracesTab({ userId, projectId }: TabProps) {
</div>
);
}
+
+function SessionsTab({ userId, projectId }: TabProps) {
+ return (
+ <div className="mt-5 pt-5">
+ <SessionsTable
+ projectId={projectId}
+ userId={userId}
+ omittedFilter={["userId"]}
+ />
+ </div>
+ );
+}
diff --git a/src/pages/public/traces/[traceId].tsx b/src/pages/public/traces/[traceId].tsx
index 7d1c7901e1..4e9355ee15 100644
--- a/src/pages/public/traces/[traceId].tsx
+++ b/src/pages/public/traces/[traceId].tsx
@@ -1,12 +1,9 @@
-import { useRouter } from "next/router";
-import { TracePage } from "@/src/components/trace";
+// This url is deprecated, we keep this redirect page for backward compatibility
-export default function PublicTracePage() {
- const router = useRouter();
- const traceId = router.query.traceId as string;
- return (
- <div className="py-5">
- <TracePage traceId={traceId} />
- </div>
- );
-}
+import TraceRedirectPage, {
+ getServerSideProps,
+} from "@/src/pages/trace/[traceId]";
+
+export { getServerSideProps };
+
+export default TraceRedirectPage;
diff --git a/src/pages/trace/[traceId].tsx b/src/pages/trace/[traceId].tsx
index 686df043e2..1be90d79f7 100644
--- a/src/pages/trace/[traceId].tsx
+++ b/src/pages/trace/[traceId].tsx
@@ -38,7 +38,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => {
};
};
-const TracePage = () => {
+const TraceRedirectPage = () => {
const router = useRouter();
if (router.isFallback) {
return <div>Loading...</div>;
@@ -47,4 +47,4 @@ const TracePage = () => {
return <div>Redirecting...</div>;
};
-export default TracePage;
+export default TraceRedirectPage;
diff --git a/src/server/api/definitions/observationsTable.ts b/src/server/api/definitions/observationsTable.ts
index a8a77edc1b..df15f7b4bd 100644
--- a/src/server/api/definitions/observationsTable.ts
+++ b/src/server/api/definitions/observationsTable.ts
@@ -36,7 +36,7 @@ export const observationsTableCols: ColumnDefinition[] = [
internal: 'o."end_time"',
},
{
- name: "latency",
+ name: "latency (s)",
type: "number",
internal: '"latency"',
},
diff --git a/src/server/api/definitions/sessionsView.ts b/src/server/api/definitions/sessionsView.ts
new file mode 100644
index 0000000000..c62b7f6ab0
--- /dev/null
+++ b/src/server/api/definitions/sessionsView.ts
@@ -0,0 +1,17 @@
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
+
+export const sessionsViewCols: ColumnDefinition[] = [
+ { name: "⭐️", type: "boolean", internal: "s.bookmarked" },
+ { name: "userId", type: "string", internal: 't."user_id"' },
+ {
+ name: "createdAt",
+ type: "datetime",
+ internal: 's."created_at"',
+ },
+ { name: "Trace Name", type: "string", internal: 't."name"' },
+ {
+ name: "Session duration (s)",
+ type: "number",
+ internal: 'o."sessionDuration"/1000',
+ },
+];
diff --git a/src/server/api/definitions/tracesTable.ts b/src/server/api/definitions/tracesTable.ts
index 9011411700..fdc798bf85 100644
--- a/src/server/api/definitions/tracesTable.ts
+++ b/src/server/api/definitions/tracesTable.ts
@@ -29,7 +29,7 @@ export const tracesTableCols: ColumnDefinition[] = [
internal: "scores_avg",
},
{
- name: "latency",
+ name: "Latency (s)",
type: "number",
internal: "tl.latency",
},
diff --git a/src/server/api/root.ts b/src/server/api/root.ts
index 861e3202fc..6e03c6f3af 100644
--- a/src/server/api/root.ts
+++ b/src/server/api/root.ts
@@ -7,11 +7,11 @@ import { projectsRouter } from "@/src/features/projects/server/projectsRouter";
import { apiKeysRouter } from "@/src/features/public-api/server/apiKeyRouter";
import { projectMembersRouter } from "@/src/features/rbac/server/projectMembersRouter";
import { userRouter } from "@/src/server/api/routers/users";
-import { publishTracesRouter } from "@/src/features/public-traces/server/publishTracesRouter";
import { datasetRouter } from "@/src/features/datasets/server/dataset-router";
import { environmentRouter } from "@/src/server/api/routers/environment";
import { usageMeteringRouter } from "@/src/features/usage-metering/server/usageMeteringRouter";
import { observationsRouter } from "@/src/server/api/routers/observations";
+import { sessionRouter } from "@/src/server/api/routers/sessions";
/**
* This is the primary router for your server.
@@ -20,6 +20,7 @@ import { observationsRouter } from "@/src/server/api/routers/observations";
*/
export const appRouter = createTRPCRouter({
traces: traceRouter,
+ sessions: sessionRouter,
generations: generationsRouter,
scores: scoresRouter,
dashboard: dashboardRouter,
@@ -27,7 +28,6 @@ export const appRouter = createTRPCRouter({
users: userRouter,
apiKeys: apiKeysRouter,
projectMembers: projectMembersRouter,
- publishTraces: publishTracesRouter,
datasets: datasetRouter,
environment: environmentRouter,
usageMetering: usageMeteringRouter,
diff --git a/src/server/api/routers/sessions.ts b/src/server/api/routers/sessions.ts
new file mode 100644
index 0000000000..da4ab2233c
--- /dev/null
+++ b/src/server/api/routers/sessions.ts
@@ -0,0 +1,186 @@
+import { z } from "zod";
+
+import { sessionsViewCols } from "@/src/server/api/definitions/sessionsView";
+import { filterToPrismaSql } from "@/src/features/filters/server/filterToPrisma";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+ protectedGetSessionProcedure,
+} from "@/src/server/api/trpc";
+import { type Observation, Prisma } from "@prisma/client";
+import { singleFilter } from "@/src/server/api/interfaces/filters";
+import type Decimal from "decimal.js";
+import { paginationZod } from "@/src/utils/zod";
+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
+import { TRPCError } from "@trpc/server";
+
+const SessionFilterOptions = z.object({
+ projectId: z.string(), // Required for protectedProjectProcedure
+ searchQuery: z.string().nullable(),
+ filter: z.array(singleFilter).nullable(),
+ ...paginationZod,
+});
+
+export type ObservationReturnType = Omit<Observation, "input" | "output"> & {
+ traceId: string;
+} & { price?: Decimal };
+
+export const sessionRouter = createTRPCRouter({
+ all: protectedProjectProcedure
+ .input(SessionFilterOptions)
+ .query(async ({ input, ctx }) => {
+ const filterCondition = filterToPrismaSql(
+ input.filter ?? [],
+ sessionsViewCols,
+ );
+
+ const sessions = await ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ createdAt: Date;
+ bookmarked: boolean;
+ public: boolean;
+ countTraces: number;
+ userIds: string[];
+ totalCount: number;
+ sessionDuration: number | null;
+ }>
+ >(Prisma.sql`
+ WITH observation_metrics AS (
+ SELECT
+ t.session_id,
+ EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"), MAX(t.timestamp))) - EXTRACT(EPOCH FROM COALESCE(MIN(o."start_time"), MIN(t.timestamp)))::double precision AS "sessionDuration"
+ FROM traces t
+ LEFT JOIN observations o ON o.trace_id = t.id
+ WHERE
+ t."project_id" = ${input.projectId}
+ AND session_id IS NOT NULL
+ GROUP BY 1
+ ),
+ trace_metrics AS (
+ SELECT
+ session_id,
+ array_agg(distinct t.user_id) "userIds",
+ count(t.id)::int "countTraces"
+ FROM traces t
+ WHERE
+ t."project_id" = ${input.projectId}
+ AND session_id IS NOT NULL
+ GROUP BY 1
+ )
+
+ SELECT
+ s.id,
+ s."created_at" "createdAt",
+ s.bookmarked,
+ s.public,
+ t."userIds",
+ t."countTraces",
+ o."sessionDuration",
+ (count(*) OVER ())::int AS "totalCount"
+ FROM trace_sessions s
+ LEFT JOIN trace_metrics t ON t.session_id = s.id
+ LEFT JOIN observation_metrics o ON o.session_id = s.id
+ WHERE
+ s."project_id" = ${input.projectId}
+ ${filterCondition}
+ ORDER BY 2 desc
+ LIMIT ${input.limit}
+ OFFSET ${input.page * input.limit}
+ `);
+ return sessions.map((s) => ({
+ ...s,
+ sessionDuration:
+ s.sessionDuration !== null ? s.sessionDuration / 1000 : null,
+ userIds: s.userIds.filter((t) => t !== null),
+ }));
+ }),
+ byId: protectedGetSessionProcedure
+ .input(z.object({ projectId: z.string(), sessionId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const session = await ctx.prisma.traceSession.findFirst({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
+ },
+ include: {
+ traces: {
+ orderBy: {
+ timestamp: "asc",
+ },
+ include: {
+ scores: true,
+ },
+ },
+ },
+ });
+ if (!session) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found in project",
+ });
+ }
+
+ return {
+ ...session,
+ users: [
+ ...new Set(
+ session.traces.map((t) => t.userId).filter((t) => t !== null),
+ ),
+ ],
+ };
+ }),
+ bookmark: protectedProjectProcedure
+ .input(
+ z.object({
+ sessionId: z.string(),
+ projectId: z.string(),
+ bookmarked: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "objects:bookmark",
+ });
+
+ const session = await ctx.prisma.traceSession.update({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
+ },
+ data: {
+ bookmarked: input.bookmarked,
+ },
+ });
+ if (!session) {
+ throw new Error("Session not found in project");
+ }
+ return session;
+ }),
+ publish: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ sessionId: z.string(),
+ public: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "objects:publish",
+ });
+ return ctx.prisma.traceSession.update({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
+ },
+ data: {
+ public: input.public,
+ },
+ });
+ }),
+});
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 5fa0d56564..7625447fb1 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -155,6 +155,7 @@ export const traceRouter = createTRPCRouter({
t.*,
t."user_id" AS "userId",
t."metadata" AS "metadata",
+ t.session_id AS "sessionId",
t."bookmarked" AS "bookmarked",
COALESCE(u."promptTokens", 0)::int AS "promptTokens",
COALESCE(u."completionTokens", 0)::int AS "completionTokens",
@@ -324,36 +325,57 @@ export const traceRouter = createTRPCRouter({
}),
)
.mutation(async ({ input, ctx }) => {
- try {
- throwIfNoAccess({
- session: ctx.session,
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "objects:bookmark",
+ });
+ const trace = await ctx.prisma.trace.update({
+ where: {
+ id: input.traceId,
projectId: input.projectId,
- scope: "traces:bookmark",
- });
- const trace = await ctx.prisma.trace.findFirst({
- where: {
- id: input.traceId,
- projectId: input.projectId,
- },
+ },
+ data: {
+ bookmarked: input.bookmarked,
+ },
+ });
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found in project",
});
- if (!trace) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Trace not found in project",
- });
- }
-
- return ctx.prisma.trace.update({
- where: {
- id: input.traceId,
- },
- data: {
- bookmarked: input.bookmarked,
- },
+ }
+ return trace;
+ }),
+ publish: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ traceId: z.string(),
+ public: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "objects:publish",
+ });
+ const trace = await ctx.prisma.trace.update({
+ where: {
+ id: input.traceId,
+ projectId: input.projectId,
+ },
+ data: {
+ public: input.public,
+ },
+ });
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found in project",
});
- } catch (e) {
- console.error("Failed to bookmark trace", e);
- throw e;
}
+ return trace;
}),
});
diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.ts
index da928f3a60..d6ea2cb3e3 100644
--- a/src/server/api/services/EventProcessor.ts
+++ b/src/server/api/services/EventProcessor.ts
@@ -251,18 +251,38 @@ export class TraceProcessor implements EventProcessor {
id: internalId,
name: body.name ?? undefined,
userId: body.userId ?? undefined,
+ input: body.input ?? undefined,
+ output: body.output ?? undefined,
metadata: mergedMetadata ?? body.metadata ?? undefined,
release: body.release ?? undefined,
version: body.version ?? undefined,
+ session: body.sessionId
+ ? {
+ connectOrCreate: {
+ where: { id: body.sessionId, projectId: apiScope.projectId },
+ create: { id: body.sessionId, projectId: apiScope.projectId },
+ },
+ }
+ : undefined,
public: body.public ?? undefined,
project: { connect: { id: apiScope.projectId } },
},
update: {
name: body.name ?? undefined,
userId: body.userId ?? undefined,
+ input: body.input ?? undefined,
+ output: body.output ?? undefined,
metadata: mergedMetadata ?? body.metadata ?? undefined,
release: body.release ?? undefined,
version: body.version ?? undefined,
+ session: body.sessionId
+ ? {
+ connectOrCreate: {
+ where: { id: body.sessionId, projectId: apiScope.projectId },
+ create: { id: body.sessionId, projectId: apiScope.projectId },
+ },
+ }
+ : undefined,
public: body.public ?? undefined,
},
});
diff --git a/src/server/api/trpc.ts b/src/server/api/trpc.ts
index fc0a3c65c9..54ded336e4 100644
--- a/src/server/api/trpc.ts
+++ b/src/server/api/trpc.ts
@@ -241,3 +241,71 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
});
export const protectedGetTraceProcedure = t.procedure.use(enforceTraceAccess);
+
+/*
+ * Protect session-level getter routes.
+ * - Users need to be member of the project to access the trace.
+ * - Alternatively, the trace needs to be public.
+ */
+
+const inputSessionSchema = z.object({
+ sessionId: z.string(),
+ projectId: z.string(),
+});
+
+const enforceSessionAccess = t.middleware(async ({ ctx, rawInput, next }) => {
+ const result = inputSessionSchema.safeParse(rawInput);
+ if (!result.success)
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid input, sessionId is required",
+ });
+
+ const { sessionId, projectId } = result.data;
+
+ const session = await prisma.traceSession.findFirst({
+ where: {
+ id: sessionId,
+ projectId,
+ },
+ select: {
+ public: true,
+ },
+ });
+
+ if (!session)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found",
+ });
+
+ const userSessionProject = ctx.session?.user?.projects?.find(
+ ({ id }) => id === projectId,
+ );
+
+ if (
+ !session.public &&
+ !userSessionProject &&
+ ctx.session?.user?.admin !== true
+ )
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message:
+ "User is not a member of this project and this session is not public",
+ });
+
+ return next({
+ ctx: {
+ session: {
+ ...ctx.session,
+ projectRole:
+ ctx.session?.user?.admin === true
+ ? "ADMIN"
+ : userSessionProject?.role,
+ },
+ },
+ });
+});
+
+export const protectedGetSessionProcedure =
+ t.procedure.use(enforceSessionAccess);
diff --git a/src/utils/dates.ts b/src/utils/dates.ts
index 863a04a077..88793620df 100644
--- a/src/utils/dates.ts
+++ b/src/utils/dates.ts
@@ -17,3 +17,24 @@ export const setEndOfDay = (date: Date) => {
export const intervalInSeconds = (start: Date, end: Date | null) =>
end ? (end.getTime() - start.getTime()) / 1000 : 0;
+
+export const formatInterval = (seconds: number) => {
+ const hrs = Math.floor(seconds / 3600);
+ const mins = Math.floor((seconds % 3600) / 60);
+ const secs = Math.floor(seconds % 60);
+ const ms = Math.floor((seconds % 1) * 1000);
+
+ const pad = (num: number, digits?: number) =>
+ `${"0".repeat(digits ?? 2)}${num}`.slice(-(digits ?? 2));
+ return (
+ `${pad(hrs)}:${pad(mins)}:${pad(secs)}.${pad(ms, 3)}`
+ // dynamically remove leading zeros
+ .replace(/^0+:/, "")
+ .replace(/^0+:/, "")
+ // if the time is less than 1 minute, remove the leading zeros from the seconds
+ // make sure to only match 00.xxx and not 00:00.xxx
+ .replace(/^00\./, "0.") +
+ // if the time is less than 1 minute, add a s at the end
+ (seconds < 60 ? "s" : "")
+ );
+};