🪢 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
Build docker image, CI seeder, improve docker run instructions (#86)
Marc Klingen266fceb5fcf4
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 23da1829c2..345faeb887 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -1,6 +1,13 @@name: CI/CD-on: push+on:+ workflow_dispatch:+ push:+ branches:+ - "main"+ pull_request:+ branches:+ - "main"jobs:ci:@@ -17,8 +24,8 @@ jobs:with:node-version: 18- - name: Start containers- run: docker-compose -f "docker-compose.dev.yml" up -d --build+ # - name: Start containers+ # run: docker-compose -f "docker-compose.dev.yml" up -d --build- name: install dependenciesrun: |@@ -38,6 +45,11 @@ jobs:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgresNEXTAUTH_SECRET: "secret"NEXTAUTH_URL: "http://localhost:3030"+ REGISTRY: ghcr.io+ IMAGE_NAME: ${{ github.repository }}+ permissions:+ packages: write+ contents: readsteps:- name: Setup node@@ -48,10 +60,33 @@ jobs:- name: Checkoutuses: actions/checkout@v3- - name: Build Docker image- run: |- docker build \- --build-arg DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres \- --build-arg NEXTAUTH_SECRET=mysecret \- --build-arg NEXTAUTH_URL=http:localhost:3030 \- -t langfuse .+ - name: Log in to the Container registry+ uses: docker/login-action@v2+ with:+ registry: ${{ env.REGISTRY }}+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - name: Extract metadata (tags, labels) for Docker+ id: meta+ uses: docker/metadata-action@v4+ with:+ images: |+ ${{ env.REGISTRY }}/${{ github.repository }}+ tags: |+ type=ref,event=branch+ type=ref,event=pr+ type=sha+ type=raw,value=latest++ - name: Build and push Docker image+ uses: docker/build-push-action@v2+ with:+ context: .+ push: true+ tags: ${{ steps.meta.outputs.tags }}+ labels: ${{ steps.meta.outputs.labels }}+ build-args: |+ DATABASE_URL=${{ env.DATABASE_URL }}+ NEXTAUTH_SECRET=${{ env.NEXTAUTH_SECRET }}+ NEXTAUTH_URL=${{ env.NEXTAUTH_URL }}diff --git a/Dockerfile b/Dockerfileindex 7917dbd020..aa955e04ec 100644--- a/Dockerfile+++ b/Dockerfile@@ -37,13 +37,13 @@ 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+ENV NEXT_TELEMETRY_DISABLED 1+# Generate prisma clientRUN npx prisma generate-RUN npm run build-# If using npm comment out above and use below instead-# RUN npm run build+# Build the application+RUN npm run build# Production image, copy all the files and run nextFROM base AS runner@@ -55,7 +55,7 @@ WORKDIR /appENV NODE_ENV production# Uncomment the following line in case you want to disable telemetry during runtime.-# ENV NEXT_TELEMETRY_DISABLED 1+ENV NEXT_TELEMETRY_DISABLED 1RUN addgroup --system --gid 1001 nodejsRUN adduser --system --uid 1001 nextjs@@ -74,4 +74,4 @@ EXPOSE 3000ENV PORT 3000-CMD ["node", "server.js"]\ No newline at end of file+CMD ["node", "server.js"]diff --git a/README.md b/README.mdindex a912f8abd5..a9eb265a48 100644--- a/README.md+++ b/README.md@@ -84,6 +84,72 @@ Follow the [quickstart](https://langfuse.com/docs/get-started) with instructions- Detailed reports on latency, cost, quality- Evals+# Run locally++```bash+# Clone repository+git clone [email protected]:langfuse/langfuse.git+cd langfuse++# Run server and db+docker compose up -d++# Apply db migrations+DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres DIRECT_URL=postgresql://postgres:postgres@localhost:5432/postgres npx prisma migrate deploy+```++-> Visit http://localhost:3000++## Update++```bash+# Stop server and db+docker compose down++# Pull latest changes+git pull+docker-compose pull++# Run server and db+docker compose up -d++# Apply db migrations+DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres DIRECT_URL=postgresql://postgres:postgres@localhost:5432/postgres npx prisma migrate deploy+```++# For testing of SDKs++The following runs the server and db in docker-compose, applies migrations and a seeder which initializes a project, user and creates default API keys.++```bash+docker compose up -d+npm i # necessary for seeder+DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres DIRECT_URL=postgresql://postgres:postgres@localhost:5432/postgres npx --yes prisma migrate reset --force --skip-generate+```++# Local development++```+# Install dependencies+npm install++# Run the db+docker-compose -f docker-compose.dev.yml up -d++# create an env file+cp .env.dev.example .env++# Migration+npx prisma migrate dev++# Optional: seed the database+# npx prisma db seed+# npx prisma db seed:examples++# Start the server+npm run dev+```+# Contributing to LangfuseJoin the community [on Discord](https://discord.gg/7NXusRtqYU).diff --git a/docker-compose.yml b/docker-compose.ymlindex 3f92db279b..cbd1c5e531 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -1,24 +1,25 @@version: "3.5"services:- server:- build:- dockerfile: Dockerfile- args:- - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres- - NEXTAUTH_SECRET=mysecret- - NEXTAUTH_URL=http:localhost:3030- command: ["sh", "-c", "npx prisma migrate deploy && node server.js"]+ langfuse-server:+ image: ghcr.io/langfuse/langfuse:latest+ ## Want to build image from source? Uncomment the following lines and comment out the image line above+ # build:+ # dockerfile: Dockerfile+ # args:+ # - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres+ # - NEXTAUTH_SECRET=mysecret+ # - NEXTAUTH_URL=http:localhost:3000depends_on:- dbports:- - "3030:3000"+ - "3000:3000"environment:- - NODE_ENV=development+ - NODE_ENV=production- DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres- DIRECT_URL=postgresql://postgres:postgres@db:5432/postgres- NEXTAUTH_SECRET=mysecret- - NEXTAUTH_URL=http:localhost:3030+ - NEXTAUTH_URL=http:localhost:3000db:image: postgresdiff --git a/package.json b/package.jsonindex bcd3e46df3..2f61bdfdef 100644--- a/package.json+++ b/package.json@@ -13,9 +13,8 @@"start": "next start","test": "jest --runInBand","test:watch": "jest --watch --runInBand",- "migrate:dev": "dotenv -e .env.local -- npx prisma migrate dev",- "migrate:prod": "dotenv -e .env.local -- npx prisma migrate deploy",- "prisma-studio": "dotenv -e .env.local -- npx prisma studio"+ "db:seed": "npx prisma db seed",+ "db:seed:examples": "npx prisma db seed -- --environment examples"},"prisma": {"seed": "ts-node -r tsconfig-paths/register --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"diff --git a/prisma/seed.ts b/prisma/seed.tsindex 6f0a6e66ff..4e12b79b49 100755--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -4,14 +4,29 @@ import {getDisplaySecretKey,} from "@/src/features/publicApi/lib/apiKeys";import { hash } from "bcryptjs";+import { parseArgs } from "node:util";++const options = {+ environment: { type: "string" },+} as const;const prisma = new PrismaClient();-const TRACE_VOLUME = 1000;+const TRACE_VOLUME = 100;async function main() {- const user = await prisma.user.create({- data: {+ const environment = parseArgs({+ options,+ }).values.environment;++ const user = await prisma.user.upsert({+ where: { id: "user-1" },+ update: {+ name: "Demo User",+ email: "Demo User",+ password: await hash("password", 12),+ },+ create: {id: "user-1",name: "Demo User",email: "[email protected]",@@ -19,43 +34,16 @@ async function main() {},});- const project1 = await prisma.project.create({- data: {- id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ const seedProjectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ const project1 = await prisma.project.upsert({+ where: { id: seedProjectId },+ update: {name: "llm-app",- apiKeys: {- create: [- {- note: "seeded key",- hashedSecretKey: await hashSecretKey("sk-lf-1234567890"),- displaySecretKey: getDisplaySecretKey("sk-lf-1234567890"),- publishableKey: "pk-lf-1234567890",- },- ],- },- members: {- create: {- role: "OWNER",- userId: user.id,- },- },},- });-- const project2 = await prisma.project.create({- data: {- id: "239ad00f-562f-411d-af14-831c75ddd875",- name: "demo-app",- apiKeys: {- create: [- {- note: "seeded key",- hashedSecretKey: await hashSecretKey("sk-lf-asdfghjkl"),- displaySecretKey: getDisplaySecretKey("sk-lf-asdfghjkl"),- publishableKey: "pk-lf-asdfghjkl",- },- ],- },+ create: {+ id: seedProjectId,+ name: "llm-app",members: {create: {role: "OWNER",@@ -65,156 +53,205 @@ async function main() {},});- for (let i = 0; i < TRACE_VOLUME; i++) {- // print progress to console with a progress bar that refreshes every 10 iterations- if (i % 10 === 0) {- process.stdout.clearLine(0);- process.stdout.cursorTo(0);- process.stdout.write(`Seeding ${i} of ${TRACE_VOLUME}`);- }- // random date within last 90 days, with a linear bias towards more recent dates- const traceTs = new Date(- Date.now() - Math.floor(Math.random() ** 1.5 * 90 * 24 * 60 * 60 * 1000)- );+ const seedApiKey = {+ id: "seed-api-key",+ secret: process.env.SEED_SECRET_KEY ?? "sk-lf-1234567890",+ public: "pk-lf-1234567890",+ note: "seeded key",+ };- const trace = await prisma.trace.create({+ if (!(await prisma.apiKey.findUnique({ where: { id: seedApiKey.id } }))) {+ await prisma.apiKey.create({data: {- id: `trace-${Math.floor(Math.random() * 1000000000)}`,- timestamp: traceTs,- name: ["generate-outreach", "label-inbound", "draft-response"][- i % 3- ] as string,- metadata: {- user: `user-${i}@langfuse.com`,- },+ note: seedApiKey.note,+ id: seedApiKey.id,+ publishableKey: seedApiKey.public,+ hashedSecretKey: await hashSecretKey(seedApiKey.secret),+ displaySecretKey: getDisplaySecretKey(seedApiKey.secret),project: {connect: {- id: [project1.id, project2.id][i % 2],+ id: project1.id,},},- userId: `user-${i % 10}`,- scores: {- createMany: {- data: [- {- name: "latency",- value: Math.floor(Math.random() * 20),- timestamp: traceTs,- },- {- name: "feedback",- value: Math.floor(Math.random() * 3) - 1,- timestamp: traceTs,- },- ...(Math.random() > 0.7- ? [- {- name: "sentiment",- value: Math.floor(Math.random() * 10) - 5,- timestamp: traceTs,- },- ]- : []),- ],+ },+ });+ }++ // Do not run the following for local docker compose setup+ if (environment === "examples") {+ const project2 = await prisma.project.create({+ data: {+ id: "239ad00f-562f-411d-af14-831c75ddd875",+ name: "demo-app",+ apiKeys: {+ create: [+ {+ note: "seeded key",+ hashedSecretKey: await hashSecretKey("sk-lf-asdfghjkl"),+ displaySecretKey: getDisplaySecretKey("sk-lf-asdfghjkl"),+ publishableKey: "pk-lf-asdfghjkl",+ },+ ],+ },+ members: {+ create: {+ role: "OWNER",+ userId: user.id,},},},});- const existingSpanIds: string[] = [];-- for (let j = 0; j < Math.floor(Math.random() * 10) + 1; j++) {- // add between 1 and 30 ms to trace timestamp- const spanTsStart = new Date(- traceTs.getTime() + Math.floor(Math.random() * 30)- );- // random duration of upto 30ms- const spanTsEnd = new Date(- spanTsStart.getTime() + Math.floor(Math.random() * 30)+ for (let i = 0; i < TRACE_VOLUME; i++) {+ // print progress to console with a progress bar that refreshes every 10 iterations+ if (i % 10 === 0) {+ process.stdout.clearLine(0);+ process.stdout.cursorTo(0);+ process.stdout.write(`Seeding ${i} of ${TRACE_VOLUME}`);+ }+ // random date within last 90 days, with a linear bias towards more recent dates+ const traceTs = new Date(+ Date.now() - Math.floor(Math.random() ** 1.5 * 90 * 24 * 60 * 60 * 1000));- const span = await prisma.observation.create({+ const trace = await prisma.trace.create({data: {- type: "SPAN",- id: `span-${Math.floor(Math.random() * 1000000000)}`,- startTime: spanTsStart,- endTime: spanTsEnd,- name: `span-${i}-${j}`,+ id: `trace-${Math.floor(Math.random() * 1000000000)}`,+ timestamp: traceTs,+ name: ["generate-outreach", "label-inbound", "draft-response"][+ i % 3+ ] as string,metadata: {user: `user-${i}@langfuse.com`,},- Project: { connect: { id: trace.projectId } },- traceId: trace.id,- // if this is the first span or in 50% of cases, add no parent; otherwise randomly select parent from existing spans- ...(existingSpanIds.length === 0 || Math.random() > 0.5- ? {}- : {- parentObservationId:- existingSpanIds[- Math.floor(Math.random() * existingSpanIds.length)- ],- }),+ project: {+ connect: {+ id: [project1.id, project2.id][i % 2],+ },+ },+ userId: `user-${i % 10}`,+ scores: {+ createMany: {+ data: [+ {+ name: "latency",+ value: Math.floor(Math.random() * 20),+ timestamp: traceTs,+ },+ {+ name: "feedback",+ value: Math.floor(Math.random() * 3) - 1,+ timestamp: traceTs,+ },+ ...(Math.random() > 0.7+ ? [+ {+ name: "sentiment",+ value: Math.floor(Math.random() * 10) - 5,+ timestamp: traceTs,+ },+ ]+ : []),+ ],+ },+ },},});- existingSpanIds.push(span.id);+ const existingSpanIds: string[] = [];- for (let k = 0; k < Math.floor(Math.random() * 2) + 1; k++) {- // random start and end times within span- const generationTsStart = new Date(- spanTsStart.getTime() +- Math.floor(- Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())- )+ for (let j = 0; j < Math.floor(Math.random() * 10) + 1; j++) {+ // add between 1 and 30 ms to trace timestamp+ const spanTsStart = new Date(+ traceTs.getTime() + Math.floor(Math.random() * 30));- const generationTsEnd = new Date(- generationTsStart.getTime() +- Math.floor(- Math.random() *- (spanTsEnd.getTime() - generationTsStart.getTime())- )+ // random duration of upto 30ms+ const spanTsEnd = new Date(+ spanTsStart.getTime() + Math.floor(Math.random() * 30));- const promptTokens = Math.floor(Math.random() * 1000) + 300;- const completionTokens = Math.floor(Math.random() * 500) + 100;-- await prisma.observation.create({+ const span = await prisma.observation.create({data: {- type: "GENERATION",- id: `generation-${Math.floor(Math.random() * 1000000000)}`,- startTime: generationTsStart,- endTime: generationTsEnd,- name: `generation-${i}-${j}-${k}`,+ type: "SPAN",+ id: `span-${Math.floor(Math.random() * 1000000000)}`,+ startTime: spanTsStart,+ endTime: spanTsEnd,+ name: `span-${i}-${j}`,+ metadata: {+ user: `user-${i}@langfuse.com`,+ },Project: { connect: { id: trace.projectId } },- input:- Math.random() > 0.5- ? [- {- role: "system",- content: "Be a helpful assistant",- },- {- role: "user",- content: "How can i create a React component?",- },- ]- : {- input: "How can i create a React component?",- retrievedDocuments: [+ traceId: trace.id,+ // if this is the first span or in 50% of cases, add no parent; otherwise randomly select parent from existing spans+ ...(existingSpanIds.length === 0 || Math.random() > 0.5+ ? {}+ : {+ parentObservationId:+ existingSpanIds[+ Math.floor(Math.random() * existingSpanIds.length)+ ],+ }),+ },+ });++ existingSpanIds.push(span.id);++ for (let k = 0; k < Math.floor(Math.random() * 2) + 1; k++) {+ // random start and end times within span+ const generationTsStart = new Date(+ spanTsStart.getTime() ++ Math.floor(+ Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())+ )+ );+ const generationTsEnd = new Date(+ generationTsStart.getTime() ++ Math.floor(+ Math.random() *+ (spanTsEnd.getTime() - generationTsStart.getTime())+ )+ );++ const promptTokens = Math.floor(Math.random() * 1000) + 300;+ const completionTokens = Math.floor(Math.random() * 500) + 100;++ await prisma.observation.create({+ data: {+ type: "GENERATION",+ id: `generation-${Math.floor(Math.random() * 1000000000)}`,+ startTime: generationTsStart,+ endTime: generationTsEnd,+ name: `generation-${i}-${j}-${k}`,+ Project: { connect: { id: trace.projectId } },+ input:+ Math.random() > 0.5+ ? [{- title: "How to create a React component",- url: "https://www.google.com",- description: "A guide to creating React components",+ role: "system",+ content: "Be a helpful assistant",},{- title: "React component creation",- url: "https://www.google.com",- description: "A guide to creating React components",+ role: "user",+ content: "How can i create a React component?",},- ],- },- output: {- complation: `Creating a React component can be done in two ways: as a functional component or as a class component. Let's start with a basic example of both.+ ]+ : {+ input: "How can i create a React component?",+ retrievedDocuments: [+ {+ title: "How to create a React component",+ url: "https://www.google.com",+ description: "A guide to creating React components",+ },+ {+ title: "React component creation",+ url: "https://www.google.com",+ description: "A guide to creating React components",+ },+ ],+ },+ output: {+ complation: `Creating a React component can be done in two ways: as a functional component or as a class component. Let's start with a basic example of both.1. **Functional Component**:@@ -243,51 +280,53 @@ async function main() {With the advent of hooks in React, functional components can do everything that class components can do and hence, the community has been favoring functional components over class components.Remember to import React at the top of your file whenever you're creating a component, because JSX transpiles to 'React.createElement' calls under the hood.`,- },- model: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",- modelParameters: {- temperature:- Math.random() > 0.9 ? undefined : Math.random().toFixed(2),- topP: Math.random() > 0.9 ? undefined : Math.random().toFixed(2),- maxTokens:- Math.random() > 0.9- ? undefined- : Math.floor(Math.random() * 1000),- },- metadata: {- user: `user-${i}@langfuse.com`,- },- promptTokens,- completionTokens,- totalTokens: promptTokens + completionTokens,- parentObservationId: span.id,- traceId: trace.id,- },- });-- for (let l = 0; l < Math.floor(Math.random() * 2); l++) {- // random start time within span- const eventTs = new Date(- spanTsStart.getTime() +- Math.floor(- Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())- )- );-- await prisma.observation.create({- data: {- type: "EVENT",- id: `event-${Math.floor(Math.random() * 1000000000)}`,- startTime: eventTs,- name: `event-${i}-${j}-${k}-${l}`,+ },+ model: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",+ modelParameters: {+ temperature:+ Math.random() > 0.9 ? undefined : Math.random().toFixed(2),+ topP:+ Math.random() > 0.9 ? undefined : Math.random().toFixed(2),+ maxTokens:+ Math.random() > 0.9+ ? undefined+ : Math.floor(Math.random() * 1000),+ },metadata: {user: `user-${i}@langfuse.com`,},+ promptTokens,+ completionTokens,+ totalTokens: promptTokens + completionTokens,parentObservationId: span.id,traceId: trace.id,- Project: { connect: { id: trace.projectId } },},});++ for (let l = 0; l < Math.floor(Math.random() * 2); l++) {+ // random start time within span+ const eventTs = new Date(+ spanTsStart.getTime() ++ Math.floor(+ Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())+ )+ );++ await prisma.observation.create({+ data: {+ type: "EVENT",+ id: `event-${Math.floor(Math.random() * 1000000000)}`,+ startTime: eventTs,+ name: `event-${i}-${j}-${k}-${l}`,+ metadata: {+ user: `user-${i}@langfuse.com`,+ },+ parentObservationId: span.id,+ traceId: trace.id,+ Project: { connect: { id: trace.projectId } },+ },+ });+ }}}}diff --git a/src/env.mjs b/src/env.mjsindex 58807bf808..b1df917d1f 100644--- a/src/env.mjs+++ b/src/env.mjs@@ -13,6 +13,7 @@ export const env = createEnv({process.env.NODE_ENV === "production"? z.string().min(1): z.string().min(1).optional(),+ SEED_SECRET_KEY: z.string().min(1).optional(),NEXTAUTH_URL: z.preprocess(// This makes Vercel deployments not fail if you don't set NEXTAUTH_URL// Since NextAuth.js automatically uses the VERCEL_URL if present.@@ -42,6 +43,7 @@ export const env = createEnv({* middlewares) or client-side so we need to destruct manually.*/runtimeEnv: {+ SEED_SECRET_KEY: process.env.SEED_SECRET_KEY,NEXT_PUBLIC_DEMO_PROJECT_ID: process.env.NEXT_PUBLIC_DEMO_PROJECT_ID,DATABASE_URL: process.env.DATABASE_URL,NODE_ENV: process.env.NODE_ENV,