Download puter_provider.py from mgokg/puter: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/spaces/mgokg/puter/resolve/main/puter_provider.py
- Command line
-
hf download hf://spaces/mgokg/puter/puter_provider.py
-
curl -L -o puter_provider.py https://huggingface.co/spaces/mgokg/puter/resolve/main/puter_provider.py
15.4 kB
| """ | |
| LiteLLM custom provider "puter". | |
| Nutzung: litellm.completion(model="puter/gpt-4o-mini", messages=[...]) | |
| Authentifizierung (Reihenfolge): | |
| 1. api_key=... im litellm-Aufruf (Puter Auth-Token, z.B. aus dem UI) | |
| 2. Umgebungsvariable PUTER_AUTH_TOKEN (HF Space Secret) | |
| Das Token ist der Bearer-Token deines Puter-Accounts (Cookie `puter_auth_token` | |
| bzw. localStorage `puter.auth.token.v2`). Es verbraucht DEIN Puter-Kontingent. | |
| Treiber: Puter nutzt heute den einheitlichen Treiber "ai-chat" (er wählt den | |
| Provider anhand der Modell-ID). Die alten Namen (openai-completion, claude, ...) | |
| werden nur noch als Fallback probiert, falls "ai-chat" mit 404 antwortet. | |
| Explizit geht auch "claude:claude-sonnet-4". | |
| Web-Suche: Puter unterstützt das Tool {"type": "web_search"} (vgl. puter.ai.chat | |
| mit tools=[{type:"web_search"}]). Aktivierbar pro Request über set_web_search(True) | |
| bzw. global über die Env-Variable PUTER_WEB_SEARCH=1. | |
| Env-Optionen: | |
| PUTER_API_URL (Default https://api.puter.com/drivers/call) | |
| PUTER_UPSTREAM_STREAM =1 -> echtes Streaming von Puter (experimentell). | |
| Default: Puter nicht-streamend fragen, Ergebnis als Chunk ausliefern. | |
| PUTER_WEB_SEARCH =1 -> Web-Suche standardmäßig für alle Requests aktivieren. | |
| """ | |
| import contextvars | |
| import json | |
| import os | |
| from typing import Any, Dict, Iterator, List, Optional, Tuple | |
| import httpx | |
| import litellm | |
| from litellm import CustomLLM | |
| from litellm.types.utils import GenericStreamingChunk, ModelResponse, Usage | |
| PUTER_URL = os.getenv("PUTER_API_URL", "https://api.puter.com/drivers/call") | |
| MODELS_URL = os.getenv("PUTER_MODELS_URL", "https://api.puter.com/puterai/chat/models/details") | |
| TIMEOUT = httpx.Timeout(120.0, connect=15.0) | |
| UPSTREAM_STREAM = os.getenv("PUTER_UPSTREAM_STREAM") == "1" | |
| PRIMARY_DRIVER = "ai-chat" | |
| LEGACY_DRIVERS = { | |
| "openai-completion", "claude", "gemini", "xai", "deepseek", | |
| "mistral", "openrouter", "together-ai", | |
| } | |
| _LEGACY_PREFIX = [ | |
| (("gpt", "o1", "o3", "o4", "chatgpt"), "openai-completion"), | |
| (("claude",), "claude"), | |
| (("gemini",), "gemini"), | |
| (("grok",), "xai"), | |
| (("deepseek",), "deepseek"), | |
| (("mistral", "codestral", "pixtral", "ministral"), "mistral"), | |
| ] | |
| # Web-Suche pro Request (contextvar, damit es bei parallelen Gradio-Requests | |
| # nicht durcheinandergeht). None = kein Override -> Env PUTER_WEB_SEARCH zieht. | |
| _web_search_ctx: "contextvars.ContextVar[Optional[bool]]" = contextvars.ContextVar( | |
| "puter_web_search", default=None | |
| ) | |
| WEB_SEARCH_TOOL = {"type": "web_search"} | |
| class PuterError(Exception): | |
| def __init__(self, message: str, status_code: int = 500): | |
| super().__init__(message) | |
| self.status_code = status_code | |
| # ---------------------------------------------------------------- Web-Suche | |
| def set_web_search(enabled: Optional[bool]) -> None: | |
| """Web-Suche fuer die folgenden Requests im aktuellen Kontext (de)aktivieren. | |
| True -> web_search-Tool anhaengen. | |
| False -> web_search-Tool unterdruecken (auch wenn Env gesetzt ist). | |
| None -> Override aufheben (Env PUTER_WEB_SEARCH entscheidet). | |
| """ | |
| _web_search_ctx.set(None if enabled is None else bool(enabled)) | |
| def _web_search_enabled() -> bool: | |
| override = _web_search_ctx.get() | |
| if override is not None: | |
| return override | |
| return os.getenv("PUTER_WEB_SEARCH") == "1" | |
| def _normalize_tools(tools: Any) -> List[dict]: | |
| """OpenAI-/Puter-Tools tolerieren; web_search auf Puter-Format vereinheitlichen.""" | |
| if not isinstance(tools, (list, tuple)): | |
| return [] | |
| out: List[dict] = [] | |
| for t in tools: | |
| if not isinstance(t, dict): | |
| continue | |
| if "web_search" in str(t.get("type", "")): | |
| out.append(dict(WEB_SEARCH_TOOL)) | |
| else: | |
| out.append(t) | |
| return out | |
| def _resolve_tools(optional_params: Optional[dict]) -> Optional[list]: | |
| tools = _normalize_tools((optional_params or {}).get("tools")) | |
| if _web_search_enabled() and not any(t.get("type") == "web_search" for t in tools): | |
| tools.append(dict(WEB_SEARCH_TOOL)) | |
| return tools or None | |
| # ---------------------------------------------------------------- Auth / Routing | |
| def _clean_token(token: Optional[str]) -> str: | |
| t = (token or "").strip().strip('"').strip("'") | |
| if t.lower().startswith("bearer "): | |
| t = t[7:].strip() | |
| return t | |
| def _resolve_token(api_key: Optional[str]) -> str: | |
| token = _clean_token(api_key) or _clean_token(os.getenv("PUTER_AUTH_TOKEN")) | |
| if not token: | |
| raise PuterError( | |
| "Kein Puter Auth-Token. Setze PUTER_AUTH_TOKEN (Space Secret) " | |
| "oder übergib api_key=...", | |
| 401, | |
| ) | |
| return token | |
| def _candidates(model: str) -> List[Tuple[str, str]]: | |
| """Liste von (driver, modell), die der Reihe nach probiert werden.""" | |
| if ":" in model: | |
| head, rest = model.split(":", 1) | |
| if head == PRIMARY_DRIVER or head in LEGACY_DRIVERS: | |
| return [(head, rest)] | |
| out = [(PRIMARY_DRIVER, model)] | |
| low = model.lower() | |
| legacy = "openrouter" | |
| for prefixes, driver in _LEGACY_PREFIX: | |
| if low.startswith(prefixes): | |
| legacy = driver | |
| break | |
| out.append((legacy, model)) | |
| return out | |
| def _headers(token: str) -> Dict[str, str]: | |
| return { | |
| "Authorization": f"Bearer {token}", | |
| "Content-Type": "application/json;charset=UTF-8", | |
| "Origin": "https://puter.com", | |
| "Referer": "https://puter.com/", | |
| "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) puter-litellm/1.1", | |
| } | |
| def _payload(driver: str, model: str, messages: List[dict], opt: dict, stream: bool, | |
| tools: Optional[list] = None) -> dict: | |
| args: Dict[str, Any] = {"messages": messages, "model": model, "stream": stream} | |
| if opt.get("temperature") is not None: | |
| args["temperature"] = opt["temperature"] | |
| max_tokens = opt.get("max_tokens") or opt.get("max_completion_tokens") | |
| if max_tokens: | |
| args["max_tokens"] = max_tokens | |
| if tools: | |
| args["tools"] = tools | |
| return { | |
| "interface": "puter-chat-completion", | |
| "driver": driver, | |
| "test_mode": False, | |
| "method": "complete", | |
| "args": args, | |
| } | |
| def _send(client: httpx.Client, token: str, model: str, messages: list, opt: dict, stream: bool, | |
| tools: Optional[list] = None): | |
| """Schickt den Request; bei 404 (Driver unbekannt) wird der nächste Kandidat probiert.""" | |
| last = None | |
| for driver, m in _candidates(model): | |
| req = client.build_request( | |
| "POST", PUTER_URL, headers=_headers(token), | |
| json=_payload(driver, m, messages, opt, stream, tools), | |
| ) | |
| resp = client.send(req, stream=stream) | |
| if resp.status_code == 404: | |
| resp.read() | |
| last = resp | |
| continue | |
| return resp | |
| return last | |
| # ---------------------------------------------------------------- Parsing / Fehler | |
| def _raise_for_error(obj: Any) -> None: | |
| """Puter meldet Fehler teils mit HTTP 200 + {"success": false, "error": {...}}.""" | |
| if isinstance(obj, dict) and obj.get("success") is False: | |
| err = obj.get("error") or {} | |
| if isinstance(err, dict): | |
| code = err.get("code") or err.get("message") or "unknown_error" | |
| msg = err.get("message") or str(err) | |
| delegate = err.get("delegate") | |
| else: | |
| code, msg, delegate = "error", str(err), None | |
| if delegate == "usage-limited-chat" or "insufficient" in str(code) or "usage" in str(code): | |
| raise PuterError(f"Puter-Kontingent/Guthaben aufgebraucht ({code}): {msg}", 402) | |
| if code in {"token_auth_failed", "token_missing", "forbidden"}: | |
| raise PuterError(f"Puter: Token ungültig ({code}): {msg}", 401) | |
| raise PuterError(f"Puter: {code} – {msg}", 500) | |
| def _content_to_text(content: Any) -> str: | |
| if content is None: | |
| return "" | |
| if isinstance(content, str): | |
| return content | |
| if isinstance(content, list): # [{"type":"text","text":"..."}] | |
| return "".join( | |
| p.get("text", "") for p in content if isinstance(p, dict) and p.get("type", "text") == "text" | |
| ) | |
| return str(content) | |
| def _extract_message_text(data: Any) -> str: | |
| """Toleriert: result.message.content | result.choices[0].message.content | result.content | str.""" | |
| if isinstance(data, str): | |
| return data | |
| if not isinstance(data, dict): | |
| return "" | |
| result = data.get("result", data) | |
| if isinstance(result, str): | |
| return result | |
| if not isinstance(result, dict): | |
| return "" | |
| if isinstance(result.get("choices"), list) and result["choices"]: | |
| ch = result["choices"][0] or {} | |
| return _content_to_text((ch.get("message") or ch.get("delta") or {}).get("content")) | |
| msg = result.get("message", result) | |
| if isinstance(msg, dict): | |
| return _content_to_text(msg.get("content")) | |
| return _content_to_text(msg) | |
| def _http_error(resp: httpx.Response) -> PuterError: | |
| body = resp.text[:300] | |
| if resp.status_code in (401, 403): | |
| return PuterError( | |
| f"Puter lehnt das Token ab (HTTP {resp.status_code}). Abgelaufen? Neu aus dem Cookie holen. {body}", 401) | |
| if resp.status_code == 404: | |
| return PuterError( | |
| f"Puter HTTP 404 (Driver/Modell nicht gefunden). Prüfe die Modell-ID bzw. probiere " | |
| f"'driver:modell'. Antwort: {body}", 404) | |
| if resp.status_code == 429: | |
| return PuterError(f"Puter Rate-Limit (HTTP 429), kurz warten. {body}", 429) | |
| return PuterError(f"Puter HTTP {resp.status_code}: {body}", resp.status_code) | |
| def _chunk(text: str, index: int, finished: bool = False) -> GenericStreamingChunk: | |
| return { | |
| "text": text, | |
| "is_finished": finished, | |
| "finish_reason": "stop" if finished else "", | |
| "usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0}, | |
| "index": index, | |
| "tool_use": None, | |
| } | |
| def _line_text(obj: dict) -> str: | |
| """Text aus einer Streaming-Zeile (NDJSON {"type":"text"} oder OpenAI-Delta).""" | |
| if obj.get("type") == "text": | |
| return obj.get("text") or "" | |
| if isinstance(obj.get("choices"), list) and obj["choices"]: | |
| return _content_to_text(((obj["choices"][0] or {}).get("delta") or {}).get("content")) | |
| return "" | |
| # ---------------------------------------------------------------- Provider | |
| class PuterLLM(CustomLLM): | |
| def _complete_text(self, token: str, model: str, messages: list, opt: dict, | |
| tools: Optional[list] = None) -> str: | |
| try: | |
| with httpx.Client(timeout=TIMEOUT) as client: | |
| resp = _send(client, token, model, messages, opt, stream=False, tools=tools) | |
| except httpx.HTTPError as e: | |
| raise PuterError(f"Verbindung zu Puter fehlgeschlagen: {e}", 502) | |
| if resp.status_code >= 400: | |
| raise _http_error(resp) | |
| try: | |
| data = resp.json() | |
| except ValueError: | |
| raise PuterError(f"Puter: keine JSON-Antwort: {resp.text[:200]}", 502) | |
| _raise_for_error(data) | |
| return _extract_message_text(data) | |
| # --- non-streaming --- | |
| def completion(self, model: str, messages: list, model_response: ModelResponse, | |
| optional_params: dict, api_key: Optional[str] = None, **kwargs) -> ModelResponse: | |
| token = _resolve_token(api_key or (kwargs.get("litellm_params") or {}).get("api_key")) | |
| tools = _resolve_tools(optional_params) | |
| text = self._complete_text(token, model, messages, optional_params, tools) | |
| model_response.choices[0].message.content = text # type: ignore | |
| model_response.choices[0].finish_reason = "stop" # type: ignore | |
| model_response.model = model | |
| model_response.usage = Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0) # type: ignore | |
| return model_response | |
| async def acompletion(self, *args, **kwargs) -> ModelResponse: | |
| import asyncio | |
| return await asyncio.to_thread(self.completion, *args, **kwargs) | |
| # --- streaming --- | |
| def streaming(self, model: str, messages: list, optional_params: dict, | |
| api_key: Optional[str] = None, **kwargs) -> Iterator[GenericStreamingChunk]: | |
| token = _resolve_token(api_key or (kwargs.get("litellm_params") or {}).get("api_key")) | |
| tools = _resolve_tools(optional_params) | |
| if not UPSTREAM_STREAM: | |
| # Robust: Puter nicht-streamend fragen, Antwort als ein Chunk ausliefern. | |
| text = self._complete_text(token, model, messages, optional_params, tools) | |
| if text: | |
| yield _chunk(text, 0) | |
| yield _chunk("", 1, finished=True) | |
| return | |
| idx = 0 | |
| try: | |
| with httpx.Client(timeout=TIMEOUT) as client: | |
| resp = _send(client, token, model, messages, optional_params, stream=True, tools=tools) | |
| try: | |
| if resp.status_code >= 400: | |
| resp.read() | |
| raise _http_error(resp) | |
| for line in resp.iter_lines(): | |
| line = line.strip() | |
| if line.startswith("data:"): | |
| line = line[5:].strip() | |
| if not line or line == "[DONE]": | |
| continue | |
| try: | |
| obj = json.loads(line) | |
| except json.JSONDecodeError: | |
| continue | |
| if not isinstance(obj, dict): | |
| continue | |
| _raise_for_error(obj) | |
| text = _line_text(obj) | |
| if not text and "result" in obj and idx == 0: | |
| text = _extract_message_text(obj) | |
| if text: | |
| yield _chunk(text, idx) | |
| idx += 1 | |
| finally: | |
| resp.close() | |
| except httpx.HTTPError as e: | |
| raise PuterError(f"Verbindung zu Puter fehlgeschlagen: {e}", 502) | |
| yield _chunk("", idx, finished=True) | |
| def list_models(token: Optional[str] = None) -> List[str]: | |
| """Modell-IDs von Puter holen (Format toleriert); bei Fehler leere Liste.""" | |
| try: | |
| headers = _headers(_resolve_token(token)) if (token or os.getenv("PUTER_AUTH_TOKEN")) else {} | |
| r = httpx.get(MODELS_URL, headers=headers, timeout=10.0) | |
| if r.status_code != 200: | |
| return [] | |
| data = r.json() | |
| if isinstance(data, dict): | |
| data = data.get("models") or data.get("result") or data.get("data") or [] | |
| ids = [] | |
| for it in data if isinstance(data, list) else []: | |
| if isinstance(it, str): | |
| ids.append(it) | |
| elif isinstance(it, dict): | |
| mid = it.get("id") or it.get("name") or it.get("model") | |
| if isinstance(mid, str): | |
| ids.append(mid) | |
| return sorted(set(ids)) | |
| except Exception: | |
| return [] | |
| def register() -> None: | |
| litellm.custom_provider_map = [ | |
| p for p in (litellm.custom_provider_map or []) if p.get("provider") != "puter" | |
| ] + [{"provider": "puter", "custom_handler": PuterLLM()}] |