Skip to content

Commit 88a06d2

Browse files
committed
update docstrings
1 parent 6b54d1e commit 88a06d2

5 files changed

Lines changed: 62 additions & 45 deletions

File tree

langfuse/_client/client.py

Lines changed: 47 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,6 @@
11
"""Langfuse OpenTelemetry integration module.
22
3-
This module implements Langfuse's core observability functionality using the OpenTelemetry (OTel) standard.
4-
It provides structured tracing of AI/LLM application events, including spans, generations, and scoring,
5-
with built-in support for batching, sampling, and distributed tracing.
6-
7-
The main class, Langfuse, provides a high-level interface for:
8-
- Creating and managing distributed trace contexts
9-
- Tracking AI model interactions with specialized span types (spans, generations)
10-
- Scoring and evaluating model outputs with different metrics types
11-
- Capturing detailed metadata, usage statistics, and cost information
12-
- Processing and uploading media content in observations
13-
14-
This implementation uses OpenTelemetry's distributed tracing framework to ensure
15-
consistency, interoperability, and compliance with observability standards.
16-
All span and trace IDs follow the W3C Trace Context specification.
3+
This module implements Langfuse's core observability functionality on top of the OpenTelemetry (OTel) standard.
174
"""
185

196
import logging
@@ -44,6 +31,7 @@
4431
LANGFUSE_DEBUG,
4532
LANGFUSE_HOST,
4633
LANGFUSE_PUBLIC_KEY,
34+
LANGFUSE_SAMPLE_RATE,
4735
LANGFUSE_SECRET_KEY,
4836
LANGFUSE_TRACING_ENABLED,
4937
LANGFUSE_TRACING_ENVIRONMENT,
@@ -79,7 +67,7 @@
7967

8068

