Running Langfuse experiments from code and CI

Run your application over a Langfuse dataset from code, attach evaluator scores to each run, and block merges when quality drops, all inside infrastructure you control.

On this page

Running Langfuse experiments from code and CI in your own pipeline

SDK experiments run your application over a dataset and attach evaluator scores to the resulting traces and dataset runs, so a team changing prompts, models or application code can measure the effect of that change before it reaches users. The point is repeatable quality checks: the same dataset, the same evaluators and the same comparison every time a change is proposed. Teams usually need this once their release process covers more than a single prompt, for example when a change touches retrieval logic, tool wiring, a model router or several prompts that must be tested together, and when a reviewer should be able to rerun the check from a pull request rather than trust a manual spot check. The MIT-licensed open source core includes this capability, so an SDK-driven experiment workflow does not require an Enterprise license key.

The UI prompt experiments covered elsewhere in this group suit a single prompt or model comparison that a prompt owner runs by hand. Code-driven experiments suit changes that need the application's own code path exercised, because the runner calls your application function for each dataset item rather than only the prompt template. Before you commit to this approach, confirm with your engineers which SDK version and Langfuse server version your environment supports, since the SDKs and server releases are tied together, and check the current experiment interface in the Langfuse experiments via SDK documentation against the version you run. Decide early who owns the datasets and evaluator functions, because those become shared test assets that every later change depends on.

How an SDK experiment moves from dataset to CI decision

The flow starts in the CI job, which launches the experiment runner. The runner pulls a dataset from your self-hosted Langfuse, calls the application once per item, and sends the resulting traces back. Evaluator functions then attach scores to each run, and a gate step compares the new run with a baseline run to pass or fail the build. Check that the baseline is a run your team trusts, and that the gate reads the same score names the evaluators write.

Experiment flow from CI trigger to a pass or fail build decision.

How to set up SDK experiments in CI for self-hosted Langfuse

This sequence takes a self-hosted Langfuse project from an empty dataset to a CI job that runs your application against that dataset, scores each output, and shows the resulting traces and scores in the dataset run. Each step ends with a check you can run before moving on.

  1. Create the dataset in your Langfuse project

    A platform engineer or ML engineer creates a dataset in the self-hosted Langfuse project that will hold the test cases, either in the UI or through the SDK. Add items with inputs and, where you have them, expected outputs. Confirm the dataset name, since your CI job will reference it, and check that the items appear in the dataset view with the inputs you expect. Keep sensitive production data out of the items, as described in the dataset-building guidance for this group.

  2. Store the project keys and host URL as CI secrets

    The team that runs the CI system adds the project public key, project secret key and host URL as masked or protected secrets in the CI platform, never in the repository. The public and secret keys come from the project settings in your self-hosted Langfuse instance, and the host URL is the address your runners use to reach that instance, which may differ from the address users see. Confirm the job can read the variables by printing only their length in a test job, not their values.

  3. Install and configure the SDK in the pipeline

    The developer adds the Langfuse SDK for your language to the project's dependencies and sets the connection through environment variables that the pipeline injects from the secrets store. Check the SDK version against the Langfuse server version, since recent SDK majors require a minimum Langfuse release. Confirm the setup with a single test trace sent from the runner, then check that it appears in the Langfuse project.

  4. Write the task function around the application

    The developer writes a task function that takes a dataset item's input, calls the application code under test, and returns its output. Keep this function as close as possible to the production call path so the experiment measures what users get. Check it locally against two or three dataset items and confirm each returns the output shape your evaluators expect.

  5. Add evaluator functions for the scores

    The team writes evaluator functions that receive the output and the expected output and return named scores, such as a deterministic check or a call to a judge model. Start with checks that are cheap and deterministic so failures are easy to read. Confirm each evaluator returns a value of the type you plan to gate on, and run it once against a known good and known bad output.

  6. Run the baseline experiment on the main branch

    The CI job runs the experiment runner on the main branch to create a baseline dataset run, using a run name that identifies the commit. The baseline gives you the reference scores for every evaluator. Confirm the run appears under the dataset in Langfuse with a score for each item and each evaluator, and record the aggregate scores that the CI job will compare against.

  7. Run the candidate and compare against the baseline

    On a merge request or pull request, the same job runs the candidate code against the same dataset version and writes a second dataset run. The job compares the aggregate scores with the baseline and fails when a score drops below the threshold your team sets. Confirm the job fails on a deliberately broken change and passes on an unchanged one, and that both runs are visible side by side in the Langfuse UI.

  8. Verify traces and scores in the dataset run

    Open the candidate dataset run in Langfuse and check that each item links to a trace of the application call, that the evaluator scores are attached to the traces or run, and that the trace contains the steps you expect. This confirms the experiment is observable, so a failing gate can be investigated. The work is done when a reviewer can go from a failed CI check to the trace for the failing item without leaving Langfuse.

