Skip to content

: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.

11.6 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.langfuse._config import LangfuseSourceConfig
from products.warehouse_sources.sources.langfuse.langfuse import (
    HOST_NOT_ALLOWED_ERROR,
    HTTP_NOT_ALLOWED_ERROR,
    REPEATED_CURSOR_ERROR,
    RESPONSE_LIMIT_ERROR,
    TABLE_NOT_IN_VERSION_ERROR,
    LangfuseResumeConfig,
    langfuse_source,
    validate_credentials as validate_langfuse_credentials,
)
from products.warehouse_sources.sources.langfuse.settings import (
    DEFAULT_VERSION,
    INCREMENTAL_FIELDS,
    LANGFUSE_API_VERSION_V1,
    LANGFUSE_API_VERSION_V2,
    LANGFUSE_LEGACY_SUNSET,
    SUPPORTED_VERSIONS,
    endpoints_for_version,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ProductKey,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    VersionDeprecation,
    detect,
)


@SourceRegistry.register
class LangfuseSource(ResumableSource[LangfuseSourceConfig, LangfuseResumeConfig]):
    codebase_detection = detect(
        env=(
            "^LANGFUSE_",
            "^NEXT_PUBLIC_LANGFUSE_PUBLIC_KEY$",
            "^NEXT_PUBLIC_LANGFUSE_BASE_URL$",
            "^CC_LANGFUSE_PUBLIC_KEY$",
            "^CC_LANGFUSE_SECRET_KEY$",
            "^CC_LANGFUSE_BASE_URL$",
            "^HERMES_LANGFUSE_PUBLIC_KEY$",
            "^HERMES_LANGFUSE_SECRET_KEY$",
            "^HERMES_LANGFUSE_BASE_URL$",
            "^TRACE_TO_LANGFUSE$",
        ),
        npm=(
            "langfuse",
            "@langfuse/tracing",
            "@langfuse/otel",
            "@langfuse/client",
            "@langfuse/langchain",
            "langfuse-langchain",
            "langfuse-node",
            "@langfuse/core",
            "@langfuse/browser",
            "@langfuse/openai",
            "@langfuse/vercel-ai-sdk",
            "@langfuse/cli",
            "@langfuse/n8n-nodes-langfuse",
            "@langfuse/opencode-observability-plugin",
            "@langfuse/pi-observability-plugin",
            "@langfuse/codex-observability-plugin",
            "langfuse-core",
            "langfuse-vercel",
            "openclaw-x-langfuse-plugin",
            "@mastra/langfuse",
            "@voltagent/langfuse-exporter",
        ),
        pypi=("langfuse", "langfuse-langchain", "langfuse-haystack", "llama-index-callbacks-langfuse"),
        cargo=("langfuse", "opentelemetry-langfuse", "langfuse-ergonomic", "langfuse-client-base", "swiftide-langfuse"),
        composer=(
            "axyr/laravel-langfuse",
            "janzaba/langfuse",
            "dropsolid/langfuse-php-sdk",
            "lingoda/langfuse-bundle",
            "dij-digital/langfuse-php",
            "dij-digital/langfuse-laravel",
        ),
        go=(
            "github.com/henomis/langfuse-go",
            "github.com/git-hulk/langfuse-go",
            "github.com/wepala/langfuse-go",
            "github.com/oiime/langfuse-go",
        ),
        hex=("langfuse",),
        maven=(
            "com.langfuse:langfuse-java",
            "io.quarkiverse.langfuse:quarkus-langfuse",
            "com.quantpulsar:opentelemetry-exporter-langfuse",
        ),
        rubygems=("langfuse-rb", "langfuse-ruby", "langfuse"),
        alternative_to=(ProductKey.LLM_ANALYTICS,),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    api_docs_url = "https://langfuse.com/docs/api-and-data-platform/features/public-api"

    supported_versions = SUPPORTED_VERSIONS
    default_version = DEFAULT_VERSION
    # The replacement for `/traces` and `/sessions` returns observation rows, not trace or session
    # objects, so v3 drops both tables and sources that sync them need a manual move.
    deprecated_versions = (
        VersionDeprecation(version=LANGFUSE_API_VERSION_V1, sunset_at=LANGFUSE_LEGACY_SUNSET),
        VersionDeprecation(version=LANGFUSE_API_VERSION_V2, sunset_at=LANGFUSE_LEGACY_SUNSET),
    )

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.LANGFUSE

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.LANGFUSE,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Langfuse",
            releaseStatus=ReleaseStatus.GA,
            caption="""Sync traces, observations, scores, sessions, prompts, datasets, and annotation queues from your Langfuse project.

Find your project API keys in your Langfuse **Project settings > API Keys**. Set the host to match your data region (`https://cloud.langfuse.com` for EU, `https://us.cloud.langfuse.com` for US) or your self-hosted instance URL.""",
            iconPath="/static/services/langfuse.svg",
            docsUrl="https://posthog.com/docs/cdp/sources/langfuse",
            keywords=["llm", "observability", "traces", "prompts"],
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="host",
                        label="Host",
                        type=SourceFieldInputConfigType.TEXT,
                        required=False,
                        placeholder="https://cloud.langfuse.com",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="public_key",
                        label="Public key",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="pk-lf-...",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="secret_key",
                        label="Secret key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="sk-lf-...",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.langfuse.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Invalid Langfuse API keys. Check the project public key and secret key, and make sure the host matches your Langfuse data region.",
            "403 Client Error": "Your Langfuse API keys do not have access to this resource. Check the keys and try again.",
            # Every LANGFUSE_ENDPOINTS path is a collection route, and get_rows skips a fan-out child
            # whose parent was deleted, so a 404 here means the route itself doesn't exist on this
            # host - typically a self-hosted instance running a Langfuse version that predates this
            # endpoint. Retrying never helps.
            "404 Client Error": "This Langfuse endpoint was not found on your host. Self-hosted instances on an older Langfuse version may not support it yet - upgrade your instance or remove this table from the sync.",
            HOST_NOT_ALLOWED_ERROR: "The Langfuse host is not allowed. Please use a publicly reachable instance URL.",
            HTTP_NOT_ALLOWED_ERROR: "The Langfuse host must use HTTPS. Please update the host to use https://.",
            RESPONSE_LIMIT_ERROR: "The Langfuse host returned a response that was too large or too slow to download. Check that the host points at a real Langfuse instance.",
            # PAGE_LIMIT_ERROR is intentionally absent: it is retryable, so a huge sync resumes
            # from its checkpoint on the next attempt instead of failing permanently.
            REPEATED_CURSOR_ERROR: "The Langfuse host repeated a pagination cursor, so the sync was stopped to avoid looping. Check that the host points at a real Langfuse instance.",
            TABLE_NOT_IN_VERSION_ERROR: "Langfuse retired the API for this table. Trace and session data is in the observations table: group its rows by traceId or sessionId.",
        }

    def get_retryable_errors(self) -> set[str]:
        # `get_rows`'s tenacity retry already retries a 429/422/5xx (the "Langfuse API error
        # (retryable)" sentinel), a dropped connection, a read timeout, and an interrupted chunked
        # transfer up to MAX_RETRIES. Once that budget exhausts, urllib3 wraps the failure as "Max
        # retries exceeded with url" (with the read timeout nested inside as its cause), and Temporal
        # retries the whole activity from the saved pagination checkpoint, so the failure is
        # transient and self-recovering. The host is customer-controlled (self-hosted Langfuse), so
        # match only the stable, host-independent parts of the message.
        return {
            "Langfuse API error (retryable)",
            "Read timed out",
            "Max retries exceeded with url",
            "Connection broken",
        }

    def get_schemas(
        self,
        config: LangfuseSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        schemas = [
            SourceSchema(
                name=endpoint,
                supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
                supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
            )
            for endpoint in endpoints_for_version(self.resolve_api_version(api_version))
        ]
        if names is not None:
            names_set = set(names)
            schemas = [s for s in schemas if s.name in names_set]
        return schemas

    def validate_credentials(
        self,
        config: LangfuseSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_langfuse_credentials(config.host, config.public_key, config.secret_key, team_id)

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LangfuseResumeConfig]:
        return ResumableSourceManager[LangfuseResumeConfig](inputs, LangfuseResumeConfig)

    def source_for_pipeline(
        self,
        config: LangfuseSourceConfig,
        resumable_source_manager: ResumableSourceManager[LangfuseResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        api_version = self.resolve_api_version(inputs.api_version)
        if inputs.schema_name not in endpoints_for_version(api_version):
            raise ValueError(
                f"{TABLE_NOT_IN_VERSION_ERROR}: '{inputs.schema_name}' is not available on API version {api_version}"
            )

        return langfuse_source(
            host=config.host,
            public_key=config.public_key,
            secret_key=config.secret_key,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
            team_id=inputs.team_id,
            should_use_incremental_field=inputs.should_use_incremental_field,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value
            if inputs.should_use_incremental_field
            else None,
            incremental_field=inputs.incremental_field,
        )