8169
class Langfuse:
82-
"""Main client for Langfuse observability using OpenTelemetry.
70+
"""Main client for Langfuse tracing and platform features.
8371
8472
This class provides an interface for creating and managing traces, spans,
8573
and generations in Langfuse as well as interacting with the Langfuse API.
@@ -97,10 +85,21 @@ class Langfuse:
9785
async_api: Asynchronous API client for Langfuse backend communication
9886
langfuse_tracer: Internal LangfuseTracer instance managing OpenTelemetry components
9987
100-
Thread Safety:
101-
All methods are thread-safe. The client maintains context propagation using
102-
OpenTelemetry's context management, allowing concurrent operations across
103-
different threads while maintaining correct trace relationships.
88+
Parameters:
89+
public_key (Optional[str]): Your Langfuse public API key. Can also be set via LANGFUSE_PUBLIC_KEY environment variable.
90+
secret_key (Optional[str]): Your Langfuse secret API key. Can also be set via LANGFUSE_SECRET_KEY environment variable.
91+
host (Optional[str]): The Langfuse API host URL. Defaults to "https://cloud.langfuse.com". Can also be set via LANGFUSE_HOST environment variable.
92+
timeout (Optional[int]): Timeout in seconds for API requests. Defaults to 30 seconds.
93+
httpx_client (Optional[httpx.Client]): Custom httpx client for making non-tracing HTTP requests. If not provided, a default client will be created.
94+
debug (bool): Enable debug logging. Defaults to False. Can also be set via LANGFUSE_DEBUG environment variable.
95+
tracing_enabled (Optional[bool]): Enable or disable tracing. Defaults to True. Can also be set via LANGFUSE_TRACING_ENABLED environment variable.
96+
flush_at (Optional[int]): Number of spans to batch before sending to the API. Defaults to 512. Can also be set via LANGFUSE_FLUSH_AT environment variable.
97+
flush_interval (Optional[float]): Time in seconds between batch flushes. Defaults to 5 seconds. Can also be set via LANGFUSE_FLUSH_INTERVAL environment variable.
98+
environment (Optional[str]): Environment name for tracing. Default is 'default'. Can also be set via LANGFUSE_TRACING_ENVIRONMENT environment variable. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.
99+
release (Optional[str]): Release version/hash of your application. Used for grouping analytics by release.
100+
media_upload_thread_count (Optional[int]): Number of background threads for handling media uploads. Defaults to 1. Can also be set via LANGFUSE_MEDIA_UPLOAD_THREAD_COUNT environment variable.
101+
sample_rate (Optional[float]): Sampling rate for traces (0.0 to 1.0). Defaults to 1.0 (100% of traces are sampled). Can also be set via LANGFUSE_SAMPLE_RATE environment variable.
102+
mask (Optional[MaskFunction]): Function to mask sensitive data in traces before sending to the API.
104103
105104
Example:
106105
```python
@@ -111,8 +110,6 @@ class Langfuse:
111110
public_key="your-public-key",
112111
secret_key="your-secret-key",
113112
host="https://cloud.langfuse.com", # Optional, default shown
114-
debug=False, # Optional, enables detailed logging
115-
sample_rate=1.0 # Optional, control trace sampling
116113
)
117114
118115
# Create a trace span
@@ -188,6 +185,7 @@ def __init__(
188185

189186
self._host = host or os.environ.get(LANGFUSE_HOST, "https://cloud.langfuse.com")
190187
self._environment = environment or os.environ.get(LANGFUSE_TRACING_ENVIRONMENT)
188+
sample_rate = sample_rate or float(os.environ.get(LANGFUSE_SAMPLE_RATE, 1.0))
191189

192190
self._tracing_enabled = (
193191
tracing_enabled
@@ -242,6 +240,8 @@ def start_span(
242240
This method creates a new span but does not set it as the current span in the
243241
context. To create and use a span within a context, use start_as_current_span().
244242
243+
The created span will be the child of the current span in the context.
244+
245245
Args:
246246
trace_context: Optional context for connecting to an existing trace
247247
name: Name of the span (e.g., function or operation name)
@@ -328,6 +328,8 @@ def start_as_current_span(
328328
manager. Use this method with a 'with' statement to automatically handle span
329329
lifecycle within a code block.
330330
331+
The created span will be the child of the current span in the context.
332+
331333
Args:
332334
trace_context: Optional context for connecting to an existing trace
333335
name: Name of the span (e.g., function or operation name)
@@ -419,12 +421,14 @@ def start_generation(
419421
cost_details: Optional[Dict[str, float]] = None,
420422
prompt: Optional[PromptClient] = None,
421423
) -> LangfuseGeneration:
422-
"""Create a new generation span for AI model interactions.
424+
"""Create a new generation span for model generations.
423425
424-
This method creates a specialized span for tracking AI model generations/completions.
425-
It includes additional fields specific to LLM operations such as model name,
426+
This method creates a specialized span for tracking model generations.
427+
It includes additional fields specific to model generations such as model name,
426428
token usage, and cost details.
427429
430+
The created generation span will be the child of the current span in the context.
431+
428432
Args:
429433
trace_context: Optional context for connecting to an existing trace
430434
name: Name of the generation operation
@@ -538,10 +542,12 @@ def start_as_current_generation(
538542
) -> _AgnosticContextManager[LangfuseGeneration]:
539543
"""Create a new generation span and set it as the current span in a context manager.
540544
541-
This method creates a specialized span for AI model generations and sets it as the
545+
This method creates a specialized span for model generations and sets it as the
542546
current span within a context manager. Use this method with a 'with' statement to
543547
automatically handle the generation span lifecycle within a code block.
544548
549+
The created generation span will be the child of the current span in the context.
550+
545551
Args:
546552
trace_context: Optional context for connecting to an existing trace
547553
name: Name of the generation operation
@@ -869,20 +875,20 @@ def update_current_trace(
869875
):
870876
"""Update the current trace with additional information.
871877
872-
This method updates the trace that the current span belongs to. It's useful for
878+
This method updates the Langfuse trace that the current span belongs to. It's useful for
873879
adding trace-level metadata like user ID, session ID, or tags that apply to
874-
the entire trace rather than just a single span.
880+
the entire Langfuse trace rather than just a single observation.
875881
876882
Args:
877-
name: Updated name for the trace
878-
user_id: ID of the user who initiated the trace
879-
session_id: Session identifier for grouping related traces
883+
name: Updated name for the Langfuse trace
884+
user_id: ID of the user who initiated the Langfuse trace
885+
session_id: Session identifier for grouping related Langfuse traces
880886
version: Version identifier for the application or service
881-
input: Input data for the overall trace
882-
output: Output data from the overall trace
883-
metadata: Additional metadata to associate with the trace
884-
tags: List of tags to categorize the trace
885-
public: Whether the trace should be publicly accessible
887+
input: Input data for the overall Langfuse trace
888+
output: Output data from the overall Langfuse trace
889+
metadata: Additional metadata to associate with the Langfuse trace
890+
tags: List of tags to categorize the Langfuse trace
891+
public: Whether the Langfuse trace should be publicly accessible
886892
887893
Example:
888894
```python
@@ -1032,7 +1038,7 @@ def create_trace_id(self, *, seed: Optional[str] = None) -> str:
10321038
If not provided, a random ID will be generated.
10331039
10341040
Returns:
1035-
A 32-character lowercase hexadecimal string representing the trace ID.
1041+
A 32-character lowercase hexadecimal string representing the Langfuse trace ID.
10361042
10371043
Example:
10381044
```python
@@ -1142,13 +1148,13 @@ def create_score(
11421148
) -> None:
11431149
"""Create a score for a specific trace or observation.
11441150
1145-
This method creates a score for evaluating a trace or observation. Scores can be
1151+
This method creates a score for evaluating a Langfuse trace or observation. Scores can be
11461152
used to track quality metrics, user feedback, or automated evaluations.
11471153
11481154
Args:
11491155
name: Name of the score (e.g., "relevance", "accuracy")
11501156
value: Score value (can be numeric for NUMERIC/BOOLEAN types or string for CATEGORICAL)
1151-
trace_id: ID of the trace to associate the score with
1157+
trace_id: ID of the Langfuse trace to associate the score with
11521158
observation_id: Optional ID of the specific observation to score
11531159
score_id: Optional custom ID for the score (auto-generated if not provided)
11541160
data_type: Type of score (NUMERIC, BOOLEAN, or CATEGORICAL)
@@ -1161,7 +1167,7 @@ def create_score(
11611167
langfuse.create_score(
11621168
name="accuracy",
11631169
value=0.92,
1164-
trace_id="abcdef123456",
1170+
trace_id="abcdef1234567890abcdef1234567890",
11651171
data_type="NUMERIC",
11661172
comment="High accuracy with minor irrelevant details"
11671173
)
@@ -1170,8 +1176,8 @@ def create_score(
11701176
langfuse.create_score(
11711177
name="sentiment",
11721178
value="positive",
1173-
trace_id="abcdef123456",
1174-
observation_id="789012",
1179+
trace_id="abcdef1234567890abcdef1234567890",
1180+
observation_id="abcdef1234567890",
11751181
data_type="CATEGORICAL"
11761182
)
11771183
```

