🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor: sequential database access (#637)
Marc Klingen6da21c6c22a5
diff --git a/src/pages/api/public/dataset-run-items.ts b/src/pages/api/public/dataset-run-items.tsindex 6f6892f69e..97f0a4692f 100644--- a/src/pages/api/public/dataset-run-items.ts+++ b/src/pages/api/public/dataset-run-items.ts@@ -44,26 +44,25 @@ export default async function handler(const { datasetItemId, observationId, runName } =DatasetRunItemPostSchema.parse(req.body);- const [item, observation] = await Promise.all([- prisma.datasetItem.findUnique({- where: {- id: datasetItemId,- status: "ACTIVE",- dataset: {- projectId: authCheck.scope.projectId,- },- },- include: {- dataset: true,- },- }),- prisma.observation.findUnique({- where: {- id: observationId,+ const item = await prisma.datasetItem.findUnique({+ where: {+ id: datasetItemId,+ status: "ACTIVE",+ dataset: {projectId: authCheck.scope.projectId,},- }),- ]);+ },+ include: {+ dataset: true,+ },+ });+ const observation = await prisma.observation.findUnique({+ where: {+ id: observationId,+ projectId: authCheck.scope.projectId,+ },+ });+// Validity of id and access checksif (!item) {console.error("item not found");diff --git a/src/pages/api/public/metrics/usage.ts b/src/pages/api/public/metrics/usage.tsindex 2cbeb36f18..ad90febf36 100644--- a/src/pages/api/public/metrics/usage.ts+++ b/src/pages/api/public/metrics/usage.ts@@ -43,8 +43,7 @@ export default async function handler(: Prisma.empty;if (obj.group_by === undefined) {- const [usage, totalItemsRes] = await Promise.all([- prisma.$queryRaw`+ const usage = await prisma.$queryRaw`WITH model_usage AS (SELECTDATE_TRUNC('DAY',@@ -83,16 +82,15 @@ export default async function handler(FROM daily_usageORDER BY 1 descLIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}- `,- prisma.$queryRaw<{ count: bigint }[]>`+ `;+ const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>`SELECTcount(DISTINCT DATE_TRUNC('DAY', observations.start_time))FROMobservationsJOIN traces ON observations.trace_id = traces.idWHERE traces.project_id = ${authCheck.scope.projectId}- `,- ]);+ `;const totalItems =totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;@@ -107,8 +105,7 @@ export default async function handler(},});} else if (obj.group_by === "trace_name") {- const [usage, totalItemsRes] = await Promise.all([- prisma.$queryRaw`+ const usage = await prisma.$queryRaw`WITH model_usage AS (SELECTt."name" trace_name,@@ -167,15 +164,14 @@ export default async function handler(group by 1ORDER BY 1LIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}- `,- prisma.$queryRaw<{ count: bigint }[]>`+ `;+ const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>`SELECTcount(DISTINCT CASE WHEN "name" IS NULL THEN 'COUNT_NULL' ELSE "name" END)FROMtracesWHERE project_id = ${authCheck.scope.projectId}- `,- ]);+ `;const totalItems =totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;diff --git a/src/pages/api/public/observations/index.ts b/src/pages/api/public/observations/index.tsindex d6a3b375f8..ef623b76bf 100644--- a/src/pages/api/public/observations/index.ts+++ b/src/pages/api/public/observations/index.ts@@ -104,8 +104,7 @@ const getObservation = async (? Prisma.sql`AND o."parent_observation_id" = ${query.parentObservationId}`: Prisma.empty;- const [observations, count] = await Promise.all([- prisma.$queryRaw<Observation[]>`+ const observations = await prisma.$queryRaw<Observation[]>`SELECTo."id",o."name",@@ -137,8 +136,8 @@ const getObservation = async (ORDER by o."start_time" DESCOFFSET ${(query.page - 1) * query.limit}LIMIT ${query.limit}- `,- prisma.$queryRaw<{ count: bigint }[]>`+ `;+ const count = await prisma.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*) FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"WHERE o."project_id" = ${authenticatedProjectId}${observationTypeCondition}@@ -146,8 +145,7 @@ const getObservation = async (${userIdCondition}${traceIdCondition}${parentObservationIdCondition}- `,- ]);+ `;if (!count || count.length !== 1) {throw new Error(diff --git a/src/pages/api/public/scores.ts b/src/pages/api/public/scores.tsindex 322f0112f2..434932db14 100644--- a/src/pages/api/public/scores.ts+++ b/src/pages/api/public/scores.ts@@ -85,10 +85,9 @@ export default async function handler(const userCondition = Prisma.sql`AND t."user_id" = ${obj.userId}`;const nameCondition = Prisma.sql`AND s."name" = ${obj.name}`;- const [scores, totalItems] = await Promise.all([- prisma.$queryRaw<- Array<Score & { trace: { userId: string } }>- >(Prisma.sql`+ const scores = await prisma.$queryRaw<+ Array<Score & { trace: { userId: string } }>+ >(Prisma.sql`SELECTs.id,s.timestamp,@@ -105,17 +104,16 @@ export default async function handler(${obj.name ? nameCondition : Prisma.empty}ORDER BY t."timestamp" DESCLIMIT ${obj.limit} OFFSET ${skipValue}- `),- prisma.score.count({- where: {- name: obj.name ?? undefined, // optional filter- trace: {- projectId: authCheck.scope.projectId,- userId: obj.userId ?? undefined, // optional filter- },+ `);+ const totalItems = await prisma.score.count({+ where: {+ name: obj.name ?? undefined, // optional filter+ trace: {+ projectId: authCheck.scope.projectId,+ userId: obj.userId ?? undefined, // optional filter},- }),- ]);+ },+ });return res.status(200).json({data: scores,diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.tsindex 514efb48de..48664e6e72 100644--- a/src/pages/api/public/traces.ts+++ b/src/pages/api/public/traces.ts@@ -79,10 +79,9 @@ export default async function handler(const userCondition = Prisma.sql`AND t."user_id" = ${obj.userId}`;const nameCondition = Prisma.sql`AND t."name" = ${obj.name}`;- const [traces, totalItems] = await Promise.all([- prisma.$queryRaw<- Array<Trace & { observations: string[]; scores: string[] }>- >(Prisma.sql`+ const traces = await prisma.$queryRaw<+ Array<Trace & { observations: string[]; scores: string[] }>+ >(Prisma.sql`SELECTt.id,t.timestamp,@@ -105,15 +104,14 @@ export default async function handler(GROUP BY t.idORDER BY t."timestamp" DESCLIMIT ${obj.limit} OFFSET ${skipValue}- `),- prisma.trace.count({- where: {- projectId: authCheck.scope.projectId,- name: obj.name ?? undefined,- userId: obj.userId ?? undefined,- },- }),- ]);+ `);+ const totalItems = await prisma.trace.count({+ where: {+ projectId: authCheck.scope.projectId,+ name: obj.name ?? undefined,+ userId: obj.userId ?? undefined,+ },+ });return res.status(200).json({data: traces,diff --git a/src/pages/api/public/traces/[traceId].ts b/src/pages/api/public/traces/[traceId].tsindex f9c5428eec..a61848ceae 100644--- a/src/pages/api/public/traces/[traceId].ts+++ b/src/pages/api/public/traces/[traceId].ts@@ -43,23 +43,21 @@ export default async function handler(}// END CHECK ACCESS SCOPE- const [trace, observations] = await Promise.all([- prisma.trace.findFirst({- where: {- id: traceId,- projectId: authCheck.scope.projectId,- },- include: {- scores: true,- },- }),- prisma.observation.findMany({- where: {- traceId: traceId,- projectId: authCheck.scope.projectId,- },- }),- ]);+ const trace = await prisma.trace.findFirst({+ where: {+ id: traceId,+ projectId: authCheck.scope.projectId,+ },+ include: {+ scores: true,+ },+ });+ const observations = await prisma.observation.findMany({+ where: {+ traceId: traceId,+ projectId: authCheck.scope.projectId,+ },+ });if (!trace) {return res.status(404).json({diff --git a/src/pages/api/public/users.ts b/src/pages/api/public/users.tsindex 168fddbf41..ad05d4e929 100644--- a/src/pages/api/public/users.ts+++ b/src/pages/api/public/users.ts@@ -36,8 +36,7 @@ export default async function handler(const obj = GetUsersSchema.parse(req.query); // uses query and not body- const [users, totalItemsRes] = await Promise.all([- prisma.$queryRaw`+ const users = await prisma.$queryRaw`WITH model_usage AS (SELECTuser_id,@@ -93,15 +92,14 @@ export default async function handler(group by 1ORDER BY 1LIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}- `,- prisma.$queryRaw<{ count: bigint }[]>`+ `;+ const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>`SELECTcount(DISTINCT CASE WHEN user_id IS NULL THEN 'COUNT_NULL' ELSE user_id END)FROMtracesWHERE project_id = ${authCheck.scope.projectId}- `,- ]);+ `;const totalItems =totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;diff --git a/src/server/api/routers/generations.ts b/src/server/api/routers/generations.tsindex 0cf4e48219..31a01c5490 100644--- a/src/server/api/routers/generations.ts+++ b/src/server/api/routers/generations.ts@@ -255,23 +255,22 @@ export const generationsRouter = createTRPCRouter({type: "GENERATION",} as const;- const [model, name, traceName] = await Promise.all([- ctx.prisma.observation.groupBy({- by: ["model"],- where: queryFilter,- _count: { _all: true },- }),- ctx.prisma.observation.groupBy({- by: ["name"],- where: queryFilter,- _count: { _all: true },- }),- ctx.prisma.$queryRaw<- Array<{- traceName: string | null;- count: number;- }>- >(Prisma.sql`+ const model = await ctx.prisma.observation.groupBy({+ by: ["model"],+ where: queryFilter,+ _count: { _all: true },+ });+ const name = await ctx.prisma.observation.groupBy({+ by: ["name"],+ where: queryFilter,+ _count: { _all: true },+ });+ const traceName = await ctx.prisma.$queryRaw<+ Array<{+ traceName: string | null;+ count: number;+ }>+ >(Prisma.sql`SELECTt.name "traceName",count(*)::int AS count@@ -281,8 +280,8 @@ export const generationsRouter = createTRPCRouter({AND o.project_id = ${input.projectId}AND t.project_id = ${input.projectId}GROUP BY 1- `),- ]);+ `);+// typecheck filter options, needs to include all columns with optionsconst res: ObservationOptions = {model: modeldiff --git a/src/server/api/routers/scores.ts b/src/server/api/routers/scores.tsindex 32d2578632..affb95ddf8 100644--- a/src/server/api/routers/scores.ts+++ b/src/server/api/routers/scores.ts@@ -64,19 +64,17 @@ export const scoresRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- const [names] = await Promise.all([- ctx.prisma.score.groupBy({- where: {- trace: {- projectId: input.projectId,- },- },- by: ["name"],- _count: {- _all: true,+ const names = await ctx.prisma.score.groupBy({+ where: {+ trace: {+ projectId: input.projectId,},- }),- ]);+ },+ by: ["name"],+ _count: {+ _all: true,+ },+ });const res: ScoreOptions = {name: names.map((i) => ({ value: i.name, count: i._count._all })),diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.tsindex 1d6952e685..b73da60033 100644--- a/src/server/api/routers/traces.ts+++ b/src/server/api/routers/traces.ts@@ -183,25 +183,23 @@ export const traceRouter = createTRPCRouter({filterOptions: protectedProjectProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {- const [scores, names] = await Promise.all([- ctx.prisma.score.groupBy({- where: {- trace: {- projectId: input.projectId,- },- },- by: ["name"],- }),- ctx.prisma.trace.groupBy({- where: {+ const scores = await ctx.prisma.score.groupBy({+ where: {+ trace: {projectId: input.projectId,},- by: ["name"],- _count: {- _all: true,- },- }),- ]);+ },+ by: ["name"],+ });+ const names = await ctx.prisma.trace.groupBy({+ where: {+ projectId: input.projectId,+ },+ by: ["name"],+ _count: {+ _all: true,+ },+ });const res: TraceOptions = {scores_avg: scores.map((score) => score.name),name: names@@ -216,25 +214,23 @@ export const traceRouter = createTRPCRouter({byId: protectedGetTraceProcedure.input(z.object({ traceId: z.string() })).query(async ({ input, ctx }) => {- const [trace, observations, pricings] = await Promise.all([- ctx.prisma.trace.findFirstOrThrow({- where: {- id: input.traceId,- },- include: {- scores: true,- },- }),- ctx.prisma.observation.findMany({- where: {- traceId: {- equals: input.traceId,- not: null,- },+ const trace = await ctx.prisma.trace.findFirstOrThrow({+ where: {+ id: input.traceId,+ },+ include: {+ scores: true,+ },+ });+ const observations = await ctx.prisma.observation.findMany({+ where: {+ traceId: {+ equals: input.traceId,+ not: null,},- }),- ctx.prisma.pricing.findMany(),- ]);+ },+ });+ const pricings = await ctx.prisma.pricing.findMany();const obsStartTimes = observations.map((o) => o.startTime)diff --git a/src/server/api/routers/users.ts b/src/server/api/routers/users.tsindex 2554dd8d6c..fad4e9065f 100644--- a/src/server/api/routers/users.ts+++ b/src/server/api/routers/users.ts@@ -112,21 +112,20 @@ export const userRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- const [agg, lastScoresOfUsers] = await Promise.all([- ctx.prisma.$queryRaw<- {- userId: string;- firstTrace: Date;- lastTrace: Date;- totalTraces: number;- totalPromptTokens: number;- totalCompletionTokens: number;- totalTokens: number;- firstObservation: Date;- lastObservation: Date;- totalObservations: number;- }[]- >`+ const agg = await ctx.prisma.$queryRaw<+ {+ userId: string;+ firstTrace: Date;+ lastTrace: Date;+ totalTraces: number;+ totalPromptTokens: number;+ totalCompletionTokens: number;+ totalTokens: number;+ firstObservation: Date;+ lastObservation: Date;+ totalObservations: number;+ }[]+ >`SELECTt.user_id "userId",min(t."timestamp") "firstTrace",@@ -147,15 +146,14 @@ export const userRouter = createTRPCRouter({GROUP BY 1ORDER BY "totalTokens" DESCLIMIT 50- `,-- ctx.prisma.$queryRaw<- Array<- Score & {- userId: string;- }- >- >`+ `;+ const lastScoresOfUsers = await ctx.prisma.$queryRaw<+ Array<+ Score & {+ userId: string;+ }+ >+ >`WITH ranked_scores AS (SELECTt.user_id,@@ -182,8 +180,7 @@ export const userRouter = createTRPCRouter({FROMranked_scoresWHERE rn = 1- `,- ]);+ `;return {userId: input.userId,