-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathspan.py
More file actions
1519 lines (1352 loc) · 54.5 KB
/
span.py
File metadata and controls
1519 lines (1352 loc) · 54.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
"""OTEL span wrapper for Langfuse.
This module defines custom span classes that extend OpenTelemetry spans with
Langfuse-specific functionality. These wrapper classes provide methods for
creating, updating, and scoring various types of spans used in AI application tracing.
Classes:
- LangfuseObservationWrapper: Abstract base class for all Langfuse spans
- LangfuseSpan: Implementation for general-purpose spans
- LangfuseGeneration: Specialized span implementation for LLM generations
All span classes provide methods for media processing, attribute management,
and scoring integration specific to Langfuse's observability platform.
"""
from datetime import datetime
from time import time_ns
from typing import (
TYPE_CHECKING,
Any,
Dict,
Literal,
Optional,
Type,
Union,
cast,
overload,
)
from opentelemetry import trace as otel_trace_api
from opentelemetry.trace.status import Status, StatusCode
from opentelemetry.util._decorator import _AgnosticContextManager
from langfuse.model import PromptClient
if TYPE_CHECKING:
from langfuse._client.client import Langfuse
from typing_extensions import deprecated
from langfuse._client.attributes import (
LangfuseOtelSpanAttributes,
create_generation_attributes,
create_span_attributes,
create_trace_attributes,
)
from langfuse._client.constants import (
ObservationTypeGenerationLike,
ObservationTypeLiteral,
ObservationTypeLiteralNoEvent,
ObservationTypeSpanLike,
get_observation_types_list,
)
from langfuse.api import MapValue, ScoreDataType
from langfuse.logger import langfuse_logger
from langfuse.types import SpanLevel
# Factory mapping for observation classes
# Note: "event" is handled separately due to special instantiation logic
# Populated after class definitions
_OBSERVATION_CLASS_MAP: Dict[str, Type["LangfuseObservationWrapper"]] = {}
class LangfuseObservationWrapper:
"""Abstract base class for all Langfuse span types.
This class provides common functionality for all Langfuse span types, including
media processing, attribute management, and scoring. It wraps an OpenTelemetry
span and extends it with Langfuse-specific features.
Attributes:
_otel_span: The underlying OpenTelemetry span
_langfuse_client: Reference to the parent Langfuse client
trace_id: The trace ID for this span
observation_id: The observation ID (span ID) for this span
"""
def __init__(
self,
*,
otel_span: otel_trace_api.Span,
langfuse_client: "Langfuse",
as_type: ObservationTypeLiteral,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
environment: Optional[str] = None,
release: Optional[str] = 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,
):
"""Initialize a new Langfuse span wrapper.
Args:
otel_span: The OpenTelemetry span to wrap
langfuse_client: Reference to the parent Langfuse client
as_type: The type of span ("span" or "generation")
input: Input data for the span (any JSON-serializable object)
output: Output data from the span (any JSON-serializable object)
metadata: Additional metadata to associate with the span
environment: The tracing environment
release: Release identifier for the application
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
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
"""
self._otel_span = otel_span
self._otel_span.set_attribute(
LangfuseOtelSpanAttributes.OBSERVATION_TYPE, as_type
)
self._langfuse_client = langfuse_client
self._observation_type = as_type
self.trace_id = self._langfuse_client._get_otel_trace_id(otel_span)
self.id = self._langfuse_client._get_otel_span_id(otel_span)
self._environment = environment or self._langfuse_client._environment
if self._environment is not None:
self._otel_span.set_attribute(
LangfuseOtelSpanAttributes.ENVIRONMENT, self._environment
)
self._release = release or self._langfuse_client._release
if self._release is not None:
self._otel_span.set_attribute(
LangfuseOtelSpanAttributes.RELEASE, self._release
)
# Handle media only if span is sampled
if self._otel_span.is_recording():
media_processed_input = self._process_media_and_apply_mask(
data=input, field="input", span=self._otel_span
)
media_processed_output = self._process_media_and_apply_mask(
data=output, field="output", span=self._otel_span
)
media_processed_metadata = self._process_media_and_apply_mask(
data=metadata, field="metadata", span=self._otel_span
)
attributes = {}
if as_type in get_observation_types_list(ObservationTypeGenerationLike):
attributes = create_generation_attributes(
input=media_processed_input,
output=media_processed_output,
metadata=media_processed_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,
observation_type=cast(
ObservationTypeGenerationLike,
as_type,
),
)
else:
# For span-like types and events
attributes = create_span_attributes(
input=media_processed_input,
output=media_processed_output,
metadata=media_processed_metadata,
version=version,
level=level,
status_message=status_message,
observation_type=cast(
Optional[Union[ObservationTypeSpanLike, Literal["event"]]],
as_type
if as_type
in get_observation_types_list(ObservationTypeSpanLike)
or as_type == "event"
else None,
),
)
# We don't want to overwrite the observation type, and already set it
attributes.pop(LangfuseOtelSpanAttributes.OBSERVATION_TYPE, None)
self._otel_span.set_attributes(
{k: v for k, v in attributes.items() if v is not None}
)
# Set OTEL span status if level is ERROR
self._set_otel_span_status_if_error(
level=level, status_message=status_message
)
def end(self, *, end_time: Optional[int] = None) -> "LangfuseObservationWrapper":
"""End the span, marking it as completed.
This method ends the wrapped OpenTelemetry span, marking the end of the
operation being traced. After this method is called, the span is considered
complete and can no longer be modified.
Args:
end_time: Optional explicit end time in nanoseconds since epoch
"""
self._otel_span.end(end_time=end_time)
return self
@deprecated(
"Trace-level input/output is deprecated. "
"For trace attributes (user_id, session_id, tags, etc.), use propagate_attributes() instead. "
"This method will be removed in a future major version."
)
def set_trace_io(
self,
*,
input: Optional[Any] = None,
output: Optional[Any] = None,
) -> "LangfuseObservationWrapper":
"""Set trace-level input and output for the trace this span belongs to.
.. deprecated::
This is a legacy method for backward compatibility with Langfuse platform
features that still rely on trace-level input/output (e.g., legacy LLM-as-a-judge
evaluators). It will be removed in a future major version.
For setting other trace attributes (user_id, session_id, metadata, tags, version),
use :meth:`Langfuse.propagate_attributes` instead.
Args:
input: Input data to associate with the trace.
output: Output data to associate with the trace.
Returns:
The span instance for method chaining.
"""
if not self._otel_span.is_recording():
return self
media_processed_input = self._process_media_and_apply_mask(
data=input, field="input", span=self._otel_span
)
media_processed_output = self._process_media_and_apply_mask(
data=output, field="output", span=self._otel_span
)
attributes = create_trace_attributes(
input=media_processed_input,
output=media_processed_output,
)
self._otel_span.set_attributes(attributes)
return self
def set_trace_as_public(self) -> "LangfuseObservationWrapper":
"""Make this trace publicly accessible via its URL.
When a trace is published, anyone with the trace link can view the full trace
without needing to be logged in to Langfuse. This action cannot be undone
programmatically - once any span in a trace is published, the entire trace
becomes public.
Returns:
The span instance for method chaining.
"""
if not self._otel_span.is_recording():
return self
attributes = create_trace_attributes(public=True)
self._otel_span.set_attributes(attributes)
return self
@overload
def score(
self,
*,
name: str,
value: float,
score_id: Optional[str] = None,
data_type: Optional[
Literal[ScoreDataType.NUMERIC, ScoreDataType.BOOLEAN]
] = None,
comment: Optional[str] = None,
config_id: Optional[str] = None,
timestamp: Optional[datetime] = None,
metadata: Optional[Any] = None,
) -> None: ...
@overload
def score(
self,
*,
name: str,
value: str,
score_id: Optional[str] = None,
data_type: Optional[
Literal[ScoreDataType.CATEGORICAL, ScoreDataType.TEXT]
] = ScoreDataType.CATEGORICAL,
comment: Optional[str] = None,
config_id: Optional[str] = None,
timestamp: Optional[datetime] = None,
metadata: Optional[Any] = None,
) -> None: ...
def score(
self,
*,
name: str,
value: Union[float, str],
score_id: Optional[str] = None,
data_type: Optional[ScoreDataType] = None,
comment: Optional[str] = None,
config_id: Optional[str] = None,
timestamp: Optional[datetime] = None,
metadata: Optional[Any] = None,
) -> None:
"""Create a score for this specific span.
This method creates a score associated with this specific span (observation).
Scores can represent any kind of evaluation, feedback, or quality metric.
Args:
name: Name of the score (e.g., "relevance", "accuracy")
value: Score value (numeric for NUMERIC/BOOLEAN, string for CATEGORICAL/TEXT)
score_id: Optional custom ID for the score (auto-generated if not provided)
data_type: Type of score (NUMERIC, BOOLEAN, CATEGORICAL, or TEXT)
comment: Optional comment or explanation for the score
config_id: Optional ID of a score config defined in Langfuse
timestamp: Optional timestamp for the score (defaults to current UTC time)
metadata: Optional metadata to be attached to the score
Example:
```python
with langfuse.start_as_current_observation(name="process-query") as span:
# Do work
result = process_data()
# Score the span
span.score(
name="accuracy",
value=0.95,
data_type="NUMERIC",
comment="High accuracy result"
)
```
"""
self._langfuse_client.create_score(
name=name,
value=cast(str, value),
trace_id=self.trace_id,
observation_id=self.id,
score_id=score_id,
data_type=cast(Literal["CATEGORICAL", "TEXT"], data_type),
comment=comment,
config_id=config_id,
timestamp=timestamp,
metadata=metadata,
)
@overload
def score_trace(
self,
*,
name: str,
value: float,
score_id: Optional[str] = None,
data_type: Optional[
Literal[ScoreDataType.NUMERIC, ScoreDataType.BOOLEAN]
] = None,
comment: Optional[str] = None,
config_id: Optional[str] = None,
timestamp: Optional[datetime] = None,
metadata: Optional[Any] = None,
) -> None: ...
@overload
def score_trace(
self,
*,
name: str,
value: str,
score_id: Optional[str] = None,
data_type: Optional[
Literal[ScoreDataType.CATEGORICAL, ScoreDataType.TEXT]
] = ScoreDataType.CATEGORICAL,
comment: Optional[str] = None,
config_id: Optional[str] = None,
timestamp: Optional[datetime] = None,
metadata: Optional[Any] = None,
) -> None: ...
def score_trace(
self,
*,
name: str,
value: Union[float, str],
score_id: Optional[str] = None,
data_type: Optional[ScoreDataType] = None,
comment: Optional[str] = None,
config_id: Optional[str] = None,
timestamp: Optional[datetime] = None,
metadata: Optional[Any] = None,
) -> None:
"""Create a score for the entire trace that this span belongs to.
This method creates a score associated with the entire trace that this span
belongs to, rather than the specific span. This is useful for overall
evaluations that apply to the complete trace.
Args:
name: Name of the score (e.g., "user_satisfaction", "overall_quality")
value: Score value (numeric for NUMERIC/BOOLEAN, string for CATEGORICAL/TEXT)
score_id: Optional custom ID for the score (auto-generated if not provided)
data_type: Type of score (NUMERIC, BOOLEAN, CATEGORICAL, or TEXT)
comment: Optional comment or explanation for the score
config_id: Optional ID of a score config defined in Langfuse
timestamp: Optional timestamp for the score (defaults to current UTC time)
metadata: Optional metadata to be attached to the score
Example:
```python
with langfuse.start_as_current_observation(name="handle-request") as span:
# Process the complete request
result = process_request()
# Score the entire trace (not just this span)
span.score_trace(
name="overall_quality",
value=0.9,
data_type="NUMERIC",
comment="Good overall experience"
)
```
"""
self._langfuse_client.create_score(
name=name,
value=cast(str, value),
trace_id=self.trace_id,
score_id=score_id,
data_type=cast(Literal["CATEGORICAL", "TEXT"], data_type),
comment=comment,
config_id=config_id,
timestamp=timestamp,
metadata=metadata,
)
def _set_processed_span_attributes(
self,
*,
span: otel_trace_api.Span,
as_type: Optional[ObservationTypeLiteral] = None,
input: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Any] = None,
) -> None:
"""Set span attributes after processing media and applying masks.
Internal method that processes media in the input, output, and metadata
and applies any configured masking before setting them as span attributes.
Args:
span: The OpenTelemetry span to set attributes on
as_type: The type of span ("span" or "generation")
input: Input data to process and set
output: Output data to process and set
metadata: Metadata to process and set
"""
processed_input = self._process_media_and_apply_mask(
span=span,
data=input,
field="input",
)
processed_output = self._process_media_and_apply_mask(
span=span,
data=output,
field="output",
)
processed_metadata = self._process_media_and_apply_mask(
span=span,
data=metadata,
field="metadata",
)
media_processed_attributes = (
create_generation_attributes(
input=processed_input,
output=processed_output,
metadata=processed_metadata,
)
if as_type == "generation"
else create_span_attributes(
input=processed_input,
output=processed_output,
metadata=processed_metadata,
)
)
span.set_attributes(media_processed_attributes)
def _process_media_and_apply_mask(
self,
*,
data: Optional[Any] = None,
span: otel_trace_api.Span,
field: Union[Literal["input"], Literal["output"], Literal["metadata"]],
) -> Optional[Any]:
"""Process media in an attribute and apply masking.
Internal method that processes any media content in the data and applies
the configured masking function to the result.
Args:
data: The data to process
span: The OpenTelemetry span context
field: Which field this data represents (input, output, or metadata)
Returns:
The processed and masked data
"""
return self._mask_attribute(
data=self._process_media_in_attribute(data=data, field=field)
)
def _mask_attribute(self, *, data: Any) -> Any:
"""Apply the configured mask function to data.
Internal method that applies the client's configured masking function to
the provided data, with error handling and fallback.
Args:
data: The data to mask
Returns:
The masked data, or the original data if no mask is configured
"""
if not self._langfuse_client._mask:
return data
try:
return self._langfuse_client._mask(data=data)
except Exception as e:
langfuse_logger.error(
f"Masking error: Custom mask function threw exception when processing data. Using fallback masking. Error: {e}"
)
return "<fully masked due to failed mask function>"
def _process_media_in_attribute(
self,
*,
data: Optional[Any] = None,
field: Union[Literal["input"], Literal["output"], Literal["metadata"]],
) -> Optional[Any]:
"""Process any media content in the attribute data.
Internal method that identifies and processes any media content in the
provided data, using the client's media manager.
Args:
data: The data to process for media content
span: The OpenTelemetry span context
field: Which field this data represents (input, output, or metadata)
Returns:
The data with any media content processed
"""
if self._langfuse_client._resources is not None:
return (
self._langfuse_client._resources._media_manager._find_and_process_media(
data=data,
field=field,
trace_id=self.trace_id,
observation_id=self.id,
)
)
return data
def _set_otel_span_status_if_error(
self, *, level: Optional[SpanLevel] = None, status_message: Optional[str] = None
) -> None:
"""Set OpenTelemetry span status to ERROR if level is ERROR.
This method sets the underlying OpenTelemetry span status to ERROR when the
Langfuse observation level is set to ERROR, ensuring consistency between
Langfuse and OpenTelemetry error states.
Args:
level: The span level to check
status_message: Optional status message to include as description
"""
if level == "ERROR" and self._otel_span.is_recording():
try:
self._otel_span.set_status(
Status(StatusCode.ERROR, description=status_message)
)
except Exception:
# Silently ignore any errors when setting OTEL status to avoid existing flow disruptions
pass
def update(
self,
*,
name: Optional[str] = None,
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,
**kwargs: Any,
) -> "LangfuseObservationWrapper":
"""Update this observation with new information.
This method updates the observation with new information that becomes available
during execution, such as outputs, metadata, or status changes.
Args:
name: Observation name
input: Updated input data for the operation
output: Output data from the operation
metadata: Additional metadata to associate with the observation
version: Version identifier for the code or component
level: Importance level of the observation (info, warning, error)
status_message: Optional status message for the observation
completion_start_time: When the generation started (for generation types)
model: Model identifier used (for generation types)
model_parameters: Parameters passed to the model (for generation types)
usage_details: Token or other usage statistics (for generation types)
cost_details: Cost breakdown for the operation (for generation types)
prompt: Reference to the prompt used (for generation types)
**kwargs: Additional keyword arguments (ignored)
"""
if not self._otel_span.is_recording():
return self
processed_input = self._process_media_and_apply_mask(
data=input, field="input", span=self._otel_span
)
processed_output = self._process_media_and_apply_mask(
data=output, field="output", span=self._otel_span
)
processed_metadata = self._process_media_and_apply_mask(
data=metadata, field="metadata", span=self._otel_span
)
if name:
self._otel_span.update_name(name)
if self._observation_type in get_observation_types_list(
ObservationTypeGenerationLike
):
attributes = create_generation_attributes(
input=processed_input,
output=processed_output,
metadata=processed_metadata,
version=version,
level=level,
status_message=status_message,
observation_type=cast(
ObservationTypeGenerationLike,
self._observation_type,
),
completion_start_time=completion_start_time,
model=model,
model_parameters=model_parameters,
usage_details=usage_details,
cost_details=cost_details,
prompt=prompt,
)
else:
# For span-like types and events
attributes = create_span_attributes(
input=processed_input,
output=processed_output,
metadata=processed_metadata,
version=version,
level=level,
status_message=status_message,
observation_type=cast(
Optional[Union[ObservationTypeSpanLike, Literal["event"]]],
self._observation_type
if self._observation_type
in get_observation_types_list(ObservationTypeSpanLike)
or self._observation_type == "event"
else None,
),
)
self._otel_span.set_attributes(attributes=attributes)
# Set OTEL span status if level is ERROR
self._set_otel_span_status_if_error(level=level, status_message=status_message)
return self
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["span"],
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": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["generation"],
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": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["agent"],
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,
) -> "LangfuseAgent": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["tool"],
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,
) -> "LangfuseTool": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["chain"],
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,
) -> "LangfuseChain": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["retriever"],
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,
) -> "LangfuseRetriever": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["evaluator"],
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,
) -> "LangfuseEvaluator": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["embedding"],
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,
) -> "LangfuseEmbedding": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["guardrail"],
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,
) -> "LangfuseGuardrail": ...
@overload
def start_observation(
self,
*,
name: str,
as_type: Literal["event"],
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": ...
def start_observation(
self,
*,
name: str,
as_type: ObservationTypeLiteral = "span",
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,
) -> Union[
"LangfuseSpan",
"LangfuseGeneration",
"LangfuseAgent",
"LangfuseTool",
"LangfuseChain",
"LangfuseRetriever",
"LangfuseEvaluator",
"LangfuseEmbedding",
"LangfuseGuardrail",
"LangfuseEvent",
]:
"""Create a new child observation of the specified type.
This is the generic method for creating any type of child observation.
Unlike start_as_current_observation(), this method does not set the new
observation as the current observation in the context.
Args:
name: Name of the observation
as_type: Type of observation to create
input: Input data for the operation
output: Output data from the operation
metadata: Additional metadata to associate with the observation
version: Version identifier for the code or component
level: Importance level of the observation (info, warning, error)
status_message: Optional status message for the observation
completion_start_time: When the model started generating (for generation types)
model: Name/identifier of the AI model used (for generation types)
model_parameters: Parameters used for the model (for generation types)
usage_details: Token usage information (for generation types)
cost_details: Cost information (for generation types)
prompt: Associated prompt template (for generation types)
Returns:
A new observation of the specified type that must be ended with .end()
"""
if as_type == "event":
timestamp = time_ns()
event_span = self._langfuse_client._otel_tracer.start_span(
name=name, start_time=timestamp
)
return cast(
LangfuseEvent,
LangfuseEvent(
otel_span=event_span,
langfuse_client=self._langfuse_client,
input=input,
output=output,
metadata=metadata,
environment=self._environment,
release=self._release,
version=version,
level=level,
status_message=status_message,
).end(end_time=timestamp),
)
observation_class = _OBSERVATION_CLASS_MAP.get(as_type)
if not observation_class:
langfuse_logger.warning(
f"Unknown observation type: {as_type}, falling back to LangfuseSpan"
)
observation_class = LangfuseSpan
with otel_trace_api.use_span(self._otel_span):
new_otel_span = self._langfuse_client._otel_tracer.start_span(name=name)
common_args = {
"otel_span": new_otel_span,
"langfuse_client": self._langfuse_client,
"environment": self._environment,
"release": self._release,
"input": input,
"output": output,
"metadata": metadata,
"version": version,
"level": level,
"status_message": status_message,
}
if as_type in get_observation_types_list(ObservationTypeGenerationLike):
common_args.update(
{
"completion_start_time": completion_start_time,
"model": model,
"model_parameters": model_parameters,
"usage_details": usage_details,
"cost_details": cost_details,
"prompt": prompt,
}
)
return observation_class(**common_args) # type: ignore[no-any-return,return-value,arg-type]
@overload
def start_as_current_observation(
self,
*,
name: str,
as_type: Literal["span"],
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,
) -> _AgnosticContextManager["LangfuseSpan"]: ...
@overload
def start_as_current_observation(
self,
*,
name: str,
as_type: Literal["generation"],
input: Optional[Any] = None,