---
title: Environments
description: Configure environments to organize your traces, observations, and scores.
sidebarTitle: Environments
---

# Environments

Environments allow you to organize your traces, observations, and scores from different contexts such as production, staging, or development. This helps you:

- Keep your development and production data separate while using the same project
- Filter and analyze data by environment
- Reuse datasets and prompts across environments

## Filtering

In the Langfuse UI, you can filter events by environment using the environment filter in the navigation bar. This filter applies across all views in Langfuse.

See our [API Reference](/docs/api) for details on how to filter by environment on our API.

## Managing Environments

Environments are created the first time data is ingested with a given `environment` value and are persistent. They cannot currently be deleted or renamed via the UI.

For guidance on how to structure, separate, and work with multiple environments across projects and stages, see the FAQ: [Managing different environments](/faq/all/managing-different-environments).

## Configure environments [#configure-environments]

You can configure the environment by setting the `LANGFUSE_TRACING_ENVIRONMENT` environment variable (recommended) or by using the `environment` parameter in the client initialization.
If both are specified, the initialization parameter takes precedence.
If nothing is specified, the default environment is `default`.

In the Python SDK, you can also set the environment for a specific trace scope with `propagate_attributes(environment="...")`. This is useful when the environment belongs to the incoming request rather than to the service process itself, for example when one shared LLM proxy handles requests from development, staging, QA, and production. Use `as_baggage=True` to propagate that environment across service boundaries.

### Naming constraints

The environment must be a string that follows this regex pattern: `^(?!langfuse)[a-z0-9-_]+$` with at most 40 characters.

This means:

- Cannot start with "langfuse"
- Can only contain lowercase letters, numbers, hyphens, and underscores

### Data Model

The `environment` attribute is available on all events in Langfuse:

- Traces
- Observations (spans, events, generations)
- Scores
- Sessions

See [Data Model](/docs/observability/data-model) for more details.

<LangTabs items={["Python SDK", "JS/TS SDK", "OpenTelemetry", "OpenAI (Python)", "OpenAI (JS/TS)", "Langchain (Python)", "Langchain (JS/TS)", "Vercel AI SDK (JS/TS)"]}>
<Tab title="Python SDK">

```python
from langfuse import get_client, observe, propagate_attributes
import os

# Set the environment variable
# Alternatively, set via .env file and load via dotenv
os.environ["LANGFUSE_TRACING_ENVIRONMENT"] = "production"

# Get the client (will use environment variable)
langfuse = get_client()

# All operations will now be associated with the "production" environment
with langfuse.start_as_current_observation(as_type="span", name="my-operation") as span:
    # Your code here
    pass

@observe
def main():
    return "Hello"

main()

# For request-scoped environments, propagate the environment explicitly.
# This maps to the first-class langfuse.environment field.
with langfuse.start_as_current_observation(as_type="span", name="proxy-request"):
    with propagate_attributes(environment="staging"):
        # All child observations created here are associated with staging.
        pass
```

</Tab>
<Tab>

Set the Langfuse Environment via environment variable:

```bash
export LANGFUSE_TRACING_ENVIRONMENT=production
```

</Tab>
<Tab>

When using [OpenTelemetry](/docs/opentelemetry/get-started), you can set the environment using any of these attributes:

- `langfuse.environment`
- `deployment.environment.name`
- `deployment.environment`

To set an environment property globally, you can use resource attributes: `os.environ["OTEL_RESOURCE_ATTRIBUTES"] = "langfuse.environment=staging"`.

Alternatively, you can set the environment on a per-span basis:

```python
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_observation("my-operation") as span:
    # Set environment using Langfuse-specific attribute
    span.set_attribute("langfuse.environment", "staging")

    # Or using OpenTelemetry convention
    span.set_attribute("deployment.environment.name", "staging")
```

</Tab>
<Tab>

When using the **Python SDK**, the environment provided on client initialization will apply to all event inputs and outputs regardless of the Langfuse-maintained integration you are using.

See the Python SDK tab for more details.

When using the [OpenAI SDK Integration](/integrations/model-providers/openai-py)

```python
from langfuse import Langfuse
from langfuse.openai import openai

# Either set the environment variable or configure the Langfuse client
os.environ["LANGFUSE_TRACING_ENVIRONMENT"] = "production"

langfuse = Langfuse(environment="production")

# the integration will use the instantiated client under the hood
completion = openai.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a calculator."},
    {"role": "user", "content": "1 + 1 = "}],
)
```

