-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpydantic_ai.py
More file actions
1476 lines (1133 loc) · 53.3 KB
/
pydantic_ai.py
File metadata and controls
1476 lines (1133 loc) · 53.3 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 contextvars
import logging
import sys
import time
from contextlib import AbstractAsyncContextManager
from typing import Any
from braintrust.bt_json import bt_safe_deep_copy
from braintrust.logger import NOOP_SPAN, Attachment, current_logger, current_span, init_logger, start_span
from braintrust.span_types import SpanTypeAttribute
from wrapt import wrap_function_wrapper
logger = logging.getLogger(__name__)
__all__ = ["setup_pydantic_ai"]
def setup_pydantic_ai(
api_key: str | None = None,
project_id: str | None = None,
project_name: str | None = None,
) -> bool:
"""
Setup Braintrust integration with Pydantic AI. Will automatically patch Pydantic AI Agents and direct API functions for automatic tracing.
Args:
api_key (Optional[str]): Braintrust API key.
project_id (Optional[str]): Braintrust project ID.
project_name (Optional[str]): Braintrust project name.
Returns:
bool: True if setup was successful, False otherwise.
"""
span = current_span()
if span == NOOP_SPAN and current_logger() is None:
init_logger(project=project_name, api_key=api_key, project_id=project_id)
try:
import pydantic_ai.direct as direct_module
from pydantic_ai import Agent
Agent = wrap_agent(Agent)
wrap_function_wrapper(direct_module, "model_request", _create_direct_model_request_wrapper())
wrap_function_wrapper(direct_module, "model_request_sync", _create_direct_model_request_sync_wrapper())
wrap_function_wrapper(direct_module, "model_request_stream", _create_direct_model_request_stream_wrapper())
wrap_function_wrapper(
direct_module, "model_request_stream_sync", _create_direct_model_request_stream_sync_wrapper()
)
wrap_model_classes()
# Patch StreamedResponseSync to propagate context to background threads
try:
if hasattr(direct_module, "StreamedResponseSync"):
wrap_function_wrapper(
direct_module.StreamedResponseSync, "_start_producer", _create_start_producer_wrapper()
)
logger.debug("Pydantic AI StreamedResponseSync context propagation patching successful")
except Exception as e:
logger.warning(f"Failed to patch StreamedResponseSync context propagation: {e}")
return True
except ImportError:
# Not installed - this is expected when using auto_instrument()
return False
def wrap_agent(Agent: Any) -> Any:
if _is_patched(Agent):
return Agent
def _ensure_model_wrapped(instance: Any):
"""Ensure the agent's model class is wrapped (lazy wrapping)."""
if hasattr(instance, "_model") and instance._model is not None:
model_class = type(instance._model)
_wrap_concrete_model_class(model_class)
async def agent_run_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
_ensure_model_wrapped(instance)
input_data, metadata = _build_agent_input_and_metadata(args, kwargs, instance)
with start_span(
name=f"agent_run [{instance.name}]" if hasattr(instance, "name") and instance.name else "agent_run",
type=SpanTypeAttribute.LLM,
input=input_data if input_data else None,
metadata=metadata,
) as agent_span:
start_time = time.time()
result = await wrapped(*args, **kwargs)
end_time = time.time()
_create_tool_spans_from_messages(result)
output = _serialize_result_output(result)
metrics = _extract_usage_metrics(result, start_time, end_time)
agent_span.log(output=output, metrics=metrics)
return result
wrap_function_wrapper(Agent, "run", agent_run_wrapper)
def agent_run_sync_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
_ensure_model_wrapped(instance)
input_data, metadata = _build_agent_input_and_metadata(args, kwargs, instance)
with start_span(
name=f"agent_run_sync [{instance.name}]"
if hasattr(instance, "name") and instance.name
else "agent_run_sync",
type=SpanTypeAttribute.LLM,
input=input_data if input_data else None,
metadata=metadata,
) as agent_span:
start_time = time.time()
result = wrapped(*args, **kwargs)
end_time = time.time()
_create_tool_spans_from_messages(result)
output = _serialize_result_output(result)
metrics = _extract_usage_metrics(result, start_time, end_time)
agent_span.log(output=output, metrics=metrics)
return result
wrap_function_wrapper(Agent, "run_sync", agent_run_sync_wrapper)
def agent_to_cli_sync_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
_ensure_model_wrapped(instance)
input_data, metadata = _build_agent_input_and_metadata(args, kwargs, instance)
with start_span(
name=f"agent_to_cli_sync [{instance.name}]"
if hasattr(instance, "name") and instance.name
else "agent_to_cli_sync",
type=SpanTypeAttribute.LLM,
input=input_data if input_data else None,
metadata=metadata,
) as agent_span:
start_time = time.time()
result = wrapped(*args, **kwargs)
end_time = time.time()
agent_span.log(metrics={"start": start_time, "end": end_time, "duration": end_time - start_time})
return result
wrap_function_wrapper(Agent, "to_cli_sync", agent_to_cli_sync_wrapper)
def agent_run_stream_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
_ensure_model_wrapped(instance)
input_data, metadata = _build_agent_input_and_metadata(args, kwargs, instance)
agent_name = instance.name if hasattr(instance, "name") else None
span_name = f"agent_run_stream [{agent_name}]" if agent_name else "agent_run_stream"
return _AgentStreamWrapper(
wrapped(*args, **kwargs),
span_name,
input_data,
metadata,
)
wrap_function_wrapper(Agent, "run_stream", agent_run_stream_wrapper)
def agent_run_stream_sync_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
_ensure_model_wrapped(instance)
input_data, metadata = _build_agent_input_and_metadata(args, kwargs, instance)
agent_name = instance.name if hasattr(instance, "name") else None
span_name = f"agent_run_stream_sync [{agent_name}]" if agent_name else "agent_run_stream_sync"
# Create span context BEFORE calling wrapped function so internal spans nest under it
span_cm = start_span(
name=span_name,
type=SpanTypeAttribute.LLM,
input=input_data if input_data else None,
metadata=metadata,
)
span = span_cm.__enter__()
start_time = time.time()
try:
# Call the original function within the span context
stream_result = wrapped(*args, **kwargs)
return _AgentStreamResultSyncProxy(
stream_result,
span,
span_cm,
start_time,
)
except Exception:
# Clean up span on error
span_cm.__exit__(*sys.exc_info())
raise
wrap_function_wrapper(Agent, "run_stream_sync", agent_run_stream_sync_wrapper)
async def agent_run_stream_events_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
_ensure_model_wrapped(instance)
input_data, metadata = _build_agent_input_and_metadata(args, kwargs, instance)
agent_name = instance.name if hasattr(instance, "name") else None
span_name = f"agent_run_stream_events [{agent_name}]" if agent_name else "agent_run_stream_events"
with start_span(
name=span_name,
type=SpanTypeAttribute.LLM,
input=input_data if input_data else None,
metadata=metadata,
) as agent_span:
start_time = time.time()
event_count = 0
final_result = None
async for event in wrapped(*args, **kwargs):
event_count += 1
if hasattr(event, "output"):
final_result = event
yield event
end_time = time.time()
if final_result:
_create_tool_spans_from_messages(final_result)
output = None
metrics = {
"start": start_time,
"end": end_time,
"duration": end_time - start_time,
"event_count": event_count,
}
if final_result:
output = _serialize_result_output(final_result)
usage_metrics = _extract_usage_metrics(final_result, start_time, end_time)
metrics.update(usage_metrics)
agent_span.log(output=output, metrics=metrics)
wrap_function_wrapper(Agent, "run_stream_events", agent_run_stream_events_wrapper)
Agent._braintrust_patched = True
return Agent
def _create_direct_model_request_wrapper():
"""Create wrapper for direct.model_request()."""
async def wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
with start_span(
name="model_request",
type=SpanTypeAttribute.LLM,
input=input_data,
metadata=metadata,
) as span:
start_time = time.time()
result = await wrapped(*args, **kwargs)
end_time = time.time()
output = _serialize_model_response(result)
metrics = _extract_response_metrics(result, start_time, end_time)
span.log(output=output, metrics=metrics)
return result
return wrapper
def _create_direct_model_request_sync_wrapper():
"""Create wrapper for direct.model_request_sync()."""
def wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
with start_span(
name="model_request_sync",
type=SpanTypeAttribute.LLM,
input=input_data,
metadata=metadata,
) as span:
start_time = time.time()
result = wrapped(*args, **kwargs)
end_time = time.time()
output = _serialize_model_response(result)
metrics = _extract_response_metrics(result, start_time, end_time)
span.log(output=output, metrics=metrics)
return result
return wrapper
def _create_direct_model_request_stream_wrapper():
"""Create wrapper for direct.model_request_stream()."""
def wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
return _DirectStreamWrapper(
wrapped(*args, **kwargs),
"model_request_stream",
input_data,
metadata,
)
return wrapper
def _create_direct_model_request_stream_sync_wrapper():
"""Create wrapper for direct.model_request_stream_sync()."""
def wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
return _DirectStreamWrapperSync(
wrapped(*args, **kwargs),
"model_request_stream_sync",
input_data,
metadata,
)
return wrapper
def wrap_model_request(original_func: Any) -> Any:
async def wrapper(*args, **kwargs):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
with start_span(
name="model_request",
type=SpanTypeAttribute.LLM,
input=input_data,
metadata=metadata,
) as span:
start_time = time.time()
result = await original_func(*args, **kwargs)
end_time = time.time()
output = _serialize_model_response(result)
metrics = _extract_response_metrics(result, start_time, end_time)
span.log(output=output, metrics=metrics)
return result
return wrapper
def wrap_model_request_sync(original_func: Any) -> Any:
def wrapper(*args, **kwargs):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
with start_span(
name="model_request_sync",
type=SpanTypeAttribute.LLM,
input=input_data,
metadata=metadata,
) as span:
start_time = time.time()
result = original_func(*args, **kwargs)
end_time = time.time()
output = _serialize_model_response(result)
metrics = _extract_response_metrics(result, start_time, end_time)
span.log(output=output, metrics=metrics)
return result
return wrapper
def wrap_model_request_stream(original_func: Any) -> Any:
def wrapper(*args, **kwargs):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
return _DirectStreamWrapper(
original_func(*args, **kwargs),
"model_request_stream",
input_data,
metadata,
)
return wrapper
def wrap_model_request_stream_sync(original_func: Any) -> Any:
def wrapper(*args, **kwargs):
input_data, metadata = _build_direct_model_input_and_metadata(args, kwargs)
return _DirectStreamWrapperSync(
original_func(*args, **kwargs),
"model_request_stream_sync",
input_data,
metadata,
)
return wrapper
def wrap_model_classes():
"""Wrap Model classes to capture internal model requests made by agents."""
try:
from pydantic_ai.models import Model
def wrap_all_subclasses(base_class):
"""Recursively wrap all subclasses of a base class."""
for subclass in base_class.__subclasses__():
if not getattr(subclass, "__abstractmethods__", None):
try:
_wrap_concrete_model_class(subclass)
except Exception as e:
logger.debug(f"Could not wrap {subclass.__name__}: {e}")
wrap_all_subclasses(subclass)
wrap_all_subclasses(Model)
except Exception as e:
logger.warning(f"Failed to wrap Model classes: {e}")
def _build_model_class_input_and_metadata(instance: Any, args: Any, kwargs: Any):
"""Build input data and metadata for model class request wrappers.
Returns:
Tuple of (model_name, display_name, input_data, metadata)
"""
model_name, provider = _extract_model_info_from_model_instance(instance)
display_name = model_name or type(instance).__name__
messages = args[0] if len(args) > 0 else kwargs.get("messages")
model_settings = args[1] if len(args) > 1 else kwargs.get("model_settings")
serialized_messages = _serialize_messages(messages)
input_data = {"messages": serialized_messages}
if model_settings is not None:
input_data["model_settings"] = bt_safe_deep_copy(model_settings)
metadata = _build_model_metadata(model_name, provider, model_settings=None)
return model_name, display_name, input_data, metadata
def _wrap_concrete_model_class(model_class: Any):
"""Wrap a concrete model class to trace its request methods."""
if _is_patched(model_class):
return
async def model_request_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
model_name, display_name, input_data, metadata = _build_model_class_input_and_metadata(instance, args, kwargs)
with start_span(
name=f"chat {display_name}",
type=SpanTypeAttribute.LLM,
input=input_data,
metadata=metadata,
) as span:
start_time = time.time()
result = await wrapped(*args, **kwargs)
end_time = time.time()
output = _serialize_model_response(result)
metrics = _extract_response_metrics(result, start_time, end_time)
span.log(output=output, metrics=metrics)
return result
def model_request_stream_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
model_name, display_name, input_data, metadata = _build_model_class_input_and_metadata(instance, args, kwargs)
return _DirectStreamWrapper(
wrapped(*args, **kwargs),
f"chat {display_name}",
input_data,
metadata,
)
wrap_function_wrapper(model_class, "request", model_request_wrapper)
wrap_function_wrapper(model_class, "request_stream", model_request_stream_wrapper)
model_class._braintrust_patched = True
class _AgentStreamWrapper(AbstractAsyncContextManager):
"""Wrapper for agent.run_stream() that adds tracing while passing through the stream result."""
def __init__(self, stream_cm: Any, span_name: str, input_data: Any, metadata: Any):
self.stream_cm = stream_cm
self.span_name = span_name
self.input_data = input_data
self.metadata = metadata
self.span_cm = None
self.start_time = None
self.stream_result = None
self._enter_task = None
self._first_token_time = None
async def __aenter__(self):
self._enter_task = asyncio.current_task()
# Use context manager properly so span stays current
# DON'T pass start_time here - we'll set it via metrics in __aexit__
self.span_cm = start_span(
name=self.span_name,
type=SpanTypeAttribute.LLM,
input=self.input_data if self.input_data else None,
metadata=self.metadata,
)
self.span_cm.__enter__()
# Capture start time right before entering the stream (API call initiation)
self.start_time = time.time()
self.stream_result = await self.stream_cm.__aenter__()
# Wrap the stream result to capture first token time
return _StreamResultProxy(self.stream_result, self)
async def __aexit__(self, exc_type, exc_val, exc_tb):
try:
await self.stream_cm.__aexit__(exc_type, exc_val, exc_tb)
finally:
if self.span_cm and self.start_time and self.stream_result:
end_time = time.time()
_create_tool_spans_from_messages(self.stream_result)
output = _serialize_stream_output(self.stream_result)
metrics = _extract_stream_usage_metrics(
self.stream_result, self.start_time, end_time, self._first_token_time
)
self.span_cm.log(output=output, metrics=metrics)
# Clean up span context
if self.span_cm:
if asyncio.current_task() is self._enter_task:
self.span_cm.__exit__(None, None, None)
else:
self.span_cm.end()
return False
class _StreamResultProxy:
"""Proxy for stream result that captures first token time."""
def __init__(self, stream_result: Any, wrapper: _AgentStreamWrapper):
self._stream_result = stream_result
self._wrapper = wrapper
def __getattr__(self, name: str):
"""Delegate all attribute access to the wrapped stream result."""
attr = getattr(self._stream_result, name)
# Wrap streaming methods to capture first token time
if callable(attr) and name in ("stream_text", "stream_output"):
async def wrapped_method(*args, **kwargs):
result = attr(*args, **kwargs)
async for item in result:
if self._wrapper._first_token_time is None:
self._wrapper._first_token_time = time.time()
yield item
return wrapped_method
return attr
class _DirectStreamWrapper(AbstractAsyncContextManager):
"""Wrapper for model_request_stream() that adds tracing while passing through the stream."""
def __init__(self, stream_cm: Any, span_name: str, input_data: Any, metadata: Any):
self.stream_cm = stream_cm
self.span_name = span_name
self.input_data = input_data
self.metadata = metadata
self.span_cm = None
self.start_time = None
self.stream = None
self._enter_task = None
self._first_token_time = None
async def __aenter__(self):
self._enter_task = asyncio.current_task()
# Use context manager properly so span stays current
# DON'T pass start_time here - we'll set it via metrics in __aexit__
self.span_cm = start_span(
name=self.span_name,
type=SpanTypeAttribute.LLM,
input=self.input_data if self.input_data else None,
metadata=self.metadata,
)
self.span_cm.__enter__()
# Capture start time right before entering the stream (API call initiation)
self.start_time = time.time()
self.stream = await self.stream_cm.__aenter__()
# Wrap the stream to capture first token time
return _DirectStreamIteratorProxy(self.stream, self)
async def __aexit__(self, exc_type, exc_val, exc_tb):
try:
await self.stream_cm.__aexit__(exc_type, exc_val, exc_tb)
finally:
if self.span_cm and self.start_time and self.stream:
end_time = time.time()
try:
final_response = self.stream.get()
output = _serialize_model_response(final_response)
metrics = _extract_response_metrics(
final_response, self.start_time, end_time, self._first_token_time
)
self.span_cm.log(output=output, metrics=metrics)
except Exception as e:
logger.debug(f"Failed to extract stream output/metrics: {e}")
# Clean up span context
if self.span_cm:
if asyncio.current_task() is self._enter_task:
self.span_cm.__exit__(None, None, None)
else:
self.span_cm.end()
return False
class _DirectStreamIteratorProxy:
"""Proxy for direct stream that captures first token time."""
def __init__(self, stream: Any, wrapper: _DirectStreamWrapper):
self._stream = stream
self._wrapper = wrapper
self._iterator = None
def __getattr__(self, name: str):
"""Delegate all attribute access to the wrapped stream."""
return getattr(self._stream, name)
def __aiter__(self):
"""Return async iterator that captures first token time."""
# Get the actual async iterator from the stream
self._iterator = self._stream.__aiter__() if hasattr(self._stream, "__aiter__") else self._stream
return self
async def __anext__(self):
"""Capture first token time on first iteration."""
if self._iterator is None:
# In case __aiter__ wasn't called, initialize it
self._iterator = self._stream.__aiter__() if hasattr(self._stream, "__aiter__") else self._stream
item = await self._iterator.__anext__()
if self._wrapper._first_token_time is None:
self._wrapper._first_token_time = time.time()
return item
class _AgentStreamResultSyncProxy:
"""Proxy for agent.run_stream_sync() result that adds tracing while delegating to actual stream result."""
def __init__(self, stream_result: Any, span: Any, span_cm: Any, start_time: float):
self._stream_result = stream_result
self._span = span
self._span_cm = span_cm
self._start_time = start_time
self._logged = False
self._finalize_on_del = True
self._first_token_time = None
def __getattr__(self, name: str):
"""Delegate all attribute access to the wrapped stream result."""
attr = getattr(self._stream_result, name)
# Wrap any method that returns an iterator to auto-finalize when exhausted
if callable(attr) and name in ("stream_text", "stream_output", "__iter__"):
def wrapped_method(*args, **kwargs):
try:
iterator = attr(*args, **kwargs)
# If it's an iterator, wrap it
if hasattr(iterator, "__iter__") or hasattr(iterator, "__next__"):
try:
for item in iterator:
if self._first_token_time is None:
self._first_token_time = time.time()
yield item
finally:
self._finalize()
self._finalize_on_del = False # Don't finalize again in __del__
else:
return iterator
except Exception:
self._finalize()
self._finalize_on_del = False
raise
return wrapped_method
return attr
def _finalize(self):
"""Log metrics and close span."""
if self._span and not self._logged and self._stream_result:
try:
end_time = time.time()
_create_tool_spans_from_messages(self._stream_result)
output = _serialize_stream_output(self._stream_result)
metrics = _extract_stream_usage_metrics(
self._stream_result, self._start_time, end_time, self._first_token_time
)
self._span.log(output=output, metrics=metrics)
self._logged = True
finally:
try:
self._span_cm.__exit__(None, None, None)
except Exception:
pass
def __del__(self):
"""Ensure span is closed when proxy is destroyed."""
if self._finalize_on_del:
self._finalize()
class _DirectStreamWrapperSync:
"""Wrapper for model_request_stream_sync() that adds tracing while passing through the stream."""
def __init__(self, stream_cm: Any, span_name: str, input_data: Any, metadata: Any):
self.stream_cm = stream_cm
self.span_name = span_name
self.input_data = input_data
self.metadata = metadata
self.span_cm = None
self.start_time = None
self.stream = None
self._first_token_time = None
def __enter__(self):
# Use context manager properly so span stays current
# DON'T pass start_time here - we'll set it via metrics in __exit__
self.span_cm = start_span(
name=self.span_name,
type=SpanTypeAttribute.LLM,
input=self.input_data if self.input_data else None,
metadata=self.metadata,
)
span = self.span_cm.__enter__()
# Capture start time right before entering the stream (API call initiation)
self.start_time = time.time()
self.stream = self.stream_cm.__enter__()
# Wrap the stream to capture first token time
return _DirectStreamIteratorSyncProxy(self.stream, self)
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self.stream_cm.__exit__(exc_type, exc_val, exc_tb)
finally:
if self.span_cm and self.start_time and self.stream:
end_time = time.time()
try:
final_response = self.stream.get()
output = _serialize_model_response(final_response)
metrics = _extract_response_metrics(
final_response, self.start_time, end_time, self._first_token_time
)
self.span_cm.log(output=output, metrics=metrics)
except Exception as e:
logger.debug(f"Failed to extract stream output/metrics: {e}")
# Always clean up span context
if self.span_cm:
self.span_cm.__exit__(None, None, None)
return False
class _DirectStreamIteratorSyncProxy:
"""Proxy for direct stream (sync) that captures first token time."""
def __init__(self, stream: Any, wrapper: _DirectStreamWrapperSync):
self._stream = stream
self._wrapper = wrapper
self._iterator = None
def __getattr__(self, name: str):
"""Delegate all attribute access to the wrapped stream."""
return getattr(self._stream, name)
def __iter__(self):
"""Return iterator that captures first token time."""
# Get the actual iterator from the stream
self._iterator = self._stream.__iter__() if hasattr(self._stream, "__iter__") else self._stream
return self
def __next__(self):
"""Capture first token time on first iteration."""
if self._iterator is None:
# In case __iter__ wasn't called, initialize it
self._iterator = self._stream.__iter__() if hasattr(self._stream, "__iter__") else self._stream
item = self._iterator.__next__()
if self._wrapper._first_token_time is None:
self._wrapper._first_token_time = time.time()
return item
def _create_tool_spans_from_messages(result: Any) -> None:
"""
Create TOOL-type spans from tool call/return message parts in a completed agent result.
Uses message timestamps from PydanticAI to position spans correctly in the trace:
- start_time = ModelResponse.timestamp (when the model requested the tool call)
- end_time = ModelRequest.timestamp (when the tool result was sent back)
"""
try:
_create_tool_spans_from_messages_impl(result)
except Exception:
pass
def _create_tool_spans_from_messages_impl(result: Any) -> None:
from pydantic_ai.messages import ToolCallPart, ToolReturnPart
messages = result.new_messages()
returns_by_id: dict[str, tuple[Any, float | None]] = {}
for msg in messages:
if not hasattr(msg, "parts"):
continue
msg_ts = _msg_timestamp(msg)
for part in msg.parts:
if isinstance(part, ToolReturnPart) and hasattr(part, "tool_call_id"):
returns_by_id[part.tool_call_id] = (part, msg_ts)
for msg in messages:
if not hasattr(msg, "parts"):
continue
call_ts = _msg_timestamp(msg)
for part in msg.parts:
if not isinstance(part, ToolCallPart):
continue
tool_name = getattr(part, "tool_name", None) or "unknown_tool"
tool_call_id = getattr(part, "tool_call_id", None)
try:
input_data = part.args_as_dict()
except Exception:
input_data = bt_safe_deep_copy(getattr(part, "args", None))
output_data = None
return_ts: float | None = None
if tool_call_id and tool_call_id in returns_by_id:
return_part, return_ts = returns_by_id[tool_call_id]
output_data = bt_safe_deep_copy(getattr(return_part, "content", None))
metadata = {}
if tool_call_id:
metadata["tool_call_id"] = tool_call_id
with start_span(
name=tool_name,
type=SpanTypeAttribute.TOOL,
input=input_data,
start_time=call_ts,
metadata=metadata if metadata else None,
) as tool_span:
metrics = {}
if call_ts is not None:
metrics["start"] = call_ts
if return_ts is not None:
metrics["end"] = return_ts
if call_ts is not None and return_ts is not None:
metrics["duration"] = return_ts - call_ts
tool_span.log(output=output_data, metrics=metrics if metrics else None)
tool_span.end(end_time=return_ts)
def _msg_timestamp(msg: Any) -> float | None:
"""Extract epoch-seconds timestamp from a PydanticAI message, or None."""
ts = getattr(msg, "timestamp", None)
if ts is None:
return None
try:
return ts.timestamp() # datetime → float
except Exception:
return None
def _serialize_user_prompt(user_prompt: Any) -> Any:
"""Serialize user prompt, handling BinaryContent and other types."""
if user_prompt is None:
return None
if isinstance(user_prompt, str):
return user_prompt
if isinstance(user_prompt, list):
return [_serialize_content_part(part) for part in user_prompt]
return _serialize_content_part(user_prompt)
def _serialize_content_part(part: Any) -> Any:
"""Serialize a content part, handling BinaryContent specially.
This function handles:
- BinaryContent: converts to Braintrust Attachment
- Parts with nested content (UserPromptPart): recursively serializes content items
- Strings: passes through unchanged
- Other objects: converts to dict via model_dump
"""
if part is None:
return None
if hasattr(part, "data") and hasattr(part, "media_type") and hasattr(part, "kind"):
if part.kind == "binary":
data = part.data
media_type = part.media_type
extension = media_type.split("/")[1] if "/" in media_type else "bin"
filename = f"file.{extension}"
attachment = Attachment(data=data, filename=filename, content_type=media_type)
return {"type": "binary", "attachment": attachment, "media_type": media_type}
if hasattr(part, "content"):
content = part.content
if isinstance(content, list):
serialized_content = [_serialize_content_part(item) for item in content]
result = bt_safe_deep_copy(part)
if isinstance(result, dict):
result["content"] = serialized_content
return result
elif content is not None:
serialized_content = _serialize_content_part(content)
result = bt_safe_deep_copy(part)
if isinstance(result, dict):
result["content"] = serialized_content
return result
if isinstance(part, str):
return part
return bt_safe_deep_copy(part)
def _serialize_messages(messages: Any) -> Any:
"""Serialize messages list."""
if not messages:
return []
result = []
for msg in messages:
if hasattr(msg, "parts") and msg.parts:
original_parts = msg.parts
serialized_parts = [_serialize_content_part(p) for p in original_parts]
# Use model_dump with exclude to avoid serializing parts field prematurely
if hasattr(msg, "model_dump"):
try:
serialized_msg = msg.model_dump(exclude={"parts"}, exclude_none=True)
except (TypeError, ValueError):
# If exclude parameter not supported, fall back to bt_safe_deep_copy
serialized_msg = bt_safe_deep_copy(msg)
else:
serialized_msg = bt_safe_deep_copy(msg)
if isinstance(serialized_msg, dict):
serialized_msg["parts"] = serialized_parts
else:
serialized_msg = bt_safe_deep_copy(msg)
result.append(serialized_msg)
return result
def _serialize_result_output(result: Any) -> Any:
"""Serialize agent run result output."""
if not result:
return None
output_dict = {}
if hasattr(result, "output"):
output_dict["output"] = bt_safe_deep_copy(result.output)
if hasattr(result, "response"):