from __future__ import annotations
import os
# Prevent Gradio's optional SSR proxy from reserving the Space's public port.
os.environ["GRADIO_SSR_MODE"] = "false"
# Import ZeroGPU integration before torch / CUDA-aware libraries.
import spaces
import asyncio
import copy
import gc
import json
import logging
import re
import secrets
import threading
import time
import uuid
from pathlib import Path
from typing import Any, Iterator, Optional, Union
import gradio as gr
import torch
import uvicorn
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse
from gradio_client import Client
from huggingface_hub import HfApi, hf_hub_download
from pydantic import BaseModel, ConfigDict, Field
import llama_cpp
from llama_cpp import Llama, llama_supports_gpu_offload
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s %(levelname)s %(process)d %(name)s: %(message)s",
)
logger = logging.getLogger("qwen-zerogpu-api")
PORT = int(os.getenv("PORT", "7860"))
API_KEY = os.getenv("LLAMA_API_KEY", "").strip()
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
SPACE_HOST = os.getenv("SPACE_HOST", "").strip()
DEFAULT_MODEL_ID = "qwen2.5-0.5b"
MODEL_CONFIGS: dict[str, dict[str, Any]] = {
"qwen2.5-0.5b": {
"repo_id": "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF",
"filename": "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf",
"quantization": "Q4_K_M",
"native_context": 32768,
"size_label": "491 MB",
"owned_by": "qwen",
},
"qwen3.5-4b": {
"repo_id": "ggml-org/Qwen3.5-4B-GGUF",
"filename": "Qwen3.5-4B-Q4_K_M.gguf",
"quantization": "Q4_K_M",
"native_context": 262144,
"size_label": "3.03 GB",
"owned_by": "qwen",
},
}
# Backward-compatible name accepted by the model-switch endpoint and chat clients.
MODEL_ALIASES = {"qwen2.5-coder-0.5b-instruct": "qwen2.5-0.5b"}
def canonical_model_id(model_id: str) -> str:
return MODEL_ALIASES.get(model_id, model_id)
def positive_int(name: str, default: int, maximum: int) -> int:
raw = os.getenv(name, str(default))
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError(f"{name} must be an integer, got {raw!r}") from exc
if value < 1 or value > maximum:
raise RuntimeError(f"{name} must be between 1 and {maximum}")
return value
# Keep the default context within the default model's native 32K limit.
DEFAULT_CONTEXT_LIMIT = MODEL_CONFIGS[DEFAULT_MODEL_ID]["native_context"]
DEFAULT_CONTEXT_LENGTH = positive_int(
"LLAMA_N_CTX", min(32768, DEFAULT_CONTEXT_LIMIT), DEFAULT_CONTEXT_LIMIT
)
N_BATCH = positive_int("LLAMA_N_BATCH", 1024, 4096)
N_UBATCH = positive_int("LLAMA_N_UBATCH", 512, N_BATCH)
N_THREADS = positive_int("LLAMA_N_THREADS", 4, 64)
MAX_TOKENS = positive_int("LLAMA_MAX_TOKENS", 8192, 32768)
# Selected model/configuration lives in the long-lived API process. The actual
# llama.cpp instance is worker-local and may disappear when ZeroGPU reclaims it.
_RUNTIME_LOCK = threading.RLock()
_ACTIVE_MODEL_ID = DEFAULT_MODEL_ID
_ACTIVE_CONTEXT_LENGTH = DEFAULT_CONTEXT_LENGTH
_ACTIVE_MODEL_PATH: Optional[str] = None
_MODEL: Optional[Llama] = None
_MODEL_PID: Optional[int] = None
_MODEL_ID_LOADED: Optional[str] = None
_MODEL_CONTEXT_LOADED: Optional[int] = None
# ZeroGPU executes decorated callbacks in isolated worker processes. Model state
# is therefore owned by the API process and passed explicitly into each job.
_MODEL_SWITCHING = False
_MODEL_SWITCH_LOCK = threading.Lock()
def get_model_path(model_id: str) -> str:
config = MODEL_CONFIGS[model_id]
logger.info(
"Downloading/checking model: %s / %s",
config["repo_id"], config["filename"],
)
path = hf_hub_download(
repo_id=config["repo_id"],
filename=config["filename"],
token=HF_TOKEN,
)
size_mb = Path(path).stat().st_size / (1024 * 1024)
logger.info("Model file available: %s (%.1f MiB)", path, size_mb)
return path
def load_llama(model_id: str, model_path: str, context_length: int) -> Llama:
if not llama_supports_gpu_offload():
raise RuntimeError(
"The installed llama.cpp wheel has no usable CUDA backend in this "
"ZeroGPU worker. CPU fallback is intentionally disabled."
)
logger.info(
"Initializing %s with CUDA layer offload; context=%s, n_gpu_layers=-1",
model_id, context_length,
)
started = time.perf_counter()
model = Llama(
model_path=model_path,
n_gpu_layers=-1,
main_gpu=0,
n_ctx=context_length,
n_batch=N_BATCH,
n_ubatch=N_UBATCH,
n_threads=N_THREADS,
n_threads_batch=N_THREADS,
offload_kqv=True,
flash_attn=True,
use_mmap=True,
use_mlock=False,
verbose=os.getenv("LLAMA_VERBOSE", "0") == "1",
)
logger.info(
"Model %s initialized in %.2fs (context=%s)",
model_id, time.perf_counter() - started, context_length,
)
return model
def unload_model() -> None:
global _MODEL, _MODEL_PID, _MODEL_ID_LOADED, _MODEL_CONTEXT_LOADED
old = _MODEL
_MODEL = None
_MODEL_PID = None
_MODEL_ID_LOADED = None
_MODEL_CONTEXT_LOADED = None
if old is not None:
try:
old.close()
except Exception:
logger.exception("Error while closing the previous llama.cpp model")
del old
gc.collect()
try:
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
except Exception:
logger.debug("CUDA cache cleanup was unavailable", exc_info=True)
def ensure_model_loaded(model_id: str, model_path: str, context_length: int) -> Llama:
"""Load/cache the requested model inside the current ZeroGPU worker."""
global _MODEL, _MODEL_PID, _MODEL_ID_LOADED, _MODEL_CONTEXT_LOADED
with _RUNTIME_LOCK:
pid = os.getpid()
if (
_MODEL is not None
and _MODEL_PID == pid
and _MODEL_ID_LOADED == model_id
and _MODEL_CONTEXT_LOADED == context_length
):
return _MODEL
unload_model()
path = model_path
if not path or not Path(path).is_file():
path = get_model_path(model_id)
loaded = load_llama(model_id, path, context_length)
_MODEL = loaded
_MODEL_PID = pid
_MODEL_ID_LOADED = model_id
_MODEL_CONTEXT_LOADED = context_length
return loaded
def ensure_request_model(payload: dict[str, Any]) -> tuple[Llama, str, str, int, bool]:
"""Resolve the active model in this worker; fall back to Qwen2.5-Coder-0.5B on load failure."""
requested_id = str(payload.get("model_id") or DEFAULT_MODEL_ID)
requested_path = str(payload.get("model_path") or DEFAULT_MODEL_PATH)
requested_context = int(payload.get("context_length") or DEFAULT_CONTEXT_LENGTH)
try:
model = ensure_model_loaded(requested_id, requested_path, requested_context)
return model, requested_id, requested_path, requested_context, False
except Exception:
if requested_id == DEFAULT_MODEL_ID:
raise
logger.exception("Could not initialize %s; falling back to %s", requested_id, DEFAULT_MODEL_ID)
fallback_model = ensure_model_loaded(
DEFAULT_MODEL_ID, DEFAULT_MODEL_PATH, DEFAULT_CONTEXT_LENGTH
)
return fallback_model, DEFAULT_MODEL_ID, DEFAULT_MODEL_PATH, DEFAULT_CONTEXT_LENGTH, True
def gpu_inference_duration(payload: dict[str, Any], api_key: str) -> int:
# ZeroGPU checks this declared reservation against remaining quota before
# the job starts. It is not based on the eventual token count/runtime, so
# keep it as tight as safely possible while allowing cold model startup.
try:
requested = int(payload.get("max_tokens") or 256)
except (TypeError, ValueError):
requested = 256
requested = max(1, min(requested, MAX_TOKENS))
active_id = str(payload.get("model_id") or DEFAULT_MODEL_ID)
# Keep reservations close to realistic execution time so short prompts do
# not reserve the same GPU window as long code-generation requests.
# Qwen3.5-4B needs a longer reservation than the smaller default model.
is_large_model = active_id == "qwen3.5-4b"
base = 15 if is_large_model else 8
per_token = 0.020 if is_large_model else 0.012
return min(90, max(base, base + int(requested * per_token)))
def gpu_switch_duration(payload: dict[str, Any], api_key: str) -> int:
# ZeroGPU quota admission uses this declared maximum before execution.
# Model files are downloaded before the callback; this covers unload/setup.
target = str(payload.get("model_id", DEFAULT_MODEL_ID))
return 45 if target == "qwen3.5-4b" else 20
def verify_worker_key(api_key: str) -> None:
if not api_key or not secrets.compare_digest(str(api_key), API_KEY):
raise PermissionError("Invalid API key")
def json_sse(event: str, payload: dict[str, Any]) -> str:
return json.dumps({"event": event, **payload}, ensure_ascii=False)
def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Copy OpenAI messages and convert assistant tool arguments to JSON objects.
Qwen chat templates generally iterate over function.arguments as a mapping;
OpenAI conversation history commonly stores it as a JSON string.
"""
copied = copy.deepcopy(messages)
system_parts: list[str] = []
conversation: list[dict[str, Any]] = []
for message in copied:
role = message.get("role")
if role in {"system", "developer"}:
content = message.get("content")
if isinstance(content, str) and content.strip():
system_parts.append(content.strip())
continue
conversation.append(message)
# Normalize system/developer instructions into one leading system message.
normalized = ([{"role": "system", "content": "\n\n".join(system_parts)}]
if system_parts else []) + conversation
for message in normalized:
if message.get("role") != "assistant":
continue
for tool_call in message.get("tool_calls") or []:
function = tool_call.get("function") or {}
arguments = function.get("arguments")
if isinstance(arguments, str):
try:
parsed = json.loads(arguments)
if isinstance(parsed, dict):
function["arguments"] = parsed
except json.JSONDecodeError:
# Preserve invalid history as a string; the model template
# can still see it, and this API will not execute it.
pass
return normalized
def function_tool_names(tools: Optional[list[dict[str, Any]]]) -> set[str]:
return {
tool.get("function", {}).get("name")
for tool in (tools or [])
if isinstance(tool, dict)
and isinstance(tool.get("function"), dict)
and isinstance(tool.get("function", {}).get("name"), str)
}
_TOOL_BLOCK_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL)
_FUNCTION_RE = re.compile(r"\s]+)>(.*?)", re.DOTALL)
_PARAMETER_RE = re.compile(r"\s]+)>(.*?)", re.DOTALL)
def parse_tool_argument(value: str) -> Any:
value = value.strip()
if not value:
return ""
try:
return json.loads(value)
except json.JSONDecodeError:
return value
def parse_qwen_tool_calls(
content: Optional[str],
tools: Optional[list[dict[str, Any]]],
parallel: bool = True,
) -> tuple[Optional[str], list[dict[str, Any]]]:
"""Convert Qwen2.5 JSON and Qwen3.5 XML tool blocks to OpenAI tool_calls.
Only declared functions are accepted. Unrecognized or malformed blocks stay
in assistant content rather than being turned into executable requests.
"""
if not isinstance(content, str) or not content or not tools:
return content, []
allowed = function_tool_names(tools)
calls: list[dict[str, Any]] = []
removable: list[tuple[int, int]] = []
for block in _TOOL_BLOCK_RE.finditer(content):
raw = block.group(1).strip()
parsed_items: list[tuple[str, Any]] = []
# Qwen2.5 native format: {"name": "fn", "arguments": {...}}
try:
obj = json.loads(raw)
if isinstance(obj, dict) and isinstance(obj.get("name"), str):
parsed_items.append((obj["name"], obj.get("arguments", {})))
except json.JSONDecodeError:
pass
# Qwen3.5 native format: value...
if not parsed_items:
for fn_match in _FUNCTION_RE.finditer(raw):
name = fn_match.group(1).strip()
args: dict[str, Any] = {}
for param in _PARAMETER_RE.finditer(fn_match.group(2)):
args[param.group(1).strip()] = parse_tool_argument(param.group(2))
parsed_items.append((name, args))
block_valid = bool(parsed_items)
block_calls: list[dict[str, Any]] = []
for name, arguments in parsed_items:
if name not in allowed:
block_valid = False
break
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
block_valid = False
break
if not isinstance(arguments, dict):
block_valid = False
break
block_calls.append({
"id": f"call_{uuid.uuid4().hex[:24]}",
"type": "function",
"function": {
"name": name,
"arguments": json.dumps(arguments, ensure_ascii=False, separators=(",", ":")),
},
})
if block_valid and block_calls:
calls.extend(block_calls)
removable.append((block.start(), block.end()))
if not parallel and len(calls) > 1:
calls = calls[:1]
cleaned = content
for start_pos, end_pos in reversed(removable):
cleaned = cleaned[:start_pos] + cleaned[end_pos:]
# Qwen3.5 may include private reasoning markers before the final answer or
# tool call. Do not expose those reasoning spans in the OpenAI content field.
cleaned = re.sub(r".*?\s*", "", cleaned, flags=re.DOTALL).strip()
return cleaned or None, calls
def normalize_tool_response(
result: dict[str, Any],
tools: Optional[list[dict[str, Any]]],
parallel: bool,
) -> dict[str, Any]:
if not tools:
return result
for choice in result.get("choices", []):
message = choice.get("message") or {}
content, parsed_calls = parse_qwen_tool_calls(message.get("content"), tools, parallel)
existing_calls = message.get("tool_calls")
if existing_calls:
calls = list(existing_calls)
if not parallel:
calls = calls[:1]
message["tool_calls"] = calls
message["content"] = content
choice["finish_reason"] = "tool_calls"
elif parsed_calls:
message["content"] = content
message["tool_calls"] = parsed_calls
choice["finish_reason"] = "tool_calls"
else:
message["content"] = content if content is not None else message.get("content")
return result
def tool_choice_instruction(payload: dict[str, Any]) -> Optional[str]:
choice = payload.get("tool_choice")
if choice == "required":
return "You must call one or more of the provided functions. Do not answer with ordinary prose."
if isinstance(choice, dict):
fn = (choice.get("function") or {}).get("name")
if fn:
return f"You must call the function named {fn}. Do not call any other function."
return None
def prepare_messages(payload: dict[str, Any]) -> list[dict[str, Any]]:
messages = normalize_messages(payload["messages"])
instruction = tool_choice_instruction(payload)
if instruction:
# Keep instructions in one leading system message for Qwen chat templates.
if messages and messages[0].get("role") == "system":
existing = messages[0].get("content") or ""
messages[0]["content"] = f"{existing}\n\n{instruction}".strip()
else:
messages.insert(0, {"role": "system", "content": instruction})
return messages
def chat_kwargs(payload: dict[str, Any]) -> dict[str, Any]:
max_tokens = int(payload.get("max_tokens") or 256)
if max_tokens < 1 or max_tokens > MAX_TOKENS:
raise ValueError(f"max_tokens must be between 1 and {MAX_TOKENS}")
kwargs: dict[str, Any] = {
"temperature": float(payload.get("temperature", 0.2)),
"top_p": float(payload.get("top_p", 0.95)),
"max_tokens": max_tokens,
"repeat_penalty": float(payload.get("repeat_penalty", 1.05)),
"presence_penalty": float(payload.get("presence_penalty", 0.0)),
"frequency_penalty": float(payload.get("frequency_penalty", 0.0)),
"stream": bool(payload.get("stream", False)),
"model": str(payload.get("model_id") or DEFAULT_MODEL_ID),
}
if payload.get("stop") is not None:
kwargs["stop"] = payload["stop"]
if payload.get("seed") is not None:
kwargs["seed"] = int(payload["seed"])
# Qwen's bundled templates use the presence of tools to render their native
# function-call instructions. tool_choice='none' deliberately hides tools.
if payload.get("tools") is not None and payload.get("tool_choice") != "none":
kwargs["tools"] = payload["tools"]
# Do not pass tool_choice to llama-cpp-python's generic forced-function
# adapter: that adapter expects a JSON-only function response, while the
# Qwen GGUF templates emit their native markup. Forced selection
# is expressed as a system instruction and parsed from the native format.
return kwargs
def limit_tool_calls(result: dict[str, Any], parallel: bool) -> dict[str, Any]:
if parallel:
return result
for choice in result.get("choices", []):
calls = (choice.get("message") or {}).get("tool_calls")
if isinstance(calls, list) and len(calls) > 1:
choice["message"]["tool_calls"] = calls[:1]
return result
def openai_stream_chunk(base: dict[str, Any], delta: dict[str, Any], finish_reason: Optional[str] = None) -> str:
chunk = {
"id": base.get("id", f"chatcmpl-{uuid.uuid4().hex}"),
"object": "chat.completion.chunk",
"created": base.get("created", int(time.time())),
"model": base.get("model", _ACTIVE_MODEL_ID),
"choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
}
if base.get("system_fingerprint") is not None:
chunk["system_fingerprint"] = base["system_fingerprint"]
return "data: " + json.dumps(chunk, ensure_ascii=False) + "\n\n"
def stream_tool_aware_completion(model: Llama, payload: dict[str, Any], kwargs: dict[str, Any]) -> Iterator[str]:
"""Stream text natively; normalize Qwen's textual tool markup to OpenAI SSE.
Tool-enabled generations are buffered until completion because Qwen emits
tool markup as ordinary text tokens under its GGUF Jinja template. Once the
complete block is validated, its structured OpenAI tool-call deltas are
streamed. Non-tool text requests remain token-live.
"""
has_tools = bool(payload.get("tools")) and payload.get("tool_choice") != "none"
if not has_tools:
for chunk in model.create_chat_completion(
messages=normalize_messages(payload["messages"]), **kwargs
):
yield "data: " + json.dumps(chunk, ensure_ascii=False) + "\n\n"
return
meta: dict[str, Any] = {}
content_parts: list[str] = []
native_calls: dict[int, dict[str, Any]] = {}
finish_reason = "stop"
for chunk in model.create_chat_completion(
messages=normalize_messages(payload["messages"]), **kwargs
):
if not meta:
meta = dict(chunk)
for choice in chunk.get("choices", []):
finish_reason = choice.get("finish_reason") or finish_reason
delta = choice.get("delta") or {}
if isinstance(delta.get("content"), str):
content_parts.append(delta["content"])
for call in delta.get("tool_calls") or []:
idx = int(call.get("index", 0))
current = native_calls.setdefault(idx, {
"id": call.get("id"), "type": call.get("type", "function"),
"function": {"name": "", "arguments": ""},
})
if call.get("id"):
current["id"] = call["id"]
function = call.get("function") or {}
if function.get("name"):
current["function"]["name"] += function["name"]
if function.get("arguments"):
current["function"]["arguments"] += function["arguments"]
raw_content = "".join(content_parts)
content, parsed_calls = parse_qwen_tool_calls(
raw_content,
payload.get("tools"),
bool(payload.get("parallel_tool_calls", True)),
)
calls = [native_calls[index] for index in sorted(native_calls)]
if parsed_calls:
calls = parsed_calls
elif not bool(payload.get("parallel_tool_calls", True)):
calls = calls[:1]
yield openai_stream_chunk(meta, {"role": "assistant"})
if content:
for offset in range(0, len(content), 64):
yield openai_stream_chunk(meta, {"content": content[offset:offset + 64]})
for index, call in enumerate(calls):
function = call.get("function") or {}
call_id = call.get("id") or f"call_{uuid.uuid4().hex[:24]}"
name = function.get("name", "")
arguments = function.get("arguments", "{}")
if not isinstance(arguments, str):
arguments = json.dumps(arguments, ensure_ascii=False, separators=(",", ":"))
yield openai_stream_chunk(meta, {
"tool_calls": [{
"index": index,
"id": call_id,
"type": "function",
"function": {"name": name, "arguments": ""},
}]
})
for offset in range(0, len(arguments), 64):
yield openai_stream_chunk(meta, {
"tool_calls": [{
"index": index,
"function": {"arguments": arguments[offset:offset + 64]},
}]
})
yield openai_stream_chunk(meta, {}, "tool_calls" if calls else finish_reason)
return
@spaces.GPU(duration=gpu_inference_duration)
def gpu_text_completion(payload: dict[str, Any], api_key: str) -> dict[str, Any]:
verify_worker_key(api_key)
model, model_id, model_path, context_length, used_fallback = ensure_request_model(payload)
max_tokens = int(payload.get("max_tokens") or 256)
if max_tokens < 1 or max_tokens > MAX_TOKENS:
raise ValueError(f"max_tokens must be between 1 and {MAX_TOKENS}")
kwargs: dict[str, Any] = {
"prompt": payload["prompt"],
"temperature": float(payload.get("temperature", 0.2)),
"top_p": float(payload.get("top_p", 0.95)),
"max_tokens": max_tokens,
"repeat_penalty": float(payload.get("repeat_penalty", 1.05)),
"stream": False,
"model": model_id,
}
if payload.get("stop") is not None:
kwargs["stop"] = payload["stop"]
if payload.get("seed") is not None:
kwargs["seed"] = int(payload["seed"])
result = model.create_completion(**kwargs)
result["model"] = model_id
if used_fallback:
result["x_model_fallback"] = DEFAULT_MODEL_ID
return result
@spaces.GPU(duration=gpu_inference_duration)
def gpu_chat_completion(payload: dict[str, Any], api_key: str) -> dict[str, Any]:
verify_worker_key(api_key)
model, model_id, model_path, context_length, used_fallback = ensure_request_model(payload)
active_payload = {**payload, "model_id": model_id, "model_path": model_path, "context_length": context_length}
started = time.perf_counter()
kwargs = chat_kwargs(active_payload)
kwargs["stream"] = False
messages = prepare_messages(active_payload)
result = model.create_chat_completion(messages=messages, **kwargs)
result = normalize_tool_response(
result,
payload.get("tools") if payload.get("tool_choice") != "none" else None,
bool(payload.get("parallel_tool_calls", True)),
)
result = limit_tool_calls(result, bool(payload.get("parallel_tool_calls", True)))
result["model"] = model_id
if used_fallback:
result["x_model_fallback"] = DEFAULT_MODEL_ID
elapsed = max(time.perf_counter() - started, 1e-6)
usage = result.get("usage", {})
completion_tokens = int(usage.get("completion_tokens", 0))
logger.info(
"Chat completed: model=%s, output_tokens=%s, elapsed=%.3fs, tok_s=%.2f, tool_calls=%s",
model_id, completion_tokens, elapsed,
completion_tokens / elapsed, bool((result.get("choices", [{}])[0].get("message") or {}).get("tool_calls")),
)
return result
@spaces.GPU(duration=gpu_inference_duration)
def gpu_chat_stream(payload: dict[str, Any], api_key: str) -> Iterator[str]:
verify_worker_key(api_key)
try:
model, model_id, model_path, context_length, used_fallback = ensure_request_model(payload)
stream_payload = {
**payload,
"model_id": model_id,
"model_path": model_path,
"context_length": context_length,
}
kwargs = chat_kwargs(stream_payload)
kwargs["stream"] = True
if used_fallback:
# This comment is consumed by the REST bridge and never reaches clients.
yield f": qwen-model-fallback={DEFAULT_MODEL_ID}\n\n"
stream_payload["messages"] = prepare_messages(stream_payload)
yield from stream_tool_aware_completion(model, stream_payload, kwargs)
yield "data: [DONE]\n\n"
except Exception as exc:
logger.exception("Streaming inference failed")
error = {"error": {"message": str(exc), "type": "server_error"}}
yield "data: " + json.dumps(error, ensure_ascii=False) + "\n\n"
yield "data: [DONE]\n\n"
@spaces.GPU(duration=gpu_switch_duration)
def gpu_switch_model(payload: dict[str, Any], api_key: str) -> Iterator[str]:
"""Switch the in-memory model inside a scheduled ZeroGPU callback."""
global _MODEL, _MODEL_PID, _MODEL_ID_LOADED, _MODEL_CONTEXT_LOADED
verify_worker_key(api_key)
target_id = str(payload["model_id"])
context_length = int(payload["context_length"])
target_path = str(payload["model_path"])
if target_id not in MODEL_CONFIGS:
yield json_sse("error", {"message": "Unsupported model"})
return
logger.info("Model switch requested: %s (context=%s)", target_id, context_length)
yield json_sse("log", {"message": "Unloading the currently loaded model"})
with _RUNTIME_LOCK:
unload_model()
yield json_sse("progress", {"message": "Previous model unloaded; preparing the selected model"})
try:
yield json_sse("log", {"message": "Initializing llama.cpp with full CUDA layer offload"})
loaded = load_llama(target_id, target_path, context_length)
_MODEL = loaded
_MODEL_PID = os.getpid()
_MODEL_ID_LOADED = target_id
_MODEL_CONTEXT_LOADED = context_length
logger.info("Model switch completed: %s context=%s", target_id, context_length)
yield json_sse("done", {
"status": "success",
"model": target_id,
"context_length": context_length,
"message": "Model is ready",
})
return
except Exception as selected_error:
logger.exception("Could not initialize requested model %s", target_id)
yield json_sse("error", {
"message": f"Could not load {target_id}: {selected_error}",
"fallback": DEFAULT_MODEL_ID,
})
# The fallback model is always the default Qwen2.5-Coder-0.5B. It was
# downloaded at app startup and remains in the Hub cache after unloading.
try:
yield json_sse("log", {"message": "Loading fallback model Qwen2.5-Coder-0.5B"})
fallback_path = DEFAULT_MODEL_PATH
fallback = load_llama(DEFAULT_MODEL_ID, fallback_path, DEFAULT_CONTEXT_LENGTH)
_MODEL = fallback
_MODEL_PID = os.getpid()
_MODEL_ID_LOADED = DEFAULT_MODEL_ID
_MODEL_CONTEXT_LOADED = DEFAULT_CONTEXT_LENGTH
logger.info("Fallback model restored: %s", DEFAULT_MODEL_ID)
yield json_sse("done", {
"status": "fallback",
"model": DEFAULT_MODEL_ID,
"context_length": DEFAULT_CONTEXT_LENGTH,
"message": "Requested model failed; default model restored",
})
except Exception as fallback_error:
logger.exception("Could not restore default fallback model")
yield json_sse("error", {
"status": "failed",
"model": DEFAULT_MODEL_ID,
"message": f"Requested model and fallback failed: {fallback_error}",
})
class ChatRequest(BaseModel):
model: Optional[str] = None
messages: list[dict[str, Any]]
temperature: float = Field(default=0.2, ge=0, le=2)
top_p: float = Field(default=0.95, gt=0, le=1)
max_tokens: int = Field(default=256, ge=1, le=MAX_TOKENS)
stream: bool = False
stop: Optional[Union[str, list[str]]] = None
presence_penalty: float = Field(default=0.0, ge=-2, le=2)
frequency_penalty: float = Field(default=0.0, ge=-2, le=2)
repeat_penalty: float = Field(default=1.05, ge=0.5, le=2)
seed: Optional[int] = None
tools: Optional[list[dict[str, Any]]] = None
tool_choice: Optional[Union[str, dict[str, Any]]] = None
parallel_tool_calls: bool = True
model_config = ConfigDict(extra="ignore")
class CompletionRequest(BaseModel):
model: Optional[str] = None
prompt: str
temperature: float = Field(default=0.2, ge=0, le=2)
top_p: float = Field(default=0.95, gt=0, le=1)
max_tokens: int = Field(default=256, ge=1, le=MAX_TOKENS)
stream: bool = False
stop: Optional[Union[str, list[str]]] = None
repeat_penalty: float = Field(default=1.05, ge=0.5, le=2)
seed: Optional[int] = None
model_config = ConfigDict(extra="ignore")
if not API_KEY:
raise RuntimeError("Missing required Space Secret LLAMA_API_KEY")
if not HF_TOKEN:
raise RuntimeError("Missing required Space Secret HF_TOKEN (read access)")
if not SPACE_HOST:
raise RuntimeError("Missing Hugging Face SPACE_HOST environment variable")
try:
HF_USER = HfApi(token=HF_TOKEN).whoami()
HF_TOKEN_VALID = True
logger.info("HF_TOKEN validated for account: %s", HF_USER.get("name", "authenticated user"))
except Exception as exc:
raise RuntimeError("HF_TOKEN is invalid. Create a read token at https://huggingface.co/settings/tokens") from exc
# Default model download happens on CPU during startup, not inside a GPU
# allocation. This also guarantees a local fallback file is available.
DEFAULT_MODEL_PATH = get_model_path(DEFAULT_MODEL_ID)
_ACTIVE_MODEL_PATH = DEFAULT_MODEL_PATH
api = FastAPI(
title="Qwen ZeroGPU OpenAI-compatible API",
version="3.0.0",
description=(
"OpenAI-compatible API for Qwen2.5-Coder-0.5B-Instruct and Qwen3.5-4B "
"using llama.cpp CUDA on Hugging Face ZeroGPU. Includes tool calling and SSE model switching."
),
)
api.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-IP-Token"],
)
def require_api_key(authorization: Optional[str] = Header(default=None)) -> None:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing Bearer API key")
supplied = authorization[7:].strip()
if not secrets.compare_digest(supplied, API_KEY):
raise HTTPException(status_code=401, detail="Invalid API key")
def require_query_api_key(api_key: str) -> None:
if not secrets.compare_digest(api_key, API_KEY):
raise HTTPException(status_code=401, detail="Invalid API key")
from functools import lru_cache
@lru_cache(maxsize=1)
def get_internal_gradio_client() -> Client:
url = f"https://{SPACE_HOST}/console"
logger.info("Connecting internal Gradio client through HF gateway: %s", url)
return Client(
url,
token=HF_TOKEN,
verbose=False,
analytics_enabled=False,
max_workers=8,
)
def submit_gpu_job(api_name: str, payload: dict[str, Any]):
# Use the public HF gateway and the Space owner's authenticated token.
return get_internal_gradio_client().submit(payload, API_KEY, api_name=api_name)
def attach_active_model(payload: dict[str, Any]) -> dict[str, Any]:
"""Pass authoritative API-process model state into a ZeroGPU callback."""
return {
**payload,
"model_id": _ACTIVE_MODEL_ID,
"model_path": _ACTIVE_MODEL_PATH or DEFAULT_MODEL_PATH,
"context_length": _ACTIVE_CONTEXT_LENGTH,
}
def set_active_default_after_fallback() -> None:
global _ACTIVE_MODEL_ID, _ACTIVE_MODEL_PATH, _ACTIVE_CONTEXT_LENGTH
_ACTIVE_MODEL_ID = DEFAULT_MODEL_ID
_ACTIVE_MODEL_PATH = DEFAULT_MODEL_PATH
_ACTIVE_CONTEXT_LENGTH = DEFAULT_CONTEXT_LENGTH
def sync_result_model(result: dict[str, Any]) -> None:
if result.get("model") == DEFAULT_MODEL_ID and _ACTIVE_MODEL_ID != DEFAULT_MODEL_ID:
set_active_default_after_fallback()
logger.warning("Inference switched to the default fallback model %s", DEFAULT_MODEL_ID)
def validate_tools(body: ChatRequest) -> None:
if body.tool_choice is not None and body.tools is None:
raise HTTPException(status_code=422, detail="tool_choice requires tools")
if body.tools is None:
return
if not body.tools:
raise HTTPException(status_code=422, detail="tools must not be an empty array")
names: set[str] = set()
for index, tool in enumerate(body.tools):
if tool.get("type") != "function":
raise HTTPException(status_code=422, detail=f"tools[{index}].type must be 'function'")
fn = tool.get("function")
if not isinstance(fn, dict):
raise HTTPException(status_code=422, detail=f"tools[{index}].function must be an object")
name = fn.get("name")
if not isinstance(name, str) or not name.strip():
raise HTTPException(status_code=422, detail=f"tools[{index}].function.name is required")
if name in names:
raise HTTPException(status_code=422, detail=f"Duplicate tool function name: {name}")
names.add(name)
parameters = fn.get("parameters", {"type": "object"})
if not isinstance(parameters, dict) or parameters.get("type") not in (None, "object"):
raise HTTPException(status_code=422, detail=f"tools[{index}].function.parameters must be a JSON Schema object")
choice = body.tool_choice
if isinstance(choice, str) and choice not in {"none", "auto", "required"}:
raise HTTPException(status_code=422, detail="tool_choice must be none, auto, required, or a function selector object")
if isinstance(choice, dict):
if choice.get("type") != "function" or not isinstance(choice.get("function"), dict):
raise HTTPException(status_code=422, detail="Named tool_choice must use {type: 'function', function: {name: ...}}")
selected_name = choice["function"].get("name")
if selected_name not in names:
raise HTTPException(status_code=422, detail="tool_choice references a function not declared in tools")
def validate_active_model(requested: Optional[str]) -> None:
normalized = canonical_model_id(requested) if requested is not None else None
if normalized is not None and normalized != _ACTIVE_MODEL_ID:
raise HTTPException(
status_code=409,
detail=f"Requested model '{requested}' is not active. Current model is '{_ACTIVE_MODEL_ID}'. Use GET /v1/model/switch first.",
)
def sse_event(event: str, data: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
@api.get("/health")
def health() -> dict[str, Any]:
return {
"status": "ok",
"model": _ACTIVE_MODEL_ID,
"default_model": DEFAULT_MODEL_ID,
"fallback_model": DEFAULT_MODEL_ID,
"available_models": list(MODEL_CONFIGS),
"quantization": MODEL_CONFIGS[_ACTIVE_MODEL_ID]["quantization"],
"runtime": "llama.cpp",
"gpu": "Hugging Face ZeroGPU on-demand CUDA",
"context_length": _ACTIVE_CONTEXT_LENGTH,
"native_context_limit": MODEL_CONFIGS[_ACTIVE_MODEL_ID]["native_context"],
"model_downloaded": bool(_ACTIVE_MODEL_PATH and Path(_ACTIVE_MODEL_PATH).is_file()),
"model_loaded": None,
"model_runtime": "Loaded on demand inside isolated ZeroGPU workers",
"model_switching": _MODEL_SWITCHING,
"hf_token_configured": bool(HF_TOKEN),
"hf_token_valid": HF_TOKEN_VALID,
"internal_gradio_target": f"https://{SPACE_HOST}/console",
}
@api.get("/v1/models", dependencies=[Depends(require_api_key)])
def list_models() -> dict[str, Any]:
return {
"object": "list",
"data": [
{
"id": model_id,
"object": "model",
"created": 0,
"owned_by": config["owned_by"],
"active": model_id == _ACTIVE_MODEL_ID,
"switching": _MODEL_SWITCHING,
"quantization": config["quantization"],
"context_length": _ACTIVE_CONTEXT_LENGTH if model_id == _ACTIVE_MODEL_ID else min(DEFAULT_CONTEXT_LENGTH, config["native_context"]),
"native_context_limit": config["native_context"],
}
for model_id, config in MODEL_CONFIGS.items()
],
}
@api.get("/v1/context", dependencies=[Depends(require_api_key)])
def context_info() -> dict[str, Any]:
return {
"model": _ACTIVE_MODEL_ID,
"context_length": _ACTIVE_CONTEXT_LENGTH,
"native_context_limit": MODEL_CONFIGS[_ACTIVE_MODEL_ID]["native_context"],
"max_tokens_limit": min(MAX_TOKENS, _ACTIVE_CONTEXT_LENGTH),
}
@api.get("/v1/model/switch")
async def switch_model(
request: Request,
model: str = Query(..., description="qwen2.5-0.5b or qwen3.5-4b"),
api_key: str = Query(..., description="LLAMA_API_KEY; query auth requested for EventSource compatibility"),
context_length: Optional[int] = Query(None, ge=2048, le=262144),
):
# Query credentials are supported for browser EventSource; they can appear
# in URL history/proxy logs, so use a Bearer header when possible.
require_query_api_key(api_key)
model = canonical_model_id(model)
if model not in MODEL_CONFIGS:
supported = [*MODEL_CONFIGS, *MODEL_ALIASES]
raise HTTPException(status_code=400, detail=f"Unsupported model. Available: {', '.join(supported)}")
selected_context = context_length or min(DEFAULT_CONTEXT_LENGTH, MODEL_CONFIGS[model]["native_context"])
if selected_context > MODEL_CONFIGS[model]["native_context"]:
raise HTTPException(
status_code=400,
detail=f"{model} supports at most {MODEL_CONFIGS[model]['native_context']} context tokens",
)
if selected_context < 2048:
raise HTTPException(status_code=400, detail="context_length must be at least 2048")
async def event_stream():
global _ACTIVE_MODEL_ID, _ACTIVE_CONTEXT_LENGTH, _ACTIVE_MODEL_PATH, _MODEL_SWITCHING
acquired = await asyncio.to_thread(_MODEL_SWITCH_LOCK.acquire)
if not acquired:
yield sse_event("error", {"message": "Could not acquire model-switch lock"})
yield sse_event("close", {"message": "Model switch stream finished with an error"})
return
_MODEL_SWITCHING = True
try:
yield sse_event("progress", {"stage": "validation", "message": "Validating model request"})
logger.info("Model switch HTTP request accepted: target=%s context=%s", model, selected_context)
if model == _ACTIVE_MODEL_ID and selected_context == _ACTIVE_CONTEXT_LENGTH:
yield sse_event("log", {"message": "Requested model and context are already active; no GPU allocation needed"})
yield sse_event("done", {
"status": "unchanged",
"model": _ACTIVE_MODEL_ID,
"context_length": _ACTIVE_CONTEXT_LENGTH,
"message": "Requested model and context are already active",
})
yield sse_event("close", {"message": "Model switch stream finished; no changes were needed"})
return
config = MODEL_CONFIGS[model]
yield sse_event("log", {"message": f"Checking availability: {config['repo_id']} / {config['filename']}"})
def preflight() -> None:
info = HfApi(token=HF_TOKEN).model_info(config["repo_id"], files_metadata=True)
filenames = {item.rfilename for item in (info.siblings or [])}
if config["filename"] not in filenames:
raise FileNotFoundError(f"{config['filename']} not found in {config['repo_id']}")
await asyncio.to_thread(preflight)
yield sse_event("progress", {"stage": "available", "message": "Model repository and GGUF file are available"})
# Download before requesting GPU time. This keeps the network transfer
# outside the ZeroGPU reservation; the worker unloads old VRAM state
# and initializes the target model after the file is cached locally.
yield sse_event("log", {"message": "Downloading/checking the selected GGUF in the Space cache before GPU allocation"})
model_path = await asyncio.to_thread(get_model_path, model)
yield sse_event("progress", {"stage": "downloaded", "message": "Model file is ready; preparing the ZeroGPU worker", "size": config["size_label"]})
yield sse_event("log", {"message": "Submitting unload and CUDA model setup to the ZeroGPU queue"})
payload = {
"model_id": model,
"model_path": model_path,
"context_length": selected_context,
}
job = await asyncio.to_thread(submit_gpu_job, "/gpu_switch_model", payload)
iterator = iter(job)
sentinel = object()
def read_next():
try:
return next(iterator)
except StopIteration:
return sentinel
switch_outcome: Optional[str] = None
while True:
update = await asyncio.to_thread(read_next)
if update is sentinel:
break
if isinstance(update, str):
try:
data = json.loads(update)
event = data.pop("event", "progress")
if event == "done":
switch_outcome = str(data.get("status", "success"))
if switch_outcome == "success":
_ACTIVE_MODEL_ID = model
_ACTIVE_CONTEXT_LENGTH = selected_context
_ACTIVE_MODEL_PATH = model_path
else:
# Any fallback outcome is pinned to the default.
_ACTIVE_MODEL_ID = DEFAULT_MODEL_ID
_ACTIVE_CONTEXT_LENGTH = DEFAULT_CONTEXT_LENGTH
_ACTIVE_MODEL_PATH = DEFAULT_MODEL_PATH
elif event == "error" and data.get("status") == "failed":
switch_outcome = "failed"
_ACTIVE_MODEL_ID = DEFAULT_MODEL_ID
_ACTIVE_CONTEXT_LENGTH = DEFAULT_CONTEXT_LENGTH
_ACTIVE_MODEL_PATH = DEFAULT_MODEL_PATH
yield sse_event(event, data)
except json.JSONDecodeError:
yield sse_event("log", {"message": update})
if switch_outcome is None:
yield sse_event("error", {"message": "ZeroGPU switch job ended without a done event"})
_ACTIVE_MODEL_ID = DEFAULT_MODEL_ID
_ACTIVE_CONTEXT_LENGTH = DEFAULT_CONTEXT_LENGTH
_ACTIVE_MODEL_PATH = DEFAULT_MODEL_PATH
yield sse_event("close", {"message": "Model switch stream finished"})
except Exception as exc:
logger.exception("Model switch failed: target=%s", model)
# Any failure after the request enters the SSE workflow leaves the
# API selection pinned to the Qwen2.5 default. The next GPU job will
# load it explicitly even if a warm worker held another model.
_ACTIVE_MODEL_ID = DEFAULT_MODEL_ID
_ACTIVE_CONTEXT_LENGTH = DEFAULT_CONTEXT_LENGTH
_ACTIVE_MODEL_PATH = DEFAULT_MODEL_PATH
yield sse_event("error", {
"message": str(exc),
"fallback_model": DEFAULT_MODEL_ID,
"current_model": _ACTIVE_MODEL_ID,
})
yield sse_event("close", {"message": "Model switch stream finished with an error; default model selected"})
finally:
_MODEL_SWITCHING = False
_MODEL_SWITCH_LOCK.release()
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache, no-transform",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@api.post("/v1/chat/completions", dependencies=[Depends(require_api_key)])
def chat_completions(body: ChatRequest):
if _MODEL_SWITCHING:
raise HTTPException(status_code=409, detail="A model switch is in progress; retry after the SSE stream reports done")
if not body.messages:
raise HTTPException(status_code=422, detail="messages must contain at least one item")
validate_active_model(body.model)
validate_tools(body)
if body.max_tokens > _ACTIVE_CONTEXT_LENGTH:
raise HTTPException(status_code=422, detail="max_tokens cannot exceed the active context length")
payload = attach_active_model(body.model_dump(exclude_none=True))
payload["model"] = _ACTIVE_MODEL_ID
try:
if body.stream:
job = submit_gpu_job("/gpu_chat_stream", payload)
def stream_job() -> Iterator[str]:
try:
for update in job:
if isinstance(update, str):
if update.startswith(": qwen-model-fallback="):
set_active_default_after_fallback()
logger.warning("Streaming inference selected fallback model %s", DEFAULT_MODEL_ID)
continue
yield update
except Exception as exc:
logger.exception("ZeroGPU streaming job failed")
yield "data: " + json.dumps({"error": {"message": str(exc), "type": "server_error"}}) + "\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(
stream_job(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
)
result = submit_gpu_job("/gpu_chat_completion", payload).result()
if isinstance(result, dict):
sync_result_model(result)
return result
except HTTPException:
raise
except Exception as exc:
logger.exception("Chat completion failed")
raise HTTPException(status_code=503, detail=f"Inference unavailable: {exc}") from exc
@api.post("/v1/completions", dependencies=[Depends(require_api_key)])
def text_completions(body: CompletionRequest):
if _MODEL_SWITCHING:
raise HTTPException(status_code=409, detail="A model switch is in progress; retry after the SSE stream reports done")
validate_active_model(body.model)
if body.stream:
raise HTTPException(status_code=400, detail="Streaming legacy completions is not enabled; use /v1/chat/completions")
try:
payload = attach_active_model(body.model_dump(exclude_none=True))
payload["model"] = _ACTIVE_MODEL_ID
result = submit_gpu_job("/gpu_text_completion", payload).result()
if isinstance(result, dict):
sync_result_model(result)
return result
except Exception as exc:
logger.exception("Text completion failed")
raise HTTPException(status_code=503, detail=f"Inference unavailable: {exc}") from exc
# Register all ZeroGPU callbacks as hidden Gradio API events. External tools are
# described to the model; this Space never executes caller-supplied tool code.
with gr.Blocks(title="Qwen ZeroGPU OpenAI API", analytics_enabled=False) as demo:
gr.Markdown(
"""
# Qwen ZeroGPU API
**Default:** Qwen2.5-Coder-0.5B-Instruct Q4_K_M · **Alternative:** Qwen3.5-4B Q4_K_M
**Runtime:** llama.cpp CUDA · Hugging Face ZeroGPU
**REST:** `/v1` · **Tool calls:** OpenAI-compatible, caller-executed
"""
)
with gr.Row(visible=False):
chat_payload = gr.JSON(value={"messages": [{"role": "user", "content": "ping"}]})
chat_key = gr.Textbox(value="", type="password")
chat_output = gr.JSON()
chat_button = gr.Button("Register chat callback")
chat_button.click(gpu_chat_completion, [chat_payload, chat_key], chat_output, api_name="gpu_chat_completion")
with gr.Row(visible=False):
stream_payload = gr.JSON(value={"messages": [{"role": "user", "content": "ping"}]})
stream_key = gr.Textbox(value="", type="password")
stream_output = gr.Textbox()
stream_button = gr.Button("Register stream callback")
stream_button.click(gpu_chat_stream, [stream_payload, stream_key], stream_output, api_name="gpu_chat_stream")
with gr.Row(visible=False):
legacy_payload = gr.JSON(value={"prompt": "ping"})
legacy_key = gr.Textbox(value="", type="password")
legacy_output = gr.JSON()
legacy_button = gr.Button("Register legacy completion callback")
legacy_button.click(gpu_text_completion, [legacy_payload, legacy_key], legacy_output, api_name="gpu_text_completion")
with gr.Row(visible=False):
switch_payload = gr.JSON(value={"model_id": DEFAULT_MODEL_ID, "model_path": "", "context_length": DEFAULT_CONTEXT_LENGTH})
switch_key = gr.Textbox(value="", type="password")
switch_output = gr.Textbox()
switch_button = gr.Button("Register model switch callback")
switch_button.click(gpu_switch_model, [switch_payload, switch_key], switch_output, api_name="gpu_switch_model")
demo.queue(default_concurrency_limit=1, max_size=32)
@api.get("/", include_in_schema=False)
def root():
return RedirectResponse(url="/console")
app = gr.mount_gradio_app(api, demo, path="/console")
if __name__ == "__main__":
logger.info("llama-cpp-python version: %s", getattr(llama_cpp, "__version__", "unknown"))
logger.info("Default model: %s (context=%s)", DEFAULT_MODEL_ID, DEFAULT_CONTEXT_LENGTH)
# Disable access logs because the model-switch endpoint accepts api_key in
# the query string for SSE/EventSource compatibility.
uvicorn.run(
app,
host="0.0.0.0",
port=PORT,
log_level=os.getenv("LOG_LEVEL", "info").lower(),
access_log=False,
)