|
| 1 | +import inspect |
1 | 2 | from functools import wraps
|
2 | 3 |
|
3 | 4 | import sentry_sdk.utils
|
@@ -26,8 +27,7 @@ def ai_track(description, **span_kwargs):
|
26 | 27 | # type: (str, Any) -> Callable[..., Any]
|
27 | 28 | def decorator(f):
|
28 | 29 | # type: (Callable[..., Any]) -> Callable[..., Any]
|
29 |
| - @wraps(f) |
30 |
| - def wrapped(*args, **kwargs): |
| 30 | + def sync_wrapped(*args, **kwargs): |
31 | 31 | # type: (Any, Any) -> Any
|
32 | 32 | curr_pipeline = _ai_pipeline_name.get()
|
33 | 33 | op = span_kwargs.get("op", "ai.run" if curr_pipeline else "ai.pipeline")
|
@@ -56,7 +56,39 @@ def wrapped(*args, **kwargs):
|
56 | 56 | _ai_pipeline_name.set(None)
|
57 | 57 | return res
|
58 | 58 |
|
59 |
| - return wrapped |
| 59 | + async def async_wrapped(*args, **kwargs): |
| 60 | + # type: (Any, Any) -> Any |
| 61 | + curr_pipeline = _ai_pipeline_name.get() |
| 62 | + op = span_kwargs.get("op", "ai.run" if curr_pipeline else "ai.pipeline") |
| 63 | + |
| 64 | + with start_span(description=description, op=op, **span_kwargs) as span: |
| 65 | + for k, v in kwargs.pop("sentry_tags", {}).items(): |
| 66 | + span.set_tag(k, v) |
| 67 | + for k, v in kwargs.pop("sentry_data", {}).items(): |
| 68 | + span.set_data(k, v) |
| 69 | + if curr_pipeline: |
| 70 | + span.set_data("ai.pipeline.name", curr_pipeline) |
| 71 | + return await f(*args, **kwargs) |
| 72 | + else: |
| 73 | + _ai_pipeline_name.set(description) |
| 74 | + try: |
| 75 | + res = await f(*args, **kwargs) |
| 76 | + except Exception as e: |
| 77 | + event, hint = sentry_sdk.utils.event_from_exception( |
| 78 | + e, |
| 79 | + client_options=sentry_sdk.get_client().options, |
| 80 | + mechanism={"type": "ai_monitoring", "handled": False}, |
| 81 | + ) |
| 82 | + sentry_sdk.capture_event(event, hint=hint) |
| 83 | + raise e from None |
| 84 | + finally: |
| 85 | + _ai_pipeline_name.set(None) |
| 86 | + return res |
| 87 | + |
| 88 | + if inspect.iscoroutinefunction(f): |
| 89 | + return wraps(f)(async_wrapped) |
| 90 | + else: |
| 91 | + return wraps(f)(sync_wrapped) |
60 | 92 |
|
61 | 93 | return decorator
|
62 | 94 |
|
|
0 commit comments