Spaces:
Paused

mgokg commited on
Commit
f826d18
·
verified ·
1 Parent(s): d5e0121

Update puter_provider.py

Browse files
Files changed (1) hide show
  1. puter_provider.py +160 -62
puter_provider.py CHANGED
@@ -9,10 +9,20 @@ Authentifizierung (Reihenfolge):
9
 
10
  Das Token ist der Bearer-Token deines Puter-Accounts (Cookie `puter_auth_token`
11
  bzw. localStorage `puter.auth.token.v2`). Es verbraucht DEIN Puter-Kontingent.
 
 
 
 
 
 
 
 
 
 
12
  """
13
  import json
14
  import os
15
- from typing import Any, Dict, Iterator, List, Optional
16
 
17
  import httpx
18
  import litellm
@@ -20,16 +30,16 @@ from litellm import CustomLLM
20
  from litellm.types.utils import GenericStreamingChunk, ModelResponse, Usage
21
 
22
  PUTER_URL = os.getenv("PUTER_API_URL", "https://api.puter.com/drivers/call")
 
23
  TIMEOUT = httpx.Timeout(120.0, connect=15.0)
 
24
 
25
- # Puter-"Services" (= Provider hinter puter.ai.chat)
26
- KNOWN_DRIVERS = {
27
  "openai-completion", "claude", "gemini", "xai", "deepseek",
28
  "mistral", "openrouter", "together-ai",
29
  }
30
-
31
- # Heuristik: Modellname -> Driver. Explizit geht auch: "claude:claude-sonnet-4".
32
- _PREFIX_TO_DRIVER = [
33
  (("gpt", "o1", "o3", "o4", "chatgpt"), "openai-completion"),
34
  (("claude",), "claude"),
35
  (("gemini",), "gemini"),
@@ -45,6 +55,7 @@ class PuterError(Exception):
45
  self.status_code = status_code
46
 
47
 
 
48
  def _clean_token(token: Optional[str]) -> str:
49
  t = (token or "").strip().strip('"').strip("'")
50
  if t.lower().startswith("bearer "):
@@ -63,17 +74,21 @@ def _resolve_token(api_key: Optional[str]) -> str:
63
  return token
64
 
65
 
66
- def _resolve_driver(model: str) -> tuple[str, str]:
67
- """'claude:claude-sonnet-4' -> ('claude', 'claude-sonnet-4'); sonst Heuristik."""
68
  if ":" in model:
69
  head, rest = model.split(":", 1)
70
- if head in KNOWN_DRIVERS:
71
- return head, rest
 
72
  low = model.lower()
73
- for prefixes, driver in _PREFIX_TO_DRIVER:
 
74
  if low.startswith(prefixes):
75
- return driver, model
76
- return "openrouter", model # z.B. "meta-llama/llama-3.3-70b-instruct"
 
 
77
 
78
 
79
  def _headers(token: str) -> Dict[str, str]:
@@ -82,16 +97,15 @@ def _headers(token: str) -> Dict[str, str]:
82
  "Content-Type": "application/json;charset=UTF-8",
83
  "Origin": "https://puter.com",
84
  "Referer": "https://puter.com/",
85
- "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) puter-litellm/1.0",
86
  }
87
 
88
 
89
- def _payload(model: str, messages: List[dict], optional_params: dict, stream: bool) -> dict:
90
- driver, puter_model = _resolve_driver(model)
91
- args: Dict[str, Any] = {"messages": messages, "model": puter_model, "stream": stream}
92
- if optional_params.get("temperature") is not None:
93
- args["temperature"] = optional_params["temperature"]
94
- max_tokens = optional_params.get("max_tokens") or optional_params.get("max_completion_tokens")
95
  if max_tokens:
96
  args["max_tokens"] = max_tokens
97
  return {
@@ -103,19 +117,39 @@ def _payload(model: str, messages: List[dict], optional_params: dict, stream: bo
103
  }
104
 
105
 
106
- def _raise_for_error(obj: Any, status: int = 200) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  """Puter meldet Fehler teils mit HTTP 200 + {"success": false, "error": {...}}."""
108
  if isinstance(obj, dict) and obj.get("success") is False:
109
  err = obj.get("error") or {}
110
  if isinstance(err, dict):
111
  code = err.get("code") or err.get("message") or "unknown_error"
112
  msg = err.get("message") or str(err)
 
113
  else:
114
- code, msg = "error", str(err)
115
- http = 401 if code in {"token_auth_failed", "token_missing", "forbidden"} else (
116
- 402 if "insufficient" in str(code) or "usage" in str(code) else 500
117
- )
118
- raise PuterError(f"Puter: {code} – {msg}", http)
 
119
 
120
 
121
  def _content_to_text(content: Any) -> str:
@@ -123,46 +157,89 @@ def _content_to_text(content: Any) -> str:
123
  return ""
124
  if isinstance(content, str):
125
  return content
126
- if isinstance(content, list): # Claude: [{"type":"text","text":"..."}]
127
  return "".join(
128
  p.get("text", "") for p in content if isinstance(p, dict) and p.get("type", "text") == "text"
129
  )
130
  return str(content)
131
 
132
 
133
- def _extract_message_text(data: dict) -> str:
 
 
 
 
 
134
  result = data.get("result", data)
135
- msg = result.get("message", result) if isinstance(result, dict) else {}
136
- return _content_to_text(msg.get("content") if isinstance(msg, dict) else msg)
 
 
 
 
 
 
 
 
 
137
 
138
 
139
  def _http_error(resp: httpx.Response) -> PuterError:
140
  body = resp.text[:300]
141
  if resp.status_code in (401, 403):
142
  return PuterError(
143
- f"Puter lehnt das Token ab (HTTP {resp.status_code}). Abgelaufen? Neu aus dem Cookie holen. {body}",
144
- 401,
145
- )
 
 
 
 
146
  return PuterError(f"Puter HTTP {resp.status_code}: {body}", resp.status_code)
147
 
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  class PuterLLM(CustomLLM):
150
- # --- non-streaming ---
151
- def completion(self, model: str, messages: list, model_response: ModelResponse,
152
- optional_params: dict, api_key: Optional[str] = None, **kwargs) -> ModelResponse:
153
- token = _resolve_token(api_key or (kwargs.get("litellm_params") or {}).get("api_key"))
154
- payload = _payload(model, messages, optional_params, stream=False)
155
  try:
156
  with httpx.Client(timeout=TIMEOUT) as client:
157
- resp = client.post(PUTER_URL, headers=_headers(token), json=payload)
158
  except httpx.HTTPError as e:
159
  raise PuterError(f"Verbindung zu Puter fehlgeschlagen: {e}", 502)
160
  if resp.status_code >= 400:
161
  raise _http_error(resp)
162
- data = resp.json()
 
 
 
163
  _raise_for_error(data)
 
164
 
165
- text = _extract_message_text(data)
 
 
 
 
166
  model_response.choices[0].message.content = text # type: ignore
167
  model_response.choices[0].finish_reason = "stop" # type: ignore
168
  model_response.model = model
@@ -173,21 +250,30 @@ class PuterLLM(CustomLLM):
173
  import asyncio
174
  return await asyncio.to_thread(self.completion, *args, **kwargs)
175
 
176
- # --- streaming (NDJSON: {"type":"text","text":"..."} pro Zeile) ---
177
  def streaming(self, model: str, messages: list, optional_params: dict,
178
  api_key: Optional[str] = None, **kwargs) -> Iterator[GenericStreamingChunk]:
179
  token = _resolve_token(api_key or (kwargs.get("litellm_params") or {}).get("api_key"))
180
- payload = _payload(model, messages, optional_params, stream=True)
 
 
 
 
 
 
 
 
181
  idx = 0
182
  try:
183
  with httpx.Client(timeout=TIMEOUT) as client:
184
- with client.stream("POST", PUTER_URL, headers=_headers(token), json=payload) as resp:
 
185
  if resp.status_code >= 400:
186
  resp.read()
187
  raise _http_error(resp)
188
  for line in resp.iter_lines():
189
  line = line.strip()
190
- if line.startswith("data:"): # falls SSE
191
  line = line[5:].strip()
192
  if not line or line == "[DONE]":
193
  continue
@@ -195,31 +281,43 @@ class PuterLLM(CustomLLM):
195
  obj = json.loads(line)
196
  except json.JSONDecodeError:
197
  continue
198
- _raise_for_error(obj)
199
  if not isinstance(obj, dict):
200
  continue
201
- if obj.get("type") == "text" and obj.get("text"):
202
- yield _chunk(obj["text"], idx)
203
- idx += 1
204
- elif "result" in obj and idx == 0: # Driver ignorierte stream=True
205
  text = _extract_message_text(obj)
206
- if text:
207
- yield _chunk(text, idx)
208
- idx += 1
 
 
209
  except httpx.HTTPError as e:
210
  raise PuterError(f"Verbindung zu Puter fehlgeschlagen: {e}", 502)
211
  yield _chunk("", idx, finished=True)
212
 
213
 
214
- def _chunk(text: str, index: int, finished: bool = False) -> GenericStreamingChunk:
215
- return {
216
- "text": text,
217
- "is_finished": finished,
218
- "finish_reason": "stop" if finished else "",
219
- "usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0},
220
- "index": index,
221
- "tool_use": None,
222
- }
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
 
225
  def register() -> None:
 
9
 
10
  Das Token ist der Bearer-Token deines Puter-Accounts (Cookie `puter_auth_token`
11
  bzw. localStorage `puter.auth.token.v2`). Es verbraucht DEIN Puter-Kontingent.
12
+
13
+ Treiber: Puter nutzt heute den einheitlichen Treiber "ai-chat" (er wählt den
14
+ Provider anhand der Modell-ID). Die alten Namen (openai-completion, claude, ...)
15
+ werden nur noch als Fallback probiert, falls "ai-chat" mit 404 antwortet.
16
+ Explizit geht auch "claude:claude-sonnet-4".
17
+
18
+ Env-Optionen:
19
+ PUTER_API_URL (Default https://api.puter.com/drivers/call)
20
+ PUTER_UPSTREAM_STREAM =1 -> echtes Streaming von Puter (experimentell).
21
+ Default: Puter nicht-streamend fragen, Ergebnis als Chunk ausliefern.
22
  """
