Langfuse: Observability and Evaluation for LLM Applications — The Complete Guide in 9 Chapters

Langfuse is an open-source platform for observing and evaluating applications built on large language models. When a chatbot gives a wrong answer, a retrieval step fetches the wrong document, or a monthly model bill suddenly doubles, the cause is rarely visible in ordinary application logs. Langfuse records what happened inside each model call, how long it took, what it cost, and how good the result was, so teams can debug and improve their systems with evidence instead of guesswork.

This guide explains Langfuse from first principles to production use, in nine chapters. It covers the core data model, a self-hosted installation with Docker Compose, a hands-on Python example, prompt management, evaluation, production monitoring, the AI Gateway, and the limits that decide whether the platform fits your project. Every version number, date, and technical claim in this article was checked against the official Langfuse documentation and the project’s public repositories on 6 December 2026. At that date the latest platform release was v4.94.0, published on 4 December 2026, and the Python SDK was at v5.3.0, published on 2 December 2026.

Langfuse describes itself as an open-source AI engineering platform, and that wording is precise. It is not only a logging tool: tracing, prompt management, evaluation, and a gateway for model traffic are parts of one system, so the trace you inspect while debugging is the same record you score in an experiment and the same data that feeds a cost dashboard. The open-source core is licensed under the MIT licence, while enterprise features live in separate folders in the repository. The project has attracted more than 38,000 stars on GitHub, and it was acquired by ClickHouse in January 2026.

1. What Langfuse Is and the Observability Problem It Solves

Traditional software is deterministic: given the same input, the same code produces the same output, and a stack trace usually points at the fault. Applications built on large language models behave differently. The same prompt can produce different answers, a small wording change can alter quality, a retrieval step can silently return irrelevant context, and every call has a price measured in tokens. When users report a bad answer, developers often have no record of the prompt, the model version, the retrieved documents, or the intermediate steps that produced it.

Langfuse closes that gap by recording the full execution of each request. It captures prompts and completions, token counts, latency, cost, model names, and the sequence of steps an agent took. That record turns a vague complaint, such as the assistant gave a wrong answer, into a concrete question that can be answered from data: which prompt version was used, what context was retrieved, and where the chain first went wrong.

The platform is useful in two settings. During development, it shortens the loop between changing a prompt and seeing the effect. In production, it provides the visibility that operations teams expect from any serious system: error rates, latency distributions, cost per user, and alerts when something drifts. Teams can run Langfuse as a hosted service, Langfuse Cloud, or self-host it on their own infrastructure, which keeps every trace inside their own network. Chapter 3 walks through the self-hosted route.

2. Core Concepts: Traces, Spans, Generations, Sessions and Scores

Langfuse organises observations into a small set of concepts. A trace is the top-level record of one end-to-end request, for example one user question to a chatbot. Inside a trace, spans represent individual units of work, such as a retrieval step, a tool call, or a chunk of application code. A generation is a specific kind of span: a single call to a language model, with its prompt, completion, model name, token usage, latency, and cost.

This hierarchy matters because it matches how LLM applications actually fail. A trace can look slow overall while one generation inside it is responsible for most of the latency. A wrong answer can be traced to a span that retrieved the wrong document rather than to the model itself. By nesting generations inside spans inside traces, Langfuse lets you open a request and read it like a story, from the user’s input down to each model call.

A session groups related traces, typically one conversation or one user’s sequence of interactions. Sessions make it possible to review a whole conversation, including how a follow-up question depended on earlier turns, rather than judging single exchanges in isolation. Stateful agents benefit most from this view: if you build agents that remember context across steps, the companion guide to building stateful agents with LangGraph explains the design patterns whose behaviour sessions make visible.

Scores are the platform’s way of recording quality. A score can be numeric, categorical, or boolean, and it can be attached to a trace, a span, or a generation. Scores come from several sources: a user pressing a thumbs-up button, a human reviewer, a code-based check such as exact match, or a model-based evaluation. Because scores live next to the traces they judge, a team can filter for low-scoring traces and read exactly what went wrong, instead of debating averages in a spreadsheet.

Two supporting ideas complete the model. Metadata and tags let you label traces with the environment, the prompt version, the customer, or any other dimension you want to slice by. User identifiers link traces to people or accounts, which is the basis for per-user cost and quality analysis. Together, traces, spans, generations, sessions, and scores give one consistent vocabulary for describing everything an LLM application does.

3. Self-Hosting Langfuse with Docker Compose

Self-hosting is the most direct way to try Langfuse, and it is also the option that gives the strongest data control: prompts, completions, and evaluation data never leave your machine. The official Docker Compose setup runs seven services: the web application, a background worker, the AI Gateway, ClickHouse, MinIO for object storage, Redis, and PostgreSQL. The web interface listens on port 3000, MinIO on port 9090, and the AI Gateway on port 3031. The documented minimum for a single machine is 4 CPU cores, 16 GiB of RAM, and 100 GiB of disk, with PostgreSQL 17 and ClickHouse 25.12 or later.

