Spaces:
Sleeping
Sleeping
Download scratch_vision/core/token_usage.py from prthm11/scratch-vision-game: direct link, hf CLI and curl.
- Browser
- Download file 3.05 kB
-
https://huggingface.co/spaces/prthm11/scratch-vision-game/resolve/main/scratch_vision/core/token_usage.py
- Command line
-
hf download hf://spaces/prthm11/scratch-vision-game/scratch_vision/core/token_usage.py
-
curl -L -o token_usage.py https://huggingface.co/spaces/prthm11/scratch-vision-game/resolve/main/scratch_vision/core/token_usage.py
3.05 kB
| """Per-project LLM token accounting, written to generated_projects/<id>/token_usage.json.""" | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict | |
| from ..config import get_settings | |
| logger = logging.getLogger(__name__) | |
| def _first_int(source: dict, *keys: str) -> int: | |
| for key in keys: | |
| value = source.get(key) | |
| if value: | |
| return int(value) | |
| return 0 | |
| def extract_token_usage(response: Any) -> Dict[str, int]: | |
| usage = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0} | |
| if response is None: | |
| return usage | |
| # 1. LangChain AIMessage.usage_metadata ; 2. provider response_metadata | |
| source = getattr(response, "usage_metadata", None) | |
| if not isinstance(source, dict): | |
| metadata = getattr(response, "response_metadata", None) | |
| if isinstance(metadata, dict): | |
| source = metadata.get("token_usage") or metadata.get("usage") | |
| if not isinstance(source, dict): | |
| return usage | |
| usage["input_tokens"] = _first_int(source, "input_tokens", "prompt_tokens") | |
| usage["output_tokens"] = _first_int(source, "output_tokens", "completion_tokens") | |
| usage["total_tokens"] = _first_int(source, "total_tokens") or usage["input_tokens"] + usage["output_tokens"] | |
| return usage | |
| def save_token_usage(project_id: str, call_name: str, response: Any) -> None: | |
| """Append one call's usage and refresh totals. Never raises: accounting must not break a request.""" | |
| try: | |
| settings = get_settings() | |
| usage = extract_token_usage(response) | |
| project_dir = settings.generated_dir / project_id | |
| project_dir.mkdir(parents=True, exist_ok=True) | |
| token_file = project_dir / "token_usage.json" | |
| try: | |
| token_data = json.loads(token_file.read_text(encoding="utf-8")) if token_file.exists() else {} | |
| except (OSError, json.JSONDecodeError): | |
| token_data = {} | |
| calls = token_data.setdefault("calls", []) | |
| calls.append( | |
| { | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "call_name": call_name, | |
| "model": settings.llm_model, | |
| **usage, | |
| } | |
| ) | |
| token_data["summary"] = { | |
| "total_input_tokens": sum(c.get("input_tokens", 0) for c in calls), | |
| "total_output_tokens": sum(c.get("output_tokens", 0) for c in calls), | |
| "total_tokens": sum(c.get("total_tokens", 0) for c in calls), | |
| "total_llm_calls": len(calls), | |
| } | |
| token_file.write_text(json.dumps(token_data, indent=4), encoding="utf-8") | |
| logger.info( | |
| "Token usage [%s] project=%s input=%d output=%d total=%d", | |
| call_name, project_id, usage["input_tokens"], usage["output_tokens"], usage["total_tokens"], | |
| ) | |
| except Exception: | |
| logger.exception("Failed to save token usage for %s", call_name) | |