-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_openai.py
More file actions
2277 lines (1856 loc) · 80.2 KB
/
test_openai.py
File metadata and controls
2277 lines (1856 loc) · 80.2 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 asyncio
import time
import braintrust
import openai
import pytest
from braintrust import logger, wrap_openai
from braintrust.oai import ChatCompletionWrapper
from braintrust.test_helpers import assert_dict_matches, init_test_logger
from braintrust.wrappers.test_utils import assert_metrics_are_valid, run_in_subprocess, verify_autoinstrument_script
from openai import AsyncOpenAI
from openai._types import NOT_GIVEN
from pydantic import BaseModel
TEST_ORG_ID = "test-org-openai-py-tracing"
PROJECT_NAME = "test-project-openai-py-tracing"
TEST_MODEL = "gpt-4o-mini" # cheapest model for tests
TEST_PROMPT = "What's 12 + 12?"
TEST_SYSTEM_PROMPT = "You are a helpful assistant that only responds with numbers."
@pytest.fixture
def memory_logger():
init_test_logger(PROJECT_NAME)
with logger._internal_with_memory_background_logger() as bgl:
yield bgl
def test_tracing_processor_sets_current_span(memory_logger):
"""Ensure that on_trace_start sets the span as current so nested spans work."""
pytest.importorskip("agents", reason="agents package not available")
from braintrust.wrappers.openai import BraintrustTracingProcessor
assert not memory_logger.pop()
processor = BraintrustTracingProcessor()
class DummyTrace:
def __init__(self):
self.trace_id = "test-trace-id"
self.name = "test-trace"
def export(self):
return {"group_id": "group", "metadata": {"foo": "bar"}}
trace = DummyTrace()
with braintrust.start_span(name="parent-span") as parent_span:
assert braintrust.current_span() == parent_span
processor.on_trace_start(trace)
created_span = processor._spans[trace.trace_id]
assert braintrust.current_span() == created_span
processor.on_trace_end(trace)
assert braintrust.current_span() == parent_span
spans = memory_logger.pop()
assert spans
assert any(span.get("span_attributes", {}).get("name") == trace.name for span in spans)
@pytest.mark.vcr
def test_openai_chat_metrics(memory_logger):
assert not memory_logger.pop()
client = openai.OpenAI()
clients = [client, wrap_openai(client)]
for client in clients:
start = time.time()
response = client.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}]
)
end = time.time()
assert response
assert response.choices[0].message.content
assert (
"24" in response.choices[0].message.content or "twenty-four" in response.choices[0].message.content.lower()
)
if not _is_wrapped(client):
assert not memory_logger.pop()
continue
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert TEST_MODEL in span["metadata"]["model"]
assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
@pytest.mark.vcr
def test_openai_responses_metrics(memory_logger):
assert not memory_logger.pop()
# First test with an unwrapped client
unwrapped_client = openai.OpenAI()
unwrapped_response = unwrapped_client.responses.create(
model=TEST_MODEL,
input=TEST_PROMPT,
instructions="Just the number please",
)
assert unwrapped_response
assert unwrapped_response.output
assert len(unwrapped_response.output) > 0
unwrapped_content = unwrapped_response.output[0].content[0].text
# No spans should be generated with unwrapped client
assert not memory_logger.pop()
# Now test with wrapped client
client = wrap_openai(openai.OpenAI())
start = time.time()
response = client.responses.create(
model=TEST_MODEL,
input=TEST_PROMPT,
instructions="Just the number please",
)
end = time.time()
assert response
# Extract content from output field
assert response.output
assert len(response.output) > 0
wrapped_content = response.output[0].content[0].text
# Both should contain a numeric response for the math question
assert "24" in unwrapped_content or "twenty-four" in unwrapped_content.lower()
assert "24" in wrapped_content or "twenty-four" in wrapped_content.lower()
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert 0 <= metrics.get("prompt_cached_tokens", 0)
assert 0 <= metrics.get("completion_reasoning_tokens", 0)
assert TEST_MODEL in span["metadata"]["model"]
assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
assert len(span["output"]) > 0
span_output_text = span["output"][0]["content"][0]["text"]
assert "24" in span_output_text or "twenty-four" in span_output_text.lower()
# Test responses.parse method
class NumberAnswer(BaseModel):
value: int
reasoning: str
# First test with unwrapped client - should work but no spans
parse_response = unwrapped_client.responses.parse(model=TEST_MODEL, input=TEST_PROMPT, text_format=NumberAnswer)
assert parse_response
# Access the structured output via text_format
assert parse_response.output_parsed
assert parse_response.output_parsed.value == 24
assert parse_response.output_parsed.reasoning
# No spans should be generated with unwrapped client
assert not memory_logger.pop()
# Now test with wrapped client - should generate spans
start = time.time()
parse_response = client.responses.parse(model=TEST_MODEL, input=TEST_PROMPT, text_format=NumberAnswer)
end = time.time()
assert parse_response
# Access the structured output via text_format
assert parse_response.output_parsed
assert parse_response.output_parsed.value == 24
assert parse_response.output_parsed.reasoning
# Verify spans are generated
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert 0 <= metrics.get("prompt_cached_tokens", 0)
assert 0 <= metrics.get("completion_reasoning_tokens", 0)
assert TEST_MODEL in span["metadata"]["model"]
assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
assert len(span["output"]) > 0
assert span["output"][0]["content"][0]["parsed"]
assert span["output"][0]["content"][0]["parsed"]["value"] == 24
assert span["output"][0]["content"][0]["parsed"]["reasoning"] == parse_response.output_parsed.reasoning
@pytest.mark.vcr
def test_openai_responses_metadata_preservation(memory_logger):
"""Test that additional metadata fields in responses are preserved."""
assert not memory_logger.pop()
client = wrap_openai(openai.OpenAI())
# Test with responses.create - the response object has various metadata fields
start = time.time()
response = client.responses.create(
model=TEST_MODEL,
input="What is 10 + 10?",
instructions="Respond with just the number",
)
end = time.time()
assert response
assert response.output
# Check that the response has metadata fields like id, created_at, object, etc.
assert hasattr(response, "id")
assert hasattr(response, "created_at")
assert hasattr(response, "object")
assert hasattr(response, "model")
# Verify spans capture metadata
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
# Check that span metadata includes the parameters
assert TEST_MODEL in span["metadata"]["model"] # Model name may include version date
assert span["metadata"]["provider"] == "openai"
assert span["metadata"]["instructions"] == "Respond with just the number"
# Check that response metadata is preserved (non-output, non-usage fields)
# The metadata should be in span["metadata"] after our changes
assert "metadata" in span
if "id" in span.get("metadata", {}):
# Response metadata like id, created, object should be preserved
assert span["metadata"]["id"] == response.id
# Verify metrics are properly extracted
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert "time_to_first_token" in metrics
# Test with responses.parse to ensure metadata is preserved there too
class SimpleAnswer(BaseModel):
value: int
start = time.time()
parse_response = client.responses.parse(
model=TEST_MODEL,
input="What is 15 + 15?",
text_format=SimpleAnswer,
)
end = time.time()
assert parse_response
assert parse_response.output_parsed
assert parse_response.output_parsed.value == 30
# Verify metadata preservation in parse response
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
# Check parameters are in metadata
assert TEST_MODEL in span["metadata"]["model"] # Model name may include version date
assert span["metadata"]["provider"] == "openai"
# Verify the structured output is captured
assert span["output"][0]["content"][0]["parsed"]["value"] == 30
# Check metrics
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
@pytest.mark.vcr
def test_openai_responses_sparse_indices(memory_logger):
"""Test that streaming responses with sparse/out-of-order indices are handled correctly."""
assert not memory_logger.pop()
from braintrust.oai import ResponseWrapper
# Create a mock response with sparse content indices (e.g., indices 0, 2, 5)
# This simulates a streaming response where items arrive out of order or with gaps
class MockResult:
def __init__(
self,
type,
content_index=None,
delta=None,
annotation_index=None,
annotation=None,
output_index=None,
item=None,
):
self.type = type
if content_index is not None:
self.content_index = content_index
if delta is not None:
self.delta = delta
if annotation_index is not None:
self.annotation_index = annotation_index
if annotation is not None:
self.annotation = annotation
if output_index is not None:
self.output_index = output_index
if item is not None:
self.item = item
class MockItem:
def __init__(self, id="test_id", type="message"):
self.id = id
self.type = type
# Test sparse content indices
all_results = [
MockResult("response.output_item.added", item=MockItem()),
MockResult("response.output_text.delta", content_index=0, delta="First", output_index=0),
MockResult("response.output_text.delta", content_index=2, delta="Third", output_index=0), # Gap at index 1
MockResult("response.output_text.delta", content_index=5, delta="Sixth", output_index=0), # Gap at indices 3,4
]
# Process the results
wrapper = ResponseWrapper(None, None)
output = [{}] # Initialize with one output item
result = wrapper._postprocess_streaming_results(all_results)
# Verify the output was built correctly with gaps filled
assert "output" in result
assert len(result["output"]) == 1
content = result["output"][0].get("content", [])
# Should have 6 items (indices 0-5)
assert len(content) >= 6
assert content[0].get("text") == "First"
assert content[1].get("text", "") == "" # Gap should be empty
assert content[2].get("text") == "Third"
assert content[3].get("text", "") == "" # Gap should be empty
assert content[4].get("text", "") == "" # Gap should be empty
assert content[5].get("text") == "Sixth"
# Test sparse annotation indices
all_results_with_annotations = [
MockResult("response.output_item.added", item=MockItem()),
MockResult("response.output_text.delta", content_index=0, delta="Text", output_index=0),
MockResult(
"response.output_text.annotation.added",
content_index=0,
annotation_index=1,
annotation={"text": "Second annotation"},
output_index=0,
),
MockResult(
"response.output_text.annotation.added",
content_index=0,
annotation_index=3,
annotation={"text": "Fourth annotation"},
output_index=0,
),
]
result = wrapper._postprocess_streaming_results(all_results_with_annotations)
# Verify annotations were built correctly with gaps filled
assert "output" in result
content = result["output"][0].get("content", [])
assert len(content) >= 1
annotations = content[0].get("annotations", [])
# Should have 4 items (indices 0-3)
assert len(annotations) >= 4
assert annotations[0] == {} # Gap should be empty dict
assert annotations[1] == {"text": "Second annotation"}
assert annotations[2] == {} # Gap should be empty dict
assert annotations[3] == {"text": "Fourth annotation"}
# No spans should be generated from this unit test
assert not memory_logger.pop()
@pytest.mark.vcr
def test_openai_embeddings(memory_logger):
assert not memory_logger.pop()
client = openai.OpenAI()
response = client.embeddings.create(model="text-embedding-ada-002", input="This is a test")
assert response
assert response.data
assert response.data[0].embedding
assert not memory_logger.pop()
client2 = wrap_openai(openai.OpenAI())
start = time.time()
response2 = client2.embeddings.create(model="text-embedding-ada-002", input="This is a test")
end = time.time()
assert response2
assert response2.data
assert response2.data[0].embedding
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
assert span["metadata"]["model"] == "text-embedding-ada-002"
assert span["metadata"]["provider"] == "openai"
assert "This is a test" in str(span["input"])
@pytest.mark.vcr
def test_openai_chat_streaming_sync(memory_logger):
assert not memory_logger.pop()
client = openai.OpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
start = time.time()
stream = client.chat.completions.create(
model=TEST_MODEL,
messages=[{"role": "user", "content": TEST_PROMPT}],
stream=True,
stream_options={"include_usage": True},
)
chunks = []
for chunk in stream:
chunks.append(chunk)
end = time.time()
# Verify streaming works
assert chunks
assert len(chunks) > 1
# Concatenate content from chunks to verify
content = ""
for chunk in chunks:
if chunk.choices and chunk.choices[0].delta.content:
content += chunk.choices[0].delta.content
# Make sure we got a valid answer in the content
assert "24" in content or "twenty-four" in content.lower()
if not is_wrapped:
assert not memory_logger.pop()
continue
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert TEST_MODEL in span["metadata"]["model"]
# assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
assert "24" in str(span["output"]) or "twenty-four" in str(span["output"]).lower()
@pytest.mark.vcr
def test_openai_chat_with_system_prompt(memory_logger):
assert not memory_logger.pop()
client = openai.OpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
response = client.chat.completions.create(
model=TEST_MODEL,
messages=[{"role": "system", "content": TEST_SYSTEM_PROMPT}, {"role": "user", "content": TEST_PROMPT}],
)
assert response
assert response.choices
assert "24" in response.choices[0].message.content
if not is_wrapped:
assert not memory_logger.pop()
continue
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
inputs = span["input"]
assert len(inputs) == 2
assert inputs[0]["role"] == "system"
assert inputs[0]["content"] == TEST_SYSTEM_PROMPT
assert inputs[1]["role"] == "user"
assert inputs[1]["content"] == TEST_PROMPT
@pytest.mark.vcr
def test_openai_client_comparison(memory_logger):
"""Test that wrapped and unwrapped clients produce the same output."""
assert not memory_logger.pop()
# Get regular and wrapped clients
client = openai.OpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
response = client.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}], temperature=0, seed=42
)
# Both should have data
assert response.choices[0].message.content
if not is_wrapped:
assert not memory_logger.pop()
continue
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
@pytest.mark.vcr
def test_openai_client_error(memory_logger):
assert not memory_logger.pop()
# For the wrapped client only, since we need special error handling
client = wrap_openai(openai.OpenAI())
# Use a non-existent model to force an error
fake_model = "non-existent-model"
try:
client.chat.completions.create(model=fake_model, messages=[{"role": "user", "content": TEST_PROMPT}])
pytest.fail("Expected an exception but none was raised")
except Exception as e:
# We expect an error here
pass
logs = memory_logger.pop()
assert len(logs) == 1
log = logs[0]
assert log["project_id"] == PROJECT_NAME
# It seems the error field may not be present in newer OpenAI versions
# Just check that we got a log entry with the fake model
assert fake_model in str(log)
@pytest.mark.vcr
@pytest.mark.asyncio
async def test_openai_chat_async(memory_logger):
assert not memory_logger.pop()
# First test with an unwrapped async client
client = AsyncOpenAI()
resp = await client.chat.completions.create(model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}])
assert resp
assert resp.choices
assert resp.choices[0].message.content
content = resp.choices[0].message.content
# Verify it contains a correct response
assert "24" in content or "twenty-four" in content.lower()
# No spans should be generated with unwrapped client
assert not memory_logger.pop()
# Now test with wrapped client
client2 = wrap_openai(AsyncOpenAI())
start = time.time()
resp2 = await client2.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}]
)
end = time.time()
assert resp2
assert resp2.choices
assert resp2.choices[0].message.content
content2 = resp2.choices[0].message.content
# Verify the wrapped client also gives correct responses
assert "24" in content2 or "twenty-four" in content2.lower()
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert TEST_MODEL in span["metadata"]["model"]
# assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_responses_async(memory_logger):
assert not memory_logger.pop()
client = AsyncOpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
start = time.time()
resp = await client.responses.create(
model=TEST_MODEL,
input=TEST_PROMPT,
instructions="Just the number please",
)
end = time.time()
assert resp
assert resp.output
assert len(resp.output) > 0
# Extract the text from the output
content = resp.output[0].content[0].text
# Verify response contains correct answer
assert "24" in content or "twenty-four" in content.lower()
if not is_wrapped:
assert not memory_logger.pop()
continue
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert 0 <= metrics.get("prompt_cached_tokens", 0)
assert 0 <= metrics.get("completion_reasoning_tokens", 0)
assert TEST_MODEL in span["metadata"]["model"]
# assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
# Test responses.parse method
class NumberAnswer(BaseModel):
value: int
reasoning: str
for client, is_wrapped in clients:
if not is_wrapped:
# Test unwrapped client first
parse_response = await client.responses.parse(
model=TEST_MODEL, input=TEST_PROMPT, text_format=NumberAnswer
)
assert parse_response
# Access the structured output via text_format
assert parse_response.output_parsed
assert parse_response.output_parsed.value == 24
assert parse_response.output_parsed.reasoning
# No spans should be generated with unwrapped client
assert not memory_logger.pop()
else:
# Test wrapped client
start = time.time()
parse_response = await client.responses.parse(
model=TEST_MODEL, input=TEST_PROMPT, text_format=NumberAnswer
)
end = time.time()
assert parse_response
# Access the structured output via text_format
assert parse_response.output_parsed
assert parse_response.output_parsed.value == 24
assert parse_response.output_parsed.reasoning
# Verify spans were created
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert 0 <= metrics.get("prompt_cached_tokens", 0)
assert 0 <= metrics.get("completion_reasoning_tokens", 0)
assert TEST_MODEL in span["metadata"]["model"]
# assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
assert len(span["output"]) > 0
assert span["output"][0]["content"][0]["parsed"]
assert span["output"][0]["content"][0]["parsed"]["value"] == 24
assert span["output"][0]["content"][0]["parsed"]["reasoning"] == parse_response.output_parsed.reasoning
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_embeddings_async(memory_logger):
assert not memory_logger.pop()
client = AsyncOpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
start = time.time()
resp = await client.embeddings.create(model="text-embedding-ada-002", input="This is a test")
end = time.time()
assert resp
assert resp.data
assert resp.data[0].embedding
if not is_wrapped:
assert not memory_logger.pop()
continue
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
assert span["metadata"]["model"] == "text-embedding-ada-002"
assert span["metadata"]["provider"] == "openai"
assert "This is a test" in str(span["input"])
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_chat_streaming_async(memory_logger):
assert not memory_logger.pop()
client = AsyncOpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
start = time.time()
stream = await client.chat.completions.create(
model=TEST_MODEL,
messages=[{"role": "user", "content": TEST_PROMPT}],
stream=True,
stream_options={"include_usage": True},
)
chunks = []
async for chunk in stream:
chunks.append(chunk)
end = time.time()
assert chunks
assert len(chunks) > 1
# Concatenate content from chunks to verify
content = ""
for chunk in chunks:
if chunk.choices and chunk.choices[0].delta.content:
content += chunk.choices[0].delta.content
# Make sure we got a valid answer in the content
assert "24" in content or "twenty-four" in content.lower()
if not is_wrapped:
assert not memory_logger.pop()
continue
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
assert span
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert span["metadata"]["stream"] == True
assert TEST_MODEL in span["metadata"]["model"]
# assert span["metadata"]["provider"] == "openai"
assert TEST_PROMPT in str(span["input"])
assert "24" in str(span["output"]) or "twenty-four" in str(span["output"]).lower()
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_chat_async_with_system_prompt(memory_logger):
assert not memory_logger.pop()
client = AsyncOpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
response = await client.chat.completions.create(
model=TEST_MODEL,
messages=[{"role": "system", "content": TEST_SYSTEM_PROMPT}, {"role": "user", "content": TEST_PROMPT}],
)
assert response
assert response.choices
assert "24" in response.choices[0].message.content
if not is_wrapped:
assert not memory_logger.pop()
continue
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
inputs = span["input"]
assert len(inputs) == 2
assert inputs[0]["role"] == "system"
assert inputs[0]["content"] == TEST_SYSTEM_PROMPT
assert inputs[1]["role"] == "user"
assert inputs[1]["content"] == TEST_PROMPT
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_client_async_comparison(memory_logger):
"""Test that wrapped and unwrapped async clients produce the same output."""
assert not memory_logger.pop()
# Get regular and wrapped clients
regular_client = AsyncOpenAI()
wrapped_client = wrap_openai(AsyncOpenAI())
# Test with regular client
normal_response = await regular_client.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}], temperature=0, seed=42
)
# No spans should be created for unwrapped client
assert not memory_logger.pop()
# Test with wrapped client
wrapped_response = await wrapped_client.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}], temperature=0, seed=42
)
# Both should have data
assert normal_response.choices[0].message.content
assert wrapped_response.choices[0].message.content
# Verify spans were created with wrapped client
spans = memory_logger.pop()
assert len(spans) == 1
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_client_async_error(memory_logger):
assert not memory_logger.pop()
# For the wrapped client only, since we need special error handling
client = wrap_openai(AsyncOpenAI())
# Use a non-existent model to force an error
fake_model = "non-existent-model"
try:
await client.chat.completions.create(model=fake_model, messages=[{"role": "user", "content": TEST_PROMPT}])
pytest.fail("Expected an exception but none was raised")
except Exception as e:
# We expect an error here
pass
logs = memory_logger.pop()
assert len(logs) == 1
log = logs[0]
assert log["project_id"] == PROJECT_NAME
# It seems the error field may not be present in newer OpenAI versions
# Just check that we got a log entry with the fake model
assert fake_model in str(log)
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_chat_async_context_manager(memory_logger):
"""Test async context manager behavior for chat completions streams."""
assert not memory_logger.pop()
client = AsyncOpenAI()
clients = [(client, False), (wrap_openai(client), True)]
for client, is_wrapped in clients:
start = time.time()
stream = await client.chat.completions.create(
model=TEST_MODEL,
messages=[{"role": "user", "content": TEST_PROMPT}],
stream=True,
stream_options={"include_usage": True},
)
# Test the context manager behavior
chunks = []
async with stream as s:
async for chunk in s:
chunks.append(chunk)
end = time.time()
# Verify we got chunks from the stream
assert chunks
assert len(chunks) > 1
# Concatenate content from chunks to verify
content = ""
for chunk in chunks:
if chunk.choices and chunk.choices[0].delta.content:
content += chunk.choices[0].delta.content
# Make sure we got a valid answer in the content
assert "24" in content or "twenty-four" in content.lower()
if not is_wrapped:
assert not memory_logger.pop()
continue
# Check metrics
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
metrics = span["metrics"]
assert_metrics_are_valid(metrics, start, end)
assert span["metadata"]["stream"] == True
assert "24" in str(span["output"]) or "twenty-four" in str(span["output"]).lower()
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_streaming_with_break(memory_logger):
"""Test breaking out of the streaming loop early."""
assert not memory_logger.pop()
# Only test with wrapped client
client = wrap_openai(AsyncOpenAI())
start = time.time()
stream = await client.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}], stream=True
)
# Only process the first few chunks
counter = 0
async for chunk in stream:
counter += 1
if counter >= 2:
break
end = time.time()
# We should still get valid metrics even with early break
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
metrics = span["metrics"]
assert metrics["time_to_first_token"] >= 0
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_chat_error_in_async_context(memory_logger):
"""Test error handling inside the async context manager."""
assert not memory_logger.pop()
# We only test the wrapped client for this test since we need to check span error handling
client = wrap_openai(AsyncOpenAI())
stream = await client.chat.completions.create(
model=TEST_MODEL, messages=[{"role": "user", "content": TEST_PROMPT}], stream=True
)
# Simulate an error during streaming
try:
async with stream as s:
counter = 0
async for chunk in s:
counter += 1
if counter >= 2:
raise ValueError("Intentional test error")
pytest.fail("Expected an exception but none was raised")
except ValueError as e:
assert "Intentional test error" in str(e)
# We should still get valid metrics even with error
spans = memory_logger.pop()
assert len(spans) == 1
span = spans[0]
# The error field might not be present in newer versions
# Just check that we got a span with time metrics
assert span["metrics"]["time_to_first_token"] >= 0
@pytest.mark.asyncio
@pytest.mark.vcr
async def test_openai_response_streaming_async(memory_logger):
"""Test the newer responses API with streaming."""
assert not memory_logger.pop()
client = openai.AsyncOpenAI()
clients = [client, wrap_openai(client)]
for client in clients:
start = time.time()
stream = await client.responses.create(model=TEST_MODEL, input="What's 12 + 12?", stream=True)