A server room with rows of rack-mounted servers, illustrating self-hosting Langfuse inside your own infrastructure
A server room: self-hosting keeps every trace inside your own infrastructure. Credit: BalticServers.com, CC BY-SA 3.0, via Wikimedia Commons.

The installation itself is short. Clone the repository, enter the directory, and start the stack:

git clone https://github.com/langfuse/langfuse.git
cd langfuse
docker compose up -d

After the containers are healthy, open http://localhost:3000 in a browser. The first account you create becomes the administrator, so choose its credentials carefully. From there, create a project and copy its public key, secret key, and host address into your application’s environment. That is all the setup the SDK needs.

Upgrading follows the same Compose pattern: pull the new images and restart the stack. For anything beyond a local experiment, add the usual production discipline around the Compose file: a reverse proxy with TLS, persistent volumes that are actually backed up, and secrets managed outside the repository. The Compose deployment is convenient, but it is still your infrastructure to operate. If you want a broader comparison of self-hosting trade-offs first, the guide to self-hosting Open WebUI covers the same kind of decisions for another open-source AI tool.

4. Your First Trace: Instrumenting a Python Application

Instrumentation is where Langfuse starts to feel concrete. The Python SDK, currently at v5.3.0, is built on OpenTelemetry, and it offers two complementary styles: a drop-in wrapper for the OpenAI client, which records model calls without changing your application logic, and a decorator for your own functions, which turns them into traced spans. The example below combines both. It is adapted from the official tracing quickstart, with the function and prompt written for this guide.

Python source code on a computer screen, illustrating how a few lines with the Langfuse SDK instrument an application
Python code on screen: instrumenting an application is a few lines with the Langfuse SDK. Credit: MikeRun, CC BY-SA 4.0, via Wikimedia Commons.

First install the SDK and the OpenAI client, then set three environment variables from your project settings:

pip install langfuse openai

export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_HOST="http://localhost:3000"

Then wrap your function. The @observe decorator creates a trace for the function call, and the wrapped OpenAI client records the generation inside it:

from langfuse import Langfuse, observe
from langfuse.openai import openai

langfuse = Langfuse()

@observe()
def summarise(text: str) -> str:
    response = openai.chat.completions.create(
        name="summarise-call",
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "Summarise the text in three short sentences."},
            {"role": "user", "content": text},
        ],
        metadata={"user_id": "demo-user"},
    )
    return response.choices[0].message.content

print(summarise("Langfuse records prompts, completions, tokens, latency and cost for every model call."))
langfuse.flush()

Run the script, then open the Traces view in the Langfuse interface. You should see one trace named after the decorated function, containing a generation with the prompt, the completion, the token counts, and the cost. The name argument labels the generation, and the metadata argument attaches the user identifier so the trace can be found later. The final flush() call sends any buffered events before the process exits, which matters for short scripts and serverless functions.

A few habits make instrumentation pay off over time. Give generations and spans meaningful names instead of accepting defaults, attach user identifiers and environment metadata to every trace, and keep the secret key on the server only, never in client-side code or a public repository. Tracing has a cost of its own: each recorded call adds data to your ClickHouse store, so record what you need and use sampling or retention settings when volume grows.

5. Prompt Management and Versioning

Prompts are code, but they are usually treated as string literals scattered through an application. Langfuse treats them as managed objects. A prompt has a name, a set of versions, and labels such as production that point at the version currently in use. When you change a prompt in the interface and move the label, the application picks up the new version on its next fetch, without a redeploy.

This separation changes how teams work. A product manager can propose a wording change, a developer can review the diff between versions, and an experiment can compare two versions against the same dataset, as described in Chapter 6. Every trace records which prompt version produced it, so a regression can be traced back to the exact wording change that caused it. Without versioning, the same investigation depends on guessing which commit was deployed when the bad answer appeared.

Versioning also supports safer rollouts. A new prompt version can be tested on a small share of traffic or in an experiment before it becomes the production version, and the previous version remains available for an instant rollback. The discipline is the same one software teams apply to code and database migrations: change one thing at a time, keep the history, and make the current state explicit.

6. Evaluation: Datasets, Experiments and LLM-as-a-Judge

Evaluation is where Langfuse moves from observation to improvement. A dataset is a versioned collection of test cases, each with an input and, where relevant, an expected output. Instead of judging a prompt by trying it on three examples by hand, you run it against the whole dataset and read the aggregated scores.

An experiment runs a dataset through your application, a prompt version, or a model, and records the result of every item together with its scores. Because experiments are stored, you can compare runs side by side: the same prompt with two models, two prompts with the same model, or the current production prompt against a candidate. The comparison is fair because the inputs are identical and the scoring is applied consistently.

Scores in an experiment can come from several kinds of evaluator. Code-based checks cover objective cases, such as whether an answer matches an expected value or whether a JSON response parses. Human reviewers can score a sample of outputs directly in the interface. LLM-as-a-judge uses a model to score outputs against criteria you write, such as faithfulness to the retrieved context or the tone of a reply. Model-based judging is fast and cheap, but it has its own biases, so it works best when calibrated against human judgement on a sample of cases before you trust it at scale.

