Skip to content

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

feat(api): public api v2 basic functionality (#10465)

Valery Meleshkine25e32ced893
diff --git a/packages/shared/src/domain/observations.ts b/packages/shared/src/domain/observations.ts
index ea759568a4..bde0205e09 100644
--- a/packages/shared/src/domain/observations.ts
+++ b/packages/shared/src/domain/observations.ts
@@ -94,6 +94,11 @@ export const ObservationSchema = z.object({
export type Observation = z.infer<typeof ObservationSchema>;
+export type ObservationCoreFields = Pick<
+ Observation,
+ "id" | "traceId" | "startTime" | "projectId" | "parentObservationId"
+>;
+
export const EventsObservationSchema = ObservationSchema.extend({
userId: z.string().nullable(),
sessionId: z.string().nullable(),
@@ -101,11 +106,16 @@ export const EventsObservationSchema = ObservationSchema.extend({
export type EventsObservation = z.infer<typeof EventsObservationSchema>;
+export type PartialObservation = Partial<Observation> & ObservationCoreFields;
+
+export type PartialEventsObservation = Partial<EventsObservation> &
+ ObservationCoreFields;
+
/**
* Returns true if an observation type is generation-like, meaning it could include LLM calls
* and potentially has similar input/output fields.
*/
-export const GenerationLikeObservationTypes = [
+const GenerationLikeObservationTypes = [
ObservationType.GENERATION,
ObservationType.AGENT,
ObservationType.TOOL,
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.ts
index 762a3b2e68..02f9147516 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
@@ -134,8 +134,43 @@ const FIELD_SETS = {
],
byIdPrompt: ["promptId", "promptName", "promptVersion"],
byIdTimestamps: ["createdAt", "updatedAt", "eventTs"],
+
+ // Public API v2 field sets (field groups for selective fetching)
+ core: [
+ "id",
+ "traceId",
+ "startTime",
+ "endTime",
+ "projectId",
+ "parentObservationId",
+ "type",
+ ],
+ basic: [
+ "name",
+ "level",
+ "statusMessage",
+ "version",
+ "environment",
+ "bookmarked",
+ "public",
+ "userId",
+ "sessionId",
+ ],
+ time: ["completionStartTime", "createdAt", "updatedAt"],
+ model: ["providedModelName", "internalModelId", "modelParameters"],
+ usage: [
+ "usageDetails",
+ "costDetails",
+ "totalCost",
+ "providedUsageDetails",
+ "providedCostDetails",
+ ],
+ prompt: ["promptId", "promptName", "promptVersion"],
+ metrics: ["latency", "timeToFirstToken"],
} as const;
+export type FieldSetName = keyof typeof FIELD_SETS;
+
/**
* Aggregation fields for trace-level queries
* These fields use ClickHouse aggregation functions and require GROUP BY
@@ -260,10 +295,13 @@ abstract class AbstractQueryBuilder {
* Add LIMIT and OFFSET
*/
limit(limit?: number, offset?: number): this {
- if (limit !== undefined && offset !== undefined) {
+ if (limit !== undefined && offset !== undefined && offset > 0) {
this.limitClause = "LIMIT {limit: Int32} OFFSET {offset: Int32}";
this.params.limit = limit;
this.params.offset = offset;
+ } else if (limit !== undefined) {
+ this.limitClause = "LIMIT {limit: Int32}";
+ this.params.limit = limit;
} else {
this.limitClause = "";
}
@@ -480,7 +518,7 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
/**
* Add SELECT fields from predefined field sets
*/
- selectFieldSet(...setNames: Array<keyof typeof FIELD_SETS>): this {
+ selectFieldSet(...setNames: Array<FieldSetName>): this {
setNames
.flatMap((s) => {
return FIELD_SETS[s];
diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.ts
index 7589b99fd4..49222b066d 100644
--- a/packages/shared/src/server/queries/createGenerationsQuery.ts
+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts
@@ -1,5 +1,9 @@
import Decimal from "decimal.js";
-import { Observation, EventsObservation } from "../../domain";
+import {
+ type Observation,
+ type EventsObservation,
+ type ObservationCoreFields,
+} from "../../domain";
export type ObservationPriceFields = {
inputPrice: Decimal | null;
@@ -26,3 +30,10 @@ export type FullEventsObservation = AdditionalObservationFields &
EventsObservation;
export type FullEventsObservations = Array<FullEventsObservation>;
+
+// Public API version of EventsObservation, some fields are omitted because
+// V2 allows clients to specify fields
+export type EventsObservationPublic = Partial<
+ EventsObservation & ObservationPriceFields
+> &
+ ObservationCoreFields;
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index ecc5df738e..d0c88f1e49 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -34,6 +34,7 @@ import {
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
eventsTableLegacyTraceUiColumnDefinitions,
+ eventsTableNativeUiColumnDefinitions,
eventsTableUiColumnDefinitions,
} from "../tableMappings/mapEventsTable";
import { tracesTableUiColumnDefinitions } from "../tableMappings/mapTracesTable";
@@ -45,14 +46,16 @@ import {
ObservationTableQuery,
} from "./observations";
import {
- convertObservation,
convertEventsObservation,
+ convertObservation,
} from "./observations_converters";
import {
EventsQueryBuilder,
CTEQueryBuilder,
EventsAggQueryBuilder,
} from "../queries/clickhouse-sql/event-query-builder";
+import { type EventsObservationPublic } from "../queries/createGenerationsQuery";
+import { UiColumnMappings } from "../../tableDefinitions";
type ObservationsTableQueryResultWitouhtTraceFields = Omit<
ObservationsTableQueryResult,
@@ -62,42 +65,101 @@ type ObservationsTableQueryResultWitouhtTraceFields = Omit<
/**
* Internal helper: enrich observations with model pricing data
* Uses events-specific converter to include userId and sessionId
+ * Supports both V1 (complete observations) and V2 (partial observations with field groups)
+ *
+ * @param observationRecords - Raw observation records from ClickHouse
+ * @param projectId - Project ID for model lookup
+ * @param parseIoAsJson - Whether to parse input/output as JSON
+ * @param requestedFields - Field groups for V2 API (null = V1 API, returns complete observations)
*/
-const enrichObservationsWithModelData = async (
+async function enrichObservationsWithModelData(
+ // eslint-disable-next-line no-unused-vars
+ observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,
+ projectId: string, // eslint-disable-line no-unused-vars
+ parseIoAsJson: boolean, // eslint-disable-line no-unused-vars
+ requestedFields: ObservationFieldGroup[], // eslint-disable-line no-unused-vars
+): Promise<Array<EventsObservationPublic>>;
+async function enrichObservationsWithModelData(
+ // eslint-disable-next-line no-unused-vars
+ observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,
+ projectId: string, // eslint-disable-line no-unused-vars
+ parseIoAsJson: boolean, // eslint-disable-line no-unused-vars
+ requestedFields: null, // eslint-disable-line no-unused-vars
+): Promise<Array<EventsObservation & ObservationPriceFields>>;
+async function enrichObservationsWithModelData(
observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,
projectId: string,
-): Promise<Array<EventsObservation & ObservationPriceFields>> => {
- const uniqueModels: string[] = Array.from(
- new Set(
- observationRecords
- .map((r) => r.internal_model_id)
- .filter((r): r is string => Boolean(r)),
- ),
- );
-
- const models =
- uniqueModels.length > 0
- ? await prisma.model.findMany({
- where: {
- id: {
- in: uniqueModels,
- },
- OR: [{ projectId: projectId }, { projectId: null }],
- },
- include: {
- Price: true,
- },
- })
- : [];
+ parseIoAsJson: boolean,
+ requestedFields: ObservationFieldGroup[] | null,
+): Promise<
+ Array<(EventsObservation & ObservationPriceFields) | EventsObservationPublic>
+> {
+ // Determine if this is V1 (complete) or V2 (partial) API
+ const isV2 = Array.isArray(requestedFields);
+
+ // Determine if model enrichment is needed
+ // V1 API: always enrich
+ // V2 API: only enrich if "model" field group is requested
+ const shouldEnrichModel = !isV2 || requestedFields.includes("model");
+
+ // Fetch model data if needed
+ const models = shouldEnrichModel
+ ? await (async () => {
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ observationRecords
+ .map((r) => r.internal_model_id)
+ .filter((r): r is string => Boolean(r)),
+ ),
+ );
+
+ return uniqueModels.length > 0
+ ? await prisma.model.findMany({
+ where: {
+ id: {
+ in: uniqueModels,
+ },
+ OR: [{ projectId: projectId }, { projectId: null }],
+ },
+ include: {
+ Price: true,
+ },
+ })
+ : [];
+ })()
+ : [];
return observationRecords.map((o) => {
- const model = models.find((m) => m.id === o.internal_model_id);
- return {
- ...convertEventsObservation(o),
- latency: o.latency ? Number(o.latency) / 1000 : null,
- timeToFirstToken: o.time_to_first_token
- ? Number(o.time_to_first_token) / 1000
- : null,
+ const model = shouldEnrichModel
+ ? models.find((m) => m.id === o.internal_model_id)
+ : null;
+
+ const renderingProps = {
+ shouldJsonParse: parseIoAsJson,
+ truncated: false,
+ };
+
+ // Branch based on API version to use correct overload
+ const converted = isV2
+ ? convertEventsObservation(o, renderingProps, false)
+ : convertEventsObservation(o, renderingProps, true);
+
+ const enriched = {
+ ...converted,
+ // Use ClickHouse-calculated latency/timeToFirstToken if available, otherwise use what converter calculated
+ latency:
+ o.latency !== undefined
+ ? o.latency
+ ? Number(o.latency) / 1000
+ : null
+ : (converted.latency ?? null),
+ timeToFirstToken:
+ o.time_to_first_token !== undefined
+ ? o.time_to_first_token
+ ? Number(o.time_to_first_token) / 1000
+ : null
+ : (converted.timeToFirstToken ?? null),
+ // Add model pricing fields (null if not fetched)
modelId: model?.id ?? null,
inputPrice:
model?.Price?.find((m) => m.usageType === "input")?.price ?? null,
@@ -106,12 +168,14 @@ const enrichObservationsWithModelData = async (
totalPrice:
model?.Price?.find((m) => m.usageType === "total")?.price ?? null,
};
+
+ return enriched;
});
-};
+}
-const enrichObservationsWithTraceFields = async (
+async function enrichObservationsWithTraceFields(
observationRecords: Array<EventsObservation & ObservationPriceFields>,
-): Promise<FullEventsObservations> => {
+): Promise<FullEventsObservations> {
return observationRecords.map((o) => {
return {
...o,
@@ -120,17 +184,17 @@ const enrichObservationsWithTraceFields = async (
traceTimestamp: null,
};
});
-};
+}
/**
* Internal helper: extract and convert time filter from FilterList
* Common pattern: find time filter and convert to ClickHouse DateTime format
*/
-const extractTimeFilter = (
+function extractTimeFilter(
filter: FilterList,
tableName: "events" | "traces" = "events",
fieldName: "start_time" | "timestamp" = "start_time",
-): string | null => {
+): string | null {
const timeFilter = filter.find(
(f) =>
f.clickhouseTable === tableName &&
@@ -141,7 +205,7 @@ const extractTimeFilter = (
return timeFilter
? convertDateToClickhouseDateTime((timeFilter as DateTimeFilter).value)
: null;
-};
+}
/**
* Column mapping for public API filters on events table (observations)
@@ -230,17 +294,23 @@ export const getObservationsWithModelDataFromEventsTable = async (
},
);
- return enrichObservationsWithTraceFields(
- await enrichObservationsWithModelData(observationRecords, opts.projectId),
- );
+ const withModelData: Array<EventsObservation & ObservationPriceFields> =
+ await enrichObservationsWithModelData(
+ observationRecords,
+ opts.projectId,
+ false,
+ null, // V1 path: always enrich all fields
+ );
+
+ return enrichObservationsWithTraceFields(withModelData);
};
-const getObservationsFromEventsTableInternal = async <T>(
+async function getObservationsFromEventsTableInternal<T>(
opts: ObservationTableQuery & {
select: "count" | "rows";
tags: Record<string, string>;
},
-): Promise<Array<T>> => {
+): Promise<Array<T>> {
const {
projectId,
filter,
@@ -358,7 +428,7 @@ const getObservationsFromEventsTableInternal = async <T>(
});
},
});
-};
+}
export const getObservationByIdFromEventsTable = async ({
id,
@@ -417,7 +487,7 @@ export const getObservationByIdFromEventsTable = async ({
return mapped.shift();
};
-const getObservationByIdFromEventsTableInternal = async ({
+async function getObservationByIdFromEventsTableInternal({
id,
projectId,
fetchWithInputOutput = false,
@@ -435,7 +505,7 @@ const getObservationByIdFromEventsTableInternal = async ({
traceId?: string;
renderingProps?: RenderingProps;
preferredClickhouseService?: PreferredClickhouseService;
-}) => {
+}) {
const queryBuilder = new EventsQueryBuilder({ projectId })
.selectFieldSet("byIdBase", "byIdModel", "byIdPrompt", "byIdTimestamps")
.when(fetchWithInputOutput, (b) =>
@@ -470,7 +540,7 @@ const getObservationByIdFromEventsTableInternal = async ({
},
preferredClickhouseService,
});
-};
+}
/**
* Get a trace by ID from the events table.
@@ -591,6 +661,26 @@ export const getTraceByIdFromEventsTable = async ({
return res.shift();
};
+/**
+ * Field groups for selective field fetching in v2 observations API
+ *
+ * - core: Always included (cursor-required fields)
+ * - basic, time, io, metadata, model, usage, prompt, metrics: Optional groups
+ */
+export const OBSERVATION_FIELD_GROUPS = [
+ "core", // Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type
+ "basic", // name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId
+ "time", // completionStartTime, createdAt, updatedAt
+ "io", // input, output
+ "metadata", // metadata
+ "model", // providedModelName, internalModelId, modelParameters
+ "usage", // usageDetails, costDetails, totalCost, providedUsageDetails, providedCostDetails
+ "prompt", // promptId, promptName, promptVersion
+ "metrics", // latency, timeToFirstToken
+] as const;
+
+export type ObservationFieldGroup = (typeof OBSERVATION_FIELD_GROUPS)[number];
+
type PublicApiObservationsQuery = {
projectId: string;
page: number;
@@ -606,49 +696,43 @@ type PublicApiObservationsQuery = {
version?: string;
environment?: string | string[];
advancedFilters?: FilterState;
+ parseIoAsJson?: boolean;
+ cursor?: {
+ lastStartTimeTo: Date;
+ lastTraceId: string;
+ lastId: string;
+ };
+ fields?: ObservationFieldGroup[] | null;
};
-/**
- * Internal implementation for public API observations queries.
- * Consolidates count and list queries into a single implementation.
- */
-const getObservationsFromEventsTableForPublicApiInternal = async <T>(
- opts: PublicApiObservationsQuery & { select: "rows" | "count" },
-): Promise<Array<T>> => {
- const { projectId, page, limit, advancedFilters, ...filterParams } = opts;
+function buildObservationsQueryBase(
+ opts: PublicApiObservationsQuery,
+ eventsTableUiColumnDefinitions: UiColumnMappings = [
+ ...eventsTableLegacyTraceUiColumnDefinitions,
+ ...eventsTableNativeUiColumnDefinitions,
+ ],
+): EventsQueryBuilder {
+ const { projectId, advancedFilters, ...filterParams } = opts;
// Convert and merge simple and advanced filters
const observationsFilter = deriveFilters(
- { ...filterParams, projectId, page, limit },
+ { ...filterParams, projectId },
PUBLIC_API_EVENTS_COLUMN_MAPPING,
advancedFilters,
eventsTableUiColumnDefinitions,
);
- // Remove score filters since observations don't support scores in response
- const filteredObservationsFilter = observationsFilter.filter(
- (f) => f.clickhouseTable !== "scores",
- );
-
// Determine if we need to join traces (check both simple params and advanced filters)
- const hasTraceFilter = filteredObservationsFilter.some(
+ const hasTraceFilter = observationsFilter.some(
(f) => f.clickhouseTable === "traces",
);
- // Extract time filter using helper
- const startTimeFrom = extractTimeFilter(filteredObservationsFilter);
- const appliedFilter = filteredObservationsFilter.apply();
-
- // Build query using EventsQueryBuilder
- const queryBuilder = new EventsQueryBuilder({ projectId });
-
- if (opts.select === "count") {
- queryBuilder.selectFieldSet("count");
- } else {
- queryBuilder.selectFieldSet("base", "calculated", "io", "metadata");
- }
+ // Extract time filter and apply filters
+ const startTimeFrom = extractTimeFilter(observationsFilter);
+ const appliedFilter = observationsFilter.apply();
- queryBuilder
+ // Build query with common CTE, joins, and filters
+ const queryBuilder = new EventsQueryBuilder({ projectId })
.when(hasTraceFilter, (b) =>
b.withCTE(
"traces",
@@ -663,23 +747,71 @@ const getObservationsFromEventsTableForPublicApiInternal = async <T>(
)
.where(appliedFilter);
- if (opts.select === "rows") {
+ return queryBuilder;
+}
+
+function applyOrderByForObservationsQuery(
+ queryBuilder: EventsQueryBuilder,
+): EventsQueryBuilder {
+ return (
queryBuilder
- .orderBy("ORDER BY e.start_time DESC")
- .limit(limit, (page - 1) * limit);
- }
+ // Order by to match table ordering
+ .orderBy(
+ "ORDER BY e.start_time DESC, xxHash32(e.trace_id) DESC, e.span_id DESC",
+ )
+ );
+}
+function applyOffsetPagination(
+ opts: PublicApiObservationsQuery,
+ queryBuilder: EventsQueryBuilder,
+): EventsQueryBuilder {
+ // Apply offset pagination for page-based requests
+ const offset = (opts.page - 1) * opts.limit;
+ return queryBuilder.limit(opts.limit, offset);
+}
+
+function applyCursorPagination(
+ opts: PublicApiObservationsQuery,
+ queryBuilder: EventsQueryBuilder,
+): EventsQueryBuilder {
+ // Apply cursor filter if provided
+ return queryBuilder.when(Boolean(opts.cursor), (b) => {
+ const cursor = opts.cursor!;
+ return (
+ b
+ .whereRaw(
+ "e.start_time <= {lastStartTime: DateTime64(6)} AND (e.start_time, xxHash32(e.trace_id), e.span_id) < ({lastStartTime: DateTime64(6)}, xxHash32({lastTraceId: String}), {lastId: String})",
+ {
+ lastStartTime: convertDateToClickhouseDateTime(
+ cursor.lastStartTimeTo,
+ ),
+ lastTraceId: cursor.lastTraceId,
+ lastId: cursor.lastId,
+ },
+ )
+ // When cursor pagination (v2): fetch limit+1 to detect if there are more results
+ .limit(opts.limit + 1, undefined)
+ );
+ });
+}
+
+async function getObservationsRowsFromBuilder<T>(
+ projectId: string,
+ queryBuilder: EventsQueryBuilder,
+ operationName: string = "getObservationsFromEventsTableForPublicApi_rows",
+): Promise<Array<T>> {
const { query, params } = queryBuilder.buildWithParams();
- const result = await measureAndReturn({
- operationName: `getObservationsFromEventsTableForPublicApi_${opts.select}`,
+ return await measureAndReturn({
+ operationName,
projectId,
input: {
params,
tags: {
feature: "tracing",
type: "events",
- kind: opts.select === "count" ? "publicApiCount" : "publicApiRows",
+ kind: "publicApiRows",
projectId,
},
},
@@ -692,25 +824,128 @@ const getObservationsFromEventsTableForPublicApiInternal = async <T>(
});
},
});
+}
+
+/**
+ * Internal function to get count of observations from events table for public API.
+ */
+async function getObservationsCountFromEventsTableForPublicApiInternal(
+ opts: PublicApiObservationsQuery,
+): Promise<Array<{ count: string }>> {
+ const { projectId } = opts;
+
+ // Build query with filters and common CTEs
+ const queryBuilder = buildObservationsQueryBase(opts);
+
+ // Select count field set
+ queryBuilder.selectFieldSet("count");
+
+ const { query, params } = queryBuilder.buildWithParams();
+
+ const result = await measureAndReturn({
+ operationName: "getObservationsFromEventsTableForPublicApi_count",
+ projectId,
+ input: {
+ params,
+ tags: {
+ feature: "tracing",
+ type: "events",
+ kind: "publicApiCount",
+ projectId,
+ },
+ },
+ fn: async (input) => {
+ return await queryClickhouse<{ count: string }>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ },
+ });
return result;
-};
+}
/**
- * Get observations list from events table for public API.
- * Includes model enrichment and supports public API filter format.
+ * V1 API: Get observations list from events table for public API
+ * Returns complete observations with all fields for transformDbToApiObservation
*/
export const getObservationsFromEventsTableForPublicApi = async (
- opts: PublicApiObservationsQuery,
+ opts: Omit<PublicApiObservationsQuery, "fields">,
): Promise<Array<Observation & ObservationPriceFields>> => {
+ const { projectId } = opts;
+
+ // Build query with filters and common CTEs
+ const queryBuilder = applyOffsetPagination(
+ opts,
+ applyOrderByForObservationsQuery(buildObservationsQueryBase(opts)),
+ );
+
+ OBSERVATION_FIELD_GROUPS.forEach((fieldGroup) => {
+ queryBuilder.selectFieldSet(fieldGroup);
+ });
+
const observationRecords =
- await getObservationsFromEventsTableForPublicApiInternal<ObservationsTableQueryResultWitouhtTraceFields>(
- {
- ...opts,
- select: "rows",
- },
+ await getObservationsRowsFromBuilder<ObservationsTableQueryResultWitouhtTraceFields>(
+ projectId,
+ queryBuilder,
);
- return enrichObservationsWithModelData(observationRecords, opts.projectId);
+ return await enrichObservationsWithModelData(
+ observationRecords,
+ opts.projectId,
+ opts.parseIoAsJson ?? true, // V1 API: default to parsing JSON (backwards compatibility)
+ null, // V1 API: no field groups, return complete observations
+ );
+};
+
+/**
+ * V2 API: Get observations list from events table for public API
+ * Returns partial observations based on requested field groups
+ * Field filtering happens at query time in ClickHouse
+ */
+export const getObservationsV2FromEventsTableForPublicApi = async (
+ opts: PublicApiObservationsQuery & { fields: ObservationFieldGroup[] },
+): Promise<Array<EventsObservationPublic>> => {
+ const { projectId } = opts;
+
+ // Build query with filters and common CTEs
+ let queryBuilder = buildObservationsQueryBase(opts, [
+ ...eventsTableLegacyTraceUiColumnDefinitions,
+ ...eventsTableNativeUiColumnDefinitions,
+ ]);
+
+ // Determine which field groups to include
+ // If fields are not specified (null), include "default" groups: core + basic
+ const requestedFields = opts.fields ?? ["core", "basic"];
+
+ // Core fields are always included (required for cursor pagination)
+ queryBuilder.selectFieldSet("core");
+
+ // Conditionally add other field sets based on requested groups
+ requestedFields
+ .filter((fg) => fg !== "core")
+ .forEach((fieldGroup) => {
+ queryBuilder.selectFieldSet(fieldGroup);
+ });
+
+ queryBuilder = applyCursorPagination(
+ opts,
+ applyOrderByForObservationsQuery(queryBuilder),
+ );
+
+ const observationRecords =
+ await getObservationsRowsFromBuilder<ObservationsTableQueryResultWitouhtTraceFields>(
+ projectId,
+ queryBuilder,
+ );
+
+ return await enrichObservationsWithModelData(
+ observationRecords,
+ opts.projectId,
+ Boolean(opts.parseIoAsJson),
+ opts.fields, // V2 API: field groups specified, return partial observations
+ );
};
/**
@@ -719,12 +954,8 @@ export const getObservationsFromEventsTableForPublicApi = async (
export const getObservationsCountFromEventsTableForPublicApi = async (
opts: PublicApiObservationsQuery,
): Promise<number> => {
- const countResult = await getObservationsFromEventsTableForPublicApiInternal<{
- count: string;
- }>({
- ...opts,
- select: "count",
- });
+ const countResult =
+ await getObservationsCountFromEventsTableForPublicApiInternal(opts);
return Number(countResult[0].count);
};
@@ -751,9 +982,9 @@ type PublicApiTracesQuery = {
* Uses eventsTracesAggregation to create a traces CTE that
* behaves similarly to the old traces table.
*/
-const getTracesFromEventsTableForPublicApiInternal = async <T>(
+async function getTracesFromEventsTableForPublicApiInternal<T>(
opts: PublicApiTracesQuery & { select: "rows" | "count" },
-): Promise<Array<T>> => {
+): Promise<Array<T>> {
const {
projectId,
page,
@@ -913,7 +1144,7 @@ const getTracesFromEventsTableForPublicApiInternal = async <T>(
});
return result;
-};
+}
/**
* Get traces list from events table for public API.
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index 4d7a74639e..e773918ca0 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -8,6 +8,9 @@ import {
EventsObservation,
ObservationLevelType,
ObservationType,
+ PartialEventsObservation,
+ PartialObservation,
+ ObservationCoreFields,
} from "../../domain";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
import {
@@ -20,6 +23,39 @@ import type { Model, Price } from "@prisma/client";
type ModelWithPrice = Model & { Price: Price[] };
+/**
+ * Validates that all ObservationCoreFields are present and not undefined in a ClickHouse record.
+ * Throws an error if any required core field is missing.
+ *
+ * @param record - The partial observation record from ClickHouse to validate
+ * @throws Error if any core field is undefined
+ * @returns The validated core fields in domain format
+ */
+function ensureObservationCoreFields(
+ record: Partial<ObservationRecordReadType>,
+): ObservationCoreFields {
+ const missingFields: string[] = [];
+
+ if (record.id === undefined) missingFields.push("id");
+ if (record.trace_id === undefined) missingFields.push("trace_id");
+ if (record.start_time === undefined) missingFields.push("start_time");
+ if (record.project_id === undefined) missingFields.push("project_id");
+
+ if (missingFields.length > 0) {
+ const errorMessage = `Missing required ObservationCoreFields: ${missingFields.join(", ")}${record.id ? ` (record: ${record.id})` : ""}`;
+ logger.error(errorMessage);
+ throw new Error(errorMessage);
+ }
+
+ return {
+ id: record.id!,
+ traceId: record.trace_id ?? null,
+ startTime: parseClickhouseUTCDateTimeFormat(record.start_time!),
+ projectId: record.project_id!,
+ parentObservationId: record.parent_observation_id ?? null,
+ };
+}
+
/**
* Enriches observation data with model pricing information
* @param model - The model with price data (can be null)
@@ -39,14 +75,37 @@ export const enrichObservationWithModelData = (
};
};
-export const convertObservation = (
+/**
+ * Convert observation record from ClickHouse to domain model
+ * Return type depends on input parameters: either complete Observation or Partial<Observation>
+ *
+ * @param record - Raw observation record from ClickHouse
+ * @param renderingProps - Rendering options for input/output
+ * @param complete - If true, fills missing fields with defaults (V1 API). If false/undefined, returns only present fields (V2 API)
+ *
+ * Type signatures:
+ * - convertObservation(record, props, true) → Observation
+ * - convertObservation(record, props) → Partial<Observation>
+ */
+export function convertObservationPartial(
+ // eslint-disable-next-line no-unused-vars
record: ObservationRecordReadType,
+ renderingProps: RenderingProps, // eslint-disable-line no-unused-vars
+ complete: true, // eslint-disable-line no-unused-vars
+): Observation;
+export function convertObservationPartial(
+ // eslint-disable-next-line no-unused-vars
+ record: Partial<ObservationRecordReadType>,
+ renderingProps: RenderingProps, // eslint-disable-line no-unused-vars
+ complete: false, // eslint-disable-line no-unused-vars
+): PartialObservation;
+export function convertObservationPartial(
+ record: Partial<ObservationRecordReadType>,
renderingProps: RenderingProps = DEFAULT_RENDERING_PROPS,
-): Observation => {
- const reducedCostDetails = reduceUsageOrCostDetails(record.cost_details);
- const reducedUsageDetails = reduceUsageOrCostDetails(record.usage_details);
-
- if (!record.start_time) {
+ complete: boolean,
+): Observation | PartialObservation {
+ // Core fields validation - these should always be present
+ if (record.start_time !== undefined && !record.start_time) {
logger.error(
`Found invalid value start_time: ${record.start_time} for record ${record.id} in project ${record.project_id}. Processing will fail.`,
{
@@ -58,94 +117,234 @@ export const convertObservation = (
);
}
+ const reducedCostDetails =
+ record.cost_details !== undefined
+ ? reduceUsageOrCostDetails(record.cost_details)
+ : { input: null, output: null, total: null };
+
+ const reducedUsageDetails =
+ record.usage_details !== undefined
+ ? reduceUsageOrCostDetails(record.usage_details)
+ : { input: null, output: null, total: null };
+
+ // Core fields are not optional
+ const coreFields = ensureObservationCoreFields(record);
+
+ const partial = {
+ ...coreFields,
+ ...(record.type !== undefined && { type: record.type as ObservationType }),
+ ...(record.end_time !== undefined && {
+ endTime: record.end_time
+ ? parseClickhouseUTCDateTimeFormat(record.end_time)
+ : null,
+ }),
+
+ // Basic fields
+ ...(record.name !== undefined && { name: record.name ?? null }),
+ ...(record.level !== undefined && {
+ level: record.level as ObservationLevelType,
+ }),
+ ...(record.status_message !== undefined && {
+ statusMessage: record.status_message ?? null,
+ }),
+ ...(record.version !== undefined && { version: record.version ?? null }),
+ ...(record.environment !== undefined && {
+ environment: record.environment,
+ }),
+
+ // Time fields
+ ...(record.completion_start_time !== undefined && {
+ completionStartTime: record.completion_start_time
+ ? parseClickhouseUTCDateTimeFormat(record.completion_start_time)
+ : null,
+ }),
+ ...(record.created_at !== undefined && {
+ createdAt: parseClickhouseUTCDateTimeFormat(record.created_at),
+ }),
+ ...(record.updated_at !== undefined && {
+ updatedAt: parseClickhouseUTCDateTimeFormat(record.updated_at),
+ }),
+
+ // IO fields
+ ...(record.input !== undefined && {
+ input: applyInputOutputRendering(record.input, renderingProps),
+ }),
+ ...(record.output !== undefined && {
+ output: applyInputOutputRendering(record.output, renderingProps),
+ }),
+
+ // Metadata
+ ...(record.metadata !== undefined && {
+ metadata: parseMetadataCHRecordToDomain(record.metadata),
+ }),
+
+ // Model fields
+ ...(record.provided_model_name !== undefined && {
+ model: record.provided_model_name ?? null,
+ }),
+ ...(record.internal_model_id !== undefined && {
+ internalModelId: record.internal_model_id ?? null,
+ }),
+ ...(record.model_parameters !== undefined && {
+ modelParameters: record.model_parameters
+ ? ((typeof record.model_parameters === "string"
+ ? JSON.parse(record.model_parameters)
+ : record.model_parameters) ?? null)
+ : null,
+ }),
+
+ // Usage fields
+ ...(record.usage_details !== undefined && {
+ usageDetails: Object.fromEntries(
+ Object.entries(record.usage_details ?? {}).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
+ inputUsage: reducedUsageDetails.input ?? 0,
+ outputUsage: reducedUsageDetails.output ?? 0,
+ totalUsage: reducedUsageDetails.total ?? 0,
+ }),
+ ...(record.cost_details !== undefined && {
+ costDetails: Object.fromEntries(
+ Object.entries(record.cost_details ?? {}).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
+ inputCost: reducedCostDetails.input,
+ outputCost: reducedCostDetails.output,
+ totalCost: reducedCostDetails.total,
+ }),
+ ...(record.provided_cost_details !== undefined && {
+ providedCostDetails: Object.fromEntries(
+ Object.entries(record.provided_cost_details ?? {}).map(
+ ([key, value]) => [key, Number(value)],
+ ),
+ ),
+ }),
+
+ // Prompt fields
+ ...(record.prompt_id !== undefined && {
+ promptId: record.prompt_id ?? null,
+ }),
+ ...(record.prompt_name !== undefined && {
+ promptName: record.prompt_name ?? null,
+ }),
+ ...(record.prompt_version !== undefined && {
+ promptVersion: record.prompt_version
+ ? Number(record.prompt_version)
+ : null,
+ }),
+
+ // Metrics (calculated fields)
+ ...((record.end_time !== undefined || record.start_time !== undefined) && {
+ latency:
+ record.end_time && record.start_time
+ ? parseClickhouseUTCDateTimeFormat(record.end_time).getTime() -
+ parseClickhouseUTCDateTimeFormat(record.start_time).getTime()
+ : null,
+ }),
+ ...((record.completion_start_time !== undefined ||
+ record.start_time !== undefined) && {
+ timeToFirstToken:
+ record.completion_start_time && record.start_time
+ ? (parseClickhouseUTCDateTimeFormat(
+ record.completion_start_time,
+ ).getTime() -
+ parseClickhouseUTCDateTimeFormat(record.start_time).getTime()) /
+ 1000
+ : null,
+ }),
+ };
+
+ // V2 API: return partial observation (only fields that were present in record)
+ if (!complete) {
+ return partial;
+ }
+
+ // V1 API: fill missing fields with defaults to ensure complete Observation
return {
- id: record.id,
- traceId: record.trace_id ?? null,
- projectId: record.project_id,
- type: record.type as ObservationType,
- environment: record.environment,
- parentObservationId: record.parent_observation_id ?? null,
- startTime: parseClickhouseUTCDateTimeFormat(record.start_time),
- endTime: record.end_time
- ? parseClickhouseUTCDateTimeFormat(record.end_time)
- : null,
- name: record.name ?? null,
- metadata: parseMetadataCHRecordToDomain(record.metadata),
- level: record.level as ObservationLevelType,
- statusMessage: record.status_message ?? null,
- version: record.version ?? null,
- input: applyInputOutputRendering(record.input, renderingProps),
- output: applyInputOutputRendering(record.output, renderingProps),
- // Necessary if we fill this from events as model_parameters will be an object
- modelParameters: record.model_parameters
- ? ((typeof record.model_parameters === "string"
- ? JSON.parse(record.model_parameters)
- : record.model_parameters) ?? null)
- : null,
- completionStartTime: record.completion_start_time
- ? parseClickhouseUTCDateTimeFormat(record.completion_start_time)
- : null,
- promptId: record.prompt_id ?? null,
- createdAt: parseClickhouseUTCDateTimeFormat(record.created_at),
- updatedAt: parseClickhouseUTCDateTimeFormat(record.updated_at),
- usageDetails: Object.fromEntries(
- Object.entries(record.usage_details ?? {}).map(([key, value]) => [
- key,
- Number(value),
- ]),
- ),
- costDetails: Object.fromEntries(
- Object.entries(record.cost_details ?? {}).map(([key, value]) => [
- key,
- Number(value),
- ]),
- ),
- providedCostDetails: Object.fromEntries(
- Object.entries(record.provided_cost_details ?? {}).map(([key, value]) => [
- key,
- Number(value),
- ]),
- ),
- model: record.provided_model_name ?? null,
- internalModelId: record.internal_model_id ?? null,
- promptName: record.prompt_name ?? null,
- promptVersion: record.prompt_version ? Number(record.prompt_version) : null,
- latency: record.end_time
- ? parseClickhouseUTCDateTimeFormat(record.end_time).getTime() -
- parseClickhouseUTCDateTimeFormat(record.start_time).getTime()
- : null,
- timeToFirstToken: record.completion_start_time
- ? (parseClickhouseUTCDateTimeFormat(
- record.completion_start_time,
- ).getTime() -
- parseClickhouseUTCDateTimeFormat(record.start_time).getTime()) /
- 1000
- : null,
- inputCost: reducedCostDetails.input,
- outputCost: reducedCostDetails.output,
- totalCost: reducedCostDetails.total,
- inputUsage: reducedUsageDetails.input ?? 0,
- outputUsage: reducedUsageDetails.output ?? 0,
- totalUsage: reducedUsageDetails.total ?? 0,
+ // These fields should always be present from partial conversion
+ ...coreFields,
+ type: partial.type!,
+ environment: partial.environment ?? "",
+ endTime: partial.endTime ?? null,
+ name: partial.name ?? null,
+ level: partial.level ?? "DEFAULT",
+ statusMessage: partial.statusMessage ?? null,
+ version: partial.version ?? null,
+ createdAt: partial.createdAt!,
+ updatedAt: partial.updatedAt!,
+
+ // Fields that may not be selected from ClickHouse (default to null)
+ input: partial.input ?? null,
+ output: partial.output ?? null,
+ metadata: partial.metadata ?? {},
+ model: partial.model ?? null,
+ internalModelId: partial.internalModelId ?? null,
+ modelParameters: partial.modelParameters ?? null,
+ completionStartTime: partial.completionStartTime ?? null,
+ promptId: partial.promptId ?? null,
+ promptName: partial.promptName ?? null,
+ promptVersion: partial.promptVersion ?? null,
+ latency: partial.latency ?? null,
+ timeToFirstToken: partial.timeToFirstToken ?? null,
+ usageDetails: partial.usageDetails ?? {},
+ costDetails: partial.costDetails ?? {},
+ providedCostDetails: partial.providedCostDetails ?? {},
+ inputCost: partial.inputCost ?? null,
+ outputCost: partial.outputCost ?? null,
+ totalCost: partial.totalCost ?? null,
+ inputUsage: partial.inputUsage ?? 0,
+ outputUsage: partial.outputUsage ?? 0,
+ totalUsage: partial.totalUsage ?? 0,
};
-};
+}
+
+export function convertObservation(
+ record: ObservationRecordReadType,
+ renderingProps: RenderingProps = DEFAULT_RENDERING_PROPS,
+): Observation {
+ return convertObservationPartial(record, renderingProps, true);
+}
/**
* Events-specific converter that includes userId and sessionId fields.
* Use this for observations from the events table which contain user context.
*/
-export const convertEventsObservation = (
+export function convertEventsObservation(
+ // eslint-disable-next-line no-unused-vars
record: EventsObservationRecordReadType,
+ renderingProps: RenderingProps, // eslint-disable-line no-unused-vars
+ complete: true, // eslint-disable-line no-unused-vars
+): EventsObservation;
+export function convertEventsObservation(
+ // eslint-disable-next-line no-unused-vars
+ record: Partial<EventsObservationRecordReadType>,
+ renderingProps: RenderingProps, // eslint-disable-line no-unused-vars
+ complete: false, // eslint-disable-line no-unused-vars
+): PartialEventsObservation;
+export function convertEventsObservation(
+ record: Partial<EventsObservationRecordReadType>,
renderingProps: RenderingProps = DEFAULT_RENDERING_PROPS,
-): EventsObservation => {
- const baseObservation = convertObservation(record, renderingProps);
+ complete: boolean,
+): EventsObservation | PartialEventsObservation {
+ // Branch based on complete flag to use correct overload
+ const baseObservation = complete
+ ? convertObservationPartial(
+ record as ObservationRecordReadType,
+ renderingProps,
+ true,
+ )
+ : convertObservationPartial(record, renderingProps, false);
return {
...baseObservation,
userId: record.user_id ?? null,
sessionId: record.session_id ?? null,
};
-};
+}
export const reduceUsageOrCostDetails = (
details: Record<string, number> | null | undefined,
diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.ts
index 81aa17d408..ffa1d277db 100644
--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts
@@ -33,8 +33,7 @@ export const eventsTableLegacyTraceUiColumnDefinitions: UiColumnMappings = [
},
];
-export const eventsTableUiColumnDefinitions: UiColumnMappings = [
- ...eventsTableLegacyTraceUiColumnDefinitions,
+export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [
{
uiTableName: "Environment",
uiTableId: "environment",
@@ -192,26 +191,6 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "events",
clickhouseSelect: 'e."metadata"',
},
- // Scores column duplicated to allow renaming column name. Will be removed once session storage cache is outdated
- // Column names are cached in user sessions - changing them breaks existing filters
- {
- uiTableName: "Scores",
- uiTableId: "scores",
- clickhouseTableName: "scores",
- clickhouseSelect: "s.scores_avg",
- },
- {
- uiTableName: "Scores (numeric)",
- uiTableId: "scores_avg",
- clickhouseTableName: "scores",
- clickhouseSelect: "s.scores_avg",
- },
- {
- uiTableName: "Scores (categorical)",
- uiTableId: "score_categories",
- clickhouseTableName: "scores",
- clickhouseSelect: "s.score_categories",
- },
{
uiTableName: "Version",
uiTableId: "version",
@@ -243,3 +222,28 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseSelect: 'e."session_id"',
},
];
+
+export const eventsTableUiColumnDefinitions: UiColumnMappings = [
+ ...eventsTableLegacyTraceUiColumnDefinitions,
+ ...eventsTableNativeUiColumnDefinitions,
+ // Scores column duplicated to allow renaming column name. Will be removed once session storage cache is outdated
+ // Column names are cached in user sessions - changing them breaks existing filters
+ {
+ uiTableName: "Scores",
+ uiTableId: "scores",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.scores_avg",
+ },
+ {
+ uiTableName: "Scores (numeric)",
+ uiTableId: "scores_avg",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.scores_avg",
+ },
+ {
+ uiTableName: "Scores (categorical)",
+ uiTableId: "score_categories",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.score_categories",
+ },
+];
diff --git a/web/src/__tests__/async/event-query-builder.servertest.ts b/web/src/__tests__/async/event-query-builder.servertest.ts
index 67200fc02f..fc3aac0879 100644
--- a/web/src/__tests__/async/event-query-builder.servertest.ts
+++ b/web/src/__tests__/async/event-query-builder.servertest.ts
@@ -37,11 +37,10 @@ describe("CTEQueryBuilder", () => {
expect(query).toContain("t.name");
expect(query).toContain("s.score");
expect(query).toContain("COUNT(*) as total");
- expect(query).toContain("LIMIT {limit: Int32} OFFSET {offset: Int32}");
+ expect(query).toContain("LIMIT {limit: Int32}");
expect(params.projectId).toBe("test-project");
expect(params.ids).toEqual(["id1", "id2"]);
expect(params.limit).toBe(10);
- expect(params.offset).toBe(0);
});
it("should support type-safe selectColumns() after establishing aliases", () => {
diff --git a/web/src/__tests__/async/observations-api-v2.servertest.ts b/web/src/__tests__/async/observations-api-v2.servertest.ts
new file mode 100644
index 0000000000..07cc342f6f
--- /dev/null
+++ b/web/src/__tests__/async/observations-api-v2.servertest.ts
@@ -0,0 +1,712 @@
+import { createEvent, createEventsCh } from "@langfuse/shared/src/server";
+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";
+import { GetObservationsV2Response } from "@/src/features/public-api/types/observations";
+import { randomUUID } from "crypto";
+import { env } from "@/src/env.mjs";
+
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+const maybe =
+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"
+ ? describe
+ : describe.skip;
+
+describe("/api/public/v2/observations API Endpoint", () => {
+ it("should kill redis connection", () => {
+ // we need at least one test case to avoid hanging
+ // redis connection when everything else is skipped.
+ });
+
+ maybe("GET /api/public/v2/observations", () => {
+ it("should fetch observations with only requested field groups", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000; // microseconds for events table
+
+ // Create observation
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ end_time: timeValue + 1000 * 1000,
+ input: "What is the capital of France?",
+ output: "The capital of France is Paris.",
+ metadata: { source: "API" },
+ metadata_names: ["source"],
+ metadata_raw_values: ["API"],
+ provided_model_name: "gpt-4",
+ });
+
+ await createEventsCh([observation]);
+
+ // Request only basic field group (core is always included)
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?fields=basic`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(response.body.meta).toBeDefined();
+ expect(response.body.data.length).toBeGreaterThanOrEqual(1);
+
+ // Find our created observation
+ const createdObs = response.body.data.find(
+ (obs: any) => obs.id === observationId,
+ );
+ expect(createdObs).toBeDefined();
+
+ // Verify core fields are always present
+ expect(createdObs?.id).toBe(observationId);
+ expect(createdObs?.traceId).toBe(traceId);
+ expect(createdObs?.type).toBe("GENERATION");
+ expect(createdObs?.startTime).toBeDefined();
+ expect(createdObs?.endTime).toBeDefined();
+ expect(createdObs?.projectId).toBe(projectId);
+
+ // Verify basic fields are present
+ expect(createdObs?.name).toBe("test-observation");
+ expect(createdObs?.level).toBe("DEFAULT");
+
+ // Verify fields from non-requested groups are not present
+ expect(createdObs?.input).toBeUndefined();
+ expect(createdObs?.output).toBeUndefined();
+ expect(createdObs?.metadata).toBeUndefined();
+ expect(createdObs?.providedModelName).toBeUndefined();
+ });
+
+ it("should return input/output as strings by default (parseIoAsJson=false)", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create observation with JSON input/output
+ const jsonInput = JSON.stringify({ question: "What is 2+2?" });
+ const jsonOutput = JSON.stringify({ answer: 4 });
+
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ end_time: timeValue + 1000 * 1000,
+ input: jsonInput,
+ output: jsonOutput,
+ });
+
+ await createEventsCh([observation]);
+
+ // Request with parseIoAsJson=false (default)
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?fields=io&traceId=${traceId}&parseIoAsJson=false`,
+ );
+
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === observationId);
+ expect(obs).toBeDefined();
+
+ // Input and output should be strings, not parsed objects
+ expect(typeof obs?.input).toBe("string");
+ expect(typeof obs?.output).toBe("string");
+ expect(obs?.input).toBe(jsonInput);
+ expect(obs?.output).toBe(jsonOutput);
+ });
+
+ it("should parse input/output as JSON when parseIoAsJson=true", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create observation with JSON input/output
+ const inputData = { question: "What is 2+2?" };
+ const outputData = { answer: 4 };
+
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "test-observation",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ end_time: timeValue + 1000 * 1000,
+ input: JSON.stringify(inputData),
+ output: JSON.stringify(outputData),
+ });
+
+ await createEventsCh([observation]);
+
+ // Request with parseIoAsJson=true
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?fields=io&traceId=${traceId}&parseIoAsJson=true`,
+ );
+
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === observationId);
+ expect(obs).toBeDefined();
+
+ // Input and output should be parsed as objects
+ expect(typeof obs?.input).toBe("object");
+ expect(typeof obs?.output).toBe("object");
+ expect(obs?.input).toEqual(inputData);
+ expect(obs?.output).toEqual(outputData);
+ });
+
+ it("should respect limit parameter with default of 50", async () => {
+ // Test default limit
+ const response1 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ "/api/public/v2/observations",
+ );
+
+ expect(response1.status).toBe(200);
+ expect(response1.body.data.length).toBeLessThanOrEqual(50);
+
+ // Test custom limit
+ const response2 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ "/api/public/v2/observations?limit=5",
+ );
+
+ expect(response2.status).toBe(200);
+ expect(response2.body.data.length).toBeLessThanOrEqual(5);
+ });
+
+ it("should support standard filters (name, type, level, etc.)", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create observation with specific attributes
+ const observation = createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "unique-observation-name",
+ type: "GENERATION",
+ level: "WARNING",
+ start_time: timeValue,
+ });
+
+ await createEventsCh([observation]);
+
+ // Test filtering by name
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?fields=basic&name=unique-observation-name`,
+ );
+
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === observationId);
+ expect(obs).toBeDefined();
+ expect(obs?.name).toBe("unique-observation-name");
+ expect(obs?.type).toBe("GENERATION");
+ expect(obs?.level).toBe("WARNING");
+ });
+
+ it("should support filter parameter on various columns without SQL crashes", async () => {
+ const traceId = randomUUID();
+ const observationId1 = randomUUID();
+ const observationId2 = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create observations with trace-level fields that require joins
+ const observation1 = createEvent({
+ id: observationId1,
+ span_id: observationId1,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "filter-test-obs-1",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ end_time: timeValue + 2000 * 1000,
+ provided_model_name: "gpt-4",
+ // Trace-level fields (require join to traces table)
+ user_id: "test-user-123",
+ trace_name: "test-trace",
+ tags: ["tag1", "tag2"],
+ session_id: "session-abc",
+ });
+
+ const observation2 = createEvent({
+ id: observationId2,
+ span_id: observationId2,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "filter-test-obs-2",
+ type: "SPAN",
+ level: "WARNING",
+ start_time: timeValue + 1000 * 1000,
+ end_time: timeValue + 3000 * 1000,
+ provided_model_name: "gpt-3.5-turbo",
+ // Trace-level fields (require join to traces table)
+ user_id: "test-user-456",
+ trace_name: "different-trace",
+ session_id: "session-xyz",
+ });
+
+ await createEventsCh([observation1, observation2]);
+
+ // Focus on testing columns that require joins to other tables
+ // (columns from traces table: userId, traceName, sessionId, traceTags, traceEnvironment)
+ // and score-related columns that may require special handling
+ const filterTestCases = [
+ // Trace table columns (require join)
+ {
+ description: "trace field: userId",
+ filter: [
+ {
+ type: "string",
+ column: "userId",
+ operator: "=",
+ value: "test-user-123",
+ },
+ ],
+ },
+ {
+ description: "trace field: traceName",
+ filter: [
+ {
+ type: "string",
+ column: "traceName",
+ operator: "contains",
+ value: "test",
+ },
+ ],
+ },
+ {
+ description: "trace field: sessionId",
+ filter: [
+ {
+ type: "string",
+ column: "sessionId",
+ operator: "=",
+ value: "session-abc",
+ },
+ ],
+ },
+ {
+ description: "trace field: traceEnvironment",
+ filter: [
+ {
+ type: "string",
+ column: "traceEnvironment",
+ operator: "=",
+ value: "production",
+ },
+ ],
+ },
+ // Also test a few events table columns to ensure they still work
+ {
+ description: "events field: name",
+ filter: [
+ {
+ type: "string",
+ column: "name",
+ operator: "contains",
+ value: "filter-test",
+ },
+ ],
+ },
+ {
+ description: "events field: type",
+ filter: [
+ {
+ type: "string",
+ column: "type",
+ operator: "=",
+ value: "GENERATION",
+ },
+ ],
+ },
+ ];
+
+ // Test each filter to ensure no SQL crashes
+ for (const testCase of filterTestCases) {
+ const filterParam = JSON.stringify(testCase.filter);
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&fields=basic,io,cost,model,metadata&filter=${encodeURIComponent(filterParam)}`,
+ );
+
+ // Main assertion: should not crash (200 status)
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ // Response should be an array (even if empty)
+ expect(Array.isArray(response.body.data)).toBe(true);
+ }
+
+ // Verify a trace-field filter (requires join) returns expected observations
+ const userIdFilterParam = JSON.stringify([
+ {
+ type: "string",
+ column: "userId",
+ operator: "=",
+ value: "test-user-123",
+ },
+ ]);
+ const userIdFilterResponse = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&fields=basic&filter=${encodeURIComponent(userIdFilterParam)}`,
+ );
+
+ expect(userIdFilterResponse.status).toBe(200);
+ const userFilteredObs = userIdFilterResponse.body.data.find(
+ (obs: any) => obs.id === observationId1,
+ );
+ expect(userFilteredObs).toBeDefined();
+
+ // Verify trace name filter (requires join)
+ const traceNameFilterParam = JSON.stringify([
+ {
+ type: "string",
+ column: "traceName",
+ operator: "contains",
+ value: "test",
+ },
+ ]);
+ const traceNameResponse = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&fields=basic&filter=${encodeURIComponent(traceNameFilterParam)}`,
+ );
+
+ expect(traceNameResponse.status).toBe(200);
+ expect(traceNameResponse.body.data.length).toBeGreaterThanOrEqual(1);
+ });
+ });
+
+ maybe("Cursor-based pagination", () => {
+ it("should return cursor when results equal limit", async () => {
+ const traceId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create 3 observations
+ const observations = [];
+ for (let i = 0; i < 3; i++) {
+ const obsId = randomUUID();
+ observations.push(
+ createEvent({
+ id: obsId,
+ span_id: obsId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: `cursor-test-obs-${i}`,
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue + i * 1000 * 1000, // 1 second apart
+ }),
+ );
+ }
+
+ await createEventsCh(observations);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Fetch with limit=2 (should have cursor since we have 3 observations)
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&limit=2`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data.length).toBe(2);
+ expect(response.body.meta.cursor).toBeDefined();
+ expect(typeof response.body.meta.cursor).toBe("string");
+ });
+
+ it("should not return cursor when results less than limit", async () => {
+ const traceId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create only 2 observations
+ const observations = [];
+ for (let i = 0; i < 2; i++) {
+ const obsId = randomUUID();
+ observations.push(
+ createEvent({
+ id: obsId,
+ span_id: obsId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: `no-cursor-test-obs-${i}`,
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue + i * 1000 * 1000,
+ }),
+ );
+ }
+
+ await createEventsCh(observations);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Fetch with limit=5 (should not have cursor since we only have 2)
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&limit=5`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data.length).toBe(2);
+ expect(response.body.meta.cursor).toBeUndefined();
+ });
+
+ it("should paginate correctly using cursor without overlap", async () => {
+ const traceId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create 5 observations with distinct timestamps
+ const observations = [];
+ for (let i = 0; i < 5; i++) {
+ const obsId = randomUUID();
+ observations.push(
+ createEvent({
+ id: obsId,
+ span_id: obsId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: `pagination-test-obs-${i}`,
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue + i * 1000 * 1000, // 1 second apart
+ }),
+ );
+ }
+
+ await createEventsCh(observations);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Fetch first page with limit=2
+ const page1 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&limit=2`,
+ );
+
+ expect(page1.status).toBe(200);
+ expect(page1.body.data.length).toBe(2);
+ expect(page1.body.meta.cursor).toBeDefined();
+
+ const page1Ids = page1.body.data.map((obs: any) => obs.id);
+
+ // Fetch second page using cursor
+ const page2 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&limit=2&cursor=${page1.body.meta.cursor}`,
+ );
+
+ expect(page2.status).toBe(200);
+ expect(page2.body.data.length).toBe(2);
+ expect(page2.body.meta.cursor).toBeDefined(); // Should have cursor for third page
+
+ const page2Ids = page2.body.data.map((obs: any) => obs.id);
+
+ // Verify no overlap between pages
+ const overlap = page1Ids.filter((id: string) => page2Ids.includes(id));
+ expect(overlap.length).toBe(0);
+
+ // Fetch third page
+ const page3 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&limit=2&cursor=${page2.body.meta.cursor}`,
+ );
+
+ expect(page3.status).toBe(200);
+ expect(page3.body.data.length).toBe(1); // Only 1 remaining
+ expect(page3.body.meta.cursor).toBeUndefined(); // No more pages
+
+ const page3Ids = page3.body.data.map((obs: any) => obs.id);
+
+ // Verify all observations retrieved exactly once
+ const allIds = [...page1Ids, ...page2Ids, ...page3Ids];
+ expect(allIds.length).toBe(5);
+ expect(new Set(allIds).size).toBe(5); // All unique
+ });
+
+ it("should handle cursor with observations having same start_time", async () => {
+ const traceId1 = randomUUID();
+ const traceId2 = randomUUID();
+ const traceId3 = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+ const userId = randomUUID();
+
+ // Create observations with SAME start_time but different trace_ids
+ // This tests the xxHash32(trace_id) ordering component
+ const obs1 = createEvent({
+ trace_id: traceId1,
+ project_id: projectId,
+ name: "same-time-obs-1",
+ type: "GENERATION",
+ level: "DEFAULT",
+ user_id: userId,
+ start_time: timeValue,
+ });
+
+ const obs2 = createEvent({
+ trace_id: traceId2,
+ project_id: projectId,
+ name: "same-time-obs-2",
+ type: "GENERATION",
+ level: "DEFAULT",
+ user_id: userId,
+ start_time: timeValue, // Same time
+ });
+
+ const obs3 = createEvent({
+ trace_id: traceId3,
+ project_id: projectId,
+ name: "same-time-obs-3",
+ type: "GENERATION",
+ level: "DEFAULT",
+ user_id: userId,
+ start_time: timeValue, // Same time
+ });
+
+ await createEventsCh([obs1, obs2, obs3]);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Fetch first page
+ const page1 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?userId=${userId}&limit=2&fromStartTime=${new Date(timeValue / 1000).toISOString()}&toStartTime=${new Date(timeValue / 1000 + 1000).toISOString()}`,
+ );
+
+ expect(page1.status).toBe(200);
+ expect(page1.body.data.length).toBe(2);
+
+ const page1Ids = page1.body.data.map((obs: any) => obs.id);
+
+ // Fetch second page using cursor
+ const page2 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?userId=${userId}&limit=2&cursor=${page1.body.meta.cursor}`,
+ );
+
+ expect(page2.status).toBe(200);
+ expect(page2.body.data.length).toBeGreaterThan(0);
+
+ const page2Ids = page2.body.data.map((obs: any) => obs.id);
+
+ // Verify no overlap (tests that xxHash32 ordering works)
+ const overlap = page1Ids.filter((id: string) => page2Ids.includes(id));
+ expect(overlap.length).toBe(0);
+
+ // Verify that all events were fetched
+ expect([...page1Ids, ...page2Ids].sort()).toEqual(
+ [obs1, obs2, obs3].map((o) => o.span_id).sort(),
+ );
+ });
+
+ it("should work with cursor and other filters", async () => {
+ const traceId = randomUUID();
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000;
+
+ // Create observations with specific type
+ const observations = [];
+ for (let i = 0; i < 4; i++) {
+ const obsId = randomUUID();
+ observations.push(
+ createEvent({
+ id: obsId,
+ span_id: obsId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: `cursor-filter-obs-${i}`,
+ type: "SPAN", // All same type
+ level: "DEFAULT",
+ start_time: timeValue + i * 1000 * 1000,
+ }),
+ );
+ }
+
+ await createEventsCh(observations);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Fetch first page with type filter
+ const page1 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&type=SPAN&limit=2`,
+ );
+
+ expect(page1.status).toBe(200);
+ expect(page1.body.data.length).toBe(2);
+ expect(page1.body.data.every((obs: any) => obs.type === "SPAN")).toBe(
+ true,
+ );
+ expect(page1.body.meta.cursor).toBeDefined();
+
+ // Fetch second page with same filter and cursor
+ const page2 = await makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ `/api/public/v2/observations?traceId=${traceId}&type=SPAN&limit=2&cursor=${page1.body.meta.cursor}`,
+ );
+
+ expect(page2.status).toBe(200);
+ expect(page2.body.data.length).toBe(2);
+ expect(page2.body.data.every((obs: any) => obs.type === "SPAN")).toBe(
+ true,
+ );
+
+ // Verify no overlap
+ const page1Ids = page1.body.data.map((obs: any) => obs.id);
+ const page2Ids = page2.body.data.map((obs: any) => obs.id);
+ const overlap = page1Ids.filter((id: string) => page2Ids.includes(id));
+ expect(overlap.length).toBe(0);
+ });
+
+ it("should reject invalid cursor format", async () => {
+ const { makeAPICall } = await import("@/src/__tests__/test-utils");
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/v2/observations?fields=id&cursor=invalid-base64-string`,
+ );
+
+ // Should fail validation
+ expect(response.status).toBe(400);
+ expect(response.body).toHaveProperty("message");
+ expect((response.body as { message: string }).message).toContain(
+ "Invalid cursor format",
+ );
+ });
+ });
+});
diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.ts
index 33cb8fe88f..41ac8e7755 100644
--- a/web/src/__tests__/async/observations-api.servertest.ts
+++ b/web/src/__tests__/async/observations-api.servertest.ts
@@ -8,7 +8,10 @@ import {
createObservationsCh,
createEventsCh,
} from "@langfuse/shared/src/server";
-import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+} from "@/src/__tests__/test-utils";
import { GetObservationsV1Response } from "@/src/features/public-api/types/observations";
import { randomUUID } from "crypto";
import { env } from "@/src/env.mjs";
@@ -756,15 +759,16 @@ describe("/api/public/observations API Endpoint", () => {
},
]);
- const response = await makeZodVerifiedAPICall(
- GetObservationsV1Response,
+ const response = await makeAPICall(
"GET",
`/api/public/observations${queryParam}&traceId=${traceId}&type=GENERATION&filter=${encodeURIComponent(filterParam)}`,
);
- expect(response.status).toBe(200);
+ expect(response.status).toBe(500); // TODO 400
// Score filter should be ignored, so some observations should be returned
- expect(response.body.data.length).toBeGreaterThan(0);
+ expect(JSON.stringify(response.body)).toContain(
+ "does not match a UI / CH table mapping",
+ );
});
it("should filter by userId (trace field)", async () => {
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index cfe4e7e6c4..106153d39e 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -4,9 +4,9 @@ import {
StringFilter,
type ObservationRecordReadType,
queryClickhouse,
- convertObservation,
measureAndReturn,
observationsTableUiColumnDefinitions,
+ convertObservation,
} from "@langfuse/shared/src/server";
import type { FilterState } from "@langfuse/shared";
import { env } from "@/src/env.mjs";
@@ -168,7 +168,9 @@ const generateFilter = (query: QueryType) => {
simpleFilterProps,
filterParams,
advancedFilters,
- observationsTableUiColumnDefinitions,
+ observationsTableUiColumnDefinitions.filter(
+ (c) => c.clickhouseTableName !== "scores",
+ ),
);
// Remove score filters since observations don't support scores in response
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 733da9ce11..ed19880dd7 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -12,10 +12,15 @@ import {
reduceUsageOrCostDetails,
stringDateTime,
type ObservationPriceFields,
+ OBSERVATION_FIELD_GROUPS,
+ type ObservationFieldGroup,
} from "@langfuse/shared/src/server";
import { z } from "zod/v4";
import { useEventsTableSchema } from "../../query/types";
+// Re-export for convenience
+export { OBSERVATION_FIELD_GROUPS, type ObservationFieldGroup };
+
/**
* Objects
*/
@@ -211,3 +216,119 @@ export const GetObservationV1Query = z.object({
useEventsTable: useEventsTableSchema,
});
export const GetObservationV1Response = APIObservation;
+
+/**
+ * Cursor schema for v2 observations pagination
+ * Encodes the position in the result set using the table's ordering:
+ * (start_time, xxHash32(trace_id), span_id)
+ */
+export const ObservationsCursorV2 = z.object({
+ lastStartTimeTo: z.coerce.date(),
+ lastTraceId: z.string(),
+ lastId: z.string(),
+});
+
+export type ObservationsCursorV2Type = z.infer<typeof ObservationsCursorV2>;
+
+/**
+ * Schema for base64-encoded cursor string
+ * Used in API responses - just a plain string, no transformation
+ */
+export const EncodedObservationsCursorV2String = z
+ .string()
+ .describe("Base64-encoded cursor for pagination");
+
+/**
+ * Schema for base64-encoded cursor in API requests
+ * Decodes and validates the cursor structure
+ */
+export const EncodedObservationsCursorV2 = z
+ .string()
+ .transform((val) => {
+ try {
+ const decoded = Buffer.from(val, "base64").toString("utf-8");
+ const parsed = JSON.parse(decoded);
+ return parsed;
+ } catch (e) {
+ throw new InvalidRequestError("Invalid cursor format");
+ }
+ })
+ .pipe(ObservationsCursorV2);
+
+/**
+ * Encodes a cursor object to base64 string for API response
+ */
+export const encodeCursor = (
+ cursor: ObservationsCursorV2Type,
+): z.infer<typeof EncodedObservationsCursorV2String> => {
+ return Buffer.from(
+ JSON.stringify({
+ lastStartTimeTo:
+ cursor.lastStartTimeTo instanceof Date
+ ? cursor.lastStartTimeTo.toISOString()
+ : cursor.lastStartTimeTo,
+ lastTraceId: cursor.lastTraceId,
+ lastId: cursor.lastId,
+ }),
+ ).toString("base64");
+};
+
+// GET /v2/observations
+export const GetObservationsV2Query = z.object({
+ // Field groups parameter (optional - defaults to all groups)
+ fields: z
+ .string()
+ .nullish()
+ .transform((v) => {
+ if (!v) return null;
+ return v
+ .split(",")
+ .map((f) => f.trim())
+ .filter((f) =>
+ OBSERVATION_FIELD_GROUPS.includes(f as ObservationFieldGroup),
+ );
+ })
+ .pipe(z.array(z.enum(OBSERVATION_FIELD_GROUPS)).nullable()),
+ // Pagination
+ limit: z.coerce.number().nonnegative().lte(1000).default(50),
+ cursor: EncodedObservationsCursorV2.optional(),
+ // Parsing behavior
+ parseIoAsJson: z
+ .union([z.literal("true"), z.literal("false")])
+ .transform((val) => val === "true")
+ .default(false),
+ // Filters
+ type: ObservationType.nullish(),
+ name: z.string().nullish(),
+ userId: z.string().nullish(),
+ level: z.enum(ObservationLevel).nullish(),
+ traceId: z.string().nullish(),
+ version: z.string().nullish(),
+ parentObservationId: z.string().nullish(),
+ environment: z.union([z.array(z.string()), z.string()]).nullish(),
+ fromStartTime: stringDateTime.optional(),
+ toStartTime: stringDateTime.optional(),
+ filter: z
+ .string()
+ .optional()
+ .transform((str) => {
+ if (!str) return undefined;
+ try {
+ const parsed = JSON.parse(str);
+ return parsed;
+ } catch (e) {
+ if (e instanceof InvalidRequestError) throw e;
+ throw new InvalidRequestError("Invalid JSON in filter parameter");
+ }
+ })
+ .pipe(z.array(singleFilter).optional()),
+});
+
+export const GetObservationsV2Response = z
+ .object({
+ data: z.array(z.record(z.string(), z.any())), // Field-group-filtered observations
+ meta: z.object({
+ cursor: EncodedObservationsCursorV2String.optional(),
+ }),
+ })
+ .strict();
diff --git a/web/src/pages/api/public/v2/observations/index.ts b/web/src/pages/api/public/v2/observations/index.ts
new file mode 100644
index 0000000000..21d510c3d5
--- /dev/null
+++ b/web/src/pages/api/public/v2/observations/index.ts
@@ -0,0 +1,75 @@
+import { getObservationsV2FromEventsTableForPublicApi } from "@langfuse/shared/src/server";
+
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+
+import {
+ GetObservationsV2Query,
+ GetObservationsV2Response,
+ encodeCursor,
+} from "@/src/features/public-api/types/observations";
+
+export default withMiddlewares({
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Observations V2",
+ querySchema: GetObservationsV2Query,
+ responseSchema: GetObservationsV2Response,
+ fn: async ({ query, auth }) => {
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: 0, // v2 doesn't use page-based pagination
+ limit: query.limit,
+ traceId: query.traceId ?? undefined,
+ userId: query.userId ?? undefined,
+ level: query.level ?? undefined,
+ name: query.name ?? undefined,
+ type: query.type ?? undefined,
+ environment: query.environment ?? undefined,
+ parentObservationId: query.parentObservationId ?? undefined,
+ fromStartTime: query.fromStartTime ?? undefined,
+ toStartTime: query.toStartTime ?? undefined,
+ version: query.version ?? undefined,
+ advancedFilters: query.filter,
+ parseIoAsJson: query.parseIoAsJson ?? false,
+ cursor: query.cursor ?? undefined,
+ fields: query.fields ?? undefined,
+ };
+
+ // Fetch observations from events table with field groups applied at query time
+ const items = await getObservationsV2FromEventsTableForPublicApi({
+ ...filterProps,
+ fields: filterProps.fields ?? [], // V2 requires fields array
+ });
+
+ // Determine if there are more results (we fetched limit+1)
+ const hasMore = items.length > query.limit;
+ const dataToReturn = hasMore ? items.slice(0, query.limit) : items;
+
+ // Convert empty parent_observation_id to null for consistency with v1
+ const transformedItems = dataToReturn.map((item) => {
+ if (item.parentObservationId === "") {
+ return { ...item, parentObservationId: null };
+ }
+ return item;
+ });
+
+ // Generate cursor if there are more results
+ const lastItemIdx = dataToReturn.length - 1;
+ const meta =
+ hasMore && dataToReturn.length > 0
+ ? {
+ cursor: encodeCursor({
+ lastStartTimeTo: dataToReturn[lastItemIdx].startTime,
+ lastTraceId: dataToReturn[lastItemIdx].traceId ?? "",
+ lastId: dataToReturn[lastItemIdx].id,
+ }),
+ }
+ : {};
+
+ return {
+ data: transformedItems,
+ meta,
+ };
+ },
+ }),
+});
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index a69e510bc2..af136320d1 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -8,7 +8,6 @@ import {
getDistinctScoreNames,
queryClickhouseStream,
logger,
- convertObservation,
ObservationRecordReadType,
StringFilter,
FilterList,
@@ -16,6 +15,7 @@ import {
observationsTableUiColumnDefinitions,
enrichObservationWithModelData,
clickhouseSearchCondition,
+ convertObservation,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { Readable } from "stream";
@@ -154,7 +154,7 @@ export const getObservationStream = async (props: {
const search = clickhouseSearchCondition(searchQuery, searchType, "o");
const query = `
-
+
WITH scores_agg AS (
SELECT
trace_id,
@@ -227,7 +227,7 @@ export const getObservationStream = async (props: {
if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as "time_to_first_token",
o.input as input,
o.output as output,
- o.metadata as metadata,
+ o.metadata as metadata,
t.name as traceName,
t.tags as traceTags,
t.timestamp as traceTimestamp,