tokensafe 2.7.2 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/proxy.py CHANGED
@@ -8,6 +8,7 @@ Endpoint: http://127.0.0.1:8765/v1
8
8
  import sys
9
9
  import os
10
10
  import json
11
+ import time
11
12
  import queue
12
13
  import threading
13
14
  import urllib.request
@@ -50,6 +51,12 @@ class EventBroadcaster:
50
51
  self._subscribers.remove(q)
51
52
 
52
53
  def publish(self, event_type: str, data: Dict[str, Any]):
54
+ # Live relay: anonymized metadata copy to the cloud live view (best-effort)
55
+ try:
56
+ from src.live_relay import LIVE_RELAY
57
+ LIVE_RELAY.record(event_type, data if isinstance(data, dict) else {})
58
+ except Exception:
59
+ pass
53
60
  payload = f"event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
54
61
  with self._lock:
55
62
  dead = []
@@ -63,6 +70,332 @@ class EventBroadcaster:
63
70
 
64
71
  BROADCASTER = EventBroadcaster()
65
72
 
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # OpenAI <-> Anthropic payload translation.
76
+ # The proxy accepts OpenAI /v1/chat/completions bodies from any agent; when the
77
+ # resolved upstream is Anthropic (/v1/messages) the body, response, SSE stream,
78
+ # and error envelopes must be converted in-flight, otherwise the raw OpenAI
79
+ # shape is rejected by the Anthropic API (missing max_tokens, system role, etc).
80
+ # ---------------------------------------------------------------------------
81
+
82
+ _ANTHROPIC_FINISH_MAP = {
83
+ "end_turn": "stop",
84
+ "stop_sequence": "stop",
85
+ "max_tokens": "length",
86
+ "tool_use": "tool_calls",
87
+ "refusal": "content_filter",
88
+ }
89
+
90
+ _OPENAI_ONLY_FIELDS = (
91
+ "frequency_penalty", "presence_penalty", "logprobs", "top_logprobs", "n",
92
+ "response_format", "seed", "stream_options", "user", "parallel_tool_calls",
93
+ "prompt_cache_key", "logit_bias", "service_tier",
94
+ )
95
+
96
+
97
+ def _blocks_from_content(content: Any, role: str = "user") -> List[Dict[str, Any]]:
98
+ """Converts one OpenAI message content (str or block list) into Anthropic content blocks."""
99
+ blocks: List[Dict[str, Any]] = []
100
+ if isinstance(content, str):
101
+ if content:
102
+ blocks.append({"type": "text", "text": content})
103
+ return blocks
104
+ if not isinstance(content, list):
105
+ return blocks
106
+ for blk in content:
107
+ if not isinstance(blk, dict):
108
+ continue
109
+ btype = blk.get("type")
110
+ if btype == "text" and isinstance(blk.get("text"), str):
111
+ nb = {"type": "text", "text": blk["text"]}
112
+ if isinstance(blk.get("cache_control"), dict):
113
+ nb["cache_control"] = blk["cache_control"]
114
+ blocks.append(nb)
115
+ elif btype == "image_url":
116
+ url = (blk.get("image_url") or {}).get("url", "") if isinstance(blk.get("image_url"), dict) else ""
117
+ if url.startswith("data:"):
118
+ head, _, b64 = url.partition(",")
119
+ media = head[5:].split(";", 1)[0] or "image/png"
120
+ if b64:
121
+ blocks.append({"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}})
122
+ elif url:
123
+ blocks.append({"type": "image", "source": {"type": "url", "url": url}})
124
+ return blocks
125
+
126
+
127
+ def _collapse_plain_text(blocks: List[Dict[str, Any]]) -> Any:
128
+ """Collapses pure-text blocks (no cache_control) back into a plain string —
129
+ Anthropic accepts string content, and it keeps payloads closest to the client's shape."""
130
+ if not blocks or any(b.get("type") != "text" or "cache_control" in b for b in blocks):
131
+ return blocks
132
+ texts = [b.get("text", "") for b in blocks]
133
+ return texts[0] if len(texts) == 1 else "\n\n".join(texts)
134
+
135
+
136
+ def _merge_same_role(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
137
+ """Anthropic requires alternating roles; folds consecutive same-role messages."""
138
+ merged: List[Dict[str, Any]] = []
139
+ for msg in messages:
140
+ if merged and merged[-1].get("role") == msg.get("role"):
141
+ prev = merged[-1]
142
+ prev_c = prev.get("content")
143
+ cur_c = msg.get("content")
144
+ prev_blocks = prev_c if isinstance(prev_c, list) else ([{"type": "text", "text": prev_c}] if prev_c else [])
145
+ cur_blocks = cur_c if isinstance(cur_c, list) else ([{"type": "text", "text": cur_c}] if cur_c else [])
146
+ prev["content"] = prev_blocks + cur_blocks
147
+ else:
148
+ merged.append(msg)
149
+ return merged
150
+
151
+
152
+ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str, Any]:
153
+ """Converts an OpenAI chat-completions payload into an Anthropic /v1/messages payload."""
154
+ src_messages = payload.get("messages") if isinstance(payload.get("messages"), list) else []
155
+
156
+ system_parts: List[Dict[str, Any]] = []
157
+ out_messages: List[Dict[str, Any]] = []
158
+ for msg in src_messages:
159
+ if not isinstance(msg, dict):
160
+ continue
161
+ role = msg.get("role")
162
+ if role in ("system", "developer"):
163
+ for blk in _blocks_from_content(msg.get("content"), role):
164
+ system_parts.append(blk)
165
+ continue
166
+
167
+ if role == "assistant":
168
+ blocks: List[Dict[str, Any]] = _blocks_from_content(msg.get("content"), "assistant")
169
+ for tc in (msg.get("tool_calls") or []):
170
+ if not isinstance(tc, dict):
171
+ continue
172
+ fn = tc.get("function") or {}
173
+ try:
174
+ tool_input = json.loads(fn.get("arguments") or "{}")
175
+ if not isinstance(tool_input, dict):
176
+ tool_input = {"_raw": tool_input}
177
+ except Exception:
178
+ # Self-healing: repair malformed argument JSON instead of
179
+ # silently dropping the tool call's inputs.
180
+ from src.json_repair import parse_tool_arguments
181
+ tool_input = parse_tool_arguments(fn.get("arguments")) or {}
182
+ blocks.append({
183
+ "type": "tool_use",
184
+ "id": tc.get("id") or "toolu_call",
185
+ "name": fn.get("name") or "unknown",
186
+ "input": tool_input,
187
+ })
188
+ if not blocks:
189
+ blocks = [{"type": "text", "text": ""}]
190
+ out_messages.append({"role": "assistant", "content": _collapse_plain_text(blocks) if len(blocks) == 1 and blocks[0].get("type") == "text" else blocks})
191
+ elif role == "tool":
192
+ tc_content = msg.get("content")
193
+ text = tc_content if isinstance(tc_content, str) else json.dumps(tc_content, ensure_ascii=False)
194
+ out_messages.append({
195
+ "role": "user",
196
+ "content": [{"type": "tool_result", "tool_use_id": msg.get("tool_call_id") or "toolu_call", "content": [{"type": "text", "text": text}]}],
197
+ })
198
+ elif role == "user":
199
+ out_messages.append({"role": "user", "content": _collapse_plain_text(_blocks_from_content(msg.get("content"), "user")) or [{"type": "text", "text": ""}]})
200
+
201
+ out: Dict[str, Any] = {
202
+ "model": payload.get("model") or "claude-3-5-sonnet-latest",
203
+ "max_tokens": payload.get("max_tokens") if isinstance(payload.get("max_tokens"), int) and payload["max_tokens"] > 0 else 4096,
204
+ "messages": _merge_same_role(out_messages),
205
+ }
206
+ if system_parts:
207
+ out["system"] = system_parts if len(system_parts) > 1 or system_parts[0].get("cache_control") else system_parts[0]["text"]
208
+ if isinstance(payload.get("temperature"), (int, float)):
209
+ out["temperature"] = payload["temperature"]
210
+ if isinstance(payload.get("top_p"), (int, float)):
211
+ out["top_p"] = payload["top_p"]
212
+ if payload.get("stop"):
213
+ out["stop_sequences"] = payload["stop"] if isinstance(payload["stop"], list) else [payload["stop"]]
214
+ if isinstance(payload.get("stream"), bool):
215
+ out["stream"] = payload["stream"]
216
+
217
+ # Tools: OpenAI {type:function, function:{...}} -> Anthropic schema.
218
+ # Tools already in Anthropic shape ({name, input_schema}) pass through untouched.
219
+ tools = payload.get("tools")
220
+ if isinstance(tools, list) and tools:
221
+ ant_tools = []
222
+ for t in tools:
223
+ if not isinstance(t, dict):
224
+ continue
225
+ if isinstance(t.get("input_schema"), dict) and t.get("name"):
226
+ at = dict(t)
227
+ else:
228
+ fn = t.get("function") if isinstance(t.get("function"), dict) else t
229
+ name = fn.get("name")
230
+ if not name:
231
+ continue
232
+ at = {
233
+ "name": name,
234
+ "description": fn.get("description") or "",
235
+ "input_schema": fn.get("parameters") if isinstance(fn.get("parameters"), dict) else {"type": "object", "properties": {}},
236
+ }
237
+ if isinstance(t.get("cache_control"), dict):
238
+ at["cache_control"] = t["cache_control"]
239
+ ant_tools.append(at)
240
+ if ant_tools:
241
+ out["tools"] = ant_tools
242
+ tc = payload.get("tool_choice")
243
+ if tc == "auto" or (isinstance(tc, dict) and tc.get("type") == "auto"):
244
+ out["tool_choice"] = {"type": "auto"}
245
+ elif tc == "required" or (isinstance(tc, dict) and tc.get("type") == "required"):
246
+ out["tool_choice"] = {"type": "any"}
247
+ elif isinstance(tc, dict) and tc.get("type") == "function":
248
+ fname = (tc.get("function") or {}).get("name")
249
+ if fname:
250
+ out["tool_choice"] = {"type": "tool", "name": fname}
251
+
252
+ for k in _OPENAI_ONLY_FIELDS:
253
+ out.pop(k, None)
254
+ return out
255
+
256
+
257
+ def _translate_anthropic_json_to_openai(resp_json: Dict[str, Any], fallback_model: str = "") -> Dict[str, Any]:
258
+ """Converts a non-streaming Anthropic /v1/messages response into an OpenAI chat.completion."""
259
+ if not isinstance(resp_json, dict) or resp_json.get("type") not in (None, "message"):
260
+ return resp_json # already OpenAI-shaped or unknown envelope: pass through
261
+ blocks = resp_json.get("content") if isinstance(resp_json.get("content"), list) else []
262
+ text_parts: List[str] = []
263
+ tool_calls = []
264
+ for blk in blocks:
265
+ if not isinstance(blk, dict):
266
+ continue
267
+ if blk.get("type") == "text" and isinstance(blk.get("text"), str):
268
+ text_parts.append(blk["text"])
269
+ elif blk.get("type") == "tool_use":
270
+ tool_calls.append({
271
+ "id": blk.get("id") or f"call_{blk.get('name', 'tool')}",
272
+ "type": "function",
273
+ "function": {
274
+ "name": blk.get("name") or "unknown",
275
+ "arguments": json.dumps(blk.get("input") or {}, ensure_ascii=False),
276
+ },
277
+ })
278
+ usage = resp_json.get("usage") or {}
279
+ in_tok = int(usage.get("input_tokens") or 0)
280
+ out_tok = int(usage.get("output_tokens") or 0)
281
+ cache_read = int(usage.get("cache_read_input_tokens") or 0)
282
+ finish = _ANTHROPIC_FINISH_MAP.get(resp_json.get("stop_reason"), "stop" if resp_json.get("stop_reason") else None)
283
+ message: Dict[str, Any] = {"role": "assistant", "content": "\n\n".join(text_parts) if text_parts else None}
284
+ if tool_calls:
285
+ message["tool_calls"] = tool_calls
286
+ translated = {
287
+ "id": resp_json.get("id") or f"chatcmpl-{int(time.time() * 1000)}",
288
+ "object": "chat.completion",
289
+ "created": int(time.time()),
290
+ "model": resp_json.get("model") or fallback_model,
291
+ "choices": [{"index": 0, "message": message, "finish_reason": finish}],
292
+ "usage": {
293
+ "prompt_tokens": in_tok,
294
+ "completion_tokens": out_tok,
295
+ "total_tokens": in_tok + out_tok,
296
+ "prompt_tokens_details": {"cached_tokens": cache_read},
297
+ },
298
+ }
299
+ return translated
300
+
301
+
302
+ def _translate_anthropic_error_body(err_bytes: bytes) -> bytes:
303
+ """Maps an Anthropic error envelope {type:error,error:{type,message}} onto the OpenAI one."""
304
+ try:
305
+ data = json.loads(err_bytes.decode("utf-8"))
306
+ if isinstance(data, dict) and isinstance(data.get("error"), dict) and data.get("type") == "error":
307
+ inner = data["error"]
308
+ return json.dumps({"error": {"message": inner.get("message", "Upstream error"), "type": inner.get("type", "api_error"), "code": None}}).encode("utf-8")
309
+ except Exception:
310
+ pass
311
+ return err_bytes
312
+
313
+
314
+ class _AnthropicSSETranslator:
315
+ """Converts an Anthropic /v1/messages SSE event stream into OpenAI chat.completion.chunk SSE lines."""
316
+
317
+ def __init__(self, model: str = ""):
318
+ self.model = model or "claude"
319
+ self._buf = b""
320
+ self._tool_blocks: Dict[int, Dict[str, Any]] = {}
321
+ self._chunk_id = f"chatcmpl-{int(time.time() * 1000)}"
322
+ self._done = False
323
+ self._usage_in = 0
324
+
325
+ def _chunk(self, delta: Dict[str, Any], finish: Any = None) -> bytes:
326
+ payload = {
327
+ "id": self._chunk_id,
328
+ "object": "chat.completion.chunk",
329
+ "created": int(time.time()),
330
+ "model": self.model,
331
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
332
+ }
333
+ return (b"data: " + json.dumps(payload, ensure_ascii=False).encode("utf-8") + b"\n\n")
334
+
335
+ def _handle_event(self, event: str, data: Dict[str, Any]) -> bytes:
336
+ out = b""
337
+ if event == "message_start":
338
+ msg = data.get("message") or {}
339
+ if msg.get("model"):
340
+ self.model = msg["model"]
341
+ self._usage_in = int((msg.get("usage") or {}).get("input_tokens") or 0)
342
+ out += self._chunk({"role": "assistant", "content": ""})
343
+ elif event == "content_block_start":
344
+ blk = data.get("content_block") or {}
345
+ if blk.get("type") == "tool_use":
346
+ idx = int(data.get("index") or 0)
347
+ self._tool_blocks[idx] = {"id": blk.get("id") or "toolu_call", "name": blk.get("name") or "unknown"}
348
+ out += self._chunk({"tool_calls": [{"index": idx, "id": self._tool_blocks[idx]["id"], "type": "function", "function": {"name": self._tool_blocks[idx]["name"], "arguments": ""}}]})
349
+ elif event == "content_block_delta":
350
+ delta = data.get("delta") or {}
351
+ if delta.get("type") == "text_delta" and isinstance(delta.get("text"), str):
352
+ out += self._chunk({"content": delta["text"]})
353
+ elif delta.get("type") == "input_json_delta":
354
+ idx = int(data.get("index") or 0)
355
+ out += self._chunk({"tool_calls": [{"index": idx, "function": {"arguments": delta.get("partial_json") or ""}}]})
356
+ elif event == "message_delta":
357
+ delta = data.get("delta") or {}
358
+ finish = _ANTHROPIC_FINISH_MAP.get(delta.get("stop_reason"))
359
+ if finish or data.get("usage"):
360
+ out += self._chunk({}, finish=finish)
361
+ elif event == "message_stop" and not self._done:
362
+ self._done = True
363
+ out += b"data: [DONE]\n\n"
364
+ return out
365
+
366
+ def feed(self, chunk: bytes) -> bytes:
367
+ """Feeds raw upstream bytes; returns translated OpenAI SSE bytes (may be empty)."""
368
+ if not chunk:
369
+ return b""
370
+ self._buf += chunk
371
+ out = b""
372
+ while True:
373
+ nl = self._buf.find(b"\n")
374
+ if nl < 0:
375
+ break
376
+ line = self._buf[:nl].rstrip(b"\r")
377
+ self._buf = self._buf[nl + 1:]
378
+ if not line:
379
+ continue
380
+ if line.startswith(b"event:"):
381
+ self._pending_event = line[6:].strip().decode("utf-8", "replace")
382
+ elif line.startswith(b"data:"):
383
+ try:
384
+ data = json.loads(line[5:].strip().decode("utf-8"))
385
+ except Exception:
386
+ continue
387
+ if isinstance(data, dict):
388
+ out += self._handle_event(getattr(self, "_pending_event", ""), data)
389
+ return out
390
+
391
+ def flush(self) -> bytes:
392
+ """Emits a final [DONE] if the upstream stream ended without message_stop."""
393
+ if self._done:
394
+ return b""
395
+ self._done = True
396
+ return self._chunk({}, finish="stop") + b"data: [DONE]\n\n"
397
+
398
+
66
399
  class TokenSafeProxyHandler(BaseHTTPRequestHandler):
67
400
  """Handles HTTP requests and proxies /v1/chat/completions with token optimization."""
68
401
 
@@ -241,7 +574,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
241
574
  msg = messages[idx]
242
575
  if msg.get("role") == "user" and isinstance(msg.get("content"), str):
243
576
  raw_user = msg["content"]
244
- compaction = PromptCompactor.compact(raw_user, enable_deepseek=False)
577
+ compaction = PromptCompactor.compact(raw_user, enable_distill=False)
245
578
  if compaction["saved_tokens"] > 5:
246
579
  msg["content"] = compaction["compact_text"]
247
580
  try:
@@ -324,6 +657,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
324
657
  payload["tools"], provider=provider, inject_cache_control=False
325
658
  )
326
659
 
660
+ if provider == "anthropic":
661
+ payload = _translate_openai_payload_to_anthropic(payload)
662
+
327
663
  headers = {"Content-Type": "application/json"}
328
664
  if provider == "anthropic":
329
665
  x_api_key = self.headers.get("x-api-key", "") if hasattr(self.headers, "get") else ""
@@ -357,6 +693,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
357
693
  if is_stream:
358
694
  self.send_header("Cache-Control", "no-cache")
359
695
  self.end_headers()
696
+ sse_t = _AnthropicSSETranslator(str(payload.get("model") or "")) if provider == "anthropic" else None
360
697
  reader = getattr(resp, "read1", None) or resp.read
361
698
  while True:
362
699
  try:
@@ -364,15 +701,33 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
364
701
  except TypeError:
365
702
  chunk = resp.read()
366
703
  if chunk:
367
- self.wfile.write(chunk)
368
- self.wfile.flush()
704
+ out = sse_t.feed(chunk) if sse_t else chunk
705
+ if out:
706
+ self.wfile.write(out)
707
+ self.wfile.flush()
369
708
  break
370
709
  if not chunk:
371
710
  break
372
- self.wfile.write(chunk)
373
- self.wfile.flush()
711
+ out = sse_t.feed(chunk) if sse_t else chunk
712
+ if out:
713
+ self.wfile.write(out)
714
+ self.wfile.flush()
715
+ if sse_t:
716
+ tail = sse_t.flush()
717
+ if tail:
718
+ self.wfile.write(tail)
719
+ self.wfile.flush()
374
720
  else:
375
721
  resp_data = resp.read()
722
+ if provider == "anthropic":
723
+ try:
724
+ raw_json = json.loads(resp_data.decode("utf-8"))
725
+ resp_data = json.dumps(
726
+ _translate_anthropic_json_to_openai(raw_json, str(payload.get("model") or "")),
727
+ ensure_ascii=False,
728
+ ).encode("utf-8")
729
+ except Exception:
730
+ pass
376
731
  self.send_header("Content-Length", str(len(resp_data)))
377
732
  self.end_headers()
378
733
  self.wfile.write(resp_data)
@@ -401,6 +756,8 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
401
756
  with e:
402
757
  err_body = e.read()
403
758
  ctype = e.headers.get("Content-Type", "application/json") if e.headers else "application/json"
759
+ if provider == "anthropic":
760
+ err_body = _translate_anthropic_error_body(err_body)
404
761
  self.send_response(e.code)
405
762
  self.send_header("Content-Type", ctype)
406
763
  self.send_header("Content-Length", str(len(err_body)))