23
  import json
24
  import os
25
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
26
 
27
  import httpx
28
  import litellm
 
30
  from litellm.types.utils import GenericStreamingChunk, ModelResponse, Usage
31
 
32
  PUTER_URL = os.getenv("PUTER_API_URL", "https://api.puter.com/drivers/call")
33
+ MODELS_URL = os.getenv("PUTER_MODELS_URL", "https://api.puter.com/puterai/chat/models/details")
34
  TIMEOUT = httpx.Timeout(120.0, connect=15.0)
35
+ UPSTREAM_STREAM = os.getenv("PUTER_UPSTREAM_STREAM") == "1"
36
 
37
+ PRIMARY_DRIVER = "ai-chat"
38
+ LEGACY_DRIVERS = {
39
  "openai-completion", "claude", "gemini", "xai", "deepseek",
40
  "mistral", "openrouter", "together-ai",
41
  }
42
+ _LEGACY_PREFIX = [
 
 
43
  (("gpt", "o1", "o3", "o4", "chatgpt"), "openai-completion"),
44
  (("claude",), "claude"),
45
  (("gemini",), "gemini"),
 
55
  self.status_code = status_code
56
 
57
 
58
+ # ---------------------------------------------------------------- Auth / Routing
59
  def _clean_token(token: Optional[str]) -> str:
60
  t = (token or "").strip().strip('"').strip("'")
61
  if t.lower().startswith("bearer "):
 
74
  return token
75
 
76
 
77
+ def _candidates(model: str) -> List[Tuple[str, str]]:
78
+ """Liste von (driver, modell), die der Reihe nach probiert werden."""
79
  if ":" in model:
80
  head, rest = model.split(":", 1)
81
+ if head == PRIMARY_DRIVER or head in LEGACY_DRIVERS:
82
+ return [(head, rest)]
83
+ out = [(PRIMARY_DRIVER, model)]
84
  low = model.lower()
85
+ legacy = "openrouter"
86
+ for prefixes, driver in _LEGACY_PREFIX:
87
  if low.startswith(prefixes):
88
+ legacy = driver
89
+ break
90
+ out.append((legacy, model))
91
+ return out
92
 
93
 
94
  def _headers(token: str) -> Dict[str, str]:
 
97
  "Content-Type": "application/json;charset=UTF-8",
98
  "Origin": "https://puter.com",
99
  "Referer": "https://puter.com/",
100
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) puter-litellm/1.1",
101
  }
