🪢 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
docerize
Max Deichmanne7d981f27dc2
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000000..72e9aa4250--- /dev/null+++ b/.dockerignore@@ -0,0 +1,7 @@+Dockerfile+.dockerignore+node_modules+npm-debug.log+README.md+.next+.git\ No newline at end of filediff --git a/.vscode/settings.json b/.vscode/settings.jsondeleted file mode 100644index 610ec47213..0000000000--- a/.vscode/settings.json+++ /dev/null@@ -1,35 +0,0 @@-{- "editor.codeActionsOnSave": {- "source.fixAll.eslint": true- },- "editor.defaultFormatter": "esbenp.prettier-vscode",- "editor.formatOnSave": true,- "eslint.rules.customizations": [- {- "rule": "*",- "severity": "warn"- }- ],- "typescript.tsdk": "node_modules/typescript/lib",- "[prisma]": {- "editor.defaultFormatter": "Prisma.prisma"- },- "[python]": {- "editor.defaultFormatter": "ms-python.python",- "editor.tabSize": 2- },- "editor.tabSize": 2,- "[javascript]": {- "editor.tabSize": 2- },- "[typescript]": {- "editor.tabSize": 2- },- "[json]": {- "editor.tabSize": 2- },- "python.formatting.provider": "black",- "[yaml]": {- "editor.defaultFormatter": "esbenp.prettier-vscode"- }-}diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000000..6339bb9d3c--- /dev/null+++ b/Dockerfile@@ -0,0 +1,61 @@+FROM node:18-alpine AS base++# Install dependencies only when needed+FROM base AS deps+# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.+RUN apk add --no-cache libc6-compat+WORKDIR /app++# Install dependencies based on the preferred package manager+COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./+RUN \+ if [ -f yarn.lock ]; then yarn --frozen-lockfile; \+ elif [ -f package-lock.json ]; then npm ci; \+ elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \+ else echo "Lockfile not found." && exit 1; \+ fi+++# Rebuild the source code only when needed+FROM base AS builder+WORKDIR /app+COPY --from=deps /app/node_modules ./node_modules+COPY . .++# Next.js collects completely anonymous telemetry data about general usage.+# Learn more here: https://nextjs.org/telemetry+# Uncomment the following line in case you want to disable telemetry during the build.+# ENV NEXT_TELEMETRY_DISABLED 1++RUN npx prisma generate+RUN yarn build++# If using npm comment out above and use below instead+# RUN npm run build++# Production image, copy all the files and run next+FROM base AS runner+WORKDIR /app++ENV NODE_ENV production+# Uncomment the following line in case you want to disable telemetry during runtime.+# ENV NEXT_TELEMETRY_DISABLED 1++RUN addgroup --system --gid 1001 nodejs+RUN adduser --system --uid 1001 nextjs++COPY --from=builder /app/public ./public++# Automatically leverage output traces to reduce image size+# https://nextjs.org/docs/advanced-features/output-file-tracing+COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./+COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static+COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma++USER nextjs++EXPOSE 3000++ENV PORT 3000++CMD ["node", "server.js"]\ No newline at end of filediff --git a/docker-compose.yml b/docker-compose.ymlindex 016fc1d228..3b9a8eb547 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -1,6 +1,19 @@version: '3.5'services:++ server:+ build:+ dockerfile: Dockerfile+ command: ["sh", "-c", "npx prisma migrate deploy && node server.js"]+ depends_on:+ - db+ ports:+ - "3000:3000"+ environment:+ - NODE_ENV=development+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres+ - DIRECT_URL=postgresql://postgres:postgres@db:5432/postgresdb:image: postgresrestart: alwaysdiff --git a/next.config.mjs b/next.config.mjsindex d921057fcf..047ec82376 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -18,5 +18,6 @@ const config = {locales: ["en"],defaultLocale: "en",},+ output: 'standalone'};export default config;diff --git a/prisma/migrations/20230523082455_rename_metrics_to_gradings/migration.sql b/prisma/migrations/20230523082455_rename_metrics_to_gradings/migration.sqlnew file mode 100644index 0000000000..f7ee58664e--- /dev/null+++ b/prisma/migrations/20230523082455_rename_metrics_to_gradings/migration.sql@@ -0,0 +1,32 @@+/*+ Warnings:++ - You are about to drop the `metrics` table. If the table is not empty, all the data it contains will be lost.++*/+-- DropForeignKey+ALTER TABLE "metrics" DROP CONSTRAINT "metrics_observationId_fkey";++-- DropForeignKey+ALTER TABLE "metrics" DROP CONSTRAINT "metrics_traceId_fkey";++-- DropTable+DROP TABLE "metrics";++-- CreateTable+CREATE TABLE "gradings" (+ "id" TEXT NOT NULL,+ "timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "name" TEXT NOT NULL,+ "value" INTEGER NOT NULL,+ "traceId" TEXT NOT NULL,+ "observationId" TEXT,++ CONSTRAINT "gradings_pkey" PRIMARY KEY ("id")+);++-- AddForeignKey+ALTER TABLE "gradings" ADD CONSTRAINT "gradings_traceId_fkey" FOREIGN KEY ("traceId") REFERENCES "traces"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "gradings" ADD CONSTRAINT "gradings_observationId_fkey" FOREIGN KEY ("observationId") REFERENCES "observations"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/prisma/migrations/20230523084523_rename_to_score/migration.sql b/prisma/migrations/20230523084523_rename_to_score/migration.sqlnew file mode 100644index 0000000000..22257c0af4--- /dev/null+++ b/prisma/migrations/20230523084523_rename_to_score/migration.sql@@ -0,0 +1,32 @@+/*+ Warnings:++ - You are about to drop the `gradings` table. If the table is not empty, all the data it contains will be lost.++*/+-- DropForeignKey+ALTER TABLE "gradings" DROP CONSTRAINT "gradings_observationId_fkey";++-- DropForeignKey+ALTER TABLE "gradings" DROP CONSTRAINT "gradings_traceId_fkey";++-- DropTable+DROP TABLE "gradings";++-- CreateTable+CREATE TABLE "scores" (+ "id" TEXT NOT NULL,+ "timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "name" TEXT NOT NULL,+ "value" INTEGER NOT NULL,+ "traceId" TEXT NOT NULL,+ "observationId" TEXT,++ CONSTRAINT "scores_pkey" PRIMARY KEY ("id")+);++-- AddForeignKey+ALTER TABLE "scores" ADD CONSTRAINT "scores_traceId_fkey" FOREIGN KEY ("traceId") REFERENCES "traces"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "scores" ADD CONSTRAINT "scores_observationId_fkey" FOREIGN KEY ("observationId") REFERENCES "observations"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 308ed95854..3796f4969c 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -71,7 +71,7 @@ model Trace {status StringstatusMessage String? @map("status_message")Observations Observation[]- metrics Metric[]+ metrics Score[]@@map("traces")}@@ -88,7 +88,7 @@ model Observation {parentObservationId String? @map("parent_observation_id")parent Observation? @relation("ParentChilds", fields: [parentObservationId], references: [id])childs Observation[] @relation("ParentChilds")- metrics Metric[]+ metrics Score[]@@map("observations")}@@ -99,7 +99,7 @@ enum ObservationType {LLMCALL}-model Metric {+model Score {id String @id @default(cuid())timestamp DateTime @default(now())name String@@ -109,5 +109,5 @@ model Metric {observationId String?observation Observation? @relation(fields: [observationId], references: [id], onDelete: SetNull)- @@map("metrics")+ @@map("scores")}diff --git a/prisma/seed.ts b/prisma/seed.tsindex 452db13a5a..228ea3a8d9 100644--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -77,7 +77,7 @@ async function main() {},});- const metric1 = await prisma.metric.create({+ const score1 = await prisma.score.create({data: {name: "user_feedback",value: 1,@@ -94,7 +94,7 @@ async function main() {},});- const metric2 = await prisma.metric.create({+ const score2 = await prisma.score.create({data: {name: "change_of_completion",value: 22,@@ -106,7 +106,7 @@ async function main() {},});- console.log({ trace, span, event, llmCall, metric1, metric2 });+ console.log({ trace, span, event, llmCall, grading1: score1, grading2: score2 });}main()diff --git a/src/components/ui/code.tsx b/src/components/ui/code.tsxindex 438485a845..eb66891828 100644--- a/src/components/ui/code.tsx+++ b/src/components/ui/code.tsx@@ -1,5 +1,6 @@import { type PropsWithChildren } from "react";+// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport function JSONview(props: { json: string | any }) {const text =typeof props.json === "string"diff --git a/src/pages/api-doc.tsx b/src/pages/api-doc.tsxindex c77d851b9f..6bb8eba5f2 100644--- a/src/pages/api-doc.tsx+++ b/src/pages/api-doc.tsx@@ -5,13 +5,16 @@ import fs from "fs";import yaml from "js-yaml";const SwaggerUI = dynamic<{- spec: any;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ spec?: any;}>(import("swagger-ui-react"), { ssr: false });function ApiDoc({ spec }: InferGetStaticPropsType<typeof getStaticProps>) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignmentreturn <SwaggerUI spec={spec} />;}+// eslint-disable-next-line @typescript-eslint/require-awaitexport const getStaticProps: GetStaticProps = async () => {const file = fs.readFileSync("./generated/openapi/openapi.yml", "utf8");const spec = yaml.load(file);diff --git a/src/pages/api/cors.ts b/src/pages/api/cors.tsindex 2db85633ff..92966956f5 100644--- a/src/pages/api/cors.ts+++ b/src/pages/api/cors.ts@@ -4,10 +4,11 @@ import Cors from "cors";export function runMiddleware(req: NextApiRequest,res: NextApiResponse,+ // eslint-disable-next-line @typescript-eslint/ban-typesfn: Function) {return new Promise((resolve, reject) => {- fn(req, res, (result: any) => {+ fn(req, res, (result: unknown) => {if (result instanceof Error) {return reject(result);}diff --git a/src/pages/api/metrics.ts b/src/pages/api/metrics.tsindex e8a8562b48..df7ae1763b 100644--- a/src/pages/api/metrics.ts+++ b/src/pages/api/metrics.ts@@ -24,7 +24,7 @@ export default async function handler(try {const obj = MetricSchema.parse(req.body);- const data: Prisma.MetricCreateInput = {+ const data: Prisma.ScoreCreateInput = {timestamp: new Date(),value: obj.value,name: obj.name,@@ -34,7 +34,8 @@ export default async function handler(}),};- const newObservation = await prisma.metric.create({ data });+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const newObservation = await prisma.score.create({ data });res.status(201).json(newObservation);} catch (error: unknown) {diff --git a/src/pages/demo.tsx b/src/pages/demo.tsxindex bcd5615ef8..4db94ff413 100644--- a/src/pages/demo.tsx+++ b/src/pages/demo.tsx@@ -1,7 +1,7 @@"use client";import * as React from "react";-import { ChevronsUpDown, Plus, X } from "lucide-react";+import { ChevronsUpDown } from "lucide-react";import { Button } from "~/components/ui/button";import {diff --git a/src/pages/llm-calls.tsx b/src/pages/llm-calls.tsxindex 2b1a1d5ed1..35bcc80dfd 100644--- a/src/pages/llm-calls.tsx+++ b/src/pages/llm-calls.tsx@@ -10,6 +10,12 @@ import {import { api } from "~/utils/api";import { useRouter } from "next/router";++interface TraceRowData {+ id: string;+ traceId: string+}+export default function Traces() {const llmCalls = api.llmCalls.all.useQuery(undefined, {refetchInterval: 1000,@@ -22,15 +28,15 @@ export default function Traces() {type: "actions",headerName: "ID",width: 100,- getActions: (params: GridRowParams) => [+ getActions: (params: GridRowParams<TraceRowData>) => [<buttonkey="openLlmCall"className="rounded bg-indigo-50 px-2 py-1 text-xs font-semibold text-indigo-600 shadow-sm hover:bg-indigo-100"onClick={() =>- void router.push(`/llm-calls/${params.row.id as string}`)+ void router.push(`/llm-calls/${params.row.id}`)}>- ...{lastCharacters(params.row.id as string, 7)}+ ...{lastCharacters(params.row.id, 7)}</button>,],},@@ -39,15 +45,15 @@ export default function Traces() {type: "actions",headerName: "Trace",width: 100,- getActions: (params: GridRowParams) => [+ getActions: (params: GridRowParams<TraceRowData>) => [<buttonkey="openTrace"className="rounded bg-indigo-50 px-2 py-1 text-xs font-semibold text-indigo-600 shadow-sm hover:bg-indigo-100"onClick={() =>- void router.push(`/traces/${params.row.traceId as string}`)+ void router.push(`/traces/${params.row.traceId}`)}>- ...{lastCharacters(params.row.traceId as string, 7)}+ ...{lastCharacters(params.row.traceId, 7)}</button>,],},diff --git a/src/pages/llm-calls/[llmCallId].tsx b/src/pages/llm-calls/[llmCallId].tsxindex eed74478d8..2404a67a60 100644--- a/src/pages/llm-calls/[llmCallId].tsx+++ b/src/pages/llm-calls/[llmCallId].tsx@@ -17,12 +17,10 @@ export default function LlmCallPage() {});const obsMetrics =- llmCall.data?.metrics.filter(- (metric) => metric.observationId === llmCall.data.id+ llmCall.data?.scores.filter(+ (score) => score.observationId === llmCall.data.id) ?? [];- const traceMetrics =- llmCall.data?.metrics.filter((metric) => !obsMetrics?.includes(metric)) ??- [];+ const traceScores = llmCall.data?.scores.filter((score) => !obsMetrics?.includes(score)) ??[];return (<>@@ -104,7 +102,7 @@ export default function LlmCallPage() {label: "Metrics (trace)",value: (<DescriptionList- items={traceMetrics.map((metric) => ({+ items={traceScores.map((metric) => ({label: metric.name,value: metric.value,}))}diff --git a/src/pages/metrics.tsx b/src/pages/metrics.tsxindex 848b0fb92f..7634e2bfb6 100644--- a/src/pages/metrics.tsx+++ b/src/pages/metrics.tsx@@ -10,8 +10,17 @@ import {import { api } from "~/utils/api";import { useRouter } from "next/router";+interface RowData {+ id: string;+ traceId: string;+ timestamp: string;+ name: string;+ value: number;+ observationId?: string;+}+export default function MetricsPage() {- const metrics = api.metrics.all.useQuery(undefined, {+ const metrics = api.scores.all.useQuery(undefined, {refetchInterval: 1000,});const router = useRouter();@@ -22,8 +31,8 @@ export default function MetricsPage() {type: "actions",headerName: "ID",width: 100,- getActions: (params: GridRowParams) => [- <div key=".">...{lastCharacters(params.row.id as string, 7)}</div>,+ getActions: (params: GridRowParams<RowData>) => [+ <div key=".">...{lastCharacters(params.row.id, 7)}</div>,],},{@@ -31,15 +40,13 @@ export default function MetricsPage() {type: "actions",headerName: "Trace",width: 100,- getActions: (params: GridRowParams) => [+ getActions: (params: GridRowParams<RowData>) => [<buttonkey="openTrace"className="rounded bg-indigo-50 px-2 py-1 text-xs font-semibold text-indigo-600 shadow-sm hover:bg-indigo-100"- onClick={() =>- void router.push(`/traces/${params.row.traceId as string}`)- }+ onClick={() => void router.push(`/traces/${params.row.traceId}`)}>- ...{lastCharacters(params.row.traceId as string, 7)}+ ...{lastCharacters(params.row.traceId, 7)}</button>,],},diff --git a/src/pages/traces.tsx b/src/pages/traces.tsxindex 09e11dddf1..42b9b1b169 100644--- a/src/pages/traces.tsx+++ b/src/pages/traces.tsx@@ -10,11 +10,10 @@ import {import { api } from "~/utils/api";import { useRouter } from "next/router";-// const rows: GridRowsProp = [-// { id: 1, col1: "Hello", col2: "World" },-// { id: 2, col1: "DataGridPro", col2: "is Awesome" },-// { id: 3, col1: "MUI", col2: "is Amazing" },-// ];+interface TraceRowData {+ id: string;+}+export default function Traces() {const traces = api.traces.all.useQuery(undefined, { refetchInterval: 1000 });@@ -26,13 +25,13 @@ export default function Traces() {type: "actions",headerName: "ID",width: 100,- getActions: (params: GridRowParams) => [+ getActions: (params: GridRowParams<TraceRowData>) => [<buttonkey="openTrace"className="rounded bg-indigo-50 px-2 py-1 text-xs font-semibold text-indigo-600 shadow-sm hover:bg-indigo-100"- onClick={() => void router.push(`/traces/${params.row.id as string}`)}+ onClick={() => void router.push(`/traces/${params.row.id}`)}>- ...{lastCharacters(params.row.id as string, 7)}+ ...{lastCharacters(params.row.id, 7)}</button>,],},diff --git a/src/server/api/root.ts b/src/server/api/root.tsindex 37c40002c1..cb283551c1 100644--- a/src/server/api/root.ts+++ b/src/server/api/root.ts@@ -2,7 +2,7 @@ import { createTRPCRouter } from "~/server/api/trpc";import { exampleRouter } from "~/server/api/routers/example";import { traceRouter } from "./routers/traces";import { llmCallRouter } from "./routers/llmCalls";-import { metricsRouter } from "./routers/metrics";+import { scoresRouter } from "./routers/scores";/*** This is the primary router for your server.@@ -13,7 +13,7 @@ export const appRouter = createTRPCRouter({example: exampleRouter,traces: traceRouter,llmCalls: llmCallRouter,- metrics: metricsRouter,+ scores: scoresRouter,});// export type definition of APIdiff --git a/src/server/api/routers/llmCalls.ts b/src/server/api/routers/llmCalls.tsindex e6f408e808..f66332da70 100644--- a/src/server/api/routers/llmCalls.ts+++ b/src/server/api/routers/llmCalls.ts@@ -18,20 +18,22 @@ export const llmCallRouter = createTRPCRouter({return llmCalls;}),- byId: publicProcedure.input(z.string()).query(async ({ input }) => {- // also works for other observations- const llmCall = (await prisma.observation.findUnique({- where: {- id: input,- },- })) as LlmCall;+ byId: publicProcedure+ .input(z.string())+ .query(async ({ input }) => {+ // also works for other observations+ const llmCall = (await prisma.observation.findUnique({+ where: {+ id: input,+ },+ })) as LlmCall;- const metrics = await prisma.metric.findMany({+ const scores = await prisma.score.findMany({where: {traceId: llmCall.traceId,},});- return { ...llmCall, metrics };- }),+ return { ...llmCall, scores };+ }),});diff --git a/src/server/api/routers/metrics.ts b/src/server/api/routers/scores.tssimilarity index 75%rename from src/server/api/routers/metrics.tsrename to src/server/api/routers/scores.tsindex 617295cc3f..0a0deafce7 100644--- a/src/server/api/routers/metrics.ts+++ b/src/server/api/routers/scores.ts@@ -3,16 +3,16 @@ import { z } from "zod";import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";import { prisma } from "~/server/db";-export const metricsRouter = createTRPCRouter({+export const scoresRouter = createTRPCRouter({all: publicProcedure.query(() =>- prisma.metric.findMany({+ prisma.score.findMany({orderBy: {timestamp: "desc",},})),byId: publicProcedure.input(z.string()).query(({ input }) =>- prisma.metric.findUniqueOrThrow({+ prisma.score.findUniqueOrThrow({where: {id: input,},