追踪 Token 使用量(就像手机流量统计)。 对应源码: runtime/src/usage.rs
| 190 | # ====================================================================== |
| 191 | |
| 192 | class UsageTracker: |
| 193 | """ |
| 194 | 追踪 Token 使用量(就像手机流量统计)。 |
| 195 | |
| 196 | 对应源码: runtime/src/usage.rs |
| 197 | """ |
| 198 | def __init__(self): |
| 199 | self.turns = 0 |
| 200 | self._cumulative_input = 0 |
| 201 | self._cumulative_output = 0 |
| 202 | |
| 203 | def record(self, usage: TokenUsage): |
| 204 | self.turns += 1 |
| 205 | self._cumulative_input += usage.input_tokens |
| 206 | self._cumulative_output += usage.output_tokens |
| 207 | |
| 208 | def cumulative_usage(self) -> TokenUsage: |
| 209 | return TokenUsage( |
| 210 | input_tokens=self._cumulative_input, |
| 211 | output_tokens=self._cumulative_output, |
| 212 | ) |
| 213 | |
| 214 | def summary(self) -> str: |
| 215 | total = self._cumulative_input + self._cumulative_output |
| 216 | return f"turns={self.turns}, input={self._cumulative_input}, output={self._cumulative_output}, total={total}" |
| 217 | |
| 218 | |
| 219 | # ====================================================================== |