Download eval/local_intelligence/providers/hf.py from arach/training-lab: direct link, hf CLI and curl.
- Browser
- Download file 2.61 kB
-
https://huggingface.co/arach/training-lab/resolve/main/eval/local_intelligence/providers/hf.py
- Command line
-
hf download hf://arach/training-lab/eval/local_intelligence/providers/hf.py
-
curl -L -o hf.py https://huggingface.co/arach/training-lab/resolve/main/eval/local_intelligence/providers/hf.py
2.61 kB
| from __future__ import annotations | |
| import json | |
| import os | |
| from pathlib import Path | |
| import time | |
| import urllib.request | |
| from .base import BaseProvider, ProviderResponse | |
| _TOKEN_KEYS = [ | |
| "HF_TOKEN", | |
| "HUGGINGFACE_TOKEN", | |
| "HUGGING_FACE_TOKEN", | |
| "HUGGING_FACE_HUB_TOKEN", | |
| "HF_API_TOKEN", | |
| ] | |
| _ENV_CANDIDATES = [ | |
| Path.cwd() / ".env.local", | |
| Path.cwd() / ".env", | |
| Path.home() / ".env.local", | |
| ] | |
| def _load_token_from_env_files() -> str | None: | |
| for env_path in _ENV_CANDIDATES: | |
| if not env_path.exists(): | |
| continue | |
| for line in env_path.read_text().splitlines(): | |
| stripped = line.strip() | |
| if not stripped or stripped.startswith("#") or "=" not in stripped: | |
| continue | |
| key, value = stripped.split("=", 1) | |
| key = key.strip() | |
| value = value.strip().strip('"').strip("'") | |
| if key in _TOKEN_KEYS and value: | |
| return value | |
| return None | |
| class HuggingFaceProvider(BaseProvider): | |
| name = "hf" | |
| def __init__(self, model_name: str | None, token: str | None = None, timeout_seconds: int = 90): | |
| if not model_name: | |
| raise ValueError("HF provider requires --model.") | |
| self.model_name = model_name | |
| self.token = token or next((os.environ.get(key) for key in _TOKEN_KEYS if os.environ.get(key)), None) or _load_token_from_env_files() | |
| self.timeout_seconds = timeout_seconds | |
| def generate(self, card: dict, messages: list[dict[str, str]], prompt_text: str) -> ProviderResponse: | |
| url = "https://router.huggingface.co/v1/chat/completions" | |
| body = { | |
| "model": self.model_name, | |
| "messages": messages, | |
| "temperature": 0, | |
| "response_format": {"type": "json_object"}, | |
| "stream": False, | |
| } | |
| headers = {"Content-Type": "application/json"} | |
| if self.token: | |
| headers["Authorization"] = f"Bearer {self.token}" | |
| req = urllib.request.Request( | |
| url, | |
| data=json.dumps(body).encode("utf-8"), | |
| headers=headers, | |
| method="POST", | |
| ) | |
| start = time.perf_counter() | |
| with urllib.request.urlopen(req, timeout=self.timeout_seconds) as resp: | |
| payload = json.loads(resp.read().decode("utf-8")) | |
| latency_ms = (time.perf_counter() - start) * 1000 | |
| content = payload["choices"][0]["message"]["content"] | |
| return ProviderResponse( | |
| raw_text=content.strip(), | |
| latency_ms=latency_ms, | |
| metadata={"model": self.model_name}, | |
| ) | |