-
Notifications
You must be signed in to change notification settings - Fork 614
Expand file tree
/
Copy pathutils.py
More file actions
35 lines (25 loc) · 1.18 KB
/
utils.py
File metadata and controls
35 lines (25 loc) · 1.18 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
"""Utility functions for PydanticAI span instrumentation."""
import sentry_sdk
from sentry_sdk.consts import SPANDATA
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Union, Dict, Any, List
from pydantic_ai.usage import RequestUsage, RunUsage # type: ignore
def _set_usage_data(
span: "sentry_sdk.tracing.Span", usage: "Union[RequestUsage, RunUsage]"
) -> None:
"""Set token usage data on a span.
This function works with both RequestUsage (single request) and
RunUsage (agent run) objects from pydantic_ai.
Args:
span: The Sentry span to set data on.
usage: RequestUsage or RunUsage object containing token usage information.
"""
if usage is None:
return
if hasattr(usage, "input_tokens") and usage.input_tokens is not None:
span.set_data(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens)
if hasattr(usage, "output_tokens") and usage.output_tokens is not None:
span.set_data(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens)
if hasattr(usage, "total_tokens") and usage.total_tokens is not None:
span.set_data(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, usage.total_tokens)