langfuse/_client/environment_variables.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
LANGFUSE_RELEASE = "LANGFUSE_RELEASE"
1717
"""
18-
.. envvar:: LANGFUSE_TRACING_ENVIRONMENT
18+
.. envvar:: LANGFUSE_RELEASE
1919
2020
Release number/hash of the application to provide analytics grouped by release.
2121
"""
@@ -86,3 +86,12 @@
8686
Max delay until a new ingestion batch is sent to the API.
8787
**Default value:** ``1``
8888
"""
89+
90+
LANGFUSE_SAMPLE_RATE = "LANGFUSE_SAMPLE_RATE"
91+
"""
92+
.. envvar: LANGFUSE_SAMPLE_RATE
93+
94+
Float between 0 and 1 indicating the sample rate of traces to bet sent to Langfuse servers.
95+
96+
**Default value**: ``1.0``
97+
"""

langfuse/_client/resource_manager.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,9 @@ def _init_tracer_provider(
377377
if isinstance(default_provider, otel_trace_api.ProxyTracerProvider):
378378
provider = TracerProvider(
379379
resource=resource,
380-
sampler=TraceIdRatioBased(sample_rate) if sample_rate is not None else None,
380+
sampler=TraceIdRatioBased(sample_rate)
381+
if sample_rate is not None and sample_rate < 1
382+
else None,
381383
)
382384
otel_trace_api.set_tracer_provider(provider)
383385

langfuse/_client/span.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Span implementations for Langfuse OpenTelemetry integration.
1+
"""OTEL span wrapper for Langfuse.
22
33
This module defines custom span classes that extend OpenTelemetry spans with
44
Langfuse-specific functionality. These wrapper classes provide methods for

langfuse/_client/span_processor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def on_end(self, span: ReadableSpan) -> None:
8888
# This is important to not send spans to wrong project in multi-project setups
8989
if self._is_langfuse_span(span) and not self._is_langfuse_project_span(span):
9090
langfuse_logger.debug(
91-
f"Security: Span rejected - belongs to project '{span.instrumentation_scope.attributes.get('public_key')}' but processor is for '{self.public_key}'. "
91+
f"Security: Span rejected - belongs to project '{span.instrumentation_scope.attributes.get('public_key') if span.instrumentation_scope and span.instrumentation_scope.attributes else None}' but processor is for '{self.public_key}'. "
9292
f"This prevents cross-project data leakage in multi-project environments."
9393
)
9494
return

0 commit comments

Comments
 (0)