|
#!/usr/bin/env python3 |
|
"""Micro-proxy: strip tool_choice from Claude Code requests before forwarding to DeepSeek. |
|
|
|
Usage: |
|
python3 proxy.py |
|
# Then set: ANTHROPIC_BASE_URL=http://localhost:8787 |
|
""" |
|
|
|
import http.server |
|
import json |
|
import urllib.request |
|
import sys |
|
import os |
|
from datetime import datetime |
|
|
|
TARGET = "https://api.deepseek.com/anthropic" |
|
PORT = 8787 |
|
LOG = "/tmp/deepseek-proxy.log" |
|
|
|
STRIP_HEADERS = {"host", "content-length", "transfer-encoding", "anthropic-beta"} |
|
FORWARD_ONLY = {"authorization", "content-type", "x-api-key"} |
|
|
|
|
|
class Proxy(http.server.BaseHTTPRequestHandler): |
|
def _forward(self, method, body=None): |
|
data = body.encode() if isinstance(body, str) else body |
|
req = urllib.request.Request( |
|
f"{TARGET}{self.path}", data=data, method=method |
|
) |
|
for k, v in self.headers.items(): |
|
kl = k.lower() |
|
if kl in STRIP_HEADERS: |
|
continue |
|
if kl.startswith("anthropic-") and kl != "anthropic-version": |
|
continue |
|
req.add_header(k, v) |
|
|
|
try: |
|
resp = urllib.request.urlopen(req, timeout=120) |
|
self.send_response(resp.status) |
|
for k, v in resp.headers.items(): |
|
if k.lower() not in ("transfer-encoding",): |
|
self.send_header(k, v) |
|
self.end_headers() |
|
# Stream chunks for SSE support |
|
while chunk := resp.read(8192): |
|
try: |
|
self.wfile.write(chunk) |
|
except BrokenPipeError: |
|
break # client disconnected, stop streaming |
|
except urllib.error.HTTPError as e: |
|
self.send_response(e.code) |
|
self.end_headers() |
|
self.wfile.write(e.read()) |
|
|
|
def do_GET(self): |
|
self._forward("GET") |
|
|
|
do_HEAD = do_GET |
|
|
|
def do_POST(self): |
|
length = int(self.headers.get("Content-Length", 0)) |
|
body = self.rfile.read(length) |
|
data = json.loads(body) |
|
tc = data.pop("tool_choice", None) |
|
if tc: |
|
self._log(f"STRIP tool_choice={json.dumps(tc)}") |
|
self._forward("POST", json.dumps(data)) |
|
|
|
def log_message(self, fmt, *args): |
|
self._log(args[0]) |
|
|
|
def _log(self, msg): |
|
line = f"[proxy {datetime.now().strftime('%H:%M:%S')}] {msg}" |
|
print(line, file=sys.stderr) |
|
with open(LOG, "a") as f: |
|
f.write(line + "\n") |
|
|
|
|
|
if __name__ == "__main__": |
|
# --- Startup: check if the tool_choice bug has been fixed upstream --- |
|
auth = os.environ.get("ANTHROPIC_AUTH_TOKEN", "") |
|
if not auth: |
|
# Try reading from Claude Code settings |
|
for p in [os.path.expanduser("~/.claude/settings.json"), |
|
os.path.expanduser("~/.claude/settings.local.json")]: |
|
try: |
|
with open(p) as f: |
|
auth = json.load(f).get("env", {}).get("ANTHROPIC_AUTH_TOKEN", "") |
|
if auth: break |
|
except Exception: |
|
pass |
|
|
|
BUG_FIXED = False |
|
if auth: |
|
probe = json.dumps({ |
|
"model": "deepseek-v4-pro", |
|
"max_tokens": 1, |
|
"messages": [{"role": "user", "content": "hi"}], |
|
"tool_choice": {"type": "tool", "name": "test"}, |
|
"tools": [{"name": "test", "description": "test", "input_schema": {"type": "object", "properties": {}}}], |
|
}).encode() |
|
try: |
|
req = urllib.request.Request( |
|
f"{TARGET}/v1/messages", |
|
data=probe, |
|
headers={"Content-Type": "application/json", "x-api-key": auth, "anthropic-version": "2023-06-01"}, |
|
method="POST", |
|
) |
|
resp = urllib.request.urlopen(req, timeout=10) |
|
body = resp.read().decode() |
|
except urllib.error.HTTPError as e: |
|
body = e.read().decode() |
|
try: |
|
msg = json.loads(body).get("error", {}).get("message", "") |
|
except Exception: |
|
msg = "" |
|
BUG_FIXED = "does not support this tool_choice" not in msg |
|
else: |
|
print("[proxy] WARNING: no auth token found, skipping upstream bug check", file=sys.stderr) |
|
|
|
if BUG_FIXED: |
|
print("[proxy] ============================================", file=sys.stderr) |
|
print("[proxy] UPSTREAM BUG APPEARS FIXED!", file=sys.stderr) |
|
print("[proxy] The tool_choice error is no longer returned.", file=sys.stderr) |
|
print("[proxy] You can remove this proxy:", file=sys.stderr) |
|
print("[proxy] Set ANTHROPIC_BASE_URL back to https://api.deepseek.com/anthropic", file=sys.stderr) |
|
print("[proxy] in ~/.claude/settings.json and bash_env, then restart Claude Code.", file=sys.stderr) |
|
print("[proxy] ============================================", file=sys.stderr) |
|
sys.exit(0) |
|
|
|
print(f"DeepSeek proxy on http://localhost:{PORT} -> {TARGET}", file=sys.stderr) |
|
print(f"[proxy] Bug still present — stripping tool_choice as workaround", file=sys.stderr) |
|
http.server.HTTPServer(("127.0.0.1", PORT), Proxy).serve_forever() |
Thanks for this elegant workaround.
Tested successfully with Claude Code + DeepSeek (deepseek-v4-pro). The proxy strips both
tool_choiceandanthropic-betaheader, then forwards toapi.deepseek.com/anthropic. WebSearch and WebFetch work after routing throughlocalhost:8787.One note: the startup probe can give a false negative — direct curl tests with
tool_choicepass (HTTP 200), but Claude Code's actual internal request format still triggers the rejection. Removed the probe and just always serve.Thanks again for the clean, stdlib-only implementation.