Skip to content

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

perf(ui): parallelize users, sessions, models, score config, scores queries in trpc routes (#3039)

Marc Klingen51be8f8fb3d9
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index f60c5e9eb4..36a3bef228 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -51,9 +51,11 @@ export const promptRouter = createTRPCRouter({
"prompts",
);
- const prompts = await ctx.prisma.$queryRaw<Array<Prompt>>(
- generatePromptQuery(
- Prisma.sql`
+ const [prompts, promptCount] = await Promise.all([
+ // prompts
+ ctx.prisma.$queryRaw<Array<Prompt>>(
+ generatePromptQuery(
+ Prisma.sql`
p.id,
p.name,
p.version,
@@ -64,26 +66,25 @@ export const promptRouter = createTRPCRouter({
p.created_at as "createdAt",
p.labels,
p.tags`,
- input.projectId,
- filterCondition,
- orderByCondition,
- input.limit,
- input.page,
+ input.projectId,
+ filterCondition,
+ orderByCondition,
+ input.limit,
+ input.page,
+ ),
),
- );
-
- const promptCount = await ctx.prisma.$queryRaw<
- Array<{ totalCount: bigint }>
- >(
- generatePromptQuery(
- Prisma.sql` count(*) AS "totalCount"`,
- input.projectId,
- filterCondition,
- Prisma.empty,
- 1, // limit
- 0, // page
+ // promptCount
+ ctx.prisma.$queryRaw<Array<{ totalCount: bigint }>>(
+ generatePromptQuery(
+ Prisma.sql` count(*) AS "totalCount"`,
+ input.projectId,
+ filterCondition,
+ Prisma.empty,
+ 1, // limit
+ 0, // page
+ ),
),
- );
+ ]);
return {
prompts: prompts,
@@ -562,23 +563,24 @@ export const promptRouter = createTRPCRouter({
projectId: input.projectId,
scope: "prompts:read",
});
- const prompts = await ctx.prisma.prompt.findMany({
- where: {
- projectId: input.projectId,
- name: input.name,
- },
- ...(input.limit !== undefined && input.page !== undefined
- ? { take: input.limit, skip: input.page * input.limit }
- : undefined),
- orderBy: [{ version: "desc" }],
- });
-
- const totalCount = await ctx.prisma.prompt.count({
- where: {
- projectId: input.projectId,
- name: input.name,
- },
- });
+ const [prompts, totalCount] = await Promise.all([
+ ctx.prisma.prompt.findMany({
+ where: {
+ projectId: input.projectId,
+ name: input.name,
+ },
+ ...(input.limit !== undefined && input.page !== undefined
+ ? { take: input.limit, skip: input.page * input.limit }
+ : undefined),
+ orderBy: [{ version: "desc" }],
+ }),
+ ctx.prisma.prompt.count({
+ where: {
+ projectId: input.projectId,
+ name: input.name,
+ },
+ }),
+ ]);
const userIds = prompts
.map((p) => p.createdBy)
@@ -634,115 +636,118 @@ export const promptRouter = createTRPCRouter({
observationsTableCols,
"prompts",
);
- const metrics = await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- observationCount: number;
- firstUsed: Date | null;
- lastUsed: Date | null;
- medianOutputTokens: number | null;
- medianInputTokens: number | null;
- medianTotalCost: number | null;
- medianLatency: number | null;
- }>
- >(
- Prisma.sql`
- select p.id, p.version, observation_metrics.* from prompts p
- LEFT JOIN LATERAL (
+ const [metrics, generationScores, traceScores] = await Promise.all([
+ // metrics
+ ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ observationCount: number;
+ firstUsed: Date | null;
+ lastUsed: Date | null;
+ medianOutputTokens: number | null;
+ medianInputTokens: number | null;
+ medianTotalCost: number | null;
+ medianLatency: number | null;
+ }>
+ >(
+ Prisma.sql`
+ select p.id, p.version, observation_metrics.* from prompts p
+ LEFT JOIN LATERAL (
+ SELECT
+ count(*) AS "observationCount",
+ MIN(o.start_time) AS "firstUsed",
+ MAX(o.start_time) AS "lastUsed",
+ PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.completion_tokens) AS "medianOutputTokens",
+ PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.prompt_tokens) AS "medianInputTokens",
+ PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.calculated_total_cost) AS "medianTotalCost",
+ PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.latency) AS "medianLatency"
+ FROM
+ "observations_view" o
+ WHERE
+ o.prompt_id = p.id
+ AND "type" = 'GENERATION'
+ AND "project_id" = ${input.projectId}
+ ${filterCondition}
+ ) AS observation_metrics ON true
+ WHERE "project_id" = ${input.projectId}
+ AND p.id in (${Prisma.join(input.promptIds)})
+ ORDER BY version DESC
+ `,
+ ),
+ // generationScores
+ ctx.prisma.$queryRaw<
+ Array<{
+ promptId: string;
+ scores: Array<ScoreSimplified>;
+ }>
+ >(Prisma.sql`
SELECT
- count(*) AS "observationCount",
- MIN(o.start_time) AS "firstUsed",
- MAX(o.start_time) AS "lastUsed",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.completion_tokens) AS "medianOutputTokens",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.prompt_tokens) AS "medianInputTokens",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.calculated_total_cost) AS "medianTotalCost",
- PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY o.latency) AS "medianLatency"
+ p.id AS "promptId",
+ array_agg(s.score) AS "scores"
FROM
- "observations_view" o
+ prompts p
+ LEFT JOIN LATERAL (
+ SELECT
+ jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
+ FROM
+ observations AS o
+ LEFT JOIN scores s ON o.trace_id = s.trace_id
+ AND s.observation_id = o.id
+ AND s.project_id = ${input.projectId}
+ WHERE
+ o.prompt_id IS NOT NULL
+ AND o.type = 'GENERATION'
+ AND o.prompt_id = p.id
+ AND o.project_id = ${input.projectId}
+ AND s.name IS NOT NULL
+ AND p.id IN (${Prisma.join(input.promptIds)})
+ ${filterCondition}
+ ) s ON TRUE
WHERE
- o.prompt_id = p.id
- AND "type" = 'GENERATION'
- AND "project_id" = ${input.projectId}
- ${filterCondition}
- ) AS observation_metrics ON true
- WHERE "project_id" = ${input.projectId}
- AND p.id in (${Prisma.join(input.promptIds)})
- ORDER BY version DESC
- `,
- );
-
- const generationScores = await ctx.prisma.$queryRaw<
- Array<{
- promptId: string;
- scores: Array<ScoreSimplified>;
- }>
- >(Prisma.sql`
- SELECT
- p.id AS "promptId",
- array_agg(s.score) AS "scores"
- FROM
- prompts p
- LEFT JOIN LATERAL (
+ p.project_id = ${input.projectId}
+ AND s.score IS NOT NULL
+ GROUP BY
+ p.id
+ `),
+ // traceScores
+ ctx.prisma.$queryRaw<
+ Array<{
+ promptId: string;
+ scores: Array<ScoreSimplified>;
+ }>
+ >(Prisma.sql`
SELECT
- jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
+ p.id AS "promptId",
+ array_agg(s.score) AS "scores"
FROM
- observations AS o
- LEFT JOIN scores s ON o.trace_id = s.trace_id
- AND s.observation_id = o.id
- AND s.project_id = ${input.projectId}
+ prompts p
+ LEFT JOIN LATERAL (
+ SELECT
+ jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
+ FROM
+ scores s
+ WHERE
+ s.trace_id IN (
+ SELECT o.trace_id
+ FROM observations o
+ WHERE
+ o.prompt_id IS NOT NULL
+ AND o.prompt_id = p.id
+ AND o.type = 'GENERATION'
+ AND o.project_id = ${input.projectId}
+ AND o.prompt_id IN (${Prisma.join(input.promptIds)})
+ ${filterCondition}
+ )
+ AND s.observation_id IS NULL
+ AND s.project_id = ${input.projectId}
+ ) s ON TRUE
WHERE
- o.prompt_id IS NOT NULL
- AND o.type = 'GENERATION'
- AND o.prompt_id = p.id
- AND o.project_id = ${input.projectId}
- AND s.name IS NOT NULL
- AND p.id IN (${Prisma.join(input.promptIds)})
- ${filterCondition}
- ) s ON TRUE
- WHERE
- p.project_id = ${input.projectId}
- AND s.score IS NOT NULL
- GROUP BY
- p.id
- `);
-
- const traceScores = await ctx.prisma.$queryRaw<
- Array<{
- promptId: string;
- scores: Array<ScoreSimplified>;
- }>
- >(Prisma.sql`
- SELECT
- p.id AS "promptId",
- array_agg(s.score) AS "scores"
- FROM
- prompts p
- LEFT JOIN LATERAL (
- SELECT
- jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"
- FROM
- scores s
- WHERE
- s.trace_id IN (
- SELECT o.trace_id
- FROM observations o
- WHERE
- o.prompt_id IS NOT NULL
- AND o.prompt_id = p.id
- AND o.type = 'GENERATION'
- AND o.project_id = ${input.projectId}
- AND o.prompt_id IN (${Prisma.join(input.promptIds)})
- ${filterCondition}
- )
- AND s.observation_id IS NULL
- AND s.project_id = ${input.projectId}
- ) s ON TRUE
- WHERE
- p.project_id = ${input.projectId}
- AND s.score IS NOT NULL
- GROUP BY
- p.id
- `);
+ p.project_id = ${input.projectId}
+ AND s.score IS NOT NULL
+ GROUP BY
+ p.id
+ `),
+ ]);
return metrics.map((metric) => ({
...metric,
diff --git a/web/src/server/api/routers/models.ts b/web/src/server/api/routers/models.ts
index 4acd27e706..edde795655 100644
--- a/web/src/server/api/routers/models.ts
+++ b/web/src/server/api/routers/models.ts
@@ -20,29 +20,30 @@ export const modelRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(ModelAllOptions)
.query(async ({ input, ctx }) => {
- const models = await ctx.prisma.model.findMany({
- where: {
- OR: [{ projectId: input.projectId }, { projectId: null }],
- },
- skip: input.page * input.limit,
- orderBy: [
- { modelName: "asc" },
- { unit: "asc" },
- {
- startDate: {
- sort: "desc",
- nulls: "last",
+ const [models, totalAmount] = await Promise.all([
+ ctx.prisma.model.findMany({
+ where: {
+ OR: [{ projectId: input.projectId }, { projectId: null }],
+ },
+ skip: input.page * input.limit,
+ orderBy: [
+ { modelName: "asc" },
+ { unit: "asc" },
+ {
+ startDate: {
+ sort: "desc",
+ nulls: "last",
+ },
},
+ ],
+ take: input.limit,
+ }),
+ ctx.prisma.model.count({
+ where: {
+ OR: [{ projectId: input.projectId }, { projectId: null }],
},
- ],
- take: input.limit,
- });
-
- const totalAmount = await ctx.prisma.model.count({
- where: {
- OR: [{ projectId: input.projectId }, { projectId: null }],
- },
- });
+ }),
+ ]);
return {
models,
totalCount: totalAmount,
diff --git a/web/src/server/api/routers/scoreConfigs.ts b/web/src/server/api/routers/scoreConfigs.ts
index e615e32980..92e519f186 100644
--- a/web/src/server/api/routers/scoreConfigs.ts
+++ b/web/src/server/api/routers/scoreConfigs.ts
@@ -33,27 +33,28 @@ export const scoreConfigsRouter = createTRPCRouter({
scope: "scoreConfigs:read",
});
- const configs = await ctx.prisma.scoreConfig.findMany({
- where: {
- projectId: input.projectId,
- },
- ...(input.limit !== undefined && input.page !== undefined
- ? { take: input.limit, skip: input.page * input.limit }
- : undefined),
- orderBy: {
- createdAt: "desc",
- },
- });
-
- const configsCount = await ctx.prisma.scoreConfig.count({
- where: {
- projectId: input.projectId,
- },
- });
+ const [configs, totalCount] = await Promise.all([
+ ctx.prisma.scoreConfig.findMany({
+ where: {
+ projectId: input.projectId,
+ },
+ ...(input.limit !== undefined && input.page !== undefined
+ ? { take: input.limit, skip: input.page * input.limit }
+ : undefined),
+ orderBy: {
+ createdAt: "desc",
+ },
+ }),
+ ctx.prisma.scoreConfig.count({
+ where: {
+ projectId: input.projectId,
+ },
+ }),
+ ]);
return {
configs: filterAndValidateDbScoreConfigList(configs, traceException),
- totalCount: configsCount,
+ totalCount,
};
}),
create: protectedProjectProcedure
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index b1380f9f67..5158b13f86 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -95,19 +95,21 @@ export const scoresRouter = createTRPCRouter({
scoresTableCols,
);
- const scores = await ctx.prisma.$queryRaw<
- Array<
- Score & {
- traceName: string | null;
- traceUserId: string | null;
- jobConfigurationId: string | null;
- authorUserImage: string | null;
- authorUserName: string | null;
- }
- >
- >(
- generateScoresQuery(
- Prisma.sql`
+ const [scores, scoresCount] = await Promise.all([
+ // scores
+ ctx.prisma.$queryRaw<
+ Array<
+ Score & {
+ traceName: string | null;
+ traceUserId: string | null;
+ jobConfigurationId: string | null;
+ authorUserImage: string | null;
+ authorUserName: string | null;
+ }
+ >
+ >(
+ generateScoresQuery(
+ Prisma.sql`
s.id,
s.name,
s.value,
@@ -125,28 +127,27 @@ export const scoresRouter = createTRPCRouter({
u.image AS "authorUserImage",
u.name AS "authorUserName"
`,
- input.projectId,
- ctx.session.orgId,
- filterCondition,
- orderByCondition,
- input.limit,
- input.page,
+ input.projectId,
+ ctx.session.orgId,
+ filterCondition,
+ orderByCondition,
+ input.limit,
+ input.page,
+ ),
),
- );
-
- const scoresCount = await ctx.prisma.$queryRaw<
- Array<{ totalCount: bigint }>
- >(
- generateScoresQuery(
- Prisma.sql` count(*) AS "totalCount"`,
- input.projectId,
- ctx.session.orgId,
- filterCondition,
- Prisma.empty,
- 1, // limit
- 0, // page
+ // scoresCount
+ await ctx.prisma.$queryRaw<Array<{ totalCount: bigint }>>(
+ generateScoresQuery(
+ Prisma.sql` count(*) AS "totalCount"`,
+ input.projectId,
+ ctx.session.orgId,
+ filterCondition,
+ Prisma.empty,
+ 1, // limit
+ 0, // page
+ ),
),
- );
+ ]);
return {
scores,
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 00e9d990a1..3c9d9c014c 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -130,42 +130,41 @@ export const sessionRouter = createTRPCRouter({
});
}
- const scores = await ctx.prisma.score.findMany({
- where: {
- traceId: {
- in: session.traces.map((t) => t.id),
+ 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,
},
- projectId: input.projectId,
- },
- });
+ }),
+ // costData
+ ctx.prisma.$queryRaw<Array<{ totalCost: number }>>(totalCostQuery),
+ ]);
const validatedScores = filterAndValidateDbScoreList(
scores,
traceException,
);
- 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 [costData] =
- await ctx.prisma.$queryRaw<Array<{ totalCost: number }>>(
- totalCostQuery,
- );
-
return {
...session,
traces: session.traces.map((t) => ({
...t,
scores: validatedScores.filter((s) => s.traceId === t.id),
})),
- totalCost: costData?.totalCost ?? 0,
+ totalCost: costData[0].totalCost ?? 0,
users: [
...new Set(
session.traces.map((t) => t.userId).filter((t) => t !== null),