102
 
103
 
104
+ def _payload(driver: str, model: str, messages: List[dict], opt: dict, stream: bool) -> dict:
105
+ args: Dict[str, Any] = {"messages": messages, "model": model, "stream": stream}
106
+ if opt.get("temperature") is not None:
107
+ args["temperature"] = opt["temperature"]
108
+ max_tokens = opt.get("max_tokens") or opt.get("max_completion_tokens")
 
109
  if max_tokens:
110
  args["max_tokens"] = max_tokens
111
  return {
 
117
  }
118
 
119
 
120
+ def _send(client: httpx.Client, token: str, model: str, messages: list, opt: dict, stream: bool):
121
+ """Schickt den Request; bei 404 (Driver unbekannt) wird der nächste Kandidat probiert."""
122
+ last = None
123
+ for driver, m in _candidates(model):
124
+ req = client.build_request(
125
+ "POST", PUTER_URL, headers=_headers(token),
126
+ json=_payload(driver, m, messages, opt, stream),
127
+ )
128
+ resp = client.send(req, stream=stream)
129
+ if resp.status_code == 404:
130
+ resp.read()
131
+ last = resp
132
+ continue
133
+ return resp
134
+ return last
135
+
136
+
137
+ # ---------------------------------------------------------------- Parsing / Fehler
138
+ def _raise_for_error(obj: Any) -> None:
139
  """Puter meldet Fehler teils mit HTTP 200 + {"success": false, "error": {...}}."""
