Spaces:
Running on Zero
Running on Zero
Upload 6 files
Browse filesFiles changed (6)
- .env.exampleAdded+10
- .gitignoreAdded+6
- README.mdAdded+168
- app.pyAdded+136
- packages.txtAdded+4
- requirements.txtAdded+3
12345678910# Required. Put the real value in Hugging Face Space Secrets, not in Git.LLAMA_API_KEY=replace-with-a-long-random-secret
# Optional performance/model overrides:# LLAMA_N_THREADS=2# LLAMA_N_THREADS_BATCH=2# LLAMA_N_CTX=2048# LLAMA_N_BATCH=512# LLAMA_N_UBATCH=256# MODEL_ALIAS=qwen2.5-coder-0.5b-instruct123456.env.venv/__pycache__/*.py[cod].cache/models/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168---title: Qwen2.5 Coder 0.5B APIemoji: ⚡colorFrom: bluecolorTo: purplesdk: gradiopython_version: "3.11"app_file: app.py---
# Qwen2.5-Coder-0.5B-Instruct REST API
A Hugging Face **Gradio SDK Space** that serves the official Qwen2.5-Coder-0.5B-Instruct `Q4_K_M` GGUF model through a llama.cpp-backed, OpenAI-compatible REST API.
- Model: `Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF`- Quantization: `Q4_K_M` (about 491 MB on the Hub)- Runtime: `llama-cpp-python` (Python bindings to llama.cpp)- Default hardware target: Hugging Face CPU Basic (2 vCPU / 16 GB RAM)- Authentication: one required bearer API key from the Space Secret `LLAMA_API_KEY`- Streaming: supported by `/v1/chat/completions`- Docker: **not required**
## Deploy to Hugging Face Spaces
1. Create a new Space and select **Gradio** as the SDK.2. Upload or push all files from this project to the Space repository.3. Open **Settings → Variables and secrets**.4. Add a **Secret** named `LLAMA_API_KEY` and set a long, random value. Do not put the key in this repository or in a normal variable.5. Select **CPU Basic** hardware if it is not already selected, then let the Space build and start.6. Once it is running, the API base URL is:
`https://YOUR-SPACE-NAME.hf.space/v1`
The model file is downloaded automatically from the official Qwen repository on first startup. It is not included in this ZIP.
> **Hugging Face plan note (checked November 19, 2026):** Hugging Face documents CPU Basic as 2 vCPU / 16 GB RAM with no hourly compute charge, but creating a compute-backed Gradio or Docker Space on a personal account requires PRO. Free personal accounts can still run up to two Gradio Spaces on ZeroGPU; this project is a CPU-based llama.cpp service, not a ZeroGPU app. So the runtime hardware can be CPU Basic at no hourly cost, but a free personal account alone may not be able to create/run this kind of Space.
## API authentication
Every `/v1` inference/API request must include the single Space Secret as a Bearer token:
```httpAuthorization: Bearer YOUR_LLAMA_API_KEY```
The key is checked by the llama-cpp-python API server. The public `/health` endpoint is intentionally unauthenticated so hosting health checks can reach it. Do not expose or share the key.
## Endpoints
| Method | Endpoint | Authentication | Purpose ||---|---|---|---|| `GET` | `/health` | No | Health check || `GET` | `/v1/models` | Bearer key | List the served model || `POST` | `/v1/chat/completions` | Bearer key | Chat Completions; supports streaming || `POST` | `/v1/completions` | Bearer key | Text Completions || `GET` | `/docs` | No | OpenAPI documentation || `GET` | `/console` | No | Small deployment/API information page |
## Quick test with curl
Replace the Space URL and key:
```bashcurl https://YOUR-SPACE-NAME.hf.space/health```
```bashcurl https://YOUR-SPACE-NAME.hf.space/v1/chat/completions \ -H "Authorization: Bearer YOUR_LLAMA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen2.5-coder-0.5b-instruct", "messages": [ {"role": "system", "content": "You are a precise coding assistant."}, {"role": "user", "content": "Write a JavaScript function that checks whether a string is a palindrome."} ], "temperature": 0.2, "max_tokens": 256, "stream": false }'```
Streaming response:
```bashcurl -N https://YOUR-SPACE-NAME.hf.space/v1/chat/completions \ -H "Authorization: Bearer YOUR_LLAMA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen2.5-coder-0.5b-instruct", "messages": [{"role": "user", "content": "Explain JavaScript promises in three bullet points."}], "max_tokens": 256, "stream": true }'```
## Use with the OpenAI SDK
```bashnpm install openai```
```jsimport OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://YOUR-SPACE-NAME.hf.space/v1", apiKey: process.env.LLAMA_API_KEY,});
const response = await client.chat.completions.create({ model: "qwen2.5-coder-0.5b-instruct", messages: [{ role: "user", content: "Write a TypeScript debounce function." }], max_tokens: 256,});
console.log(response.choices[0].message.content);```
Set `LLAMA_API_KEY` in your local shell for the client example. The server-side key belongs only in Hugging Face Space Secrets.
## Performance settings
This project is biased toward generation speed on a small CPU instance:
- Builds llama-cpp-python from source with `GGML_NATIVE`, OpenMP, and OpenBLAS enabled. `GGML_NATIVE` lets the compiler use the CPU instructions available during the build.- Uses two inference threads by default to match CPU Basic's two vCPUs.- Uses memory-mapped model loading, a 512-token logical batch, and a 256-token physical micro-batch.- Starts with a 2,048-token context to reduce per-request memory and attention work. Increase it when larger prompts are more important than speed.- Uses Q4_K_M rather than a larger quantization to keep the model compact.
These are performance-oriented defaults, not a guaranteed tokens-per-second figure. Actual throughput depends on the Space host CPU, prompt length, generated length, and concurrent traffic. CPU Basic is not a GPU accelerator. The service serializes access to its single model instance to avoid CPU oversubscription and model-state conflicts.
### Optional Space variables
Only `LLAMA_API_KEY` is required. The following variables are optional:
| Variable | Default | Meaning ||---|---:|---|| `MODEL_REPO_ID` | `Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF` | Hugging Face model repository || `MODEL_FILENAME` | `qwen2.5-coder-0.5b-instruct-q4_k_m.gguf` | Exact GGUF file to download || `MODEL_ALIAS` | `qwen2.5-coder-0.5b-instruct` | Model name accepted in API requests || `LLAMA_N_THREADS` | `2` | Generation CPU threads || `LLAMA_N_THREADS_BATCH` | `2` | Prompt-processing CPU threads || `LLAMA_N_CTX` | `2048` | Context window size || `LLAMA_N_BATCH` | `512` | Logical prompt batch size || `LLAMA_N_UBATCH` | `256` | Physical prompt micro-batch size |
Do not set `LLAMA_API_KEY` as a public variable. Store it under **Secrets**.
## Local run
This project targets the Hugging Face Spaces Gradio environment. To run locally, install the Debian packages listed in `packages.txt`, install `requirements.txt`, set `LLAMA_API_KEY`, and run:
```bashpython app.py```
The server listens on port `7860`.
## Model and API references
- [Official Qwen GGUF repository](https://huggingface.co/Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF)- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python)- [llama.cpp server documentation](https://github.com/ggml-org/llama.cpp/tree/master/tools/server)- [Hugging Face Spaces overview](https://huggingface.co/docs/hub/spaces-overview)
The Qwen model repository is licensed under Apache-2.0. Review the model card and license before redistribution or commercial use.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136from __future__ import annotations
import loggingimport osfrom pathlib import Path
import gradio as grimport uvicornfrom huggingface_hub import hf_hub_downloadfrom llama_cpp.server.app import create_appfrom llama_cpp.server.settings import Settings
logging.basicConfig( level=os.getenv("LOG_LEVEL", "INFO").upper(), format="%(asctime)s %(levelname)s %(name)s: %(message)s",)logger = logging.getLogger("qwen-space")
SPACE_PORT = int(os.getenv("PORT", "7860"))MODEL_REPO_ID = os.getenv( "MODEL_REPO_ID", "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF")MODEL_FILENAME = os.getenv( "MODEL_FILENAME", "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf")MODEL_ALIAS = os.getenv("MODEL_ALIAS", "qwen2.5-coder-0.5b-instruct")
def _read_positive_int(name: str, default: int) -> int: raw = os.getenv(name, str(default)) try: value = int(raw) except ValueError as exc: raise RuntimeError(f"{name} must be an integer; received {raw!r}") from exc if value < 1: raise RuntimeError(f"{name} must be >= 1; received {value}") return value
def download_model() -> str: """Fetch exactly the selected GGUF file into the Hugging Face cache.""" logger.info("Downloading model %s / %s", MODEL_REPO_ID, MODEL_FILENAME) model_path = hf_hub_download( repo_id=MODEL_REPO_ID, filename=MODEL_FILENAME, cache_dir=os.getenv("HF_HUB_CACHE") or None, token=os.getenv("HF_TOKEN") or None, ) size_mb = Path(model_path).stat().st_size / (1024 * 1024) logger.info("Model ready at %s (%.1f MiB)", model_path, size_mb) return model_path
def build_api_app(): api_key = os.getenv("LLAMA_API_KEY", "").strip() if not api_key: raise RuntimeError( "Missing required Space Secret LLAMA_API_KEY. Add it under " "Settings > Variables and secrets > New secret." )
model_path = download_model() threads = _read_positive_int("LLAMA_N_THREADS", 2) batch_threads = _read_positive_int("LLAMA_N_THREADS_BATCH", 2)
# llama-cpp-python is the llama.cpp C/C++ inference runtime with its # OpenAI-compatible FastAPI server and built-in Bearer-key authentication. settings = Settings( model=model_path, model_alias=MODEL_ALIAS, host="0.0.0.0", port=SPACE_PORT, api_key=api_key, chat_format="chatml", n_ctx=_read_positive_int("LLAMA_N_CTX", 2048), n_threads=threads, n_threads_batch=batch_threads, n_batch=_read_positive_int("LLAMA_N_BATCH", 512), n_ubatch=_read_positive_int("LLAMA_N_UBATCH", 256), n_gpu_layers=0, use_mmap=True, use_mlock=False, flash_attn=False, verbose=False, ) api_app = create_app(settings=settings)
# A lightweight public health route for Space monitoring. Inference routes # remain protected by the server's built-in Bearer-key dependency. @api_app.get("/health", include_in_schema=False) async def health(): return {"status": "ok", "model": MODEL_ALIAS}
return api_app
def build_console() -> gr.Blocks: with gr.Blocks(title="Qwen2.5 Coder API", analytics_enabled=False) as demo: gr.Markdown( """ # ⚡ Qwen2.5-Coder-0.5B-Instruct API
The model is running through llama.cpp. This Space exposes an OpenAI-compatible REST API; inference endpoints require your configured Bearer API key.
**API base URL**
```text /v1 ```
**Main endpoints**
- `GET /health` — public service health check - `GET /v1/models` — model list (Bearer key required) - `POST /v1/chat/completions` — chat and streaming completions - `POST /v1/completions` — text completions - `GET /docs` — OpenAPI schema
Send `Authorization: Bearer YOUR_LLAMA_API_KEY` with `/v1` requests. The API key is never displayed on this page. """ ) return demo
def main() -> None: api_app = build_api_app() app = gr.mount_gradio_app(api_app, build_console(), path="/console") logger.info("Starting API on 0.0.0.0:%s", SPACE_PORT) uvicorn.run(app, host="0.0.0.0", port=SPACE_PORT, log_level="info")
if __name__ == "__main__": main()1234build-essentialcmakeninja-buildlibopenblas-dev123--no-binary=llama-cpp-pythonllama-cpp-python[server]>=0.3.16,<0.4 --config-settings=cmake.args="-DGGML_NATIVE=ON;-DGGML_OPENMP=ON;-DGGML_BLAS=ON;-DGGML_BLAS_VENDOR=OpenBLAS"huggingface_hub>=0.27.0.env.exampleAdded+10
.gitignoreAdded+6
README.mdAdded+168
app.pyAdded+136
packages.txtAdded+4
requirements.txtAdded+3