-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathclient.py
More file actions
2209 lines (1898 loc) · 84.5 KB
/
client.py
File metadata and controls
2209 lines (1898 loc) · 84.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Langfuse OpenTelemetry integration module.
This module implements Langfuse's core observability functionality on top of the OpenTelemetry (OTel) standard.
"""
import logging
import os
import re
import urllib.parse
from datetime import datetime
from hashlib import sha256
from time import time_ns
from typing import Any, Dict, List, Literal, Optional, Union, cast, overload
import backoff
import httpx
from opentelemetry import trace
from opentelemetry import trace as otel_trace_api
from opentelemetry.sdk.trace.id_generator import RandomIdGenerator
from opentelemetry.util._decorator import (
_AgnosticContextManager,
_agnosticcontextmanager,
)
from langfuse._client.attributes import (
LangfuseOtelSpanAttributes,
create_generation_attributes,
create_span_attributes,
)
from langfuse._client.datasets import DatasetClient, DatasetItemClient
from langfuse._client.environment_variables import (
LANGFUSE_DEBUG,
LANGFUSE_HOST,
LANGFUSE_PUBLIC_KEY,
LANGFUSE_SAMPLE_RATE,
LANGFUSE_SECRET_KEY,
LANGFUSE_TRACING_ENABLED,
LANGFUSE_TRACING_ENVIRONMENT,
)
from langfuse._client.resource_manager import LangfuseResourceManager
from langfuse._client.span import (
LangfuseEvent,
LangfuseGeneration,
LangfuseSpan,
)
from langfuse._utils import _get_timestamp
from langfuse._utils.parse_error import handle_fern_exception
from langfuse._utils.prompt_cache import PromptCache
from langfuse.api.resources.commons.errors.error import Error
from langfuse.api.resources.ingestion.types.score_body import ScoreBody
from langfuse.api.resources.prompts.types import (
CreatePromptRequest_Chat,
CreatePromptRequest_Text,
Prompt_Chat,
Prompt_Text,
)
from langfuse.logger import langfuse_logger
from langfuse.media import LangfuseMedia
from langfuse.model import (
ChatMessageDict,
ChatPromptClient,
CreateDatasetItemRequest,
CreateDatasetRequest,
Dataset,
DatasetItem,
DatasetStatus,
MapValue,
PromptClient,
TextPromptClient,
)
from langfuse.types import MaskFunction, ScoreDataType, SpanLevel, TraceContext
class Langfuse:
"""Main client for Langfuse tracing and platform features.
This class provides an interface for creating and managing traces, spans,
and generations in Langfuse as well as interacting with the Langfuse API.
The client features a thread-safe singleton pattern for each unique public API key,
ensuring consistent trace context propagation across your application. It implements
efficient batching of spans with configurable flush settings and includes background
thread management for media uploads and score ingestion.
Configuration is flexible through either direct parameters or environment variables,
with graceful fallbacks and runtime configuration updates.
Attributes:
api: Synchronous API client for Langfuse backend communication
async_api: Asynchronous API client for Langfuse backend communication
langfuse_tracer: Internal LangfuseTracer instance managing OpenTelemetry components
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.
host (Optional[str]): The Langfuse API host URL. Defaults to "https://cloud.langfuse.com". Can also be set via LANGFUSE_HOST environment variable.
timeout (Optional[int]): Timeout in seconds for API requests. Defaults to 30 seconds.
httpx_client (Optional[httpx.Client]): Custom httpx client for making non-tracing HTTP requests. If not provided, a default client will be created.
debug (bool): Enable debug logging. Defaults to False. Can also be set via LANGFUSE_DEBUG environment variable.
tracing_enabled (Optional[bool]): Enable or disable tracing. Defaults to True. Can also be set via LANGFUSE_TRACING_ENABLED environment variable.
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.
flush_interval (Optional[float]): Time in seconds between batch flushes. Defaults to 5 seconds. Can also be set via LANGFUSE_FLUSH_INTERVAL environment variable.
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'.
release (Optional[str]): Release version/hash of your application. Used for grouping analytics by release.
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.
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.
mask (Optional[MaskFunction]): Function to mask sensitive data in traces before sending to the API.
Example:
```python
from langfuse.otel import Langfuse
# Initialize the client (reads from env vars if not provided)
langfuse = Langfuse(
public_key="your-public-key",
secret_key="your-secret-key",
host="https://cloud.langfuse.com", # Optional, default shown
)
# Create a trace span
with langfuse.start_as_current_span(name="process-query") as span:
# Your application code here
# Create a nested generation span for an LLM call
with span.start_as_current_generation(
name="generate-response",
model="gpt-4",
input={"query": "Tell me about AI"},
model_parameters={"temperature": 0.7, "max_tokens": 500}
) as generation:
# Generate response here
response = "AI is a field of computer science..."
generation.update(
output=response,
usage_details={"prompt_tokens": 10, "completion_tokens": 50},
cost_details={"total_cost": 0.0023}
)
# Score the generation (supports NUMERIC, BOOLEAN, CATEGORICAL)
generation.score(name="relevance", value=0.95, data_type="NUMERIC")
```
"""
def __init__(
self,
*,
public_key: Optional[str] = None,
secret_key: Optional[str] = None,
host: Optional[str] = None,
timeout: Optional[int] = None,
httpx_client: Optional[httpx.Client] = None,
debug: bool = False,
tracing_enabled: Optional[bool] = True,
flush_at: Optional[int] = None,
flush_interval: Optional[float] = None,
environment: Optional[str] = None,
release: Optional[str] = None,
media_upload_thread_count: Optional[int] = None,
sample_rate: Optional[float] = None,
mask: Optional[MaskFunction] = None,
):
self._host = host or os.environ.get(LANGFUSE_HOST, "https://cloud.langfuse.com")
self._environment = environment or os.environ.get(LANGFUSE_TRACING_ENVIRONMENT)
self._mask = mask
self._project_id = None
sample_rate = sample_rate or float(os.environ.get(LANGFUSE_SAMPLE_RATE, 1.0))
if not 0.0 <= sample_rate <= 1.0:
raise ValueError(
f"Sample rate must be between 0.0 and 1.0, got {sample_rate}"
)
self._tracing_enabled = (
tracing_enabled
and os.environ.get(LANGFUSE_TRACING_ENABLED, "True") != "False"
)
if not self._tracing_enabled:
langfuse_logger.info(
"Configuration: Langfuse tracing is explicitly disabled. No data will be sent to the Langfuse API."
)
debug = debug if debug else (os.getenv(LANGFUSE_DEBUG, "False") == "True")
if debug:
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
langfuse_logger.setLevel(logging.DEBUG)
public_key = public_key or os.environ.get(LANGFUSE_PUBLIC_KEY)
if 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. "
"See documentation: https://langfuse.com/docs/sdk/python/low-level-sdk#initialize-client"
)
self._otel_tracer = otel_trace_api.NoOpTracer()
return
secret_key = secret_key or os.environ.get(LANGFUSE_SECRET_KEY)
if 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. "
"See documentation: https://langfuse.com/docs/sdk/python/low-level-sdk#initialize-client"
)
self._otel_tracer = otel_trace_api.NoOpTracer()
return
# Initialize api and tracer if requirements are met
self._resources = LangfuseResourceManager(
public_key=public_key,
secret_key=secret_key,
host=self._host,
timeout=timeout,
environment=environment,
release=release,
flush_at=flush_at,
flush_interval=flush_interval,
httpx_client=httpx_client,
media_upload_thread_count=media_upload_thread_count,
sample_rate=sample_rate,
)
self._otel_tracer = (
self._resources.tracer
if self._tracing_enabled
else otel_trace_api.NoOpTracer()
)
self.api = self._resources.api
self.async_api = self._resources.async_api
def start_span(
self,
*,
trace_context: Optional[TraceContext] = None,
name: str,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
) -> LangfuseSpan:
"""Create a new span for tracing a unit of work.
This method creates a new span but does not set it as the current span in the
context. To create and use a span within a context, use start_as_current_span().
The created span will be the child of the current span in the context.
Args:
trace_context: Optional context for connecting to an existing trace
name: Name of the span (e.g., function or operation name)
input: Input data for the operation (can be any JSON-serializable object)
output: Output data from the operation (can be any JSON-serializable object)
metadata: Additional metadata to associate with the span
version: Version identifier for the code or component
level: Importance level of the span (info, warning, error)
status_message: Optional status message for the span
Returns:
A LangfuseSpan object that must be ended with .end() when the operation completes
Example:
```python
span = langfuse.start_span(name="process-data")
try:
# Do work
span.update(output="result")
finally:
span.end()
```
"""
attributes = create_span_attributes(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
)
if trace_context:
trace_id = trace_context.get("trace_id", None)
parent_span_id = trace_context.get("parent_span_id", None)
if trace_id:
remote_parent_span = self._create_remote_parent_span(
trace_id=trace_id, parent_span_id=parent_span_id
)
with otel_trace_api.use_span(
cast(otel_trace_api.Span, remote_parent_span)
):
otel_span = self._otel_tracer.start_span(
name=name, attributes=attributes
)
otel_span.set_attribute(LangfuseOtelSpanAttributes.AS_ROOT, True)
return LangfuseSpan(
otel_span=otel_span,
langfuse_client=self,
input=input,
output=output,
metadata=metadata,
environment=self._environment,
)
otel_span = self._otel_tracer.start_span(name=name, attributes=attributes)
return LangfuseSpan(
otel_span=otel_span,
langfuse_client=self,
input=input,
output=output,
metadata=metadata,
environment=self._environment,
)
def start_as_current_span(
self,
*,
trace_context: Optional[TraceContext] = None,
name: str,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
end_on_exit: Optional[bool] = None,
) -> _AgnosticContextManager[LangfuseSpan]:
"""Create a new span and set it as the current span in a context manager.
This method creates a new span and sets it as the current span within a context
manager. Use this method with a 'with' statement to automatically handle span
lifecycle within a code block.
The created span will be the child of the current span in the context.
Args:
trace_context: Optional context for connecting to an existing trace
name: Name of the span (e.g., function or operation name)
input: Input data for the operation (can be any JSON-serializable object)
output: Output data from the operation (can be any JSON-serializable object)
metadata: Additional metadata to associate with the span
version: Version identifier for the code or component
level: Importance level of the span (info, warning, error)
status_message: Optional status message for the span
end_on_exit (default: True): Whether to end the span automatically when leaving the context manager. If False, the span must be manually ended to avoid memory leaks.
Returns:
A context manager that yields a LangfuseSpan
Example:
```python
with langfuse.start_as_current_span(name="process-query") as span:
# Do work
result = process_data()
span.update(output=result)
# Create a child span automatically
with span.start_as_current_span(name="sub-operation") as child_span:
# Do sub-operation work
child_span.update(output="sub-result")
```
"""
attributes = create_span_attributes(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
)
if trace_context:
trace_id = trace_context.get("trace_id", None)
parent_span_id = trace_context.get("parent_span_id", None)
if trace_id:
remote_parent_span = self._create_remote_parent_span(
trace_id=trace_id, parent_span_id=parent_span_id
)
return cast(
_AgnosticContextManager[LangfuseSpan],
self._create_span_with_parent_context(
as_type="span",
name=name,
attributes=attributes,
remote_parent_span=remote_parent_span,
parent=None,
input=input,
output=output,
metadata=metadata,
end_on_exit=end_on_exit,
),
)
return cast(
_AgnosticContextManager[LangfuseSpan],
self._start_as_current_otel_span_with_processed_media(
as_type="span",
name=name,
attributes=attributes,
input=input,
output=output,
metadata=metadata,
end_on_exit=end_on_exit,
),
)
def start_generation(
self,
*,
trace_context: Optional[TraceContext] = None,
name: str,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
completion_start_time: Optional[datetime] = None,
model: Optional[str] = None,
model_parameters: Optional[Dict[str, MapValue]] = None,
usage_details: Optional[Dict[str, int]] = None,
cost_details: Optional[Dict[str, float]] = None,
prompt: Optional[PromptClient] = None,
) -> LangfuseGeneration:
"""Create a new generation span for model generations.
This method creates a specialized span for tracking model generations.
It includes additional fields specific to model generations such as model name,
token usage, and cost details.
The created generation span will be the child of the current span in the context.
Args:
trace_context: Optional context for connecting to an existing trace
name: Name of the generation operation
input: Input data for the model (e.g., prompts)
output: Output from the model (e.g., completions)
metadata: Additional metadata to associate with the generation
version: Version identifier for the model or component
level: Importance level of the generation (info, warning, error)
status_message: Optional status message for the generation
completion_start_time: When the model started generating the response
model: Name/identifier of the AI model used (e.g., "gpt-4")
model_parameters: Parameters used for the model (e.g., temperature, max_tokens)
usage_details: Token usage information (e.g., prompt_tokens, completion_tokens)
cost_details: Cost information for the model call
prompt: Associated prompt template from Langfuse prompt management
Returns:
A LangfuseGeneration object that must be ended with .end() when complete
Example:
```python
generation = langfuse.start_generation(
name="answer-generation",
model="gpt-4",
input={"prompt": "Explain quantum computing"},
model_parameters={"temperature": 0.7}
)
try:
# Call model API
response = llm.generate(...)
generation.update(
output=response.text,
usage_details={
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens
}
)
finally:
generation.end()
```
"""
attributes = create_generation_attributes(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
completion_start_time=completion_start_time,
model=model,
model_parameters=model_parameters,
usage_details=usage_details,
cost_details=cost_details,
prompt=prompt,
)
if trace_context:
trace_id = trace_context.get("trace_id", None)
parent_span_id = trace_context.get("parent_span_id", None)
if trace_id:
remote_parent_span = self._create_remote_parent_span(
trace_id=trace_id, parent_span_id=parent_span_id
)
with otel_trace_api.use_span(
cast(otel_trace_api.Span, remote_parent_span)
):
otel_span = self._otel_tracer.start_span(
name=name, attributes=attributes
)
otel_span.set_attribute(LangfuseOtelSpanAttributes.AS_ROOT, True)
return LangfuseGeneration(
otel_span=otel_span,
langfuse_client=self,
input=input,
output=output,
metadata=metadata,
)
otel_span = self._otel_tracer.start_span(name=name, attributes=attributes)
return LangfuseGeneration(
otel_span=otel_span,
langfuse_client=self,
input=input,
output=output,
metadata=metadata,
)
def start_as_current_generation(
self,
*,
trace_context: Optional[TraceContext] = None,
name: str,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
completion_start_time: Optional[datetime] = None,
model: Optional[str] = None,
model_parameters: Optional[Dict[str, MapValue]] = None,
usage_details: Optional[Dict[str, int]] = None,
cost_details: Optional[Dict[str, float]] = None,
prompt: Optional[PromptClient] = None,
end_on_exit: Optional[bool] = None,
) -> _AgnosticContextManager[LangfuseGeneration]:
"""Create a new generation span and set it as the current span in a context manager.
This method creates a specialized span for model generations and sets it as the
current span within a context manager. Use this method with a 'with' statement to
automatically handle the generation span lifecycle within a code block.
The created generation span will be the child of the current span in the context.
Args:
trace_context: Optional context for connecting to an existing trace
name: Name of the generation operation
input: Input data for the model (e.g., prompts)
output: Output from the model (e.g., completions)
metadata: Additional metadata to associate with the generation
version: Version identifier for the model or component
level: Importance level of the generation (info, warning, error)
status_message: Optional status message for the generation
completion_start_time: When the model started generating the response
model: Name/identifier of the AI model used (e.g., "gpt-4")
model_parameters: Parameters used for the model (e.g., temperature, max_tokens)
usage_details: Token usage information (e.g., prompt_tokens, completion_tokens)
cost_details: Cost information for the model call
prompt: Associated prompt template from Langfuse prompt management
end_on_exit (default: True): Whether to end the span automatically when leaving the context manager. If False, the span must be manually ended to avoid memory leaks.
Returns:
A context manager that yields a LangfuseGeneration
Example:
```python
with langfuse.start_as_current_generation(
name="answer-generation",
model="gpt-4",
input={"prompt": "Explain quantum computing"}
) as generation:
# Call model API
response = llm.generate(...)
# Update with results
generation.update(
output=response.text,
usage_details={
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens
}
)
```
"""
attributes = create_generation_attributes(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
completion_start_time=completion_start_time,
model=model,
model_parameters=model_parameters,
usage_details=usage_details,
cost_details=cost_details,
prompt=prompt,
)
if trace_context:
trace_id = trace_context.get("trace_id", None)
parent_span_id = trace_context.get("parent_span_id", None)
if trace_id:
remote_parent_span = self._create_remote_parent_span(
trace_id=trace_id, parent_span_id=parent_span_id
)
return cast(
_AgnosticContextManager[LangfuseGeneration],
self._create_span_with_parent_context(
as_type="generation",
name=name,
attributes=attributes,
remote_parent_span=remote_parent_span,
parent=None,
input=input,
output=output,
metadata=metadata,
end_on_exit=end_on_exit,
),
)
return cast(
_AgnosticContextManager[LangfuseGeneration],
self._start_as_current_otel_span_with_processed_media(
as_type="generation",
name=name,
attributes=attributes,
input=input,
output=output,
metadata=metadata,
end_on_exit=end_on_exit,
),
)
@_agnosticcontextmanager
def _create_span_with_parent_context(
self,
*,
name,
parent,
remote_parent_span,
attributes,
as_type: Literal["generation", "span"],
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
end_on_exit: Optional[bool] = None,
):
parent_span = parent or cast(otel_trace_api.Span, remote_parent_span)
with otel_trace_api.use_span(parent_span):
with self._start_as_current_otel_span_with_processed_media(
name=name,
attributes=attributes,
as_type=as_type,
input=input,
output=output,
metadata=metadata,
end_on_exit=end_on_exit,
) as langfuse_span:
if remote_parent_span is not None:
langfuse_span._otel_span.set_attribute(
LangfuseOtelSpanAttributes.AS_ROOT, True
)
yield langfuse_span
@_agnosticcontextmanager
def _start_as_current_otel_span_with_processed_media(
self,
*,
name: str,
attributes: Dict[str, str],
as_type: Optional[Literal["generation", "span"]] = None,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
end_on_exit: Optional[bool] = None,
):
with self._otel_tracer.start_as_current_span(
name=name,
attributes=attributes,
end_on_exit=end_on_exit if end_on_exit is not None else True,
) as otel_span:
yield (
LangfuseSpan(
otel_span=otel_span,
langfuse_client=self,
input=input,
output=output,
metadata=metadata,
environment=self._environment,
)
if as_type == "span"
else LangfuseGeneration(
otel_span=otel_span,
langfuse_client=self,
input=input,
output=output,
metadata=metadata,
environment=self._environment,
)
)
def _get_current_otel_span(self) -> Optional[otel_trace_api.Span]:
current_span = otel_trace_api.get_current_span()
if current_span is otel_trace_api.INVALID_SPAN:
langfuse_logger.warning(
"Context error: No active span in current context. Operations that depend on an active span will be skipped. "
"Ensure spans are created with start_as_current_span() or that you're operating within an active span context."
)
return None
return current_span
def update_current_generation(
self,
*,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
completion_start_time: Optional[datetime] = None,
model: Optional[str] = None,
model_parameters: Optional[Dict[str, MapValue]] = None,
usage_details: Optional[Dict[str, int]] = None,
cost_details: Optional[Dict[str, float]] = None,
prompt: Optional[PromptClient] = None,
) -> None:
"""Update the current active generation span with new information.
This method updates the current generation span in the active context with
additional information. It's useful for adding output, usage stats, or other
details that become available during or after model generation.
Args:
input: Updated input data for the model
output: Output from the model (e.g., completions)
metadata: Additional metadata to associate with the generation
version: Version identifier for the model or component
level: Importance level of the generation (info, warning, error)
status_message: Optional status message for the generation
completion_start_time: When the model started generating the response
model: Name/identifier of the AI model used (e.g., "gpt-4")
model_parameters: Parameters used for the model (e.g., temperature, max_tokens)
usage_details: Token usage information (e.g., prompt_tokens, completion_tokens)
cost_details: Cost information for the model call
prompt: Associated prompt template from Langfuse prompt management
Example:
```python
with langfuse.start_as_current_generation(name="answer-query") as generation:
# Initial setup and API call
response = llm.generate(...)
# Update with results that weren't available at creation time
langfuse.update_current_generation(
output=response.text,
usage_details={
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens
}
)
```
"""
if not self._tracing_enabled:
langfuse_logger.debug(
"Operation skipped: update_current_generation - Tracing is disabled or client is in no-op mode."
)
return
current_otel_span = self._get_current_otel_span()
if current_otel_span is not None:
generation = LangfuseGeneration(
otel_span=current_otel_span, langfuse_client=self
)
generation.update(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
completion_start_time=completion_start_time,
model=model,
model_parameters=model_parameters,
usage_details=usage_details,
cost_details=cost_details,
prompt=prompt,
)
def update_current_span(
self,
*,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
) -> None:
"""Update the current active span with new information.
This method updates the current span in the active context with
additional information. It's useful for adding outputs or metadata
that become available during execution.
Args:
input: Updated input data for the operation
output: Output data from the operation
metadata: Additional metadata to associate with the span
version: Version identifier for the code or component
level: Importance level of the span (info, warning, error)
status_message: Optional status message for the span
Example:
```python
with langfuse.start_as_current_span(name="process-data") as span:
# Initial processing
result = process_first_part()
# Update with intermediate results
langfuse.update_current_span(metadata={"intermediate_result": result})
# Continue processing
final_result = process_second_part(result)
# Final update
langfuse.update_current_span(output=final_result)
```
"""
if not self._tracing_enabled:
langfuse_logger.debug(
"Operation skipped: update_current_span - Tracing is disabled or client is in no-op mode."
)
return
current_otel_span = self._get_current_otel_span()
if current_otel_span is not None:
span = LangfuseSpan(
otel_span=current_otel_span,
langfuse_client=self,
environment=self._environment,
)
span.update(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
)
def update_current_trace(
self,
*,
name: Optional[str] = None,
user_id: Optional[str] = None,
session_id: Optional[str] = None,
version: Optional[str] = None,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
tags: Optional[List[str]] = None,
public: Optional[bool] = None,
):
"""Update the current trace with additional information.
This method updates the Langfuse trace that the current span belongs to. It's useful for
adding trace-level metadata like user ID, session ID, or tags that apply to
the entire Langfuse trace rather than just a single observation.
Args:
name: Updated name for the Langfuse trace
user_id: ID of the user who initiated the Langfuse trace
session_id: Session identifier for grouping related Langfuse traces
version: Version identifier for the application or service
input: Input data for the overall Langfuse trace
output: Output data from the overall Langfuse trace
metadata: Additional metadata to associate with the Langfuse trace
tags: List of tags to categorize the Langfuse trace
public: Whether the Langfuse trace should be publicly accessible
Example:
```python
with langfuse.start_as_current_span(name="handle-request") as span:
# Get user information
user = authenticate_user(request)
# Update trace with user context
langfuse.update_current_trace(
user_id=user.id,
session_id=request.session_id,
tags=["production", "web-app"]
)
# Continue processing
response = process_request(request)
# Update span with results
span.update(output=response)
```
"""
if not self._tracing_enabled:
langfuse_logger.debug(
"Operation skipped: update_current_trace - Tracing is disabled or client is in no-op mode."
)
return
current_otel_span = self._get_current_otel_span()
if current_otel_span is not None:
span = LangfuseSpan(
otel_span=current_otel_span,
langfuse_client=self,
environment=self._environment,
)
span.update_trace(
name=name,
user_id=user_id,
session_id=session_id,
version=version,
input=input,
output=output,
metadata=metadata,
tags=tags,
public=public,
)
def create_event(
self,
*,
trace_context: Optional[TraceContext] = None,
name: str,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
version: Optional[str] = None,
level: Optional[SpanLevel] = None,
status_message: Optional[str] = None,
) -> LangfuseEvent:
"""Create a new Langfuse observation of type 'EVENT'.
The created Langfuse Event observation will be the child of the current span in the context.
Args:
trace_context: Optional context for connecting to an existing trace
name: Name of the span (e.g., function or operation name)
input: Input data for the operation (can be any JSON-serializable object)
output: Output data from the operation (can be any JSON-serializable object)
metadata: Additional metadata to associate with the span
version: Version identifier for the code or component
level: Importance level of the span (info, warning, error)
status_message: Optional status message for the span
Returns:
The Langfuse Event object
Example:
```python
event = langfuse.create_event(name="process-event")
```
"""
timestamp = time_ns()
attributes = create_span_attributes(
input=input,
output=output,
metadata=metadata,
version=version,
level=level,
status_message=status_message,
)
if trace_context:
trace_id = trace_context.get("trace_id", None)
parent_span_id = trace_context.get("parent_span_id", None)