-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtracer.py
More file actions
2459 lines (2095 loc) · 95.3 KB
/
tracer.py
File metadata and controls
2459 lines (2095 loc) · 95.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
"""Module with the logic to create and manage traces and steps."""
import asyncio
import atexit
import contextvars
import inspect
import json
import logging
import os
import threading
import time
import traceback
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
from typing import (
Any,
Awaitable,
Callable,
Dict,
Generator,
List,
Optional,
Tuple,
Union,
)
from ..._base_client import DefaultHttpxClient
from ..._client import Openlayer
from ...types.inference_pipelines.data_stream_params import ConfigLlmData
from .. import utils
from ..guardrails.base import GuardrailAction, GuardrailResult
from . import enums, steps, traces
from .context import UserSessionContext
# Type aliases for callback functions
OnFlushFailureCallback = Callable[[Dict[str, Any], Dict[str, Any], Exception], None]
OnReplaySuccessCallback = Callable[[Dict[str, Any], Dict[str, Any]], None]
OnReplayFailureCallback = Callable[[Dict[str, Any], Dict[str, Any], Exception], None]
logger = logging.getLogger(__name__)
# ----------------------------- Module setup and globals ----------------------------- #
TRUE_LIST = ["true", "on", "1"]
_publish = utils.get_env_variable("OPENLAYER_DISABLE_PUBLISH") not in TRUE_LIST
_verify_ssl = (
utils.get_env_variable("OPENLAYER_VERIFY_SSL") or "true"
).lower() in TRUE_LIST
_client = None
# Configuration variables for programmatic setup
_configured_api_key: Optional[str] = None
_configured_pipeline_id: Optional[str] = None
_configured_base_url: Optional[str] = None
_configured_timeout: Optional[Union[int, float]] = None
_configured_max_retries: Optional[int] = None
# Offline buffering and callback configuration
_configured_on_flush_failure: Optional[OnFlushFailureCallback] = None
_configured_offline_buffer_enabled: bool = False
_configured_offline_buffer_path: Optional[str] = None
_configured_max_buffer_size: Optional[int] = None
# Attachment upload configuration
_configured_attachment_upload_enabled: bool = False
_configured_url_upload_enabled: bool = False
# Background publishing configuration
_configured_background_publish_enabled: bool = True
# Background executor for async trace publishing
_background_executor: Optional[ThreadPoolExecutor] = None
def _get_background_executor() -> ThreadPoolExecutor:
"""Get or create the background executor for trace publishing."""
global _background_executor
if _background_executor is None:
_background_executor = ThreadPoolExecutor(
max_workers=4, thread_name_prefix="openlayer-tracer"
)
# Register cleanup on exit
atexit.register(_shutdown_background_executor)
return _background_executor
def _shutdown_background_executor() -> None:
"""Shutdown the background executor gracefully."""
global _background_executor
if _background_executor is not None:
logger.debug("Shutting down background executor, waiting for pending tasks...")
_background_executor.shutdown(wait=True)
_background_executor = None
logger.debug("Background executor shutdown complete")
def configure(
api_key: Optional[str] = None,
inference_pipeline_id: Optional[str] = None,
base_url: Optional[str] = None,
timeout: Optional[Union[int, float]] = None,
max_retries: Optional[int] = None,
on_flush_failure: Optional[OnFlushFailureCallback] = None,
offline_buffer_enabled: bool = False,
offline_buffer_path: Optional[str] = None,
max_buffer_size: Optional[int] = None,
attachment_upload_enabled: bool = False,
url_upload_enabled: bool = False,
background_publish_enabled: bool = True,
) -> None:
"""Configure the Openlayer tracer with custom settings.
This function allows you to programmatically set the API key, inference pipeline ID,
base URL, timeout, retry settings, and offline buffering for the Openlayer client,
instead of relying on environment variables.
Args:
api_key: The Openlayer API key. If not provided, falls back to OPENLAYER_API_KEY environment variable.
inference_pipeline_id: The default inference pipeline ID to use for tracing.
If not provided, falls back to OPENLAYER_INFERENCE_PIPELINE_ID environment variable.
base_url: The base URL for the Openlayer API. If not provided, falls back to
OPENLAYER_BASE_URL environment variable or the default.
timeout: The timeout for the Openlayer API in seconds (int or float). Defaults to 60 seconds.
max_retries: The maximum number of retries for failed API requests. Defaults to 2.
on_flush_failure: Optional callback function called when trace data fails to send to Openlayer.
Should accept (trace_data, config, error) as arguments.
offline_buffer_enabled: Enable offline buffering of failed traces. Defaults to False.
offline_buffer_path: Directory path for storing buffered traces. Defaults to ~/.openlayer/buffer.
max_buffer_size: Maximum number of trace files to store in buffer. Defaults to 1000.
attachment_upload_enabled: Enable uploading of attachments (images, audio, etc.) to
Openlayer storage. When enabled, attachments on steps will be uploaded during
trace completion. Defaults to False.
url_upload_enabled: Enable downloading and re-uploading of external URL
attachments to Openlayer storage. When enabled, attachments that reference
external URLs will be fetched and uploaded so the platform has a durable copy.
Requires attachment_upload_enabled to also be True. Defaults to False.
background_publish_enabled: Enable background publishing of traces. When enabled,
attachment uploads and trace publishing happen in a background thread, allowing
the main thread to return immediately. When disabled, tracing is synchronous.
Defaults to True.
Examples:
>>> import openlayer.lib.tracing.tracer as tracer
>>> # Configure with API key and pipeline ID
>>> tracer.configure(api_key="your_api_key_here", inference_pipeline_id="your_pipeline_id_here")
>>> # Configure with failure callback and offline buffering
>>> def on_failure(trace_data, config, error):
... print(f"Failed to send trace: {error}")
... # Could also log to monitoring system, send alerts, etc.
>>> tracer.configure(
... api_key="your_api_key_here",
... inference_pipeline_id="your_pipeline_id_here",
... on_flush_failure=on_failure,
... offline_buffer_enabled=True,
... offline_buffer_path="/tmp/openlayer_buffer",
... max_buffer_size=500,
... )
>>> # Configure with attachment uploads enabled
>>> tracer.configure(
... api_key="your_api_key_here",
... inference_pipeline_id="your_pipeline_id_here",
... attachment_upload_enabled=True,
... )
>>> # Now use the decorators normally
>>> @tracer.trace()
>>> def my_function():
... return "result"
"""
global _configured_api_key, _configured_pipeline_id, _configured_base_url, _configured_timeout, _configured_max_retries, _client
global _configured_on_flush_failure, _configured_offline_buffer_enabled, _configured_offline_buffer_path, _configured_max_buffer_size, _offline_buffer
global _configured_attachment_upload_enabled, _configured_url_upload_enabled, _configured_background_publish_enabled
_configured_api_key = api_key
_configured_pipeline_id = inference_pipeline_id
_configured_base_url = base_url
_configured_timeout = timeout
_configured_max_retries = max_retries
_configured_on_flush_failure = on_flush_failure
_configured_offline_buffer_enabled = offline_buffer_enabled
_configured_offline_buffer_path = offline_buffer_path
_configured_max_buffer_size = max_buffer_size
_configured_attachment_upload_enabled = attachment_upload_enabled
_configured_url_upload_enabled = url_upload_enabled
_configured_background_publish_enabled = background_publish_enabled
# Reset the client and buffer so they get recreated with new configuration
_client = None
_offline_buffer = None
# Reset attachment uploader
from .attachment_uploader import reset_uploader
reset_uploader()
def _get_client() -> Optional[Openlayer]:
"""Get or create the Openlayer client with lazy initialization."""
global _client
if not _publish:
return None
if _client is None:
# Lazy initialization - create client when first needed
client_kwargs = {}
# Use configured API key if available, otherwise fall back to environment variable
if _configured_api_key is not None:
client_kwargs["api_key"] = _configured_api_key
# Use configured base URL if available, otherwise fall back to environment variable
if _configured_base_url is not None:
client_kwargs["base_url"] = _configured_base_url
if _configured_timeout is not None:
client_kwargs["timeout"] = _configured_timeout
if _configured_max_retries is not None:
client_kwargs["max_retries"] = _configured_max_retries
if _verify_ssl:
_client = Openlayer(**client_kwargs)
else:
_client = Openlayer(
http_client=DefaultHttpxClient(
verify=False,
),
**client_kwargs,
)
return _client
_current_step = contextvars.ContextVar("current_step")
_current_trace = contextvars.ContextVar("current_trace")
_rag_context = contextvars.ContextVar("rag_context")
_rag_question = contextvars.ContextVar("rag_question")
# ----------------------------- Offline Buffer Implementation ----------------------------- #
class OfflineBuffer:
"""Handles offline buffering of trace data when platform communication fails."""
def __init__(
self,
buffer_path: Optional[str] = None,
max_buffer_size: Optional[int] = None,
):
"""Initialize the offline buffer.
Args:
buffer_path: Directory path for storing buffered traces.
Defaults to ~/.openlayer/buffer.
max_buffer_size: Maximum number of trace files to store.
Defaults to 1000.
"""
self.buffer_path = Path(
buffer_path or os.path.expanduser("~/.openlayer/buffer")
)
self.max_buffer_size = max_buffer_size or 1000
self._lock = threading.RLock()
# Create buffer directory if it doesn't exist
self.buffer_path.mkdir(parents=True, exist_ok=True)
logger.debug("Initialized offline buffer at %s", self.buffer_path)
def store_trace(
self,
trace_data: Dict[str, Any],
config: Dict[str, Any],
inference_pipeline_id: str,
) -> bool:
"""Store a failed trace to the offline buffer.
Args:
trace_data: The trace data that failed to send
config: The configuration used for streaming
inference_pipeline_id: The pipeline ID used
Returns:
True if successfully stored, False otherwise
"""
try:
with self._lock:
# Check buffer size limit
existing_files = list(self.buffer_path.glob("trace_*.json"))
if len(existing_files) >= self.max_buffer_size:
# Remove oldest file to make room
oldest_file = min(existing_files, key=lambda f: f.stat().st_mtime)
oldest_file.unlink()
logger.debug("Removed oldest buffered trace: %s", oldest_file)
# Create filename with timestamp and unique suffix
timestamp = int(time.time() * 1000) # milliseconds
unique_id = str(uuid.uuid4())[:8] # Short unique identifier
filename = f"trace_{timestamp}_{os.getpid()}_{unique_id}.json"
file_path = self.buffer_path / filename
# Prepare the complete data payload
buffered_payload = {
"trace_data": trace_data,
"config": config,
"inference_pipeline_id": inference_pipeline_id,
"timestamp": timestamp,
"metadata": {
"buffer_version": "1.0",
"created_by": "openlayer-python-sdk",
"process_id": os.getpid(),
},
}
# Write to file atomically
with file_path.open("w", encoding="utf-8") as f:
json.dump(buffered_payload, f, ensure_ascii=False, indent=2)
logger.info("Stored trace to offline buffer: %s", file_path)
return True
except Exception as e:
logger.error("Failed to store trace to offline buffer: %s", e)
return False
def get_buffered_traces(self) -> List[Dict[str, Any]]:
"""Get all buffered traces from disk.
Returns:
List of buffered trace payloads
"""
traces = []
try:
with self._lock:
trace_files = sorted(
self.buffer_path.glob("trace_*.json"),
key=lambda f: f.stat().st_mtime,
)
for file_path in trace_files:
try:
with file_path.open("r", encoding="utf-8") as f:
payload = json.load(f)
payload["_file_path"] = str(file_path)
traces.append(payload)
except Exception as e:
logger.error(
"Failed to read buffered trace %s: %s", file_path, e
)
except Exception as e:
logger.error("Failed to get buffered traces: %s", e)
return traces
def remove_trace(self, file_path: str) -> bool:
"""Remove a successfully replayed trace from the buffer.
Args:
file_path: Path to the trace file to remove
Returns:
True if successfully removed, False otherwise
"""
try:
with self._lock:
Path(file_path).unlink(missing_ok=True)
logger.debug("Removed successfully replayed trace: %s", file_path)
return True
except Exception as e:
logger.error("Failed to remove buffered trace %s: %s", file_path, e)
return False
def get_buffer_status(self) -> Dict[str, Any]:
"""Get current buffer status.
Returns:
Dictionary with buffer statistics
"""
try:
with self._lock:
trace_files = list(self.buffer_path.glob("trace_*.json"))
total_size = sum(f.stat().st_size for f in trace_files)
return {
"buffer_path": str(self.buffer_path),
"total_traces": len(trace_files),
"max_buffer_size": self.max_buffer_size,
"total_size_bytes": total_size,
"oldest_trace": (
min(trace_files, key=lambda f: f.stat().st_mtime).name
if trace_files
else None
),
"newest_trace": (
max(trace_files, key=lambda f: f.stat().st_mtime).name
if trace_files
else None
),
}
except Exception as e:
logger.error("Failed to get buffer status: %s", e)
return {"error": str(e)}
def clear_buffer(self) -> int:
"""Clear all buffered traces.
Returns:
Number of traces removed
"""
try:
with self._lock:
trace_files = list(self.buffer_path.glob("trace_*.json"))
count = len(trace_files)
for file_path in trace_files:
file_path.unlink(missing_ok=True)
logger.info("Cleared %d traces from offline buffer", count)
return count
except Exception as e:
logger.error("Failed to clear buffer: %s", e)
return 0
# Global offline buffer instance
_offline_buffer: Optional[OfflineBuffer] = None
def _get_offline_buffer() -> Optional[OfflineBuffer]:
"""Get or create the offline buffer instance."""
global _offline_buffer
if _configured_offline_buffer_enabled and _offline_buffer is None:
_offline_buffer = OfflineBuffer(
buffer_path=_configured_offline_buffer_path,
max_buffer_size=_configured_max_buffer_size,
)
return _offline_buffer if _configured_offline_buffer_enabled else None
# ----------------------------- Public API functions ----------------------------- #
def get_current_trace() -> Optional[traces.Trace]:
"""Returns the current trace."""
return _current_trace.get(None)
def get_current_step() -> Optional[steps.Step]:
"""Returns the current step."""
return _current_step.get(None)
def get_rag_context() -> Optional[Dict[str, Any]]:
"""Returns the current context."""
return _rag_context.get(None)
def get_rag_question() -> Optional[str]:
"""Returns the current question."""
return _rag_question.get(None)
@contextmanager
def create_step(
name: str,
step_type: enums.StepType = enums.StepType.USER_CALL,
inputs: Optional[Any] = None,
output: Optional[Any] = None,
metadata: Optional[Dict[str, Any]] = None,
inference_pipeline_id: Optional[str] = None,
on_flush_failure: Optional[OnFlushFailureCallback] = None,
) -> Generator[steps.Step, None, None]:
"""Starts a trace and yields a Step object."""
new_step, is_root_step, token = _create_and_initialize_step(
step_name=name,
step_type=step_type,
inputs=inputs,
output=output,
metadata=metadata,
)
try:
yield new_step
finally:
if new_step.end_time is None:
new_step.end_time = time.time()
if new_step.latency is None:
latency = (new_step.end_time - new_step.start_time) * 1000 # in ms
new_step.latency = latency
try:
_current_step.reset(token)
except ValueError as e:
# Handle context variable mismatch gracefully
# This can occur when async generators cross context boundaries
if "was created in a different Context" not in str(e):
raise
_handle_trace_completion(
is_root_step=is_root_step,
step_name=name,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
def add_chat_completion_step_to_trace(**kwargs) -> None:
"""Adds a chat completion step to the trace."""
with create_step(
step_type=enums.StepType.CHAT_COMPLETION,
name=kwargs.get("name", "Chat Completion"),
) as step:
step.log(**kwargs)
def trace(
*step_args,
inference_pipeline_id: Optional[str] = None,
context_kwarg: Optional[str] = None,
question_kwarg: Optional[str] = None,
promote: Optional[Union[List[str], Dict[str, str]]] = None,
guardrails: Optional[List[Any]] = None,
on_flush_failure: Optional[OnFlushFailureCallback] = None,
**step_kwargs,
):
"""Decorator to trace a function with optional guardrails.
Parameters
----------
promote : list of str or dict mapping str to str, optional
Kwarg names whose values should be surfaced as top-level columns in the
trace data. Pass a list to use the original kwarg names as column names,
or a dict to alias them::
# List form – uses original kwarg names
@tracer.trace(promote=["tool_call_count", "user_query"])
# Dict form – maps kwarg_name -> column_name
@tracer.trace(promote={"user_query": "agent_input_query"})
Examples
--------
To trace a function, simply decorate it with the ``@trace()`` decorator. By doing
so, the functions inputs, outputs, and metadata will be automatically logged to your
Openlayer project.
>>> import os
>>> from openlayer.tracing import tracer
>>> from openlayer.lib.guardrails import PIIGuardrail
>>>
>>> # Set the environment variables
>>> os.environ["OPENLAYER_API_KEY"] = "YOUR_OPENLAYER_API_KEY_HERE"
>>> os.environ["OPENLAYER_PROJECT_NAME"] = "YOUR_OPENLAYER_PROJECT_NAME_HERE"
>>>
>>> # Create guardrail instance
>>> pii_guardrail = PIIGuardrail(name="PII Protection")
>>>
>>> # Decorate functions with tracing and guardrails
>>> @tracer.trace(guardrails=[pii_guardrail])
>>> def main(user_query: str) -> str:
>>> context = retrieve_context(user_query)
>>> answer = generate_answer(user_query, context)
>>> return answer
>>>
>>> @tracer.trace()
>>> def retrieve_context(user_query: str) -> str:
>>> return "Some context"
>>>
>>> @tracer.trace(guardrails=[pii_guardrail])
>>> def generate_answer(user_query: str, context: str) -> str:
>>> return "Some answer"
>>>
>>> # Every time the main function is called, the data is automatically
>>> # streamed to your Openlayer project. E.g.:
>>> main("What is the meaning of life?")
"""
def decorator(func):
func_signature = inspect.signature(func)
if step_kwargs.get("name") is None:
step_kwargs["name"] = func.__name__
step_name = step_kwargs["name"]
# Check if it's a generator function
if inspect.isgeneratorfunction(func):
# For sync generators, use class-based approach to delay trace creation
# until actual iteration begins (not when generator object is created)
@wraps(func)
def sync_generator_wrapper(*func_args, **func_kwargs):
class TracedSyncGenerator:
def __init__(self):
self._original_gen = None
self._step = None
self._is_root_step = False
self._token = None
self._output_chunks = []
self._trace_initialized = False
self._captured_context = (
None # Capture context for ASGI compatibility
)
def __iter__(self):
return self
def __next__(self):
# Initialize tracing on first iteration only
if not self._trace_initialized:
self._original_gen = func(*func_args, **func_kwargs)
self._step, self._is_root_step, self._token = (
_create_and_initialize_step(
step_name=step_name,
step_type=enums.StepType.USER_CALL,
inputs=None,
output=None,
metadata=None,
)
)
self._inputs = _extract_function_inputs(
func_signature=func_signature,
func_args=func_args,
func_kwargs=func_kwargs,
context_kwarg=context_kwarg,
question_kwarg=question_kwarg,
)
_apply_promote_kwargs(self._inputs, promote)
self._trace_initialized = True
try:
chunk = next(self._original_gen)
self._output_chunks.append(chunk)
if self._captured_context is None:
self._captured_context = contextvars.copy_context()
return chunk
except StopIteration:
# Finalize trace when generator is exhausted
# Use captured context to ensure we have access to the trace
output = _join_output_chunks(self._output_chunks)
if self._captured_context:
self._captured_context.run(
_finalize_sync_generator_step,
step=self._step,
token=self._token,
is_root_step=self._is_root_step,
step_name=step_name,
inputs=self._inputs,
output=output,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
else:
_finalize_sync_generator_step(
step=self._step,
token=self._token,
is_root_step=self._is_root_step,
step_name=step_name,
inputs=self._inputs,
output=output,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
raise
except Exception as exc:
# Handle exceptions
if self._step:
_log_step_exception(self._step, exc)
output = _join_output_chunks(self._output_chunks)
if self._captured_context:
self._captured_context.run(
_finalize_sync_generator_step,
step=self._step,
token=self._token,
is_root_step=self._is_root_step,
step_name=step_name,
inputs=self._inputs,
output=output,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
else:
_finalize_sync_generator_step(
step=self._step,
token=self._token,
is_root_step=self._is_root_step,
step_name=step_name,
inputs=self._inputs,
output=output,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
raise
return TracedSyncGenerator()
return sync_generator_wrapper
else:
# Handle regular functions with guardrail support
@wraps(func)
def wrapper(*func_args, **func_kwargs):
if step_kwargs.get("name") is None:
step_kwargs["name"] = func.__name__
with create_step(
*step_args,
inference_pipeline_id=inference_pipeline_id,
**step_kwargs,
) as step:
output = exception = None
original_inputs = None
modified_inputs = None
guardrail_metadata = {}
try:
# Extract original inputs for guardrail processing
original_inputs = _extract_function_inputs(
func_signature=func_signature,
func_args=func_args,
func_kwargs=func_kwargs,
context_kwarg=context_kwarg,
question_kwarg=question_kwarg,
)
_apply_promote_kwargs(original_inputs, promote)
# Apply input guardrails
modified_inputs, input_guardrail_metadata = (
_apply_input_guardrails(
guardrails or [],
original_inputs,
)
)
guardrail_metadata.update(input_guardrail_metadata)
# Check if function execution should be skipped
if (
hasattr(modified_inputs, "__class__")
and modified_inputs.__class__.__name__
== "SkipFunctionExecution"
):
# Function execution was blocked with SKIP_FUNCTION strategy
output = None
logger.debug(
"Function %s execution skipped by guardrail",
func.__name__,
)
else:
# Execute function with potentially modified inputs
if modified_inputs != original_inputs:
# Reconstruct function arguments from modified inputs
bound = func_signature.bind(*func_args, **func_kwargs)
bound.apply_defaults()
# Update bound arguments with modified values
for (
param_name,
modified_value,
) in modified_inputs.items():
if param_name in bound.arguments:
bound.arguments[param_name] = modified_value
output = func(*bound.args, **bound.kwargs)
else:
output = func(*func_args, **func_kwargs)
# Apply output guardrails (skip if function was skipped)
if (
hasattr(modified_inputs, "__class__")
and modified_inputs.__class__.__name__
== "SkipFunctionExecution"
):
final_output, output_guardrail_metadata = output, {}
# Use original inputs for logging since modified_inputs
# is a special marker
modified_inputs = original_inputs
else:
final_output, output_guardrail_metadata = (
_apply_output_guardrails(
guardrails or [],
output,
modified_inputs or original_inputs,
)
)
guardrail_metadata.update(output_guardrail_metadata)
if final_output != output:
output = final_output
except Exception as exc:
# Check if this is a guardrail exception
if hasattr(exc, "guardrail_name"):
guardrail_metadata[f"{exc.guardrail_name}_blocked"] = {
"action": "blocked",
"reason": exc.reason,
"metadata": getattr(exc, "metadata", {}),
}
_log_step_exception(step, exc)
exception = exc
# Extract inputs and finalize logging using optimized helper
_process_wrapper_inputs_and_outputs(
step=step,
func_signature=func_signature,
func_args=func_args,
func_kwargs=func_kwargs,
context_kwarg=context_kwarg,
output=output,
guardrail_metadata=guardrail_metadata,
question_kwarg=question_kwarg,
)
if exception is not None:
raise exception
return output
return wrapper
return decorator
def trace_async(
*step_args,
inference_pipeline_id: Optional[str] = None,
context_kwarg: Optional[str] = None,
question_kwarg: Optional[str] = None,
promote: Optional[Union[List[str], Dict[str, str]]] = None,
guardrails: Optional[List[Any]] = None,
on_flush_failure: Optional[OnFlushFailureCallback] = None,
**step_kwargs,
):
"""Decorator to trace async functions and async generators.
This decorator automatically detects whether the function is a regular async
function
or an async generator and handles both cases appropriately.
Parameters
----------
promote : list of str or dict mapping str to str, optional
Kwarg names whose values should be surfaced as top-level columns in the
trace data. Pass a list to use the original kwarg names as column names,
or a dict to alias them::
# List form – uses original kwarg names
@tracer.trace_async(promote=["job_id", "user_query"])
# Dict form – maps kwarg_name -> column_name
@tracer.trace_async(promote={"user_query": "agent_input_query"})
Examples
--------
To trace a regular async function:
>>> @tracer.trace_async()
>>> async def main(user_query: str) -> str:
>>> context = retrieve_context(user_query)
>>> answer = generate_answer(user_query, context)
>>> return answer
To trace an async generator function:
>>> @tracer.trace_async()
>>> async def stream_response(query: str):
>>> async for chunk in openai_client.chat.completions.create(...):
>>> yield chunk.choices[0].delta.content
"""
def decorator(func):
func_signature = inspect.signature(func)
if step_kwargs.get("name") is None:
step_kwargs["name"] = func.__name__
step_name = step_kwargs["name"]
if asyncio.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):
# Check if it's specifically an async generator function
if inspect.isasyncgenfunction(func):
# For async generators, use class-based approach to delay trace creation
# until actual iteration begins (not when generator object is created)
@wraps(func)
def async_generator_wrapper(*func_args, **func_kwargs):
class TracedAsyncGenerator:
def __init__(self):
self._original_gen = None
self._step = None
self._is_root_step = False
self._token = None
self._output_chunks = []
self._trace_initialized = False
def __aiter__(self):
return self
async def __anext__(self):
# Initialize tracing on first iteration only
if not self._trace_initialized:
self._original_gen = func(*func_args, **func_kwargs)
self._step, self._is_root_step, self._token = (
_create_and_initialize_step(
step_name=step_name,
step_type=enums.StepType.USER_CALL,
inputs=None,
output=None,
metadata=None,
)
)
self._inputs = _extract_function_inputs(
func_signature=func_signature,
func_args=func_args,
func_kwargs=func_kwargs,
context_kwarg=context_kwarg,
question_kwarg=question_kwarg,
)
_apply_promote_kwargs(self._inputs, promote)
self._trace_initialized = True
try:
chunk = await self._original_gen.__anext__()
self._output_chunks.append(chunk)
return chunk
except StopAsyncIteration:
# Finalize trace when generator is exhausted
output = _join_output_chunks(self._output_chunks)
_finalize_async_generator_step(
step=self._step,
token=self._token,
is_root_step=self._is_root_step,
step_name=step_name,
inputs=self._inputs,
output=output,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
raise
except Exception as exc:
# Handle exceptions
if self._step:
_log_step_exception(self._step, exc)
output = _join_output_chunks(self._output_chunks)
_finalize_async_generator_step(
step=self._step,
token=self._token,
is_root_step=self._is_root_step,
step_name=step_name,
inputs=self._inputs,
output=output,
inference_pipeline_id=inference_pipeline_id,
on_flush_failure=on_flush_failure,
)
raise
return TracedAsyncGenerator()
return async_generator_wrapper
else:
# Create wrapper for regular async functions
@wraps(func)
async def async_function_wrapper(*func_args, **func_kwargs):
with create_step(
*step_args,
inference_pipeline_id=inference_pipeline_id,
**step_kwargs,
) as step:
output = exception = None
guardrail_metadata = {}
try:
# Apply promote / input guardrails if provided
if promote or guardrails:
try:
inputs = _extract_function_inputs(
func_signature=func_signature,
func_args=func_args,
func_kwargs=func_kwargs,
context_kwarg=context_kwarg,
question_kwarg=question_kwarg,
)
_apply_promote_kwargs(inputs, promote)
if guardrails:
# Process inputs through guardrails
modified_inputs, input_metadata = (
_apply_input_guardrails(
guardrails,
inputs,
)
)
guardrail_metadata.update(input_metadata)
# Execute function with potentially modified inputs
if modified_inputs != inputs:
# Reconstruct function arguments from modified inputs
bound = func_signature.bind(
*func_args, **func_kwargs
)