🪢 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
retry generation and span PATCH (#140)
Maximilian Deichmann6160f17208c5
diff --git a/package-lock.json b/package-lock.jsonindex 4520b9e4fe..37a5d52c70 100644--- a/package-lock.json+++ b/package-lock.json@@ -51,6 +51,7 @@"cmdk": "^0.2.0","cors": "^2.8.5","decimal.js": "^10.4.3",+ "exponential-backoff": "^3.1.1","js-yaml": "^4.1.0","lodash": "^4.17.21","lucide-react": "^0.274.0",diff --git a/package.json b/package.jsonindex e123afe14c..bd7d631ee8 100644--- a/package.json+++ b/package.json@@ -11,7 +11,7 @@"prettier": "prettier --write ./src *.{ts,js}","clean": "rm -rf node_modules","start": "next start",- "test": "jest --runInBand",+ "test": "jest --verbose=true --runInBand","test:watch": "jest --watch --runInBand","db:migrate": "npx prisma migrate dev","db:seed": "npx prisma db seed",@@ -63,6 +63,7 @@"cmdk": "^0.2.0","cors": "^2.8.5","decimal.js": "^10.4.3",+ "exponential-backoff": "^3.1.1","js-yaml": "^4.1.0","lodash": "^4.17.21","lucide-react": "^0.274.0",diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.tsindex 8ff86975ef..019387440e 100644--- a/src/pages/api/public/generations.ts+++ b/src/pages/api/public/generations.ts@@ -1,11 +1,17 @@import { prisma } from "@/src/server/db";-import { ObservationLevel, ObservationType } from "@prisma/client";+import {+ ObservationLevel,+ ObservationType,+ type PrismaClient,+} from "@prisma/client";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";import { tokenCount } from "@/src/features/ingest/lib/usage";import { v4 as uuidv4 } from "uuid";+import { backOff } from "exponential-backoff";+import { RessourceNotFoundError } from "../../../utils/exceptions";export const GenerationsCreateSchema = z.object({id: z.string().nullish(),@@ -248,123 +254,37 @@ export default async function handler();try {- const {- generationId,- traceId,- endTime,- completionStartTime,- prompt,- completion,- usage,- model,- ...otherFields- } = GenerationPatchSchema.parse(req.body);-- const existingObservation = await prisma.observation.findUnique({- where: { id: generationId, projectId: authCheck.scope.projectId },- select: {- promptTokens: true,- completionTokens: true,- model: true,+ const newObservation = await backOff(+ async () =>+ await patchGeneration(+ prisma,+ GenerationPatchSchema.parse(req.body),+ authCheck.scope.projectId,+ ),+ {+ numOfAttempts: 3,+ retry: (e: Error, attemptNumber: number) => {+ if (e instanceof RessourceNotFoundError) {+ console.log(+ `retrying generation patch, attempt ${attemptNumber}`,+ );+ return true;+ }+ return false;+ },},- });+ );+ res.status(200).json(newObservation);+ } catch (error: unknown) {+ console.error(error);- if (!existingObservation) {- console.log(`generation with id ${generationId} not found`);+ if (error instanceof RessourceNotFoundError) {return res.status(404).json({success: false,message: "Observation not found",});}- const mergedModel = model ?? existingObservation?.model ?? null;-- const newPromptTokens =- usage?.promptTokens ??- (mergedModel && prompt- ? tokenCount({- model: mergedModel,- text: JSON.stringify(prompt),- })- : undefined);-- const newCompletionTokens =- usage?.completionTokens ??- (mergedModel && completion- ? tokenCount({- model: mergedModel,- text: completion,- })- : undefined);-- const newTotalTokens =- usage?.totalTokens ??- (newPromptTokens ?? existingObservation?.promptTokens ?? 0) +- (newCompletionTokens ?? existingObservation?.completionTokens ?? 0);-- // Check before upsert as Prisma only upserts in DB transaction when using unique key in select- // Including projectid would lead to race conditions and unique key errors- const observationWithSameId = await prisma.observation.count({- where: {- id: generationId,- projectId: {- not: authCheck.scope.projectId,- },- },- });- if (observationWithSameId > 0)- throw new Error(- "Observation with same id already exists in another project",- );-- const newObservation = await prisma.observation.upsert({- where: {- id: generationId,- },- create: {- id: generationId,- traceId: traceId ?? undefined,- type: ObservationType.GENERATION,- endTime: endTime ? new Date(endTime) : undefined,- completionStartTime: completionStartTime- ? new Date(completionStartTime)- : undefined,- input: prompt ?? undefined,- output: completion ? { completion: completion } : undefined,- promptTokens: newPromptTokens,- completionTokens: newCompletionTokens,- totalTokens: newTotalTokens,- model: model ?? undefined,- ...Object.fromEntries(- Object.entries(otherFields).filter(- ([_, v]) => v !== null && v !== undefined,- ),- ),- projectId: authCheck.scope.projectId,- },- update: {- endTime: endTime ? new Date(endTime) : undefined,- completionStartTime: completionStartTime- ? new Date(completionStartTime)- : undefined,- input: prompt ?? undefined,- output: completion ? { completion: completion } : undefined,- promptTokens: newPromptTokens,- completionTokens: newCompletionTokens,- totalTokens: newTotalTokens,- traceId: traceId ?? undefined,- model: model ?? undefined,- ...Object.fromEntries(- Object.entries(otherFields).filter(- ([_, v]) => v !== null && v !== undefined,- ),- ),- },- });-- res.status(200).json(newObservation);- } catch (error: unknown) {- console.error(error);const errorMessage =error instanceof Error ? error.message : "An unknown error occurred";res.status(400).json({@@ -377,3 +297,123 @@ export default async function handler(return res.status(405).json({ message: "Method not allowed" });}}++const patchGeneration = async (+ prisma: PrismaClient,+ generationPatch: z.infer<typeof GenerationPatchSchema>,+ authenticatedProjectId: string,+) => {+ const {+ generationId,+ traceId,+ endTime,+ completionStartTime,+ prompt,+ completion,+ usage,+ model,+ ...otherFields+ } = generationPatch;++ const existingObservation = await prisma.observation.findUnique({+ where: {+ id: generationPatch.generationId,+ projectId: authenticatedProjectId,+ },+ select: {+ promptTokens: true,+ completionTokens: true,+ model: true,+ },+ });++ if (!existingObservation) {+ console.log(`generation with id ${generationId} not found`);+ throw new RessourceNotFoundError("generation", generationId);+ }++ const mergedModel = model ?? existingObservation?.model ?? null;++ const newPromptTokens =+ usage?.promptTokens ??+ (mergedModel && prompt+ ? tokenCount({+ model: mergedModel,+ text: JSON.stringify(prompt),+ })+ : undefined);++ const newCompletionTokens =+ usage?.completionTokens ??+ (mergedModel && completion+ ? tokenCount({+ model: mergedModel,+ text: completion,+ })+ : undefined);++ const newTotalTokens =+ usage?.totalTokens ??+ (newPromptTokens ?? existingObservation?.promptTokens ?? 0) ++ (newCompletionTokens ?? existingObservation?.completionTokens ?? 0);++ // Check before upsert as Prisma only upserts in DB transaction when using unique key in select+ // Including projectid would lead to race conditions and unique key errors+ const observationWithSameId = await prisma.observation.count({+ where: {+ id: generationId,+ projectId: {+ not: authenticatedProjectId,+ },+ },+ });+ if (observationWithSameId > 0)+ throw new Error(+ "Observation with same id already exists in another project",+ );++ return await prisma.observation.upsert({+ where: {+ id: generationId,+ },+ create: {+ id: generationId,+ traceId: traceId ?? undefined,+ type: ObservationType.GENERATION,+ endTime: endTime ? new Date(endTime) : undefined,+ completionStartTime: completionStartTime+ ? new Date(completionStartTime)+ : undefined,+ input: prompt ?? undefined,+ output: completion ? { completion: completion } : undefined,+ promptTokens: newPromptTokens,+ completionTokens: newCompletionTokens,+ totalTokens: newTotalTokens,+ model: model ?? undefined,+ ...Object.fromEntries(+ Object.entries(otherFields).filter(+ ([_, v]) => v !== null && v !== undefined,+ ),+ ),+ projectId: authenticatedProjectId,+ },+ update: {+ endTime: endTime ? new Date(endTime) : undefined,+ completionStartTime: completionStartTime+ ? new Date(completionStartTime)+ : undefined,+ input: prompt ?? undefined,+ output: completion ? { completion: completion } : undefined,+ promptTokens: newPromptTokens,+ completionTokens: newCompletionTokens,+ totalTokens: newTotalTokens,+ traceId: traceId ?? undefined,+ model: model ?? undefined,+ ...Object.fromEntries(+ Object.entries(otherFields).filter(+ ([_, v]) => v !== null && v !== undefined,+ ),+ ),+ },+ });+};diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.tsindex 018f8cf98e..a683f2dd48 100644--- a/src/pages/api/public/spans.ts+++ b/src/pages/api/public/spans.ts@@ -1,10 +1,16 @@import { prisma } from "@/src/server/db";-import { ObservationLevel, ObservationType } from "@prisma/client";+import {+ ObservationLevel,+ ObservationType,+ type PrismaClient,+} from "@prisma/client";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { cors, runMiddleware } from "@/src/features/publicApi/server/cors";import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";import { v4 as uuidv4 } from "uuid";+import { backOff } from "exponential-backoff";+import { RessourceNotFoundError } from "../../../utils/exceptions";const SpanPostSchema = z.object({id: z.string().nullish(),@@ -176,64 +182,37 @@ export default async function handler(", body:",JSON.stringify(req.body, null, 2),);- const { spanId, endTime, ...fields } = SpanPatchSchema.parse(req.body);-- // Check before upsert as Prisma only upserts in DB transaction when using unique key in select- // Including projectid would lead to race conditions and unique key errors- const observationsWithSameId = await prisma.observation.count({- where: {- id: spanId,- projectId: {- not: authCheck.scope.projectId,+ const newObservation = await backOff(+ async () =>+ await patchSpan(+ prisma,+ SpanPatchSchema.parse(req.body),+ authCheck.scope.projectId,+ ),+ {+ numOfAttempts: 3,+ retry: (e: Error, attemptNumber: number) => {+ if (e instanceof RessourceNotFoundError) {+ console.log(+ `retrying generation patch, attempt ${attemptNumber}`,+ );+ return true;+ }+ return false;},},- });-- if (observationsWithSameId > 0)- throw new Error(- "Observation with same id already exists in another project",- );+ );- const existingSpan = await prisma.observation.findUnique({- where: { id: spanId, projectId: authCheck.scope.projectId },- });+ res.status(200).json(newObservation);+ } catch (error: unknown) {+ console.error(error);- if (!existingSpan) {- console.log(`span with id ${spanId} not found`);+ if (error instanceof RessourceNotFoundError) {return res.status(404).json({success: false,message: "Span not found",});}-- const newObservation = await prisma.observation.upsert({- where: {- id: spanId,- },- create: {- id: spanId,- type: ObservationType.SPAN,- endTime: endTime ? new Date(endTime) : undefined,- ...Object.fromEntries(- Object.entries(fields).filter(- ([_, v]) => v !== null && v !== undefined,- ),- ),- projectId: authCheck.scope.projectId,- },- update: {- endTime: endTime ? new Date(endTime) : undefined,- ...Object.fromEntries(- Object.entries(fields).filter(- ([_, v]) => v !== null && v !== undefined,- ),- ),- },- });-- res.status(200).json(newObservation);- } catch (error: unknown) {- console.error(error);const errorMessage =error instanceof Error ? error.message : "An unknown error occurred";res.status(400).json({@@ -246,3 +225,61 @@ export default async function handler(res.status(405).json({ message: "Method not allowed" });}}++const patchSpan = async (+ prisma: PrismaClient,+ spanPatch: z.infer<typeof SpanPatchSchema>,+ authenticatedProjectId: string,+) => {+ const { spanId, endTime, ...fields } = spanPatch;++ // Check before upsert as Prisma only upserts in DB transaction when using unique key in select+ // Including projectid would lead to race conditions and unique key errors+ const observationsWithSameId = await prisma.observation.count({+ where: {+ id: spanId,+ projectId: {+ not: authenticatedProjectId,+ },+ },+ });++ if (observationsWithSameId > 0)+ throw new Error(+ "Observation with same id already exists in another project",+ );++ const existingSpan = await prisma.observation.findUnique({+ where: { id: spanId, projectId: authenticatedProjectId },+ });++ if (!existingSpan) {+ console.log(`span with id ${spanId} not found`);+ throw new RessourceNotFoundError("span", spanId);+ }++ return await prisma.observation.upsert({+ where: {+ id: spanId,+ },+ create: {+ id: spanId,+ type: ObservationType.SPAN,+ endTime: endTime ? new Date(endTime) : undefined,+ ...Object.fromEntries(+ Object.entries(fields).filter(+ ([_, v]) => v !== null && v !== undefined,+ ),+ ),+ projectId: authenticatedProjectId,+ },+ update: {+ endTime: endTime ? new Date(endTime) : undefined,+ ...Object.fromEntries(+ Object.entries(fields).filter(+ ([_, v]) => v !== null && v !== undefined,+ ),+ ),+ },+ });+};diff --git a/src/utils/exceptions.ts b/src/utils/exceptions.tsnew file mode 100644index 0000000000..0c59b43497--- /dev/null+++ b/src/utils/exceptions.ts@@ -0,0 +1,6 @@+export class RessourceNotFoundError extends Error {+ constructor(type: string, id: string) {+ super(`${type} with ${id} not found}`);+ this.name = "RessourceNotFoundError";+ }+}