- kind = anthropic: the Messages API over curl, OAuth tokens (sk-ant-oat) as Bearer with the oauth beta, tool_use/tool_result blocks. - --doctor spends no tokens: it asks /models and the provider's own usage route (ollama /api/balance, opencode go /v1/usage) instead of a tiny turn; cli providers are only checked for the program. /usage shows the same provider figures, cached for a minute. - endpoint names the API base (https://host/v1); sp_endpoint_url() builds chat/completions (default), messages, models and usage from it. A full route is still accepted and cut back to the base. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
109 lines
4.7 KiB
Python
109 lines
4.7 KiB
Python
# Fake Anthropic Messages API endpoint.
|
|
#
|
|
# argv: port, request log.
|
|
#
|
|
# It insists on what the real API insists on, so the transport under test is
|
|
# checked and not just fed: anthropic-version, an OAuth token as a Bearer
|
|
# token (and the oauth beta that goes with it), the system prompt as a
|
|
# top-level field, and tools as input_schema. A request that breaks any of
|
|
# those gets a 400 that names the field, exactly like the real one would.
|
|
#
|
|
# Model "claude-limit" answers 429 with the provider's own message, so the
|
|
# status/Retry-After path of a streamed request is exercised too.
|
|
import http.server, json, sys
|
|
|
|
|
|
def ev(d):
|
|
return ("event: " + d["type"] + "\ndata: " + json.dumps(d) + "\n\n").encode()
|
|
|
|
|
|
class H(http.server.BaseHTTPRequestHandler):
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def bad(self, why):
|
|
body = json.dumps({"type": "error", "error": {
|
|
"type": "invalid_request_error", "message": why}}).encode()
|
|
self.send_response(400)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def do_POST(self):
|
|
n = int(self.headers.get("Content-Length", 0))
|
|
raw = self.rfile.read(n)
|
|
with open(sys.argv[2], "a") as f:
|
|
f.write(self.path + "\n" + raw.decode("utf-8", "replace") + "\n")
|
|
try:
|
|
req = json.loads(raw)
|
|
except ValueError:
|
|
return self.bad("Body is not JSON")
|
|
if self.path != "/v1/messages":
|
|
return self.bad("wrong path " + self.path)
|
|
if self.headers.get("anthropic-version") != "2023-06-01":
|
|
return self.bad("missing anthropic-version")
|
|
auth = self.headers.get("authorization", "")
|
|
if not auth.startswith("Bearer sk-ant-oat"):
|
|
return self.bad("no oauth bearer token")
|
|
if "oauth-2025-04-20" not in (self.headers.get("anthropic-beta") or ""):
|
|
return self.bad("missing oauth beta")
|
|
sysmsg = req.get("system")
|
|
if not isinstance(sysmsg, list) or not sysmsg or \
|
|
sysmsg[0].get("text") != \
|
|
"You are a Claude agent, built on Anthropic's Claude Agent SDK.":
|
|
return self.bad("system must start with the Claude agent block")
|
|
if "messages" not in req or not isinstance(req["messages"], list):
|
|
return self.bad("messages must be an array")
|
|
for m in req["messages"]:
|
|
if m.get("role") not in ("user", "assistant"):
|
|
return self.bad("bad role " + str(m.get("role")))
|
|
for t in req.get("tools") or []:
|
|
if "input_schema" not in t:
|
|
return self.bad("tool without input_schema")
|
|
|
|
if req.get("model") == "claude-limit":
|
|
body = json.dumps({"type": "error", "error": {
|
|
"type": "rate_limit_error",
|
|
"message": "This request would exceed your account's rate "
|
|
"limit. Please try again later."}}).encode()
|
|
self.send_response(429)
|
|
self.send_header("Retry-After", "120")
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
|
|
if req.get("stream"):
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.end_headers()
|
|
w = self.wfile.write
|
|
w(ev({"type": "message_start", "message": {
|
|
"id": "msg_1", "type": "message", "role": "assistant",
|
|
"usage": {"input_tokens": 12}}}))
|
|
w(ev({"type": "content_block_start", "index": 0,
|
|
"content_block": {"type": "text", "text": ""}}))
|
|
for piece in ("weiter ", "gemacht"):
|
|
w(ev({"type": "content_block_delta", "index": 0,
|
|
"delta": {"type": "text_delta", "text": piece}}))
|
|
w(ev({"type": "content_block_stop", "index": 0}))
|
|
w(ev({"type": "message_delta", "delta": {
|
|
"stop_reason": "end_turn"}, "usage": {"output_tokens": 5}}))
|
|
w(ev({"type": "message_stop"}))
|
|
return
|
|
|
|
body = json.dumps({
|
|
"id": "msg_1", "type": "message", "role": "assistant",
|
|
"content": [{"type": "text", "text": "weiter gemacht"}],
|
|
"usage": {"input_tokens": 12, "output_tokens": 5}}).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
|
|
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
|