|
| 1 | +from functools import wraps |
| 2 | + |
| 3 | +import sentry_sdk.utils |
| 4 | +from sentry_sdk import start_span |
| 5 | +from sentry_sdk.tracing import Span |
| 6 | +from sentry_sdk.utils import ContextVar |
| 7 | +from sentry_sdk._types import TYPE_CHECKING |
| 8 | + |
| 9 | +if TYPE_CHECKING: |
| 10 | + from typing import Optional, Callable, Any |
| 11 | + |
| 12 | +_ai_pipeline_name = ContextVar("ai_pipeline_name", default=None) |
| 13 | + |
| 14 | + |
| 15 | +def set_ai_pipeline_name(name): |
| 16 | + # type: (Optional[str]) -> None |
| 17 | + _ai_pipeline_name.set(name) |
| 18 | + |
| 19 | + |
| 20 | +def get_ai_pipeline_name(): |
| 21 | + # type: () -> Optional[str] |
| 22 | + return _ai_pipeline_name.get() |
| 23 | + |
| 24 | + |
| 25 | +def ai_track(description, **span_kwargs): |
| 26 | + # type: (str, Any) -> Callable[..., Any] |
| 27 | + def decorator(f): |
| 28 | + # type: (Callable[..., Any]) -> Callable[..., Any] |
| 29 | + @wraps(f) |
| 30 | + def wrapped(*args, **kwargs): |
| 31 | + # type: (Any, Any) -> Any |
| 32 | + curr_pipeline = _ai_pipeline_name.get() |
| 33 | + op = span_kwargs.get("op", "ai.run" if curr_pipeline else "ai.pipeline") |
| 34 | + with start_span(description=description, op=op, **span_kwargs) as span: |
| 35 | + if curr_pipeline: |
| 36 | + span.set_data("ai.pipeline.name", curr_pipeline) |
| 37 | + return f(*args, **kwargs) |
| 38 | + else: |
| 39 | + _ai_pipeline_name.set(description) |
| 40 | + try: |
| 41 | + res = f(*args, **kwargs) |
| 42 | + except Exception as e: |
| 43 | + event, hint = sentry_sdk.utils.event_from_exception( |
| 44 | + e, |
| 45 | + client_options=sentry_sdk.get_client().options, |
| 46 | + mechanism={"type": "ai_monitoring", "handled": False}, |
| 47 | + ) |
| 48 | + sentry_sdk.capture_event(event, hint=hint) |
| 49 | + raise e from None |
| 50 | + finally: |
| 51 | + _ai_pipeline_name.set(None) |
| 52 | + return res |
| 53 | + |
| 54 | + return wrapped |
| 55 | + |
| 56 | + return decorator |
| 57 | + |
| 58 | + |
| 59 | +def record_token_usage( |
| 60 | + span, prompt_tokens=None, completion_tokens=None, total_tokens=None |
| 61 | +): |
| 62 | + # type: (Span, Optional[int], Optional[int], Optional[int]) -> None |
| 63 | + ai_pipeline_name = get_ai_pipeline_name() |
| 64 | + if ai_pipeline_name: |
| 65 | + span.set_data("ai.pipeline.name", ai_pipeline_name) |
| 66 | + if prompt_tokens is not None: |
| 67 | + span.set_measurement("ai_prompt_tokens_used", value=prompt_tokens) |
| 68 | + if completion_tokens is not None: |
| 69 | + span.set_measurement("ai_completion_tokens_used", value=completion_tokens) |
| 70 | + if ( |
| 71 | + total_tokens is None |
| 72 | + and prompt_tokens is not None |
| 73 | + and completion_tokens is not None |
| 74 | + ): |
| 75 | + total_tokens = prompt_tokens + completion_tokens |
| 76 | + if total_tokens is not None: |
| 77 | + span.set_measurement("ai_total_tokens_used", total_tokens) |
0 commit comments