Download harness/usage.py from ASown/agent-iot: direct link, hf CLI and curl.
- Browser
- Download file 1.33 kB
-
https://huggingface.co/spaces/ASown/agent-iot/resolve/main/harness/usage.py
- Command line
-
hf download hf://spaces/ASown/agent-iot/harness/usage.py
-
curl -L -o usage.py https://huggingface.co/spaces/ASown/agent-iot/resolve/main/harness/usage.py
1.33 kB
| """ | |
| Đếm token mỗi lượt (như Claude Code). Thread-local để gom mọi lời gọi LLM của | |
| AGENT CHÍNH trong một lượt (ReAct loop, hoặc contextualize+route+chat/narrate của | |
| legacy) mà không phải đổi chữ ký hàm. | |
| Lưu ý: chỉ đếm các lời gọi của agent chính. Lời gọi LLM NỘI BỘ của tool (ví dụ | |
| verify-agent trong doc-find, plan-agent của CNC) chạy ở thread khác nên KHÔNG | |
| được cộng ở đây — con số là "token của agent chính", không phải toàn hoá đơn. | |
| """ | |
| from __future__ import annotations | |
| import threading | |
| _local = threading.local() | |
| def reset() -> None: | |
| _local.data = {"in": 0, "out": 0, "total": 0, "requests": 0} | |
| def add(run_usage) -> None: | |
| """Cộng usage từ một pydantic_ai RunUsage (property result.usage).""" | |
| d = getattr(_local, "data", None) | |
| if d is None: | |
| reset(); d = _local.data | |
| try: | |
| d["in"] += getattr(run_usage, "input_tokens", 0) or 0 | |
| d["out"] += getattr(run_usage, "output_tokens", 0) or 0 | |
| d["total"] += getattr(run_usage, "total_tokens", 0) or 0 | |
| d["requests"] += getattr(run_usage, "requests", 0) or 0 | |
| except Exception: | |
| pass | |
| def get() -> dict: | |
| return dict(getattr(_local, "data", None) or {"in": 0, "out": 0, "total": 0, "requests": 0}) | |