-
Notifications
You must be signed in to change notification settings - Fork 382
/
traces.ts
201 lines (187 loc) 路 6.52 KB
/
traces.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
import { Prisma, type Trace } from "@langfuse/shared/src/db";
import { paginationZod } from "@/src/utils/zod";
import {
handleBatch,
handleBatchResultLegacy,
} from "@/src/pages/api/public/ingestion";
import {
TraceBody,
eventTypes,
stringDate,
} 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, orderBy } from "@langfuse/shared";
import { isPrismaException } from "@/src/utils/exceptions";
const GetTracesSchema = z.object({
...paginationZod,
userId: z.string().nullish(),
name: z.string().nullish(),
tags: z.union([z.array(z.string()), z.string()]).nullish(),
fromTimestamp: stringDate,
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(
req: NextApiRequest,
res: NextApiResponse,
) {
await runMiddleware(req, res, cors);
// CHECK AUTH
const authCheck = await verifyAuthHeaderAndReturnScope(
req.headers.authorization,
);
if (!authCheck.validKey)
return res.status(401).json({
message: authCheck.error,
});
// END CHECK AUTH
try {
if (req.method === "POST") {
console.log(
"Trying to create trace, project ",
authCheck.scope.projectId,
", body:",
JSON.stringify(req.body, null, 2),
);
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
message: "Access denied - need to use basic auth with secret key",
});
}
const body = TraceBody.parse(req.body);
await telemetry();
const event = {
id: v4(),
type: eventTypes.TRACE_CREATE,
timestamp: new Date().toISOString(),
body: body,
};
const result = await handleBatch([event], {}, req, authCheck);
handleBatchResultLegacy(result.errors, result.results, res);
} else if (req.method === "GET") {
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
message: "Access denied - need to use basic auth with secret key",
});
}
const obj = GetTracesSchema.parse(req.query); // uses query and not body
const skipValue = (obj.page - 1) * obj.limit;
const userCondition = obj.userId
? Prisma.sql`AND t."user_id" = ${obj.userId}`
: Prisma.empty;
const nameCondition = obj.name
? Prisma.sql`AND t."name" = ${obj.name}`
: Prisma.empty;
const tagsCondition = obj.tags
? Prisma.sql`AND ARRAY[${Prisma.join(
(Array.isArray(obj.tags) ? obj.tags : [obj.tags]).map(
(v) => Prisma.sql`${v}`,
),
", ",
)}] <@ t."tags"`
: Prisma.empty;
const fromTimestampCondition = obj.fromTimestamp
? Prisma.sql`AND t."timestamp" >= ${obj.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
: Prisma.empty;
const orderByCondition = orderByToPrismaSql(
obj.orderBy ?? null,
tracesTableCols,
);
const traces = await prisma.$queryRaw<
Array<Trace & { observations: string[]; scores: string[] }>
>(Prisma.sql`
SELECT
t.id,
CONCAT('/project/', t.project_id,'/traces/',t.id) as "htmlPath",
t.timestamp,
t.name,
t.input,
t.output,
t.project_id as "projectId",
t.session_id as "sessionId",
t.metadata,
t.external_id as "externalId",
t.user_id as "userId",
t.release,
t.version,
t.public,
t.tags,
COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION AS "totalCost",
COALESCE(EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time")), 0)::double precision AS "latency",
COALESCE(ARRAY_AGG(DISTINCT o.id) FILTER (WHERE o.id IS NOT NULL), ARRAY[]::text[]) AS "observations",
COALESCE(ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL), ARRAY[]::text[]) AS "scores"
FROM "traces" AS t
LEFT JOIN "observations_view" AS o ON t.id = o.trace_id AND o.project_id = ${authCheck.scope.projectId}
LEFT JOIN "scores" AS s ON t.id = s.trace_id
WHERE t.project_id = ${authCheck.scope.projectId}
${userCondition}
${nameCondition}
${tagsCondition}
${fromTimestampCondition}
GROUP BY t.id
${orderByCondition}
LIMIT ${obj.limit} OFFSET ${skipValue}
`);
const totalItems = await prisma.trace.count({
where: {
projectId: authCheck.scope.projectId,
name: obj.name ? obj.name : undefined,
userId: obj.userId ? obj.userId : undefined,
timestamp: obj.fromTimestamp
? { gte: new Date(obj.fromTimestamp) }
: undefined,
tags: obj.tags
? {
hasEvery: Array.isArray(obj.tags) ? obj.tags : [obj.tags],
}
: undefined,
},
});
return res.status(200).json({
data: traces,
meta: {
page: obj.page,
limit: obj.limit,
totalItems,
totalPages: Math.ceil(totalItems / obj.limit),
},
});
} else {
console.error(req.method, req.body);
return res.status(405).json({ message: "Method not allowed" });
}
} catch (error: unknown) {
console.error(error);
if (isPrismaException(error)) {
return res.status(500).json({
errors: ["Internal Server Error"],
});
}
if (error instanceof z.ZodError) {
return res.status(400).json({
message: "Invalid request data",
error: error.errors,
});
}
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(500).json({
message: "Invalid request data",
error: errorMessage,
});
}
}