🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: new observations UI (#10174)
Max Deichmannd37355981ab6
diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.tsnew file mode 100644index 0000000000..be017b315e--- /dev/null+++ b/packages/shared/src/eventsTable.ts@@ -0,0 +1,304 @@+import { type ColumnDefinition } from "./tableDefinitions";++// Column definitions for the ClickHouse events table+// Used for filtering, sorting, and mapping UI columns to ClickHouse columns+export const eventsTableCols: ColumnDefinition[] = [+ {+ name: "Span ID",+ id: "spanId",+ type: "string",+ internal: "e.span_id",+ },+ {+ name: "Trace ID",+ id: "traceId",+ type: "string",+ internal: "e.trace_id",+ },+ {+ name: "Parent Span ID",+ id: "parentSpanId",+ type: "string",+ internal: "e.parent_span_id",+ nullable: true,+ },+ {+ name: "Start Time",+ id: "startTime",+ type: "datetime",+ internal: "e.start_time",+ },+ {+ name: "End Time",+ id: "endTime",+ type: "datetime",+ internal: "e.end_time",+ nullable: true,+ },+ {+ name: "Name",+ id: "name",+ type: "stringOptions",+ internal: "e.name",+ options: [], // to be added at runtime+ nullable: true,+ },+ {+ name: "Type",+ id: "type",+ type: "stringOptions",+ internal: "e.type",+ options: [],+ },+ {+ name: "Environment",+ id: "environment",+ type: "stringOptions",+ internal: "e.environment",+ options: [], // to be added at runtime+ nullable: true,+ },+ {+ name: "Version",+ id: "version",+ type: "string",+ internal: "e.version",+ nullable: true,+ },+ {+ name: "User ID",+ id: "userId",+ type: "string",+ internal: "e.user_id",+ nullable: true,+ },+ {+ name: "Session ID",+ id: "sessionId",+ type: "string",+ internal: "e.session_id",+ nullable: true,+ },+ {+ name: "Level",+ id: "level",+ type: "stringOptions",+ internal: "e.level",+ options: [],+ },+ {+ name: "Status Message",+ id: "statusMessage",+ type: "string",+ internal: "e.status_message",+ nullable: true,+ },+ {+ name: "Completion Start Time",+ id: "completionStartTime",+ type: "datetime",+ internal: "e.completion_start_time",+ nullable: true,+ },+ {+ name: "Prompt ID",+ id: "promptId",+ type: "string",+ internal: "e.prompt_id",+ nullable: true,+ },+ {+ name: "Prompt Name",+ id: "promptName",+ type: "stringOptions",+ internal: "e.prompt_name",+ options: [], // to be added at runtime+ nullable: true,+ },+ {+ name: "Prompt Version",+ id: "promptVersion",+ type: "string",+ internal: "e.prompt_version",+ nullable: true,+ },+ {+ name: "Model ID",+ id: "modelId",+ type: "stringOptions",+ internal: "e.model_id",+ options: [], // to be added at runtime+ nullable: true,+ },+ {+ name: "Provided Model Name",+ id: "providedModelName",+ type: "stringOptions",+ internal: "e.provided_model_name",+ options: [], // to be added at runtime+ nullable: true,+ },+ {+ name: "Model Parameters",+ id: "modelParameters",+ type: "string",+ internal: "e.model_parameters",+ nullable: true,+ },+ {+ name: "Total Cost ($)",+ id: "totalCost",+ type: "number",+ internal: "e.total_cost",+ nullable: true,+ },+ {+ name: "Input Tokens",+ id: "inputTokens",+ type: "number",+ internal: "e.usage_details.input",+ nullable: true,+ },+ {+ name: "Output Tokens",+ id: "outputTokens",+ type: "number",+ internal: "e.usage_details.output",+ nullable: true,+ },+ {+ name: "Total Tokens",+ id: "totalTokens",+ type: "number",+ internal: "e.usage_details.total",+ nullable: true,+ },+ {+ name: "Input Cost ($)",+ id: "inputCost",+ type: "number",+ internal: "e.cost_details.input",+ nullable: true,+ },+ {+ name: "Output Cost ($)",+ id: "outputCost",+ type: "number",+ internal: "e.cost_details.output",+ nullable: true,+ },+ {+ name: "Latency (s)",+ id: "latency",+ type: "number",+ internal: "date_diff('millisecond', e.start_time, e.end_time) / 1000.0",+ nullable: true,+ },+ {+ name: "Time To First Token (s)",+ id: "timeToFirstToken",+ type: "number",+ internal:+ "date_diff('millisecond', e.start_time, e.completion_start_time) / 1000.0",+ nullable: true,+ },+ {+ name: "Tokens per second",+ id: "tokensPerSecond",+ type: "number",+ internal:+ "e.usage_details.output / (date_diff('millisecond', e.start_time, e.end_time) / 1000.0)",+ nullable: true,+ },+ {+ name: "Input",+ id: "input",+ type: "string",+ internal: "e.input",+ nullable: true,+ },+ {+ name: "Output",+ id: "output",+ type: "string",+ internal: "e.output",+ nullable: true,+ },+ {+ name: "Metadata",+ id: "metadata",+ type: "stringObject",+ internal: "e.metadata",+ },+ {+ name: "Service Version",+ id: "serviceVersion",+ type: "string",+ internal: "e.service_version",+ nullable: true,+ },+ {+ name: "Scope Name",+ id: "scopeName",+ type: "string",+ internal: "e.scope_name",+ nullable: true,+ },+ {+ name: "Scope Version",+ id: "scopeVersion",+ type: "string",+ internal: "e.scope_version",+ nullable: true,+ },+ {+ name: "Telemetry SDK Language",+ id: "telemetrySdkLanguage",+ type: "string",+ internal: "e.telemetry_sdk_language",+ nullable: true,+ },+ {+ name: "Telemetry SDK Name",+ id: "telemetrySdkName",+ type: "string",+ internal: "e.telemetry_sdk_name",+ nullable: true,+ },+ {+ name: "Telemetry SDK Version",+ id: "telemetrySdkVersion",+ type: "string",+ internal: "e.telemetry_sdk_version",+ nullable: true,+ },+ {+ name: "Trace Name",+ id: "traceName",+ type: "stringOptions",+ internal: "t.name",+ options: [], // to be added at runtime+ nullable: true,+ },+ {+ name: "Trace Tags",+ id: "traceTags",+ type: "arrayOptions",+ internal: "t.tags",+ options: [], // to be added at runtime+ },+ {+ name: "Scores (numeric)",+ id: "scores_avg",+ type: "numberObject",+ internal: "scores_avg",+ },+ {+ name: "Scores (categorical)",+ id: "score_categories",+ type: "categoryOptions",+ internal: "score_categories",+ options: [], // to be added at runtime+ nullable: true,+ },+];diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 49f1406ced..8b6fce3fc4 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -8,6 +8,7 @@ export * from "./tableDefinitions";export * from "./types";export * from "./tableDefinitions/tracesTable";export * from "./observationsTable";+export * from "./eventsTable";export * from "./utils/zod";export * from "./utils/json";export * from "./utils/stringChecks";diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex ca71aaa60b..ef153bb4e3 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -821,3 +821,84 @@ export class CTEQueryBuilder<return parts.join("\n");}}++/**+ * Query builder for observation-level aggregation queries on events table.+ * Similar to EventsAggregationQueryBuilder but for grouping by observation columns.+ * Used for filter options queries.+ *+ * @example+ * const builder = new EventsAggQueryBuilder({+ * projectId: "abc123",+ * groupByColumn: "e.provided_model_name",+ * selectExpression: "e.provided_model_name as name"+ * })+ * .whereRaw("e.type = 'GENERATION'")+ * .orderBy("ORDER BY count() DESC")+ * .limit(1000, 0);+ */+export class EventsAggQueryBuilder extends AbstractCTEQueryBuilder {+ private projectId: string;+ private groupByColumn: string;+ private selectExpression: string;++ constructor(options: {+ projectId: string;+ groupByColumn: string;+ selectExpression: string;+ }) {+ super();+ this.projectId = options.projectId;+ this.groupByColumn = options.groupByColumn;+ this.selectExpression = options.selectExpression;+ this.params.projectId = options.projectId;+ }++ /**+ * Build the final query+ */+ protected buildQuery(): string {+ const parts: string[] = [];++ // CTEs+ const cteSection = this.buildCTESection();+ if (cteSection) {+ parts.push(cteSection);+ }++ // SELECT+ parts.push(`SELECT ${this.selectExpression}`);++ // FROM+ parts.push("FROM events e");++ // JOINs+ const joinSection = this.buildJoinSection();+ if (joinSection) {+ parts.push(joinSection);+ }++ // WHERE - project_id filter added automatically+ const allWhereClauses = [+ "e.project_id = {projectId: String}",+ ...this.whereClauses,+ ];+ parts.push(`WHERE ${allWhereClauses.join("\n AND ")}`);++ // GROUP BY+ parts.push(`GROUP BY ${this.groupByColumn}`);++ // ORDER BY+ if (this.orderByClause) {+ parts.push(this.orderByClause);+ }++ // LIMIT+ const limitSection = this.buildLimitSection();+ if (limitSection) {+ parts.push(limitSection);+ }++ return parts.join("\n");+ }+}diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 9d7786fdda..c2b39d86be 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -29,6 +29,7 @@ export {} from "./public-api-filter-builder";export {CTEQueryBuilder,+ EventsAggQueryBuilder,EventsAggregationQueryBuilder,type CTESchema,type CTEWithSchema,diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex 2fb49541f4..f61cce83b6 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -349,6 +349,10 @@ export async function queryClickhouse<T>(opts: {// Retry logic for socket hang up and other network errorsreturn await backOff(async () => {+ // same logic as for prisma. we want to see queries in development+ if (env.NODE_ENV === "development") {+ logger.info(`clickhouse:query ${opts.query}`);+ }const res = await clickhouseClient(opts.clickhouseConfigs,opts.preferredClickhouseService,@@ -364,11 +368,6 @@ export async function queryClickhouse<T>(opts: {},});- // same logic as for prisma. we want to see queries in development- if (env.NODE_ENV === "development") {- logger.info(`clickhouse:query ${res.query_id} ${opts.query}`);- }-span.setAttribute("ch.queryId", res.query_id);// add summary headers to the span. Helps to tune performancediff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex bcc23af1a5..a9c6305996 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -48,6 +48,7 @@ import { convertObservation } from "./observations_converters";import {EventsQueryBuilder,CTEQueryBuilder,+ EventsAggQueryBuilder,} from "../queries/clickhouse-sql/event-query-builder";type ObservationsTableQueryResultWitouhtTraceFields = Omit<@@ -967,3 +968,396 @@ export const updateEvents = async (},});};++/**+ * Get grouped provided model names from events table+ * Used for filter options+ */+export const getEventsGroupedByModel = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.provided_model_name",+ selectExpression: "e.provided_model_name as name, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ name: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res.map((r) => ({ model: r.name, count: r.count }));+};++/**+ * Get grouped model IDs from events table+ * Used for filter options+ */+export const getEventsGroupedByModelId = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.model_id",+ selectExpression: "e.model_id as modelId, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ modelId: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res.map((r) => ({ modelId: r.modelId, count: r.count }));+};++/**+ * Get grouped observation names from events table+ * Used for filter options+ */+export const getEventsGroupedByName = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.name",+ selectExpression: "e.name as name, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ name: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};++/**+ * Get grouped prompt names from events table+ * Used for filter options+ */+export const getEventsGroupedByPromptName = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.prompt_name",+ selectExpression: "e.prompt_name as promptName, count() as count",+ })+ .whereRaw("e.type = 'GENERATION'")+ .whereRaw("e.prompt_name IS NOT NULL AND e.prompt_name != ''")+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ promptName: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });++ return res.filter((r) => Boolean(r.promptName));+};++/**+ * Get grouped observation types from events table+ * Used for filter options+ */+export const getEventsGroupedByType = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.type",+ selectExpression: "e.type as type, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ type: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};++/**+ * Get grouped user IDs from events table (joined with traces)+ * Used for filter options+ */+export const getEventsGroupedByUserId = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.user_id",+ selectExpression: "e.user_id as userId, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ userId: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};++/**+ * Get grouped versions from events table+ * Used for filter options+ */+export const getEventsGroupedByVersion = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.version",+ selectExpression: "e.version as version, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ version: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};++/**+ * Get grouped session IDs from events table (joined with traces)+ * Used for filter options+ */+export const getEventsGroupedBySessionId = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.session_id",+ selectExpression: "e.session_id as sessionId, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ sessionId: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};++/**+ * Get grouped levels from events table+ * Used for filter options+ */+export const getEventsGroupedByLevel = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.level",+ selectExpression: "e.level as level, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ level: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};++/**+ * Get grouped environments from events table+ * Used for filter options+ */+export const getEventsGroupedByEnvironment = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.environment",+ selectExpression: "e.environment as environment, count() as count",+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ environment: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsindex 56d508e4b2..e14a85afdf 100644--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -127,8 +127,7 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [uiTableName: "Total Cost ($)",uiTableId: "totalCost",clickhouseTableName: "events",- clickhouseSelect:- "if(mapExists((k, v) -> (k = 'total'), cost_details), cost_details['total'], NULL)",+ clickhouseSelect: "cost_details.total",},{uiTableName: "Level",@@ -174,16 +173,14 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [uiTableName: "Total Tokens",uiTableId: "totalTokens",clickhouseTableName: "events",- clickhouseSelect:- "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",+ clickhouseSelect: "usage_details.total",clickhouseTypeOverwrite: "Decimal64(3)",},{uiTableName: "Tokens",uiTableId: "tokens",clickhouseTableName: "events",- clickhouseSelect:- "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",+ clickhouseSelect: "usage_details.total",clickhouseTypeOverwrite: "Decimal64(3)",},{@@ -222,12 +219,12 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [uiTableName: "Prompt Name",uiTableId: "promptName",clickhouseTableName: "events",- clickhouseSelect: "o.prompt_name",+ clickhouseSelect: "e.prompt_name",},{uiTableName: "Prompt Version",uiTableId: "promptVersion",clickhouseTableName: "events",- clickhouseSelect: "o.prompt_version",+ clickhouseSelect: "e.prompt_version",},];diff --git a/web/src/__tests__/async/events-service.servertest.ts b/web/src/__tests__/async/events-service.servertest.tsnew file mode 100644index 0000000000..1c34279ca0--- /dev/null+++ b/web/src/__tests__/async/events-service.servertest.ts@@ -0,0 +1,561 @@+import { v4 } from "uuid";+import { createEvent, createTraceScore } from "@langfuse/shared/src/server";+import { createEventsCh, createScoresCh } from "@langfuse/shared/src/server";+import {+ getEventList,+ getEventCount,+ getEventFilterOptions,+} from "@/src/features/events/server/eventsService";+import { type ObservationType } from "@langfuse/shared";+import { env } from "@/src/env.mjs";++// Helper to wait for ClickHouse to process data+const waitForClickHouse = (ms = 2000) =>+ new Promise((resolve) => setTimeout(resolve, ms));++const maybe =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? describe+ : describe.skip;++describe("Events Service", () => {+ it("should kill redis connection", () => {+ // we need at least one test case to avoid hanging+ // redis connection when everything else is skipped.+ });+ maybe("getEventList", () => {+ it("should return paginated list of events", async () => {+ const projectId = v4();+ const traceId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");++ // Create events+ const events = [];+ for (let i = 0; i < 5; i++) {+ const eventId = v4();+ events.push(+ createEvent({+ span_id: eventId,+ id: eventId,+ trace_id: traceId,+ type: "GENERATION",+ name: `test-event-${i}`,+ start_time: timestamp.getTime() * 1000, // Convert to microseconds+ project_id: projectId,+ }),+ );+ }++ // Insert events into ClickHouse+ await createEventsCh(events);++ // Wait for ClickHouse to process+ await waitForClickHouse();++ const result = await getEventList({+ projectId,+ filter: [],+ searchType: [],+ orderBy: null,+ page: 0,+ limit: 3,+ });++ expect(result.observations).toBeDefined();+ expect(result.observations.length).toBeGreaterThanOrEqual(0);+ if (result.observations.length > 0) {+ expect(result.observations.length).toBeLessThanOrEqual(3);+ }+ });++ it.each([+ [+ "GENERATION",+ {+ column: "Type",+ operator: "any of",+ value: ["GENERATION"],+ type: "stringOptions",+ },+ ],+ [+ "test-event",+ {+ column: "Name",+ operator: "any of",+ value: ["test-event"],+ type: "stringOptions",+ },+ ],+ [+ "DEFAULT",+ {+ column: "Level",+ operator: "any of",+ value: ["DEFAULT"],+ type: "stringOptions",+ },+ ],+ ])("should filter events by %s = %s", async (filterValue, filterState) => {+ const traceId = v4();+ const eventId = v4();+ const projectId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");++ const event = createEvent({+ span_id: eventId,+ id: eventId,+ trace_id: traceId,+ type: filterValue as ObservationType,+ name: filterValue === "test-event" ? "test-event" : "other-name",+ level: filterValue === "DEFAULT" ? "DEFAULT" : "ERROR",+ start_time: timestamp.getTime() * 1000,+ project_id: projectId,+ });++ await createEventsCh([event]);+ await waitForClickHouse();++ const result = await getEventList({+ projectId,+ filter: [filterState],+ searchType: [],+ orderBy: null,+ page: 0,+ limit: 10,+ });++ expect(result.observations.length).toBeGreaterThanOrEqual(1);+ expect(result.observations.length).toBeLessThanOrEqual(10);+ expect(result.observations[0].name).toBe(+ filterValue === "test-event" ? "test-event" : "other-name",+ );+ expect(result.observations[0].type).toBe(filterValue as ObservationType);+ expect(result.observations[0].level).toBe(+ filterValue === "DEFAULT" ? "DEFAULT" : "ERROR",+ );+ expect(result.observations[0].projectId).toBe(projectId);+ expect(result.observations[0].traceId).toBe(traceId);+ });++ it("should handle pagination correctly", async () => {+ const traceId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");+ const projectId = v4();++ const ids: string[] = [];++ // Create multiple events+ const events = [];+ for (let i = 0; i < 10; i++) {+ const eventId = v4();+ ids.push(eventId);+ events.push(+ createEvent({+ span_id: eventId,+ id: eventId,+ trace_id: traceId,+ type: "GENERATION",+ name: `test-event-${i}`,+ start_time: (timestamp.getTime() + i * 1000) * 1000,+ project_id: projectId,+ }),+ );+ }++ await createEventsCh(events);+ await waitForClickHouse();++ // Get first page+ const page1 = await getEventList({+ projectId,+ filter: [],+ searchType: [],+ orderBy: null,+ page: 0,+ limit: 5,+ });++ // Get second page+ const page2 = await getEventList({+ projectId,+ filter: [],+ searchType: [],+ orderBy: null,+ page: 1,+ limit: 5,+ });++ expect(page1.observations).toBeDefined();+ expect(page2.observations).toBeDefined();++ expect(page1.observations.map((o) => o.id)).not.toEqual(+ page2.observations.map((o) => o.id),+ );+ expect(page1.observations.map((o) => o.id)).toEqual(ids.slice(0, 5));+ expect(page2.observations.map((o) => o.id)).toEqual(ids.slice(5, 10));+ });+ });++ maybe("getEventCount", () => {+ it("should return correct count of events", async () => {+ const traceId = v4();+ const projectId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");++ // Create multiple events+ const eventCount = 7;+ const events = [];+ for (let i = 0; i < eventCount; i++) {+ const eventId = v4();+ events.push(+ createEvent({+ span_id: eventId,+ id: eventId,+ trace_id: traceId,+ type: "GENERATION",+ name: `test-event-count-${i}`,+ start_time: (timestamp.getTime() + i * 1000) * 1000,+ project_id: projectId,+ }),+ );+ }++ await createEventsCh(events);+ await waitForClickHouse();++ const result = await getEventCount({+ projectId,+ filter: [],+ searchType: [],+ orderBy: null,+ });++ expect(result.totalCount).toBe(eventCount);+ });++ it.each([+ [+ "GENERATION",+ {+ column: "Type",+ operator: "any of",+ value: ["GENERATION"],+ type: "stringOptions",+ },+ ],+ [+ "test-event",+ {+ column: "Name",+ operator: "any of",+ value: ["test-event"],+ type: "stringOptions",+ },+ ],+ [+ "DEFAULT",+ {+ column: "Level",+ operator: "any of",+ value: ["DEFAULT"],+ type: "stringOptions",+ },+ ],+ ])(+ "should count events filtered by %s = %s",+ async (filterValue, filterState) => {+ const traceId = v4();+ const eventId = v4();+ const projectId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");++ const event = createEvent({+ span_id: eventId,+ id: eventId,+ trace_id: traceId,+ type: filterValue as ObservationType,+ name: filterValue === "test-event" ? "test-event" : "other-name",+ level: filterValue === "DEFAULT" ? "DEFAULT" : "ERROR",+ start_time: timestamp.getTime() * 1000,+ project_id: projectId,+ });++ await createEventsCh([event]);+ await waitForClickHouse();++ const result = await getEventCount({+ projectId,+ filter: [filterState],+ searchType: [],+ orderBy: null,+ });++ expect(result.totalCount).toBeDefined();+ expect(typeof result.totalCount).toBe("number");+ expect(result.totalCount).toBe(1);+ },+ );+ });++ maybe("getEventFilterOptions", () => {+ it("should return correct filter options for various event types", async () => {+ const projectId = v4();+ const traceId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");+ const promptId = v4();+ const promptName = `test-prompt-${v4()}`;+ const modelId = v4();++ // Create diverse events with different properties+ const events = [+ // Event with model information+ createEvent({+ span_id: v4(),+ id: v4(),+ trace_id: traceId,+ type: "GENERATION",+ name: "event-with-model",+ start_time: timestamp.getTime() * 1000,+ project_id: projectId,+ provided_model_name: "gpt-4",+ model_id: modelId,+ user_id: "user-123",+ session_id: v4(),+ version: "v1.0",+ environment: "production",+ level: "DEFAULT",+ }),+ // Event with prompt information+ createEvent({+ span_id: v4(),+ id: v4(),+ trace_id: traceId,+ type: "GENERATION",+ name: "event-with-prompt",+ start_time: (timestamp.getTime() + 1000) * 1000,+ project_id: projectId,+ prompt_id: promptId,+ prompt_name: promptName,+ level: "WARNING",+ }),+ // SPAN type event+ createEvent({+ span_id: v4(),+ id: v4(),+ trace_id: traceId,+ type: "SPAN",+ name: "span-event",+ start_time: (timestamp.getTime() + 2000) * 1000,+ project_id: projectId,+ environment: "staging",+ }),+ // EVENT type event+ createEvent({+ span_id: v4(),+ id: v4(),+ trace_id: traceId,+ type: "EVENT",+ name: "custom-event",+ start_time: (timestamp.getTime() + 3000) * 1000,+ project_id: projectId,+ level: "ERROR",+ }),+ ];++ const eventId = events[0].span_id;++ await createEventsCh(events);++ // Create scores for filter options+ const numericScore = createTraceScore({+ id: v4(),+ timestamp: timestamp.getTime(),+ project_id: projectId,+ trace_id: traceId,+ name: "accuracy",+ value: 0.95,+ source: "API",+ observation_id: eventId,+ });++ const categoricalScore = createTraceScore({+ id: v4(),+ timestamp: timestamp.getTime(),+ project_id: projectId,+ trace_id: traceId,+ name: "sentiment",+ string_value: "positive",+ source: "API",+ observation_id: eventId,+ });++ await createScoresCh([numericScore, categoricalScore]);+ await waitForClickHouse();++ // Test without time filter+ const result = await getEventFilterOptions({+ projectId,+ });++ // Verify all filter option categories exist and are arrays+ expect(result).toBeDefined();+ expect(Array.isArray(result.providedModelName)).toBe(true);+ expect(Array.isArray(result.modelId)).toBe(true);+ expect(Array.isArray(result.name)).toBe(true);+ expect(Array.isArray(result.scores_avg)).toBe(true);+ expect(Array.isArray(result.score_categories)).toBe(true);+ expect(Array.isArray(result.promptName)).toBe(true);+ expect(Array.isArray(result.traceTags)).toBe(true);+ expect(Array.isArray(result.type)).toBe(true);+ expect(Array.isArray(result.userId)).toBe(true);+ expect(Array.isArray(result.version)).toBe(true);+ expect(Array.isArray(result.sessionId)).toBe(true);+ expect(Array.isArray(result.level)).toBe(true);+ expect(Array.isArray(result.environment)).toBe(true);++ // Verify populated options have correct values+ const modelNameOption = result.providedModelName.find(+ (opt) => opt.value === "gpt-4",+ );+ expect(modelNameOption).toBeDefined();+ expect(modelNameOption?.count).toBeGreaterThanOrEqual(1);++ const modelIdOption = result.modelId.find((opt) => opt.value === modelId);+ expect(modelIdOption).toBeDefined();+ expect(modelIdOption?.count).toBeGreaterThanOrEqual(1);++ const nameOptions = result.name.map((opt) => opt.value);+ expect(nameOptions).toContain("event-with-model");+ expect(nameOptions).toContain("event-with-prompt");+ expect(nameOptions).toContain("span-event");+ expect(nameOptions).toContain("custom-event");++ const typeOptions = result.type.map((opt) => opt.value);+ expect(typeOptions).toContain("GENERATION");+ expect(typeOptions).toContain("SPAN");+ expect(typeOptions).toContain("EVENT");++ const levelOptions = result.level.map((opt) => opt.value);+ expect(levelOptions).toContain("DEFAULT");+ expect(levelOptions).toContain("WARNING");+ expect(levelOptions).toContain("ERROR");++ const environmentOptions = result.environment.map((opt) => opt.value);+ expect(environmentOptions).toContain("production");+ expect(environmentOptions).toContain("staging");++ const promptNameOption = result.promptName.find(+ (opt) => opt.value === promptName,+ );+ expect(promptNameOption).toBeDefined();++ expect(result.scores_avg).toContain("accuracy");+ expect(Array.isArray(result.score_categories)).toBe(true);++ // Test with time filter+ const resultWithTimeFilter = await getEventFilterOptions({+ projectId,+ startTimeFilter: [+ {+ column: "Start Time" as const,+ operator: ">" as const,+ value: new Date("2023-01-01T00:00:00.000Z"),+ type: "datetime" as const,+ },+ ],+ });++ expect(resultWithTimeFilter).toBeDefined();+ expect(Array.isArray(resultWithTimeFilter.name)).toBe(true);+ expect(Array.isArray(resultWithTimeFilter.type)).toBe(true);+ });+ });++ maybe("Integration tests", () => {+ it("should have consistent count between getEventCount and getEventList", async () => {+ const traceId = v4();+ const projectId = v4();+ const timestamp = new Date("2024-01-01T00:00:00.000Z");++ // Create specific number of events+ const expectedCount = 5;+ const events = [];+ for (let i = 0; i < expectedCount; i++) {+ const eventId = v4();+ events.push(+ createEvent({+ span_id: eventId,+ id: eventId,+ trace_id: traceId,+ type: "GENERATION",+ name: `test-consistency-${i}`,+ start_time: (timestamp.getTime() + i * 1000) * 1000, // Microseconds+ project_id: projectId,+ }),+ );+ }++ await createEventsCh(events);+ await waitForClickHouse();++ const filters = [+ {+ column: "Name",+ operator: "contains",+ value: "test-consistency",+ type: "string",+ },+ ];++ const countResult = await getEventCount({+ projectId,+ filter: filters,+ searchType: [],+ orderBy: null,+ });++ const listResult = await getEventList({+ projectId,+ filter: filters,+ searchType: [],+ orderBy: null,+ page: 0,+ limit: 100,+ });++ expect(listResult.observations.length).toBeLessThanOrEqual(+ countResult.totalCount,+ );+ });++ it("should handle empty project gracefully", async () => {+ const emptyProjectId = v4();++ const [count, list, options] = await Promise.all([+ getEventCount({+ projectId: emptyProjectId,+ filter: [],+ searchType: [],+ orderBy: null,+ }),+ getEventList({+ projectId: emptyProjectId,+ filter: [],+ searchType: [],+ orderBy: null,+ page: 0,+ limit: 10,+ }),+ getEventFilterOptions({+ projectId: emptyProjectId,+ }),+ ]);++ expect(count.totalCount).toBe(0);+ expect(list.observations).toHaveLength(0);+ expect(options.name).toHaveLength(0);+ expect(options.type).toHaveLength(0);+ });+ });+});diff --git a/web/src/__tests__/nestObservations.clienttest.ts b/web/src/__tests__/nestObservations.clienttest.tsnew file mode 100644index 0000000000..64fcfe9f3c--- /dev/null+++ b/web/src/__tests__/nestObservations.clienttest.ts@@ -0,0 +1,118 @@+// Mock shared dependencies+jest.mock("@langfuse/shared", () => ({+ ObservationLevel: {+ DEBUG: "DEBUG",+ DEFAULT: "DEFAULT",+ WARNING: "WARNING",+ ERROR: "ERROR",+ },+}));++import { nestObservations } from "@/src/components/trace/lib/helpers";+import { type ObservationReturnType } from "@/src/server/api/routers/traces";++describe("nestObservations", () => {+ const createMockObservation = (+ overrides: Partial<ObservationReturnType> = {},+ ): ObservationReturnType => ({+ id: "mock-id",+ name: "Mock Observation",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:01.000Z"),+ parentObservationId: null,+ traceId: "mock-trace-id",+ projectId: "mock-project-id",+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ updatedAt: new Date("2024-01-01T00:00:00.000Z"),+ level: "DEFAULT",+ statusMessage: null,+ version: null,+ model: null,+ modelParameters: null,+ promptTokens: null,+ completionTokens: null,+ totalTokens: null,+ unit: null,+ inputCost: null,+ outputCost: null,+ totalCost: null,+ completionStartTime: null,+ timeToFirstToken: null,+ promptId: null,+ modelId: null,+ inputUsage: null,+ outputUsage: null,+ totalUsage: null,+ costDetails: null,+ calculatedInputCost: null,+ calculatedOutputCost: null,+ calculatedTotalCost: null,+ latency: null,+ ...overrides,+ });++ it("should build a nested tree from flat observations with parent-child relationships", () => {+ // Create a flat list of observations representing this tree structure:+ // parent1 (root)+ // ├─ child1-1+ // └─ child1-2+ // └─ grandchild1-2-1+ // parent2 (root)+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent1",+ name: "Parent 1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ createMockObservation({+ id: "child1-1",+ name: "Child 1-1",+ parentObservationId: "parent1",+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ createMockObservation({+ id: "child1-2",+ name: "Child 1-2",+ parentObservationId: "parent1",+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ createMockObservation({+ id: "grandchild1-2-1",+ name: "Grandchild 1-2-1",+ parentObservationId: "child1-2",+ startTime: new Date("2024-01-01T00:00:03.000Z"),+ }),+ createMockObservation({+ id: "parent2",+ name: "Parent 2",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:04.000Z"),+ }),+ ];++ const result = nestObservations(observations);++ // Should have 2 root observations+ expect(result.nestedObservations).toHaveLength(2);+ expect(result.hiddenObservationsCount).toBe(0);++ // Check first root (parent1) and its children+ const parent1 = result.nestedObservations.find((o) => o.id === "parent1");+ expect(parent1).toBeDefined();+ expect(parent1?.children).toHaveLength(2);+ expect(parent1?.children[0].id).toBe("child1-1");+ expect(parent1?.children[1].id).toBe("child1-2");++ // Check nested grandchild+ const child12 = parent1?.children[1];+ expect(child12?.children).toHaveLength(1);+ expect(child12?.children[0].id).toBe("grandchild1-2-1");++ // Check second root (parent2) has no children+ const parent2 = result.nestedObservations.find((o) => o.id === "parent2");+ expect(parent2).toBeDefined();+ expect(parent2?.children).toHaveLength(0);+ });+});diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxnew file mode 100644index 0000000000..c2fee71aa3--- /dev/null+++ b/web/src/features/events/components/EventsTable.tsx@@ -0,0 +1,1181 @@+import { api } from "@/src/utils/api";+import { DataTable } from "@/src/components/table/data-table";+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";+import {+ DataTableControlsProvider,+ DataTableControls,+} from "@/src/components/table/data-table-controls";+import { useEffect, useMemo, useState, useRef, useCallback } from "react";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";+import {+ getEventsColumnName,+ observationEventsFilterConfig,+} from "../config/filter-config";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import {+ type ObservationLevelType,+ type FilterState,+ BatchExportTableName,+ type ObservationType,+ TableViewPresetTableName,+ AnnotationQueueObjectType,+ BatchActionType,+ type TimeFilter,+} from "@langfuse/shared";+import { cn } from "@/src/utils/tailwind";+import { LevelColors } from "@/src/components/level-colors";+import { numberFormatter, usdFormatter } from "@/src/utils/numbers";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";+import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";+import { useTableDateRange } from "@/src/hooks/useTableDateRange";+import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";+import { type ScoreAggregate } from "@langfuse/shared";+import TagList from "@/src/features/tag/components/TagList";+import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";+import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";+import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";+import { InfoIcon, PlusCircle } from "lucide-react";+import { UpsertModelFormDrawer } from "@/src/features/models/components/UpsertModelFormDrawer";+import { LocalIsoDate } from "@/src/components/LocalIsoDate";+import { Badge } from "@/src/components/ui/badge";+import { type Row, type RowSelectionState } from "@tanstack/react-table";+import TableIdOrName from "@/src/components/table/table-id";+import { ItemBadge } from "@/src/components/ItemBadge";+import { Skeleton } from "@/src/components/ui/skeleton";+import { PeekViewObservationDetail } from "@/src/components/table/peek/peek-observation-detail";+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useRouter } from "next/router";+import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";+import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";+import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";+import { type TableAction } from "@/src/features/table/types";+import { type DataTablePeekViewProps } from "@/src/components/table/peek";+import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";+import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";+import { MemoizedIOTableCell } from "@/src/components/ui/IOTableCell";++export type EventsTableRow = {+ // Identity fields+ id: string;+ traceId?: string;+ spanId: string;+ parentSpanId?: string;++ // Time fields+ startTime: Date;+ endTime?: Date;+ completionStartTime?: Date;+ timestamp?: Date;++ // Core properties+ type: ObservationType;+ name?: string;+ environment?: string;+ version?: string;+ level?: ObservationLevelType;+ statusMessage?: string;++ // User context+ userId?: string;+ sessionId?: string;++ // Model fields+ providedModelName?: string;+ modelId?: string;+ modelParameters?: string;++ // Prompt fields+ promptId?: string;+ promptName?: string;+ promptVersion?: string;++ // Usage and cost+ usage: {+ inputUsage: number;+ outputUsage: number;+ totalUsage: number;+ };+ usageDetails: Record<string, number>;+ totalCost?: number;+ cost: {+ inputCost?: number;+ outputCost?: number;+ };+ costDetails: Record<string, number>;++ // Performance metrics+ latency?: number;+ timeToFirstToken?: number;++ input?: string;+ output?: string;+ metadata?: unknown;++ // Trace fields+ traceTags?: string[];++ // Scores+ scores: ScoreAggregate;+};++export type EventsTableProps = {+ projectId: string;+};++export default function ObservationsEventsTable({+ projectId,+}: EventsTableProps) {+ const router = useRouter();+ const { viewId } = router.query;++ const { setDetailPageList } = useDetailPageLists();+ const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});+ const { searchQuery, searchType, setSearchQuery, setSearchType } =+ useFullTextSearch();++ const { selectAll, setSelectAll } = useSelectAll(projectId, "observations");++ const [paginationState, setPaginationState] = useQueryParams({+ page: withDefault(NumberParam, 1),+ limit: withDefault(NumberParam, 50),+ });++ const [rowHeight, setRowHeight] = useRowHeightLocalStorage(+ "observations",+ "s",+ );++ const [inputFilterState] = useQueryFilterState(+ // Default type filter - exclude SPAN and EVENT types+ !viewId+ ? [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: [+ "GENERATION",+ "AGENT",+ "TOOL",+ "CHAIN",+ "RETRIEVER",+ "EVALUATOR",+ "EMBEDDING",+ "GUARDRAIL",+ ],+ },+ ]+ : [],+ "generations", // Use "generations" table name for compatibility+ projectId,+ );++ const [orderByState, setOrderByState] = useOrderByState({+ column: "startTime",+ order: "DESC",+ });++ const { timeRange, setTimeRange } = useTableDateRange(projectId);++ // Convert timeRange to absolute date range for compatibility+ const dateRange = useMemo(() => {+ return toAbsoluteTimeRange(timeRange) ?? undefined;+ }, [timeRange]);++ const dateRangeFilter: FilterState = dateRange+ ? [+ {+ column: "startTime",+ type: "datetime",+ operator: ">=",+ value: dateRange.from,+ },+ ...(dateRange.to+ ? [+ {+ column: "startTime",+ type: "datetime",+ operator: "<=",+ value: dateRange.to,+ } as const,+ ]+ : []),+ ]+ : [];++ const oldFilterState = inputFilterState.concat(dateRangeFilter);++ const startTimeFilters = oldFilterState.filter(+ (f) =>+ (f.column === "Start Time" || f.column === "startTime") &&+ f.type === "datetime",+ ) as TimeFilter[];++ const filterOptions = api.events.filterOptions.useQuery(+ {+ projectId,+ startTimeFilter:+ startTimeFilters.length > 0 ? startTimeFilters : undefined,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );++ const newFilterOptions = useMemo(() => {+ const scoreCategories =+ filterOptions.data?.score_categories?.reduce(+ (acc, score) => {+ acc[score.label] = score.values;+ return acc;+ },+ {} as Record<string, string[]>,+ ) || {};++ const scoresNumeric = filterOptions.data?.scores_avg || [];++ return {+ environment: filterOptions.data?.environment ?? [],+ name: filterOptions.data?.name ?? [],+ type: filterOptions.data?.type ?? [],+ level: filterOptions.data?.level ?? [],+ providedModelName: filterOptions.data?.providedModelName ?? [],+ modelId: filterOptions.data?.modelId ?? [],+ promptName: filterOptions.data?.promptName ?? [],+ traceTags: filterOptions.data?.traceTags ?? [],+ userId: filterOptions.data?.userId ?? [],+ sessionId: filterOptions.data?.sessionId ?? [],+ version: filterOptions.data?.version ?? [],+ latency: [],+ timeToFirstToken: [],+ tokensPerSecond: [],+ inputTokens: [],+ outputTokens: [],+ totalTokens: [],+ inputCost: [],+ outputCost: [],+ totalCost: [],+ score_categories: scoreCategories,+ scores_avg: scoresNumeric,+ };+ }, [filterOptions.data]);++ const queryFilter = useSidebarFilterState(+ observationEventsFilterConfig,+ newFilterOptions,+ projectId,+ );++ // Create ref-based wrapper to avoid stale closure when queryFilter updates+ const queryFilterRef = useRef(queryFilter);+ queryFilterRef.current = queryFilter;++ const setFiltersWrapper = useCallback(+ (filters: FilterState) => queryFilterRef.current?.setFilterState(filters),+ [],+ );++ const filterState = queryFilter.filterState.concat(dateRangeFilter);++ const getCountPayload = {+ projectId,+ filter: filterState,+ searchQuery,+ searchType,+ page: 1,+ limit: 1,+ orderBy: null,+ };++ const getAllPayload = {+ ...getCountPayload,+ page: paginationState.page,+ limit: paginationState.limit,+ orderBy: orderByState,+ };++ const observations = api.events.all.useQuery(getAllPayload, {+ refetchOnWindowFocus: true,+ });++ const totalCountQuery = api.events.countAll.useQuery(getCountPayload, {+ refetchOnWindowFocus: true,+ });++ const totalCount = totalCountQuery.data?.totalCount ?? null;++ const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({+ onSuccess: (data) => {+ showSuccessToast({+ title: "Observations added to queue",+ description: `Selected observations will be added to queue "${data.queueName}". This may take a minute.`,+ link: {+ href: `/project/${projectId}/annotation-queues/${data.queueId}`,+ text: `View queue "${data.queueName}"`,+ },+ });+ },+ });++ useEffect(() => {+ if (observations.isSuccess) {+ setDetailPageList(+ "observations",+ observations.data.observations.map((o) => ({+ id: o.id,+ params: o.traceTimestamp+ ? {+ timestamp: o.traceTimestamp.toISOString(),+ traceId: o.traceId || "",+ }+ : undefined,+ })),+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [observations.isSuccess, observations.data]);++ const { scoreColumns, isLoading: isColumnLoading } =+ useScoreColumns<EventsTableRow>({+ scoreColumnKey: "scores",+ projectId,+ filter: scoreFilters.forObservations(),+ fromTimestamp: dateRange?.from,+ });++ const { selectActionColumn } = TableSelectionManager<EventsTableRow>({+ projectId,+ tableName: "observations",+ setSelectedRows,+ });++ const handleAddToAnnotationQueue = async ({+ projectId,+ targetId,+ }: {+ projectId: string;+ targetId: string;+ }) => {+ const selectedObservationIds = Object.keys(selectedRows).filter(+ (observationId) =>+ observations.data?.observations+ .map((o) => o.id)+ .includes(observationId),+ );++ await addToQueueMutation.mutateAsync({+ projectId,+ objectIds: selectedObservationIds,+ objectType: AnnotationQueueObjectType.OBSERVATION,+ queueId: targetId,+ isBatchAction: selectAll,+ query: {+ filter: filterState,+ orderBy: orderByState,+ },+ });+ setSelectedRows({});+ };++ const tableActions: TableAction[] = [+ {+ id: "observation-add-to-annotation-queue",+ type: BatchActionType.Create,+ label: "Add to Annotation Queue",+ description: "Add selected observations to an annotation queue.",+ targetLabel: "Annotation Queue",+ execute: handleAddToAnnotationQueue,+ accessCheck: {+ scope: "annotationQueues:CUD",+ },+ },+ ];++ const columns: LangfuseColumnDef<EventsTableRow>[] = [+ selectActionColumn,+ {+ accessorKey: "startTime",+ id: "startTime",+ header: getEventsColumnName("startTime"),+ size: 150,+ enableHiding: true,+ enableSorting: true,+ cell: ({ row }) => {+ const value: Date = row.getValue("startTime");+ return <LocalIsoDate date={value} />;+ },+ },+ {+ accessorKey: "type",+ id: "type",+ header: getEventsColumnName("type"),+ size: 50,+ enableSorting: true,+ cell: ({ row }) => {+ const value: ObservationType = row.getValue("type");+ return value ? (+ <div className="flex items-center gap-1">+ <ItemBadge type={value} />+ </div>+ ) : undefined;+ },+ },+ {+ accessorKey: "name",+ id: "name",+ header: getEventsColumnName("name"),+ size: 150,+ enableSorting: true,+ cell: ({ row }) => {+ const value: EventsTableRow["name"] = row.getValue("name");+ return value ? (+ <span className="truncate" title={value}>+ {value}+ </span>+ ) : undefined;+ },+ },+ {+ accessorKey: "input",+ header: getEventsColumnName("input"),+ id: "input",+ size: 300,+ cell: ({ row }) => {+ const value: string | undefined = row.getValue("input");+ return value ? (+ <MemoizedIOTableCell+ isLoading={false}+ data={value}+ singleLine={rowHeight === "s"}+ />+ ) : null;+ },+ enableHiding: true,+ },+ {+ accessorKey: "output",+ id: "output",+ header: getEventsColumnName("output"),+ size: 300,+ cell: ({ row }) => {+ const value: string | undefined = row.getValue("output");+ return value ? (+ <MemoizedIOTableCell+ isLoading={false}+ data={value}+ className={cn("bg-accent-light-green")}+ singleLine={rowHeight === "s"}+ />+ ) : null;+ },+ enableHiding: true,+ },+ {+ accessorKey: "level",+ id: "level",+ header: getEventsColumnName("level"),+ size: 100,+ headerTooltip: {+ description:+ "You can differentiate the importance of observations with the level attribute to control the verbosity of your traces and highlight errors and warnings.",+ href: "https://langfuse.com/docs/observability/features/log-levels",+ },+ enableHiding: true,+ cell: ({ row }) => {+ const value: ObservationLevelType | undefined = row.getValue("level");+ return value ? (+ <span+ className={cn(+ "rounded-sm p-0.5 text-xs",+ LevelColors[value].bg,+ LevelColors[value].text,+ )}+ >+ {value}+ </span>+ ) : undefined;+ },+ enableSorting: true,+ },+ {+ accessorKey: "statusMessage",+ header: getEventsColumnName("statusMessage"),+ id: "statusMessage",+ size: 150,+ headerTooltip: {+ description:+ "Use a statusMessage to e.g. provide additional information on a status such as level=ERROR.",+ href: "https://langfuse.com/docs/observability/features/log-levels",+ },+ enableHiding: true,+ defaultHidden: true,+ cell: ({ row }) => {+ const value: string | undefined = row.getValue("statusMessage");+ return value ? (+ <MemoizedIOTableCell+ isLoading={false}+ data={value}+ singleLine={rowHeight === "s"}+ />+ ) : undefined;+ },+ },+ {+ accessorKey: "latency",+ id: "latency",+ header: getEventsColumnName("latency"),+ size: 100,+ cell: ({ row }) => {+ const latency: number | undefined = row.getValue("latency");+ return latency !== undefined ? (+ <span>{formatIntervalSeconds(latency)}</span>+ ) : undefined;+ },+ enableHiding: true,+ enableSorting: true,+ },+ {+ accessorKey: "totalCost",+ header: getEventsColumnName("totalCost"),+ id: "totalCost",+ size: 120,+ cell: ({ row }) => {+ const value: number | undefined = row.getValue("totalCost");++ return value !== undefined ? (+ <BreakdownTooltip details={row.original.costDetails} isCost>+ <div className="flex items-center gap-1">+ <span>{usdFormatter(value)}</span>+ <InfoIcon className="h-3 w-3" />+ </div>+ </BreakdownTooltip>+ ) : undefined;+ },+ enableHiding: true,+ enableSorting: true,+ },+ {+ accessorKey: "cost",+ header: "Cost",+ id: "cost",+ enableHiding: true,+ defaultHidden: true,+ cell: () => {+ return observations.isPending ? (+ <Skeleton className="h-3 w-1/2" />+ ) : null;+ },+ columns: [+ {+ accessorKey: "inputCost",+ id: "inputCost",+ header: getEventsColumnName("inputCost"),+ size: 120,+ cell: ({ row }: { row: Row<EventsTableRow> }) => {+ const value = row.getValue("cost") as {+ inputCost: number | undefined;+ outputCost: number | undefined;+ };++ return value.inputCost !== undefined ? (+ <span>{usdFormatter(value.inputCost)}</span>+ ) : undefined;+ },+ enableHiding: true,+ defaultHidden: true,+ enableSorting: true,+ },+ {+ accessorKey: "outputCost",+ id: "outputCost",+ header: getEventsColumnName("outputCost"),+ size: 120,+ cell: ({ row }: { row: Row<EventsTableRow> }) => {+ const value = row.getValue("cost") as {+ inputCost: number | undefined;+ outputCost: number | undefined;+ };++ return value.outputCost !== undefined ? (+ <span>{usdFormatter(value.outputCost)}</span>+ ) : undefined;+ },+ enableHiding: true,+ defaultHidden: true,+ enableSorting: true,+ },+ ],+ },+ {+ accessorKey: "timeToFirstToken",+ id: "timeToFirstToken",+ header: getEventsColumnName("timeToFirstToken"),+ size: 150,+ enableHiding: true,+ enableSorting: true,+ cell: ({ row }) => {+ const timeToFirstToken: number | undefined =+ row.getValue("timeToFirstToken");++ return (+ <span>+ {timeToFirstToken ? formatIntervalSeconds(timeToFirstToken) : "-"}+ </span>+ );+ },+ },+ {+ accessorKey: "usage",+ header: "Usage",+ id: "usage",+ enableHiding: true,+ defaultHidden: true,+ cell: () => {+ return observations.isPending ? (+ <Skeleton className="h-3 w-1/2" />+ ) : null;+ },+ columns: [+ {+ accessorKey: "tokensPerSecond",+ id: "tokensPerSecond",+ header: "Tokens per second",+ size: 200,+ cell: ({ row }: { row: Row<EventsTableRow> }) => {+ const latency: number | undefined = row.getValue("latency");+ const usage = row.getValue("usage") as {+ inputUsage: number;+ outputUsage: number;+ totalUsage: number;+ };+ return latency !== undefined &&+ (usage.outputUsage !== 0 || usage.totalUsage !== 0) ? (+ <span>+ {usage.outputUsage && latency+ ? Number((usage.outputUsage / latency).toFixed(1))+ : undefined}+ </span>+ ) : undefined;+ },+ defaultHidden: true,+ enableHiding: true,+ enableSorting: true,+ },+ {+ accessorKey: "inputTokens",+ id: "inputTokens",+ header: getEventsColumnName("inputTokens"),+ size: 100,+ enableHiding: true,+ defaultHidden: true,+ enableSorting: true,+ cell: ({ row }: { row: Row<EventsTableRow> }) => {+ const value = row.getValue("usage") as {+ inputUsage: number;+ outputUsage: number;+ totalUsage: number;+ };+ return <span>{numberFormatter(value.inputUsage, 0)}</span>;+ },+ },+ {+ accessorKey: "outputTokens",+ id: "outputTokens",+ header: getEventsColumnName("outputTokens"),+ size: 100,+ enableHiding: true,+ defaultHidden: true,+ enableSorting: true,+ cell: ({ row }: { row: Row<EventsTableRow> }) => {+ const value = row.getValue("usage") as {+ inputUsage: number;+ outputUsage: number;+ totalUsage: number;+ };+ return <span>{numberFormatter(value.outputUsage, 0)}</span>;+ },+ },+ {+ accessorKey: "totalTokens",+ id: "totalTokens",+ header: getEventsColumnName("totalTokens"),+ size: 100,+ enableHiding: true,+ defaultHidden: true,+ enableSorting: true,+ cell: ({ row }: { row: Row<EventsTableRow> }) => {+ const value = row.getValue("usage") as {+ inputUsage: number;+ outputUsage: number;+ totalUsage: number;+ };+ return <span>{numberFormatter(value.totalUsage, 0)}</span>;+ },+ },+ ],+ },+ {+ accessorKey: "providedModelName",+ id: "providedModelName",+ header: getEventsColumnName("providedModelName"),+ size: 150,+ enableHiding: true,+ enableSorting: true,+ cell: ({ row }) => {+ const model = row.getValue("providedModelName") as string;+ const modelId = row.getValue("modelId") as string | undefined;++ if (!model) return null;++ return modelId ? (+ <TableIdOrName value={model} />+ ) : (+ <UpsertModelFormDrawer+ action="create"+ projectId={projectId}+ prefilledModelData={{+ modelName: model,+ prices:+ Object.keys(row.original.usageDetails).length > 0+ ? Object.keys(row.original.usageDetails)+ .filter((key) => key != "total")+ .reduce(+ (acc, key) => {+ acc[key] = 0.000001;+ return acc;+ },+ {} as Record<string, number>,+ )+ : undefined,+ }}+ className="cursor-pointer"+ >+ <span className="flex items-center gap-1">+ <span>{model}</span>+ <PlusCircle className="h-3 w-3" />+ </span>+ </UpsertModelFormDrawer>+ );+ },+ },+ {+ accessorKey: "promptName",+ id: "promptName",+ header: getEventsColumnName("promptName"),+ headerTooltip: {+ description: "Link to prompt version in Langfuse prompt management.",+ href: "https://langfuse.com/docs/prompt-management/get-started",+ },+ size: 200,+ enableHiding: true,+ enableSorting: true,+ cell: ({ row }) => {+ const promptName = row.original.promptName;+ const promptVersion = row.original.promptVersion;+ const value = `${promptName} (v${promptVersion})`;+ return promptName && promptVersion && <TableIdOrName value={value} />;+ },+ },+ {+ accessorKey: "environment",+ header: getEventsColumnName("environment"),+ id: "environment",+ size: 150,+ enableHiding: true,+ cell: ({ row }) => {+ const value: EventsTableRow["environment"] =+ row.getValue("environment");+ return value ? (+ <Badge+ variant="secondary"+ className="max-w-fit truncate rounded-sm px-1 font-normal"+ >+ {value}+ </Badge>+ ) : null;+ },+ },+ {+ accessorKey: "traceTags",+ id: "traceTags",+ header: getEventsColumnName("traceTags"),+ size: 250,+ enableHiding: true,+ cell: ({ row }) => {+ const traceTags: string[] | undefined = row.getValue("traceTags");+ return (+ traceTags && (+ <div+ className={cn(+ "flex gap-x-2 gap-y-1",+ rowHeight !== "s" && "flex-wrap",+ )}+ >+ <TagList selectedTags={traceTags} isLoading={false} />+ </div>+ )+ );+ },+ },+ {+ accessorKey: "scores",+ header: "Scores",+ id: "scores",+ enableHiding: true,+ defaultHidden: true,+ cell: () => {+ return isColumnLoading ? <Skeleton className="h-3 w-1/2" /> : null;+ },+ columns: scoreColumns,+ },+ {+ accessorKey: "endTime",+ id: "endTime",+ header: getEventsColumnName("endTime"),+ size: 150,+ enableHiding: true,+ enableSorting: true,+ defaultHidden: true,+ cell: ({ row }) => {+ const value: Date | undefined = row.getValue("endTime");+ return value ? <LocalIsoDate date={value} /> : undefined;+ },+ },+ {+ accessorKey: "traceId",+ id: "traceId",+ header: getEventsColumnName("traceId"),+ size: 100,+ cell: ({ row }) => {+ const value = row.getValue("traceId");+ return typeof value === "string" ? (+ <TableIdOrName value={value} />+ ) : undefined;+ },+ enableSorting: true,+ enableHiding: true,+ defaultHidden: true,+ },+ {+ accessorKey: "modelId",+ id: "modelId",+ header: getEventsColumnName("modelId"),+ size: 100,+ enableHiding: true,+ defaultHidden: true,+ },+ {+ accessorKey: "version",+ id: "version",+ header: getEventsColumnName("version"),+ size: 100,+ headerTooltip: {+ description: "Track changes via the version tag.",+ href: "https://langfuse.com/docs/experimentation",+ },+ enableHiding: true,+ enableSorting: true,+ defaultHidden: true,+ },+ {+ accessorKey: "userId",+ id: "userId",+ header: getEventsColumnName("userId"),+ size: 150,+ enableHiding: true,+ defaultHidden: true,+ },+ {+ accessorKey: "sessionId",+ id: "sessionId",+ header: getEventsColumnName("sessionId"),+ size: 150,+ enableHiding: true,+ defaultHidden: true,+ },+ ];++ const [columnVisibility, setColumnVisibilityState] =+ useColumnVisibility<EventsTableRow>(+ `eventsColumnVisibility-${projectId}`,+ columns,+ );++ const [columnOrder, setColumnOrder] = useColumnOrder<EventsTableRow>(+ `eventsColumnOrder-${projectId}`,+ columns,+ );++ const peekNavigationProps = usePeekNavigation({+ queryParams: ["observation", "display", "timestamp", "traceId"],+ paramsToMirrorPeekValue: ["observation"],+ extractParamsValuesFromRow: (row: EventsTableRow) => ({+ traceId: row.traceId || "",+ timestamp: row.timestamp?.toISOString() || "",+ }),+ expandConfig: {+ basePath: `/project/${projectId}/traces`,+ pathParam: "traceId",+ },+ });++ const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({+ tableName: TableViewPresetTableName.Observations,+ projectId,+ stateUpdaters: {+ setOrderBy: setOrderByState,+ setFilters: setFiltersWrapper,+ setColumnOrder: setColumnOrder,+ setColumnVisibility: setColumnVisibilityState,+ setSearchQuery: setSearchQuery,+ },+ validationContext: {+ columns,+ filterColumnDefinition: observationEventsFilterConfig.columnDefinitions,+ },+ currentFilterState: queryFilter.filterState,+ });++ const peekConfig: DataTablePeekViewProps = useMemo(+ () => ({+ itemType: "TRACE",+ customTitlePrefix: "Observation ID:",+ detailNavigationKey: "observations",+ children: <PeekViewObservationDetail projectId={projectId} />,+ tableDataUpdatedAt: observations.dataUpdatedAt,+ ...peekNavigationProps,+ }),+ [projectId, observations.dataUpdatedAt, peekNavigationProps],+ );++ const rows: EventsTableRow[] = useMemo(() => {+ return observations.isSuccess+ ? observations.data.observations.map((observation) => {+ return {+ id: observation.id,+ traceId: observation.traceId ?? undefined,+ type: observation.type ?? undefined,+ spanId: observation.id, // span_id maps to id+ parentSpanId: observation.parentObservationId ?? undefined,+ startTime: observation.startTime,+ endTime: observation.endTime ?? undefined,+ timeToFirstToken: observation.timeToFirstToken ?? undefined,+ scores: {}, // TODO: scores not included in FullObservation type+ latency: observation.latency ?? undefined,+ totalCost: observation.totalCost ?? undefined,+ cost: {+ inputCost: observation.inputCost ?? undefined,+ outputCost: observation.outputCost ?? undefined,+ },+ name: observation.name ?? undefined,+ version: observation.version ?? "",+ providedModelName: observation.model ?? "",+ modelId: observation.internalModelId ?? undefined,+ level: observation.level,+ statusMessage: observation.statusMessage ?? undefined,+ usage: {+ inputUsage: observation.inputUsage,+ outputUsage: observation.outputUsage,+ totalUsage: observation.totalUsage,+ },+ promptId: observation.promptId ?? undefined,+ promptName: observation.promptName ?? undefined,+ promptVersion: observation.promptVersion?.toString() ?? undefined,+ traceTags: observation.traceTags ?? undefined,+ timestamp: observation.traceTimestamp ?? undefined,+ usageDetails: observation.usageDetails ?? {},+ costDetails: observation.costDetails ?? {},+ environment: observation.environment ?? undefined,+ input: observation.input+ ? typeof observation.input === "string"+ ? observation.input+ : JSON.stringify(observation.input)+ : undefined,+ output: observation.output+ ? typeof observation.output === "string"+ ? observation.output+ : JSON.stringify(observation.output)+ : undefined,+ metadata: observation.metadata,+ userId: undefined, // TODO: map from observation data+ sessionId: undefined, // TODO: map from observation data+ completionStartTime: observation.completionStartTime ?? undefined,+ };+ })+ : [];+ }, [observations]);++ return (+ <DataTableControlsProvider>+ <div className="flex h-full w-full flex-col">+ {/* Toolbar spanning full width */}+ <DataTableToolbar+ columns={columns}+ filterState={queryFilter.filterState}+ searchConfig={{+ metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],+ updateQuery: setSearchQuery,+ currentQuery: searchQuery ?? undefined,+ searchType,+ setSearchType,+ tableAllowsFullTextSearch: true,+ }}+ viewConfig={{+ tableName: TableViewPresetTableName.Observations,+ projectId,+ controllers: viewControllers,+ }}+ columnsWithCustomSelect={["providedModelName", "name", "promptName"]}+ columnVisibility={columnVisibility}+ setColumnVisibility={setColumnVisibilityState}+ columnOrder={columnOrder}+ setColumnOrder={setColumnOrder}+ orderByState={orderByState}+ rowHeight={rowHeight}+ setRowHeight={setRowHeight}+ timeRange={timeRange}+ setTimeRange={setTimeRange}+ actionButtons={[+ <BatchExportTableButton+ {...{+ projectId,+ filterState,+ orderByState,+ searchQuery,+ searchType,+ }}+ tableName={BatchExportTableName.Observations}+ key="batchExport"+ />,+ Object.keys(selectedRows).filter((observationId) =>+ observations.data?.observations+ .map((o) => o.id)+ .includes(observationId),+ ).length > 0 ? (+ <TableActionMenu+ key="observations-multi-select-actions"+ projectId={projectId}+ actions={tableActions}+ tableName={BatchExportTableName.Observations}+ />+ ) : null,+ ]}+ multiSelect={{+ selectAll,+ setSelectAll,+ selectedRowIds: Object.keys(selectedRows).filter((observationId) =>+ observations.data?.observations+ .map((o) => o.id)+ .includes(observationId),+ ),+ setRowSelection: setSelectedRows,+ totalCount,+ pageSize: paginationState.limit,+ pageIndex: paginationState.page - 1,+ }}+ />++ {/* Content area with sidebar and table */}+ <div className="flex flex-1 overflow-hidden">+ <DataTableControls queryFilter={queryFilter} />++ <div className="flex flex-1 flex-col overflow-hidden">+ <DataTable+ tableName={"observations"}+ columns={columns}+ peekView={peekConfig}+ data={+ observations.isPending || isViewLoading+ ? { isLoading: true, isError: false }+ : observations.error+ ? {+ isLoading: false,+ isError: true,+ error: observations.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: rows,+ }+ }+ pagination={{+ totalCount,+ onChange: (updater) => {+ const newState =+ typeof updater === "function"+ ? updater({+ pageIndex: paginationState.page - 1,+ pageSize: paginationState.limit,+ })+ : updater;+ setPaginationState({+ page: newState.pageIndex + 1,+ limit: newState.pageSize,+ });+ },+ state: {+ pageIndex: paginationState.page - 1,+ pageSize: paginationState.limit,+ },+ }}+ rowSelection={selectedRows}+ setRowSelection={setSelectedRows}+ setOrderBy={setOrderByState}+ orderBy={orderByState}+ columnOrder={columnOrder}+ onColumnOrderChange={setColumnOrder}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={setColumnVisibilityState}+ rowHeight={rowHeight}+ onRowClick={(row, event) => {+ // Handle Command/Ctrl+click to open observation in new tab+ if (event && (event.metaKey || event.ctrlKey)) {+ // Prevent the default peek behavior+ event.preventDefault();++ // Construct the observation URL directly to avoid race conditions+ const observationId = row.id;+ const traceId = row.traceId;+ const timestamp = row.timestamp;++ if (traceId) {+ let observationUrl = `/project/${projectId}/traces/${encodeURIComponent(traceId)}`;++ const params = new URLSearchParams();+ params.set("observation", observationId);+ if (timestamp) {+ params.set("timestamp", timestamp.toISOString());+ }++ observationUrl += `?${params.toString()}`;++ const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${observationUrl}`;+ window.open(fullUrl, "_blank");+ }+ }+ // For normal clicks, let the data-table handle opening the peek view+ }}+ />+ </div>+ </div>+ </div>+ </DataTableControlsProvider>+ );+}diff --git a/web/src/features/events/components/index.ts b/web/src/features/events/components/index.tsnew file mode 100644index 0000000000..45cb6542ee--- /dev/null+++ b/web/src/features/events/components/index.ts@@ -0,0 +1 @@+export { default as ObservationsEventsTable } from "./EventsTable";diff --git a/web/src/features/events/config/filter-config.ts b/web/src/features/events/config/filter-config.tsnew file mode 100644index 0000000000..d407a9ff33--- /dev/null+++ b/web/src/features/events/config/filter-config.ts@@ -0,0 +1,204 @@+import { eventsTableCols } from "@langfuse/shared";+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import type { ColumnToQueryKeyMap } from "@/src/features/filters/lib/filter-query-encoding";+import type { ColumnToBackendKeyMap } from "@/src/features/filters/lib/filter-transform";++// Helper function to get column name from eventsTableCols by ID+export const getEventsColumnName = (id: string): string => {+ const column = eventsTableCols.find((col) => col.id === id);+ if (!column) {+ throw new Error(`Column ${id} not found in eventsTableCols`);+ }+ return column?.name;+};++const OBSERVATION_EVENTS_COLUMN_TO_QUERY_KEY: ColumnToQueryKeyMap = {+ environment: "environment",+ name: "name",+ type: "type",+ traceName: "traceName",+ level: "level",+ providedModelName: "providedModelName",+ modelId: "modelId",+ promptName: "promptName",+ traceTags: "traceTags",+ metadata: "metadata",+ version: "version",+ timeToFirstToken: "timeToFirstToken",+ latency: "latency",+ tokensPerSecond: "tokensPerSecond",+ inputCost: "inputCost",+ outputCost: "outputCost",+ totalCost: "totalCost",+ inputTokens: "inputTokens",+ outputTokens: "outputTokens",+ totalTokens: "totalTokens",+ score_categories: "score_categories",+ scores_avg: "scores_avg",+ spanId: "spanId",+ parentSpanId: "parentSpanId",+ traceId: "traceId",+ userId: "userId",+ sessionId: "sessionId",+ statusMessage: "statusMessage",+ completionStartTime: "completionStartTime",+ promptId: "promptId",+ promptVersion: "promptVersion",+};++/**+ * Maps frontend column IDs to backend-expected column IDs for events table+ * Events table uses different naming conventions than observations table+ */+export const OBSERVATION_EVENTS_COLUMN_TO_BACKEND_KEY: ColumnToBackendKeyMap = {+ // No mapping needed currently - events table column names align with UI+};++export const observationEventsFilterConfig: FilterConfig = {+ tableName: "observations-events",++ columnToQueryKey: OBSERVATION_EVENTS_COLUMN_TO_QUERY_KEY,++ columnDefinitions: eventsTableCols,++ defaultExpanded: ["environment", "name"],++ facets: [+ {+ type: "categorical" as const,+ column: "environment",+ label: getEventsColumnName("environment"),+ },+ {+ type: "categorical" as const,+ column: "type",+ label: getEventsColumnName("type"),+ },+ {+ type: "categorical" as const,+ column: "name",+ label: getEventsColumnName("name"),+ },+ {+ type: "categorical" as const,+ column: "level",+ label: getEventsColumnName("level"),+ },+ {+ type: "categorical" as const,+ column: "providedModelName",+ label: getEventsColumnName("providedModelName"),+ },+ {+ type: "categorical" as const,+ column: "modelId",+ label: getEventsColumnName("modelId"),+ },+ {+ type: "categorical" as const,+ column: "promptName",+ label: getEventsColumnName("promptName"),+ },+ {+ type: "categorical" as const,+ column: "traceTags",+ label: getEventsColumnName("traceTags"),+ },+ {+ type: "stringKeyValue" as const,+ column: "metadata",+ label: getEventsColumnName("metadata"),+ },+ {+ type: "categorical" as const,+ column: "version",+ label: getEventsColumnName("version"),+ },+ {+ type: "string" as const,+ column: "statusMessage",+ label: getEventsColumnName("statusMessage"),+ },+ {+ type: "categorical" as const,+ column: "userId",+ label: getEventsColumnName("userId"),+ },+ {+ type: "categorical" as const,+ column: "sessionId",+ label: getEventsColumnName("sessionId"),+ },+ {+ type: "numeric" as const,+ column: "latency",+ label: getEventsColumnName("latency"),+ min: 0,+ max: 60,+ unit: "s",+ },+ {+ type: "numeric" as const,+ column: "timeToFirstToken",+ label: getEventsColumnName("timeToFirstToken"),+ min: 0,+ max: 60,+ unit: "s",+ },+ {+ type: "numeric" as const,+ column: "inputTokens",+ label: getEventsColumnName("inputTokens"),+ min: 0,+ max: 1000000,+ },+ {+ type: "numeric" as const,+ column: "outputTokens",+ label: getEventsColumnName("outputTokens"),+ min: 0,+ max: 1000000,+ },+ {+ type: "numeric" as const,+ column: "totalTokens",+ label: getEventsColumnName("totalTokens"),+ min: 0,+ max: 1000000,+ },+ {+ type: "numeric" as const,+ column: "inputCost",+ label: getEventsColumnName("inputCost"),+ min: 0,+ max: 100,+ unit: "$",+ },+ {+ type: "numeric" as const,+ column: "outputCost",+ label: getEventsColumnName("outputCost"),+ min: 0,+ max: 100,+ unit: "$",+ },+ {+ type: "numeric" as const,+ column: "totalCost",+ label: getEventsColumnName("totalCost"),+ min: 0,+ max: 100,+ unit: "$",+ },+ {+ type: "keyValue" as const,+ column: "score_categories",+ label: "Categorical Scores",+ },+ {+ type: "numericKeyValue" as const,+ column: "scores_avg",+ label: "Numeric Scores",+ },+ ],+};diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsnew file mode 100644index 0000000000..7a7272244a--- /dev/null+++ b/web/src/features/events/server/eventsRouter.ts@@ -0,0 +1,59 @@+import { type z } from "zod/v4";+import { z as zodSchema } from "zod/v4";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { paginationZod, timeFilter } from "@langfuse/shared";+import { EventsTableOptions } from "./types";+import {+ getEventList,+ getEventCount,+ getEventFilterOptions,+} from "./eventsService";++const GetAllEventsInput = EventsTableOptions.extend({+ ...paginationZod,+});++export type GetAllEventsInput = z.infer<typeof GetAllEventsInput>;++export const eventsRouter = createTRPCRouter({+ all: protectedProjectProcedure+ .input(GetAllEventsInput)+ .query(async ({ input, ctx }) => {+ return getEventList({+ projectId: ctx.session.projectId,+ filter: input.filter ?? [],+ searchQuery: input.searchQuery ?? undefined,+ searchType: input.searchType,+ orderBy: input.orderBy,+ page: input.page,+ limit: input.limit,+ });+ }),+ countAll: protectedProjectProcedure+ .input(GetAllEventsInput)+ .query(async ({ input, ctx }) => {+ return getEventCount({+ projectId: ctx.session.projectId,+ filter: input.filter ?? [],+ searchQuery: input.searchQuery ?? undefined,+ searchType: input.searchType,+ orderBy: input.orderBy,+ });+ }),+ filterOptions: protectedProjectProcedure+ .input(+ zodSchema.object({+ projectId: zodSchema.string(),+ startTimeFilter: zodSchema.array(timeFilter).optional(),+ }),+ )+ .query(async ({ input }) => {+ return getEventFilterOptions({+ projectId: input.projectId,+ startTimeFilter: input.startTimeFilter,+ });+ }),+});diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsnew file mode 100644index 0000000000..e8a7d51193--- /dev/null+++ b/web/src/features/events/server/eventsService.ts@@ -0,0 +1,206 @@+import { type z } from "zod/v4";+import {+ getObservationsCountFromEventsTable,+ getObservationsWithModelDataFromEventsTable,+ getCategoricalScoresGroupedByName,+ getEventsGroupedByModel,+ getEventsGroupedByModelId,+ getEventsGroupedByName,+ getEventsGroupedByPromptName,+ getEventsGroupedByType,+ getEventsGroupedByUserId,+ getEventsGroupedByVersion,+ getEventsGroupedBySessionId,+ getEventsGroupedByLevel,+ getEventsGroupedByEnvironment,+ getNumericScoresGroupedByName,+ getTracesGroupedByTags,+} from "@langfuse/shared/src/server";+import { type timeFilter } from "@langfuse/shared";++type TimeFilter = z.infer<typeof timeFilter>;++interface GetObservationsListParams {+ projectId: string;+ filter: any[];+ searchQuery?: string;+ searchType: any[];+ orderBy: any;+ page: number;+ limit: number;+}++interface GetObservationsCountParams {+ projectId: string;+ filter: any[];+ searchQuery?: string;+ searchType: any[];+ orderBy: any;+}++interface GetObservationsFilterOptionsParams {+ projectId: string;+ startTimeFilter?: TimeFilter[];+}++/**+ * Get paginated list of events+ */+export async function getEventList(params: GetObservationsListParams) {+ const queryOpts = {+ projectId: params.projectId,+ filter: params.filter,+ searchQuery: params.searchQuery,+ searchType: params.searchType,+ orderBy: params.orderBy,+ limit: params.limit,+ offset: params.page * params.limit,+ selectIOAndMetadata: true, // Include input/output truncated fields+ };++ const observations =+ await getObservationsWithModelDataFromEventsTable(queryOpts);++ return { observations };+}++/**+ * Get total count of events matching filters+ */+export async function getEventCount(params: GetObservationsCountParams) {+ const queryOpts = {+ projectId: params.projectId,+ filter: params.filter,+ searchQuery: params.searchQuery,+ searchType: params.searchType,+ orderBy: params.orderBy,+ limit: 1,+ offset: 0,+ };++ const totalCount = await getObservationsCountFromEventsTable(queryOpts);++ return { totalCount };+}++/**+ * Get all available filter options for events table+ */+export async function getEventFilterOptions(+ params: GetObservationsFilterOptionsParams,+) {+ const { projectId, startTimeFilter } = params;++ // Map startTimeFilter to Timestamp column for trace queries+ const traceTimestampFilters =+ startTimeFilter && startTimeFilter.length > 0+ ? startTimeFilter.map((f) => ({+ column: "Timestamp" as const,+ operator: f.operator,+ value: f.value,+ type: "datetime" as const,+ }))+ : [];++ const getClickhouseTraceTags = async (): Promise<Array<{ tag: string }>> => {+ const traces = await getTracesGroupedByTags({+ projectId,+ filter: traceTimestampFilters,+ });+ return traces.map((i) => ({ tag: i.value }));+ };++ const [+ numericScoreNames,+ categoricalScoreNames,+ providedModelName,+ name,+ promptNames,+ traceTags,+ modelId,+ types,+ userIds,+ versions,+ sessionIds,+ levels,+ environments,+ ] = await Promise.all([+ getNumericScoresGroupedByName(projectId, traceTimestampFilters),+ getCategoricalScoresGroupedByName(projectId, traceTimestampFilters),+ getEventsGroupedByModel(projectId, startTimeFilter ?? []),+ getEventsGroupedByName(projectId, startTimeFilter ?? []),+ getEventsGroupedByPromptName(projectId, startTimeFilter ?? []),+ getClickhouseTraceTags(),+ getEventsGroupedByModelId(projectId, startTimeFilter ?? []),+ getEventsGroupedByType(projectId, startTimeFilter ?? []),+ getEventsGroupedByUserId(projectId, startTimeFilter ?? []),+ getEventsGroupedByVersion(projectId, startTimeFilter ?? []),+ getEventsGroupedBySessionId(projectId, startTimeFilter ?? []),+ getEventsGroupedByLevel(projectId, startTimeFilter ?? []),+ getEventsGroupedByEnvironment(projectId, startTimeFilter ?? []),+ ]);++ return {+ providedModelName: providedModelName+ .filter((i) => i.model !== null)+ .map((i) => ({ value: i.model as string, count: i.count })),+ modelId: modelId+ .filter((i) => i.modelId !== null)+ .map((i) => ({+ value: i.modelId as string,+ count: i.count,+ })),+ name: name+ .filter((i) => i.name !== null)+ .map((i) => ({ value: i.name as string, count: i.count })),+ scores_avg: numericScoreNames.map((score) => score.name),+ score_categories: categoricalScoreNames,+ promptName: promptNames+ .filter((i) => i.promptName !== null)+ .map((i) => ({+ value: i.promptName as string,+ count: i.count,+ })),+ traceTags: traceTags+ .filter((i) => i.tag !== null)+ .map((i) => ({+ value: i.tag as string,+ })),+ type: types+ .filter((i) => i.type !== null)+ .map((i) => ({+ value: i.type as string,+ count: i.count,+ })),+ userId: userIds+ .filter((i) => i.userId !== null)+ .map((i) => ({+ value: i.userId as string,+ count: i.count,+ })),+ version: versions+ .filter((i) => i.version !== null)+ .map((i) => ({+ value: i.version as string,+ count: i.count,+ })),+ sessionId: sessionIds+ .filter((i) => i.sessionId !== null)+ .map((i) => ({+ value: i.sessionId as string,+ count: i.count,+ })),+ level: levels+ .filter((i) => i.level !== null)+ .map((i) => ({+ value: i.level as string,+ count: i.count,+ })),+ environment: environments+ .filter((i) => i.environment !== null)+ .map((i) => ({+ value: i.environment as string,+ count: i.count,+ })),+ };+}diff --git a/web/src/features/events/server/types.ts b/web/src/features/events/server/types.tsnew file mode 100644index 0000000000..2618a19411--- /dev/null+++ b/web/src/features/events/server/types.ts@@ -0,0 +1,10 @@+import { z } from "zod/v4";+import { singleFilter, TracingSearchType, orderBy } from "@langfuse/shared";++export const EventsTableOptions = z.object({+ projectId: z.string(), // Required for protectedProjectProcedure+ filter: z.array(singleFilter),+ searchQuery: z.string().nullable(),+ searchType: z.array(TracingSearchType),+ orderBy: orderBy,+});diff --git a/web/src/pages/project/[projectId]/observations/new.tsx b/web/src/pages/project/[projectId]/observations/new.tsxnew file mode 100644index 0000000000..395626ba5d--- /dev/null+++ b/web/src/pages/project/[projectId]/observations/new.tsx@@ -0,0 +1,57 @@+import React from "react";+import { useRouter } from "next/router";+import ObservationsEventsTable from "@/src/features/events/components/EventsTable";+import Page from "@/src/components/layouts/page";+import { api } from "@/src/utils/api";+import { TracesOnboarding } from "@/src/components/onboarding/TracesOnboarding";+import {+ getTracingTabs,+ TRACING_TABS,+} from "@/src/features/navigation/utils/tracing-tabs";++export default function Events() {+ const router = useRouter();+ const projectId = router.query.projectId as string;++ // Check if the user has tracing configured+ const { data: hasTracingConfigured, isLoading } =+ api.traces.hasTracingConfigured.useQuery(+ { projectId },+ {+ enabled: !!projectId,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchInterval: 10_000,+ },+ );++ const showOnboarding = !isLoading && !hasTracingConfigured;++ return (+ <Page+ headerProps={{+ title: "Tracing - Events Table (New)",+ help: {+ description:+ "An observation captures a single function call in an application. This view uses the new ClickHouse events table.",+ href: "https://langfuse.com/docs/observability/data-model",+ },+ tabsProps: {+ tabs: getTracingTabs(projectId),+ activeTab: TRACING_TABS.OBSERVATIONS,+ },+ }}+ scrollable={showOnboarding}+ >+ {/* Show onboarding screen if user has no traces */}+ {showOnboarding ? (+ <TracesOnboarding projectId={projectId} />+ ) : (+ <ObservationsEventsTable projectId={projectId} />+ )}+ </Page>+ );+}diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 71f07aa82d..0463e0726e 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -1,6 +1,7 @@import { createTRPCRouter } from "@/src/server/api/trpc";import { traceRouter } from "./routers/traces";import { generationsRouter } from "./routers/generations";+import { eventsRouter } from "@/src/features/events/server/eventsRouter";import { scoresRouter } from "./routers/scores";import { dashboardRouter } from "@/src/features/dashboard/server/dashboard-router";import { projectsRouter } from "@/src/features/projects/server/projectsRouter";@@ -64,6 +65,7 @@ export const appRouter = createTRPCRouter({traces: traceRouter,sessions: sessionRouter,generations: generationsRouter,+ events: eventsRouter,scores: scoresRouter,scoreConfigs: scoreConfigsRouter,dashboard: dashboardRouter,