Spaces:
Paused

File size: 15,411 Bytes
ab07817
 
 
 
 
 
 
 
 
 
 
f826d18
 
 
 
 
 
f01e743
 
 
 
f826d18
 
 
 
f01e743
ab07817
f01e743
ab07817
 
f826d18
ab07817
 
 
 
 
 
 
f826d18
ab07817
f826d18
ab07817
f826d18
 
ab07817
 
 
f826d18
ab07817
 
 
 
 
 
 
 
f01e743
 
 
 
 
 
 
ab07817
 
 
 
 
 
 
f01e743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f826d18
ab07817
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f826d18
 
ab07817
 
f826d18
 
 
ab07817
f826d18
 
ab07817
f826d18
 
 
 
ab07817
 
 
 
 
 
 
 
f826d18
ab07817
 
 
f01e743
 
f826d18
 
 
 
ab07817
 
f01e743
 
ab07817
 
 
 
 
 
 
 
 
f01e743
 
f826d18
 
 
 
 
f01e743
f826d18
 
 
 
 
 
 
 
 
 
 
 
ab07817
 
 
 
 
 
f826d18
ab07817
f826d18
 
 
 
 
 
ab07817
 
 
 
 
 
 
f826d18
ab07817
 
 
 
 
 
f826d18
 
 
 
 
 
ab07817
f826d18
 
 
 
 
 
 
 
 
 
 
ab07817
 
 
 
 
 
f826d18
 
 
 
 
 
 
ab07817
 
 
f826d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab07817
f01e743
 
ab07817
 
f01e743
ab07817
 
 
 
f826d18
 
 
 
ab07817
f826d18
ab07817
f826d18
 
 
 
f01e743
 
ab07817
 
 
 
 
 
 
 
 
 
f826d18
ab07817
 
 
f01e743
f826d18
 
 
f01e743
f826d18
 
 
 
 
ab07817
 
 
f01e743
f826d18
ab07817
 
 
 
 
f826d18
ab07817
 
 
 
 
 
 
 
 
f826d18
 
 
ab07817
f826d18
 
 
 
 
ab07817
 
 
 
 
f826d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab07817
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
"""
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()}]