Which experiment configuration fits which team

Local runs are for iterating on a prompt, a model choice or an evaluator before a change is pushed. They point the SDK at a development Langfuse instance, usually a self-hosted deployment that the team does not treat as production, and they run over a small, curated dataset so feedback comes quickly. Nothing in this mode should decide whether code merges, so results are read by the developer rather than enforced.

  • Credentials: Keep project keys in a local environment file that is excluded from version control, or fetch them from your team's secrets tool. Use keys scoped to a development project, never production keys.
  • Baselines: Compare against the last run the developer marked as a reference in the dev project, not against a shared baseline that others may be changing.
  • Evaluator cost: Keep judge-model calls small for each iteration. Confirm with your provider and your own invoices what a single run costs before you raise dataset size.
  • Data: Use synthetic or de-identified items. Production traces copied into a development instance widen the audience for personal data.
  • Traces: Tag local runs with an environment or run name so they do not mix with CI output.

Check that your development instance uses separate projects and keys from production before anyone runs experiments against it.

Writing evaluator functions that gate a build reliably

An evaluator that gates a build is a policy decision as much as a code decision. The choices below determine whether a CI failure means the application regressed or the measurement drifted. Each one should be settled before the threshold is wired into a pipeline.

Deterministic checks or judge models

Use a deterministic evaluator wherever the property can be checked by code, such as JSON validity, required fields, or a tool call that must appear. Reserve a judge model for qualities like helpfulness or tone that code cannot measure. A judge adds model cost, latency and its own variance to every CI run, so it should only gate what code cannot. For judge rubric design and judge cost controls, see the sibling topic on LLM-as-a-judge evaluators. For code checks, see the sibling topic on code evaluators.

Numeric or boolean scores

Boolean scores fit pass or fail requirements, such as whether a response cites a source. Numeric scores fit graded qualities, but they need a threshold and a stable scale before a build can depend on them. A numeric score averaged over a dataset can hide a drop in one category, so decide whether the gate applies to the mean, to each item, or to a minimum pass rate. Name the score type in the evaluator so that the CI rule and the dashboard read the same value.

Thresholds per dataset slice

A single global threshold often fails to protect the cases that matter most. Split the dataset into slices such as languages, product areas, or high-risk request types, and set a threshold for each slice that the team can justify from past runs. Keep slices small enough to be meaningful but large enough that one item does not decide the result. Confirm with your team how a slice with too few items is handled, since a gate that passes on tiny samples gives false confidence.

Handling flaky judge output

A judge model can return malformed output, change its answer between identical runs, or fail under rate limits. Decide in advance whether a failed evaluation counts as a pass, a fail, or a retry, and make that rule explicit in the pipeline. Record parse failures as their own score or log entry so they are visible rather than silently dropped. Pin the judge model version and temperature where the provider allows it, and check repeat stability on a fixed set before trusting a gate.

Versioning evaluators with application code

An evaluator that changes without the application changing will move scores and can make a healthy build look like a regression. Keep evaluator code, rubric text and threshold files in the same repository and review path as the application, and tag them with the commit that set each baseline. When an evaluator changes, rerun the baseline so that the comparison is made on the same measurement. Document which evaluator version produced each stored score so that historical runs remain comparable.

Comparing runs and failing CI on score regressions

A CI gate for LLM changes should compare a candidate dataset run against a baseline run and fail the build only when a score drops past a threshold you set in advance. Start by deciding which run is the baseline: usually the run from the current production prompt or model configuration, pinned to the same dataset version as the candidate. Both runs must use the same dataset version, or the comparison measures dataset drift instead of your change. Record the dataset version, the run names and the evaluator names in the pipeline so every gate result can be traced back to its inputs.

A regression can mean two different things, and the gate should check both. An aggregate regression is a drop in the mean of an evaluator score across all items in the run, such as average faithfulness falling from one run to the next. A per-item regression is a single dataset item that scored well in the baseline and poorly in the candidate, which an average can hide when a few large drops are offset by small gains elsewhere. Per-item checks catch failures that matter to users, such as a previously correct answer to a refund question now failing a rule, while aggregate checks catch broad quality loss. Decide which items are critical enough to be hard failures before you write the gate.

In CI, a short script reads the scores for both runs through the Langfuse API, computes the comparison and exits with a non-zero code when a threshold is crossed, which stops the pipeline. Confirm the exact endpoints, filters and pagination behavior for your Langfuse version in the API reference before you write the script. Strict gates reduce the chance of shipping a regression but fire on noise, because LLM output and judge scores vary between runs even with identical code. Mitigate that with repeated runs, tolerance bands set from observed variance, and gates limited to a few stable evaluators. Review gate thresholds whenever you change judge models, evaluators or dataset versions, since each of those changes the baseline.

