Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: add frontend posthog events (#1983)

Richard Krümmel7acc8e1f4d10
diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsx
index 50d45692ce..4cd5dd2d5c 100644
--- a/web/src/components/deleteButton.tsx
+++ b/web/src/components/deleteButton.tsx
@@ -7,10 +7,10 @@ import {
} from "@/src/components/ui/popover";
import { Button } from "@/src/components/ui/button";
import { TrashIcon } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { type Scope } from "@/src/features/rbac/constants/roleAccessRights";
import { api } from "@/src/utils/api";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface DeleteButtonProps {
itemId: string;
@@ -33,7 +33,7 @@ export function DeleteButton({
}: DeleteButtonProps) {
const [isDeleted, setIsDeleted] = useState(false);
const router = useRouter();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({ projectId, scope: scope });
const traceMutation = api.traces.deleteMany.useMutation({
@@ -63,6 +63,15 @@ export function DeleteButton({
<Button
variant={isTableAction ? "ghost" : "outline"}
size={isTableAction ? "xs" : "icon"}
+ onClick={() =>
+ type === "trace"
+ ? capture("trace:delete_form_open", {
+ source: isTableAction ? "table-single-row" : "trace detail",
+ })
+ : capture("datasets:delete_form_open", {
+ source: "dataset",
+ })
+ }
>
<TrashIcon className="h-4 w-4" />
</Button>
@@ -84,7 +93,7 @@ export function DeleteButton({
traceIds: [itemId],
projectId,
});
- posthog.capture("trace:delete", {
+ capture("trace:delete", {
source: isTableAction ? "table-single-row" : "trace",
});
}}
@@ -101,7 +110,7 @@ export function DeleteButton({
projectId,
datasetId: itemId,
});
- posthog.capture("dataset:delete", {
+ capture("datasets:delete_dataset_button_click", {
source: isTableAction ? "table-single-row" : "dataset",
});
}}
diff --git a/web/src/components/layouts/doc-popup.tsx b/web/src/components/layouts/doc-popup.tsx
index fcb3d02243..e17be33114 100644
--- a/web/src/components/layouts/doc-popup.tsx
+++ b/web/src/components/layouts/doc-popup.tsx
@@ -3,9 +3,9 @@ import {
HoverCardContent,
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { HelpCircle, Info } from "lucide-react";
import Link from "next/link";
-import { usePostHog } from "posthog-js/react";
export type DocPopupProps = {
description: React.ReactNode;
@@ -26,14 +26,17 @@ export default function DocPopup({
md: "w-6 h-6",
lg: "w-8 h-8",
};
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
return (
<HoverCard
openDelay={200}
onOpenChange={(open) => {
if (open) {
- posthog.capture("help-popup:opened", { href, description });
+ capture("help_popup:opened", {
+ hfref: href,
+ description: description,
+ });
}
}}
>
@@ -44,6 +47,12 @@ export default function DocPopup({
rel="noopener"
target="_blank"
className="inline-block whitespace-nowrap text-gray-500 sm:pl-0"
+ onClick={() => {
+ capture("help_popup:href_clicked", {
+ href: href,
+ description: description,
+ });
+ }}
>
{
{
diff --git a/web/src/components/publish-object-switch.tsx b/web/src/components/publish-object-switch.tsx
index cdbae63eff..dc141ccdd4 100644
--- a/web/src/components/publish-object-switch.tsx
+++ b/web/src/components/publish-object-switch.tsx
@@ -1,8 +1,8 @@
import { Switch } from "@/src/components/ui/switch";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { api } from "@/src/utils/api";
import { Link, LockIcon } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
import { useState } from "react";
export const PublishTraceSwitch = (props: {
@@ -10,7 +10,7 @@ export const PublishTraceSwitch = (props: {
projectId: string;
isPublic: boolean;
}) => {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({
projectId: props.projectId,
scope: "objects:publish",
@@ -30,7 +30,7 @@ export const PublishTraceSwitch = (props: {
traceId: props.traceId,
public: val,
});
- posthog.capture("trace_detail:publish_trace_button_click");
+ capture("trace_detail:publish_button_click");
}}
isLoading={mut.isLoading}
disabled={!hasAccess}
@@ -43,7 +43,7 @@ export const PublishSessionSwitch = (props: {
projectId: string;
isPublic: boolean;
}) => {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({
projectId: props.projectId,
scope: "objects:publish",
@@ -63,7 +63,7 @@ export const PublishSessionSwitch = (props: {
sessionId: props.sessionId,
public: val,
});
- posthog.capture("session_detail:publish_session_button_click");
+ capture("session_detail:publish_button_click");
}}
isLoading={mut.isLoading}
disabled={!hasAccess}
diff --git a/web/src/components/star-toggle.tsx b/web/src/components/star-toggle.tsx
index 9a55b2fcc2..03969488f3 100644
--- a/web/src/components/star-toggle.tsx
+++ b/web/src/components/star-toggle.tsx
@@ -6,6 +6,7 @@ import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { cn } from "@/src/utils/tailwind";
import { type RouterOutput, type RouterInput } from "@/src/utils/types";
import { useState } from "react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function StarToggle({
value,
@@ -53,7 +54,7 @@ export function StarTraceToggle({
}) {
const utils = api.useUtils();
const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });
-
+ const capture = usePostHogClientCapture();
const [isLoading, setIsLoading] = useState(false);
const mutBookmarkTrace = api.traces.bookmark.useMutation({
@@ -109,13 +110,18 @@ export function StarTraceToggle({
size={size}
disabled={!hasAccess}
isLoading={isLoading}
- onClick={(value) =>
- mutBookmarkTrace.mutateAsync({
+ onClick={(value) => {
+ capture("table:bookmark_button_click", {
+ table: "traces",
+ id: traceId,
+ value: value,
+ });
+ return mutBookmarkTrace.mutateAsync({
projectId,
traceId,
bookmarked: value,
- })
- }
+ });
+ }}
/>
);
}
@@ -133,7 +139,7 @@ export function StarTraceDetailsToggle({
}) {
const utils = api.useUtils();
const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });
-
+ const capture = usePostHogClientCapture();
const [isLoading, setIsLoading] = useState(false);
const mutBookmarkTrace = api.traces.bookmark.useMutation({
@@ -180,13 +186,17 @@ export function StarTraceDetailsToggle({
size={size}
disabled={!hasAccess}
isLoading={isLoading}
- onClick={(value) =>
- mutBookmarkTrace.mutateAsync({
+ onClick={(value) => {
+ capture("trace_detail:bookmark_button_click", {
+ id: traceId,
+ value: value,
+ });
+ return mutBookmarkTrace.mutateAsync({
projectId,
traceId,
bookmarked: value,
- })
- }
+ });
+ }}
/>
);
}
@@ -204,6 +214,7 @@ export function StarSessionToggle({
}) {
const utils = api.useUtils();
const hasAccess = useHasAccess({ projectId, scope: "objects:bookmark" });
+ const capture = usePostHogClientCapture();
const mutBookmarkSession = api.sessions.bookmark.useMutation({
onSuccess: () => {
void utils.sessions.invalidate();
@@ -216,13 +227,18 @@ export function StarSessionToggle({
size={size}
isLoading={mutBookmarkSession.isLoading}
disabled={!hasAccess}
- onClick={(value) =>
- mutBookmarkSession.mutateAsync({
+ onClick={(value) => {
+ capture("table:bookmark_button_click", {
+ table: "sessions",
+ id: sessionId,
+ value: value,
+ });
+ return mutBookmarkSession.mutateAsync({
projectId,
sessionId,
bookmarked: value,
- })
- }
+ });
+ }}
/>
);
}
diff --git a/web/src/components/table/data-table-column-visibility-filter.tsx b/web/src/components/table/data-table-column-visibility-filter.tsx
index c54a4c2f80..6ccc508fb2 100644
--- a/web/src/components/table/data-table-column-visibility-filter.tsx
+++ b/web/src/components/table/data-table-column-visibility-filter.tsx
@@ -14,6 +14,7 @@ import {
import { type VisibilityState } from "@tanstack/react-table";
import { ChevronDown, Columns } from "lucide-react";
import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface DataTableColumnVisibilityFilterProps<TData, TValue> {
columns: LangfuseColumnDef<TData, TValue>[];
@@ -27,14 +28,24 @@ export function DataTableColumnVisibilityFilter<TData, TValue>({
setColumnVisibility,
}: DataTableColumnVisibilityFilterProps<TData, TValue>) {
const [isOpen, setIsOpen] = useState(false);
-
+ const capture = usePostHogClientCapture();
const toggleColumn = useCallback(
(columnId: string) => {
- setColumnVisibility((old) => ({
- ...old,
- [columnId]: !old[columnId],
- }));
+ setColumnVisibility((old) => {
+ const newColumnVisibility = {
+ ...old,
+ [columnId]: !old[columnId],
+ };
+ const selectedColumns = Object.keys(newColumnVisibility).filter(
+ (key) => newColumnVisibility[key],
+ );
+ capture("table:column_visibility_changed", {
+ selectedColumns: selectedColumns,
+ });
+ return newColumnVisibility;
+ });
},
+ // eslint-disable-next-line react-hooks/exhaustive-deps
[setColumnVisibility],
);
diff --git a/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx b/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx
index 3d99818a89..bf254b3a27 100644
--- a/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx
+++ b/web/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action.tsx
@@ -9,7 +9,6 @@ import {
import { Button } from "@/src/components/ui/button";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { api } from "@/src/utils/api";
-import { usePostHog } from "posthog-js/react";
import {
Dialog,
@@ -20,6 +19,7 @@ import {
DialogTitle,
} from "@/src/components/ui/dialog";
import { useState } from "react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function TraceTableMultiSelectAction({
selectedTraceIds,
@@ -32,7 +32,7 @@ export function TraceTableMultiSelectAction({
}) {
const utils = api.useUtils();
const [open, setOpen] = useState(false);
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasDeleteAccess = useHasAccess({ projectId, scope: "traces:delete" });
const mutDeleteTraces = api.traces.deleteMany.useMutation({
@@ -55,6 +55,10 @@ export function TraceTableMultiSelectAction({
<DropdownMenuItem
disabled={!hasDeleteAccess}
onClick={() => {
+ capture("trace:delete_form_open", {
+ count: selectedTraceIds.length,
+ source: "table-multi-select",
+ });
setOpen(true);
}}
>
@@ -94,7 +98,7 @@ export function TraceTableMultiSelectAction({
.then(() => {
setOpen(false);
});
- posthog.capture("trace:delete", {
+ capture("trace:delete_form_submit", {
count: selectedTraceIds.length,
source: "table-multi-select",
});
diff --git a/web/src/components/table/data-table-pagination.tsx b/web/src/components/table/data-table-pagination.tsx
index 969c5d484c..97d610f54c 100644
--- a/web/src/components/table/data-table-pagination.tsx
+++ b/web/src/components/table/data-table-pagination.tsx
@@ -14,6 +14,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface DataTablePaginationProps<TData> {
table: Table<TData>;
@@ -24,6 +25,7 @@ export function DataTablePagination<TData>({
table,
paginationOptions = [10, 20, 30, 40, 50],
}: DataTablePaginationProps<TData>) {
+ const capture = usePostHogClientCapture();
return (
<div className="mt-3 flex items-center justify-between overflow-x-auto px-2">
<div className="flex-1 text-sm text-muted-foreground">
@@ -36,6 +38,9 @@ export function DataTablePagination<TData>({
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
+ capture("table:pagination_page_size_select", {
+ pageSize: value,
+ });
table.setPageSize(Number(value));
}}
>
@@ -59,7 +64,12 @@ export function DataTablePagination<TData>({
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
- onClick={() => table.setPageIndex(0)}
+ onClick={() => {
+ table.setPageIndex(0);
+ capture("table:pagination_button_click", {
+ type: "firstPage",
+ });
+ }}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
@@ -68,7 +78,12 @@ export function DataTablePagination<TData>({
<Button
variant="outline"
className="h-8 w-8 p-0"
- onClick={() => table.previousPage()}
+ onClick={() => {
+ table.previousPage();
+ capture("table:pagination_button_click", {
+ type: "previousPage",
+ });
+ }}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
@@ -77,7 +92,12 @@ export function DataTablePagination<TData>({
<Button
variant="outline"
className="h-8 w-8 p-0"
- onClick={() => table.nextPage()}
+ onClick={() => {
+ table.nextPage();
+ capture("table:pagination_button_click", {
+ type: "nextPage",
+ });
+ }}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
@@ -86,7 +106,12 @@ export function DataTablePagination<TData>({
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
- onClick={() => table.setPageIndex(table.getPageCount() - 1)}
+ onClick={() => {
+ table.setPageIndex(table.getPageCount() - 1);
+ capture("table:pagination_button_click", {
+ type: "lastPage",
+ });
+ }}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
diff --git a/web/src/components/table/data-table-row-height-switch.tsx b/web/src/components/table/data-table-row-height-switch.tsx
index ea4c36fb10..261c2b6851 100644
--- a/web/src/components/table/data-table-row-height-switch.tsx
+++ b/web/src/components/table/data-table-row-height-switch.tsx
@@ -1,5 +1,6 @@
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import useLocalStorage from "@/src/components/useLocalStorage";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import {
MdDensityLarge,
MdDensityMedium,
@@ -35,25 +36,33 @@ export const DataTableRowHeightSwitch = ({
}: {
rowHeight: RowHeight;
setRowHeight: (e: RowHeight) => void;
-}) => (
- <Tabs
- //defaultValue={height}
- value={rowHeight}
- onValueChange={(e) => setRowHeight(e as any)}
- key="height"
- >
- <TabsList className="gap-1 border bg-transparent px-2">
- {heightOptions.map(({ id, label, icon }) => (
- <TabsTrigger
- key={id}
- value={id}
- className="px-2 shadow-none data-[state=active]:bg-slate-200 data-[state=active]:ring-border"
- >
- <span role="img" aria-label={`${label} size`}>
- {icon}
- </span>
- </TabsTrigger>
- ))}
- </TabsList>
- </Tabs>
-);
+}) => {
+ const capture = usePostHogClientCapture();
+ return (
+ <Tabs
+ //defaultValue={height}
+ value={rowHeight}
+ onValueChange={(e) => {
+ capture("table:row_height_switch_select", {
+ rowHeight: e,
+ });
+ setRowHeight(e as any);
+ }}
+ key="height"
+ >
+ <TabsList className="gap-1 border bg-transparent px-2">
+ {heightOptions.map(({ id, label, icon }) => (
+ <TabsTrigger
+ key={id}
+ value={id}
+ className="px-2 shadow-none data-[state=active]:bg-slate-200 data-[state=active]:ring-border"
+ >
+ <span role="img" aria-label={`${label} size`}>
+ {icon}
+ </span>
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ );
+};
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index 2973f8959b..c14c11c39b 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -12,6 +12,7 @@ import {
type RowHeight,
} from "@/src/components/table/data-table-row-height-switch";
import { Search } from "lucide-react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface SearchConfig {
placeholder: string;
@@ -47,9 +48,10 @@ export function DataTableToolbar<TData, TValue>({
const [searchString, setSearchString] = useState(
searchConfig?.currentQuery ?? "",
);
+ const capture = usePostHogClientCapture();
return (
- <div className="@container my-2 flex flex-1 flex-wrap items-center gap-2">
+ <div className="my-2 flex flex-1 flex-wrap items-center gap-2 @container">
{searchConfig && (
<div className="flex max-w-md items-center">
<Input
@@ -59,14 +61,18 @@ export function DataTableToolbar<TData, TValue>({
onChange={(event) => setSearchString(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
+ capture("table:search_submit");
searchConfig.updateQuery(searchString);
}
}}
- className="@6xl:w-[250px] h-10 w-[150px] rounded-r-none"
+ className="h-10 w-[150px] rounded-r-none @6xl:w-[250px]"
/>
<Button
variant="outline"
- onClick={() => searchConfig.updateQuery(searchString)}
+ onClick={() => {
+ capture("table:search_submit");
+ searchConfig.updateQuery(searchString);
+ }}
className="rounded-l-none border-l-0 p-3"
>
<Search className="h-4 w-4" />
@@ -80,7 +86,7 @@ export function DataTableToolbar<TData, TValue>({
onChange={setFilterState}
/>
)}
- <div className="@6xl:ml-auto flex flex-row flex-wrap gap-2">
+ <div className="flex flex-row flex-wrap gap-2 @6xl:ml-auto">
{!!columnVisibility && !!setColumnVisibility && (
<DataTableColumnVisibilityFilter
columns={columns}
diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsx
index 73b26a1cbd..ff453a1558 100644
--- a/web/src/components/table/data-table.tsx
+++ b/web/src/components/table/data-table.tsx
@@ -17,6 +17,7 @@ import {
TableRow,
} from "@/src/components/ui/table";
import { type OrderByState } from "@/src/features/orderBy/types";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { cn } from "@/src/utils/tailwind";
import {
flexRender,
@@ -72,6 +73,7 @@ export function DataTable<TData extends object, TValue>({
}: DataTableProps<TData, TValue>) {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const rowheighttw = getRowHeightTailwindClass(rowHeight);
+ const capture = usePostHogClientCapture();
const table = useReactTable({
data: data.data ?? [],
@@ -129,14 +131,26 @@ export function DataTable<TData extends object, TValue>({
if (orderBy?.column === columnDef.id) {
if (orderBy.order === "DESC") {
+ capture("table:column_sorting_header_click", {
+ column: columnDef.id,
+ order: "ASC",
+ });
setOrderBy({
column: columnDef.id,
order: "ASC",
});
} else {
+ capture("table:column_sorting_header_click", {
+ column: columnDef.id,
+ order: "Disabled",
+ });
setOrderBy(null);
}
} else {
+ capture("table:column_sorting_header_click", {
+ column: columnDef.id,
+ order: "DESC",
+ });
setOrderBy({
column: columnDef.id,
order: "DESC",
diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsx
index b72bb58901..8ddc13bc24 100644
--- a/web/src/components/table/use-cases/generations.tsx
+++ b/web/src/components/table/use-cases/generations.tsx
@@ -13,7 +13,6 @@ import {
} from "@/src/components/ui/dropdown-menu";
import { Button } from "@/src/components/ui/button";
import { ChevronDownIcon, Loader } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
import {
NumberParam,
StringParam,
@@ -48,6 +47,7 @@ import type Decimal from "decimal.js";
import { type ScoreSimplified } from "@/src/server/api/routers/generations/getAllQuery";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export type GenerationsTableRow = {
id: string;
@@ -92,7 +92,7 @@ export default function GenerationsTable({
promptVersion,
omittedFilter = [],
}: GenerationsTableProps) {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const [isExporting, setIsExporting] = useState(false);
const [searchQuery, setSearchQuery] = useQueryParam(
"search",
@@ -189,7 +189,7 @@ export default function GenerationsTable({
if (isExporting) return;
setIsExporting(true);
- posthog.capture("generations:export", { file_format: fileFormat });
+ capture("generations:export", { file_format: fileFormat });
if (fileFormat === "OPENAI-JSONL")
alert(
"When exporting in OpenAI-JSONL, only generations that exactly match the `ChatML` format will be exported. For any questions, reach out to support.",
@@ -663,7 +663,7 @@ export default function GenerationsTable({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="ml-auto whitespace-nowrap">
- <span className="@6xl:inline hidden">
+ <span className="hidden @6xl:inline">
{filterState.length > 0 || searchQuery
? "Export selection"
: "Export all"}{" "}
diff --git a/web/src/components/table/use-cases/models.tsx b/web/src/components/table/use-cases/models.tsx
index 249a1ea404..56c16eb437 100644
--- a/web/src/components/table/use-cases/models.tsx
+++ b/web/src/components/table/use-cases/models.tsx
@@ -2,6 +2,7 @@ import { DataTable } from "@/src/components/table/data-table";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { Button } from "@/src/components/ui/button";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { api } from "@/src/utils/api";
import { usdFormatter } from "@/src/utils/numbers";
@@ -47,7 +48,6 @@ export default function ModelTable({ projectId }: { projectId: string }) {
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
});
-
const models = api.models.all.useQuery({
page: paginationState.pageIndex,
limit: paginationState.pageSize,
@@ -294,6 +294,7 @@ const DeleteModelButton = ({
projectId: string;
}) => {
const utils = api.useUtils();
+ const capture = usePostHogClientCapture();
const mut = api.models.delete.useMutation({
onSuccess: () => {
void utils.models.invalidate();
@@ -314,14 +315,20 @@ const DeleteModelButton = ({
size="xs"
variant="ghost"
onClick={() => {
- mut
- .mutateAsync({
- projectId,
- modelId,
- })
- .catch((error) => {
- console.error(error);
- });
+ const confirmDelete = window.confirm(
+ "Are you sure you want to delete this model?",
+ );
+ if (confirmDelete) {
+ capture("models:delete_button_click");
+ mut
+ .mutateAsync({
+ projectId,
+ modelId,
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }
}}
>
<Trash size={14} />
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index 8e5b469c44..59ec51ce15 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -6,6 +6,7 @@ import { useState } from "react";
import { Button } from "@/src/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { Fragment } from "react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const IOPreview: React.FC<{
input?: unknown;
@@ -14,7 +15,7 @@ export const IOPreview: React.FC<{
hideIfNull?: boolean;
}> = ({ isLoading = false, hideIfNull = false, ...props }) => {
const [currentView, setCurrentView] = useState<"pretty" | "json">("pretty");
-
+ const capture = usePostHogClientCapture();
const input = deepParseJson(props.input);
const output = deepParseJson(props.output);
@@ -67,7 +68,10 @@ export const IOPreview: React.FC<{
{isPrettyViewAvailable ? (
<Tabs
value={currentView}
- onValueChange={(v) => setCurrentView(v as "pretty" | "json")}
+ onValueChange={(v) => {
+ setCurrentView(v as "pretty" | "json"),
+ capture("trace_detail:io_mode_switch", { view: v });
+ }}
>
<TabsList>
<TabsTrigger value="pretty">Pretty ✨</TabsTrigger>
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
index 3335f76bd4..f39ddef290 100644
--- a/web/src/components/trace/ObservationTree.tsx
+++ b/web/src/components/trace/ObservationTree.tsx
@@ -9,6 +9,7 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import { MinusCircle, MinusIcon, PlusCircleIcon, PlusIcon } from "lucide-react";
import { Toggle } from "@/src/components/ui/toggle";
import { Button } from "@/src/components/ui/button";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const ObservationTree = (props: {
observations: ObservationReturnType[];
@@ -120,126 +121,138 @@ const ObservationTreeNode = (props: {
setCurrentObservationId: (id: string | undefined) => void;
showMetrics?: boolean;
showScores?: boolean;
-}) => (
- <>
- {props.observations
- .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
- .map((observation) => {
- const collapsed = props.collapsedObservations.includes(observation.id);
-
- return (
- <Fragment key={observation.id}>
- <div className="flex">
- {Array.from({ length: props.indentationLevel }, (_, i) => (
- <div className="mx-2 border-r" key={i} />
- ))}
- <div
- className={cn(
- "group my-0.5 flex flex-1 cursor-pointer flex-col gap-1 rounded-sm p-1",
- props.currentObservationId === observation.id
- ? "bg-gray-100"
- : "hover:bg-gray-50",
- )}
- onClick={() => props.setCurrentObservationId(observation.id)}
- >
- <div className="flex gap-2">
- <ColorCodedObservationType
- observationType={observation.type}
- />
- <span className="flex-1 break-all text-sm">
- {observation.name}
- </span>
- {observation.children.length === 0 ? null : (
- <Toggle
- onClick={(ev) => (
- ev.stopPropagation(),
- props.toggleCollapsedObservation(observation.id)
- )}
- variant="default"
- pressed={collapsed}
- size="xs"
- className="w-7"
- title={
- collapsed ? "Expand children" : "Collapse children"
- }
- >
- {collapsed ? (
- <PlusIcon className="h-4 w-4" />
- ) : (
- <MinusIcon className="h-4 w-4" />
- )}
- </Toggle>
- )}
- </div>
- {props.showMetrics &&
- (observation.promptTokens ||
- observation.completionTokens ||
- observation.totalTokens ||
- observation.endTime) && (
- <div className="flex gap-2">
- {observation.endTime ? (
- <span className="text-xs text-gray-500">
- {formatIntervalSeconds(
- (observation.endTime.getTime() -
- observation.startTime.getTime()) /
- 1000,
- )}
- </span>
- ) : null}
- {observation.promptTokens ||
- observation.completionTokens ||
- observation.totalTokens ? (
- <span className="text-xs text-gray-500">
- {observation.promptTokens} →{" "}
- {observation.completionTokens} (∑{" "}
- {observation.totalTokens})
- </span>
- ) : null}
- </div>
+}) => {
+ const capture = usePostHogClientCapture();
+ return (
+ <>
+ {props.observations
+ .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
+ .map((observation) => {
+ const collapsed = props.collapsedObservations.includes(
+ observation.id,
+ );
+ return (
+ <Fragment key={observation.id}>
+ <div className="flex">
+ {Array.from({ length: props.indentationLevel }, (_, i) => (
+ <div className="mx-2 border-r" key={i} />
+ ))}
+ <div
+ className={cn(
+ "group my-0.5 flex flex-1 cursor-pointer flex-col gap-1 rounded-sm p-1",
+ props.currentObservationId === observation.id
+ ? "bg-gray-100"
+ : "hover:bg-gray-50",
)}
- {observation.level !== "DEFAULT" ? (
- <div className="flex">
- <span
- className={cn(
- "rounded-sm p-0.5 text-xs",
- LevelColors[observation.level].bg,
- LevelColors[observation.level].text,
- )}
- >
- {observation.level}
- </span>
- </div>
- ) : null}
- {props.showScores &&
- props.scores.find((s) => s.observationId === observation.id) ? (
- <div className="flex flex-wrap gap-1">
- <GroupedScoreBadges
- scores={props.scores.filter(
- (s) => s.observationId === observation.id,
- )}
+ onClick={() => props.setCurrentObservationId(observation.id)}
+ >
+ <div className="flex gap-2">
+ <ColorCodedObservationType
+ observationType={observation.type}
/>
+ <span className="flex-1 break-all text-sm">
+ {observation.name}
+ </span>
+ {observation.children.length === 0 ? null : (
+ <Toggle
+ onClick={(ev) => (
+ ev.stopPropagation(),
+ props.toggleCollapsedObservation(observation.id),
+ capture(
+ collapsed
+ ? "trace_detail:observation_tree_expand"
+ : "trace_detail:observation_tree_collapse",
+ { type: "single" },
+ )
+ )}
+ variant="default"
+ pressed={collapsed}
+ size="xs"
+ className="w-7"
+ title={
+ collapsed ? "Expand children" : "Collapse children"
+ }
+ >
+ {collapsed ? (
+ <PlusIcon className="h-4 w-4" />
+ ) : (
+ <MinusIcon className="h-4 w-4" />
+ )}
+ </Toggle>
+ )}
</div>
- ) : null}
+ {props.showMetrics &&
+ (observation.promptTokens ||
+ observation.completionTokens ||
+ observation.totalTokens ||
+ observation.endTime) && (
+ <div className="flex gap-2">
+ {observation.endTime ? (
+ <span className="text-xs text-gray-500">
+ {formatIntervalSeconds(
+ (observation.endTime.getTime() -
+ observation.startTime.getTime()) /
+ 1000,
+ )}
+ </span>
+ ) : null}
+ {observation.promptTokens ||
+ observation.completionTokens ||
+ observation.totalTokens ? (
+ <span className="text-xs text-gray-500">
+ {observation.promptTokens} →{" "}
+ {observation.completionTokens} (∑{" "}
+ {observation.totalTokens})
+ </span>
+ ) : null}
+ </div>
+ )}
+ {observation.level !== "DEFAULT" ? (
+ <div className="flex">
+ <span
+ className={cn(
+ "rounded-sm p-0.5 text-xs",
+ LevelColors[observation.level].bg,
+ LevelColors[observation.level].text,
+ )}
+ >
+ {observation.level}
+ </span>
+ </div>
+ ) : null}
+ {props.showScores &&
+ props.scores.find(
+ (s) => s.observationId === observation.id,
+ ) ? (
+ <div className="flex flex-wrap gap-1">
+ <GroupedScoreBadges
+ scores={props.scores.filter(
+ (s) => s.observationId === observation.id,
+ )}
+ />
+ </div>
+ ) : null}
+ </div>
</div>
- </div>
- {!collapsed && (
- <ObservationTreeNode
- observations={observation.children}
- collapsedObservations={props.collapsedObservations}
- toggleCollapsedObservation={props.toggleCollapsedObservation}
- scores={props.scores}
- indentationLevel={props.indentationLevel + 1}
- currentObservationId={props.currentObservationId}
- setCurrentObservationId={props.setCurrentObservationId}
- showMetrics={props.showMetrics}
- showScores={props.showScores}
- />
- )}
- </Fragment>
- );
- })}
- </>
-);
+ {!collapsed && (
+ <ObservationTreeNode
+ observations={observation.children}
+ collapsedObservations={props.collapsedObservations}
+ toggleCollapsedObservation={props.toggleCollapsedObservation}
+ scores={props.scores}
+ indentationLevel={props.indentationLevel + 1}
+ currentObservationId={props.currentObservationId}
+ setCurrentObservationId={props.setCurrentObservationId}
+ showMetrics={props.showMetrics}
+ showScores={props.showScores}
+ />
+ )}
+ </Fragment>
+ );
+ })}
+ </>
+ );
+};
const ColorCodedObservationType = (props: {
observationType: $Enums.ObservationType;
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 83dc8ad5dd..dbb9349fe0 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -23,6 +23,7 @@ import { usdFormatter } from "@/src/utils/numbers";
import Decimal from "decimal.js";
import { useCallback, useState } from "react";
import { DeleteButton } from "@/src/components/deleteButton";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function Trace(props: {
observations: Array<ObservationReturnType>;
@@ -30,6 +31,7 @@ export function Trace(props: {
scores: Score[];
projectId: string;
}) {
+ const capture = usePostHogClientCapture();
const [currentObservationId, setCurrentObservationId] = useQueryParam(
"observation",
StringParam,
@@ -77,17 +79,19 @@ export function Trace(props: {
.filter((id) => !excludeParentObservations.has(id)),
);
} while (newExcludeParentObservations.size > 0);
-
+ capture("trace_detail:observation_tree_collapse", { type: "all" });
setCollapsedObservations(
props.observations
.map((o) => o.id)
.filter((id) => !excludeParentObservations.has(id)),
);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.observations, currentObservationId]);
const expandAll = useCallback(() => {
+ capture("trace_detail:observation_tree_expand", { type: "all" });
setCollapsedObservations([]);
- }, [setCollapsedObservations]);
+ }, []);
return (
<div className="grid gap-4 md:h-full md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-7">
@@ -115,6 +119,9 @@ export function Trace(props: {
<Toggle
pressed={scoresOnObservationTree}
onPressedChange={(e) => {
+ capture("trace_detail:observation_tree_toggle_scores", {
+ show: e,
+ });
setScoresOnObservationTree(e);
}}
size="sm"
@@ -125,6 +132,9 @@ export function Trace(props: {
<Toggle
pressed={metricsOnObservationTree}
onPressedChange={(e) => {
+ capture("trace_detail:observation_tree_toggle_metrics", {
+ show: e,
+ });
setMetricsOnObservationTree(e);
}}
size="sm"
diff --git a/web/src/ee/features/evals/components/eval-config-detail.tsx b/web/src/ee/features/evals/components/eval-config-detail.tsx
index 3eceb74990..15072fb252 100644
--- a/web/src/ee/features/evals/components/eval-config-detail.tsx
+++ b/web/src/ee/features/evals/components/eval-config-detail.tsx
@@ -21,6 +21,7 @@ import {
import { Label } from "@/src/components/ui/label";
import TableLink from "@/src/components/table/table-link";
import EvalLogTable from "@/src/ee/features/evals/components/eval-log";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const EvalConfigDetail = () => {
const router = useRouter();
@@ -124,6 +125,7 @@ export function DeactivateConfig({
const utils = api.useUtils();
const hasAccess = useHasAccess({ projectId, scope: "evalJob:CUD" });
const [isOpen, setIsOpen] = useState(false);
+ const capture = usePostHogClientCapture();
const mutEvalConfig = api.evals.updateEvalJob.useMutation({
onSuccess: () => {
@@ -141,6 +143,7 @@ export function DeactivateConfig({
evalConfigId: config?.id ?? "",
updatedStatus: "INACTIVE",
});
+ capture("eval_config:delete");
setIsOpen(false);
};
diff --git a/web/src/ee/features/evals/components/eval-config-form.tsx b/web/src/ee/features/evals/components/eval-config-form.tsx
index 0609b0781c..ff36cbd969 100644
--- a/web/src/ee/features/evals/components/eval-config-form.tsx
+++ b/web/src/ee/features/evals/components/eval-config-form.tsx
@@ -1,4 +1,3 @@
-import { usePostHog } from "posthog-js/react";
import { useFieldArray, useForm } from "react-hook-form";
import { Input } from "@/src/components/ui/input";
import { Button } from "@/src/components/ui/button";
@@ -42,6 +41,7 @@ import { Card } from "@/src/components/ui/card";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { Label } from "@/src/components/ui/label";
import DocPopup from "@/src/components/layouts/doc-popup";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const formSchema = z.object({
scoreName: z.string(),
@@ -113,7 +113,7 @@ export const InnerEvalConfigForm = (props: {
onFormSuccess?: () => void;
}) => {
const [formError, setFormError] = useState<string | null>(null);
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -182,7 +182,7 @@ export const InnerEvalConfigForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("evals:new_config_form");
+ capture("eval_config:new_form_submit");
const validatedFilter = z.array(singleFilter).safeParse(values.filter);
diff --git a/web/src/ee/features/evals/components/eval-template-detail.tsx b/web/src/ee/features/evals/components/eval-template-detail.tsx
index e15eb28dd6..afb89aa55f 100644
--- a/web/src/ee/features/evals/components/eval-template-detail.tsx
+++ b/web/src/ee/features/evals/components/eval-template-detail.tsx
@@ -16,6 +16,7 @@ import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { Button } from "@/src/components/ui/button";
import { Pencil } from "lucide-react";
import { useState } from "react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const EvalTemplateDetail = () => {
const router = useRouter();
@@ -92,12 +93,14 @@ export function EvalVersionDropdown(props: {
defaultOption?: EvalTemplate;
onSelect?: (template: EvalTemplate) => void;
}) {
+ const capture = usePostHogClientCapture();
const handleSelect = (value: string) => {
const selectedTemplate = props.options?.find(
(template) => template.id === value,
);
if (selectedTemplate && props.onSelect) {
props.onSelect(selectedTemplate);
+ capture("eval_templates:view_version");
}
};
@@ -133,9 +136,11 @@ export function UpdateTemplate({
setIsEditing: (isEditing: boolean) => void;
}) {
const hasAccess = useHasAccess({ projectId, scope: "evalTemplate:create" });
+ const capture = usePostHogClientCapture();
const handlePromptEdit = () => {
setIsEditing(true);
+ capture("eval_templates:update_form_open");
};
return (
diff --git a/web/src/ee/features/evals/components/template-form.tsx b/web/src/ee/features/evals/components/template-form.tsx
index e3d6253452..e3faa834b3 100644
--- a/web/src/ee/features/evals/components/template-form.tsx
+++ b/web/src/ee/features/evals/components/template-form.tsx
@@ -1,4 +1,3 @@
-import { usePostHog } from "posthog-js/react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
@@ -45,6 +44,7 @@ import {
import { TEMPLATES } from "@/src/ee/features/evals/components/templates";
import { Label } from "@/src/components/ui/label";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const EvalTemplateForm = (props: {
projectId: string;
@@ -186,7 +186,7 @@ export const InnerEvalTemplateForm = (props: {
isEditing?: boolean;
setIsEditing?: (isEditing: boolean) => void;
}) => {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const [formError, setFormError] = useState<string | null>(null);
// updates the model params based on the pre-filled data
@@ -281,7 +281,11 @@ export const InnerEvalTemplateForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("evals:new_template_form");
+ capture(
+ props.isEditing
+ ? "eval_templates:update_form_submit"
+ : "eval_templates:new_form_submit",
+ );
const model = EvalModelNames.safeParse(modelParams.model);
diff --git a/web/src/ee/features/evals/pages/configs.tsx b/web/src/ee/features/evals/pages/configs.tsx
index 0c5d25a724..9da707cda8 100644
--- a/web/src/ee/features/evals/pages/configs.tsx
+++ b/web/src/ee/features/evals/pages/configs.tsx
@@ -5,11 +5,12 @@ import Link from "next/link";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { Lock } from "lucide-react";
import EvalConfigTable from "@/src/ee/features/evals/components/eval-config-table";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export default function ConfigsPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
-
+ const capture = usePostHogClientCapture();
const hasWriteAccess = useHasAccess({
projectId,
scope: "evalJob:CUD",
@@ -25,7 +26,11 @@ export default function ConfigsPage() {
href: "https://langfuse.com/docs/scores/model-based-evals",
}}
actionButtons={
- <Button disabled={!hasWriteAccess} asChild>
+ <Button
+ disabled={!hasWriteAccess}
+ onClick={() => capture("eval_config:new_form_open")}
+ asChild
+ >
<Link
href={
hasWriteAccess ? `/project/${projectId}/evals/configs/new` : "#"
diff --git a/web/src/ee/features/evals/pages/templates.tsx b/web/src/ee/features/evals/pages/templates.tsx
index 48a43177a4..7b4c93ffd8 100644
--- a/web/src/ee/features/evals/pages/templates.tsx
+++ b/web/src/ee/features/evals/pages/templates.tsx
@@ -5,11 +5,12 @@ import Link from "next/link";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { Lock } from "lucide-react";
import EvalsTemplateTable from "@/src/ee/features/evals/components/eval-templates-table";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export default function TemplatesPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
-
+ const capture = usePostHogClientCapture();
const hasWriteAccess = useHasAccess({
projectId,
scope: "evalTemplate:create",
@@ -25,7 +26,11 @@ export default function TemplatesPage() {
href: "https://langfuse.com/docs/scores/model-based-evals",
}}
actionButtons={
- <Button disabled={!hasWriteAccess} asChild>
+ <Button
+ disabled={!hasWriteAccess}
+ onClick={() => capture("eval_templates:new_form_open")}
+ asChild
+ >
<Link
href={
hasWriteAccess
diff --git a/web/src/ee/features/playground/page/context/index.tsx b/web/src/ee/features/playground/page/context/index.tsx
index 0c8115e352..85c26b5a3c 100644
--- a/web/src/ee/features/playground/page/context/index.tsx
+++ b/web/src/ee/features/playground/page/context/index.tsx
@@ -27,6 +27,7 @@ import {
import type { MessagesContext } from "@/src/components/ChatMessages/types";
import type { ModelParamsContext } from "@/src/components/ModelParameters";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type PlaygroundContextType = {
promptVariables: PromptVariable[];
@@ -60,6 +61,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
children,
}) => {
const projectId = useProjectIdFromURL();
+ const capture = usePostHogClientCapture();
const [initialPromptId] = useQueryParam("promptId", StringParam);
const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);
const [output, setOutput] = useState("");
@@ -188,6 +190,12 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
setOutput(response);
}
setOutputJson(getOutputJson(response, finalMessages, modelParams));
+ capture("playground:execute_button_click", {
+ inputLength: finalMessages.length,
+ modelName: modelParams.model,
+ modelProvider: modelParams.provider,
+ outputLength: response.length,
+ });
} catch (err) {
console.error(err);
@@ -196,6 +204,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
} finally {
setIsStreaming(false);
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [messages, modelParams, promptVariables]);
useCommandEnter(!isStreaming, handleSubmit);
diff --git a/web/src/ee/features/playground/server/analytics/posthogCallback.ts b/web/src/ee/features/playground/server/analytics/posthogCallback.ts
index be970bcd43..f3836a1e6b 100644
--- a/web/src/ee/features/playground/server/analytics/posthogCallback.ts
+++ b/web/src/ee/features/playground/server/analytics/posthogCallback.ts
@@ -1,5 +1,5 @@
import type { ValidatedChatCompletionBody } from "@/src/ee/features/playground/server/validateChatCompletionBody";
-import { ServerPosthog } from "@/src/server/services/posthog";
+import { ServerPosthog } from "@/src/features/posthog-analytics/ServerPosthog";
import type { LLMResult } from "@langchain/core/outputs";
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
diff --git a/web/src/features/auth/components/AuthCloudRegionSwitch.tsx b/web/src/features/auth/components/AuthCloudRegionSwitch.tsx
index 3d7569179f..09679d20ab 100644
--- a/web/src/features/auth/components/AuthCloudRegionSwitch.tsx
+++ b/web/src/features/auth/components/AuthCloudRegionSwitch.tsx
@@ -1,7 +1,7 @@
import { env } from "@/src/env.mjs";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { Divider } from "@tremor/react";
-import { usePostHog } from "posthog-js/react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const regions =
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"
@@ -37,7 +37,7 @@ export function CloudRegionSwitch({
}: {
isSignUpPage?: boolean;
}) {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) return null;
@@ -64,8 +64,8 @@ export function CloudRegionSwitch({
key={region.name}
value={region.name}
onClick={() => {
- posthog.capture(
- "cloud_region_switch",
+ capture(
+ "sign_in:cloud_region_switch",
{
region: region.name,
},
diff --git a/web/src/features/dashboard/components/TabsComponent.tsx b/web/src/features/dashboard/components/TabsComponent.tsx
index 269673a0a9..6f275c004e 100644
--- a/web/src/features/dashboard/components/TabsComponent.tsx
+++ b/web/src/features/dashboard/components/TabsComponent.tsx
@@ -1,3 +1,4 @@
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { cn } from "@/src/utils/tailwind";
import { type ReactNode, useState } from "react";
@@ -10,6 +11,7 @@ export type TabComponentProps = {
export const TabComponent = ({ tabs }: TabComponentProps) => {
const [selectedIndex, setSelectedIndex] = useState(0);
+ const capture = usePostHogClientCapture();
return (
<div>
<div className="sm:hidden">
@@ -44,7 +46,12 @@ export const TabComponent = ({ tabs }: TabComponentProps) => {
"cursor-pointer whitespace-nowrap border-b-2 px-1 py-3 text-sm font-medium",
)}
aria-current={index === selectedIndex ? "page" : undefined}
- onClick={() => setSelectedIndex(index)}
+ onClick={() => {
+ setSelectedIndex(index);
+ capture("dashboard:chart_tab_switch", {
+ tabLabel: tab.tabTitle,
+ });
+ }}
>
{tab.tabTitle}
</a>
diff --git a/web/src/features/datasets/components/DatasetActionButton.tsx b/web/src/features/datasets/components/DatasetActionButton.tsx
index 0818fcc749..b8908c2c09 100644
--- a/web/src/features/datasets/components/DatasetActionButton.tsx
+++ b/web/src/features/datasets/components/DatasetActionButton.tsx
@@ -12,6 +12,7 @@ import { DialogTrigger } from "@radix-ui/react-dialog";
import { DatasetForm } from "@/src/features/datasets/components/DatasetForm";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { type Prisma } from "@langfuse/shared";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface BaseDatasetButtonProps {
mode: "create" | "update" | "delete";
@@ -44,6 +45,7 @@ type DatasetActionButtonProps =
| DeleteDatasetButtonProps;
export const DatasetActionButton = (props: DatasetActionButtonProps) => {
+ const capture = usePostHogClientCapture();
const [open, setOpen] = useState(false);
const hasAccess = useHasAccess({
projectId: props.projectId,
@@ -60,13 +62,23 @@ export const DatasetActionButton = (props: DatasetActionButtonProps) => {
size={"icon"}
className={props.className}
disabled={!hasAccess}
+ onClick={() =>
+ capture("datasets:update_form_open", {
+ source: "dataset",
+ })
+ }
>
<Edit className="h-4 w-4" />
</Button>
) : (
<div
className="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
- onClick={() => setOpen(true)}
+ onClick={() => {
+ setOpen(true);
+ capture("datasets:update_form_open", {
+ source: "table-single-row",
+ });
+ }}
>
{hasAccess ? (
<Edit className="mr-2 h-4 w-4" />
@@ -79,13 +91,22 @@ export const DatasetActionButton = (props: DatasetActionButtonProps) => {
) : props.mode === "delete" ? (
<div
className="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
- onClick={() => setOpen(true)}
+ onClick={() => {
+ setOpen(true);
+ capture("datasets:delete_form_open", {
+ source: "table-single-row",
+ });
+ }}
>
<Trash className="mr-2 h-4 w-4" />
Delete
</div>
) : (
- <Button className={props.className} disabled={!hasAccess}>
+ <Button
+ className={props.className}
+ disabled={!hasAccess}
+ onClick={() => capture("datasets:new_form_open")}
+ >
{hasAccess ? (
<PlusIcon className="-ml-0.5 mr-1.5" aria-hidden="true" />
) : (
diff --git a/web/src/features/datasets/components/DatasetForm.tsx b/web/src/features/datasets/components/DatasetForm.tsx
index 24c9f9dbdf..b6ba0c70b5 100644
--- a/web/src/features/datasets/components/DatasetForm.tsx
+++ b/web/src/features/datasets/components/DatasetForm.tsx
@@ -12,10 +12,10 @@ import {
} from "@/src/components/ui/form";
import { api } from "@/src/utils/api";
import { useState } from "react";
-import { usePostHog } from "posthog-js/react";
import { Input } from "@/src/components/ui/input";
import { JsonEditor } from "@/src/components/json-editor";
import { type Prisma } from "@langfuse/shared";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface BaseDatasetFormProps {
mode: "create" | "update" | "delete";
@@ -73,7 +73,7 @@ const formSchema = z.object({
export const DatasetForm = (props: DatasetFormProps) => {
const [formError, setFormError] = useState<string | null>(null);
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues:
@@ -104,7 +104,7 @@ export const DatasetForm = (props: DatasetFormProps) => {
description: values.description !== "" ? values.description.trim() : null,
};
if (props.mode === "create") {
- posthog.capture("datasets:new_dataset_form_submit");
+ capture("datasets:new_form_submit");
createMutation
.mutateAsync({
...trimmedValues,
@@ -120,7 +120,7 @@ export const DatasetForm = (props: DatasetFormProps) => {
console.error(error);
});
} else if (props.mode === "update") {
- posthog.capture("datasets:update_dataset_form_submit");
+ capture("datasets:update_form_submit");
renameMutation
.mutateAsync({
...trimmedValues,
@@ -141,7 +141,7 @@ export const DatasetForm = (props: DatasetFormProps) => {
const handleDelete = () => {
if (props.mode !== "delete") return;
- posthog.capture("datasets:delete_dataset_form_submit");
+ capture("datasets:delete_form_submit");
deleteMutation
.mutateAsync({
projectId: props.projectId,
diff --git a/web/src/features/datasets/components/DatasetItemsTable.tsx b/web/src/features/datasets/components/DatasetItemsTable.tsx
index af19707e81..424f135ce3 100644
--- a/web/src/features/datasets/components/DatasetItemsTable.tsx
+++ b/web/src/features/datasets/components/DatasetItemsTable.tsx
@@ -22,6 +22,7 @@ import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type RowData = {
id: string;
@@ -47,7 +48,7 @@ export function DatasetItemsTable({
}) {
const { setDetailPageList } = useDetailPageLists();
const utils = api.useUtils();
-
+ const capture = usePostHogClientCapture();
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
@@ -208,7 +209,13 @@ export function DatasetItemsTable({
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ capture("dataset_item:archive_toggle", {
+ status:
+ status === DatasetStatus.ARCHIVED
+ ? "unarchived"
+ : "archived",
+ });
mutUpdate.mutate({
projectId: projectId,
datasetId: datasetId,
@@ -217,8 +224,8 @@ export function DatasetItemsTable({
status === DatasetStatus.ARCHIVED
? DatasetStatus.ACTIVE
: DatasetStatus.ARCHIVED,
- })
- }
+ });
+ }}
>
<Archive className="mr-2 h-4 w-4" />
{status === DatasetStatus.ARCHIVED ? "Unarchive" : "Archive"}
diff --git a/web/src/features/datasets/components/NewDatasetItemButton.tsx b/web/src/features/datasets/components/NewDatasetItemButton.tsx
index c5dccb4913..a9c65b5816 100644
--- a/web/src/features/datasets/components/NewDatasetItemButton.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemButton.tsx
@@ -9,6 +9,7 @@ import { useState } from "react";
import { NewDatasetItemForm } from "@/src/features/datasets/components/NewDatasetItemForm";
import { DialogTrigger } from "@radix-ui/react-dialog";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const NewDatasetItemButton = (props: {
projectId: string;
@@ -20,6 +21,7 @@ export const NewDatasetItemButton = (props: {
projectId: props.projectId,
scope: "datasets:CUD",
});
+ const capture = usePostHogClientCapture();
return (
<Dialog open={hasAccess && open} onOpenChange={setOpen}>
<DialogTrigger asChild>
@@ -27,6 +29,7 @@ export const NewDatasetItemButton = (props: {
variant="secondary"
className={props.className}
disabled={!hasAccess}
+ onClick={() => capture("dataset_item:new_form_open")}
>
{hasAccess ? (
<PlusIcon className="-ml-0.5 mr-1.5" aria-hidden="true" />
diff --git a/web/src/features/datasets/components/NewDatasetItemForm.tsx b/web/src/features/datasets/components/NewDatasetItemForm.tsx
index 8a63197ac4..56a4d7f683 100644
--- a/web/src/features/datasets/components/NewDatasetItemForm.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemForm.tsx
@@ -19,10 +19,10 @@ import {
} from "@/src/components/ui/select";
import { api } from "@/src/utils/api";
import { useState } from "react";
-import { usePostHog } from "posthog-js/react";
import { JsonEditor } from "@/src/components/json-editor";
import { type Prisma } from "@langfuse/shared";
import { cn } from "@/src/utils/tailwind";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const formSchema = z.object({
datasetId: z.string().min(1, "Select a dataset"),
@@ -85,7 +85,7 @@ export const NewDatasetItemForm = (props: {
onFormSuccess?: () => void;
}) => {
const [formError, setFormError] = useState<string | null>(null);
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -107,10 +107,13 @@ export const NewDatasetItemForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("datasets:new_dataset_item_form_submit", {
- hasSourceTrace: !!props.traceId,
- hasSourceObservation: !!props.observationId,
- });
+ if (props.traceId) {
+ capture("dataset_item:new_from_trace_form_submit", {
+ object: props.observationId ? "observation" : "trace",
+ });
+ } else {
+ capture("dataset_item:new_form_submit");
+ }
createDatasetItemMutation
.mutateAsync({
...values,
diff --git a/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx b/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
index 0a5a3e37fb..42c1648a91 100644
--- a/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemFromObservationButton.tsx
@@ -21,6 +21,7 @@ import { NewDatasetItemForm } from "@/src/features/datasets/components/NewDatase
import { type Prisma } from "@langfuse/shared";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { useSession } from "next-auth/react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const NewDatasetItemFromTrace = (props: {
projectId: string;
@@ -47,6 +48,7 @@ export const NewDatasetItemFromTrace = (props: {
projectId: props.projectId,
scope: "datasets:CUD",
});
+ const capture = usePostHogClientCapture();
return (
<>
@@ -88,7 +90,12 @@ export const NewDatasetItemFromTrace = (props: {
</div>
) : (
<Button
- onClick={() => setOpen(true)}
+ onClick={() => {
+ setOpen(true);
+ capture("dataset_item:new_from_trace_form_open", {
+ object: props.observationId ? "observation" : "trace",
+ });
+ }}
variant="secondary"
disabled={!hasAccess}
>
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index 17490e9e5e..83e5f55fe2 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -27,6 +27,7 @@ import {
} from "@langfuse/shared";
import { NonEmptyString } from "@/src/utils/zod";
import { cn } from "@/src/utils/tailwind";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
// Has WipFilterState, passes all valid filters to parent onChange
export function PopoverFilterBuilder({
@@ -38,6 +39,7 @@ export function PopoverFilterBuilder({
filterState: FilterState;
onChange: Dispatch<SetStateAction<FilterState>>;
}) {
+ const capture = usePostHogClientCapture();
const [wipFilterState, _setWipFilterState] =
useState<WipFilterState>(filterState);
const addNewFilter = () => {
@@ -75,10 +77,16 @@ export function PopoverFilterBuilder({
<div className="flex items-center">
<Popover
onOpenChange={(open) => {
+ if (open) {
+ capture("table:filter_builder_open");
+ }
// Create empty filter when opening popover
if (open && filterState.length === 0) addNewFilter();
// Discard all wip filters when closing popover
if (!open) {
+ capture("table:filter_builder_close", {
+ filter: filterState,
+ });
setWipFilterState(filterState);
}
}}
@@ -86,14 +94,14 @@ export function PopoverFilterBuilder({
<PopoverTrigger asChild>
<Button variant="outline">
<Filter className="h-4 w-4" />
- <span className="@6xl:ml-2 @6xl:inline hidden">Filter</span>
+ <span className="hidden @6xl:ml-2 @6xl:inline">Filter</span>
{filterState.length > 0 && filterState.length < 3 ? (
<InlineFilterState filterState={filterState} />
) : null}
{filterState.length > 0 && (
<span
className={cn(
- "@6xl:hidden ml-3 rounded-md bg-slate-200 px-2 py-1 text-xs",
+ "ml-3 rounded-md bg-slate-200 px-2 py-1 text-xs @6xl:hidden",
filterState.length > 2 && "@6xl:inline",
)}
>
@@ -136,7 +144,7 @@ export function InlineFilterState({
return (
<span
key={i}
- className="@6xl:block ml-2 hidden whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs"
+ className="ml-2 hidden whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs @6xl:block"
>
{filter.column}
{filter.type === "stringObject" || filter.type === "numberObject"
diff --git a/web/src/features/manual-scoring/components/ManualScoreButton.tsx b/web/src/features/manual-scoring/components/ManualScoreButton.tsx
index c33a51606e..cc0fb0c9ed 100644
--- a/web/src/features/manual-scoring/components/ManualScoreButton.tsx
+++ b/web/src/features/manual-scoring/components/ManualScoreButton.tsx
@@ -26,6 +26,7 @@ import { useForm } from "react-hook-form";
import { Slider } from "@/src/components/ui/slider";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { LockIcon } from "lucide-react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const SCORE_NAME = "manual-score";
@@ -47,6 +48,7 @@ export function ManualScoreButton({
projectId: string;
variant?: "button" | "badge";
}) {
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({
projectId,
scope: "scores:CUD",
@@ -60,6 +62,13 @@ export function ManualScoreButton({
: s.observationId === null),
);
+ // variant === "badge" type is session
+ // if observationId is defined type is observation
+ // else type is trace
+ const type =
+ variant === "badge" ? "session" : observationId ? "observation" : "trace";
+ const source = type === "session" ? "SessionDetail" : "TraceDetail";
+
const utils = api.useUtils();
const onSuccess = async () => {
await Promise.all([
@@ -81,6 +90,10 @@ export function ManualScoreButton({
const handleDelete = async () => {
if (score) {
await mutDeleteScore.mutateAsync(score.id);
+ capture("score:delete", {
+ type: type,
+ source: source,
+ });
onOpenChange(false);
}
};
@@ -101,6 +114,10 @@ export function ManualScoreButton({
form.reset();
setOpen(false);
} else {
+ capture(score ? "score:update_form_open" : "score:create_form_open", {
+ type: type,
+ source: source,
+ });
form.setValue("score", score?.value ?? 0);
form.setValue("comment", score?.comment ?? "");
setOpen(true);
@@ -114,6 +131,10 @@ export function ManualScoreButton({
value: values.score,
comment: values.comment,
});
+ capture("score:update_form_submit", {
+ type: type,
+ source: source,
+ });
} else {
await mutCreateScore.mutateAsync({
name: SCORE_NAME,
@@ -122,6 +143,10 @@ export function ManualScoreButton({
traceId,
observationId,
});
+ capture("score:create_form_submit", {
+ type: type,
+ source: source,
+ });
}
onOpenChange(false);
};
diff --git a/web/src/features/models/components/NewModelForm.tsx b/web/src/features/models/components/NewModelForm.tsx
index bec58e5434..8bb1b8ad8e 100644
--- a/web/src/features/models/components/NewModelForm.tsx
+++ b/web/src/features/models/components/NewModelForm.tsx
@@ -1,4 +1,3 @@
-import { usePostHog } from "posthog-js/react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
@@ -28,6 +27,7 @@ import { AutoComplete } from "@/src/features/prompts/components/auto-complete";
import { api } from "@/src/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { JsonEditor } from "@/src/components/json-editor";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const formSchema = z.object({
modelName: z.string().min(1),
@@ -73,7 +73,7 @@ export const NewModelForm = (props: {
onFormSuccess?: () => void;
}) => {
const [formError, setFormError] = useState<string | null>(null);
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -100,7 +100,7 @@ export const NewModelForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("models:new_model_form_submit");
+ capture("models:new_form_submit");
createModelMutation
.mutateAsync({
projectId: props.projectId,
diff --git a/web/src/features/navigate-detail-pages/DetailPageNav.tsx b/web/src/features/navigate-detail-pages/DetailPageNav.tsx
index f94ed97223..eb5fe42b41 100644
--- a/web/src/features/navigate-detail-pages/DetailPageNav.tsx
+++ b/web/src/features/navigate-detail-pages/DetailPageNav.tsx
@@ -6,9 +6,9 @@ import {
TooltipTrigger,
} from "@/src/components/ui/tooltip";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { ChevronDown, ChevronUp } from "lucide-react";
import { useRouter } from "next/router";
-import { usePostHog } from "posthog-js/react";
import { useEffect } from "react";
export const DetailPageNav = (props: {
@@ -19,8 +19,7 @@ export const DetailPageNav = (props: {
const { detailPagelists } = useDetailPageLists();
const ids = detailPagelists[props.listKey] ?? [];
- const posthog = usePostHog();
-
+ const capture = usePostHogClientCapture();
const router = useRouter();
const currentIndex = ids.findIndex((id) => id === props.currentId);
const previousPageId = currentIndex > 0 ? ids[currentIndex - 1] : undefined;
@@ -61,9 +60,7 @@ export const DetailPageNav = (props: {
disabled={!previousPageId}
onClick={() => {
if (previousPageId) {
- posthog.capture(
- "navigate_detail_pages:button_click_prev_or_next",
- );
+ capture("navigate_detail_pages:button_click_prev_or_next");
void router.push(
props.path(encodeURIComponent(previousPageId)),
);
@@ -89,9 +86,7 @@ export const DetailPageNav = (props: {
disabled={!nextPageId}
onClick={() => {
if (nextPageId) {
- posthog.capture(
- "navigate_detail_pages:button_click_prev_or_next",
- );
+ capture("navigate_detail_pages:button_click_prev_or_next");
void router.push(props.path(encodeURIComponent(nextPageId)));
}
}}
diff --git a/web/src/features/notifications/Notification.tsx b/web/src/features/notifications/Notification.tsx
index 3b9acd2cb6..c2838dbd67 100644
--- a/web/src/features/notifications/Notification.tsx
+++ b/web/src/features/notifications/Notification.tsx
@@ -1,3 +1,4 @@
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { X } from "lucide-react";
export interface TNotification {
@@ -19,29 +20,35 @@ const Notification: React.FC<NotificationProps> = ({
setLastSeenId,
dismissToast,
toast,
-}) => (
- <div className="flex justify-between">
- <div className="flex min-w-[300px] flex-1 flex-col justify-center">
- <div className="m-0 text-sm font-medium leading-tight text-gray-800">
- {notification.message}
- </div>
- {notification.description && (
- <div className="mt-2 flex-1 text-sm leading-tight text-gray-800">
- {notification.description}
+}) => {
+ const capture = usePostHogClientCapture();
+ return (
+ <div className="flex justify-between">
+ <div className="flex min-w-[300px] flex-1 flex-col justify-center">
+ <div className="m-0 text-sm font-medium leading-tight text-gray-800">
+ {notification.message}
</div>
- )}
+ {notification.description && (
+ <div className="mt-2 flex-1 text-sm leading-tight text-gray-800">
+ {notification.description}
+ </div>
+ )}
+ </div>
+ <button
+ className="flex h-6 w-6 cursor-pointer items-start justify-end border-none bg-transparent p-0 text-gray-800 transition-colors duration-200"
+ onClick={() => {
+ capture("notification:dismiss_notification", {
+ notificationId: notification.id,
+ });
+ setLastSeenId(notification.id);
+ dismissToast(toast);
+ }}
+ aria-label="Close"
+ >
+ <X size={14} />
+ </button>
</div>
- <button
- className="flex h-6 w-6 cursor-pointer items-start justify-end border-none bg-transparent p-0 text-gray-800 transition-colors duration-200"
- onClick={() => {
- setLastSeenId(notification.id);
- dismissToast(toast);
- }}
- aria-label="Close"
- >
- <X size={14} />
- </button>
- </div>
-);
+ );
+};
export default Notification;
diff --git a/web/src/features/notifications/checkNotifications.tsx b/web/src/features/notifications/checkNotifications.tsx
index d8ec52889f..94dd338456 100644
--- a/web/src/features/notifications/checkNotifications.tsx
+++ b/web/src/features/notifications/checkNotifications.tsx
@@ -7,6 +7,35 @@ import Notification, {
} from "@/src/features/notifications/Notification";
import { Button } from "@/src/components/ui/button";
import { env } from "@/src/env.mjs";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+
+const ButtonWithPosthog = ({
+ children,
+ className,
+ notificationId,
+ href,
+}: {
+ children: React.ReactNode;
+ className?: string;
+ notificationId: string;
+ href: string;
+}) => {
+ const capture = usePostHogClientCapture();
+ return (
+ <Button
+ size="sm"
+ variant="secondary"
+ className={className}
+ onClick={() => {
+ capture("notification:click_link"),
+ { notificationId: notificationId, href: href };
+ }}
+ asChild
+ >
+ <Link href={href}>{children}</Link>
+ </Button>
+ );
+};
export const NOTIFICATIONS: TNotification[] = [
// {
@@ -15,7 +44,7 @@ export const NOTIFICATIONS: TNotification[] = [
// message: "Langfuse 2.0 is live on ProductHunt",
// },
{
- id: 2,
+ id: 4,
releaseDate: new Date("2024-04-24"),
message: "Langfuse Launch Week #1 is in Full Swing",
description: (
@@ -31,9 +60,13 @@ export const NOTIFICATIONS: TNotification[] = [
<li>LLM Playground</li>
<li>More to come every day until Friday</li>
</ul>
- <Button size="sm" variant="secondary" className="mt-3">
- <Link href="https://langfuse.com/launch">Follow along</Link>
- </Button>
+ <ButtonWithPosthog
+ className="mt-3"
+ notificationId="2"
+ href="https://langfuse.com/launch"
+ >
+ Follow along
+ </ButtonWithPosthog>
</div>
),
},
@@ -60,11 +93,12 @@ export const NOTIFICATIONS: TNotification[] = [
the post for details.
</p>
)}
- <Button size="sm" variant="secondary" className="mt-3">
- <Link href="https://langfuse.com/changelog/2024-01-29-custom-model-prices">
- Changelog post
- </Link>
- </Button>
+ <ButtonWithPosthog
+ notificationId="1"
+ href="https://langfuse.com/changelog/2024-01-29-custom-model-prices"
+ >
+ Changelog post
+ </ButtonWithPosthog>
</div>
),
},
diff --git a/web/src/server/services/posthog.ts b/web/src/features/posthog-analytics/ServerPosthog.ts
similarity index 100%
rename from web/src/server/services/posthog.ts
rename to web/src/features/posthog-analytics/ServerPosthog.ts
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
new file mode 100644
index 0000000000..8e2f38e526
--- /dev/null
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -0,0 +1,124 @@
+import { type CaptureResult, type CaptureOptions } from "posthog-js";
+import { usePostHog } from "posthog-js/react";
+
+// resource:action, only use snake_case
+const events = {
+ table: [
+ "filter_builder_open",
+ "filter_builder_close",
+ "search_submit",
+ "row_height_switch_select",
+ "pagination_button_click",
+ "pagination_page_size_select",
+ "column_visibility_change",
+ "column_sorting_header_click",
+ "bookmark_button_click",
+ "column_visibility_changed",
+ ],
+ trace: ["delete_form_open", "delete", "delete_form_submit"],
+ trace_detail: [
+ "publish_button_click",
+ "bookmark_button_click",
+ "observation_tree_collapse",
+ "observation_tree_expand",
+ "observation_tree_toggle_scores",
+ "observation_tree_toggle_metrics",
+ "io_mode_switch",
+ ],
+ generations: ["export"],
+ score: [
+ "delete",
+ "update_form_open",
+ "create_form_open",
+ "update_form_submit",
+ "create_form_submit",
+ ],
+ models: ["delete_button_click", "new_form_submit", "new_form_open"],
+ prompts: [
+ "new_form_submit",
+ "new_form_open",
+ "update_form_open",
+ "update_form_submit",
+ ],
+ prompt_detail: [
+ "test_in_playground_button_click",
+ "add_label_submit",
+ "apply_labels",
+ "version_delete_open",
+ "version_delete_submit",
+ ],
+ session_detail: ["publish_button_click"],
+ eval_config: ["delete", "new_form_submit", "new_form_open"],
+ eval_templates: [
+ "view_version",
+ "new_form_open",
+ "update_form_open",
+ "new_form_submit",
+ "update_form_submit",
+ ],
+ integrations: ["posthog_form_submitted"],
+ sign_in: ["cloud_region_switch", "button_click"],
+ playground: ["execute_button_click"],
+ dashboard: ["chart_tab_switch", "date_range_changed"],
+ datasets: [
+ "delete_form_open",
+ "delete_dataset_button_click",
+ "update_form_open",
+ "delete_form_open",
+ "new_form_open",
+ "new_form_submit",
+ "update_form_submit",
+ "delete_form_submit",
+ ],
+ projects: ["new_form_submit", "new_form_open"],
+ dataset_item: [
+ "archive_toggle",
+ "new_form_open",
+ "new_form_submit",
+ "new_from_trace_form_submit",
+ "new_from_trace_form_open",
+ ],
+ notification: ["click_link", "dismiss_notification"],
+ tag: [
+ "add_existing_tag",
+ "remove_tag",
+ "modal_open",
+ "create_new_button_click",
+ ],
+ onboarding: ["code_example_tab_switch"],
+ project_settings: [
+ "project_delete",
+ "rename_form_submit",
+ "project_transfer",
+ "api_key_delete",
+ "api_key_create",
+ "llm_api_key_delete",
+ "llm_api_key_create",
+ "send_membership_invitation",
+ "delete_membership_invitation",
+ "delete_membership",
+ "pricing_dialog_opened",
+ ],
+ help_popup: ["opened", "href_clicked"],
+ navigate_detail_pages: ["button_click_prev_or_next"],
+} as const;
+
+// type that represents all possible event names, e.g. "traces:bookmark"
+type EventName = {
+ [Resource in keyof typeof events]: `${Resource}:${(typeof events)[Resource][number]}`;
+}[keyof typeof events];
+
+export const usePostHogClientCapture = () => {
+ const posthog = usePostHog();
+
+ // wrapped posthog.capture function that only allows events that are in the allowlist
+ function capture(
+ eventName: EventName,
+ properties?: Record<string, any> | null,
+ options?: CaptureOptions,
+ ): CaptureResult | void {
+ return posthog.capture(eventName, properties, options);
+ }
+
+ return capture;
+};
diff --git a/web/src/features/projects/components/DeleteProjectButton.tsx b/web/src/features/projects/components/DeleteProjectButton.tsx
index a675c7c891..79a39b46f9 100644
--- a/web/src/features/projects/components/DeleteProjectButton.tsx
+++ b/web/src/features/projects/components/DeleteProjectButton.tsx
@@ -18,18 +18,18 @@ import { Input } from "@/src/components/ui/input";
import { useSession } from "next-auth/react";
import { api } from "@/src/utils/api";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
-import { usePostHog } from "posthog-js/react";
import { useRouter } from "next/router";
import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Header from "@/src/components/layouts/header";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function DeleteProjectButton(props: { projectId: string }) {
const utils = api.useUtils();
const router = useRouter();
const session = useSession();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
//code for dynamic confirmation message
const userInfo = session.data?.user;
@@ -65,12 +65,12 @@ export function DeleteProjectButton(props: { projectId: string }) {
// delete project functionality
const onSubmit = () => {
+ capture("project_settings:project_delete");
deleteProject
.mutateAsync({
projectId: props.projectId,
})
.then(() => {
- posthog.capture("project_settings:project_delete");
void router.push("/");
})
.catch((error) => {
diff --git a/web/src/features/projects/components/NewProjectButton.tsx b/web/src/features/projects/components/NewProjectButton.tsx
index 241fe9b189..ebdbe6e0cd 100644
--- a/web/src/features/projects/components/NewProjectButton.tsx
+++ b/web/src/features/projects/components/NewProjectButton.tsx
@@ -25,8 +25,8 @@ import { cn } from "@/src/utils/tailwind";
import { useState } from "react";
import { useSession } from "next-auth/react";
import { chatRunTrigger } from "@/src/features/support-chat/chat";
-import { usePostHog } from "posthog-js/react";
import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
interface NewProjectButtonProps {
size?: "xs" | "default";
@@ -43,7 +43,7 @@ export function NewProjectButton({ size = "default" }: NewProjectButtonProps) {
});
const utils = api.useUtils();
const router = useRouter();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const createProjectMutation = api.projects.create.useMutation({
onSuccess: (newProject) => {
void updateSession();
@@ -54,7 +54,7 @@ export function NewProjectButton({ size = "default" }: NewProjectButtonProps) {
});
function onSubmit(values: z.infer<typeof projectNameSchema>) {
- posthog.capture("projects:new_project_form_submit");
+ capture("projects:new_form_submit");
createProjectMutation
.mutateAsync(values)
.then(() => {
@@ -68,7 +68,15 @@ export function NewProjectButton({ size = "default" }: NewProjectButtonProps) {
}
return (
- <Dialog open={open} onOpenChange={setOpen}>
+ <Dialog
+ open={open}
+ onOpenChange={(open) => {
+ if (open) {
+ capture("projects:new_form_open");
+ }
+ setOpen(open);
+ }}
+ >
<DialogTrigger asChild>
<Button
size={size}
diff --git a/web/src/features/projects/components/RenameProject.tsx b/web/src/features/projects/components/RenameProject.tsx
index 21b1489e47..1bfa463bc9 100644
--- a/web/src/features/projects/components/RenameProject.tsx
+++ b/web/src/features/projects/components/RenameProject.tsx
@@ -16,8 +16,10 @@ import {
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
import Header from "@/src/components/layouts/header";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export default function RenameProject(props: { projectId: string }) {
+ const capture = usePostHogClientCapture();
const utils = api.useUtils();
const hasAccess = useHasAccess({
projectId: props.projectId,
@@ -43,6 +45,7 @@ export default function RenameProject(props: { projectId: string }) {
});
function onSubmit(values: z.infer<typeof projectNameSchema>) {
+ capture("project_settings:rename_form_submit");
renameProject
.mutateAsync({
projectId: props.projectId,
diff --git a/web/src/features/projects/components/TransferOwnershipButton.tsx b/web/src/features/projects/components/TransferOwnershipButton.tsx
index b7c2b810ba..a4c6cfe019 100644
--- a/web/src/features/projects/components/TransferOwnershipButton.tsx
+++ b/web/src/features/projects/components/TransferOwnershipButton.tsx
@@ -17,13 +17,13 @@ import {
} from "@/src/components/ui/form";
import { Input } from "@/src/components/ui/input";
import { api } from "@/src/utils/api";
-import { usePostHog } from "posthog-js/react";
import { useRouter } from "next/router";
import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useSession } from "next-auth/react";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const formSchema = z.object({
newOwnerEmail: z.string().email(),
@@ -31,7 +31,7 @@ const formSchema = z.object({
export function TransferOwnershipButton(props: { projectId: string }) {
const utils = api.useUtils();
const router = useRouter();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const session = useSession();
const project = session.data?.user?.projects.find(
@@ -63,7 +63,7 @@ export function TransferOwnershipButton(props: { projectId: string }) {
newOwnerEmail: values.newOwnerEmail,
})
.then(() => {
- posthog.capture("project_settings:project_transfer");
+ capture("project_settings:project_transfer");
void router.push("/");
})
.catch((error) => {
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index 84d3233475..4c0bc17f5d 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -1,6 +1,5 @@
import { capitalize } from "lodash";
import router from "next/router";
-import { usePostHog } from "posthog-js/react";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/src/components/ui/button";
@@ -43,6 +42,7 @@ import { ArrowTopRightIcon } from "@radix-ui/react-icons";
import { PromptDescription } from "@/src/features/prompts/components/prompt-description";
import { JsonEditor } from "@/src/components/json-editor";
import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type NewPromptFormProps = {
initialPrompt?: Prompt | null;
@@ -54,7 +54,7 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
const projectId = useProjectIdFromURL();
const [formError, setFormError] = useState<string | null>(null);
const utils = api.useUtils();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
let initialPromptContent: PromptContentType | null;
try {
@@ -108,7 +108,15 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
).data?.name;
function onSubmit(values: NewPromptFormSchemaType) {
- posthog.capture("prompts:new_prompt_form_submit");
+ capture(
+ initialPrompt ? "prompts:update_form_submit" : "prompts:new_form_submit",
+ {
+ type: values.type,
+ active: values.isActive,
+ hasConfig: values.config !== "{}",
+ countVariables: currentExtractedVariables.length,
+ },
+ );
if (!projectId) throw Error("Project ID is not defined.");
diff --git a/web/src/features/prompts/components/SetPromptVersionLabels/AddLabelForm.tsx b/web/src/features/prompts/components/SetPromptVersionLabels/AddLabelForm.tsx
index 563f7321f3..c8fcbd8551 100644
--- a/web/src/features/prompts/components/SetPromptVersionLabels/AddLabelForm.tsx
+++ b/web/src/features/prompts/components/SetPromptVersionLabels/AddLabelForm.tsx
@@ -13,6 +13,7 @@ import { Button } from "@/src/components/ui/button";
import { Input } from "@/src/components/ui/input";
import { zodResolver } from "@hookform/resolvers/zod";
import { PromptLabelSchema } from "@/src/features/prompts/server/utils/validation";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const AddLabelFormSchema = z.object({
newLabel: PromptLabelSchema,
@@ -25,6 +26,8 @@ export const AddLabelForm = (props: {
setSelectedLabels: React.Dispatch<React.SetStateAction<string[]>>;
onAddLabel: () => void;
}) => {
+ const capture = usePostHogClientCapture();
+
const form = useForm<AddLabelFromSchemaType>({
resolver: zodResolver(AddLabelFormSchema),
defaultValues: {
@@ -37,7 +40,7 @@ export const AddLabelForm = (props: {
props.setLabels((prev) => [...prev, newLabel]);
props.setSelectedLabels((prev) => [...new Set([...prev, newLabel])]);
-
+ capture("prompt_detail:add_label_submit");
props.onAddLabel();
form.reset();
};
diff --git a/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx b/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx
index 69957fcf24..5539c50028 100644
--- a/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx
+++ b/web/src/features/prompts/components/SetPromptVersionLabels/index.tsx
@@ -1,7 +1,6 @@
import React, { useEffect, useState, useRef } from "react";
import { FlagIcon, PlusIcon } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
import { Button } from "@/src/components/ui/button";
import {
@@ -22,11 +21,12 @@ import { type Prompt } from "@langfuse/shared";
import { AddLabelForm } from "./AddLabelForm";
import { LabelCommandItem } from "./LabelCommandItem";
import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function SetPromptVersionLabels({ prompt }: { prompt: Prompt }) {
const projectId = useProjectIdFromURL();
const utils = api.useUtils();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });
const [selectedLabels, setSelectedLabels] = useState<string[]>([]);
@@ -78,7 +78,7 @@ export function SetPromptVersionLabels({ prompt }: { prompt: Prompt }) {
labels: selectedLabels,
});
- posthog.capture("prompt:setLabels", { labels: selectedLabels });
+ capture("prompt_detail:apply_labels", { labels: selectedLabels });
setIsOpen(false);
};
diff --git a/web/src/features/prompts/components/delete-prompt-version.tsx b/web/src/features/prompts/components/delete-prompt-version.tsx
index 0cb41e3ee1..11363302e1 100644
--- a/web/src/features/prompts/components/delete-prompt-version.tsx
+++ b/web/src/features/prompts/components/delete-prompt-version.tsx
@@ -10,6 +10,7 @@ import {
} from "@/src/components/ui/popover";
import { useRouter } from "next/router";
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function DeletePromptVersion({
promptVersionId,
@@ -20,6 +21,7 @@ export function DeletePromptVersion({
version: number;
countVersions: number;
}) {
+ const capture = usePostHogClientCapture();
const projectId = useProjectIdFromURL();
const utils = api.useUtils();
const router = useRouter();
@@ -52,7 +54,12 @@ export function DeletePromptVersion({
<Popover
key={promptVersionId}
open={isOpen}
- onOpenChange={() => setIsOpen(!isOpen)}
+ onOpenChange={() => {
+ if (isOpen) {
+ capture("prompt_detail:version_delete_open");
+ }
+ setIsOpen(!isOpen);
+ }}
>
<PopoverTrigger asChild>
<Button variant="outline" type="button" size="icon">
@@ -79,6 +86,7 @@ export function DeletePromptVersion({
return;
}
+ capture("prompt_detail:version_delete_submit");
void mutDeletePromptVersion.mutateAsync({
promptVersionId,
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index dedda9168f..df285035ef 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -31,9 +31,11 @@ import {
AccordionItem,
AccordionTrigger,
} from "@/src/components/ui/accordion";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const PromptDetail = () => {
const projectId = useProjectIdFromURL();
+ const capture = usePostHogClientCapture();
const promptName = decodeURIComponent(useRouter().query.promptName as string);
const [currentPromptVersion, setCurrentPromptVersion] = useQueryParam(
"version",
@@ -109,25 +111,34 @@ export const PromptDetail = () => {
<>
<SetPromptVersionLabels prompt={prompt} />
- <Link
- href={`/project/${projectId}/playground?promptId=${encodeURIComponent(prompt.id)}`}
+ <Button
+ variant="outline"
+ title="Test in prompt playground"
+ size="icon"
+ onClick={() =>
+ capture("prompt_detail:test_in_playground_button_click")
+ }
+ asChild
>
- <Button
- variant="outline"
- title="Test in prompt playground"
- size="icon"
+ <Link
+ href={`/project/${projectId}/playground?promptId=${encodeURIComponent(prompt.id)}`}
>
<Terminal className="h-5 w-5" />
- </Button>
- </Link>
+ </Link>
+ </Button>
- <Link
- href={`/project/${projectId}/prompts/new?promptId=${encodeURIComponent(prompt.id)}`}
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => capture("prompts:update_form_open")}
+ asChild
>
- <Button variant="outline" size="icon">
+ <Link
+ href={`/project/${projectId}/prompts/new?promptId=${encodeURIComponent(prompt.id)}`}
+ >
<Pencil className="h-5 w-5" />
- </Button>
- </Link>
+ </Link>
+ </Button>
<DeletePromptVersion
promptVersionId={prompt.id}
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 898134dfc4..964fd02a0a 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -19,6 +19,7 @@ import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { promptsTableColsWithOptions } from "@/src/server/api/definitions/promptsTable";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import { createColumnHelper } from "@tanstack/react-table";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type PromptTableRow = {
name: string;
@@ -75,7 +76,7 @@ export function PromptTable() {
);
const filterOptionTags = promptFilterOptions.data?.tags ?? [];
const allTags = filterOptionTags.map((t) => t.value);
-
+ const capture = usePostHogClientCapture();
const totalCount = prompts.data?.totalCount ?? 0;
useEffect(() => {
@@ -209,7 +210,10 @@ export function PromptTable() {
<Button
variant="secondary"
disabled={!hasCUDAccess}
- aria-label="Promote Prompt to Production"
+ aria-label="Create New Prompt"
+ onClick={() => {
+ capture("prompts:new_form_open");
+ }}
>
{hasCUDAccess ? (
<PlusIcon className="-ml-0.5 mr-1.5" aria-hidden="true" />
diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsx
index e79042b113..dd8957b67d 100644
--- a/web/src/features/public-api/components/ApiKeyList.tsx
+++ b/web/src/features/public-api/components/ApiKeyList.tsx
@@ -18,12 +18,12 @@ import {
TableHeader,
TableRow,
} from "@/src/components/ui/table";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { CreateApiKeyButton } from "@/src/features/public-api/components/CreateApiKeyButton";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { api } from "@/src/utils/api";
import { DialogDescription } from "@radix-ui/react-dialog";
import { TrashIcon } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
import { useState } from "react";
export function ApiKeyList(props: { projectId: string }) {
@@ -97,7 +97,7 @@ export function ApiKeyList(props: { projectId: string }) {
// show dialog to let user confirm that this is a destructive action
function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({
projectId: props.projectId,
scope: "apiKeys:delete",
@@ -136,7 +136,7 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
id: props.apiKeyId,
})
.then(() => {
- posthog.capture("project_settings:api_key_delete");
+ capture("project_settings:api_key_delete");
setOpen(false);
})
.catch((error) => {
diff --git a/web/src/features/public-api/components/CreateApiKeyButton.tsx b/web/src/features/public-api/components/CreateApiKeyButton.tsx
index ee52ad1225..b974c4dc8b 100644
--- a/web/src/features/public-api/components/CreateApiKeyButton.tsx
+++ b/web/src/features/public-api/components/CreateApiKeyButton.tsx
@@ -10,12 +10,12 @@ import {
} from "@/src/components/ui/dialog";
import { CodeView } from "@/src/components/ui/CodeJsonViewer";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
-import { usePostHog } from "posthog-js/react";
import { QuickstartExamples } from "@/src/features/public-api/components/QuickstartExamples";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function CreateApiKeyButton(props: { projectId: string }) {
const utils = api.useUtils();
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({
projectId: props.projectId,
scope: "apiKeys:create",
@@ -47,7 +47,7 @@ export function CreateApiKeyButton(props: { projectId: string }) {
publicKey,
});
setOpen(true);
- posthog.capture("project_settings:api_key_create");
+ capture("project_settings:api_key_create");
})
.catch((error) => {
console.error(error);
diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsx
index fcc383db3f..7ac90e8d04 100644
--- a/web/src/features/public-api/components/LLMApiKeyList.tsx
+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx
@@ -34,6 +34,7 @@ import {
TableHeader,
TableRow,
} from "@/src/components/ui/table";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
@@ -42,7 +43,6 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { ModelProvider, evalLLMModels } from "@langfuse/shared";
import { DialogDescription } from "@radix-ui/react-dialog";
import { PlusIcon, TrashIcon } from "lucide-react";
-import { usePostHog } from "posthog-js/react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
@@ -112,7 +112,7 @@ export function LlmApiKeyList(props: { projectId: string }) {
// show dialog to let user confirm that this is a destructive action
function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const hasAccess = useHasAccess({
projectId: props.projectId,
scope: "llmApiKeys:delete",
@@ -151,7 +151,7 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
id: props.apiKeyId,
})
.then(() => {
- posthog.capture("project_settings:llm_api_key_delete");
+ capture("project_settings:llm_api_key_delete");
setOpen(false);
})
.catch((error) => {
@@ -180,7 +180,7 @@ export function CreateLlmApiKeyComponent(props: {
projectId: string;
existingApiKeys: RouterOutput["llmApiKey"]["all"]["data"];
}) {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const [open, setOpen] = useState(false);
const hasAccess = useHasAccess({
projectId: props.projectId,
@@ -212,7 +212,9 @@ export function CreateLlmApiKeyComponent(props: {
});
return;
}
- posthog.capture("project_settings:llm_api_key_create");
+ capture("project_settings:llm_api_key_create", {
+ provider: values.provider,
+ });
return mutCreateLlmApiKey
.mutateAsync({
diff --git a/web/src/features/public-api/components/QuickstartExamples.tsx b/web/src/features/public-api/components/QuickstartExamples.tsx
index 72d5568586..de97cdd14d 100644
--- a/web/src/features/public-api/components/QuickstartExamples.tsx
+++ b/web/src/features/public-api/components/QuickstartExamples.tsx
@@ -5,6 +5,7 @@ import {
TabsContent,
TabsTrigger,
} from "@/src/components/ui/tabs";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const QuickstartExamples = ({
secretKey,
@@ -14,205 +15,223 @@ export const QuickstartExamples = ({
secretKey: string;
publicKey: string;
host: string;
-}) => (
- <Tabs defaultValue="python" className="relative max-w-full">
- <div className="overflow-x-scroll">
- <TabsList>
- <TabsTrigger value="python">Python</TabsTrigger>
- <TabsTrigger value="js">JS/TS</TabsTrigger>
- <TabsTrigger value="openai">OpenAI</TabsTrigger>
- <TabsTrigger value="langchain">Langchain</TabsTrigger>
- <TabsTrigger value="langchain-js">Langchain JS</TabsTrigger>
- <TabsTrigger value="llamaindex">LlamaIndex</TabsTrigger>
- <TabsTrigger value="other">Other</TabsTrigger>
- </TabsList>
- </div>
- <TabsContent value="python">
- <CodeView content="pip install langfuse" className="mb-2 bg-blue-50" />
- <CodeView
- className="bg-blue-50"
- content={`from langfuse import Langfuse\n\nlangfuse = Langfuse(\n secret_key="${secretKey}",\n public_key="${publicKey}",\n host="${host}"\n)`}
- />
- <p className="mt-3 text-xs text-gray-600">
- See{" "}
- <a
- href="https://langfuse.com/docs/get-started"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- Quickstart
- </a>{" "}
- and{" "}
- <a
- href="https://langfuse.com/docs/sdk/python"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- Python docs
- </a>{" "}
- for more details and an end-to-end example.
- </p>
- </TabsContent>
- <TabsContent value="js">
- <CodeView content="npm install langfuse" className="mb-2 bg-blue-50" />
- <CodeView
- className="bg-blue-50"
- content={`import { Langfuse } from "langfuse";\n\nconst langfuse = new Langfuse({\n secretKey: "${secretKey}",\n publicKey: "${publicKey}",\n baseUrl: "${host}"\n});`}
- />
- <p className="mt-3 text-xs text-gray-600">
- See{" "}
- <a
- href="https://langfuse.com/docs/get-started"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- Quickstart
- </a>{" "}
- and{" "}
- <a
- href="https://langfuse.com/docs/sdk/typescript"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- JS/TS docs
- </a>{" "}
- for more details and an end-to-end example.
- </p>
- </TabsContent>
- <TabsContent value="openai">
- <p className="mt-2 text-xs text-gray-600">
- The integration is a drop-in replacement for the OpenAI Python SDK. By
- changing the import, Langfuse will capture all LLM calls and send them
- to Langfuse asynchronously.
- </p>
- <CodeView content="pip install langfuse" className="my-2 bg-blue-50" />
- <CodeView
- title=".env"
- content={`LANGFUSE_SECRET_KEY=${secretKey}\nLANGFUSE_PUBLIC_KEY=${publicKey}\nLANGFUSE_HOST="${host}"`}
- className="my-2 bg-blue-50"
- />
- <CodeView
- content={`# remove: import openai\n\nfrom langfuse.openai import openai`}
- className="my-2 bg-blue-50"
- />
- <p className="mt-2 text-xs text-gray-600">
- Use the OpenAI SDK as you would normally. See the{" "}
- <a
- href="https://langfuse.com/docs/integrations/openai"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- OpenAI Integration docs
- </a>{" "}
- for more details and an end-to-end example.
- </p>
- </TabsContent>
- <TabsContent value="langchain">
- <p className="mt-2 text-xs text-gray-600">
- The integration uses the Langchain callback system to automatically
- capture detailed traces of your Langchain executions.
- </p>
- <CodeView content="pip install langfuse" className="my-2 bg-blue-50" />
- <CodeView
- content={LANGCHAIN_PYTHON_CODE({ publicKey, secretKey, host })}
- className="my-2 bg-blue-50"
- />
- <p className="mt-2 text-xs text-gray-600">
- See the{" "}
- <a
- href="https://langfuse.com/docs/integrations/langchain/python"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- Langchain Integration docs
- </a>{" "}
- for more details and an end-to-end example.
- </p>
- </TabsContent>
- <TabsContent value="langchain-js">
- <p className="mt-2 text-xs text-gray-600">
- The integration uses the Langchain callback system to automatically
- capture detailed traces of your Langchain executions.
- </p>
- <CodeView
- content="npm install langfuse-langchain"
- className="my-2 bg-blue-50"
- />
- <CodeView
- content={LANGCHAIN_JS_CODE({ publicKey, secretKey, host })}
- className="my-2 bg-blue-50"
- />
- <p className="mt-2 text-xs text-gray-600">
- See the{" "}
- <a
- href="https://langfuse.com/docs/integrations/langchain/typescript"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- Langchain Integration docs
- </a>{" "}
- for more details and an end-to-end example.
- </p>
- </TabsContent>
- <TabsContent value="llamaindex">
- <p className="mt-2 text-xs text-gray-600">
- The integration uses the LlamaIndex callback system to automatically
- capture detailed traces of your LlamaIndex executions.
- </p>
- <CodeView
- content="pip install langfuse llama-index"
- className="my-2 bg-blue-50"
- />
- <CodeView
- content={LLAMA_INDEX_CODE({ publicKey, secretKey, host })}
- className="my-2 bg-blue-50"
- />
- <p className="mt-2 text-xs text-gray-600">
- See the{" "}
- <a
- href="https://langfuse.com/docs/integrations/llama-index"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- LlamaIndex Integration docs
- </a>{" "}
- for more details and an end-to-end example.
- </p>
- </TabsContent>
- <TabsContent value="other">
- <p className="mt-2 text-xs text-gray-600">
- Use the{" "}
- <a
- href="https://api.reference.langfuse.com/"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- API
- </a>{" "}
- or one of the{" "}
- <a
- href="https://langfuse.com/docs/integrations"
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- native integrations
- </a>{" "}
- (e.g. LiteLLM, Flowise, and Langflow) to integrate with Langfuse.
- </p>
- </TabsContent>
- </Tabs>
-);
+}) => {
+ const capture = usePostHogClientCapture();
+ const tabs = [
+ { value: "python", label: "Python" },
+ { value: "js", label: "JS/TS" },
+ { value: "openai", label: "OpenAI" },
+ { value: "langchain", label: "Langchain" },
+ { value: "langchain-js", label: "Langchain JS" },
+ { value: "llamaindex", label: "LlamaIndex" },
+ { value: "other", label: "Other" },
+ ];
+ return (
+ <Tabs defaultValue="python" className="relative max-w-full">
+ <div className="overflow-x-scroll">
+ <TabsList>
+ {tabs.map((tab) => (
+ <TabsTrigger
+ key={tab.value}
+ value={tab.value}
+ onClick={() =>
+ capture("onboarding:code_example_tab_switch", {
+ tabLabel: tab.value,
+ })
+ }
+ >
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </div>
+ <TabsContent value="python">
+ <CodeView content="pip install langfuse" className="mb-2 bg-blue-50" />
+ <CodeView
+ className="bg-blue-50"
+ content={`from langfuse import Langfuse\n\nlangfuse = Langfuse(\n secret_key="${secretKey}",\n public_key="${publicKey}",\n host="${host}"\n)`}
+ />
+ <p className="mt-3 text-xs text-gray-600">
+ See{" "}
+ <a
+ href="https://langfuse.com/docs/get-started"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Quickstart
+ </a>{" "}
+ and{" "}
+ <a
+ href="https://langfuse.com/docs/sdk/python"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Python docs
+ </a>{" "}
+ for more details and an end-to-end example.
+ </p>
+ </TabsContent>
+ <TabsContent value="js">
+ <CodeView content="npm install langfuse" className="mb-2 bg-blue-50" />
+ <CodeView
+ className="bg-blue-50"
+ content={`import { Langfuse } from "langfuse";\n\nconst langfuse = new Langfuse({\n secretKey: "${secretKey}",\n publicKey: "${publicKey}",\n baseUrl: "${host}"\n});`}
+ />
+ <p className="mt-3 text-xs text-gray-600">
+ See{" "}
+ <a
+ href="https://langfuse.com/docs/get-started"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Quickstart
+ </a>{" "}
+ and{" "}
+ <a
+ href="https://langfuse.com/docs/sdk/typescript"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ JS/TS docs
+ </a>{" "}
+ for more details and an end-to-end example.
+ </p>
+ </TabsContent>
+ <TabsContent value="openai">
+ <p className="mt-2 text-xs text-gray-600">
+ The integration is a drop-in replacement for the OpenAI Python SDK. By
+ changing the import, Langfuse will capture all LLM calls and send them
+ to Langfuse asynchronously.
+ </p>
+ <CodeView content="pip install langfuse" className="my-2 bg-blue-50" />
+ <CodeView
+ title=".env"
+ content={`LANGFUSE_SECRET_KEY=${secretKey}\nLANGFUSE_PUBLIC_KEY=${publicKey}\nLANGFUSE_HOST="${host}"`}
+ className="my-2 bg-blue-50"
+ />
+ <CodeView
+ content={`# remove: import openai\n\nfrom langfuse.openai import openai`}
+ className="my-2 bg-blue-50"
+ />
+ <p className="mt-2 text-xs text-gray-600">
+ Use the OpenAI SDK as you would normally. See the{" "}
+ <a
+ href="https://langfuse.com/docs/integrations/openai"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ OpenAI Integration docs
+ </a>{" "}
+ for more details and an end-to-end example.
+ </p>
+ </TabsContent>
+ <TabsContent value="langchain">
+ <p className="mt-2 text-xs text-gray-600">
+ The integration uses the Langchain callback system to automatically
+ capture detailed traces of your Langchain executions.
+ </p>
+ <CodeView content="pip install langfuse" className="my-2 bg-blue-50" />
+ <CodeView
+ content={LANGCHAIN_PYTHON_CODE({ publicKey, secretKey, host })}
+ className="my-2 bg-blue-50"
+ />
+ <p className="mt-2 text-xs text-gray-600">
+ See the{" "}
+ <a
+ href="https://langfuse.com/docs/integrations/langchain/python"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Langchain Integration docs
+ </a>{" "}
+ for more details and an end-to-end example.
+ </p>
+ </TabsContent>
+ <TabsContent value="langchain-js">
+ <p className="mt-2 text-xs text-gray-600">
+ The integration uses the Langchain callback system to automatically
+ capture detailed traces of your Langchain executions.
+ </p>
+ <CodeView
+ content="npm install langfuse-langchain"
+ className="my-2 bg-blue-50"
+ />
+ <CodeView
+ content={LANGCHAIN_JS_CODE({ publicKey, secretKey, host })}
+ className="my-2 bg-blue-50"
+ />
+ <p className="mt-2 text-xs text-gray-600">
+ See the{" "}
+ <a
+ href="https://langfuse.com/docs/integrations/langchain/typescript"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Langchain Integration docs
+ </a>{" "}
+ for more details and an end-to-end example.
+ </p>
+ </TabsContent>
+ <TabsContent value="llamaindex">
+ <p className="mt-2 text-xs text-gray-600">
+ The integration uses the LlamaIndex callback system to automatically
+ capture detailed traces of your LlamaIndex executions.
+ </p>
+ <CodeView
+ content="pip install langfuse llama-index"
+ className="my-2 bg-blue-50"
+ />
+ <CodeView
+ content={LLAMA_INDEX_CODE({ publicKey, secretKey, host })}
+ className="my-2 bg-blue-50"
+ />
+ <p className="mt-2 text-xs text-gray-600">
+ See the{" "}
+ <a
+ href="https://langfuse.com/docs/integrations/llama-index"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ LlamaIndex Integration docs
+ </a>{" "}
+ for more details and an end-to-end example.
+ </p>
+ </TabsContent>
+ <TabsContent value="other">
+ <p className="mt-2 text-xs text-gray-600">
+ Use the{" "}
+ <a
+ href="https://api.reference.langfuse.com/"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ API
+ </a>{" "}
+ or one of the{" "}
+ <a
+ href="https://langfuse.com/docs/integrations"
+ className="underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ native integrations
+ </a>{" "}
+ (e.g. LiteLLM, Flowise, and Langflow) to integrate with Langfuse.
+ </p>
+ </TabsContent>
+ </Tabs>
+ );
+};
const LANGCHAIN_PYTHON_CODE = (p: {
publicKey: string;
secretKey: string;
diff --git a/web/src/features/rbac/components/CreateProjectMemberButton.tsx b/web/src/features/rbac/components/CreateProjectMemberButton.tsx
index 2bd747aeac..ecfd58fccd 100644
--- a/web/src/features/rbac/components/CreateProjectMemberButton.tsx
+++ b/web/src/features/rbac/components/CreateProjectMemberButton.tsx
@@ -32,6 +32,7 @@ import { Input } from "@/src/components/ui/input";
import { MembershipRole } from "@langfuse/shared";
import { roleAccessRights } from "@/src/features/rbac/constants/roleAccessRights";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const availableRoles = [
MembershipRole.ADMIN,
@@ -45,6 +46,7 @@ const formSchema = z.object({
});
export function CreateProjectMemberButton(props: { projectId: string }) {
+ const capture = usePostHogClientCapture();
const [open, setOpen] = useState(false);
const hasAccess = useHasAccess({
projectId: props.projectId,
@@ -72,6 +74,9 @@ export function CreateProjectMemberButton(props: { projectId: string }) {
if (!hasAccess) return null;
function onSubmit(values: z.infer<typeof formSchema>) {
+ capture("project_settings:send_membership_invitation", {
+ role: values.role,
+ });
return mutCreateProjectMember
.mutateAsync({
projectId: props.projectId,
diff --git a/web/src/features/rbac/components/ProjectMembersTable.tsx b/web/src/features/rbac/components/ProjectMembersTable.tsx
index fa4360ef0c..e09d2e1da1 100644
--- a/web/src/features/rbac/components/ProjectMembersTable.tsx
+++ b/web/src/features/rbac/components/ProjectMembersTable.tsx
@@ -14,8 +14,10 @@ import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { CreateProjectMemberButton } from "@/src/features/rbac/components/CreateProjectMemberButton";
import { useSession } from "next-auth/react";
import Header from "@/src/components/layouts/header";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export function ProjectMembersTable({ projectId }: { projectId: string }) {
+ const capture = usePostHogClientCapture();
const hasReadAccess = useHasAccess({
projectId: projectId,
scope: "members:read",
@@ -77,6 +79,7 @@ export function ProjectMembersTable({ projectId }: { projectId: string }) {
size="icon"
loading={mutDeleteMembership.isLoading}
onClick={() => {
+ capture("project_settings:delete_membership");
mutDeleteMembership.mutate({
projectId: projectId,
userId: m.user.id,
@@ -122,6 +125,9 @@ export function ProjectMembersTable({ projectId }: { projectId: string }) {
size="icon"
loading={mutDeleteInvitation.isLoading}
onClick={() => {
+ capture(
+ "project_settings:delete_membership_invitation",
+ );
mutDeleteInvitation.mutate({
id: invite.id,
projectId: projectId,
diff --git a/web/src/features/tag/components/TagCommandItem.tsx b/web/src/features/tag/components/TagCommandItem.tsx
index 04933a262d..b90bd18e9a 100644
--- a/web/src/features/tag/components/TagCommandItem.tsx
+++ b/web/src/features/tag/components/TagCommandItem.tsx
@@ -2,6 +2,7 @@ import { CommandItem } from "@/src/components/ui/command";
import { cn } from "@/src/utils/tailwind";
import { Check } from "lucide-react";
import { Button } from "@/src/components/ui/button";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type TagCommandItemProps = {
value: string;
@@ -14,11 +15,15 @@ const TagCommandItem = ({
selectedTags,
setSelectedTags,
}: TagCommandItemProps) => {
+ const capture = usePostHogClientCapture();
return (
<CommandItem
key={value}
onSelect={() => {
setSelectedTags([...selectedTags, value]);
+ capture("tag:add_existing_tag", {
+ name: value,
+ });
}}
>
<div
diff --git a/web/src/features/tag/components/TagInput.tsx b/web/src/features/tag/components/TagInput.tsx
index 3b9426ef8a..927916aa25 100644
--- a/web/src/features/tag/components/TagInput.tsx
+++ b/web/src/features/tag/components/TagInput.tsx
@@ -3,6 +3,7 @@ import { cn } from "@/src/utils/tailwind";
import { X } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { Command as CommandPrimitive } from "cmdk";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type TagInputProps = React.ComponentPropsWithoutRef<
typeof CommandPrimitive.Input
@@ -14,39 +15,45 @@ type TagInputProps = React.ComponentPropsWithoutRef<
export const TagInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
TagInputProps
->(({ className, selectedTags, setSelectedTags, ...props }, ref) => (
- <div
- className="flex flex-wrap items-center overflow-auto rounded-lg border px-2"
- cmdk-input-wrapper=""
- >
- {selectedTags.length > 0 && (
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 pt-2">
- {selectedTags.map((tag: string) => (
- <Button
- key={tag}
- variant="secondary"
- size="xs"
- onClick={() => {
- const newTags = selectedTags.filter((t) => t !== tag);
- setSelectedTags(newTags);
- }}
- >
- {tag}
- <X className="ml-1 h-3 w-3" />
- </Button>
- ))}
- </div>
- )}
- <CommandPrimitive.Input
- ref={ref}
- className={cn(
- "flex h-11 w-full rounded-md border-transparent bg-transparent px-1 text-sm outline-none placeholder:text-slate-500 focus:border-0 focus:border-none focus:border-transparent focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-slate-400 ",
- className,
+>(({ className, selectedTags, setSelectedTags, ...props }, ref) => {
+ const capture = usePostHogClientCapture();
+ return (
+ <div
+ className="flex flex-wrap items-center overflow-auto rounded-lg border px-2"
+ cmdk-input-wrapper=""
+ >
+ {selectedTags.length > 0 && (
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 pt-2">
+ {selectedTags.map((tag: string) => (
+ <Button
+ key={tag}
+ variant="secondary"
+ size="xs"
+ onClick={() => {
+ const newTags = selectedTags.filter((t) => t !== tag);
+ setSelectedTags(newTags);
+ capture("tag:remove_tag", {
+ name: tag,
+ });
+ }}
+ >
+ {tag}
+ <X className="ml-1 h-3 w-3" />
+ </Button>
+ ))}
+ </div>
)}
- autoFocus
- {...props}
- />
- </div>
-));
+ <CommandPrimitive.Input
+ ref={ref}
+ className={cn(
+ "flex h-11 w-full rounded-md border-transparent bg-transparent px-1 text-sm outline-none placeholder:text-slate-500 focus:border-0 focus:border-none focus:border-transparent focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-slate-400 ",
+ className,
+ )}
+ autoFocus
+ {...props}
+ />
+ </div>
+ );
+});
TagInput.displayName = CommandPrimitive.Input.displayName;
diff --git a/web/src/features/tag/components/TagMananger.tsx b/web/src/features/tag/components/TagMananger.tsx
index 87094b6ac4..99c89331ff 100644
--- a/web/src/features/tag/components/TagMananger.tsx
+++ b/web/src/features/tag/components/TagMananger.tsx
@@ -10,6 +10,7 @@ import {
} from "@/src/components/ui/popover";
import { Command, CommandList, CommandGroup } from "cmdk";
import { cn } from "@/src/utils/tailwind";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
type TagManagerProps = {
tags: string[];
@@ -34,7 +35,7 @@ const TagManager = ({
setInputValue,
setSelectedTags,
} = useTagManager({ initialTags: tags, allTags });
-
+ const capture = usePostHogClientCapture();
const filteredTags = availableTags.filter(
(value) =>
value.toLowerCase().includes(inputValue.trim().toLowerCase()) &&
@@ -42,6 +43,9 @@ const TagManager = ({
);
const handlePopoverChange = (open: boolean) => {
+ if (open) {
+ capture("tag:modal_open");
+ }
if (!open && selectedTags !== tags) {
setInputValue("");
mutateTags(selectedTags);
diff --git a/web/src/features/tag/hooks/useTagManager.tsx b/web/src/features/tag/hooks/useTagManager.tsx
index 14446eb2c8..c752b56bfe 100644
--- a/web/src/features/tag/hooks/useTagManager.tsx
+++ b/web/src/features/tag/hooks/useTagManager.tsx
@@ -1,3 +1,4 @@
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useState, useMemo } from "react";
type UseTagManagerProps = {
@@ -12,11 +13,15 @@ export function useTagManager({ initialTags, allTags }: UseTagManagerProps) {
() => allTags.filter((value) => !selectedTags.includes(value)),
[allTags, selectedTags],
);
+ const capture = usePostHogClientCapture();
const handleItemCreate = () => {
setSelectedTags((prevSelectedTags) => [
// dedupe
...new Set([...prevSelectedTags, inputValue]),
]);
+ capture("tag:create_new_button_click", {
+ name: inputValue,
+ });
availableTags.push(inputValue);
setInputValue("");
};
diff --git a/web/src/features/telemetry/index.ts b/web/src/features/telemetry/index.ts
index ca85b2e3bf..dca662fc62 100644
--- a/web/src/features/telemetry/index.ts
+++ b/web/src/features/telemetry/index.ts
@@ -1,5 +1,5 @@
import { VERSION } from "@/src/constants";
-import { ServerPosthog } from "@/src/server/services/posthog";
+import { ServerPosthog } from "@/src/features/posthog-analytics/ServerPosthog";
import { Prisma, prisma } from "@langfuse/shared/src/db";
import { v4 as uuidv4 } from "uuid";
diff --git a/web/src/features/usage-metering/ProjectUsageChart.tsx b/web/src/features/usage-metering/ProjectUsageChart.tsx
index f1b25aa2d7..54107fc77b 100644
--- a/web/src/features/usage-metering/ProjectUsageChart.tsx
+++ b/web/src/features/usage-metering/ProjectUsageChart.tsx
@@ -13,7 +13,7 @@ import {
DialogTrigger,
} from "@/src/components/ui/dialog";
import Header from "@/src/components/layouts/header";
-import { usePostHog } from "posthog-js/react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export const ProjectUsageChart: React.FC<{ projectId: string }> = ({
projectId,
@@ -21,7 +21,7 @@ export const ProjectUsageChart: React.FC<{ projectId: string }> = ({
const usage = api.usageMetering.last30d.useQuery({
projectId,
});
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const project = api.projects.byId.useQuery({ projectId });
const planLimit =
project.data?.cloudConfig?.monthlyObservationLimit ?? 50_000;
@@ -67,7 +67,7 @@ export const ProjectUsageChart: React.FC<{ projectId: string }> = ({
<Dialog
onOpenChange={(open) => {
if (open) {
- posthog.capture("project_settings:pricing_dialog_opened");
+ capture("project_settings:pricing_dialog_opened");
}
}}
>
diff --git a/web/src/pages/api/cron/ingestion-metrics.ts b/web/src/pages/api/cron/ingestion-metrics.ts
index 23ac193f46..cbf8b6a1a6 100644
--- a/web/src/pages/api/cron/ingestion-metrics.ts
+++ b/web/src/pages/api/cron/ingestion-metrics.ts
@@ -1,5 +1,5 @@
import { env } from "@/src/env.mjs";
-import { ServerPosthog } from "@/src/server/services/posthog";
+import { ServerPosthog } from "@/src/features/posthog-analytics/ServerPosthog";
import { prisma, Prisma } from "@langfuse/shared/src/db";
import { type NextApiRequest, type NextApiResponse } from "next";
diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsx
index 508bb32fa3..43181e5759 100644
--- a/web/src/pages/auth/sign-in.tsx
+++ b/web/src/pages/auth/sign-in.tsx
@@ -22,7 +22,6 @@ import Link from "next/link";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
-import { usePostHog } from "posthog-js/react";
import { Divider } from "@tremor/react";
import { CloudPrivacyNotice } from "@/src/features/auth/components/AuthCloudPrivacyNotice";
import { CloudRegionSwitch } from "@/src/features/auth/components/AuthCloudRegionSwitch";
@@ -32,6 +31,7 @@ import { isAnySsoConfigured } from "@langfuse/ee/sso";
import { Shield } from "lucide-react";
import { useRouter } from "next/router";
import { captureException } from "@sentry/nextjs";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
const credentialAuthForm = z.object({
email: z.string().email(),
@@ -95,7 +95,7 @@ export function SSOButtons({
authProviders: PageProps["authProviders"];
action?: string;
}) {
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
return (
// any authprovider from props is enanbles
@@ -108,7 +108,7 @@ export function SSOButtons({
{authProviders.google && (
<Button
onClick={() => {
- posthog.capture("sign_in:google_button_click");
+ capture("sign_in:button_click", { provider: "google" });
void signIn("google");
}}
variant="secondary"
@@ -120,7 +120,7 @@ export function SSOButtons({
{authProviders.github && (
<Button
onClick={() => {
- posthog.capture("sign_in:github_button_click");
+ capture("sign_in:button_click", { provider: "github" });
void signIn("github");
}}
variant="secondary"
@@ -132,7 +132,9 @@ export function SSOButtons({
{authProviders.azureAd && (
<Button
onClick={() => {
- posthog.capture("sign_in:azure_ad_button_click");
+ capture("sign_in:button_click", {
+ provider: "azure-ad",
+ });
void signIn("azure-ad");
}}
variant="secondary"
@@ -144,7 +146,7 @@ export function SSOButtons({
{authProviders.okta && (
<Button
onClick={() => {
- posthog.capture("sign_in:okta_button_click");
+ capture("sign_in:button_click", { provider: "okta" });
void signIn("okta");
}}
variant="secondary"
@@ -156,7 +158,7 @@ export function SSOButtons({
{authProviders.auth0 && (
<Button
onClick={() => {
- posthog.capture("sign_in:auth0_button_click");
+ capture("sign_in:button_click", { provider: "auth0" });
void signIn("auth0");
}}
variant="secondary"
@@ -202,7 +204,7 @@ export default function SignIn({ authProviders, signUpDisabled }: PageProps) {
>(nextAuthErrorDescription ?? nextAuthError);
const [ssoLoading, setSsoLoading] = useState<boolean>(false);
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const [turnstileToken, setTurnstileToken] = useState<string>();
// Used to refresh turnstile as the token can only be used once
const [turnstileCData, setTurnstileCData] = useState<string>(
@@ -221,7 +223,7 @@ export default function SignIn({ authProviders, signUpDisabled }: PageProps) {
values: z.infer<typeof credentialAuthForm>,
) {
setCredentialsFormError(null);
- posthog.capture("sign_in:credentials_form_submit");
+ capture("sign_in:button_click", { provider: "email/password" });
const result = await signIn("credentials", {
email: values.email,
password: values.password,
@@ -267,6 +269,7 @@ export default function SignIn({ authProviders, signUpDisabled }: PageProps) {
setSsoLoading(false);
} else {
const { providerId } = await res.json();
+ capture("sign_in:button_click", { provider: "sso" });
void signIn(providerId);
}
}
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index 1fdf145126..db2a3aacf0 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -23,7 +23,6 @@ import {
} from "use-query-params";
import { isValidOption } from "@/src/utils/types";
import { api } from "@/src/utils/api";
-import { usePostHog } from "posthog-js/react";
import { FeedbackButtonWrapper } from "@/src/features/feedback/component/FeedbackButton";
import { BarChart2 } from "lucide-react";
import { Button } from "@/src/components/ui/button";
@@ -34,6 +33,7 @@ import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState
import { LatencyTables } from "@/src/features/dashboard/components/LatencyTables";
import { useMemo } from "react";
import { useSession } from "next-auth/react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export type DashboardDateRange = {
from: Date;
@@ -43,7 +43,7 @@ export type DashboardDateRange = {
export default function Start() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const posthog = usePostHog();
+ const capture = usePostHogClientCapture();
const session = useSession();
const project = session.data?.user?.projects.find(
@@ -74,7 +74,7 @@ export default function Start() {
option?: AvailableDateRangeSelections,
dateRange?: DashboardDateRange,
) => {
- posthog.capture("dashboard:date_range_changed");
+ capture("dashboard:date_range_changed");
setUrlParams({
select: option ? option.toString() : urlParams.select,
from: dateRange ? dateRange.from.getTime() : urlParams.from,
diff --git a/web/src/pages/project/[projectId]/models.tsx b/web/src/pages/project/[projectId]/models.tsx
index b07a07b627..3adb10341b 100644
--- a/web/src/pages/project/[projectId]/models.tsx
+++ b/web/src/pages/project/[projectId]/models.tsx
@@ -6,12 +6,13 @@ import { Button } from "@/src/components/ui/button";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { Lock } from "lucide-react";
import Link from "next/link";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export default function ModelsPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
const hasWriteAccess = useHasAccess({ projectId, scope: "models:CUD" });
-
+ const capture = usePostHogClientCapture();
return (
<div>
<Header
@@ -22,7 +23,11 @@ export default function ModelsPage() {
href: "https://langfuse.com/docs/model-usage-and-cost",
}}
actionButtons={
- <Button disabled={!hasWriteAccess} asChild>
+ <Button
+ disabled={!hasWriteAccess}
+ onClick={() => capture("models:new_form_open")}
+ asChild
+ >
<Link
href={hasWriteAccess ? `/project/${projectId}/models/new` : "#"}
>
diff --git a/web/src/pages/project/[projectId]/settings/posthog-integration.tsx b/web/src/pages/project/[projectId]/settings/posthog-integration.tsx
index 3fd3251017..30b287d434 100644
--- a/web/src/pages/project/[projectId]/settings/posthog-integration.tsx
+++ b/web/src/pages/project/[projectId]/settings/posthog-integration.tsx
@@ -13,6 +13,7 @@ import { Input } from "@/src/components/ui/input";
import { PasswordInput } from "@/src/components/ui/password-input";
import { Switch } from "@/src/components/ui/switch";
import { env } from "@/src/env.mjs";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
@@ -20,7 +21,6 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { Card } from "@tremor/react";
import Link from "next/link";
import { useRouter } from "next/router";
-import posthog from "posthog-js";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { type z } from "zod";
@@ -29,7 +29,6 @@ export default function PosthogIntegrationSettings() {
const router = useRouter();
const projectId = router.query.projectId as string;
const state = api.posthogIntegration.get.useQuery({ projectId });
-
if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) return null;
return (
@@ -102,6 +101,7 @@ const PostHogIntegrationSettings = ({
state?: RouterOutput["posthogIntegration"]["get"];
projectId: string;
}) => {
+ const capture = usePostHogClientCapture();
const posthogForm = useForm<z.infer<typeof posthogIntegrationFormSchema>>({
resolver: zodResolver(posthogIntegrationFormSchema),
defaultValues: {
@@ -135,7 +135,7 @@ const PostHogIntegrationSettings = ({
async function onSubmit(
values: z.infer<typeof posthogIntegrationFormSchema>,
) {
- posthog.capture("integrations:posthog_form_submitted");
+ capture("integrations:posthog_form_submitted");
mut.mutate({
projectId,
...values,