140
  if isinstance(obj, dict) and obj.get("success") is False:
141
  err = obj.get("error") or {}
142
  if isinstance(err, dict):
143
  code = err.get("code") or err.get("message") or "unknown_error"
144
  msg = err.get("message") or str(err)
145
+ delegate = err.get("delegate")
146
  else:
147
+ code, msg, delegate = "error", str(err), None
148
+ if delegate == "usage-limited-chat" or "insufficient" in str(code) or "usage" in str(code):
149
+ raise PuterError(f"Puter-Kontingent/Guthaben aufgebraucht ({code}): {msg}", 402)
150
+ if code in {"token_auth_failed", "token_missing", "forbidden"}:
151
+ raise PuterError(f"Puter: Token ungültig ({code}): {msg}", 401)
152
+ raise PuterError(f"Puter: {code} – {msg}", 500)
153
 
154
 
155
  def _content_to_text(content: Any) -> str:
 
157
  return ""
158
  if isinstance(content, str):
159
  return content
160
+ if isinstance(content, list): # [{"type":"text","text":"..."}]
161
  return "".join(
162
  p.get("text", "") for p in content if isinstance(p, dict) and p.get("type", "text") == "text"
163
  )
164
  return str(content)
165
 
166
 
167
+ def _extract_message_text(data: Any) -> str:
168
+ """Toleriert: result.message.content | result.choices[0].message.content | result.content | str."""
169
+ if isinstance(data, str):
170
+ return data
171
+ if not isinstance(data, dict):
172
+ return ""
173
  result = data.get("result", data)
174
+ if isinstance(result, str):
175
+ return result
176
+ if not isinstance(result, dict):
177
+ return ""
178
+ if isinstance(result.get("choices"), list) and result["choices"]:
179
+ ch = result["choices"][0] or {}
180
+ return _content_to_text((ch.get("message") or ch.get("delta") or {}).get("content"))
181
+ msg = result.get("message", result)
182
+ if isinstance(msg, dict):
183
+ return _content_to_text(msg.get("content"))
184
+ return _content_to_text(msg)
185
 
186
 
187
  def _http_error(resp: httpx.Response) -> PuterError:
188
  body = resp.text[:300]
189
  if resp.status_code in (401, 403):
190
  return PuterError(
191
+ f"Puter lehnt das Token ab (HTTP {resp.status_code}). Abgelaufen? Neu aus dem Cookie holen. {body}", 401)
192
+ if resp.status_code == 404:
193
+ return PuterError(
194
+ f"Puter HTTP 404 (Driver/Modell nicht gefunden). Prüfe die Modell-ID bzw. probiere "
195
+ f"'driver:modell'. Antwort: {body}", 404)
196
+ if resp.status_code == 429:
197
+ return PuterError(f"Puter Rate-Limit (HTTP 429), kurz warten. {body}", 429)
198
  return PuterError(f"Puter HTTP {resp.status_code}: {body}", resp.status_code)
199
 
200
 
201
+ def _chunk(text: str, index: int, finished: bool = False) -> GenericStreamingChunk:
202
+ return {
203
+ "text": text,
204
+ "is_finished": finished,
205
+ "finish_reason": "stop" if finished else "",
206
+ "usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0},
207
+ "index": index,
208
+ "tool_use": None,
209
+ }
210
+
211
+
212
+ def _line_text(obj: dict) -> str:
213
+ """Text aus einer Streaming-Zeile (NDJSON {"type":"text"} oder OpenAI-Delta)."""
214
+ if obj.get("type") == "text":
215
+ return obj.get("text") or ""
216
+ if isinstance(obj.get("choices"), list) and obj["choices"]:
217
+ return _content_to_text(((obj["choices"][0] or {}).get("delta") or {}).get("content"))
218
+ return ""
219
+
220
+
221
+ # ---------------------------------------------------------------- Provider
222
  class PuterLLM(CustomLLM):
