Skip to content

Commit a08fe82

Browse files
committed
feat: implemented class using InputTokenDetails, will revert for completions compatibility
1 parent 428c9a6 commit a08fe82

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/agents/usage.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,17 @@
11
from dataclasses import dataclass
2+
from typing import TypeVar
3+
4+
from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails
5+
6+
T = TypeVar("T", bound="InputTokensDetails | OutputTokensDetails")
7+
8+
9+
def add_numeric_fields(current: T, other: T) -> None:
10+
for field in current.__dataclass_fields__:
11+
v1 = getattr(current, field, 0)
12+
v2 = getattr(other, field, 0)
13+
if isinstance(v1, (int, float)) and isinstance(v2, (int, float)):
14+
setattr(current, field, (v1 or 0) + (v2 or 0))
215

316

417
@dataclass
@@ -9,9 +22,13 @@ class Usage:
922
input_tokens: int = 0
1023
"""Total input tokens sent, across all requests."""
1124

25+
input_tokens_details: InputTokensDetails = InputTokensDetails(cached_tokens=0)
26+
1227
output_tokens: int = 0
1328
"""Total output tokens received, across all requests."""
1429

30+
output_tokens_details: OutputTokensDetails = OutputTokensDetails(reasoning_tokens=0)
31+
1532
total_tokens: int = 0
1633
"""Total tokens sent and received, across all requests."""
1734

@@ -20,3 +37,5 @@ def add(self, other: "Usage") -> None:
2037
self.input_tokens += other.input_tokens if other.input_tokens else 0
2138
self.output_tokens += other.output_tokens if other.output_tokens else 0
2239
self.total_tokens += other.total_tokens if other.total_tokens else 0
40+
add_numeric_fields(self.input_tokens_details, other.input_tokens_details)
41+
add_numeric_fields(self.output_tokens_details, other.output_tokens_details)

0 commit comments

Comments
 (0)