What gets traced in an experiment run and where to find it

This table lists each artifact an SDK experiment run produces, where it appears in Langfuse, who usually reads it and what to check when a run looks wrong. Read it as a triage guide: start with the dataset run to compare scores, then open traces to find the cause of a regression, and check CI logs when the failure happened before results reached Langfuse.

ArtifactWhere it appears in LangfuseWho uses itWhat to check when a run looks wrong
Application traces per dataset itemTracing view, linked from the dataset run for each dataset itemEngineers debugging a specific outputConfirm each item produced a trace, the input matches the dataset item and the application version or metadata tags identify the change under test
Evaluator scoresScores attached to each trace and summarized on the dataset runEngineers and quality leads comparing runsCheck that each score name is present on every item, that evaluators did not error silently and that scores are on the expected scale
Dataset run metadataDataset runs view, where runs are listed and compared side by sideProduct owners and reviewers approving a changeConfirm the run name, the dataset version used and the run metadata that identifies the commit or configuration under test
Run-level aggregate scoresDataset run summary for each evaluatorRelease reviewers and CI gate ownersCompare against the baseline run, not an older unrelated run, and confirm the comparison uses the same dataset and evaluator versions
Experiment item count and coverageDataset run item listCI owners and test maintainersCheck for missing items caused by timeouts, exceptions in the task function or a dataset that changed between runs
Judge model tracesTraces created by LLM-as-a-judge evaluators, if the evaluator call is tracedEngineers auditing judge cost and behaviorConfirm the judge model, prompt version and that judge failures are not being recorded as low scores
CI job logsYour CI system, not Langfuse, including the SDK output and exit statusPlatform and DevOps engineersCheck the exit code, the run identifier printed by the job and whether the failure came from the gate threshold or from a crash before results were sent

Securing API keys, test data and judge access in CI

Experiment runs in CI touch three sensitive things: Langfuse credentials, the data in your datasets and the judge models that score output. The cards below cover where each lives, who can change it and what to confirm before a pipeline goes live against your self-hosted host.

Store project keys in the CI secret store

The SDK reads the public and secret keys for a Langfuse project from environment variables, so they belong in the secret store of your CI system, masked in logs and scoped to the jobs that run experiments. Do not place them in repository files or pipeline definitions that pull requests can edit. Check whether forked pull requests can read secrets, because that setting is the most common way keys leak from CI.

Experiments via SDK docs

Use a project key per pipeline

Create a separate project key for each pipeline or environment, such as one for pull request checks and one for scheduled regression runs, so a leaked key can be revoked without breaking other jobs. Keep these keys in the project that holds the experiment datasets rather than a broader scope. Confirm with your Langfuse administrator how key rotation is done on your instance and who can perform it.

Keep sensitive production data out of datasets

Datasets used by CI are copied into the test run, appear in run history and can be read by anyone with project access. Remove personal data, customer identifiers, secrets and regulated records from inputs and expected outputs before adding traces as dataset items. Use synthetic or redacted examples where the behavior under test does not depend on the original values.

Confirm network reachability from runners

Hosted runners in the public cloud often cannot reach a self-hosted Langfuse behind a private network. Decide whether runners sit inside the same network, use a private runner or reach the host through an approved gateway, and confirm that the endpoint uses TLS with certificates your runners trust. Test the connection with a no-op experiment before relying on the pipeline for merge decisions.

Control who changes evaluators

An evaluator that is edited in a pull request can change the score that gates a merge, so treat evaluator code and judge prompts like production test code. Require review from the owners of quality gates, and restrict who can change the CI configuration that selects datasets and thresholds. Organization-level role controls such as project RBAC need a Self-Hosted Enterprise license key, so confirm with your vendor which roles your plan provides.

Langfuse license key docs

Scope judge model credentials

Experiment evaluators that call a judge model need their own model credentials, separate from the application keys under test. Give the CI job a key limited to the judge model and spending budget it needs, and log which judge model scored each run. Confirm where those credentials are stored on the Langfuse side and who in your organization can view them.

Questions teams ask before running Langfuse experiments in CI

How much effort does it take to set up experiments from code?

Setup has three parts: a running self-hosted Langfuse instance, a dataset with expected outputs, and an experiment script that runs your application over that dataset and attaches evaluator scores to the traces and dataset runs. Experiments via the SDK run your application over a dataset and attach evaluator scores to the resulting traces and dataset runs, so the script itself is usually the smaller piece. The larger effort is usually the instance and the dataset. Confirm the exact SDK version and setup steps against the current SDK documentation before you plan the work.

What drives the cost of running experiments in CI?

Most of the recurring cost comes from three sources: calls to judge models made by LLM-as-a-judge evaluators, the number of dataset items each run processes, and how often the pipeline runs. Each item typically triggers a call to your application model plus one call per model-based evaluator, so cost grows with the product of those three factors. Deterministic code evaluators avoid judge calls entirely. Ask for a quote that states which evaluators call a model, the dataset size you expect, and the run frequency, and confirm your model provider's pricing for each.

