Skip to content

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

2.5 KB
Raw Blame
import {
  LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
  withMiddlewares,
} from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { logger } from "@langfuse/shared/src/server";
import {
  GetMetricsV1Query,
  GetMetricsV1Response,
} from "@/src/features/public-api/types/metrics";
import { executeQuery } from "@langfuse/shared/query/server";
import { METRICS_DEPRECATION } from "@/src/features/public-api/server/deprecations";
import { clampToDataAccessDays } from "@/src/features/entitlements/server/hasEntitlementLimit";
export default withMiddlewares(
  {
    GET: createAuthedProjectAPIRoute({
      name: "Get Metrics",
      action: "metrics:read",
      rateLimitResource: "public-api-metrics",
      querySchema: GetMetricsV1Query,
      responseSchema: GetMetricsV1Response,
      deprecation: METRICS_DEPRECATION,
      // v1 metrics executes QueryBuilder against the legacy traces/observations
      // tables; the v2 endpoint at /api/public/v2/metrics targets events_full.
      rejectInEventsOnlyMode: true,
      fn: async ({ query, auth }) => {
        try {
          // Extract the parsed query object
          const dataAccessWindow = clampToDataAccessDays({
            plan: auth.scope.plan,
            fromTimestamp: query.query.fromTimestamp,
          });
          const queryParams = {
            ...query.query,
            fromTimestamp:
              dataAccessWindow.effectiveFromTimestamp?.toISOString() ??
              query.query.fromTimestamp,
          };

          // Log the received query for debugging
          logger.debug("Received metrics query", {
            query: queryParams,
            projectId: auth.scope.projectId,
          });

          // Execute the query using QueryBuilder
          const result = await executeQuery(auth.scope.projectId, queryParams);

          // Format and return the result
          return {
            data: result,
            // meta: {
            //   page: queryParams.page,
            //   limit: queryParams.limit,
            //   totalItems: result.length,
            //   totalPages: Math.ceil(result.length / queryParams.limit),
            // },
          };
        } catch (error) {
          logger.error("Error in metrics API", { error, query });
          throw error;
        }
      },
    }),
  },
  {
    clickHouseResourceErrorMessage:
      LEGACY_PUBLIC_API_METRICS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,
  },
);