0
# Core Tracing and Observability
1
2
Fundamental tracing functionality for instrumenting AI applications with automatic span creation, context propagation, and detailed performance monitoring. Built on OpenTelemetry standards for industry compatibility.
3
4
## Capabilities
5
6
### Main Client
7
8
The primary interface for all Langfuse tracing operations, providing methods for creating spans, managing traces, and configuring observability.
9
10
```python { .api }
11
class Langfuse:
12
def __init__(self, *, public_key: str = None, secret_key: str = None,
13
host: str = "https://cloud.langfuse.com", tracing_enabled: bool = True,
14
environment: str = None, timeout: int = 60, **kwargs): ...
15
```
16
17
**Parameters:**
18
- `public_key` (str, optional): Project public key, can also be set via LANGFUSE_PUBLIC_KEY env var
19
- `secret_key` (str, optional): Project secret key, can also be set via LANGFUSE_SECRET_KEY env var
20
- `host` (str): Langfuse server URL, defaults to cloud instance
21
- `tracing_enabled` (bool): Enable/disable tracing globally
22
- `environment` (str, optional): Environment tag for traces
23
- `timeout` (int): Request timeout in seconds
24
25
### Manual Span Creation
26
27
Create spans manually for precise control over tracing boundaries and span metadata.
28
29
```python { .api }
30
def start_span(self, name: str, *, input: Any = None, output: Any = None,
31
metadata: Any = None, **kwargs) -> LangfuseSpan:
32
"""Create a new span without setting it as current.
33
34
Args:
35
name: Span name
36
input: Input data for the operation
37
output: Output data from the operation
38
metadata: Additional metadata
39
40
Returns:
41
LangfuseSpan that must be ended with .end()
42
"""
43
```
44
45
### Context Manager Spans
46
47
Create spans with automatic lifecycle management using Python context managers.
48
49
```python { .api }
50
def start_as_current_span(self, *, name: str, input: Any = None, output: Any = None,
51
metadata: Any = None, **kwargs) -> ContextManager[LangfuseSpan]:
52
"""Create a span as a context manager.
53
54
Args:
55
name: Span name
56
input: Input data for the operation
57
output: Output data from the operation
58
metadata: Additional metadata
59
60
Returns:
61
Context manager yielding LangfuseSpan
62
"""
63
```
64
65
**Usage Example:**
66
67
```python
68
with langfuse.start_as_current_span(name="process-data") as span:
69
result = process_data()
70
span.update(output=result)
71
```
72
73
### Generic Observation Creation
74
75
Create observations of any type with a unified interface supporting all observation types.
76
77
```python { .api }
78
def start_observation(self, *, name: str, as_type: ObservationTypeLiteral,
79
input: Any = None, output: Any = None, metadata: Any = None,
80
**kwargs) -> Union[LangfuseSpan, LangfuseGeneration, LangfuseAgent, LangfuseTool, LangfuseChain, LangfuseRetriever, LangfuseEvaluator, LangfuseEmbedding, LangfuseGuardrail]:
81
"""Create observation of specified type.
82
83
Args:
84
name: Observation name
85
as_type: Type of observation (span, generation, tool, etc.)
86
input: Input data
87
output: Output data
88
metadata: Additional metadata
89
**kwargs: Type-specific parameters (model, usage_details, etc.)
90
91
Returns:
92
Observation of the specified type
93
"""
94
```
95
96
```python { .api }
97
def start_as_current_observation(self, *, name: str, as_type: ObservationTypeLiteralNoEvent,
98
input: Any = None, output: Any = None, metadata: Any = None,
99
**kwargs) -> ContextManager[Union[LangfuseSpan, LangfuseGeneration, ...]]:
100
"""Create observation as context manager.
101
102
Args:
103
name: Observation name
104
as_type: Type of observation (all types except event)
105
input: Input data
106
output: Output data
107
metadata: Additional metadata
108
**kwargs: Type-specific parameters
109
110
Returns:
111
Context manager yielding observation
112
"""
113
```
114
115
### Event Creation
116
117
Create point-in-time events for logging discrete occurrences.
118
119
```python { .api }
120
def create_event(self, *, name: str, input: Any = None, output: Any = None,
121
metadata: Any = None, level: SpanLevel = None,
122
status_message: str = None) -> LangfuseEvent:
123
"""Create a point-in-time event.
124
125
Args:
126
name: Event name
127
input: Event input data
128
output: Event output data
129
metadata: Additional metadata
130
level: Importance level (DEBUG, DEFAULT, WARNING, ERROR)
131
status_message: Status message
132
133
Returns:
134
LangfuseEvent (already ended)
135
"""
136
```
137
138
### Decorator-Based Tracing
139
140
Automatic function instrumentation with minimal code changes using the observe decorator.
141
142
```python { .api }
143
def observe(func=None, *, name: str = None, as_type: ObservationTypeLiteralNoEvent = None,
144
capture_input: bool = None, capture_output: bool = None,
145
transform_to_string: Callable[[Iterable], str] = None) -> Union[Callable, Callable[[Callable], Callable]]:
146
"""Decorator for automatic function tracing.
147
148
Args:
149
func: Function to decorate (when used without parentheses)
150
name: Custom observation name (defaults to function name)
151
as_type: Observation type (span, generation, tool, etc.)
152
capture_input: Whether to capture function inputs
153
capture_output: Whether to capture function outputs
154
transform_to_string: Function to transform generator outputs to string
155
156
Returns:
157
Decorated function with automatic tracing
158
"""
159
```
160
161
**Usage Examples:**
162
163
```python
164
# Simple decoration
165
@observe
166
def process_data(data):
167
return processed_data
168
169
# With configuration
170
@observe(name="llm-generation", as_type="generation")
171
def generate_text(prompt):
172
return llm_response
173
174
# Special function arguments for tracing control
175
def my_function(data, langfuse_trace_id=None, langfuse_parent_observation_id=None):
176
# Function will be traced with specified trace/parent IDs
177
pass
178
```
179
180
### Client Management
181
182
Utilities for managing client instances in multi-project setups.
183
184
```python { .api }
185
def get_client(*, public_key: str = None) -> Langfuse:
186
"""Get or create Langfuse client instance.
187
188
Args:
189
public_key: Project identifier for multi-project setups
190
191
Returns:
192
Langfuse client instance
193
"""
194
```
195
196
### Resource Management
197
198
Methods for managing client resources and ensuring proper cleanup.
199
200
```python { .api }
201
def flush(self) -> None:
202
"""Force flush of pending events to Langfuse."""
203
204
def shutdown(self) -> None:
205
"""Shutdown client and release resources."""
206
207
def auth_check(self) -> bool:
208
"""Check API authentication credentials."""
209
```
210
211
### Trace Context Management
212
213
Utilities for working with trace context and IDs.
214
215
```python { .api }
216
def create_trace_id(self) -> str:
217
"""Generate a unique trace ID."""
218
219
def get_current_trace_id(self) -> str:
220
"""Get current trace ID from context."""
221
222
def get_current_observation_id(self) -> str:
223
"""Get current observation ID from context."""
224
225
def get_trace_url(self, trace_id: str) -> str:
226
"""Get URL to view trace in Langfuse UI."""
227
```
228
229
## Usage Examples
230
231
### Basic Tracing
232
233
```python
234
from langfuse import Langfuse
235
236
langfuse = Langfuse()
237
238
# Manual span management
239
span = langfuse.start_span(name="data-processing")
240
try:
241
result = process_data()
242
span.update(output=result)
243
finally:
244
span.end()
245
246
# Context manager (recommended)
247
with langfuse.start_as_current_span(name="data-processing") as span:
248
result = process_data()
249
span.update(output=result)
250
```
251
252
### Automatic Tracing with Decorators
253
254
```python
255
from langfuse import observe
256
257
@observe(as_type="generation")
258
def generate_response(prompt):
259
# This function is automatically traced
260
response = call_llm(prompt)
261
return response
262
263
@observe(name="custom-processor")
264
async def process_async(data):
265
# Works with async functions too
266
result = await async_process(data)
267
return result
268
```
269
270
### Nested Spans
271
272
```python
273
@observe(name="main-process")
274
def main_process():
275
# Parent span created automatically
276
277
@observe(name="sub-process")
278
def sub_process():
279
# Child span created automatically
280
return "result"
281
282
return sub_process()
283
284
# Or with manual management
285
with langfuse.start_as_current_span(name="parent") as parent:
286
with parent.start_as_current_observation(name="child", as_type="tool") as child:
287
result = call_external_api()
288
child.update(output=result)
289
```
290
291
### Error Handling
292
293
```python
294
@observe(as_type="generation")
295
def risky_operation():
296
try:
297
result = might_fail()
298
return result
299
except Exception as e:
300
# Error automatically captured in trace
301
raise
302
```
303
304
### Generator Support
305
306
```python
307
@observe(capture_output=True)
308
def stream_data():
309
for item in data_stream():
310
yield process_item(item)
311
# Full output automatically captured when generator exhausted
312
```