Spaces:
Sleeping
Sleeping
Adarsh Kumar commited on
Upload 13 files
Browse filesFiles changed (13)
- .dockerignoreAdded+10
- .env.exampleAdded+20
- .gitignoreAdded+5
- DockerfileAdded+23
- MakefileAdded+22
- README.mdAdded+261
- app.pyAdded+498
- compose.yamlAdded+17
- pytest.iniAdded+4
- requirements-dev.txtAdded+3
- requirements.txtAdded+3
- smoke_test.pyAdded+79
- tests/test_app.pyAdded+242
12345678910.git.github.venv__pycache__.pytest_cache*.py[cod].envtestssmoke_test.pyrequirements-dev.txt1234567891011121314151617181920# Upstream OpenAI-compatible APIUPSTREAM_BASE_URL=https://osaii.wyvernhub.net/api/v1# UPSTREAM_API_KEY=your-upstream-key-if-required
# The requested deployment is public. ZCode may use any placeholder API key.PUBLIC_ACCESS=true# To protect it later, use PUBLIC_ACCESS=false and set PROVIDER_API_KEY as a HF Secret.# PROVIDER_API_KEY=replace-with-a-long-random-value
SERVICE_NAME=ZCode Model RelayMODEL_CACHE_TTL=60MAX_BODY_MB=25MAX_CONCURRENT_REQUESTS=6QUEUE_TIMEOUT_SECONDS=20UPSTREAM_READ_TIMEOUT=600RATE_LIMIT_PER_MINUTE=12LOG_LEVEL=INFO
# Optional comma-separated allowlist. Empty exposes every upstream model.# ALLOWED_MODELS=osaii/faster-experimental,poe/Gemma-4-31B12345.env.venv/__pycache__/.pytest_cache/*.py[cod]1234567891011121314151617181920212223FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1 \ PORT=7860
RUN useradd --create-home --uid 1000 userWORKDIR /home/user/app
COPY --chown=user:user requirements.txt ./RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt
COPY --chown=user:user app.py ./USER user
EXPOSE 7860
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/healthz', timeout=3)" || exit 1
CMD ["sh", "-c", "exec uvicorn app:app --host 0.0.0.0 --port ${PORT:-7860} --proxy-headers --forwarded-allow-ips='*'"]12345678910111213141516171819202122.PHONY: install dev test run docker-build docker-run smoke
install: python -m pip install -r requirements.txt
dev: python -m pip install -r requirements-dev.txt
test: pytest -q
run: uvicorn app:app --host 0.0.0.0 --port 7860 --reload
docker-build: docker build -t zcode-model-relay .
docker-run: docker run --rm -p 7860:7860 --env-file .env zcode-model-relay
smoke: python smoke_test.py http://127.0.0.1:7860123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261---title: ZCode OpenAI Provideremoji: 🧰colorFrom: bluecolorTo: indigosdk: dockerapp_port: 7860pinned: false---
# ZCode OpenAI Provider
A small, production-shaped **OpenAI-compatible relay** for a Hugging Face Docker Space. It is designed for **ZCode** and other coding agents that use Chat Completions.
## What it supports
- `GET /v1/models` — live upstream catalog with a short cache- `POST /v1/chat/completions` — JSON and SSE streaming- OpenAI function tools and `tool_choice`- usage, reasoning and provider-specific response fields- OpenAI multimodal `content` arrays with `image_url`- clean OpenAI-shaped errors, body-size checks, concurrency control and rate limiting- optional server API-key protection- `/healthz`, `/readyz`, `/docs`, and a status page at `/`
The request JSON is forwarded without rebuilding it. This is important: ZCode's full tool definitions, stream options, tool results and image parts reach the upstream unchanged.
## Deploy to Hugging Face Spaces
### 1. Create the Space
1. Open <https://huggingface.co/new-space>.2. Choose a name such as `zcode-model-relay`.3. Select **Docker** as the SDK.4. Select **Public**, as requested.5. Create the Space.
### 2. Upload this folder as the Space repository root
The Space root must contain `README.md`, `Dockerfile`, `app.py`, and `requirements.txt`.
Using Git:
```bashgit clone https://huggingface.co/spaces/YOUR_USERNAME/zcode-model-relaycp -a /path/to/public-repo/hf-space/. zcode-model-relay/cd zcode-model-relaygit add .git commit -m "Deploy OpenAI-compatible ZCode relay"git push```
Hugging Face builds the image and exposes port `7860`. No GPU is needed because this container proxies a remote model API.
### 3. Optional Space variables
The defaults already target the tested upstream. In **Space → Settings → Variables and secrets**, you may configure:
| Name | Type | Default | Purpose ||---|---|---|---|| `UPSTREAM_BASE_URL` | Variable | `https://osaii.wyvernhub.net/api/v1` | OpenAI-compatible upstream ending in `/v1` || `UPSTREAM_API_KEY` | Secret | empty | Upstream Bearer key, if required later || `PUBLIC_ACCESS` | Variable | `true` | `true` accepts requests without server authentication || `PROVIDER_API_KEY` | Secret | empty | Used only when `PUBLIC_ACCESS=false` || `RATE_LIMIT_PER_MINUTE` | Variable | `12` | Per-client in-memory limit; `0` disables it || `MAX_CONCURRENT_REQUESTS` | Variable | `6` | Concurrent upstream requests || `MAX_BODY_MB` | Variable | `25` | Allows base64 image input while bounding request size || `ALLOWED_MODELS` | Variable | empty | Optional comma-separated model allowlist |
A restart applies variable changes.
## Connect it to ZCode
ZCode supports custom OpenAI-compatible providers. It appends `/chat/completions`, so the Base URL must end at `/v1`.
1. Open **ZCode → Settings → Model settings**.2. Click **Add provider → Create custom provider**.3. Configure:
```textName: HF Model RelayAPI format: Chat completions (/chat/completions)Base URL: https://YOUR_USERNAME-zcode-model-relay.hf.space/v1API key: public```
`public` is only a placeholder because this requested deployment has `PUBLIC_ACCESS=true`; the server ignores the Authorization value. If ZCode offers an **API key required** switch, turn it off.
4. Click **Add model** and enter this recommended coding model exactly:
```textosaii/faster-experimental```
5. Enable the provider and run **Test model**.
### Recommended models
Always check `https://YOUR_USERNAME-zcode-model-relay.hf.space/v1/models` because the upstream catalog can change.
| Model | Best use | Verified behavior ||---|---|---|| `osaii/faster-experimental` | **ZCode coding agent** | streaming, usage and structured function tool calls || `osaii/ultrafast-experimental` | fast chat | low-latency alias; catalog availability is dynamic || `poe/Gemma-4-31B` | **image understanding** | correctly classified independently generated red and blue test images || `poe/DeepSeek-V4.1-Flash-T` | reasoning chat | streaming chat; its current Poe route rejects ZCode-style tool payloads || `poe/GLM-5.3-Flash-T` | reasoning chat | chat works; its current Poe route rejects forced tool payloads |
For ZCode's agent loop, start with `osaii/faster-experimental`. The Gemma route understands images but is not the recommended tool-calling coding model.
### Optional manual ZCode configuration
ZCode can also store a custom provider in `~/.zcode/v2/config.json`. Back up the file first and merge rather than replacing existing providers:
```json{ "provider": { "hf-model-relay": { "name": "HF Model Relay", "kind": "openai-compatible", "source": "custom", "options": { "baseURL": "https://YOUR_USERNAME-zcode-model-relay.hf.space/v1", "apiKey": "public", "apiKeyRequired": false }, "models": { "osaii/faster-experimental": { "name": "OSAI Faster — Tool Calling", "limit": { "context": 131072, "output": 32768 } }, "poe/Gemma-4-31B": { "name": "Gemma 4 31B — Vision", "limit": { "context": 32768, "output": 8192 } } } } }}```
The ZCode UI is safer than hand-editing configuration because ZCode's schema can change between releases.
## API checks
Replace the base URL first:
```bashBASE=https://YOUR_USERNAME-zcode-model-relay.hf.space```
Health and models:
```bashcurl -sS "$BASE/healthz"curl -sS "$BASE/v1/models" | python -m json.tool```
Non-streaming chat:
```bashcurl -sS "$BASE/v1/chat/completions" \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer public' \ -d '{ "model": "osaii/faster-experimental", "stream": false, "messages": [{"role": "user", "content": "Reply with exactly OK"}] }' | python -m json.tool```
Streaming:
```bashcurl -N "$BASE/v1/chat/completions" \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer public' \ -d '{ "model": "osaii/faster-experimental", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Write a two-line Python function"}] }'```
## Vision request shape
Image understanding uses standard OpenAI multimodal message parts. The relay preserves this array unchanged:
```json{ "model": "poe/Gemma-4-31B", "stream": false, "messages": [ { "role": "user", "content": [ {"type": "text", "text": "Describe this image."}, { "type": "image_url", "image_url": {"url": "data:image/png;base64,BASE64_DATA"} } ] } ]}```
## Run locally with Docker
```bashcp .env.example .envdocker compose up --build```
Then use:
```texthttp://localhost:7860/v1```
Without Compose:
```bashdocker build -t zcode-model-relay .docker run --rm -p 7860:7860 --env-file .env zcode-model-relay```
## Run locally without Docker
```bashpython -m venv .venv. .venv/bin/activate # Windows: .venv\Scripts\activatepip install -r requirements-dev.txtuvicorn app:app --host 0.0.0.0 --port 7860```
Tests:
```bashpytest -qpython smoke_test.py http://127.0.0.1:7860```
## Public-deployment warning
With `PUBLIC_ACCESS=true`, anyone who discovers the Space URL can use the upstream through your Space. The built-in per-client limit reduces accidental abuse but is not durable authentication, and Hugging Face replicas do not share its in-memory counters.
For a safer deployment later:
1. Set `PUBLIC_ACCESS=false` as a Space Variable.2. Set a long random `PROVIDER_API_KEY` as a Space Secret.3. Put that key into ZCode instead of `public`.
Also verify that the upstream's terms allow redistribution through a public relay. Free Hugging Face Spaces sleep when idle, so ZCode's first request after inactivity may need to wait for the Space to wake up.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498"""OpenAI-compatible relay for ZCode and Hugging Face Docker Spaces.
The relay intentionally keeps the request body intact. That is what preservesZCode tool definitions, streaming options, reasoning fields, and OpenAI-stylemultimodal image content."""from __future__ import annotations
import asyncioimport hmacimport jsonimport loggingimport osimport timeimport uuidfrom collections import defaultdict, dequefrom contextlib import asynccontextmanagerfrom html import escapefrom typing import Any
import httpxfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
def env_bool(name: str, default: bool) -> bool: value = os.getenv(name) if value is None: return default return value.strip().lower() in {"1", "true", "yes", "on"}
SERVICE_NAME = os.getenv("SERVICE_NAME", "ZCode Model Relay")UPSTREAM_BASE_URL = os.getenv( "UPSTREAM_BASE_URL", "https://osaii.wyvernhub.net/api/v1").rstrip("/")UPSTREAM_API_KEY = os.getenv("UPSTREAM_API_KEY", "").strip()PUBLIC_ACCESS = env_bool("PUBLIC_ACCESS", True)PROVIDER_API_KEY = os.getenv("PROVIDER_API_KEY", "").strip()MODEL_CACHE_TTL = max(0, int(os.getenv("MODEL_CACHE_TTL", "60")))MAX_BODY_MB = max(1, int(os.getenv("MAX_BODY_MB", "25")))MAX_BODY_BYTES = MAX_BODY_MB * 1024 * 1024MAX_CONCURRENT_REQUESTS = max(1, int(os.getenv("MAX_CONCURRENT_REQUESTS", "6")))QUEUE_TIMEOUT_SECONDS = max(1.0, float(os.getenv("QUEUE_TIMEOUT_SECONDS", "20")))RATE_LIMIT_PER_MINUTE = max(0, int(os.getenv("RATE_LIMIT_PER_MINUTE", "12")))UPSTREAM_READ_TIMEOUT = max(30.0, float(os.getenv("UPSTREAM_READ_TIMEOUT", "600")))ALLOWED_MODELS = { item.strip() for item in os.getenv("ALLOWED_MODELS", "").split(",") if item.strip()}
logging.basicConfig( level=os.getenv("LOG_LEVEL", "INFO").upper(), format="%(asctime)s %(levelname)s %(name)s %(message)s",)logger = logging.getLogger("zcode-relay")
def make_upstream_client() -> httpx.AsyncClient: timeout = httpx.Timeout( connect=30.0, read=UPSTREAM_READ_TIMEOUT, write=60.0, pool=30.0, ) return httpx.AsyncClient(timeout=timeout, follow_redirects=True)
upstream_client = make_upstream_client()request_slots = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)model_cache_lock = asyncio.Lock()model_cache: dict[str, Any] = {"value": None, "stored_at": 0.0}rate_buckets: dict[str, deque[float]] = defaultdict(deque)rate_lock = asyncio.Lock()
@asynccontextmanagerasync def lifespan(_: FastAPI): if not PUBLIC_ACCESS and not PROVIDER_API_KEY: logger.warning( "PUBLIC_ACCESS=false but PROVIDER_API_KEY is empty; protected API calls will fail" ) logger.info( "starting service=%s upstream=%s public=%s", SERVICE_NAME, UPSTREAM_BASE_URL, PUBLIC_ACCESS, ) yield await upstream_client.aclose()
app = FastAPI( title=SERVICE_NAME, version="1.0.0", description=( "A transparent OpenAI Chat Completions relay for ZCode. " "Supports SSE, tools, reasoning fields, and multimodal message parts." ), lifespan=lifespan,)app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], expose_headers=[ "retry-after", "x-request-id", "x-relay-upstream", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", ],)
def openai_error( message: str, status_code: int, error_type: str = "invalid_request_error", code: str | None = None, headers: dict[str, str] | None = None,) -> JSONResponse: return JSONResponse( { "error": { "message": message, "type": error_type, "param": None, "code": code, } }, status_code=status_code, headers=headers, )
def client_ip(request: Request) -> str: forwarded = request.headers.get("x-forwarded-for", "") if forwarded: return forwarded.split(",", 1)[0].strip() return request.client.host if request.client else "unknown"
async def authorize(request: Request) -> JSONResponse | None: if PUBLIC_ACCESS: return None supplied = request.headers.get("authorization", "") expected = f"Bearer {PROVIDER_API_KEY}" if not PROVIDER_API_KEY or not hmac.compare_digest(supplied, expected): return openai_error( "Invalid or missing provider API key.", 401, "authentication_error", "invalid_api_key", {"WWW-Authenticate": "Bearer"}, ) return None
async def check_rate_limit(request: Request) -> JSONResponse | None: if RATE_LIMIT_PER_MINUTE <= 0: return None now = time.monotonic() key = client_ip(request) async with rate_lock: bucket = rate_buckets[key] while bucket and bucket[0] <= now - 60: bucket.popleft() if len(bucket) >= RATE_LIMIT_PER_MINUTE: retry_after = max(1, int(60 - (now - bucket[0]))) return openai_error( "Relay rate limit reached. Please retry shortly.", 429, "rate_limit_error", "relay_rate_limit", {"Retry-After": str(retry_after)}, ) bucket.append(now) return None
def upstream_headers(request: Request, request_id: str) -> dict[str, str]: headers = { "accept": request.headers.get("accept", "application/json"), "content-type": request.headers.get("content-type", "application/json"), "user-agent": f"{SERVICE_NAME.replace(' ', '-')}/1.0", "x-request-id": request_id, } if UPSTREAM_API_KEY: headers["authorization"] = f"Bearer {UPSTREAM_API_KEY}" # A few OpenAI-compatible gateways use these optional attribution headers. for name in ("http-referer", "x-title"): if request.headers.get(name): headers[name] = request.headers[name] return headers
def response_headers(upstream: httpx.Response, request_id: str) -> dict[str, str]: result = { "x-request-id": request_id, "x-relay-upstream": UPSTREAM_BASE_URL, } allowed_exact = {"content-type", "cache-control", "retry-after"} for name, value in upstream.headers.items(): low = name.lower() if ( low in allowed_exact or low.startswith("x-ratelimit-") or low.startswith("x-osaii-") or low.startswith("x-usage-") ): result[low] = value # StreamingResponse/Response determines transfer and content length itself. result.pop("content-length", None) result.pop("content-encoding", None) result.pop("transfer-encoding", None) return result
async def acquire_slot() -> JSONResponse | None: try: await asyncio.wait_for(request_slots.acquire(), timeout=QUEUE_TIMEOUT_SECONDS) return None except TimeoutError: return openai_error( "The relay is busy. Please retry shortly.", 503, "server_error", "relay_busy", {"Retry-After": "5"}, )
async def read_limited_body(request: Request) -> bytes | JSONResponse: length = request.headers.get("content-length") if length: try: if int(length) > MAX_BODY_BYTES: return openai_error( f"Request exceeds the {MAX_BODY_MB} MB relay limit.", 413, code="request_too_large", ) except ValueError: pass body = await request.body() if len(body) > MAX_BODY_BYTES: return openai_error( f"Request exceeds the {MAX_BODY_MB} MB relay limit.", 413, code="request_too_large", ) return body
async def send_upstream( request: Request, path: str, body: bytes) -> tuple[httpx.Response | None, JSONResponse | None, str]: request_id = request.headers.get("x-request-id") or f"relay_{uuid.uuid4().hex}" target = f"{UPSTREAM_BASE_URL}/{path.lstrip('/')}" try: upstream_request = upstream_client.build_request( request.method, target, content=body if request.method != "GET" else None, headers=upstream_headers(request, request_id), ) upstream = await upstream_client.send(upstream_request, stream=True) return upstream, None, request_id except httpx.TimeoutException as exc: logger.warning("upstream timeout request_id=%s error=%s", request_id, exc) return ( None, openai_error( "The upstream model server timed out.", 504, "server_error", "upstream_timeout", ), request_id, ) except httpx.HTTPError as exc: logger.warning("upstream connection error request_id=%s error=%s", request_id, exc) return ( None, openai_error( "Could not connect to the upstream model server.", 502, "server_error", "upstream_connection_error", ), request_id, )
async def proxy_chat(request: Request) -> Response: denied = await authorize(request) if denied: return denied limited = await check_rate_limit(request) if limited: return limited body = await read_limited_body(request) if isinstance(body, JSONResponse): return body
# Validate only enough to provide a clean error and optional model filtering. # The complete JSON is forwarded byte-for-byte so tools and images survive. try: payload = json.loads(body) except (json.JSONDecodeError, UnicodeDecodeError): return openai_error("Invalid JSON body.", 400, code="invalid_json") if not isinstance(payload, dict): return openai_error("JSON body must be an object.", 400, code="invalid_body") model = payload.get("model") if not isinstance(model, str) or not model: return openai_error("The 'model' field is required.", 400, code="missing_model") if ALLOWED_MODELS and model not in ALLOWED_MODELS: return openai_error( f"Model '{model}' is not enabled on this relay.", 403, code="model_not_allowed", )
busy = await acquire_slot() if busy: return busy
upstream, error, request_id = await send_upstream( request, "chat/completions", body ) if error: request_slots.release() return error assert upstream is not None headers = response_headers(upstream, request_id) content_type = upstream.headers.get("content-type", "") wants_stream = payload.get("stream") is True is_stream = wants_stream or content_type.startswith("text/event-stream")
if is_stream: async def stream_body(): try: async for chunk in upstream.aiter_raw(): yield chunk finally: await upstream.aclose() request_slots.release()
return StreamingResponse( stream_body(), status_code=upstream.status_code, media_type="text/event-stream", headers=headers, )
try: content = await upstream.aread() finally: await upstream.aclose() request_slots.release() return Response( content=content, status_code=upstream.status_code, headers=headers, media_type=None, )
async def fetch_models( request: Request, force: bool = False, skip_auth: bool = False) -> Response: if not skip_auth: denied = await authorize(request) if denied: return denied now = time.monotonic() cached = model_cache["value"] if not force and cached is not None and now - model_cache["stored_at"] < MODEL_CACHE_TTL: return JSONResponse(cached, headers={"x-model-cache": "hit"})
async with model_cache_lock: now = time.monotonic() cached = model_cache["value"] if not force and cached is not None and now - model_cache["stored_at"] < MODEL_CACHE_TTL: return JSONResponse(cached, headers={"x-model-cache": "hit"})
upstream, error, request_id = await send_upstream(request, "models", b"") if error: if cached is not None: return JSONResponse( cached, headers={ "x-model-cache": "stale", "warning": '110 - "upstream unavailable; serving stale model list"', }, ) return error assert upstream is not None try: raw = await upstream.aread() finally: await upstream.aclose() if upstream.status_code >= 400: return Response( raw, status_code=upstream.status_code, headers=response_headers(upstream, request_id), ) try: data = json.loads(raw) if not isinstance(data, dict): raise ValueError("model response is not an object") if ALLOWED_MODELS and isinstance(data.get("data"), list): data["data"] = [ item for item in data["data"] if isinstance(item, dict) and item.get("id") in ALLOWED_MODELS ] model_cache["value"] = data model_cache["stored_at"] = time.monotonic() return JSONResponse(data, headers={"x-model-cache": "miss"}) except (json.JSONDecodeError, ValueError) as exc: logger.warning("invalid upstream model list: %s", exc) return openai_error( "The upstream returned an invalid model list.", 502, "server_error", "invalid_upstream_response", )
@app.get("/healthz", include_in_schema=False)async def healthz(): return { "ok": True, "service": SERVICE_NAME, "version": "1.0.0", "public_access": PUBLIC_ACCESS, "upstream_configured": bool(UPSTREAM_BASE_URL), }
@app.get("/readyz", include_in_schema=False)async def readyz(request: Request): result = await fetch_models(request, force=True, skip_auth=True) if result.status_code >= 400: return JSONResponse( {"ok": False, "upstream": "unavailable"}, status_code=503 ) return {"ok": True, "upstream": "ready"}
@app.get("/v1/models")@app.get("/models", include_in_schema=False)async def models(request: Request): return await fetch_models(request)
@app.post("/v1/chat/completions")@app.post("/chat/completions", include_in_schema=False)async def chat_completions(request: Request): return await proxy_chat(request)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)async def home(): access = "Public (API key ignored)" if PUBLIC_ACCESS else "Bearer key required" upstream_name = escape(UPSTREAM_BASE_URL) service_name = escape(SERVICE_NAME) return HTMLResponse( f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{service_name}</title><style>:root{{--bg:#09111f;--card:#111c2f;--line:#263753;--text:#eaf1ff;--muted:#94a7c6;--ok:#4ade80;--accent:#7dd3fc}}*{{box-sizing:border-box}}body{{margin:0;background:linear-gradient(145deg,#07101d,#0c1830);color:var(--text);font:15px/1.55 system-ui,sans-serif;min-height:100vh}}main{{max-width:900px;margin:auto;padding:56px 22px}}.badge{{display:inline-block;padding:5px 10px;border:1px solid #285f49;border-radius:999px;color:var(--ok);background:#0c2b22}}h1{{font-size:clamp(30px,6vw,58px);line-height:1.05;margin:18px 0}}p{{color:var(--muted)}}.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:14px;margin:30px 0}}.card{{background:rgba(17,28,47,.9);border:1px solid var(--line);border-radius:16px;padding:18px}}code,pre{{font-family:ui-monospace,SFMono-Regular,monospace}}code{{color:var(--accent)}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;background:#07101d;border:1px solid var(--line);padding:14px;border-radius:12px;color:#c9e9ff}}a{{color:var(--accent)}}ul{{padding-left:20px;color:var(--muted)}}</style></head><body><main><span class="badge">● online</span><h1>{service_name}</h1><p>OpenAI-compatible Chat Completions relay for ZCode, coding agents, tools, streaming and vision messages.</p><div class="grid"><section class="card"><b>Access</b><p>{escape(access)}</p></section><section class="card"><b>Upstream</b><p><code>{upstream_name}</code></p></section></div><section class="card"><b>ZCode provider</b><pre>API format: Chat completionsBase URL: https://YOUR-SPACE.hf.space/v1API key: publicModel ID: osaii/faster-experimental</pre></section><div class="grid"><section class="card"><b>Endpoints</b><ul><li><a href="/v1/models">GET /v1/models</a></li><li>POST /v1/chat/completions</li><li><a href="/docs">Interactive API docs</a></li><li><a href="/healthz">Health</a></li></ul></section><section class="card"><b>Capabilities</b><ul><li>SSE streaming</li><li>OpenAI function tools</li><li>Usage and reasoning passthrough</li><li>Multimodal image parts</li></ul></section></div></main></body></html>""" )1234567891011121314151617services: zcode-provider: build: . ports: - "7860:7860" env_file: - path: .env required: false environment: PORT: "7860" restart: unless-stopped healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/healthz', timeout=3)"] interval: 30s timeout: 5s retries: 3 start_period: 15s1234[pytest]testpaths = testspythonpath = .addopts = -ra123-r requirements.txtpytest==8.4.2anyio==4.11.0123fastapi==0.121.3uvicorn[standard]==0.38.0httpx==0.28.112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#!/usr/bin/env python3"""Small end-to-end check for a running local or Hugging Face deployment."""from __future__ import annotations
import jsonimport sys
import httpx
def check(name: str, condition: bool, detail: str = "") -> None: mark = "✓" if condition else "✗" print(f"{mark} {name}{': ' + detail if detail else ''}") if not condition: raise SystemExit(1)
def main() -> None: base = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:7860").rstrip("/") model = sys.argv[2] if len(sys.argv) > 2 else "osaii/faster-experimental"
with httpx.Client(timeout=120, follow_redirects=True) as client: health = client.get(f"{base}/healthz") check("health", health.status_code == 200 and health.json().get("ok") is True)
models = client.get( f"{base}/v1/models", headers={"Authorization": "Bearer public"} ) model_data = models.json().get("data", []) if models.status_code == 200 else [] ids = [item.get("id") for item in model_data if isinstance(item, dict)] check("models", models.status_code == 200 and bool(ids), f"{len(ids)} available") check("selected model exists", model in ids, model)
payload = { "model": model, "stream": False, "messages": [{"role": "user", "content": "Reply with exactly: OK"}], } reply = client.post( f"{base}/v1/chat/completions", headers={"Authorization": "Bearer public"}, json=payload, ) try: answer = reply.json()["choices"][0]["message"] except Exception: answer = {} check("JSON chat", reply.status_code == 200 and bool(answer), reply.text[:160])
payload["stream"] = True payload["stream_options"] = {"include_usage": True} chunks = 0 done = False with client.stream( "POST", f"{base}/v1/chat/completions", headers={"Authorization": "Bearer public"}, json=payload, ) as stream: check( "SSE content type", stream.headers.get("content-type", "").startswith("text/event-stream"), ) for line in stream.iter_lines(): if not line.startswith("data: "): continue if line[6:] == "[DONE]": done = True else: json.loads(line[6:]) chunks += 1 check("SSE chunks", chunks > 0, str(chunks)) check("SSE done marker", done)
print("\nAll smoke checks passed.")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242from __future__ import annotations
import json
import httpximport pytest
import app as relay
class MockSSEStream(httpx.AsyncByteStream): def __init__(self, content: bytes): self.content = content
async def __aiter__(self): # Two chunks also exercise boundary-transparent forwarding. middle = len(self.content) // 2 yield self.content[:middle] yield self.content[middle:]
@pytest.fixturedef anyio_backend(): return "asyncio"
@pytest.fixture(autouse=True)def reset_state(monkeypatch): relay.model_cache["value"] = None relay.model_cache["stored_at"] = 0.0 relay.rate_buckets.clear() monkeypatch.setattr(relay, "PUBLIC_ACCESS", True) monkeypatch.setattr(relay, "RATE_LIMIT_PER_MINUTE", 0) monkeypatch.setattr(relay, "ALLOWED_MODELS", set())
@pytest.fixturedef mock_upstream(monkeypatch): seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response: if request.url.path.endswith("/models"): return httpx.Response( 200, json={ "object": "list", "data": [ {"id": "coding-model", "object": "model"}, {"id": "vision-model", "object": "model"}, ], }, headers={"x-ratelimit-remaining": "11"}, ) if request.url.path.endswith("/chat/completions"): payload = json.loads(request.content) seen.append(payload) if payload.get("stream"): body = ( 'data: {"id":"one","object":"chat.completion.chunk",' '"choices":[{"index":0,"delta":{"content":"OK"},' '"finish_reason":null}]}\n\n' 'data: {"id":"one","object":"chat.completion.chunk",' '"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n' "data: [DONE]\n\n" ).encode() return httpx.Response( 200, stream=MockSSEStream(body), headers={"content-type": "text/event-stream"}, ) return httpx.Response( 200, json={ "id": "chatcmpl-test", "object": "chat.completion", "model": payload["model"], "choices": [ { "index": 0, "message": { "role": "assistant", "content": None, "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "read_file", "arguments": '{"path":"a.py"}', }, } ], }, "finish_reason": "tool_calls", } ], "usage": {"total_tokens": 12}, }, ) return httpx.Response(404, json={"error": {"message": "not found"}})
client = httpx.AsyncClient( transport=httpx.MockTransport(handler), base_url="https://mock.example/v1" ) monkeypatch.setattr(relay, "upstream_client", client) monkeypatch.setattr(relay, "UPSTREAM_BASE_URL", "https://mock.example/v1") return seen, client
@pytest.mark.anyioasync def test_health_and_home(mock_upstream): _, upstream = mock_upstream async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: health = await client.get("/healthz") assert health.status_code == 200 assert health.json()["ok"] is True home = await client.get("/") assert home.status_code == 200 assert "ZCode provider" in home.text await upstream.aclose()
@pytest.mark.anyioasync def test_dynamic_models_and_cache(mock_upstream): _, upstream = mock_upstream async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: first = await client.get("/v1/models") second = await client.get("/v1/models") assert first.status_code == 200 assert [m["id"] for m in first.json()["data"]] == [ "coding-model", "vision-model", ] assert first.headers["x-model-cache"] == "miss" assert second.headers["x-model-cache"] == "hit" await upstream.aclose()
@pytest.mark.anyioasync def test_tools_and_multimodal_body_are_preserved(mock_upstream): seen, upstream = mock_upstream payload = { "model": "coding-model", "stream": False, "messages": [ { "role": "user", "content": [ {"type": "text", "text": "Inspect this image and file."}, { "type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}, }, ], } ], "tools": [ { "type": "function", "function": { "name": "read_file", "parameters": {"type": "object"}, }, } ], "tool_choice": "required", "parallel_tool_calls": True, "temperature": 0.2, } async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: response = await client.post("/v1/chat/completions", json=payload) assert response.status_code == 200 message = response.json()["choices"][0]["message"] assert message["tool_calls"][0]["function"]["name"] == "read_file" assert seen == [payload] await upstream.aclose()
@pytest.mark.anyioasync def test_sse_is_passed_through(mock_upstream): _, upstream = mock_upstream payload = { "model": "coding-model", "stream": True, "stream_options": {"include_usage": True}, "messages": [{"role": "user", "content": "hello"}], } async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: async with client.stream("POST", "/v1/chat/completions", json=payload) as response: text = (await response.aread()).decode() assert response.status_code == 200 assert response.headers["content-type"].startswith("text/event-stream") assert '"content":"OK"' in text assert "data: [DONE]" in text await upstream.aclose()
@pytest.mark.anyioasync def test_clean_validation_errors(mock_upstream): _, upstream = mock_upstream async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: bad_json = await client.post( "/v1/chat/completions", content=b"{bad", headers={"content-type": "application/json"}, ) assert bad_json.status_code == 400 assert bad_json.json()["error"]["code"] == "invalid_json" bad_shape = await client.post("/v1/chat/completions", json=[]) assert bad_shape.status_code == 400 missing_model = await client.post( "/v1/chat/completions", json={"messages": []} ) assert missing_model.status_code == 400 await upstream.aclose()
@pytest.mark.anyioasync def test_optional_bearer_auth(mock_upstream, monkeypatch): _, upstream = mock_upstream monkeypatch.setattr(relay, "PUBLIC_ACCESS", False) monkeypatch.setattr(relay, "PROVIDER_API_KEY", "secret-value") async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: denied = await client.get("/v1/models") allowed = await client.get( "/v1/models", headers={"authorization": "Bearer secret-value"} ) assert denied.status_code == 401 assert allowed.status_code == 200 await upstream.aclose().dockerignoreAdded+10
.env.exampleAdded+20
.gitignoreAdded+5
DockerfileAdded+23
MakefileAdded+22
README.mdAdded+261
app.pyAdded+498
compose.yamlAdded+17
pytest.iniAdded+4
requirements-dev.txtAdded+3
requirements.txtAdded+3
smoke_test.pyAdded+79
tests/test_app.pyAdded+242