Skip to content

Commit e26abd6

Browse files
committed
feat: simplify adder
1 parent 6cc68f4 commit e26abd6

File tree

1 file changed

+7
-32
lines changed

1 file changed

+7
-32
lines changed

src/agents/usage.py

Lines changed: 7 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,6 @@
11
from dataclasses import dataclass, field
2-
from typing import TypeVar
32

43
from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails
5-
from pydantic import BaseModel
6-
7-
T = TypeVar("T", bound=BaseModel)
8-
9-
10-
def add_numeric_fields(current: T, other: T) -> T:
11-
"""
12-
Add numeric fields from other to current.
13-
"""
14-
clone = current.model_copy()
15-
for key, v1 in current.model_dump().items():
16-
v2 = getattr(other, key, 0)
17-
if isinstance(v1, (int, float)) and isinstance(v2, (int, float)):
18-
setattr(clone, key, (v1 or 0) + (v2 or 0))
19-
return clone
20-
21-
22-
def add_input_tokens_details(
23-
current: InputTokensDetails, other: InputTokensDetails
24-
) -> InputTokensDetails:
25-
return add_numeric_fields(current, other)
26-
27-
28-
def add_output_tokens_details(
29-
current: OutputTokensDetails, other: OutputTokensDetails
30-
) -> OutputTokensDetails:
31-
return add_numeric_fields(current, other)
324

335

346
@dataclass
@@ -59,9 +31,12 @@ def add(self, other: "Usage") -> None:
5931
self.input_tokens += other.input_tokens if other.input_tokens else 0
6032
self.output_tokens += other.output_tokens if other.output_tokens else 0
6133
self.total_tokens += other.total_tokens if other.total_tokens else 0
62-
self.input_tokens_details = add_input_tokens_details(
63-
self.input_tokens_details, other.input_tokens_details
34+
self.input_tokens_details = InputTokensDetails(
35+
cached_tokens=self.input_tokens_details.cached_tokens
36+
+ other.input_tokens_details.cached_tokens
6437
)
65-
self.output_tokens_details = add_output_tokens_details(
66-
self.output_tokens_details, other.output_tokens_details
38+
39+
self.output_tokens_details = OutputTokensDetails(
40+
reasoning_tokens=self.output_tokens_details.reasoning_tokens
41+
+ other.output_tokens_details.reasoning_tokens
6742
)

0 commit comments

Comments
 (0)