Can an internal team set this up without outside help?

Yes, if the team has someone who operates Kubernetes or Docker, can run PostgreSQL and ClickHouse, and writes Python or TypeScript for the application under test. Langfuse documents Docker Compose on a single VM for testing and Kubernetes with Helm or Terraform for production, and the self-hosted version contains the same core features as Langfuse Cloud. The harder parts for most teams are writing evaluators that reflect real quality criteria and keeping the dataset representative. Decide early who owns each of these.

How long until the first gated CI run?

The timeline depends on whether a self-hosted instance already exists, how many evaluators you need, and how quickly the team agrees on pass and fail thresholds. A team with a running instance can often wire up one dataset and one evaluator in a short sprint, while a new production-grade deployment takes longer. No duration figure is supplied for this work, so ask your partner or internal lead for a timeline based on your written scope and confirm it against your own environment.

What does the work need from our team?

You need four things: a dataset of representative inputs with expected outputs, evaluator logic that defines acceptable quality, CI runner access with the credentials to call your application and the Langfuse API, and a self-hosted Langfuse instance that your pipeline can reach. Add a named owner who can approve threshold changes, since a gate that nobody maintains will either block releases for the wrong reasons or be disabled. Check that dataset content meets your data handling rules before it reaches a shared runner.

Should test data and CI secrets be handled differently?

Yes. Datasets built from production traces can contain personal data or secrets, so filter them before they become test items, and store Langfuse keys and model provider keys in your CI secret store rather than in repository files. Limit which runners and branches can reach the self-hosted instance. Confirm with your security team how your CI platform protects secrets and which runners execute pull request code.

When does a partner help with experiments in CI?

A partner is most useful when the team needs evaluators calibrated against expert judgment, a dataset built from production traces under data rules, or a gate that must be defended in an audit or a customer security review. DeployOpen implements, customizes, integrates and supports self-hosted Langfuse in your infrastructure and works to a written, fixed scope. Ask for a quote that lists the deliverables, the evaluators covered and the retest or support terms before work begins.

Official Langfuse documentation for SDK experiments

The next read for this topic is the Langfuse documentation on experiments via SDK, which explains how an experiment runs your application over a dataset and attaches evaluator scores to the resulting traces and dataset runs. Read it before you write the CI job, because the runner's behavior determines what your pipeline can compare. Pay particular attention to how dataset items are matched to your task function, how evaluator functions receive inputs and outputs, and how a run is named and grouped so that two runs can be compared later. Your team should confirm these details against the SDK version it pins, since the SDK and the server it talks to must be compatible. Note that the Python SDK v5 and JS/TS SDK v6 need Langfuse v4.59.0 or later, so check your self-hosted server version before you copy any example code.

Because your instance is self-hosted, also read the Langfuse self-hosting documentation for the version you run. Its guidance on the web and worker containers, PostgreSQL, ClickHouse and blob storage determines whether your CI runners can reach the public API endpoint, how keys are issued for a project, and what happens to experiment data during an upgrade. Ask your platform team which base URL and network path the CI environment will use, and whether the runner needs egress rules, a proxy or a private DNS entry to reach the instance. Also confirm which environment variables, such as the host and key pair, will be stored in your CI secrets store and who can rotate them. Treat these documents as the reference for your own deployment, and record the version you tested against so later upgrades can be checked against the same behavior.

How DeployOpen works on this

DeployOpen plans, builds and hands over experiment pipelines that run Langfuse SDK experiments from your code and CI, inside infrastructure you control. Each engagement starts from a written scope that names the datasets, evaluators, thresholds and runners involved.

How we scope

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • We inventory the applications, datasets, evaluator functions and CI runners that the experiment pipeline must cover.
  • We agree which score regressions block a merge and which only report, so thresholds are decided before the build.

How we build

  • We wire the SDK experiment runner to your self-hosted Langfuse instance using keys and endpoints stored in your CI secrets store.
  • We write evaluator functions and test them against known good and known bad outputs before they gate any pipeline.
  • We configure CI jobs to fail on agreed score regressions and tag experiment runs so traces can be traced back to commits.

How we hand over

  • You receive pipeline code, evaluator source, runner configuration and a short document describing how to add datasets and evaluators.
  • We run a walkthrough with the engineers who own the application so the failure and override steps are understood by your team.
  • Handover includes a checklist for rotating SDK keys and for reviewing evaluator changes in pull requests.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after handover.
  • Retainers can cover SDK version updates, such as moving to a newer Python or JS/TS SDK, and the matching Langfuse server version.
  • We can retest the pipeline after changes to datasets, models or evaluators so regression thresholds stay meaningful.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.