Langfuse JS/TS SDKs
    Preparing search index...

    Class LangfuseClient

    Main client for interacting with the Langfuse API.

    The LangfuseClient provides access to all Langfuse functionality including:

    • Prompt management and retrieval
    • Dataset operations
    • Score creation and management
    • Media upload and handling
    • Direct API access for advanced use cases
    // Initialize with explicit credentials
    const langfuse = new LangfuseClient({
    publicKey: "pk_...",
    secretKey: "sk_...",
    baseUrl: "https://cloud.langfuse.com"
    });

    // Or use environment variables
    const langfuse = new LangfuseClient();

    // Use the client
    const prompt = await langfuse.prompt.get("my-prompt");
    const compiledPrompt = prompt.compile({ variable: "value" });
    Index

    Constructors

    • Creates a new LangfuseClient instance.

      Parameters

      • Optionalparams: LangfuseClientParams

        Configuration parameters. If not provided, will use environment variables.

      Returns LangfuseClient

      Will log warnings if required credentials are not provided

      // With explicit configuration
      const client = new LangfuseClient({
      publicKey: "pk_...",
      secretKey: "sk_...",
      baseUrl: "https://your-instance.langfuse.com"
      });

      // Using environment variables
      const client = new LangfuseClient();

    Properties

    api: LangfuseAPIClient

    Direct access to the underlying Langfuse API client. Use this for advanced API operations not covered by the high-level managers.

    createDataset: (
        request: CreateDatasetRequest,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<Dataset>

    Type declaration

      • (
            request: CreateDatasetRequest,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<Dataset>
      • Create a dataset

        Parameters

        • request: CreateDatasetRequest
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<Dataset>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.datasets.create({
        name: "name",
        description: undefined,
        metadata: undefined
        })

    Use api.datasets.create instead

    createDatasetItem: (
        request: CreateDatasetItemRequest,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<DatasetItem>

    Type declaration

      • (
            request: CreateDatasetItemRequest,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<DatasetItem>
      • Create a dataset item

        Parameters

        • request: CreateDatasetItemRequest
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<DatasetItem>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.datasetItems.create({
        datasetName: "datasetName",
        input: undefined,
        expectedOutput: undefined,
        metadata: undefined,
        sourceTraceId: undefined,
        sourceObservationId: undefined,
        id: undefined,
        status: undefined
        })

    Use api.datasetItems.create instead

    createPrompt: {
        (body: CreateChatPromptBodyWithPlaceholders): Promise<ChatPromptClient>;
        (body: Omit<Text, "type"> & { type?: "text" }): Promise<TextPromptClient>;
        (body: Chat): Promise<ChatPromptClient>;
    }

    Type declaration

    Use prompt.create instead

    Manager for dataset operations including retrieval and item linking.

    fetchMedia: (
        mediaId: string,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<GetMediaResponse>

    Type declaration

      • (
            mediaId: string,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<GetMediaResponse>
      • Get a media record

        Parameters

        • mediaId: string

          The unique langfuse identifier of a media record

        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<GetMediaResponse>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.media.get("mediaId")
        

    Use api.media.get instead

    fetchObservation: (
        observationId: string,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<ObservationsView>

    Type declaration

      • (
            observationId: string,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<ObservationsView>
      • Get a observation

        Parameters

        • observationId: string

          The unique langfuse identifier of an observation, can be an event, span or generation

        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<ObservationsView>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.observations.get("observationId")
        

    Use api.observations.get instead

    fetchObservations: (
        request?: GetObservationsRequest,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<ObservationsViews>

    Type declaration

      • (
            request?: GetObservationsRequest,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<ObservationsViews>
      • Get a list of observations

        Parameters

        • Optionalrequest: GetObservationsRequest
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<ObservationsViews>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.observations.getMany()
        

    Use api.observations.list instead

    fetchSessions: (
        sessionId: string,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<SessionWithTraces>

    Type declaration

      • (
            sessionId: string,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<SessionWithTraces>
      • Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId>

        Parameters

        • sessionId: string

          The unique id of a session

        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<SessionWithTraces>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.sessions.get("sessionId")
        

    Use api.sessions.get instead

    fetchTrace: (
        traceId: string,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<TraceWithFullDetails>

    Type declaration

      • (
            traceId: string,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<TraceWithFullDetails>
      • Get a specific trace

        Parameters

        • traceId: string

          The unique langfuse identifier of a trace

        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<TraceWithFullDetails>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.trace.get("traceId")
        

    Use api.trace.get instead

    fetchTraces: (
        request?: GetTracesRequest,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<Traces>

    Type declaration

      • (
            request?: GetTracesRequest,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<Traces>
      • Get list of traces

        Parameters

        • Optionalrequest: GetTracesRequest
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<Traces>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.trace.list()
        

    Use api.trace.list instead

    getDataset: (
        name: string,
        options?: { fetchItemsPageSize: number },
    ) => Promise<
        Dataset & { items: (DatasetItem & { link: LinkDatasetItemFunction })[] },
    >

    Type declaration

      • (
            name: string,
            options?: { fetchItemsPageSize: number },
        ): Promise<
            Dataset & { items: (DatasetItem & { link: LinkDatasetItemFunction })[] },
        >
      • Retrieves a dataset by name along with all its items.

        This method automatically handles pagination to fetch all dataset items and enhances each item with a link function for easy experiment tracking.

        Parameters

        • name: string

          The name of the dataset to retrieve

        • Optionaloptions: { fetchItemsPageSize: number }

          Optional configuration for fetching

          • fetchItemsPageSize: number

            Number of items to fetch per page (default: 50)

        Returns Promise<
            Dataset & { items: (DatasetItem & { link: LinkDatasetItemFunction })[] },
        >

        Promise that resolves to the dataset with enhanced items

        const dataset = await langfuse.dataset.get("my-dataset");

        for (const item of dataset.items) {
        // Use the item data for your experiment
        const result = await processItem(item.input);

        // Link the result to the dataset item
        await item.link(
        { otelSpan: currentSpan },
        "experiment-run-1",
        { description: "Testing new model" }
        );
        }

    Use dataset.get instead

    getDatasetItem: (
        id: string,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<DatasetItem>

    Type declaration

      • (id: string, requestOptions?: RequestOptions): HttpResponsePromise<DatasetItem>
      • Get a dataset item

        Parameters

        • id: string
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<DatasetItem>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.datasetItems.get("id")
        

    Use api.datasetItems.get instead

    getDatasetRun: (
        datasetName: string,
        runName: string,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<DatasetRunWithItems>

    Type declaration

      • (
            datasetName: string,
            runName: string,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<DatasetRunWithItems>
      • Get a dataset run and its items

        Parameters

        • datasetName: string
        • runName: string
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<DatasetRunWithItems>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.datasets.getRun("datasetName", "runName")
        

    Use api.datasets.getRun instead

    getDatasetRuns: (
        datasetName: string,
        request?: GetDatasetRunsRequest,
        requestOptions?: RequestOptions,
    ) => HttpResponsePromise<PaginatedDatasetRuns>

    Type declaration

      • (
            datasetName: string,
            request?: GetDatasetRunsRequest,
            requestOptions?: RequestOptions,
        ): HttpResponsePromise<PaginatedDatasetRuns>
      • Get dataset runs

        Parameters

        • datasetName: string
        • Optionalrequest: GetDatasetRunsRequest
        • OptionalrequestOptions: RequestOptions

          Request-specific configuration.

        Returns HttpResponsePromise<PaginatedDatasetRuns>

        LangfuseAPI.Error

        LangfuseAPI.UnauthorizedError

        LangfuseAPI.AccessDeniedError

        LangfuseAPI.MethodNotAllowedError

        LangfuseAPI.NotFoundError

        await client.datasets.getRuns("datasetName")
        

    Use api.datasets.getRuns instead

    getPrompt: {
        (
            name: string,
            options?: {
                cacheTtlSeconds?: number;
                fallback?: string;
                fetchTimeoutMs?: number;
                label?: string;
                maxRetries?: number;
                type?: "text";
                version?: number;
            },
        ): Promise<TextPromptClient>;
        (
            name: string,
            options?: {
                cacheTtlSeconds?: number;
                fallback?: ChatMessage[];
                fetchTimeoutMs?: number;
                label?: string;
                maxRetries?: number;
                type: "chat";
                version?: number;
            },
        ): Promise<ChatPromptClient>;
    }

    Type declaration

      • (
            name: string,
            options?: {
                cacheTtlSeconds?: number;
                fallback?: string;
                fetchTimeoutMs?: number;
                label?: string;
                maxRetries?: number;
                type?: "text";
                version?: number;
            },
        ): Promise<TextPromptClient>
      • Retrieves a text prompt by name.

        Parameters

        • name: string

          Name of the prompt to retrieve

        • Optionaloptions: {
              cacheTtlSeconds?: number;
              fallback?: string;
              fetchTimeoutMs?: number;
              label?: string;
              maxRetries?: number;
              type?: "text";
              version?: number;
          }

          Optional retrieval configuration

          • OptionalcacheTtlSeconds?: number

            Cache TTL in seconds (0 to disable caching)

          • Optionalfallback?: string

            Fallback text content if prompt fetch fails

          • OptionalfetchTimeoutMs?: number

            Request timeout in milliseconds

          • Optionallabel?: string

            Label to filter by

          • OptionalmaxRetries?: number

            Maximum retry attempts for failed requests

          • Optionaltype?: "text"

            Specify text prompt type

          • Optionalversion?: number

            Specific version to retrieve (defaults to latest)

        Returns Promise<TextPromptClient>

        Promise that resolves to a TextPromptClient

      • (
            name: string,
            options?: {
                cacheTtlSeconds?: number;
                fallback?: ChatMessage[];
                fetchTimeoutMs?: number;
                label?: string;
                maxRetries?: number;
                type: "chat";
                version?: number;
            },
        ): Promise<ChatPromptClient>
      • Retrieves a chat prompt by name.

        Parameters

        • name: string

          Name of the prompt to retrieve

        • Optionaloptions: {
              cacheTtlSeconds?: number;
              fallback?: ChatMessage[];
              fetchTimeoutMs?: number;
              label?: string;
              maxRetries?: number;
              type: "chat";
              version?: number;
          }

          Optional retrieval configuration

          • OptionalcacheTtlSeconds?: number

            Cache TTL in seconds (0 to disable caching)

          • Optionalfallback?: ChatMessage[]

            Fallback chat messages if prompt fetch fails

          • OptionalfetchTimeoutMs?: number

            Request timeout in milliseconds

          • Optionallabel?: string

            Label to filter by

          • OptionalmaxRetries?: number

            Maximum retry attempts for failed requests

          • type: "chat"

            Specify chat prompt type

          • Optionalversion?: number

            Specific version to retrieve (defaults to latest)

        Returns Promise<ChatPromptClient>

        Promise that resolves to a ChatPromptClient

    Use prompt.get instead

    Manager for media upload and reference resolution.

    Manager for prompt operations including creation, retrieval, and caching.

    resolveMediaReferences: <T>(
        params: LangfuseMediaResolveMediaReferencesParams<T>,
    ) => Promise<T>

    Type declaration

      • <T>(params: LangfuseMediaResolveMediaReferencesParams<T>): Promise<T>
      • Replaces media reference strings in an object with base64 data URIs.

        This method recursively traverses an object looking for media reference strings in the format "@@@langfuseMedia:...@@@". When found, it fetches the actual media content from Langfuse and replaces the reference string with a base64 data URI.

        If fetching media content fails for a reference string, a warning is logged and the reference string is left unchanged.

        Type Parameters

        • T

        Parameters

        Returns Promise<T>

        A deep copy of the input object with media references resolved

        const obj = {
        image: "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@",
        nested: {
        pdf: "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@"
        }
        };

        const result = await langfuse.media.resolveReferences({
        obj,
        resolveWith: "base64DataUri"
        });

        // Result:
        // {
        // image: "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
        // nested: {
        // pdf: "data:application/pdf;base64,JVBERi0xLjcK..."
        // }
        // }

    Use media.resolveReferences instead

    Manager for score creation and batch processing.

    updatePrompt: (
        params: { name: string; newLabels: string[]; version: number },
    ) => Promise<Prompt>

    Type declaration

      • (
            params: { name: string; newLabels: string[]; version: number },
        ): Promise<Prompt>
      • Updates the labels of an existing prompt version.

        Parameters

        • params: { name: string; newLabels: string[]; version: number }

          Update parameters

          • name: string

            Name of the prompt to update

          • newLabels: string[]

            New labels to apply to the prompt version

          • version: number

            Version number of the prompt to update

        Returns Promise<Prompt>

        Promise that resolves to the updated prompt

        const updatedPrompt = await langfuse.prompt.update({
        name: "my-prompt",
        version: 1,
        newLabels: ["production", "v2"]
        });

    Use prompt.update instead

    Methods

    • Flushes any pending score events to the Langfuse API.

      This method ensures all queued scores are sent immediately rather than waiting for the automatic flush interval or batch size threshold.

      Returns Promise<void>

      Promise that resolves when all pending scores have been sent

      langfuse.score.create({ name: "quality", value: 0.8 });
      await langfuse.flush(); // Ensures the score is sent immediately
    • Generates a URL to view a specific trace in the Langfuse UI.

      Parameters

      • traceId: string

        The ID of the trace to generate a URL for

      Returns Promise<string>

      Promise that resolves to the trace URL

      const traceId = "trace-123";
      const url = await langfuse.getTraceUrl(traceId);
      console.log(`View trace at: ${url}`);
    • Gracefully shuts down the client by flushing all pending data.

      This method should be called before your application exits to ensure all data is sent to Langfuse.

      Returns Promise<void>

      Promise that resolves when shutdown is complete

      // Before application exit
      await langfuse.shutdown();