Skip to content
Draft
3 changes: 3 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
LANGFUSE_BASE_URL=http://localhost:3000
LANGFUSE_PUBLIC_KEY=pk-lf-1234567890
LANGFUSE_SECRET_KEY=sk-lf-1234567890
# Alternatively, an API key and the project to write to
# LANGFUSE_API_KEY=
# LANGFUSE_PROJECT_ID=

# Optionally for E2E tests
OPENAI_API_KEY=
Expand Down
5 changes: 3 additions & 2 deletions langfuse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@
```

Configuration is via constructor args or environment variables: `LANGFUSE_PUBLIC_KEY`,
`LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL` (defaults to https://cloud.langfuse.com). See `langfuse._client.environment_variables`
for the full list.
`LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL` (defaults to https://cloud.langfuse.com). Alternatively,
`LANGFUSE_API_KEY` with `LANGFUSE_PROJECT_ID`. See `langfuse._client.environment_variables` for the
full list.

Docs: https://langfuse.com/docs — machine-readable index: https://langfuse.com/llms.txt

Expand Down
103 changes: 96 additions & 7 deletions langfuse/_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
Iterator,
List,
Literal,
Mapping,
Optional,
Sequence,
Tuple,
Expand Down Expand Up @@ -49,16 +50,19 @@
)
from langfuse._client.constants import (
LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT,
PROJECT_ID_HEADER_NAMES,
ObservationTypeGenerationLike,
ObservationTypeLiteralNoEvent,
ObservationTypeSpanLike,
get_observation_types_list,
)
from langfuse._client.datasets import DatasetClient
from langfuse._client.environment_variables import (
LANGFUSE_API_KEY,
LANGFUSE_BASE_URL,
LANGFUSE_DEBUG,
LANGFUSE_HOST,
LANGFUSE_PROJECT_ID,
LANGFUSE_PUBLIC_KEY,
LANGFUSE_RELEASE,
LANGFUSE_SAMPLE_RATE,
Expand Down Expand Up @@ -179,6 +183,77 @@ def _serialize_evaluations(evaluations: List[Evaluation]) -> List[Dict[str, Any]
]


class _CredentialsError(ValueError):
"""Misconfigured API key, key pair or project ID."""


def _validate_project_id_headers(
project_id: Optional[str],
additional_headers: Optional[Dict[str, str]],
httpx_client: Optional[httpx.Client],
) -> None:
"""Raise if a user-supplied project header names a different project."""
if project_id is None:
return

sources: List[Tuple[str, Mapping[str, str]]] = []
if additional_headers:
sources.append(("additional_headers", additional_headers))

client_headers = getattr(httpx_client, "headers", None)
if isinstance(client_headers, Mapping):
sources.append(("httpx_client.headers", client_headers))

for source, headers in sources:
for name, value in headers.items():
if name.lower() in PROJECT_ID_HEADER_NAMES and value != project_id:
message = (
f"Conflicting project IDs: project_id is '{project_id}' but "
f"{source} sets '{name}: {value}'. Remove the header or make "
"the values match."
)
raise _CredentialsError(message)


def _get_credentials(
*,
api_key: Optional[str],
public_key: Optional[str],
secret_key: Optional[str],
project_id: Optional[str],
additional_headers: Optional[Dict[str, str]],
httpx_client: Optional[httpx.Client],
) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[str]]:
"""Return ``(api_key, public_key, secret_key, project_id)``; raise on misconfiguration."""
if not (api_key or public_key or secret_key):
api_key = os.environ.get(LANGFUSE_API_KEY) or None

if not api_key:
public_key = public_key or os.environ.get(LANGFUSE_PUBLIC_KEY)
secret_key = secret_key or os.environ.get(LANGFUSE_SECRET_KEY)
if project_id:
message = "project_id requires api_key. Remove project_id or pass api_key."
raise _CredentialsError(message)

# LANGFUSE_PROJECT_ID is ignored: it configures API key clients only
return None, public_key, secret_key, None

if public_key or secret_key:
message = "Pass either api_key or public_key and secret_key, not both."
raise _CredentialsError(message)

project_id = project_id or os.environ.get(LANGFUSE_PROJECT_ID) or None
if not project_id:
message = (
"api_key requires project_id. Pass project_id or set LANGFUSE_PROJECT_ID."
)
raise _CredentialsError(message)

_validate_project_id_headers(project_id, additional_headers, httpx_client)

return api_key, None, None, project_id


class Langfuse:
"""Main client for Langfuse tracing and platform features.

Expand All @@ -201,6 +276,8 @@ class Langfuse:
Parameters:
public_key (Optional[str]): Your Langfuse public API key. Can also be set via LANGFUSE_PUBLIC_KEY environment variable.
secret_key (Optional[str]): Your Langfuse secret API key. Can also be set via LANGFUSE_SECRET_KEY environment variable.
api_key (Optional[str]): Your Langfuse secret API key, sent as a bearer token. Requires `project_id`. Can also be set via LANGFUSE_API_KEY environment variable.
project_id (Optional[str]): The Langfuse project to send data to. Required with `api_key`. Can also be set via LANGFUSE_PROJECT_ID environment variable.
base_url (Optional[str]): The Langfuse API base URL. Defaults to "https://cloud.langfuse.com". Can also be set via LANGFUSE_BASE_URL environment variable.
host (Optional[str]): Deprecated. Use base_url instead. The Langfuse API host URL. Defaults to "https://cloud.langfuse.com".
timeout (Optional[int]): Timeout in seconds for API requests. Defaults to 5 seconds.
Expand Down Expand Up @@ -311,6 +388,8 @@ def __init__(
secret_key: Optional[str] = None,
base_url: Optional[str] = None,
host: Optional[str] = None,
api_key: Optional[str] = None,
project_id: Optional[str] = None,
timeout: Optional[int] = None,
httpx_client: Optional[httpx.Client] = None,
debug: bool = False,
Expand Down Expand Up @@ -345,7 +424,16 @@ def __init__(
or os.environ.get(LANGFUSE_RELEASE, None)
or get_common_release_envs()
)
self._project_id: Optional[str] = None
api_key, public_key, secret_key, project_id = _get_credentials(
api_key=api_key,
public_key=public_key,
secret_key=secret_key,
project_id=project_id,
additional_headers=additional_headers,
httpx_client=httpx_client,
)
# Cache read by _get_project_id(); a configured project needs no lookup
self._project_id: Optional[str] = project_id
if sample_rate is None:
sample_rate = float(os.environ.get(LANGFUSE_SAMPLE_RATE, 1.0))
if not 0.0 <= sample_rate <= 1.0:
Expand Down Expand Up @@ -373,17 +461,16 @@ def __init__(
)
langfuse_logger.setLevel(logging.DEBUG)

public_key = public_key or os.environ.get(LANGFUSE_PUBLIC_KEY)
if public_key is None:
if api_key is None and public_key is None:
langfuse_logger.warning(
"Authentication error: Langfuse client initialized without public_key. Client will be disabled. "
"Provide a public_key parameter or set LANGFUSE_PUBLIC_KEY environment variable. "
"Provide a public_key parameter or set LANGFUSE_PUBLIC_KEY environment variable, "
"or use api_key with project_id. "
)
self._otel_tracer = otel_trace_api.NoOpTracer()
return

secret_key = secret_key or os.environ.get(LANGFUSE_SECRET_KEY)
if secret_key is None:
if api_key is None and secret_key is None:
langfuse_logger.warning(
"Authentication error: Langfuse client initialized without secret_key. Client will be disabled. "
"Provide a secret_key parameter or set LANGFUSE_SECRET_KEY environment variable. "
Expand All @@ -400,7 +487,9 @@ def __init__(
self._resources = LangfuseResourceManager(
public_key=public_key,
secret_key=secret_key,
api_key=api_key,
base_url=self._base_url,
project_id=project_id,
timeout=timeout,
environment=self._environment,
release=release,
Expand Down Expand Up @@ -2495,7 +2584,7 @@ def get_current_observation_id(self) -> Optional[str]:
return self._get_otel_span_id(current_otel_span) if current_otel_span else None

def _get_project_id(self) -> Optional[str]:
"""Fetch and return the current project id. Persisted across requests. Returns None if no project id is found for api keys."""
"""Return the configured project id, or fetch and cache it for project-bound api keys. Returns None if no project id is found."""
if not self._project_id:
proj = self.api.projects.get()
if not proj.data or not proj.data[0].id:
Expand Down
6 changes: 6 additions & 0 deletions langfuse/_client/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@

LANGFUSE_TRACER_NAME = "langfuse-sdk"

PROJECT_ID_HEADER = "langfuse-project-id"
"""Header naming the target project. Required with organization and user API keys."""

# Lowercase header names the server reads as the target project
PROJECT_ID_HEADER_NAMES = (PROJECT_ID_HEADER, "x-langfuse-project-id")

LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT = "sdk-experiment"

MASK_FALLBACK_VALUE = "<fully masked due to failed mask function>"
Expand Down
14 changes: 14 additions & 0 deletions langfuse/_client/environment_variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@
Secret API key of Langfuse project
"""

LANGFUSE_API_KEY = "LANGFUSE_API_KEY"
"""
.. envvar:: LANGFUSE_API_KEY

Langfuse secret API key, sent as a bearer token. Requires :envvar:`LANGFUSE_PROJECT_ID`.
"""

LANGFUSE_PROJECT_ID = "LANGFUSE_PROJECT_ID"
"""
.. envvar:: LANGFUSE_PROJECT_ID

The Langfuse project to send data to. Required with :envvar:`LANGFUSE_API_KEY`.
"""

LANGFUSE_BASE_URL = "LANGFUSE_BASE_URL"
"""
.. envvar:: LANGFUSE_BASE_URL
Expand Down
Loading