223
+ def _complete_text(self, token: str, model: str, messages: list, opt: dict) -> str:
 
 
 
 
224
  try:
225
  with httpx.Client(timeout=TIMEOUT) as client:
226
+ resp = _send(client, token, model, messages, opt, stream=False)
227
  except httpx.HTTPError as e:
228
  raise PuterError(f"Verbindung zu Puter fehlgeschlagen: {e}", 502)
229
  if resp.status_code >= 400:
230
  raise _http_error(resp)
231
+ try:
232
+ data = resp.json()
233
+ except ValueError:
234
+ raise PuterError(f"Puter: keine JSON-Antwort: {resp.text[:200]}", 502)
235
  _raise_for_error(data)
236
+ return _extract_message_text(data)
237
 
238
+ # --- non-streaming ---
239
+ def completion(self, model: str, messages: list, model_response: ModelResponse,
240
+ optional_params: dict, api_key: Optional[str] = None, **kwargs) -> ModelResponse:
241
+ token = _resolve_token(api_key or (kwargs.get("litellm_params") or {}).get("api_key"))
242
+ text = self._complete_text(token, model, messages, optional_params)
243
  model_response.choices[0].message.content = text # type: ignore
244
  model_response.choices[0].finish_reason = "stop" # type: ignore
245
  model_response.model = model
 
250
  import asyncio
251
  return await asyncio.to_thread(self.completion, *args, **kwargs)
252
 
253
+ # --- streaming ---
254
  def streaming(self, model: str, messages: list, optional_params: dict,
255
  api_key: Optional[str] = None, **kwargs) -> Iterator[GenericStreamingChunk]:
256
  token = _resolve_token(api_key or (kwargs.get("litellm_params") or {}).get("api_key"))
257
+
258
+ if not UPSTREAM_STREAM:
259
+ # Robust: Puter nicht-streamend fragen, Antwort als ein Chunk ausliefern.
260
+ text = self._complete_text(token, model, messages, optional_params)
261
+ if text:
262
+ yield _chunk(text, 0)
263
+ yield _chunk("", 1, finished=True)
264
+ return
265
+
266
  idx = 0
267
  try:
268
  with httpx.Client(timeout=TIMEOUT) as client:
269
+ resp = _send(client, token, model, messages, optional_params, stream=True)
270
+ try:
271
  if resp.status_code >= 400:
272
  resp.read()
273
  raise _http_error(resp)
274
  for line in resp.iter_lines():
275
  line = line.strip()
276
+ if line.startswith("data:"):
277
  line = line[5:].strip()
278
  if not line or line == "[DONE]":
279
  continue
 
281
  obj = json.loads(line)
282
  except json.JSONDecodeError:
283
  continue
 
284
  if not isinstance(obj, dict):
285
  continue
286
+ _raise_for_error(obj)
287
+ text = _line_text(obj)
288
+ if not text and "result" in obj and idx == 0:
 
289
  text = _extract_message_text(obj)
290
+ if text:
291
+ yield _chunk(text, idx)
292
+ idx += 1
293
+ finally:
294
+ resp.close()
295
  except httpx.HTTPError as e:
296
  raise PuterError(f"Verbindung zu Puter fehlgeschlagen: {e}", 502)
297
  yield _chunk("", idx, finished=True)
298
 
299
 
300
+ def list_models(token: Optional[str] = None) -> List[str]:
301
+ """Modell-IDs von Puter holen (Format toleriert); bei Fehler leere Liste."""
302
+ try:
303
+ headers = _headers(_resolve_token(token)) if (token or os.getenv("PUTER_AUTH_TOKEN")) else {}
304
+ r = httpx.get(MODELS_URL, headers=headers, timeout=10.0)
305
+ if r.status_code != 200:
306
+ return []
307
+ data = r.json()
308
+ if isinstance(data, dict):
309
+ data = data.get("models") or data.get("result") or data.get("data") or []
310
+ ids = []
311
+ for it in data if isinstance(data, list) else []:
312
+ if isinstance(it, str):
313
+ ids.append(it)
314
+ elif isinstance(it, dict):
315
+ mid = it.get("id") or it.get("name") or it.get("model")
316
+ if isinstance(mid, str):
317
+ ids.append(mid)
318
+ return sorted(set(ids))
319
+ except Exception:
320
+ return []
321
 
322
 
323
  def register() -> None: