Skip to content

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

feat: move sessions api to experimentation setup (#4161)

Max Deichmann10e9aef0449f
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 6abc8d10ad..5f099a352a 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -18,7 +18,7 @@ import {
} from "@langfuse/shared";
import { Prisma } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
-import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import Decimal from "decimal.js";
import {
createSessionsAllQuery,
@@ -49,80 +49,80 @@ export const sessionRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
- if (input.queryClickhouse) {
- const sessions = await getSessionsTable({
- projectId: input.projectId,
- filter: input.filter ?? [],
- orderBy: input.orderBy,
- offset: input.page * input.limit,
- limit: input.limit,
- });
-
- const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
- where: {
- id: {
- in: sessions.map((s) => s.session_id),
- },
- projectId: input.projectId,
- },
- select: {
- id: true,
- bookmarked: true,
- public: true,
- },
- });
- return {
- sessions: sessions.map((s) => ({
- id: s.session_id,
- userIds: s.user_ids,
- countTraces: s.trace_ids.length,
- sessionDuration: Number(s.duration) / 1000,
- inputCost: new Decimal(s.session_input_cost),
- outputCost: new Decimal(s.session_output_cost),
- totalCost: new Decimal(s.session_total_cost),
- promptTokens: Number(s.session_input_usage),
- completionTokens: Number(s.session_output_usage),
- totalTokens: Number(s.session_total_usage),
- traceTags: s.trace_tags,
- createdAt: s.min_timestamp,
- bookmarked:
- prismaSessionInfo.find((p) => p.id === s.session_id)
- ?.bookmarked ?? false,
- public: prismaSessionInfo.find((p) => p.id === s.session_id)
- ?.public,
- })),
- };
- }
-
- const sessions = await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- createdAt: Date;
- bookmarked: boolean;
- public: boolean;
- }>
- >(
- createSessionsAllQuery(
- Prisma.sql`
+ return await measureAndReturnApi({
+ input,
+ operation: "sessions.all",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const sessions = await ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ createdAt: Date;
+ bookmarked: boolean;
+ public: boolean;
+ }>
+ >(
+ createSessionsAllQuery(
+ Prisma.sql`
s.id,
s."created_at" AS "createdAt",
s.bookmarked,
s.public
`,
- input,
- ),
- );
+ input,
+ ),
+ );
+
+ return {
+ sessions,
+ };
+ },
+ clickhouseExecution: async () => {
+ const sessions = await getSessionsTable({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ offset: input.page * input.limit,
+ limit: input.limit,
+ });
- return {
- sessions,
- };
+ const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
+ where: {
+ id: {
+ in: sessions.map((s) => s.session_id),
+ },
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ bookmarked: true,
+ public: true,
+ },
+ });
+ return {
+ sessions: sessions.map((s) => ({
+ id: s.session_id,
+ userIds: s.user_ids,
+ countTraces: s.trace_ids.length,
+ sessionDuration: Number(s.duration) / 1000,
+ inputCost: new Decimal(s.session_input_cost),
+ outputCost: new Decimal(s.session_output_cost),
+ totalCost: new Decimal(s.session_total_cost),
+ promptTokens: Number(s.session_input_usage),
+ completionTokens: Number(s.session_output_usage),
+ totalTokens: Number(s.session_total_usage),
+ traceTags: s.trace_tags,
+ createdAt: new Date(s.min_timestamp),
+ bookmarked:
+ prismaSessionInfo.find((p) => p.id === s.session_id)
+ ?.bookmarked ?? false,
+ public:
+ prismaSessionInfo.find((p) => p.id === s.session_id)
+ ?.public ?? false,
+ })),
+ };
+ },
+ });
} catch (e) {
console.error(e);
throw new TRPCError({
@@ -139,54 +139,53 @@ export const sessionRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
- if (input.queryClickhouse) {
- const count = await getSessionsTableCount({
- projectId: input.projectId,
- filter: input.filter ?? [],
- orderBy: input.orderBy,
- offset: input.page * input.limit,
- limit: input.limit,
- });
-
- return {
- totalCount: count,
- };
- }
-
- const inputForTotal: z.infer<typeof SessionFilterOptions> = {
- filter: input.filter,
- projectId: input.projectId,
- orderBy: null,
- limit: 1,
- page: 0,
- };
+ return await measureAndReturnApi({
+ input,
+ operation: "sessions.countAll",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const inputForTotal: z.infer<typeof SessionFilterOptions> = {
+ filter: input.filter,
+ projectId: input.projectId,
+ orderBy: null,
+ limit: 1,
+ page: 0,
+ };
+
+ const totalCount = await ctx.prisma.$queryRaw<
+ Array<{
+ totalCount: number;
+ }>
+ >(
+ createSessionsAllQuery(
+ Prisma.sql`
+ count(*)::int as "totalCount"
+ `,
+ inputForTotal,
+ {
+ ignoreOrderBy: true,
+ },
+ ),
+ );
- const totalCount = await ctx.prisma.$queryRaw<
- Array<{
- totalCount: number;
- }>
- >(
- createSessionsAllQuery(
- Prisma.sql`
- count(*)::int as "totalCount"
- `,
- inputForTotal,
- {
- ignoreOrderBy: true,
- },
- ),
- );
+ return {
+ totalCount: totalCount[0].totalCount,
+ };
+ },
+ clickhouseExecution: async () => {
+ const count = await getSessionsTableCount({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ offset: input.page * input.limit,
+ limit: input.limit,
+ });
- return {
- totalCount: totalCount[0].totalCount,
- };
+ return {
+ totalCount: count,
+ };
+ },
+ });
} catch (e) {
console.error(e);
throw new TRPCError({
@@ -205,70 +204,69 @@ export const sessionRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
if (input.sessionIds.length === 0) return [];
-
- if (input.queryClickhouse) {
- return []; // initial endpoint returns all data from CH.
- }
-
- const inputForMetrics: z.infer<typeof SessionFilterOptions> = {
- filter: [],
- projectId: input.projectId,
- orderBy: null,
- limit: 10000, // no limit
- page: 0,
- };
-
- const metrics = await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- countTraces: number;
- userIds: (string | null)[] | null;
- sessionDuration: number | null;
- inputCost: Decimal;
- outputCost: Decimal;
- totalCost: Decimal;
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
- traceTags: string[];
- }>
- >(
- createSessionsAllQuery(
- Prisma.sql`
- s.id,
- t."userIds",
- t."countTraces",
- o."sessionDuration",
- o."totalCost" AS "totalCost",
- o."inputCost" AS "inputCost",
- o."outputCost" AS "outputCost",
- o."promptTokens" AS "promptTokens",
- o."completionTokens" AS "completionTokens",
- o."totalTokens" AS "totalTokens",
- t."tags" AS "traceTags"
- `,
- inputForMetrics,
- {
- ignoreOrderBy: true,
- sessionIdList: input.sessionIds,
- },
- ),
- );
-
- return metrics.map((row) => ({
- ...row,
- userIds: (row.userIds?.filter((t) => t !== null) ?? []) as string[],
- traceTags: (row.traceTags?.filter((t) => t !== null) ??
- []) as string[],
- }));
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.metrics",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const inputForMetrics: z.infer<typeof SessionFilterOptions> = {
+ filter: [],
+ projectId: input.projectId,
+ orderBy: null,
+ limit: 10000, // no limit
+ page: 0,
+ };
+
+ const metrics = await ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ countTraces: number;
+ userIds: (string | null)[] | null;
+ sessionDuration: number | null;
+ inputCost: Decimal;
+ outputCost: Decimal;
+ totalCost: Decimal;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ traceTags: string[];
+ }>
+ >(
+ createSessionsAllQuery(
+ Prisma.sql`
+ s.id,
+ t."userIds",
+ t."countTraces",
+ o."sessionDuration",
+ o."totalCost" AS "totalCost",
+ o."inputCost" AS "inputCost",
+ o."outputCost" AS "outputCost",
+ o."promptTokens" AS "promptTokens",
+ o."completionTokens" AS "completionTokens",
+ o."totalTokens" AS "totalTokens",
+ t."tags" AS "traceTags"
+ `,
+ inputForMetrics,
+ {
+ ignoreOrderBy: true,
+ sessionIdList: input.sessionIds,
+ },
+ ),
+ );
+
+ return metrics.map((row) => ({
+ ...row,
+ userIds: (row.userIds?.filter((t) => t !== null) ??
+ []) as string[],
+ traceTags: (row.traceTags?.filter((t) => t !== null) ??
+ []) as string[],
+ }));
+ },
+ clickhouseExecution: async () => {
+ return []; // initial endpoint returns all data from CH.
+ },
+ });
} catch (e) {
console.error(e);
throw new TRPCError({
@@ -288,91 +286,89 @@ export const sessionRouter = createTRPCRouter({
.query(async ({ input, ctx }) => {
try {
const { timestampFilter } = input;
-
- if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
- if (input.queryClickhouse) {
- const columns = [
- ...tracesTableUiColumnDefinitions,
- {
- uiTableName: "Created At",
- uiTableId: "createdAt",
- clickhouseTableName: "traces",
- clickhouseSelect: "timestamp",
- },
- ];
- const [userIds, tags] = await Promise.all([
- getTracesGroupedByUserIds({
- projectId: input.projectId,
- filter: timestampFilter ? [timestampFilter] : [],
- sessionIdNullFilter: true,
- columns,
- }),
- getTracesGroupedByTags({
- projectId: input.projectId,
- filter: timestampFilter ? [timestampFilter] : [],
- sessionIdNullFilter: true,
- columns,
- }),
- ]);
-
- return {
- userIds: userIds.map((row) => ({
- value: row.user_id,
- })),
- tags: tags.map((row) => ({
- value: row.value,
- })),
- };
- }
-
- const rawTimestampFilter =
- timestampFilter && timestampFilter.type === "datetime"
- ? datetimeFilterToPrismaSql(
- "timestamp",
- timestampFilter.operator,
- timestampFilter.value,
- )
- : Prisma.empty;
- const [userIds, tags] = await Promise.all([
- ctx.prisma.$queryRaw<Array<{ value: string }>>(Prisma.sql`
- SELECT
- traces.user_id AS value
- FROM traces
- WHERE
- traces.session_id IS NOT NULL
- AND traces.user_id IS NOT NULL
- AND traces.project_id = ${input.projectId} ${rawTimestampFilter}
- GROUP BY traces.user_id
- ORDER BY traces.user_id ASC
- LIMIT 1000;
- `),
- ctx.prisma.$queryRaw<
- Array<{
- value: string;
- }>
- >(Prisma.sql`
- SELECT DISTINCT tag AS value
- FROM traces t
- JOIN observations o ON o.trace_id = t.id,
- UNNEST(t.tags) AS tag
- WHERE o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId} ${rawTimestampFilter}
- LIMIT 1000;
- `),
- ]);
-
- const res: SessionOptions = {
- userIds: userIds,
- tags: tags,
- };
- return res;
+ return await measureAndReturnApi({
+ input,
+ operation: "sessions.filterOptions",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const rawTimestampFilter =
+ timestampFilter && timestampFilter.type === "datetime"
+ ? datetimeFilterToPrismaSql(
+ "timestamp",
+ timestampFilter.operator,
+ timestampFilter.value,
+ )
+ : Prisma.empty;
+ const [userIds, tags] = await Promise.all([
+ ctx.prisma.$queryRaw<Array<{ value: string }>>(Prisma.sql`
+ SELECT
+ traces.user_id AS value
+ FROM traces
+ WHERE
+ traces.session_id IS NOT NULL
+ AND traces.user_id IS NOT NULL
+ AND traces.project_id = ${input.projectId} ${rawTimestampFilter}
+ GROUP BY traces.user_id
+ ORDER BY traces.user_id ASC
+ LIMIT 1000;
+ `),
+ ctx.prisma.$queryRaw<
+ Array<{
+ value: string;
+ }>
+ >(Prisma.sql`
+ SELECT DISTINCT tag AS value
+ FROM traces t
+ JOIN observations o ON o.trace_id = t.id,
+ UNNEST(t.tags) AS tag
+ WHERE o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND t.project_id = ${input.projectId} ${rawTimestampFilter}
+ LIMIT 1000;
+ `),
+ ]);
+
+ const res: SessionOptions = {
+ userIds: userIds,
+ tags: tags,
+ };
+ return res;
+ },
+ clickhouseExecution: async () => {
+ const columns = [
+ ...tracesTableUiColumnDefinitions,
+ {
+ uiTableName: "Created At",
+ uiTableId: "createdAt",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "timestamp",
+ },
+ ];
+ const [userIds, tags] = await Promise.all([
+ getTracesGroupedByUserIds({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ sessionIdNullFilter: true,
+ columns,
+ }),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ sessionIdNullFilter: true,
+ columns,
+ }),
+ ]);
+
+ return {
+ userIds: userIds.map((row) => ({
+ value: row.user_id,
+ })),
+ tags: tags.map((row) => ({
+ value: row.value,
+ })),
+ };
+ },
+ });
} catch (e) {
console.error(e);
throw new TRPCError({
@@ -391,131 +387,134 @@ export const sessionRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
try {
- if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
- });
- }
-
- if (input.queryClickhouse) {
- const postgresSession = await ctx.prisma.traceSession.findFirst({
- where: {
- id: input.sessionId,
- projectId: input.projectId,
- },
- });
-
- if (!postgresSession) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Session not found in project",
+ return await measureAndReturnApi({
+ input,
+ operation: "sessions.byId",
+ user: ctx.session.user ?? undefined,
+ pgExecution: async () => {
+ const session = await ctx.prisma.traceSession.findFirst({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
+ },
+ include: {
+ traces: {
+ orderBy: {
+ timestamp: "asc",
+ },
+ select: {
+ id: true,
+ userId: true,
+ name: true,
+ timestamp: true,
+ },
+ },
+ },
+ });
+ if (!session) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found in project",
+ });
+ }
+
+ const totalCostQuery = Prisma.sql`
+ SELECT
+ SUM(COALESCE(o."calculated_total_cost", 0)) AS "totalCost"
+ FROM observations_view o
+ JOIN traces t ON t.id = o.trace_id
+ WHERE
+ t."session_id" = ${input.sessionId}
+ AND t."project_id" = ${input.projectId}
+ `;
+
+ const [scores, costData] = await Promise.all([
+ ctx.prisma.score.findMany({
+ where: {
+ traceId: {
+ in: session.traces.map((t) => t.id),
+ },
+ projectId: input.projectId,
+ },
+ }),
+ // costData
+ ctx.prisma.$queryRaw<Array<{ totalCost: number }>>(
+ totalCostQuery,
+ ),
+ ]);
+
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
+
+ return {
+ ...session,
+ traces: session.traces.map((t) => ({
+ ...t,
+ scores: validatedScores.filter((s) => s.traceId === t.id),
+ })),
+ totalCost: costData[0].totalCost ?? 0,
+ users: [
+ ...new Set(
+ session.traces.map((t) => t.userId).filter((t) => t !== null),
+ ),
+ ],
+ };
+ },
+ clickhouseExecution: async () => {
+ const postgresSession = await ctx.prisma.traceSession.findFirst({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
+ },
});
- }
- const clickhouseTraces = await getTracesForSession(
- input.projectId,
- input.sessionId,
- );
+ if (!postgresSession) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found in project",
+ });
+ }
- const [scores, costData] = await Promise.all([
- getScoresForTraces(
- input.projectId,
- clickhouseTraces.map((t) => t.id),
- ),
- getCostForTraces(
+ const clickhouseTraces = await getTracesForSession(
input.projectId,
- clickhouseTraces.map((t) => t.id),
- ),
- ]);
+ input.sessionId,
+ );
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
-
- return {
- ...postgresSession,
- traces: clickhouseTraces.map((t) => ({
- ...t,
- scores: validatedScores.filter((s) => s.traceId === t.id),
- })),
- totalCost: costData,
- users: [
- ...new Set(
- clickhouseTraces.map((t) => t.userId).filter((t) => t !== null),
+ const [scores, costData] = await Promise.all([
+ getScoresForTraces(
+ input.projectId,
+ clickhouseTraces.map((t) => t.id),
),
- ],
- };
- }
-
- const session = await ctx.prisma.traceSession.findFirst({
- where: {
- id: input.sessionId,
- projectId: input.projectId,
- },
- include: {
- traces: {
- orderBy: {
- timestamp: "asc",
- },
- select: {
- id: true,
- userId: true,
- name: true,
- timestamp: true,
- },
- },
+ getCostForTraces(
+ input.projectId,
+ clickhouseTraces.map((t) => t.id),
+ ),
+ ]);
+
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
+
+ return {
+ ...postgresSession,
+ traces: clickhouseTraces.map((t) => ({
+ ...t,
+ scores: validatedScores.filter((s) => s.traceId === t.id),
+ })),
+ totalCost: costData ?? 0,
+ users: [
+ ...new Set(
+ clickhouseTraces
+ .map((t) => t.userId)
+ .filter((t) => t !== null),
+ ),
+ ],
+ };
},
});
- if (!session) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Session not found in project",
- });
- }
-
- const totalCostQuery = Prisma.sql`
- SELECT
- SUM(COALESCE(o."calculated_total_cost", 0)) AS "totalCost"
- FROM observations_view o
- JOIN traces t ON t.id = o.trace_id
- WHERE
- t."session_id" = ${input.sessionId}
- AND t."project_id" = ${input.projectId}
- `;
-
- const [scores, costData] = await Promise.all([
- ctx.prisma.score.findMany({
- where: {
- traceId: {
- in: session.traces.map((t) => t.id),
- },
- projectId: input.projectId,
- },
- }),
- // costData
- ctx.prisma.$queryRaw<Array<{ totalCost: number }>>(totalCostQuery),
- ]);
-
- const validatedScores = filterAndValidateDbScoreList(
- scores,
- traceException,
- );
-
- return {
- ...session,
- traces: session.traces.map((t) => ({
- ...t,
- scores: validatedScores.filter((s) => s.traceId === t.id),
- })),
- totalCost: costData[0].totalCost ?? 0,
- users: [
- ...new Set(
- session.traces.map((t) => t.userId).filter((t) => t !== null),
- ),
- ],
- };
} catch (e) {
console.error(e);
throw new TRPCError({