:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
from dataclasses import dataclass, field
from datetime import date, timedelta
from typing import Literal, Optional
from products.warehouse_sources.sources.sdk import UNVERSIONED_API_VERSION, IncrementalField, IncrementalFieldType
# Source-level vendor API version labels. Distinct from the per-endpoint URL versions baked into
# LANGFUSE_ENDPOINTS below (Langfuse versions each resource route independently). v1 and v2 resolve
# to the same wire: v1 keeps the pre-versioning UNVERSIONED default so already-pinned rows resolve
# unchanged. Both read the `/traces` and `/sessions` routes Langfuse Cloud stops serving on
# 2026-11-16; v3 drops those tables, as `observations` already carries traceId and sessionId.
LANGFUSE_API_VERSION_V1 = UNVERSIONED_API_VERSION
LANGFUSE_API_VERSION_V2 = "v2"
LANGFUSE_API_VERSION_V3 = "v3"
SUPPORTED_VERSIONS = (LANGFUSE_API_VERSION_V1, LANGFUSE_API_VERSION_V2, LANGFUSE_API_VERSION_V3)
DEFAULT_VERSION = LANGFUSE_API_VERSION_V3
LANGFUSE_LEGACY_SUNSET = date(2026, 11, 16)
def _datetime_incremental_field(name: str) -> IncrementalField:
return {
"label": name,
"type": IncrementalFieldType.DateTime,
"field": name,
"field_type": IncrementalFieldType.DateTime,
}
# Mutable to stay consistent with the other per-endpoint config objects in this package; these
# are module-level constants that nothing reassigns.
@dataclass(frozen=False)
class LangfuseEndpointConfig:
name: str
path: str
# "page" endpoints use ?page=N with a meta.totalPages envelope; "cursor" endpoints
# (v2 observations, v3 scores) return an opaque meta.cursor for the next page.
pagination: Literal["page", "cursor"]
page_size: int
incremental_fields: list[IncrementalField] = field(default_factory=list)
default_incremental_field: Optional[str] = None
# Server-side lower-bound query param for the incremental field (e.g. fromTimestamp).
incremental_filter_param: Optional[str] = None
# Extra query params sent on every request (orderBy, fields selection, ...).
extra_params: dict[str, str] = field(default_factory=dict)
primary_keys: list[str] = field(default_factory=lambda: ["id"])
partition_key: Optional[str] = None
# The order rows are emitted in. Only traces accepts an explicit orderBy, which we pin
# ascending; the other list endpoints return newest-first, so they are "desc".
sort_mode: Literal["asc", "desc"] = "desc"
# Safety overlap subtracted from the incremental watermark each run. Langfuse's time filters
# are on event/creation time, so rows that arrive late (ingestion lag) would otherwise be
# skipped forever. Re-pulled rows are deduped on the primary key by merge.
incremental_lookback: Optional[timedelta] = None
# Fields the API documents as fractional (USD costs, second-precision durations) but sends as
# plain JSON numbers, so a page holding only whole values infers an integer column. On an
# ascending backfill the first page is the oldest traffic, which is where costs are most often
# a flat 0. The table adopts int64, and every later fractional value then fails to cast.
float_fields: frozenset[str] = frozenset()
# Split a score `value` whose type follows the row's dataType (a number, a boolean, or a string)
# into a numeric `value` and a text `stringValue`, the shape of the legacy scores API. Arrow holds
# one type per column, so a page that mixes NUMERIC and CATEGORICAL scores fails to load.
split_score_values: bool = False
# Page the endpoint by keyset instead of by offset: after each page, move the from-filter up to
# the newest row seen and restart at page 1. Langfuse answers a deep offset with a 422 resource
# limit, which kills a backfill that walks far enough. Only safe on an endpoint that is pinned
# ascending on the field the from-filter applies to, so a later page never holds an earlier row.
keyset_pagination: bool = False
# Fan-out child: `path` holds a `{parent_id}` placeholder, filled with the `id` of every row of
# this parent endpoint.
parent: Optional[str] = None
# From-filter value sent when no incremental watermark applies, for endpoints that reject a
# request without a lower bound (experiments).
required_from_value: Optional[str] = None
_DEFAULT_LOOKBACK = timedelta(hours=1)
# Observation field groups: everything the v2 endpoint can return. Without this the API only
# returns the `core` and `basic` groups (no io/usage/cost columns).
_OBSERVATION_FIELDS = "core,basic,time,io,metadata,model,usage,prompt,metrics,trace_context"
# Score field groups added on top of the always-returned core fields.
_SCORE_FIELDS = "details,subject,annotation"
# Experiment field groups. `scores` is left out: those rows are already synced by the scores table.
_EXPERIMENT_FIELDS = "core,metadata"
_EXPERIMENT_ITEM_FIELDS = "core,dataset,io,metadata,itemMetadata,experimentMetadata"
# The experiments endpoints require fromStartTime, so a full sync sends a bound before any data.
_EARLIEST_START_TIME = "1970-01-01T00:00:00Z"
# Endpoints cover the resources a user most commonly wants to analyze from an LLM observability
# platform: traces, observations, scores, sessions, prompts, datasets, model pricing, score
# configs, annotation queues, experiments, and comments.
# Incremental support is only declared where the API documents a server-side timestamp filter.
LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {
"traces": LangfuseEndpointConfig(
name="traces",
path="/api/public/traces",
pagination="page",
page_size=50,
incremental_fields=[_datetime_incremental_field("timestamp")],
default_incremental_field="timestamp",
incremental_filter_param="fromTimestamp",
# Pin a stable ascending order so pages don't shift as new traces arrive mid-sync,
# and so the pipeline's incremental watermark advances safely per batch.
extra_params={"orderBy": "timestamp.asc"},
partition_key="timestamp",
sort_mode="asc",
incremental_lookback=_DEFAULT_LOOKBACK,
float_fields=frozenset({"totalCost", "latency"}),
keyset_pagination=True,
),
"observations": LangfuseEndpointConfig(
name="observations",
path="/api/public/v2/observations",
pagination="cursor",
page_size=1000, # documented maximum for the v2 bulk endpoint
incremental_fields=[_datetime_incremental_field("startTime")],
default_incremental_field="startTime",
incremental_filter_param="fromStartTime",
extra_params={"fields": _OBSERVATION_FIELDS},
partition_key="startTime",
# v2 observations return newest-first (startTime descending) and accept no orderBy.
sort_mode="desc",
incremental_lookback=_DEFAULT_LOOKBACK,
float_fields=frozenset({"totalCost", "latency", "timeToFirstToken"}),
),
"scores": LangfuseEndpointConfig(
name="scores",
path="/api/public/v3/scores",
pagination="cursor",
page_size=100, # documented maximum for the v3 scores endpoint
incremental_fields=[_datetime_incremental_field("timestamp")],
default_incremental_field="timestamp",
incremental_filter_param="fromTimestamp",
extra_params={"fields": _SCORE_FIELDS},
split_score_values=True,
partition_key="timestamp",
sort_mode="desc",
incremental_lookback=_DEFAULT_LOOKBACK,
),
"sessions": LangfuseEndpointConfig(
name="sessions",
path="/api/public/sessions",
pagination="page",
page_size=50,
incremental_fields=[_datetime_incremental_field("createdAt")],
default_incremental_field="createdAt",
incremental_filter_param="fromTimestamp",
partition_key="createdAt",
sort_mode="desc",
incremental_lookback=_DEFAULT_LOOKBACK,
),
"prompts": LangfuseEndpointConfig(
name="prompts",
path="/api/public/v2/prompts",
pagination="page",
page_size=50,
incremental_fields=[_datetime_incremental_field("lastUpdatedAt")],
default_incremental_field="lastUpdatedAt",
incremental_filter_param="fromUpdatedAt",
# One row per prompt name (with a versions array); no stable creation field to partition on.
primary_keys=["name"],
sort_mode="desc",
),
"datasets": LangfuseEndpointConfig(
name="datasets",
path="/api/public/v2/datasets",
pagination="page",
page_size=50,
# No server-side timestamp filter -> full refresh only.
),
"dataset_items": LangfuseEndpointConfig(
name="dataset_items",
path="/api/public/dataset-items",
pagination="page",
page_size=50,
# Only filterable by datasetName/version, not by time -> full refresh only.
partition_key="createdAt",
),
"models": LangfuseEndpointConfig(
name="models",
path="/api/public/models",
pagination="page",
page_size=50,
# No server-side timestamp filter -> full refresh only.
),
"score_configs": LangfuseEndpointConfig(
name="score_configs",
path="/api/public/score-configs",
pagination="page",
page_size=50,
# No server-side timestamp filter -> full refresh only.
partition_key="createdAt",
),
"annotation_queues": LangfuseEndpointConfig(
name="annotation_queues",
path="/api/public/annotation-queues",
pagination="page",
page_size=50,
# No server-side timestamp filter -> full refresh only.
partition_key="createdAt",
),
"annotation_queue_items": LangfuseEndpointConfig(
name="annotation_queue_items",
path="/api/public/annotation-queues/{parent_id}/items",
pagination="page",
page_size=50,
parent="annotation_queues",
# Only filterable by status, not by time -> full refresh only.
primary_keys=["queueId", "id"],
partition_key="createdAt",
),
"experiments": LangfuseEndpointConfig(
name="experiments",
path="/api/public/experiments",
pagination="cursor",
page_size=100, # documented maximum
# Full refresh only: startTime and itemCount are computed over the requested window, so a
# windowed incremental sync would overwrite each row with partial totals.
incremental_filter_param="fromStartTime",
required_from_value=_EARLIEST_START_TIME,
extra_params={"fields": _EXPERIMENT_FIELDS},
),
"experiment_items": LangfuseEndpointConfig(
name="experiment_items",
path="/api/public/experiment-items",
pagination="cursor",
page_size=100, # documented maximum
incremental_fields=[_datetime_incremental_field("startTime")],
default_incremental_field="startTime",
incremental_filter_param="fromStartTime",
required_from_value=_EARLIEST_START_TIME,
extra_params={"fields": _EXPERIMENT_ITEM_FIELDS},
primary_keys=["experimentId", "id"],
partition_key="startTime",
# Documented as ordered by time descending.
sort_mode="desc",
incremental_lookback=_DEFAULT_LOOKBACK,
),
"comments": LangfuseEndpointConfig(
name="comments",
path="/api/public/comments",
pagination="page",
page_size=50,
# Only filterable by object and author, not by time -> full refresh only.
partition_key="createdAt",
),
}
ENDPOINTS = tuple(LANGFUSE_ENDPOINTS.keys())
LEGACY_ONLY_ENDPOINTS = frozenset({"traces", "sessions"})
ENDPOINTS_BY_VERSION: dict[str, tuple[str, ...]] = {
LANGFUSE_API_VERSION_V1: ENDPOINTS,
LANGFUSE_API_VERSION_V2: ENDPOINTS,
LANGFUSE_API_VERSION_V3: tuple(name for name in ENDPOINTS if name not in LEGACY_ONLY_ENDPOINTS),
}
def endpoints_for_version(api_version: str) -> tuple[str, ...]:
try:
return ENDPOINTS_BY_VERSION[api_version]
except KeyError as e:
raise ValueError(f"Unsupported Langfuse API version: {api_version!r}") from e
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in LANGFUSE_ENDPOINTS.items()
}