Codex
Replace the dataset with the current testing tree and the three UT docs.
d26f22a
Raw History Blame Contribute Delete
3.01 kB
"""Small configurable OpenAI-compatible pass-through proxy for conductor runs."""
from __future__ import annotations
import http.server
import json
import os
import time
import urllib.error
import urllib.request
import uuid
UPSTREAM_BASE = os.environ.get("UPSTREAM_BASE", "https://yunwu.ai/v1").rstrip("/")
PORT = int(os.environ.get("PROXY_PORT", "8817"))
USAGE_LOG = os.environ.get("USAGE_LOG", "usage.jsonl")
class ProxyHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, fmt: str, *args: object) -> None:
return None
def do_GET(self) -> None: # noqa: N802
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"status":"proxy ok"}')
def do_POST(self) -> None: # noqa: N802
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
target = UPSTREAM_BASE + self.path.removeprefix("/v1")
headers = {
key: value
for key, value in self.headers.items()
if key.lower() not in {"host", "content-length", "transfer-encoding"}
}
request = urllib.request.Request(target, data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(request, timeout=1800) as response:
response_body = response.read()
status = response.status
response_headers = dict(response.headers.items())
except urllib.error.HTTPError as error:
response_body = error.read()
status = error.code
response_headers = dict(error.headers.items()) if error.headers else {}
except Exception as error: # pragma: no cover - live-network path
self.send_error(502, str(error))
return
try:
payload = json.loads(response_body)
usage = payload.get("usage") if isinstance(payload, dict) else None
if isinstance(usage, dict):
record = {
"ts": time.time(),
"attempt_id": uuid.uuid4().hex,
"path": self.path,
"model": payload.get("model", ""),
"usage": usage,
}
with open(USAGE_LOG, "a", encoding="utf-8") as stream:
stream.write(json.dumps(record, ensure_ascii=False) + "\n")
except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError):
pass
self.send_response(status)
for key, value in response_headers.items():
if key.lower() not in {"transfer-encoding", "content-encoding", "connection"}:
self.send_header(key, value)
self.end_headers()
self.wfile.write(response_body)
if __name__ == "__main__":
print(f"[proxy] listening on 127.0.0.1:{PORT}", flush=True)
http.server.ThreadingHTTPServer(("127.0.0.1", PORT), ProxyHandler).serve_forever()