The practical loop is simple and repeatable: collect failing traces from production, add them to a dataset, change the prompt or the retrieval step, run an experiment, and ship only if the scores improve without regressing elsewhere. Over time the dataset becomes a regression suite for the behaviour of your application, and the scores become the evidence behind each release decision.

7. Monitoring Production: Dashboards, Topics, Alerts and Cost Tracking

Once an application is live, the question changes from whether it works to whether it keeps working. Langfuse provides custom dashboards that summarise trace volume, latency, token usage, cost, and score distributions over time. A dashboard can be scoped to a model, a user, a prompt version, or any tag you attach to traces, so a spike can be narrowed to its cause instead of being treated as a mystery.

Topics let you group traces by subject, for example by feature area or by the kind of request. Combined with scores, they answer questions such as which topic produces the most low-rated answers, or where users abandon a conversation. Alerts watch a metric and notify you when it crosses a threshold, so a cost spike or a latency regression is discovered by the system rather than by a customer complaint.

Cost tracking deserves special attention because language model pricing is usage-based and easy to lose sight of. Langfuse records token counts and the resulting cost for each generation, and aggregates them by model, user, and time period. That makes it possible to see which model dominates the bill, which users are the most expensive to serve, and whether a prompt change that improved quality also doubled the cost. The LLM Playground, built into the interface, lets you test prompt changes against the same models and compare the results before deploying them.

8. AI Gateway and Integrations

The AI Gateway is Langfuse’s single entry point for model traffic. Instead of each service calling providers directly, calls pass through the gateway, which handles routing to the right model, fallbacks when a provider fails, load balancing, and caching. Centralising traffic this way also centralises observability: every call is traced and costed in the same place, whatever the provider behind it.

Integrations cover the tools most teams already use. The OpenAI integration is a drop-in module, as shown in Chapter 4: importing the wrapped client records generations without rewriting application code. LangChain and LlamaIndex integrations trace the steps of chains and agents, including retrieval and tool calls, which is where multi-step applications are hardest to debug. LiteLLM support brings the same tracing to applications that route through a unified model interface. If you are building with LangChain and want the full picture of how agents are structured, the guide to building AI agents with LangChain pairs naturally with this chapter.

Because the SDKs are built on OpenTelemetry, Langfuse also fits into wider observability setups. Traces can be exported in the OpenTelemetry format, and the platform exposes an MCP server and a command-line interface for programmatic access. The practical point is that adopting Langfuse does not require abandoning your existing stack: it observes the calls your application already makes, through the libraries you already use.

9. Limits, Costs and When Langfuse Fits

Langfuse is a strong fit when an LLM application is in production, or heading there, and when quality, cost, and reliability matter enough to measure. It fits teams that iterate on prompts, run agents with several steps, serve multiple users, or need to show how a model behaved for compliance or debugging. The combination of tracing, prompt versioning, and evaluation in one system is the main reason to choose it over assembling separate tools.

It is less obviously the right choice for a one-off script or a small prototype. A weekend experiment that makes a handful of model calls gains little from a full observability stack, and the effort of running the platform would exceed the benefit. A hosted account lowers that barrier, but the decision should still follow the volume and the stakes of the application.

Self-hosting has real costs of its own. Seven services need operating, upgrading, and backing up, and trace volume grows with usage, so ClickHouse storage and retention need planning. The hosted Cloud option removes the operational work in exchange for a usage-based price. Whichever route you choose, treat ingestion volume as a budget: trace what you need, sample or drop what you do not, and set retention so storage grows predictably.

Version support is worth checking before you commit. Version 4 became generally available on 29 July 2026, and Langfuse Cloud has been v4-only since 16 November 2026. Version 3 receives security patches only until the end of January 2027, so a self-hosted installation still on v3 should plan its upgrade. The platform also keeps adding surface area, including skill management in beta, so check the current documentation before assuming a feature list is complete.

Summary

Langfuse gives LLM applications the observability that traditional software has long taken for granted. Traces, spans, generations, sessions, and scores record what happened, how long it took, what it cost, and how good the result was. Self-hosting with Docker Compose keeps that data inside your own infrastructure. The Python SDK instruments an application in a few lines, through a decorator and a drop-in OpenAI wrapper. Versioned prompts, datasets, experiments, and LLM-as-a-judge evaluation turn debugging into a repeatable loop, while dashboards, topics, alerts, and cost tracking keep production behaviour visible. The AI Gateway and the OpenTelemetry-based integrations connect the platform to the tools teams already use.

The honest conclusion is the same one this guide opened with: an LLM application that is not observed is an application you cannot improve with confidence. Langfuse, at v4.94.0 with the Python SDK at v5.3.0, is a mature, open-source way to change that, provided you are willing to operate it or pay for the hosted service, and provided your application has reached the scale where evidence beats intuition.

Sources

All sources were accessed on 6 December 2026.

Leave a Comment