-
Notifications
You must be signed in to change notification settings - Fork 382
/
EventProcessor.ts
586 lines (540 loc) 路 17.9 KB
/
EventProcessor.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
import { tokenCount } from "@/src/features/ingest/lib/usage";
import { checkApiAccessScope } from "@/src/features/public-api/server/apiScope";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import {
type legacyObservationCreateEvent,
eventTypes,
type scoreEvent,
type eventCreateEvent,
type spanCreateEvent,
type generationCreateEvent,
type spanUpdateEvent,
type generationUpdateEvent,
type legacyObservationUpdateEvent,
type sdkLogEvent,
type traceEvent,
} from "@/src/features/public-api/server/ingestion-api-schema";
import { prisma } from "@langfuse/shared/src/db";
import { ResourceNotFoundError } from "@/src/utils/exceptions";
import { mergeJson } from "@/src/utils/json";
import {
type Trace,
type Observation,
type Score,
Prisma,
type Model,
} from "@langfuse/shared/src/db";
import { v4 } from "uuid";
import { type z } from "zod";
import { jsonSchema } from "@/src/utils/zod";
import { sendToBetterstack } from "@/src/features/betterstack/server/betterstack-webhook";
import { ForbiddenError } from "@langfuse/shared";
export interface EventProcessor {
process(
apiScope: ApiAccessScope,
): Promise<Trace | Observation | Score> | undefined;
}
export async function findModel(p: {
event: {
projectId: string;
model?: string;
unit?: string;
startTime?: Date;
};
existingDbObservation?: Observation;
}): Promise<Model | null> {
const { event, existingDbObservation } = p;
// either get the model from the existing observation
// or match pattern on the user provided model name
const modelCondition = event.model
? Prisma.sql`AND ${event.model} ~ match_pattern`
: existingDbObservation?.internalModel
? Prisma.sql`AND model_name = ${existingDbObservation.internalModel}`
: undefined;
if (!modelCondition) return null;
// unit based on the current event or the existing observation, both can be undefined
const mergedUnit = event.unit ?? existingDbObservation?.unit;
const unitCondition = mergedUnit
? Prisma.sql`AND unit = ${mergedUnit}`
: Prisma.empty;
const sql = Prisma.sql`
SELECT
id,
created_at AS "createdAt",
updated_at AS "updatedAt",
project_id AS "projectId",
model_name AS "modelName",
match_pattern AS "matchPattern",
start_date AS "startDate",
input_price AS "inputPrice",
output_price AS "outputPrice",
total_price AS "totalPrice",
unit,
tokenizer_id AS "tokenizerId",
tokenizer_config AS "tokenizerConfig"
FROM
models
WHERE (project_id = ${event.projectId}
OR project_id IS NULL)
${modelCondition}
${unitCondition}
AND (start_date IS NULL OR start_date <= ${
event.startTime ? new Date(event.startTime) : new Date()
}::timestamp with time zone at time zone 'UTC')
ORDER BY
project_id ASC,
start_date DESC
LIMIT 1
`;
const foundModels = await prisma.$queryRaw<Array<Model>>(sql);
return foundModels[0] ?? null;
}
type ObservationEvent =
| z.infer<typeof legacyObservationCreateEvent>
| z.infer<typeof legacyObservationUpdateEvent>
| z.infer<typeof eventCreateEvent>
| z.infer<typeof spanCreateEvent>
| z.infer<typeof spanUpdateEvent>
| z.infer<typeof generationCreateEvent>
| z.infer<typeof generationUpdateEvent>;
export class ObservationProcessor implements EventProcessor {
event: ObservationEvent;
constructor(event: ObservationEvent) {
this.event = event;
}
async convertToObservation(
apiScope: ApiAccessScope,
existingObservation: Observation | null,
): Promise<{
id: string;
create: Prisma.ObservationUncheckedCreateInput;
update: Prisma.ObservationUncheckedUpdateInput;
}> {
let type: "EVENT" | "SPAN" | "GENERATION";
switch (this.event.type) {
case eventTypes.OBSERVATION_CREATE:
case eventTypes.OBSERVATION_UPDATE:
type = this.event.body.type;
break;
case eventTypes.EVENT_CREATE:
type = "EVENT" as const;
break;
case eventTypes.SPAN_CREATE:
case eventTypes.SPAN_UPDATE:
type = "SPAN" as const;
break;
case eventTypes.GENERATION_CREATE:
case eventTypes.GENERATION_UPDATE:
type = "GENERATION" as const;
break;
}
if (
this.event.type === eventTypes.OBSERVATION_UPDATE &&
!existingObservation
) {
throw new ResourceNotFoundError(this.event.id, "Observation not found");
}
// find matching model definition based on event and existing observation in db
const internalModel: Model | undefined | null =
type === "GENERATION"
? await findModel({
event: {
projectId: apiScope.projectId,
model:
"model" in this.event.body
? this.event.body.model ?? undefined
: undefined,
unit:
"usage" in this.event.body
? this.event.body.usage?.unit ?? undefined
: undefined,
startTime: this.event.body.startTime
? new Date(this.event.body.startTime)
: undefined,
},
existingDbObservation: existingObservation ?? undefined,
})
: undefined;
const traceId =
!this.event.body.traceId && !existingObservation
? // Create trace if no traceid
(
await prisma.trace.create({
data: {
projectId: apiScope.projectId,
name: this.event.body.name,
},
})
).id
: this.event.body.traceId;
const [newInputCount, newOutputCount] =
"usage" in this.event.body
? this.calculateTokenCounts(
this.event.body,
internalModel ?? undefined,
existingObservation ?? undefined,
)
: [undefined, undefined];
// merge metadata from existingObservation.metadata and metadata
const mergedMetadata = mergeJson(
existingObservation?.metadata
? jsonSchema.parse(existingObservation.metadata)
: undefined,
this.event.body.metadata ?? undefined,
);
const prompt =
"promptName" in this.event.body &&
typeof this.event.body.promptName === "string" &&
"promptVersion" in this.event.body &&
typeof this.event.body.promptVersion === "number"
? await prisma.prompt.findUnique({
where: {
projectId_name_version: {
projectId: apiScope.projectId,
name: this.event.body.promptName,
version: this.event.body.promptVersion,
},
},
})
: undefined;
// Only null if promptName and promptVersion are set but prompt is not found
if (prompt === null)
console.warn("Prompt not found for observation", this.event.body);
const observationId = this.event.body.id ?? v4();
return {
id: observationId,
create: {
id: observationId,
traceId: traceId,
type: type,
name: this.event.body.name,
startTime: this.event.body.startTime
? new Date(this.event.body.startTime)
: undefined,
endTime:
"endTime" in this.event.body && this.event.body.endTime
? new Date(this.event.body.endTime)
: undefined,
completionStartTime:
"completionStartTime" in this.event.body &&
this.event.body.completionStartTime
? new Date(this.event.body.completionStartTime)
: undefined,
metadata: mergedMetadata ?? this.event.body.metadata ?? undefined,
model: "model" in this.event.body ? this.event.body.model : undefined,
modelParameters:
"modelParameters" in this.event.body
? this.event.body.modelParameters ?? undefined
: undefined,
input: this.event.body.input ?? undefined,
output: this.event.body.output ?? undefined,
promptTokens: newInputCount,
completionTokens: newOutputCount,
totalTokens:
"usage" in this.event.body
? this.event.body.usage?.total ??
(newInputCount ?? 0) + (newOutputCount ?? 0)
: undefined,
unit:
"usage" in this.event.body
? this.event.body.usage?.unit ?? internalModel?.unit
: internalModel?.unit,
level: this.event.body.level ?? undefined,
statusMessage: this.event.body.statusMessage ?? undefined,
parentObservationId: this.event.body.parentObservationId ?? undefined,
version: this.event.body.version ?? undefined,
projectId: apiScope.projectId,
promptId: prompt ? prompt.id : undefined,
...(internalModel
? { internalModel: internalModel.modelName }
: undefined),
inputCost:
"usage" in this.event.body
? this.event.body.usage?.inputCost
: undefined,
outputCost:
"usage" in this.event.body
? this.event.body.usage?.outputCost
: undefined,
totalCost:
"usage" in this.event.body
? this.event.body.usage?.totalCost
: undefined,
},
update: {
name: this.event.body.name ?? undefined,
startTime: this.event.body.startTime
? new Date(this.event.body.startTime)
: undefined,
endTime:
"endTime" in this.event.body && this.event.body.endTime
? new Date(this.event.body.endTime)
: undefined,
completionStartTime:
"completionStartTime" in this.event.body &&
this.event.body.completionStartTime
? new Date(this.event.body.completionStartTime)
: undefined,
metadata: mergedMetadata ?? this.event.body.metadata ?? undefined,
model: "model" in this.event.body ? this.event.body.model : undefined,
modelParameters:
"modelParameters" in this.event.body
? this.event.body.modelParameters ?? undefined
: undefined,
input: this.event.body.input ?? undefined,
output: this.event.body.output ?? undefined,
promptTokens: newInputCount,
completionTokens: newOutputCount,
totalTokens:
"usage" in this.event.body
? this.event.body.usage?.total ??
(newInputCount ?? 0) + (newOutputCount ?? 0)
: undefined,
unit:
"usage" in this.event.body
? this.event.body.usage?.unit ?? internalModel?.unit
: internalModel?.unit,
level: this.event.body.level ?? undefined,
statusMessage: this.event.body.statusMessage ?? undefined,
parentObservationId: this.event.body.parentObservationId ?? undefined,
version: this.event.body.version ?? undefined,
promptId: prompt ? prompt.id : undefined,
...(internalModel
? { internalModel: internalModel.modelName }
: undefined),
inputCost:
"usage" in this.event.body
? this.event.body.usage?.inputCost
: undefined,
outputCost:
"usage" in this.event.body
? this.event.body.usage?.outputCost
: undefined,
totalCost:
"usage" in this.event.body
? this.event.body.usage?.totalCost
: undefined,
},
};
}
calculateTokenCounts(
body:
| z.infer<typeof legacyObservationCreateEvent>["body"]
| z.infer<typeof generationCreateEvent>["body"],
model?: Model,
existingObservation?: Observation,
) {
const newPromptTokens =
body.usage?.input ??
((body.input || existingObservation?.input) && model && model.tokenizerId
? tokenCount({
model: model,
text: body.input ?? existingObservation?.input,
})
: undefined);
const newCompletionTokens =
body.usage?.output ??
((body.output || existingObservation?.output) &&
model &&
model.tokenizerId
? tokenCount({
model: model,
text: body.output ?? existingObservation?.output,
})
: undefined);
return [newPromptTokens, newCompletionTokens];
}
async process(apiScope: ApiAccessScope): Promise<Observation> {
if (apiScope.accessLevel !== "all")
throw new ForbiddenError("Access denied for observation creation");
const existingObservation = this.event.body.id
? await prisma.observation.findFirst({
where: { id: this.event.body.id },
})
: null;
if (
existingObservation &&
existingObservation.projectId !== apiScope.projectId
) {
throw new ForbiddenError(
`Access denied for observation creation ${existingObservation.projectId} `,
);
}
const obs = await this.convertToObservation(apiScope, existingObservation);
// Do not use nested upserts or multiple where conditions as this should be a single native database upsert
// https://www.prisma.io/docs/orm/reference/prisma-client-reference#database-upserts
return await prisma.observation.upsert({
where: {
id: obs.id,
},
create: obs.create,
update: obs.update,
});
}
}
export class TraceProcessor implements EventProcessor {
event: z.infer<typeof traceEvent>;
constructor(event: z.infer<typeof traceEvent>) {
this.event = event;
}
async process(
apiScope: ApiAccessScope,
): Promise<Trace | Observation | Score> {
const { body } = this.event;
if (apiScope.accessLevel !== "all")
throw new ForbiddenError(
`Access denied for trace creation, ${apiScope.accessLevel}`,
);
const internalId = body.id ?? v4();
console.log(
"Trying to create trace, project ",
apiScope.projectId,
", body:",
body,
);
const existingTrace = await prisma.trace.findFirst({
where: {
id: internalId,
},
});
if (existingTrace && existingTrace.projectId !== apiScope.projectId) {
throw new ForbiddenError(
`Access denied for trace creation ${existingTrace.projectId} `,
);
}
const mergedMetadata = mergeJson(
existingTrace?.metadata
? jsonSchema.parse(existingTrace.metadata)
: undefined,
body.metadata ?? undefined,
);
if (body.sessionId) {
await prisma.traceSession.upsert({
where: {
id_projectId: {
id: body.sessionId,
projectId: apiScope.projectId,
},
},
create: {
id: body.sessionId,
projectId: apiScope.projectId,
},
update: {},
});
}
// Do not use nested upserts or multiple where conditions as this should be a single native database upsert
// https://www.prisma.io/docs/orm/reference/prisma-client-reference#database-upserts
const upsertedTrace = await prisma.trace.upsert({
where: {
id: internalId,
},
create: {
id: internalId,
timestamp: this.event.body.timestamp
? new Date(this.event.body.timestamp)
: undefined,
name: body.name ?? undefined,
userId: body.userId ?? undefined,
input: body.input ?? undefined,
output: body.output ?? undefined,
metadata: mergedMetadata ?? body.metadata ?? undefined,
release: body.release ?? undefined,
version: body.version ?? undefined,
sessionId: body.sessionId ?? undefined,
public: body.public ?? undefined,
projectId: apiScope.projectId,
tags: body.tags ?? undefined,
},
update: {
name: body.name ?? undefined,
timestamp: this.event.body.timestamp
? new Date(this.event.body.timestamp)
: undefined,
userId: body.userId ?? undefined,
input: body.input ?? undefined,
output: body.output ?? undefined,
metadata: mergedMetadata ?? body.metadata ?? undefined,
release: body.release ?? undefined,
version: body.version ?? undefined,
sessionId: body.sessionId ?? undefined,
public: body.public ?? undefined,
tags: body.tags ?? undefined,
},
});
return upsertedTrace;
}
}
export class ScoreProcessor implements EventProcessor {
event: z.infer<typeof scoreEvent>;
constructor(event: z.infer<typeof scoreEvent>) {
this.event = event;
}
async process(
apiScope: ApiAccessScope,
): Promise<Trace | Observation | Score> {
const { body } = this.event;
const accessCheck = await checkApiAccessScope(
apiScope,
[
{ type: "trace", id: body.traceId },
...(body.observationId
? [{ type: "observation" as const, id: body.observationId }]
: []),
],
"score",
);
if (!accessCheck)
throw new ForbiddenError("Access denied for score creation");
const id = body.id ?? v4();
// access control via traceId
return await prisma.score.upsert({
where: {
id_traceId: {
id,
traceId: body.traceId,
},
},
create: {
id,
trace: { connect: { id: body.traceId } },
timestamp: new Date(),
value: body.value,
name: body.name,
source: "API",
comment: body.comment,
...(body.observationId && {
observation: { connect: { id: body.observationId } },
}),
},
update: {
timestamp: new Date(),
value: body.value,
name: body.name,
comment: body.comment,
source: "API",
...(body.observationId && {
observation: { connect: { id: body.observationId } },
}),
},
});
}
}
export class SdkLogProcessor implements EventProcessor {
event: z.infer<typeof sdkLogEvent>;
constructor(event: z.infer<typeof sdkLogEvent>) {
this.event = event;
}
process(apiScope: ApiAccessScope) {
try {
void sendToBetterstack({
type: "sdk-log",
event: this.event,
projectId: apiScope.projectId,
});
return undefined;
} catch (error) {
return undefined;
}
}
}