Skip to content

Instantly share code, notes, and snippets.

@arbipher
Created May 8, 2026 15:41
Show Gist options
  • Select an option

  • Save arbipher/f959c14de7a9e09c78a2b162bc6f1ec9 to your computer and use it in GitHub Desktop.

Select an option

Save arbipher/f959c14de7a9e09c78a2b162bc6f1ec9 to your computer and use it in GitHub Desktop.
deepseek-local-proxy

Prompt to reproduce this proxy (for any coding-capable AI):

"Write a Python 3 reverse proxy (stdlib only, no pip dependencies) that listens on localhost:8787 and forwards all requests to https://api.deepseek.com/anthropic. For POST requests, parse the JSON body and remove the tool_choice key before forwarding. For GET and HEAD requests, forward unchanged. Strip anthropic-beta and similar Anthropic-specific headers that DeepSeek's API may reject, but keep anthropic-version. Log each request path and whether tool_choice was stripped to both stderr and /tmp/deepseek-proxy.log. Handle BrokenPipeError gracefully during streaming responses. Add a startup health check: before listening, send a probe POST to https://api.deepseek.com/anthropic/v1/messages with tool_choice: {"type": "tool", "name": "test"}. If the response does NOT contain the error 'does not support this tool_choice', print a message that the upstream bug is fixed and exit immediately. Read the auth token from the ANTHROPIC_AUTH_TOKEN environment variable, or fall back to reading ~/.claude/settings.json / ~/.claude/settings.local.json."

post facto generated.

#!/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()
@inertia

inertia commented May 9, 2026

Copy link
Copy Markdown

Thanks for this elegant workaround.

Tested successfully with Claude Code + DeepSeek (deepseek-v4-pro). The proxy strips both tool_choice and anthropic-beta header, then forwards to api.deepseek.com/anthropic. WebSearch and WebFetch work after routing through localhost:8787.

One note: the startup probe can give a false negative — direct curl tests with tool_choice pass (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.

@arbipher

arbipher commented May 9, 2026

Copy link
Copy Markdown
Author

Make sense! The probe is not identical to the actual request, so this feature is quite decorative. It's trivial to delete that probe or just vibe by copying your note to the agent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment