🪢 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
feat: add posthog to chatCompletion endpoint (#1742)
Hassieb Pakzadb2be82b4362b
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex d99b4c3aa0..27376b3a91 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -4,6 +4,7 @@ import {HumanMessage,SystemMessage,} from "@langchain/core/messages";+import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";import {BytesOutputParser,StringOutputParser,@@ -25,6 +26,7 @@ type LLMCompletionParams = {messages: ChatMessage[];modelParams: ModelParams;functionCall?: LLMFunctionCall;+ callbacks?: BaseCallbackHandler[];};type FetchLLMCompletionParams = LLMCompletionParams & {@@ -34,14 +36,12 @@ type FetchLLMCompletionParams = LLMCompletionParams & {export async function fetchLLMCompletion(params: LLMCompletionParams & {streaming: true;- functionCall: undefined;}): Promise<IterableReadableStream<Uint8Array>>;export async function fetchLLMCompletion(params: LLMCompletionParams & {streaming: false;- functionCall: undefined;}): Promise<string>;@@ -55,7 +55,7 @@ export async function fetchLLMCompletion(export async function fetchLLMCompletion(params: FetchLLMCompletionParams): Promise<string | IterableReadableStream<Uint8Array> | unknown> {- const { messages, modelParams, streaming } = params;+ const { messages, modelParams, streaming, callbacks } = params;const finalMessages = messages.map((message) => {if (message.role === ChatMessageRole.User)return new HumanMessage(message.content);@@ -73,6 +73,7 @@ export async function fetchLLMCompletion(temperature: modelParams.temperature,maxTokens: modelParams.max_tokens,topP: modelParams.top_p,+ callbacks,});} else {chatModel = new ChatOpenAI({@@ -81,6 +82,7 @@ export async function fetchLLMCompletion(temperature: modelParams.temperature,maxTokens: modelParams.max_tokens,topP: modelParams.top_p,+ callbacks,});}diff --git a/web/src/components/layouts/header.tsx b/web/src/components/layouts/header.tsxindex 38f46e445a..b8031dcc9d 100644--- a/web/src/components/layouts/header.tsx+++ b/web/src/components/layouts/header.tsx@@ -5,6 +5,7 @@ import { useSession } from "next-auth/react";import DocPopup from "@/src/components/layouts/doc-popup";import { type Status, StatusBadge } from "./status-badge";import { cn } from "@/src/utils/tailwind";+import { Badge } from "@/src/components/ui/badge";export default function Header({level = "h2",@@ -14,6 +15,7 @@ export default function Header({breadcrumb?: { name: string; href?: string }[];status?: Status;help?: { description: string; href?: string };+ featureBetaURL?: string;actionButtons?: React.ReactNode;level?: "h2" | "h3";}) {@@ -89,7 +91,7 @@ export default function Header({</div><div className="mt-2 flex flex-wrap items-center justify-between gap-2"><div className="flex items-center gap-3 md:gap-5">- <div className="flex min-w-0 flex-row">+ <div className="flex min-w-0 flex-row justify-center align-middle">{level === "h2" ? (<h2 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">{props.title}@@ -106,6 +108,21 @@ export default function Header({size="sm"/>) : null}+ {props.featureBetaURL ? (+ <Link+ href={props.featureBetaURL}+ rel="noopener noreferrer"+ target="_blank"+ className="flex items-center"+ >+ <Badge+ title="Feature is currently in beta. Click to learn more."+ className="ml-2"+ >+ Beta+ </Badge>+ </Link>+ ) : null}</div>{props.status && <StatusBadge type={props.status} />}</div>diff --git a/web/src/components/layouts/routes.ts b/web/src/components/layouts/routes.tsindex 58b16b8bf5..328e079f5c 100644--- a/web/src/components/layouts/routes.ts+++ b/web/src/components/layouts/routes.ts@@ -95,6 +95,8 @@ export const ROUTES: Route[] = [pathname: "/project/[projectId]/playground",icon: TerminalIcon,featureFlag: "playground",+ cloudOnly: true,+ label: "Beta",},{name: "Datasets",diff --git a/web/src/features/playground/server/analytics/posthogCallback.ts b/web/src/features/playground/server/analytics/posthogCallback.tsnew file mode 100644index 0000000000..b8d4acb3f4--- /dev/null+++ b/web/src/features/playground/server/analytics/posthogCallback.ts@@ -0,0 +1,67 @@+import type { ValidatedChatCompletionBody } from "@/src/features/playground/server/validateChatCompletionBody";+import { ServerPosthog } from "@/src/server/services/posthog";+import type { LLMResult } from "@langchain/core/outputs";+import { BaseCallbackHandler } from "@langchain/core/callbacks/base";++import type { ChatMessage, ModelParams } from "@langfuse/shared";++export class PosthogCallbackHandler extends BaseCallbackHandler {+ public name = "PosthogCallbackHandler";+ private messages: ChatMessage[];+ private modelParams: ModelParams;+ private posthog: ServerPosthog;++ constructor(+ public eventPrefix: string,+ public body: ValidatedChatCompletionBody,+ private userId: string,+ ) {+ super();+ this.posthog = new ServerPosthog();+ this.messages = body.messages;+ this.modelParams = body.modelParams;+ }++ async handleLLMEnd(output: LLMResult) {+ const outputString = output.generations[0][0].text;+ const properties = this.getEventProperties(outputString);++ this.captureEvent(properties);+ await this.posthog.flushAsync();+ }++ private getInputLength() {+ return this.messages.reduce(+ (acc, message) => acc + message.content.length,+ 0,+ );+ }++ private getEventProperties(output: string): ChatCompletionEventProperties {+ return {+ outputLength: output.length,+ inputLength: this.getInputLength(),+ modelProvider: this.modelParams.provider,+ modelName: this.modelParams.model,+ };+ }++ private captureEvent(properties: ChatCompletionEventProperties) {+ this.posthog.capture({+ event: this.eventPrefix + "_chat_completion",+ distinctId: this.userId,+ properties,+ });+ }++ public async flushAsync() {+ await this.posthog.flushAsync();+ }+}++type ChatCompletionEventProperties = {+ outputLength: number;+ inputLength: number;+ modelProvider: string;+ modelName: string;+};diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.tsindex a6423fdcb4..5c8850f5c9 100644--- a/web/src/features/playground/server/chatCompletionHandler.ts+++ b/web/src/features/playground/server/chatCompletionHandler.ts@@ -4,19 +4,23 @@ import { type NextRequest, NextResponse } from "next/server";import { fetchLLMCompletion } from "@langfuse/shared";+import { PosthogCallbackHandler } from "./analytics/posthogCallback";import {validateChatCompletionBody,type ValidatedChatCompletionBody,} from "./validateChatCompletionBody";import { getCookieName } from "@/src/server/utils/cookies";+import { env } from "@/src/env.mjs";export default async function chatCompletionHandler(req: NextRequest) {const token = await getToken({req,cookieName: getCookieName("next-auth.session-token"),+ secret: env.NEXTAUTH_SECRET,});- if (!token)+ if (!token || !token.sub)+ // sub is the user idreturn NextResponse.json({ message: "Unauthenticated" }, { status: 401 });if (req.method !== "POST")@@ -47,7 +51,7 @@ export default async function chatCompletionHandler(req: NextRequest) {messages,modelParams,streaming: true,- functionCall: undefined,+ callbacks: [new PosthogCallbackHandler("playground", body, token.sub)],});return new StreamingTextResponse(stream);diff --git a/web/src/features/telemetry/index.ts b/web/src/features/telemetry/index.tsindex 4229d98106..ca85b2e3bf 100644--- a/web/src/features/telemetry/index.ts+++ b/web/src/features/telemetry/index.ts@@ -1,11 +1,8 @@import { VERSION } from "@/src/constants";+import { ServerPosthog } from "@/src/server/services/posthog";import { Prisma, prisma } from "@langfuse/shared/src/db";-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";-// Interval between jobs in millisecondsconst JOB_INTERVAL_MINUTES = Prisma.raw("60");@@ -147,11 +144,7 @@ async function posthogTelemetry({clientId: string;}) {try {- const posthog = new PostHog(POSTHOG_API_KEY, {- host: "https://eu.posthog.com",- });- if (process.env.NODE_ENV === "development") posthog.debug();-+ const posthog = new ServerPosthog();// Count projectsconst totalProjects = await prisma.project.count();diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex 03110816f7..4727427140 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -29,6 +29,7 @@ import "core-js/features/array/to-sorted";// Other CSSimport "react18-json-view/src/style.css";import { DetailPageListsProvider } from "@/src/features/navigate-detail-pages/context";+import { env } from "@/src/env.mjs";const setProjectInPosthog = () => {// project@@ -66,10 +67,7 @@ const MyApp: AppType<{ session: Session | null }> = ({useEffect(() => {// PostHog (cloud.langfuse.com)- if (- process.env.NEXT_PUBLIC_POSTHOG_KEY &&- process.env.NEXT_PUBLIC_POSTHOG_HOST- ) {+ if (env.NEXT_PUBLIC_POSTHOG_KEY && env.NEXT_PUBLIC_POSTHOG_HOST) {const handleRouteChange = () => {setProjectInPosthog();posthog.capture("$pageview");@@ -110,17 +108,14 @@ function UserTracking() {useEffect(() => {if (session.status === "authenticated") {// PostHog- if (- process.env.NEXT_PUBLIC_POSTHOG_KEY &&- process.env.NEXT_PUBLIC_POSTHOG_HOST- )+ if (env.NEXT_PUBLIC_POSTHOG_KEY && env.NEXT_PUBLIC_POSTHOG_HOST)posthog.identify(session.data.user?.id ?? undefined, {- environment: process.env.NODE_ENV,+ environment: env.NODE_ENV,email: session.data.user?.email ?? undefined,name: session.data.user?.name ?? undefined,featureFlags: session.data.user?.featureFlags ?? undefined,projects: session.data.user?.projects ?? undefined,- LANGFUSE_CLOUD_REGION: process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,+ LANGFUSE_CLOUD_REGION: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,});const emailDomain = session.data.user?.email?.split("@")[1];if (emailDomain)@@ -149,10 +144,7 @@ function UserTracking() {});} else {// PostHog- if (- process.env.NEXT_PUBLIC_POSTHOG_KEY &&- process.env.NEXT_PUBLIC_POSTHOG_HOST- ) {+ if (env.NEXT_PUBLIC_POSTHOG_KEY && env.NEXT_PUBLIC_POSTHOG_HOST) {posthog.reset();posthog.resetGroups();}diff --git a/web/src/pages/api/cron/ingestion-metrics.ts b/web/src/pages/api/cron/ingestion-metrics.tsindex a6b1f08b0e..433dbb766b 100644--- a/web/src/pages/api/cron/ingestion-metrics.ts+++ b/web/src/pages/api/cron/ingestion-metrics.ts@@ -1,7 +1,7 @@import { env } from "@/src/env.mjs";+import { ServerPosthog } from "@/src/server/services/posthog";import { prisma, Prisma } from "@langfuse/shared/src/db";import { type NextApiRequest, type NextApiResponse } from "next";-import { PostHog } from "posthog-node";export default async function handler(req: NextApiRequest,@@ -26,10 +26,7 @@ export default async function handler(: "langfuse-cloud-eu";try {- const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY, {- host: "https://eu.posthog.com",- });- if (process.env.NODE_ENV === "development") posthog.debug();+ const posthog = new ServerPosthog();// Time frame is the last time this cron job ran until nowconst startTimeframe =diff --git a/web/src/pages/project/[projectId]/playground.tsx b/web/src/pages/project/[projectId]/playground.tsxindex 97604a895e..fccf85a4eb 100644--- a/web/src/pages/project/[projectId]/playground.tsx+++ b/web/src/pages/project/[projectId]/playground.tsx@@ -15,6 +15,7 @@ export default function PlaygroundPage() {help={{description: "A sandbox to test and iterate your prompts",}}+ featureBetaURL="https://github.com/orgs/langfuse/discussions/1170"/><div className="flex-1 overflow-auto"><PlaygroundProvider>diff --git a/web/src/server/services/posthog.ts b/web/src/server/services/posthog.tsnew file mode 100644index 0000000000..dd28dfe56c--- /dev/null+++ b/web/src/server/services/posthog.ts@@ -0,0 +1,18 @@+import { env } from "@/src/env.mjs";+import { PostHog as OriginalPosthog } from "posthog-node";++// Safe as it is intended to be public+const PUBLIC_POSTHOG_API_KEY =+ env.NEXT_PUBLIC_POSTHOG_KEY ||+ "phc_zkMwFajk8ehObUlMth0D7DtPItFnxETi3lmSvyQDrwB";+const POSTHOG_HOST = env.NEXT_PUBLIC_POSTHOG_HOST || "https://eu.posthog.com";++export class ServerPosthog extends OriginalPosthog {+ constructor() {+ super(PUBLIC_POSTHOG_API_KEY, {+ host: POSTHOG_HOST,+ });++ if (process.env.NODE_ENV === "development") this.debug();+ }+}