</Tab>
<Tab>

```bash filename=".env"
LANGFUSE_TRACING_ENVIRONMENT=production
```

```ts
import OpenAI from "openai";
import { observeOpenAI } from "@langfuse/openai";

const openai = observeOpenAI(new OpenAI());
```

See [OpenAI Integration (JS/TS)](/integrations/model-providers/openai-js) for more details.

</Tab>

<Tab>

When using the **Python SDK**, the environment provided on client initialization will apply to all event inputs and outputs regardless of the Langfuse-maintained integration you are using.

See the Python SDK tab for more details.

```python
from langfuse.langchain import CallbackHandler

# Set the environment via environment variable before initializing the client
os.environ["LANGFUSE_TRACING_ENVIRONMENT"] = "production"
handler = CallbackHandler()
```

</Tab>

<Tab>

The environment is configured on the `LangfuseSpanProcessor` (or via the `LANGFUSE_TRACING_ENVIRONMENT` environment variable) — LangChain spans created by the `CallbackHandler` flow through it automatically:

```ts
import { NodeSDK } from "@opentelemetry/sdk-node";
import { LangfuseSpanProcessor } from "@langfuse/otel";
import { CallbackHandler } from "@langfuse/langchain";

const sdk = new NodeSDK({
  spanProcessors: [
    new LangfuseSpanProcessor({
      environment: "production",
    }),
  ],
});
sdk.start();

const handler = new CallbackHandler();
```

See [Langchain Integration (JS/TS)](/integrations/frameworks/langchain) for more details.

</Tab>

<Tab>

When using the [Vercel AI SDK Integration](/integrations/frameworks/vercel-ai-sdk)

```ts filename="instrumentation.ts" {/environment: "production"/}
import { registerOTel } from "@vercel/otel";
import { LangfuseSpanProcessor } from "@langfuse/otel";

export function register() {
  registerOTel({
    serviceName: "langfuse-vercel-ai-nextjs-example",
    spanProcessors: [new LangfuseSpanProcessor({ environment: "production" })],
  });
}
```

</Tab>

</LangTabs>

## Best Practices

1. **Consistent Environment Names**: Use consistent environment names across your application to make filtering and analysis easier.
2. **Environment-Specific Analysis**: Use environments to analyze and compare metrics across different deployment stages.
3. **Testing**: Use separate environments for testing to avoid polluting production data.

## GitHub Discussions

<!-- agent-instructions -->

---

## Agent Instructions

This page is part of the [Langfuse](https://langfuse.com) documentation, published as plain Markdown for AI agents. Every page is available as Markdown by appending `.md` to its URL, or by sending an `Accept: text/markdown` header. This page: `https://langfuse.com/docs/observability/features/environments.md`.

### Querying these docs

If the answer is not on this page, query the documentation instead of guessing:

- **Semantic search** across all Langfuse docs, returning an answer with the relevant pages and excerpts. Ask a specific, self-contained question:

  ```bash
  curl -sG "https://langfuse.com/api/search-docs" --data-urlencode "query=How do I trace a LangGraph agent?"
  ```

- **Index of every page**: <https://langfuse.com/llms.txt>, with per-section indexes [llms-docs.txt](https://langfuse.com/llms-docs.txt), [llms-integrations.txt](https://langfuse.com/llms-integrations.txt), and [llms-self-hosting.txt](https://langfuse.com/llms-self-hosting.txt).

### Before writing Langfuse code

- **Install the [Langfuse Agent Skill](https://langfuse.com/docs/api-and-data-platform/features/agent-skill).** It encodes Langfuse's own best practices for instrumentation, prompt management, and evaluation, and materially improves results.
- **Read [What does a good trace look like?](https://langfuse.com/docs/observability/best-practices.md)** before instrumenting an application.
- **Verify endpoints, parameters, and response fields** against the [API reference](https://api.reference.langfuse.com) instead of inferring them from code examples.
- **Use the [Langfuse CLI](https://langfuse.com/docs/api-and-data-platform/features/cli)** (`npx langfuse-cli api <resource> <action>`) to read or write traces, prompts, datasets, and scores from the terminal.

Found an error in these docs? Please open an issue at <https://github.com/langfuse/langfuse-docs/issues>.
