Skip to content

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

feat: support ordering traces on the GET API (#913)

Max Deichmanna67235ab8a3b
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index a5a0fe063d..433d26ddcc 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -26,6 +26,9 @@ service:
limit: optional<integer>
userId: optional<string>
name: optional<string>
+ orderBy:
+ type: string
+ docs: Format of the string sort_by=timestamp.asc (id, timestamp, name, userId, release, version, public, bookmarked, sessionId)
tags:
type: optional<string>
allow-multiple: true
@@ -37,3 +40,6 @@ types:
properties:
data: list<commons.TraceWithDetails>
meta: pagination.MetaResponse
+ Sort:
+ properties:
+ id: string
diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.ts
index f8542dfdf5..9675fa6289 100644
--- a/src/pages/api/public/traces.ts
+++ b/src/pages/api/public/traces.ts
@@ -15,12 +15,24 @@ import {
} from "@/src/features/public-api/server/ingestion-api-schema";
import { v4 } from "uuid";
import { telemetry } from "@/src/features/telemetry";
+import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";
+import { tracesTableCols } from "@/src/server/api/definitions/tracesTable";
+import { orderBy } from "@/src/server/api/interfaces/orderBy";
const GetTracesSchema = z.object({
...paginationZod,
userId: z.string().nullish(),
name: z.string().nullish(),
tags: z.union([z.array(z.string()), z.string()]).nullish(),
+ orderBy: z
+ .string() // orderBy=timestamp.asc
+ .nullish()
+ .transform((v) => {
+ if (!v) return null;
+ const [column, order] = v.split(".");
+ return { column, order: order?.toUpperCase() };
+ })
+ .pipe(orderBy.nullish()),
});
export default async function handler(
@@ -92,6 +104,11 @@ export default async function handler(
)}] <@ t."tags"`
: Prisma.empty;
+ const orderByCondition = orderByToPrismaSql(
+ obj.orderBy ?? null,
+ tracesTableCols,
+ );
+
const traces = await prisma.$queryRaw<
Array<Trace & { observations: string[]; scores: string[] }>
>(Prisma.sql`
@@ -116,7 +133,7 @@ export default async function handler(
${nameCondition}
${tagsCondition}
GROUP BY t.id
- ORDER BY t."timestamp" DESC
+ ${orderByCondition}
LIMIT ${obj.limit} OFFSET ${skipValue}
`);
const totalItems = await prisma.trace.count({