Skip to content

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

perf: get observation I/O only if required (#3316)

Max Deichmann93ad1e68803a
diff --git a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
index d2d5e84aa5..0363eab93d 100644
--- a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
+++ b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
@@ -19,12 +19,13 @@ import { jsonSchema } from "../../../utils/zod";
import { prisma } from "../../../db";
import { LegacyIngestionAccessScope } from ".";
import { logger } from "../../logger";
+import { ApiAccessScope } from "../../auth/types";
export interface EventProcessor {
auth(apiScope: LegacyIngestionAccessScope): void;
process(
- apiScope: LegacyIngestionAccessScope,
+ apiScope: LegacyIngestionAccessScope
): Promise<Trace | Observation | Score> | undefined;
}
@@ -40,7 +41,7 @@ export class ObservationProcessor implements EventProcessor {
calculateTokenDelegate: (p: {
model: Model;
text: unknown;
- }) => number | undefined,
+ }) => number | undefined
) {
this.event = event;
this.calculateTokenDelegate = calculateTokenDelegate;
@@ -48,7 +49,7 @@ export class ObservationProcessor implements EventProcessor {
async convertToObservation(
apiScope: LegacyIngestionAccessScope,
- existingObservation: Observation | null,
+ existingObservation: Omit<Observation, "input" | "output"> | null
): Promise<{
id: string;
create: Prisma.ObservationUncheckedCreateInput;
@@ -78,7 +79,7 @@ export class ObservationProcessor implements EventProcessor {
!existingObservation
) {
throw new LangfuseNotFoundError(
- `Observation with id ${this.event.id} not found`,
+ `Observation with id ${this.event.id} not found`
);
}
@@ -120,11 +121,12 @@ export class ObservationProcessor implements EventProcessor {
// Token counts
const [newInputCount, newOutputCount] =
"usage" in this.event.body
- ? this.calculateTokenCounts(
+ ? await this.calculateTokenCounts(
+ apiScope.projectId,
this.event.body,
this.calculateTokenDelegate,
internalModel ?? undefined,
- existingObservation ?? undefined,
+ existingObservation ?? undefined
)
: [undefined, undefined];
@@ -160,7 +162,7 @@ export class ObservationProcessor implements EventProcessor {
const calculatedCosts = ObservationProcessor.calculateTokenCosts(
internalModel,
userProvidedTokenCosts,
- tokenCounts,
+ tokenCounts
);
// merge metadata from existingObservation.metadata and metadata
@@ -168,7 +170,7 @@ export class ObservationProcessor implements EventProcessor {
existingObservation?.metadata
? jsonSchema.parse(existingObservation.metadata)
: undefined,
- this.event.body.metadata ?? undefined,
+ this.event.body.metadata ?? undefined
);
const prompt =
@@ -311,7 +313,8 @@ export class ObservationProcessor implements EventProcessor {
};
}
- calculateTokenCounts(
+ async calculateTokenCounts(
+ projectId: string,
body:
| z.infer<typeof legacyObservationCreateEvent>["body"]
| z.infer<typeof generationCreateEvent>["body"],
@@ -320,29 +323,59 @@ export class ObservationProcessor implements EventProcessor {
text: unknown;
}) => number | undefined,
model?: Model,
- existingObservation?: Observation,
+ existingObservation?: Omit<Observation, "input" | "output">
) {
- const newPromptTokens =
- body.usage?.input ??
- ((body.input || existingObservation?.input) && model && model.tokenizerId
- ? calculateTokenDelegate({
- model: model,
- text: body.input ?? existingObservation?.input,
- })
- : undefined);
-
- const newCompletionTokens =
- body.usage?.output ??
- ((body.output || existingObservation?.output) &&
- model &&
- model.tokenizerId
- ? calculateTokenDelegate({
- model: model,
- text: body.output ?? existingObservation?.output,
- })
- : undefined);
+ let newPromptTokens = body.usage?.input;
+ if (newPromptTokens === undefined && model && model.tokenizerId) {
+ if (body.input) {
+ newPromptTokens = calculateTokenDelegate({
+ model: model,
+ text: body.input,
+ });
+ } else {
+ logger.info(
+ `No input provided, trying to calculate for id: ${existingObservation?.id}`
+ );
+ const observationInput = await prisma.observation.findFirst({
+ where: { id: existingObservation?.id, projectId: projectId },
+ select: {
+ input: true,
+ },
+ });
+
+ newPromptTokens = calculateTokenDelegate({
+ model: model,
+ text: observationInput?.input,
+ });
+ }
+ }
- return [newPromptTokens, newCompletionTokens];
+ let newCompletionTokens = body.usage?.output;
+
+ if (newCompletionTokens === undefined && model && model.tokenizerId) {
+ if (body.output) {
+ newCompletionTokens = calculateTokenDelegate({
+ model: model,
+ text: body.output,
+ });
+ } else {
+ logger.info(
+ `No output provided, trying to calculate for id: ${existingObservation?.id}`
+ );
+ const observationOutput = await prisma.observation.findFirst({
+ where: { id: existingObservation?.id, projectId: projectId },
+ select: {
+ output: true,
+ },
+ });
+ newCompletionTokens = calculateTokenDelegate({
+ model: model,
+ text: observationOutput?.output,
+ });
+ }
+ }
+
+ return [newPromptTokens ?? undefined, newCompletionTokens ?? undefined];
}
static calculateTokenCosts(
@@ -352,7 +385,7 @@ export class ObservationProcessor implements EventProcessor {
outputCost?: Decimal | null;
totalCost?: Decimal | null;
},
- tokenCounts: { input?: number; output?: number; total?: number },
+ tokenCounts: { input?: number; output?: number; total?: number }
): {
inputCost?: Decimal | null;
outputCost?: Decimal | null;
@@ -369,7 +402,7 @@ export class ObservationProcessor implements EventProcessor {
totalCost:
userProvidedCosts.totalCost ??
(userProvidedCosts.inputCost ?? new Decimal(0)).add(
- userProvidedCosts.outputCost ?? new Decimal(0),
+ userProvidedCosts.outputCost ?? new Decimal(0)
),
};
}
@@ -410,7 +443,43 @@ export class ObservationProcessor implements EventProcessor {
const existingObservation = this.event.body.id
? await prisma.observation.findFirst({
- where: { id: this.event.body.id },
+ select: {
+ // do not select I/O to spare our db
+ input: false,
+ output: false,
+
+ id: true,
+ traceId: true,
+ projectId: true,
+ type: true,
+ startTime: true,
+ endTime: true,
+ name: true,
+ metadata: true,
+ parentObservationId: true,
+ level: true,
+ statusMessage: true,
+ version: true,
+ createdAt: true,
+ updatedAt: true,
+ model: true,
+ internalModelId: true,
+ modelParameters: true,
+ promptTokens: true,
+ completionTokens: true,
+ totalTokens: true,
+ unit: true,
+ inputCost: true,
+ outputCost: true,
+ totalCost: true,
+ calculatedInputCost: true,
+ calculatedOutputCost: true,
+ calculatedTotalCost: true,
+ completionStartTime: true,
+ promptId: true,
+ internalModel: true,
+ },
+ where: { id: this.event.body.id, projectId: apiScope.projectId },
})
: null;
@@ -419,7 +488,7 @@ export class ObservationProcessor implements EventProcessor {
existingObservation.projectId !== apiScope.projectId
) {
throw new ForbiddenError(
- `Access denied for observation creation ${existingObservation.projectId} `,
+ `Access denied for observation creation ${existingObservation.projectId} `
);
}
@@ -449,7 +518,7 @@ export class TraceProcessor implements EventProcessor {
}
async process(
- apiScope: LegacyIngestionAccessScope,
+ apiScope: LegacyIngestionAccessScope
): Promise<Trace | Observation | Score> {
const { body } = this.event;
@@ -458,7 +527,7 @@ export class TraceProcessor implements EventProcessor {
const internalId = body.id ?? v4();
logger.debug(
- `Trying to create trace, project ${apiScope.projectId}, id: ${internalId}`,
+ `Trying to create trace, project ${apiScope.projectId}, id: ${internalId}`
);
const existingTrace = await prisma.trace.findFirst({
@@ -469,7 +538,7 @@ export class TraceProcessor implements EventProcessor {
if (existingTrace && existingTrace.projectId !== apiScope.projectId) {
throw new ForbiddenError(
- `Access denied for trace creation ${existingTrace.projectId}`,
+ `Access denied for trace creation ${existingTrace.projectId}`
);
}
@@ -477,7 +546,7 @@ export class TraceProcessor implements EventProcessor {
existingTrace?.metadata
? jsonSchema.parse(existingTrace.metadata)
: undefined,
- body.metadata ?? undefined,
+ body.metadata ?? undefined
);
const mergedTags =
@@ -555,12 +624,12 @@ export class ScoreProcessor implements EventProcessor {
auth(apiScope: LegacyIngestionAccessScope) {
if (apiScope.accessLevel !== "scores" && apiScope.accessLevel !== "all")
throw new ForbiddenError(
- `Access denied for score creation, ${apiScope.accessLevel}`,
+ `Access denied for score creation, ${apiScope.accessLevel}`
);
}
async process(
- apiScope: LegacyIngestionAccessScope,
+ apiScope: LegacyIngestionAccessScope
): Promise<Trace | Observation | Score> {
const { body } = this.event;
@@ -578,7 +647,7 @@ export class ScoreProcessor implements EventProcessor {
});
if (existingScore && existingScore.projectId !== apiScope.projectId) {
throw new ForbiddenError(
- `Access denied for score creation ${existingScore.projectId}`,
+ `Access denied for score creation ${existingScore.projectId}`
);
}
diff --git a/packages/shared/src/server/ingestion/model-match.ts b/packages/shared/src/server/ingestion/model-match.ts
index 66d4cfa92f..bd0222efce 100644
--- a/packages/shared/src/server/ingestion/model-match.ts
+++ b/packages/shared/src/server/ingestion/model-match.ts
@@ -8,7 +8,7 @@ export async function findModel(p: {
unit?: string;
startTime?: Date;
};
- existingDbObservation?: Observation;
+ existingDbObservation?: Omit<Observation, "input" | "output">;
}): Promise<Model | null> {
const { event, existingDbObservation } = p;
// either get the model from the existing observation
diff --git a/web/sentry.client.config.ts b/web/sentry.client.config.ts
index edbf5be192..d0f35c1e28 100644
--- a/web/sentry.client.config.ts
+++ b/web/sentry.client.config.ts
@@ -2,6 +2,7 @@ import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
+
// Replay may only be enabled for the client-side
integrations: [
Sentry.replayIntegration(),