🪢 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
Simple telemetry (#130)
Marc Klingen8f43b7c2b510
diff --git a/Dockerfile b/Dockerfileindex 69b0c3ffd3..e87e5d8baa 100644--- a/Dockerfile+++ b/Dockerfile@@ -71,10 +71,15 @@ COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/staticCOPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma+RUN npm install --no-package-lock --no-save cron+COPY --chown=nextjs:nodejs cron.js ./cron.js+COPY --chown=nextjs:nodejs entrypoint.sh ./entrypoint.sh+USER nextjsEXPOSE 3000ENV PORT 3000-CMD ["node", "server.js"]+# CMD ["node", "server.js"]+CMD ["/bin/sh", "entrypoint.sh"]diff --git a/README.md b/README.mdindex 252d58016b..fee40001dd 100644--- a/README.md+++ b/README.md@@ -274,6 +274,15 @@ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres DIRECT_URL=pCheckout GitHub Actions workflows of [Python SDK](https://github.com/langfuse/langfuse-python/blob/main/.github/workflows/ci.yml) and [JS/TS SDK](https://github.com/langfuse/langfuse-js/blob/main/.github/workflows/ci.yml).-### Star History+### Telemetry-[](https://star-history.com/#langfuse/langfuse&Date)+By default, Langfuse automatically reports basic usage statistics to a centralized server (PostHog).++This helps us to:++1. understand how Langfuse is used and improve the most relevant features.+2. track overall usage for internal and external (e.g. fundraising) reporting.++None of the data is shared with third parties and does not include any sensitive information. We want to be super transparent about this and you can find the exact data we collect [here](/src/pages/api/cron/telemetry.ts).++You can opt-out by setting `TELEMETRY_ENABLED=false`.diff --git a/cron.js b/cron.jsnew file mode 100644index 0000000000..590e3f5670--- /dev/null+++ b/cron.js@@ -0,0 +1,11 @@+var CronJob = require('cron').CronJob;++var job = new CronJob(+ '*/5 * * * *', // Every 5 minutes+ function () {+ fetch("http://host.docker.internal:3000/api/cron/telemetry").catch(err => console.log(err));+ },+);++if (process.env.TELEMETRY_ENABLED === undefined || process.env.TELEMETRY_ENABLED === "true")+ job.start()diff --git a/entrypoint.sh b/entrypoint.shnew file mode 100644index 0000000000..b79464abdd--- /dev/null+++ b/entrypoint.sh@@ -0,0 +1,2 @@+node cron.js &+node server.jsdiff --git a/prisma/migrations/20230910164603_cron_add_state/migration.sql b/prisma/migrations/20230910164603_cron_add_state/migration.sqlnew file mode 100644index 0000000000..234421ccff--- /dev/null+++ b/prisma/migrations/20230910164603_cron_add_state/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "cron_jobs" ADD COLUMN "state" TEXT;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex b1951ea2dd..2dbcee2b8b 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -227,6 +227,7 @@ model Pricing {model CronJobs {name String @idlastRun DateTime? @map("last_run")+ state String?@@map("cron_jobs")}diff --git a/src/pages/api/cron/telemetry.ts b/src/pages/api/cron/telemetry.tsnew file mode 100644index 0000000000..e96f373952--- /dev/null+++ b/src/pages/api/cron/telemetry.ts@@ -0,0 +1,92 @@+import { prisma } from "@/src/server/db";+import { type NextApiRequest, type NextApiResponse } from "next";+import { PostHog } from "posthog-node";+import { v4 as uuidv4 } from "uuid";++// Safe as it is intended to be public+const POSTHOG_API_KEY = "phc_zkMwFajk8ehObUlMth0D7DtPItFnxETi3lmSvyQDrwB";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ const posthog = new PostHog(POSTHOG_API_KEY, {+ host: "https://eu.posthog.com",+ });+ if (process.env.NODE_ENV === "development") posthog.debug();++ // Time frame is the last time this cron job ran until now+ const dbCronState = await prisma.cronJobs.findUnique({+ where: { name: "telemetry" },+ });+ const startTimeframe = dbCronState?.lastRun ?? undefined;+ const clientId = dbCronState?.state ?? uuidv4();+ const endTimeframe = new Date(Date.now());++ // Count projects+ const totalProjects = await prisma.project.count();++ // Count traces+ const countTraces = await prisma.trace.count({+ where: {+ timestamp: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count scores+ const countScores = await prisma.score.count({+ where: {+ timestamp: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count observations+ const countObservations = await prisma.observation.count({+ where: {+ startTime: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ posthog.identify({+ distinctId: "docker:" + clientId,+ properties: {+ environment: process.env.NODE_ENV,+ },+ });+ posthog.capture({+ distinctId: "docker:" + clientId,+ event: "telemetry",+ properties: {+ totalProjects: totalProjects,+ traces: countTraces,+ scores: countScores,+ observations: countObservations,+ startTimeframe: startTimeframe?.toISOString(),+ endTimeframe: endTimeframe.toISOString(),+ },+ });++ await posthog.shutdownAsync();++ await prisma.cronJobs.upsert({+ where: { name: "telemetry" },+ update: { lastRun: endTimeframe, state: clientId },+ create: { name: "telemetry", lastRun: endTimeframe, state: clientId },+ });++ return res.status(200).json({ message: "OK" });+ } catch (error) {+ console.error(error);+ return res.status(500).json({ message: "Internal server error" });+ }+}