-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathtest_otel.py
More file actions
3454 lines (2816 loc) · 134 KB
/
test_otel.py
File metadata and controls
3454 lines (2816 loc) · 134 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
import json
from datetime import datetime
from hashlib import sha256
from typing import List, Sequence
import pytest
from opentelemetry import trace as trace_api
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import (
SimpleSpanProcessor,
SpanExporter,
SpanExportResult,
)
from opentelemetry.sdk.trace.id_generator import RandomIdGenerator
from langfuse._client.attributes import LangfuseOtelSpanAttributes
from langfuse._client.client import Langfuse
from langfuse._client.resource_manager import LangfuseResourceManager
from langfuse.media import LangfuseMedia
class InMemorySpanExporter(SpanExporter):
"""Simple in-memory exporter to collect spans for testing."""
def __init__(self):
self._finished_spans = []
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
self._finished_spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self):
self._stopped = True
def get_finished_spans(self) -> List[ReadableSpan]:
return self._finished_spans
def clear(self):
self._finished_spans.clear()
class TestOTelBase:
"""Base class for OTEL tests with common fixtures and helper methods."""
# ------ Common Fixtures ------
@pytest.fixture(scope="function", autouse=True)
def cleanup_otel(self):
"""Reset OpenTelemetry state between tests."""
original_provider = trace_api.get_tracer_provider()
yield
trace_api.set_tracer_provider(original_provider)
LangfuseResourceManager.reset()
@pytest.fixture
def memory_exporter(self):
"""Create an in-memory span exporter for testing."""
exporter = InMemorySpanExporter()
yield exporter
exporter.shutdown()
@pytest.fixture
def tracer_provider(self, memory_exporter):
"""Create a tracer provider with our memory exporter."""
resource = Resource.create({"service.name": "langfuse-test"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(memory_exporter)
provider.add_span_processor(processor)
trace_api.set_tracer_provider(provider)
return provider
@pytest.fixture
def mock_processor_init(self, monkeypatch, memory_exporter):
"""Mock the LangfuseSpanProcessor initialization to avoid HTTP traffic."""
def mock_init(self, **kwargs):
from opentelemetry.sdk.trace.export import BatchSpanProcessor
self.public_key = kwargs.get("public_key", "test-key")
blocked_scopes = kwargs.get("blocked_instrumentation_scopes")
self.blocked_instrumentation_scopes = (
blocked_scopes if blocked_scopes is not None else []
)
BatchSpanProcessor.__init__(
self,
span_exporter=memory_exporter,
max_export_batch_size=512,
schedule_delay_millis=5000,
)
monkeypatch.setattr(
"langfuse._client.span_processor.LangfuseSpanProcessor.__init__",
mock_init,
)
@pytest.fixture
def langfuse_client(self, monkeypatch, tracer_provider, mock_processor_init):
"""Create a mocked Langfuse client for testing."""
# Set environment variables
monkeypatch.setenv("LANGFUSE_PUBLIC_KEY", "test-public-key")
monkeypatch.setenv("LANGFUSE_SECRET_KEY", "test-secret-key")
# Create test client
client = Langfuse(
public_key="test-public-key",
secret_key="test-secret-key",
base_url="http://test-host",
tracing_enabled=True,
)
# Configure client for testing
client._otel_tracer = tracer_provider.get_tracer("langfuse-test")
yield client
@pytest.fixture
def configurable_langfuse_client(
self, monkeypatch, tracer_provider, mock_processor_init
):
"""Create a Langfuse client fixture that allows configuration parameters."""
def _create_client(**kwargs):
# Set environment variables
monkeypatch.setenv("LANGFUSE_PUBLIC_KEY", "test-public-key")
monkeypatch.setenv("LANGFUSE_SECRET_KEY", "test-secret-key")
# Create client with custom parameters
client = Langfuse(
public_key="test-public-key",
secret_key="test-secret-key",
base_url="http://test-host",
tracing_enabled=True,
**kwargs,
)
# Configure client
client._otel_tracer = tracer_provider.get_tracer("langfuse-test")
return client
return _create_client
# ------ Test Metadata Fixtures ------
@pytest.fixture
def simple_metadata(self):
"""Create simple metadata for testing."""
return {"key1": "value1", "key2": 123, "key3": True}
@pytest.fixture
def nested_metadata(self):
"""Create nested metadata structure for testing."""
return {
"config": {
"model": "gpt-4",
"parameters": {"temperature": 0.7, "max_tokens": 500},
},
"telemetry": {"client_info": {"version": "1.0.0", "platform": "python"}},
}
@pytest.fixture
def complex_metadata(self):
"""Create complex metadata with various types for testing."""
return {
"string_value": "test string",
"int_value": 42,
"float_value": 3.14159,
"bool_value": True,
"null_value": None,
"list_value": [1, 2, 3, "four", 5.0],
"nested_dict": {
"key1": "value1",
"key2": 123,
"nested_list": ["a", "b", "c"],
},
"datetime": datetime.now(),
"uuid": "550e8400-e29b-41d4-a716-446655440000",
}
# ------ Helper Methods ------
def get_span_data(self, span: ReadableSpan) -> dict:
"""Extract important data from a span for testing."""
return {
"name": span.name,
"attributes": dict(span.attributes) if span.attributes else {},
"span_id": format(span.context.span_id, "016x"),
"trace_id": format(span.context.trace_id, "032x"),
"parent_span_id": format(span.parent.span_id, "016x")
if span.parent
else None,
}
def get_spans_by_name(self, memory_exporter, name: str) -> List[dict]:
"""Get all spans with a specific name."""
spans = memory_exporter.get_finished_spans()
return [self.get_span_data(span) for span in spans if span.name == name]
def verify_span_attribute(
self, span_data: dict, attribute_key: str, expected_value=None
):
"""Verify that a span has a specific attribute with an optional expected value."""
attributes = span_data["attributes"]
assert attribute_key in attributes, (
f"Attribute {attribute_key} not found in span"
)
if expected_value is not None:
assert attributes[attribute_key] == expected_value, (
f"Expected {attribute_key} to be {expected_value}, got {attributes[attribute_key]}"
)
return attributes[attribute_key]
def verify_json_attribute(
self, span_data: dict, attribute_key: str, expected_dict=None
):
"""Verify that a span has a JSON attribute and optionally check its parsed value."""
json_string = self.verify_span_attribute(span_data, attribute_key)
parsed_json = json.loads(json_string)
if expected_dict is not None:
assert parsed_json == expected_dict, (
f"Expected JSON {attribute_key} to be {expected_dict}, got {parsed_json}"
)
return parsed_json
def assert_parent_child_relationship(self, parent_span: dict, child_span: dict):
"""Verify parent-child relationship between two spans."""
assert child_span["parent_span_id"] == parent_span["span_id"], (
f"Child span {child_span['name']} should have parent {parent_span['name']}"
)
assert child_span["trace_id"] == parent_span["trace_id"], (
f"Child span {child_span['name']} should have same trace ID as parent {parent_span['name']}"
)
class TestBasicSpans(TestOTelBase):
"""Tests for basic span operations and attributes."""
def test_basic_span_creation(self, langfuse_client, memory_exporter):
"""Test that a basic span can be created with attributes."""
# Create a span and end it
span = langfuse_client.start_span(name="test-span", input={"test": "value"})
span.end()
# Get spans with our name
spans = self.get_spans_by_name(memory_exporter, "test-span")
# Verify we created exactly one span
assert len(spans) == 1, (
f"Expected 1 span named 'test-span', but found {len(spans)}"
)
span_data = spans[0]
# Verify the span attributes
assert span_data["name"] == "test-span"
self.verify_span_attribute(
span_data, LangfuseOtelSpanAttributes.OBSERVATION_TYPE, "span"
)
# Verify the span IDs match
assert span.id == span_data["span_id"]
assert span.trace_id == span_data["trace_id"]
def test_span_hierarchy(self, langfuse_client, memory_exporter):
"""Test creating nested spans and verify their parent-child relationships."""
# Create parent span
with langfuse_client.start_as_current_span(name="parent-span") as parent_span:
# Create a child span
child_span = parent_span.start_span(name="child-span")
child_span.end()
# Create another child span using context manager
with parent_span.start_as_current_span(name="child-span-2") as child_span_2:
# Create a grandchild span
grandchild = child_span_2.start_span(name="grandchild-span")
grandchild.end()
# Get all spans
spans = [
self.get_span_data(span) for span in memory_exporter.get_finished_spans()
]
# Find spans by name
parent = next((s for s in spans if s["name"] == "parent-span"), None)
child1 = next((s for s in spans if s["name"] == "child-span"), None)
child2 = next((s for s in spans if s["name"] == "child-span-2"), None)
grandchild = next((s for s in spans if s["name"] == "grandchild-span"), None)
# Verify all spans exist
assert parent is not None, "Parent span not found"
assert child1 is not None, "First child span not found"
assert child2 is not None, "Second child span not found"
assert grandchild is not None, "Grandchild span not found"
# Verify parent-child relationships
self.assert_parent_child_relationship(parent, child1)
self.assert_parent_child_relationship(parent, child2)
self.assert_parent_child_relationship(child2, grandchild)
# All spans should have the same trace ID
assert len(set(s["trace_id"] for s in spans)) == 1
def test_update_current_span_name(self, langfuse_client, memory_exporter):
"""Test updating current span name via update_current_span method."""
# Create a span using context manager
with langfuse_client.start_as_current_span(name="original-current-span"):
# Update the current span name
langfuse_client.update_current_span(name="updated-current-span")
# Verify the span name was updated
spans = self.get_spans_by_name(memory_exporter, "updated-current-span")
assert len(spans) == 1, "Expected one span with updated name"
# Also verify no spans exist with the original name
original_spans = self.get_spans_by_name(
memory_exporter, "original-current-span"
)
assert len(original_spans) == 0, "Expected no spans with original name"
def test_span_attributes(self, langfuse_client, memory_exporter):
"""Test that span attributes are correctly set and updated."""
# Create a span with attributes
span = langfuse_client.start_span(
name="attribute-span",
input={"prompt": "Test prompt"},
output={"response": "Test response"},
metadata={"session": "test-session"},
level="INFO",
status_message="Test status",
)
# Update span with new attributes
span.update(output={"response": "Updated response"}, metadata={"updated": True})
span.end()
# Get the span data
spans = self.get_spans_by_name(memory_exporter, "attribute-span")
assert len(spans) == 1, "Expected one attribute-span"
span_data = spans[0]
# Verify attributes are set
attributes = span_data["attributes"]
assert LangfuseOtelSpanAttributes.OBSERVATION_INPUT in attributes
assert LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT in attributes
assert (
f"{LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.session" in attributes
)
# Parse JSON attributes
input_data = json.loads(
attributes[LangfuseOtelSpanAttributes.OBSERVATION_INPUT]
)
output_data = json.loads(
attributes[LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]
)
metadata_data = attributes[
f"{LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.session"
]
# Verify attribute values
assert input_data == {"prompt": "Test prompt"}
assert output_data == {"response": "Updated response"}
assert metadata_data == "test-session"
assert attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] == "INFO"
assert (
attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]
== "Test status"
)
def test_span_name_update(self, langfuse_client, memory_exporter):
"""Test updating span name via update method."""
# Create a span with initial name
span = langfuse_client.start_span(name="original-span-name")
# Update the span name
span.update(name="updated-span-name")
span.end()
# Verify the span name was updated
spans = self.get_spans_by_name(memory_exporter, "updated-span-name")
assert len(spans) == 1, "Expected one span with updated name"
# Also verify no spans exist with the original name
original_spans = self.get_spans_by_name(memory_exporter, "original-span-name")
assert len(original_spans) == 0, "Expected no spans with original name"
def test_generation_span(self, langfuse_client, memory_exporter):
"""Test creating a generation span with model-specific attributes."""
# Create a generation
generation = langfuse_client.start_generation(
name="test-generation",
model="gpt-4",
model_parameters={"temperature": 0.7, "max_tokens": 100},
input={"prompt": "Hello, AI"},
output={"response": "Hello, human"},
usage_details={"input": 10, "output": 5, "total": 15},
)
generation.end()
# Get the span data
spans = self.get_spans_by_name(memory_exporter, "test-generation")
assert len(spans) == 1, "Expected one test-generation span"
gen_data = spans[0]
# Verify generation-specific attributes
attributes = gen_data["attributes"]
assert attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] == "generation"
assert attributes[LangfuseOtelSpanAttributes.OBSERVATION_MODEL] == "gpt-4"
# Parse complex attributes
model_params = json.loads(
attributes[LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]
)
assert model_params == {"temperature": 0.7, "max_tokens": 100}
usage = json.loads(
attributes[LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS]
)
assert usage == {"input": 10, "output": 5, "total": 15}
def test_generation_name_update(self, langfuse_client, memory_exporter):
"""Test updating generation name via update method."""
# Create a generation with initial name
generation = langfuse_client.start_generation(
name="original-generation-name", model="gpt-4"
)
# Update the generation name
generation.update(name="updated-generation-name")
generation.end()
# Verify the generation name was updated
spans = self.get_spans_by_name(memory_exporter, "updated-generation-name")
assert len(spans) == 1, "Expected one generation with updated name"
# Also verify no spans exist with the original name
original_spans = self.get_spans_by_name(
memory_exporter, "original-generation-name"
)
assert len(original_spans) == 0, "Expected no generations with original name"
def test_trace_update(self, langfuse_client, memory_exporter):
"""Test updating trace level attributes."""
# Create a span and update trace attributes
with langfuse_client.start_as_current_span(name="trace-span") as span:
span.update_trace(
name="updated-trace-name",
user_id="test-user",
session_id="test-session",
tags=["tag1", "tag2"],
input={"trace-input": "value"},
metadata={"trace-meta": "data"},
)
# Get the span data
spans = self.get_spans_by_name(memory_exporter, "trace-span")
assert len(spans) == 1, "Expected one trace-span"
span_data = spans[0]
# Verify trace attributes were set
attributes = span_data["attributes"]
assert attributes[LangfuseOtelSpanAttributes.TRACE_NAME] == "updated-trace-name"
assert attributes[LangfuseOtelSpanAttributes.TRACE_USER_ID] == "test-user"
assert attributes[LangfuseOtelSpanAttributes.TRACE_SESSION_ID] == "test-session"
# Handle different serialization formats
if isinstance(attributes[LangfuseOtelSpanAttributes.TRACE_TAGS], str):
tags = json.loads(attributes[LangfuseOtelSpanAttributes.TRACE_TAGS])
else:
tags = list(attributes[LangfuseOtelSpanAttributes.TRACE_TAGS])
input_data = json.loads(attributes[LangfuseOtelSpanAttributes.TRACE_INPUT])
metadata = attributes[f"{LangfuseOtelSpanAttributes.TRACE_METADATA}.trace-meta"]
# Check attribute values
assert sorted(tags) == sorted(["tag1", "tag2"])
assert input_data == {"trace-input": "value"}
assert metadata == "data"
def test_complex_scenario(self, langfuse_client, memory_exporter):
"""Test a more complex scenario with multiple operations and nesting."""
# Create a trace with a main span
with langfuse_client.start_as_current_span(name="main-flow") as main_span:
# Add trace information
main_span.update_trace(
name="complex-test",
user_id="complex-user",
session_id="complex-session",
)
# Add a processing span
with main_span.start_as_current_span(name="processing") as processing:
processing.update(metadata={"step": "processing"})
# Add an LLM generation
with main_span.start_as_current_generation(
name="llm-call",
model="gpt-3.5-turbo",
input={"prompt": "Summarize this text"},
metadata={"service": "OpenAI"},
) as generation:
# Update the generation with results
generation.update(
output={"text": "This is a summary"},
usage_details={"input": 20, "output": 5, "total": 25},
)
# Final processing step
with main_span.start_as_current_span(name="post-processing") as post_proc:
post_proc.update(metadata={"step": "post-processing"})
# Get all spans
spans = [
self.get_span_data(span) for span in memory_exporter.get_finished_spans()
]
# Find each span by name
main = next((s for s in spans if s["name"] == "main-flow"), None)
proc = next((s for s in spans if s["name"] == "processing"), None)
llm = next((s for s in spans if s["name"] == "llm-call"), None)
post = next((s for s in spans if s["name"] == "post-processing"), None)
# Verify all spans exist
assert main is not None, "Main span not found"
assert proc is not None, "Processing span not found"
assert llm is not None, "LLM span not found"
assert post is not None, "Post-processing span not found"
# Verify parent-child relationships
self.assert_parent_child_relationship(main, proc)
self.assert_parent_child_relationship(main, llm)
self.assert_parent_child_relationship(main, post)
# Verify all spans have the same trace ID
assert len(set(s["trace_id"] for s in spans)) == 1
# Check specific attributes
assert (
main["attributes"][LangfuseOtelSpanAttributes.TRACE_NAME] == "complex-test"
)
assert (
llm["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_TYPE]
== "generation"
)
# Parse metadata
proc_metadata = proc["attributes"][
f"{LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.step"
]
assert proc_metadata == "processing"
# Parse input/output JSON
llm_input = json.loads(
llm["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_INPUT]
)
llm_output = json.loads(
llm["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]
)
assert llm_input == {"prompt": "Summarize this text"}
assert llm_output == {"text": "This is a summary"}
def test_update_current_generation_name(self, langfuse_client, memory_exporter):
"""Test updating current generation name via update_current_generation method."""
# Create a generation using context manager
with langfuse_client.start_as_current_generation(
name="original-current-generation", model="gpt-4"
):
# Update the current generation name
langfuse_client.update_current_generation(name="updated-current-generation")
# Verify the generation name was updated
spans = self.get_spans_by_name(memory_exporter, "updated-current-generation")
assert len(spans) == 1, "Expected one generation with updated name"
# Also verify no spans exist with the original name
original_spans = self.get_spans_by_name(
memory_exporter, "original-current-generation"
)
assert len(original_spans) == 0, "Expected no generations with original name"
def test_start_as_current_observation_types(self, langfuse_client, memory_exporter):
"""Test creating different observation types using start_as_current_observation."""
# Test each observation type from ObservationTypeLiteralNoEvent
observation_types = [
"span",
"generation",
"agent",
"tool",
"chain",
"retriever",
"evaluator",
"embedding",
"guardrail",
]
for obs_type in observation_types:
with langfuse_client.start_as_current_observation(
name=f"test-{obs_type}", as_type=obs_type
) as obs:
obs.update_trace(name=f"trace-{obs_type}")
spans = [
self.get_span_data(span) for span in memory_exporter.get_finished_spans()
]
# Find spans by name and verify their observation types
for obs_type in observation_types:
expected_name = f"test-{obs_type}"
matching_spans = [span for span in spans if span["name"] == expected_name]
assert len(matching_spans) == 1, (
f"Expected one span with name {expected_name}"
)
span_data = matching_spans[0]
expected_otel_type = obs_type # OTEL attributes use lowercase
actual_type = span_data["attributes"].get(
LangfuseOtelSpanAttributes.OBSERVATION_TYPE
)
assert actual_type == expected_otel_type, (
f"Expected observation type {expected_otel_type}, got {actual_type}"
)
def test_start_observation(self, langfuse_client, memory_exporter):
"""Test creating different observation types using start_observation."""
from langfuse._client.constants import (
ObservationTypeGenerationLike,
ObservationTypeLiteral,
get_observation_types_list,
)
# Test each observation type defined in constants - this ensures we test all supported types
observation_types = get_observation_types_list(ObservationTypeLiteral)
# Create a main span to use for child creation
with langfuse_client.start_as_current_span(
name="factory-test-parent"
) as parent_span:
created_observations = []
for obs_type in observation_types:
if obs_type in get_observation_types_list(
ObservationTypeGenerationLike
):
# Generation-like types with extra parameters
obs = parent_span.start_observation(
name=f"factory-{obs_type}",
as_type=obs_type,
input={"test": f"{obs_type}_input"},
model="test-model",
model_parameters={"temperature": 0.7},
usage_details={"input": 10, "output": 20},
)
if obs_type != "event": # Events are auto-ended
obs.end()
created_observations.append((obs_type, obs))
elif obs_type == "event":
# Test event creation through start_observation (should be auto-ended)
obs = parent_span.start_observation(
name=f"factory-{obs_type}",
as_type=obs_type,
input={"test": f"{obs_type}_input"},
)
created_observations.append((obs_type, obs))
else:
# Span-like types (span, guardrail)
obs = parent_span.start_observation(
name=f"factory-{obs_type}",
as_type=obs_type,
input={"test": f"{obs_type}_input"},
)
obs.end()
created_observations.append((obs_type, obs))
spans = [
self.get_span_data(span) for span in memory_exporter.get_finished_spans()
]
# Verify factory pattern created correct observation types
for obs_type in observation_types:
expected_name = f"factory-{obs_type}"
matching_spans = [span for span in spans if span["name"] == expected_name]
assert len(matching_spans) == 1, (
f"Expected one span with name {expected_name}, found {len(matching_spans)}"
)
span_data = matching_spans[0]
actual_type = span_data["attributes"].get(
LangfuseOtelSpanAttributes.OBSERVATION_TYPE
)
assert actual_type == obs_type, (
f"Factory pattern failed: Expected observation type {obs_type}, got {actual_type}"
)
# Ensure returned objects are of correct types
for obs_type, obs_instance in created_observations:
if obs_type == "span":
from langfuse._client.span import LangfuseSpan
assert isinstance(obs_instance, LangfuseSpan), (
f"Expected LangfuseSpan, got {type(obs_instance)}"
)
elif obs_type == "generation":
from langfuse._client.span import LangfuseGeneration
assert isinstance(obs_instance, LangfuseGeneration), (
f"Expected LangfuseGeneration, got {type(obs_instance)}"
)
elif obs_type == "agent":
from langfuse._client.span import LangfuseAgent
assert isinstance(obs_instance, LangfuseAgent), (
f"Expected LangfuseAgent, got {type(obs_instance)}"
)
elif obs_type == "tool":
from langfuse._client.span import LangfuseTool
assert isinstance(obs_instance, LangfuseTool), (
f"Expected LangfuseTool, got {type(obs_instance)}"
)
elif obs_type == "chain":
from langfuse._client.span import LangfuseChain
assert isinstance(obs_instance, LangfuseChain), (
f"Expected LangfuseChain, got {type(obs_instance)}"
)
elif obs_type == "retriever":
from langfuse._client.span import LangfuseRetriever
assert isinstance(obs_instance, LangfuseRetriever), (
f"Expected LangfuseRetriever, got {type(obs_instance)}"
)
elif obs_type == "evaluator":
from langfuse._client.span import LangfuseEvaluator
assert isinstance(obs_instance, LangfuseEvaluator), (
f"Expected LangfuseEvaluator, got {type(obs_instance)}"
)
elif obs_type == "embedding":
from langfuse._client.span import LangfuseEmbedding
assert isinstance(obs_instance, LangfuseEmbedding), (
f"Expected LangfuseEmbedding, got {type(obs_instance)}"
)
elif obs_type == "guardrail":
from langfuse._client.span import LangfuseGuardrail
assert isinstance(obs_instance, LangfuseGuardrail), (
f"Expected LangfuseGuardrail, got {type(obs_instance)}"
)
elif obs_type == "event":
from langfuse._client.span import LangfuseEvent
assert isinstance(obs_instance, LangfuseEvent), (
f"Expected LangfuseEvent, got {type(obs_instance)}"
)
def test_custom_trace_id(self, langfuse_client, memory_exporter):
"""Test setting a custom trace ID."""
# Create a custom trace ID
custom_trace_id = "abcdef1234567890abcdef1234567890"
# Create a span with this custom trace ID using trace_context
trace_context = {"trace_id": custom_trace_id}
span = langfuse_client.start_span(
name="custom-trace-span",
trace_context=trace_context,
input={"test": "value"},
)
span.end()
# Get spans and verify the trace ID matches
spans = self.get_spans_by_name(memory_exporter, "custom-trace-span")
assert len(spans) == 1, "Expected one span"
span_data = spans[0]
assert span_data["trace_id"] == custom_trace_id, (
"Trace ID doesn't match custom ID"
)
assert span_data["attributes"][LangfuseOtelSpanAttributes.AS_ROOT] is True
# Test additional spans with the same trace context
child_span = langfuse_client.start_span(
name="child-span", trace_context=trace_context, input={"child": "data"}
)
child_span.end()
# Verify child span uses the same trace ID
child_spans = self.get_spans_by_name(memory_exporter, "child-span")
assert len(child_spans) == 1, "Expected one child span"
assert child_spans[0]["trace_id"] == custom_trace_id, (
"Child span has wrong trace ID"
)
def test_custom_parent_span_id(self, langfuse_client, memory_exporter):
"""Test setting a custom parent span ID."""
# Create a trace and get its ID
trace_id = "abcdef1234567890abcdef1234567890"
parent_span_id = "fedcba0987654321"
# Create a context with trace ID and parent span ID
trace_context = {"trace_id": trace_id, "parent_span_id": parent_span_id}
# Create a span with this context
span = langfuse_client.start_span(
name="custom-parent-span", trace_context=trace_context
)
span.end()
# Verify the span is created with the right parent
spans = self.get_spans_by_name(memory_exporter, "custom-parent-span")
assert len(spans) == 1, "Expected one span"
assert spans[0]["trace_id"] == trace_id
assert spans[0]["attributes"][LangfuseOtelSpanAttributes.AS_ROOT] is True
def test_multiple_generations_in_trace(self, langfuse_client, memory_exporter):
"""Test creating multiple generation spans within the same trace."""
# Create a trace with multiple generation spans
with langfuse_client.start_as_current_span(name="multi-gen-flow") as main_span:
# First generation
gen1 = main_span.start_generation(
name="generation-1",
model="gpt-3.5-turbo",
input={"prompt": "First prompt"},
output={"text": "First response"},
model_parameters={"temperature": 0.7},
usage_details={"input": 10, "output": 20, "total": 30},
)
gen1.end()
# Second generation with different model
gen2 = main_span.start_generation(
name="generation-2",
model="gpt-4",
input={"prompt": "Second prompt"},
output={"text": "Second response"},
model_parameters={"temperature": 0.5},
usage_details={"input": 15, "output": 25, "total": 40},
)
gen2.end()
# Get all spans
spans = [
self.get_span_data(span) for span in memory_exporter.get_finished_spans()
]
# Find main span and generations
main = next((s for s in spans if s["name"] == "multi-gen-flow"), None)
gen1_data = next((s for s in spans if s["name"] == "generation-1"), None)
gen2_data = next((s for s in spans if s["name"] == "generation-2"), None)
# Verify all spans exist
assert main is not None, "Main span not found"
assert gen1_data is not None, "First generation span not found"
assert gen2_data is not None, "Second generation span not found"
# Verify parent-child relationships
self.assert_parent_child_relationship(main, gen1_data)
self.assert_parent_child_relationship(main, gen2_data)
# Verify all spans have the same trace ID
assert len(set(s["trace_id"] for s in spans)) == 1
# Verify generation-specific attributes are correct
assert (
gen1_data["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_TYPE]
== "generation"
)
assert (
gen1_data["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_MODEL]
== "gpt-3.5-turbo"
)
assert (
gen2_data["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_TYPE]
== "generation"
)
assert (
gen2_data["attributes"][LangfuseOtelSpanAttributes.OBSERVATION_MODEL]
== "gpt-4"
)
# Parse usage details
gen1_usage = json.loads(
gen1_data["attributes"][
LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS
]
)
gen2_usage = json.loads(
gen2_data["attributes"][
LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS
]
)
assert gen1_usage == {"input": 10, "output": 20, "total": 30}
assert gen2_usage == {"input": 15, "output": 25, "total": 40}
def test_error_handling(self, langfuse_client, memory_exporter):
"""Test error handling in span operations."""
# Create a span that will have an error
span = langfuse_client.start_span(name="error-span")
# Set an error status on the span
import traceback
from opentelemetry.trace.status import Status, StatusCode
try:
# Deliberately raise an exception
raise ValueError("Test error message")
except Exception as e:
# Get the exception details
stack_trace = traceback.format_exc()
# Record the error on the span
span._otel_span.set_status(Status(StatusCode.ERROR))
span._otel_span.record_exception(e, attributes={"stack_trace": stack_trace})
span.update(level="ERROR", status_message=str(e))
# End the span with error status
span.end()
# Verify the span contains error information
spans = self.get_spans_by_name(memory_exporter, "error-span")
assert len(spans) == 1, "Expected one error span"
span_data = spans[0]
attributes = span_data["attributes"]
# Verify error attributes were set correctly
assert attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] == "ERROR"
assert (
attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]
== "Test error message"
)
def test_error_level_in_span_creation(self, langfuse_client, memory_exporter):
"""Test that OTEL span status is set to ERROR when creating spans with level='ERROR'."""
# Create a span with level="ERROR" at creation time
span = langfuse_client.start_span(
name="create-error-span",
level="ERROR",
status_message="Initial error state",
)
span.end()
# Get the raw OTEL spans to check the status
raw_spans = [
s
for s in memory_exporter.get_finished_spans()
if s.name == "create-error-span"
]
assert len(raw_spans) == 1, "Expected one span"
raw_span = raw_spans[0]
# Verify OTEL span status was set to ERROR
from opentelemetry.trace.status import StatusCode
assert raw_span.status.status_code == StatusCode.ERROR
assert raw_span.status.description == "Initial error state"
# Also verify Langfuse attributes
spans = self.get_spans_by_name(memory_exporter, "create-error-span")
span_data = spans[0]
attributes = span_data["attributes"]
assert attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] == "ERROR"
assert (
attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]
== "Initial error state"
)
def test_error_level_in_span_update(self, langfuse_client, memory_exporter):
"""Test that OTEL span status is set to ERROR when updating spans to level='ERROR'."""
# Create a normal span
span = langfuse_client.start_span(name="update-error-span", level="INFO")
# Update it to ERROR level
span.update(level="ERROR", status_message="Updated to error state")
span.end()
# Get the raw OTEL spans to check the status
raw_spans = [
s
for s in memory_exporter.get_finished_spans()
if s.name == "update-error-span"
]
assert len(raw_spans) == 1, "Expected one span"
raw_span = raw_spans[0]
# Verify OTEL span status was set to ERROR