MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / server.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MojoLlama server — unified API server with SSE streaming, studio API, |
| 3 | concurrent handling, and auto-backend selection. |
| 4 | |
| 5 | Starts an OpenAI-compatible API server that routes inference through: |
| 6 | - MAX GPU (if GPU available) |
| 7 | - llama.cpp (if CPU only) |
| 8 | - MAX CPU (fallback) |
| 9 | |
| 10 | SSE streaming, CORS, and studio endpoints are all built in. |
| 11 | |
| 12 | Usage: |
| 13 | python3 server.py |
| 14 | python3 server.py --model /path/to/model.gguf --port 8080 |
| 15 | """ |
| 16 | |
| 17 | import os |
| 18 | import sys |
| 19 | import json |
| 20 | import time |
| 21 | import uuid |
| 22 | import argparse |
| 23 | import threading |
| 24 | import subprocess |
| 25 | import re |
| 26 | import queue |
| 27 | import concurrent.futures |
| 28 | from pathlib import Path |
| 29 | from http.server import HTTPServer, BaseHTTPRequestHandler |
| 30 | from urllib.parse import urlparse, parse_qs |
| 31 | from io import BytesIO |
| 32 | |
| 33 | # Add project to path |
| 34 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 35 | |
| 36 | from mojollama.backends import AutoBackend |
| 37 | |
| 38 | # ─── Globals ──────────────────────────────────────────────────────────── |
| 39 | |
| 40 | backend = None |
| 41 | prompts_served = 0 |
| 42 | start_time = time.time() |
| 43 | |
| 44 | # Export job tracking: job_id -> {"status": str, "log": str, "thread": Thread} |
| 45 | _export_jobs = {} |
| 46 | _export_jobs_lock = threading.Lock() |
| 47 | |
| 48 | # Training metrics subscription: list of queues |
| 49 | _training_queues = [] |
| 50 | _training_queues_lock = threading.Lock() |
| 51 | |
| 52 | _metrics_lock = threading.Lock() |
| 53 | _request_times = [] # rolling window of request latencies (seconds) |
| 54 | _metrics_max_samples = 1000 |
| 55 | |
| 56 | def _record_latency(t0): |
| 57 | """Record request latency for metrics.""" |
| 58 | elapsed = time.time() - t0 |
| 59 | with _metrics_lock: |
| 60 | _request_times.append(elapsed) |
| 61 | if len(_request_times) > _metrics_max_samples: |
| 62 | _request_times.pop(0) |
| 63 | |
| 64 | LLAMA_SERVER_PATH = "/tmp/llama.cpp/build/bin/llama-server" |
| 65 | CONVERTER_PATH = "/tmp/llama.cpp/convert_hf_to_gguf.py" |
| 66 | BASE_DIR = Path(__file__).parent.parent.parent.resolve() |
| 67 | WORK_DIR = BASE_DIR # /onedev-workspace/work |
| 68 | |
| 69 | |
| 70 | # ─── Threaded HTTP Server ────────────────────────────────────────────── |
| 71 | |
| 72 | class ThreadPoolHTTPServer(HTTPServer): |
| 73 | """HTTP server with bounded thread pool for concurrent requests. |
| 74 | |
| 75 | Instead of spawning an unbounded thread per request (ThreadingMixIn), |
| 76 | uses a ThreadPoolExecutor with a configurable max_workers limit. |
| 77 | When the queue is full, new connections get 503 Service Unavailable. |
| 78 | """ |
| 79 | |
| 80 | def __init__(self, server_address, RequestHandlerClass, |
| 81 | max_workers=32, queue_size=64): |
| 82 | self.allow_reuse_address = True |
| 83 | self._executor = concurrent.futures.ThreadPoolExecutor( |
| 84 | max_workers=max_workers |
| 85 | ) |
| 86 | self._queue_size = queue_size |
| 87 | self._active_requests = threading.BoundedSemaphore(queue_size) |
| 88 | HTTPServer.__init__(self, server_address, RequestHandlerClass) |
| 89 | |
| 90 | def process_request(self, request, client_address): |
| 91 | """Submit request to thread pool, or reject if queue is full.""" |
| 92 | if not self._active_requests.acquire(blocking=False): |
| 93 | # Queue full — send 503 |
| 94 | try: |
| 95 | request.sendall(b'HTTP/1.1 503 Service Unavailable\r\n' |
| 96 | b'Content-Length: 0\r\nConnection: close\r\n\r\n') |
| 97 | except: pass |
| 98 | request.close() |
| 99 | return |
| 100 | |
| 101 | self._executor.submit(self._handle_request, |
| 102 | request, client_address) |
| 103 | |
| 104 | def _handle_request(self, request, client_address): |
| 105 | try: |
| 106 | self.finish_request(request, client_address) |
| 107 | except Exception: |
| 108 | self.handle_error(request, client_address) |
| 109 | finally: |
| 110 | self._active_requests.release() |
| 111 | self.shutdown_request(request) |
| 112 | |
| 113 | def server_close(self): |
| 114 | self._executor.shutdown(wait=True) |
| 115 | HTTPServer.server_close(self) |
| 116 | |
| 117 | |
| 118 | # ─── Request Handler ─────────────────────────────────────────────────── |
| 119 | |
| 120 | class MojoLlamaHandler(BaseHTTPRequestHandler): |
| 121 | """OpenAI-compatible API handler with SSE streaming and studio API.""" |
| 122 | |
| 123 | # ── Helpers ───────────────────────────────────────────────────── |
| 124 | |
| 125 | def log_message(self, fmt, *args): |
| 126 | sys.stderr.write( |
| 127 | f"[{time.strftime('%H:%M:%S')}] {(fmt % args) if args else fmt}\n" |
| 128 | ) |
| 129 | |
| 130 | def _parse_path(self): |
| 131 | """Parse self.path into path, query dict.""" |
| 132 | parsed = urlparse(self.path) |
| 133 | return parsed.path, parse_qs(parsed.query) |
| 134 | |
| 135 | def _read_body(self): |
| 136 | """Read and parse JSON request body.""" |
| 137 | content_len = int(self.headers.get("Content-Length", 0)) |
| 138 | if content_len == 0: |
| 139 | return {} |
| 140 | raw = self.rfile.read(content_len) |
| 141 | if not raw: |
| 142 | return {} |
| 143 | return json.loads(raw) |
| 144 | |
| 145 | def _send_json(self, data, status=200): |
| 146 | """Send a JSON response.""" |
| 147 | body = json.dumps(data).encode() |
| 148 | self.send_response(status) |
| 149 | self._set_cors() |
| 150 | self.send_header("Content-Type", "application/json") |
| 151 | self.send_header("Content-Length", str(len(body))) |
| 152 | self.end_headers() |
| 153 | self.wfile.write(body) |
| 154 | |
| 155 | def _send_error(self, message, status=400): |
| 156 | """Send a JSON error response.""" |
| 157 | self._send_json({"error": message}, status) |
| 158 | |
| 159 | def _set_cors(self): |
| 160 | """Add CORS headers.""" |
| 161 | self.send_header("Access-Control-Allow-Origin", "*") |
| 162 | self.send_header("Access-Control-Allow-Methods", |
| 163 | "GET, POST, PUT, DELETE, OPTIONS") |
| 164 | self.send_header("Access-Control-Allow-Headers", |
| 165 | "Content-Type, Authorization") |
| 166 | |
| 167 | def _sse_send(self, data_obj): |
| 168 | """Send a single SSE message (data: json\\n\\n).""" |
| 169 | msg = f"data: {json.dumps(data_obj)}\n\n".encode() |
| 170 | self.wfile.write(msg) |
| 171 | self.wfile.flush() |
| 172 | |
| 173 | def _sse_end(self): |
| 174 | """Send the [DONE] signal to terminate the SSE stream.""" |
| 175 | self.wfile.write(b"data: [DONE]\n\n") |
| 176 | self.wfile.flush() |
| 177 | |
| 178 | def _build_tools_prompt(self, tools, tool_choice="auto"): |
| 179 | """Build a system-level instruction from OpenAI tool definitions. |
| 180 | |
| 181 | Injects available functions into the conversation so the model |
| 182 | can call them. Returns a system message dict or empty dict. |
| 183 | """ |
| 184 | if not tools: |
| 185 | return {} |
| 186 | |
| 187 | # Build a function list description |
| 188 | func_descs = [] |
| 189 | for tool in tools: |
| 190 | if tool.get("type") == "function": |
| 191 | fn = tool.get("function", {}) |
| 192 | params = fn.get("parameters", {}) |
| 193 | props_desc = ", ".join(params.get("properties", {}).keys()) |
| 194 | required = params.get("required", []) |
| 195 | func_descs.append( |
| 196 | f"- {fn.get('name')}: {fn.get('description', '')} " |
| 197 | f"(parameters: {props_desc}, required: {', '.join(required)})" |
| 198 | ) |
| 199 | |
| 200 | instruction = ( |
| 201 | "You have access to the following functions. Use them when the user's " |
| 202 | "request requires calling an external tool or retrieving information.\n\n" |
| 203 | "Available functions:\n" |
| 204 | + "\n".join(func_descs) + |
| 205 | "\n\n" |
| 206 | "To call a function, respond with ONLY a valid JSON object in this exact " |
| 207 | 'format, with no other text: {"name": "function_name", "arguments": {"arg1": "value1"}}\n' |
| 208 | 'If you need to call a function, respond with ONLY that JSON. Do not include ' |
| 209 | "any other explanation or text. If you don't need to call a function, " |
| 210 | "respond normally with your answer." |
| 211 | ) |
| 212 | |
| 213 | if tool_choice == "none": |
| 214 | return {} # Skip function calling entirely |
| 215 | elif isinstance(tool_choice, dict): |
| 216 | # Force a specific function: {"type":"function","function":{"name":"..."}} |
| 217 | fn_name = tool_choice.get("function", {}).get("name", "") |
| 218 | instruction += ( |
| 219 | f"\n\nIMPORTANT: You MUST use the '{fn_name}' function for this request. " |
| 220 | f"Respond with ONLY the function call JSON." |
| 221 | ) |
| 222 | return {"role": "system", "content": instruction, "_force_tool": fn_name} |
| 223 | else: |
| 224 | return {"role": "system", "content": instruction} |
| 225 | |
| 226 | @staticmethod |
| 227 | def _parse_tool_call_response(text): |
| 228 | """Parse a model response for function call JSON. |
| 229 | |
| 230 | Returns (tool_name, args_dict) if a function call is detected, |
| 231 | or (None, None) if it's a normal response. |
| 232 | """ |
| 233 | text = text.strip() |
| 234 | # Try to parse the entire response as JSON |
| 235 | if text.startswith("{") and text.endswith("}"): |
| 236 | try: |
| 237 | obj = json.loads(text) |
| 238 | if "name" in obj and "arguments" in obj: |
| 239 | args = obj["arguments"] |
| 240 | if isinstance(args, str): |
| 241 | args = json.loads(args) |
| 242 | return obj["name"], args |
| 243 | except (json.JSONDecodeError, TypeError): |
| 244 | pass |
| 245 | # Try to find JSON embedded in text |
| 246 | json_match = re.search(r'\{[^{}]*"name"\s*:\s*"[^"]*"\s*,[^{}]*"arguments"\s*:', text, re.DOTALL) |
| 247 | if json_match: |
| 248 | try: |
| 249 | obj = json.loads(json_match.group()) |
| 250 | if "name" in obj and "arguments" in obj: |
| 251 | args = obj["arguments"] |
| 252 | if isinstance(args, str): |
| 253 | args = json.loads(args) |
| 254 | return obj["name"], args |
| 255 | except (json.JSONDecodeError, TypeError): |
| 256 | pass |
| 257 | return None, None |
| 258 | |
| 259 | # ── HTTP Methods ──────────────────────────────────────────────── |
| 260 | |
| 261 | def do_OPTIONS(self): |
| 262 | """Handle CORS preflight.""" |
| 263 | self.send_response(204) |
| 264 | self._set_cors() |
| 265 | self.send_header("Content-Length", "0") |
| 266 | self.end_headers() |
| 267 | |
| 268 | # ── GET ───────────────────────────────────────────────────────── |
| 269 | |
| 270 | def do_GET(self): |
| 271 | path, query = self._parse_path() |
| 272 | |
| 273 | # ── Existing endpoints ────────────────────────────────── |
| 274 | if path == "/v1/models": |
| 275 | models_list = [] |
| 276 | for f in sorted(Path(WORK_DIR).glob("*.gguf")): |
| 277 | models_list.append({ |
| 278 | "id": f.stem, |
| 279 | "object": "model", |
| 280 | "created": int(f.stat().st_mtime), |
| 281 | "owned_by": "mojollama", |
| 282 | }) |
| 283 | if not models_list: |
| 284 | models_list.append({ |
| 285 | "id": "mojollama-llama-3.2-1b", |
| 286 | "object": "model", |
| 287 | "created": int(start_time), |
| 288 | "owned_by": "mojollama", |
| 289 | }) |
| 290 | self._send_json({"object": "list", "data": models_list}) |
| 291 | |
| 292 | elif path == "/health": |
| 293 | self._send_json({ |
| 294 | "status": "ok", |
| 295 | "backend": backend.info["active"] if hasattr(backend, 'info') else "unknown", |
| 296 | "uptime": f"{time.time() - start_time:.0f}s", |
| 297 | }) |
| 298 | |
| 299 | elif path == "/backend": |
| 300 | self._send_json(backend.info if hasattr(backend, 'info') else {"active": "unknown"}) |
| 301 | |
| 302 | # ── Studio API: /api/backend ───────────────────────────── |
| 303 | elif path == "/api/backend": |
| 304 | info = backend.info if hasattr(backend, 'info') else {"active": "unknown"} |
| 305 | info["prompts_served"] = prompts_served |
| 306 | info["uptime"] = f"{time.time() - start_time:.0f}s" |
| 307 | self._send_json(info) |
| 308 | |
| 309 | # ── Studio API: /api/models ────────────────────────────── |
| 310 | elif path == "/api/models": |
| 311 | models = [] |
| 312 | for f in sorted(Path(WORK_DIR).glob("*.gguf")): |
| 313 | size_bytes = f.stat().st_size |
| 314 | models.append({ |
| 315 | "name": f.name, |
| 316 | "path": str(f), |
| 317 | "size_bytes": size_bytes, |
| 318 | "size_hr": self._format_size(size_bytes), |
| 319 | "modified": f.stat().st_mtime, |
| 320 | }) |
| 321 | self._send_json({"models": models, "count": len(models)}) |
| 322 | |
| 323 | # ── Studio API: /api/dataset ───────────────────────────── |
| 324 | elif path == "/api/dataset": |
| 325 | datasets = [] |
| 326 | for f in sorted(Path(WORK_DIR).glob("*.jsonl")) + sorted(Path(WORK_DIR).glob("*.json")): |
| 327 | datasets.append({ |
| 328 | "name": f.name, |
| 329 | "path": str(f), |
| 330 | "size_bytes": f.stat().st_size, |
| 331 | }) |
| 332 | self._send_json({"datasets": datasets, "count": len(datasets)}) |
| 333 | |
| 334 | # ── Studio API: export status ────────────────────────── |
| 335 | elif path.startswith("/api/export/") and path.endswith("/status"): |
| 336 | job_id = path.split("/")[3] |
| 337 | with _export_jobs_lock: |
| 338 | job = _export_jobs.get(job_id) |
| 339 | if job is None: |
| 340 | self._send_error(f"Job {job_id} not found", 404) |
| 341 | return |
| 342 | self._send_json({ |
| 343 | "job_id": job_id, |
| 344 | "status": job["status"], |
| 345 | "log": job.get("log", ""), |
| 346 | }) |
| 347 | |
| 348 | elif path.startswith("/api/export/"): |
| 349 | # GET /api/export/{job_id} (without /status suffix) |
| 350 | job_id = path.split("/")[3] |
| 351 | with _export_jobs_lock: |
| 352 | job = _export_jobs.get(job_id) |
| 353 | if job is None: |
| 354 | self._send_error(f"Job {job_id} not found", 404) |
| 355 | return |
| 356 | self._send_json({ |
| 357 | "job_id": job_id, |
| 358 | "status": job["status"], |
| 359 | "log": job.get("log", ""), |
| 360 | }) |
| 361 | |
| 362 | # ── Studio API: training metrics SSE ─────────────────── |
| 363 | elif path == "/api/train/metrics": |
| 364 | self.send_response(200) |
| 365 | self._set_cors() |
| 366 | self.send_header("Content-Type", "text/event-stream") |
| 367 | self.send_header("Cache-Control", "no-cache") |
| 368 | self.send_header("Connection", "keep-alive") |
| 369 | self.end_headers() |
| 370 | |
| 371 | q = queue.Queue() |
| 372 | with _training_queues_lock: |
| 373 | _training_queues.append(q) |
| 374 | |
| 375 | try: |
| 376 | # Keep connection open, sending heartbeats |
| 377 | while True: |
| 378 | try: |
| 379 | metrics = q.get(timeout=5) |
| 380 | self._sse_send(metrics) |
| 381 | except queue.Empty: |
| 382 | # Send a heartbeat comment to keep connection alive |
| 383 | self.wfile.write(b": heartbeat\n\n") |
| 384 | self.wfile.flush() |
| 385 | except (BrokenPipeError, ConnectionResetError, OSError): |
| 386 | pass |
| 387 | finally: |
| 388 | with _training_queues_lock: |
| 389 | if q in _training_queues: |
| 390 | _training_queues.remove(q) |
| 391 | |
| 392 | # ── Metrics endpoint ────────────────────────────────── |
| 393 | elif path == "/metrics": |
| 394 | with _metrics_lock: |
| 395 | n = len(_request_times) |
| 396 | avg = sum(_request_times) / n if n else 0 |
| 397 | p95 = sorted(_request_times)[int(n * 0.95)] if n > 10 else 0 |
| 398 | self._send_json({ |
| 399 | "prompts_served": prompts_served, |
| 400 | "uptime_seconds": time.time() - start_time, |
| 401 | "requests_total": prompts_served, |
| 402 | "avg_latency_seconds": round(avg, 3), |
| 403 | "p95_latency_seconds": round(p95, 3), |
| 404 | "samples": n, |
| 405 | "backend": backend.info["active"] if hasattr(backend, 'info') else "unknown", |
| 406 | "connection_pool_size": _llama_pool_size, |
| 407 | "pool_available": _llama_conn_pool.qsize(), |
| 408 | }) |
| 409 | |
| 410 | # ── Model info endpoint ─────────────────────────────── |
| 411 | elif path == "/api/model-info": |
| 412 | model_path = query.get("path", [None])[0] or "" |
| 413 | if not model_path or not os.path.exists(model_path): |
| 414 | self._send_error("No model path specified or file not found", 400) |
| 415 | return |
| 416 | try: |
| 417 | from mojollama.quantizer import get_info as _gi |
| 418 | info = _gi(model_path) |
| 419 | self._send_json({ |
| 420 | "status": "ok", |
| 421 | "path": info.get("path"), |
| 422 | "file_size_human": info.get("file_size_human"), |
| 423 | "file_size_bytes": info.get("file_size_bytes"), |
| 424 | "tensor_count": info.get("tensor_count"), |
| 425 | "total_parameters": info.get("total_parameters"), |
| 426 | "primary_quantization": info.get("primary_quantization"), |
| 427 | "metadata": info.get("metadata"), |
| 428 | "tensor_type_counts": info.get("tensor_type_counts"), |
| 429 | }) |
| 430 | except Exception as e: |
| 431 | self._send_error(str(e), 500) |
| 432 | |
| 433 | # ── Serve static UI files ───────────────────────────── |
| 434 | elif path in ("/", "/index.html", "/studio.html", "/chat.html"): |
| 435 | www_dir = Path(__file__).resolve().parent.parent.parent / "www" |
| 436 | # Fallback: relative to cwd (for build containers) |
| 437 | if not www_dir.exists(): |
| 438 | www_dir = Path.cwd() / "www" |
| 439 | filename = "index.html" if path == "/" else path.lstrip("/") |
| 440 | filepath = www_dir / filename |
| 441 | if filepath.exists(): |
| 442 | content = filepath.read_bytes() |
| 443 | ext = filename.rsplit(".", 1)[-1] if "." in filename else "html" |
| 444 | mime = {"html": "text/html", "js": "application/javascript", |
| 445 | "css": "text/css", "png": "image/png", "svg": "image/svg+xml"}.get(ext, "text/plain") |
| 446 | self.send_response(200) |
| 447 | self._set_cors() |
| 448 | self.send_header("Content-Type", mime) |
| 449 | self.send_header("Content-Length", str(len(content))) |
| 450 | self.end_headers() |
| 451 | self.wfile.write(content) |
| 452 | else: |
| 453 | self._send_error("not found", 404) |
| 454 | |
| 455 | # ── Not found ────────────────────────────────────────────────────────────── |
| 456 | else: |
| 457 | self._send_error("not found", 404) |
| 458 | |
| 459 | # ── POST ──────────────────────────────────────────────────────── |
| 460 | |
| 461 | def do_POST(self): |
| 462 | global prompts_served |
| 463 | path, query = self._parse_path() |
| 464 | body = self._read_body() |
| 465 | |
| 466 | # ── Existing: /v1/completions ───────────────────────────── |
| 467 | if path in ("/v1/completions", "/completion"): |
| 468 | prompt = body.get("prompt", "") |
| 469 | max_tokens = body.get("max_tokens", body.get("n_predict", 128)) |
| 470 | temperature = body.get("temperature", 0.7) |
| 471 | stream = body.get("stream", False) |
| 472 | |
| 473 | t0 = time.time() |
| 474 | |
| 475 | if stream: |
| 476 | # Streaming response |
| 477 | return self._handle_streaming_completion(prompt, max_tokens, temperature) |
| 478 | |
| 479 | result = backend.generate(prompt, max_tokens=max_tokens, temperature=temperature) |
| 480 | elapsed = time.time() - t0 |
| 481 | prompts_served += 1 |
| 482 | _record_latency(t0) |
| 483 | |
| 484 | self._send_json({ |
| 485 | "id": f"cmpl-{prompts_served}", |
| 486 | "object": "text_completion", |
| 487 | "created": int(time.time()), |
| 488 | "model": "mojollama-llama-3.2-1b", |
| 489 | "choices": [{"text": result.get("text", ""), "index": 0, "finish_reason": "stop"}], |
| 490 | "usage": { |
| 491 | "completion_tokens": result.get("tokens", 0), |
| 492 | "total_tokens": result.get("tokens", 0), |
| 493 | }, |
| 494 | "backend": result.get("backend"), |
| 495 | "timings": {"total": f"{elapsed:.2f}s"}, |
| 496 | }) |
| 497 | |
| 498 | # ── Updated: /v1/chat/completions (with tool calling + latency tracking) ── |
| 499 | elif path == "/v1/chat/completions": |
| 500 | messages = list(body.get("messages", [])) |
| 501 | max_tokens = body.get("max_tokens", 256) |
| 502 | temperature = body.get("temperature", 0.7) |
| 503 | stream = body.get("stream", False) |
| 504 | tools = body.get("tools", []) |
| 505 | tool_choice = body.get("tool_choice", "auto") |
| 506 | |
| 507 | t0 = time.time() |
| 508 | |
| 509 | # Handle tool calling: inject function definitions into the conversation |
| 510 | if tools: |
| 511 | tool_msg = self._build_tools_prompt(tools, tool_choice) |
| 512 | if tool_msg: |
| 513 | # Insert the tool system message at the beginning |
| 514 | messages.insert(0, tool_msg) |
| 515 | |
| 516 | if stream: |
| 517 | # SSE streaming response |
| 518 | result = self._handle_streaming_chat_completion( |
| 519 | messages, max_tokens, temperature |
| 520 | ) |
| 521 | _record_latency(t0) |
| 522 | return result |
| 523 | |
| 524 | # Non-streaming: use backend.chat() |
| 525 | try: |
| 526 | result = backend.chat(messages, max_tokens=max_tokens, temperature=temperature) |
| 527 | prompts_served += 1 |
| 528 | |
| 529 | # Build OpenAI-format response |
| 530 | response = { |
| 531 | "id": f"chatcmpl-{prompts_served}", |
| 532 | "object": "chat.completion", |
| 533 | "created": int(time.time()), |
| 534 | "model": "mojollama", |
| 535 | "choices": [{ |
| 536 | "index": 0, |
| 537 | "message": {"role": "assistant", "content": result.get("text", "")}, |
| 538 | "finish_reason": "stop", |
| 539 | }], |
| 540 | "usage": { |
| 541 | "completion_tokens": result.get("tokens", 0), |
| 542 | "total_tokens": result.get("tokens", 0), |
| 543 | }, |
| 544 | "backend": result.get("backend"), |
| 545 | } |
| 546 | |
| 547 | # Check if tools were provided — try to parse a function call |
| 548 | if tools: |
| 549 | content = response["choices"][0]["message"]["content"] |
| 550 | fn_name, fn_args = self._parse_tool_call_response(content) |
| 551 | if fn_name and fn_args: |
| 552 | response["choices"][0]["message"]["content"] = None |
| 553 | response["choices"][0]["message"]["tool_calls"] = [{ |
| 554 | "id": f"call_{uuid.uuid4().hex[:12]}", |
| 555 | "type": "function", |
| 556 | "function": { |
| 557 | "name": fn_name, |
| 558 | "arguments": json.dumps(fn_args), |
| 559 | }, |
| 560 | }] |
| 561 | response["choices"][0]["finish_reason"] = "tool_calls" |
| 562 | |
| 563 | self._send_json(response) |
| 564 | except Exception as e: |
| 565 | self._send_error(f"Chat completion failed: {e}", 502) |
| 566 | finally: |
| 567 | _record_latency(t0) |
| 568 | |
| 569 | # ── Studio API: /api/chat (streaming for web UI) ───────── |
| 570 | elif path == "/api/chat": |
| 571 | messages = body.get("messages", []) |
| 572 | max_tokens = body.get("max_tokens", 256) |
| 573 | temperature = body.get("temperature", 0.7) |
| 574 | |
| 575 | return self._handle_streaming_chat_completion( |
| 576 | messages, max_tokens, temperature |
| 577 | ) |
| 578 | |
| 579 | # ── Studio API: /api/export ────────────────────────────── |
| 580 | elif path == "/api/export": |
| 581 | model = body.get("model", "") |
| 582 | outtype = body.get("outtype", "q4_0") |
| 583 | outfile = body.get("outfile", "") |
| 584 | |
| 585 | if not model: |
| 586 | self._send_error("'model' field is required") |
| 587 | return |
| 588 | |
| 589 | if not outfile: |
| 590 | model_name = model.split("/")[-1] if "/" in model else model |
| 591 | outfile = f"{model_name}-{outtype}.gguf" |
| 592 | |
| 593 | job_id = str(uuid.uuid4())[:8] |
| 594 | |
| 595 | with _export_jobs_lock: |
| 596 | _export_jobs[job_id] = { |
| 597 | "status": "running", |
| 598 | "log": f"Starting export: {model} -> {outtype} -> {outfile}\n", |
| 599 | "thread": None, |
| 600 | } |
| 601 | |
| 602 | def _run_export(jid, hf_model, ot, of): |
| 603 | log_lines = [] |
| 604 | def log(msg): |
| 605 | log_lines.append(msg) |
| 606 | with _export_jobs_lock: |
| 607 | job = _export_jobs.get(jid) |
| 608 | if job: |
| 609 | job["log"] = "\n".join(log_lines) |
| 610 | |
| 611 | log(f"Model: {hf_model}") |
| 612 | log(f"Out type: {ot}") |
| 613 | log(f"Out file: {of}") |
| 614 | log(f"Converter: {CONVERTER_PATH}") |
| 615 | log("") |
| 616 | |
| 617 | if not os.path.exists(CONVERTER_PATH): |
| 618 | log(f"ERROR: Converter not found at {CONVERTER_PATH}") |
| 619 | with _export_jobs_lock: |
| 620 | if jid in _export_jobs: |
| 621 | _export_jobs[jid]["status"] = "error" |
| 622 | return |
| 623 | |
| 624 | try: |
| 625 | cmd = [ |
| 626 | sys.executable, CONVERTER_PATH, |
| 627 | hf_model, |
| 628 | "--outtype", ot, |
| 629 | "--outfile", of, |
| 630 | ] |
| 631 | log(f"Running: {' '.join(cmd)}") |
| 632 | |
| 633 | proc = subprocess.Popen( |
| 634 | cmd, |
| 635 | stdout=subprocess.PIPE, |
| 636 | stderr=subprocess.STDOUT, |
| 637 | text=True, |
| 638 | ) |
| 639 | |
| 640 | for line in proc.stdout: |
| 641 | line = line.rstrip() |
| 642 | log(line) |
| 643 | |
| 644 | proc.wait() |
| 645 | |
| 646 | if proc.returncode == 0: |
| 647 | log(f"\n✅ Export complete: {of}") |
| 648 | if os.path.exists(of): |
| 649 | size_mb = os.path.getsize(of) / 1024 ** 2 |
| 650 | log(f" Size: {size_mb:.0f} MB") |
| 651 | with _export_jobs_lock: |
| 652 | if jid in _export_jobs: |
| 653 | _export_jobs[jid]["status"] = "done" |
| 654 | else: |
| 655 | log(f"\n❌ Export failed (exit code {proc.returncode})") |
| 656 | with _export_jobs_lock: |
| 657 | if jid in _export_jobs: |
| 658 | _export_jobs[jid]["status"] = "error" |
| 659 | |
| 660 | except Exception as e: |
| 661 | log(f"ERROR: {e}") |
| 662 | with _export_jobs_lock: |
| 663 | if jid in _export_jobs: |
| 664 | _export_jobs[jid]["status"] = "error" |
| 665 | |
| 666 | thread = threading.Thread( |
| 667 | target=_run_export, |
| 668 | args=(job_id, model, outtype, outfile), |
| 669 | daemon=True, |
| 670 | ) |
| 671 | thread.start() |
| 672 | |
| 673 | with _export_jobs_lock: |
| 674 | _export_jobs[job_id]["thread"] = thread |
| 675 | |
| 676 | self._send_json({ |
| 677 | "job_id": job_id, |
| 678 | "status": "running", |
| 679 | "message": f"Export job {job_id} started", |
| 680 | }) |
| 681 | |
| 682 | # ── Quantizer API: /api/quantize ─────────────────────────── |
| 683 | elif path == "/api/quantize": |
| 684 | input_path = body.get("input", "") |
| 685 | quant_type = body.get("type", "q4_k_m") |
| 686 | output_path = body.get("output", "") |
| 687 | |
| 688 | if not input_path or not os.path.exists(input_path): |
| 689 | self._send_error(f"input file not found: {input_path}", 400) |
| 690 | return |
| 691 | |
| 692 | try: |
| 693 | from mojollama.quantizer import quantize as _q |
| 694 | result = _q(input_path, quant_type=quant_type, output_path=output_path or None) |
| 695 | self._send_json({ |
| 696 | "status": "ok", |
| 697 | "output_path": result.get("output_path"), |
| 698 | "quant_type": result.get("quant_type"), |
| 699 | "input_size_bytes": result.get("input_size_bytes"), |
| 700 | "output_size_bytes": result.get("output_size_bytes"), |
| 701 | "compression_ratio": result.get("compression_ratio"), |
| 702 | "elapsed_seconds": result.get("elapsed_seconds"), |
| 703 | }) |
| 704 | except Exception as e: |
| 705 | self._send_error(str(e), 500) |
| 706 | |
| 707 | # ── Not found ───────────────────────────────────────── |
| 708 | else: |
| 709 | self._send_error("not found", 404) |
| 710 | |
| 711 | # ── Streaming Helpers ───────────────────────────────────────── |
| 712 | |
| 713 | def _handle_streaming_chat_completion(self, messages, max_tokens, temperature): |
| 714 | """Handle SSE streaming for chat completions using backend.chat_stream().""" |
| 715 | self.send_response(200) |
| 716 | self._set_cors() |
| 717 | self.send_header("Content-Type", "text/event-stream") |
| 718 | self.send_header("Cache-Control", "no-cache") |
| 719 | self.send_header("Connection", "keep-alive") |
| 720 | self.end_headers() |
| 721 | |
| 722 | try: |
| 723 | for chunk in backend.chat_stream(messages, max_tokens=max_tokens, |
| 724 | temperature=temperature): |
| 725 | self._sse_send(chunk) |
| 726 | except Exception as e: |
| 727 | try: |
| 728 | self._sse_send({ |
| 729 | "choices": [{"delta": {"content": f"\n[Error: {e}]"}, "index": 0}] |
| 730 | }) |
| 731 | except (BrokenPipeError, ConnectionResetError): |
| 732 | pass |
| 733 | |
| 734 | try: |
| 735 | self._sse_end() |
| 736 | global prompts_served |
| 737 | prompts_served += 1 |
| 738 | except (BrokenPipeError, ConnectionResetError): |
| 739 | pass |
| 740 | |
| 741 | def _handle_streaming_completion(self, prompt, max_tokens, temperature): |
| 742 | """Handle SSE streaming for text completions using backend.generate_stream().""" |
| 743 | self.send_response(200) |
| 744 | self._set_cors() |
| 745 | self.send_header("Content-Type", "text/event-stream") |
| 746 | self.send_header("Cache-Control", "no-cache") |
| 747 | self.send_header("Connection", "keep-alive") |
| 748 | self.end_headers() |
| 749 | |
| 750 | try: |
| 751 | for chunk in backend.generate_stream(prompt, max_tokens=max_tokens, |
| 752 | temperature=temperature): |
| 753 | self._sse_send(chunk) |
| 754 | except Exception as e: |
| 755 | try: |
| 756 | self._sse_send({ |
| 757 | "choices": [{"text": f"\n[Error: {e}]", "index": 0}] |
| 758 | }) |
| 759 | except (BrokenPipeError, ConnectionResetError): |
| 760 | pass |
| 761 | |
| 762 | try: |
| 763 | self._sse_end() |
| 764 | global prompts_served |
| 765 | prompts_served += 1 |
| 766 | except (BrokenPipeError, ConnectionResetError): |
| 767 | pass |
| 768 | |
| 769 | def _messages_to_prompt(self, messages): |
| 770 | """Convert OpenAI-format messages to a simple prompt string. |
| 771 | |
| 772 | For chat models this sends the whole conversation history. |
| 773 | llama.cpp's /completion endpoint handles chat templates internally, |
| 774 | but we format as a simple conversation for the proxy. |
| 775 | """ |
| 776 | parts = [] |
| 777 | for msg in messages: |
| 778 | role = msg.get("role", "user") |
| 779 | content = msg.get("content", "") |
| 780 | parts.append(f"<|start_header_id|>{role}<|end_header_id|>\n\n{content}<|eot_id|>") |
| 781 | parts.append("<|start_header_id|>assistant<|end_header_id|>\n\n") |
| 782 | return "".join(parts) |
| 783 | |
| 784 | @staticmethod |
| 785 | def _format_size(size_bytes): |
| 786 | """Format bytes into human-readable size.""" |
| 787 | if size_bytes < 1024: |
| 788 | return f"{size_bytes} B" |
| 789 | elif size_bytes < 1024 ** 2: |
| 790 | return f"{size_bytes / 1024:.0f} KB" |
| 791 | elif size_bytes < 1024 ** 3: |
| 792 | return f"{size_bytes / 1024 ** 2:.0f} MB" |
| 793 | else: |
| 794 | return f"{size_bytes / 1024 ** 3:.2f} GB" |
| 795 | |
| 796 | |
| 797 | def _download_from_hf(repo_id, filename=None, cache_dir="/models"): |
| 798 | """Download a GGUF model from HuggingFace Hub and return the local path.""" |
| 799 | import requests |
| 800 | import os, sys, json |
| 801 | |
| 802 | # If no filename given, list files in the repo and pick the first .gguf |
| 803 | if not filename: |
| 804 | api_url = f"https://huggingface.co/api/models/{repo_id}" |
| 805 | try: |
| 806 | resp = requests.get(api_url, timeout=30) |
| 807 | resp.raise_for_status() |
| 808 | info = resp.json() |
| 809 | siblings = info.get("siblings", []) |
| 810 | gguf_files = [s["rfilename"] for s in siblings |
| 811 | if s["rfilename"].endswith(".gguf")] |
| 812 | if not gguf_files: |
| 813 | raise RuntimeError( |
| 814 | f"No .gguf files found in {repo_id}. " |
| 815 | "Use --hf-file to specify a filename.") |
| 816 | # Pick the most common quant (Q4_K_M) or just the first |
| 817 | filename = next((f for f in gguf_files if "Q4_K_M" in f), gguf_files[0]) |
| 818 | print(f" [HF] Auto-selected: {filename}") |
| 819 | except requests.RequestException as e: |
| 820 | raise RuntimeError(f"Cannot list repo {repo_id}: {e}") |
| 821 | |
| 822 | local_path = os.path.join(cache_dir, filename.replace("/", "_")) |
| 823 | if os.path.exists(local_path): |
| 824 | print(f" [HF] Cached: {local_path}") |
| 825 | return local_path |
| 826 | |
| 827 | # Download with progress |
| 828 | url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}" |
| 829 | print(f" [HF] Downloading {url} ...") |
| 830 | print(f" [HF] Saving to {local_path}") |
| 831 | os.makedirs(os.path.dirname(local_path), exist_ok=True) |
| 832 | resp = requests.get(url, stream=True, timeout=300) |
| 833 | resp.raise_for_status() |
| 834 | total = int(resp.headers.get("content-length", 0)) |
| 835 | downloaded = 0 |
| 836 | with open(local_path, "wb") as f: |
| 837 | for chunk in resp.iter_content(chunk_size=8*1024*1024): |
| 838 | f.write(chunk) |
| 839 | downloaded += len(chunk) |
| 840 | if total: |
| 841 | pct = downloaded * 100 // total |
| 842 | print(f"\r [HF] {downloaded//1024//1024}MB / {total//1024//1024}MB ({pct}%)", end="", flush=True) |
| 843 | print() |
| 844 | return local_path |
| 845 | |
| 846 | |
| 847 | # ─── Main ────────────────────────────────────────────────────────────── |
| 848 | |
| 849 | def main(): |
| 850 | global backend |
| 851 | |
| 852 | parser = argparse.ArgumentParser(description="MojoLlama inference server") |
| 853 | parser.add_argument("--model", help="Path to GGUF model file", default="") |
| 854 | parser.add_argument("--hf-repo", help="HuggingFace repo ID to download GGUF from (e.g. Qwen/Qwen3-30B-A3B-Instruct-GGUF)", default="") |
| 855 | parser.add_argument("--hf-file", help="GGUF filename in the HF repo (auto-detected if omitted)", default="") |
| 856 | parser.add_argument("--hf-token", help="HuggingFace token for private repos", default="") |
| 857 | parser.add_argument("--port", type=int, help="HTTP server port", default=8080) |
| 858 | parser.add_argument("--llama-port", type=int, help="llama.cpp backend port", default=8081) |
| 859 | parser.add_argument("--max-workers", type=int, help="Max concurrent requests", default=32) |
| 860 | parser.add_argument("--queue-size", type=int, help="Max queued requests", default=128) |
| 861 | parser.add_argument("--weight", help="Path to MAX weight file", default="") |
| 862 | args, _ = parser.parse_known_args() |
| 863 | |
| 864 | port = args.port or int(os.environ.get("PORT", 8080)) |
| 865 | model_path = args.model or os.environ.get("MODEL_PATH", "") |
| 866 | weight_path = args.weight or os.environ.get("WEIGHT_PATH", "") |
| 867 | llama_port = args.llama_port |
| 868 | max_workers = args.max_workers |
| 869 | queue_size = args.queue_size |
| 870 | |
| 871 | # ── HuggingFace download ────────────────────────────────────────── |
| 872 | hf_repo = args.hf_repo or os.environ.get("HF_REPO", "") |
| 873 | hf_file = args.hf_file or os.environ.get("HF_FILE", "") |
| 874 | if hf_repo and not model_path: |
| 875 | model_path = _download_from_hf(hf_repo, hf_file) |
| 876 | # Auto-set TOKENIZER_PATH hint: trim "-GGUF" suffix if present |
| 877 | if not os.environ.get("TOKENIZER_PATH"): |
| 878 | base_repo = hf_repo.replace("-GGUF", "").replace("-gguf", "") |
| 879 | os.environ["TOKENIZER_PATH"] = base_repo |
| 880 | |
| 881 | print("╔══════════════════════════════════════════════╗") |
| 882 | print("║ MojoLlama — Inference Server ║") |
| 883 | print("╚══════════════════════════════════════════════╝") |
| 884 | print() |
| 885 | |
| 886 | backend = AutoBackend(model_path=model_path, weight_path=weight_path, |
| 887 | llama_port=llama_port) |
| 888 | print(f"\nBackend: {backend.info['active']}\n") |
| 889 | |
| 890 | server = ThreadPoolHTTPServer(("0.0.0.0", port), MojoLlamaHandler, |
| 891 | max_workers=max_workers, |
| 892 | queue_size=queue_size) |
| 893 | print(f"Serving on http://0.0.0.0:{port}") |
| 894 | print(f" Max workers: {max_workers}, Queue: {queue_size}") |
| 895 | print(f" /v1/models — list models") |
| 896 | print(f" /v1/completions — text completion") |
| 897 | print(f" /v1/chat/completions — chat completion (SSE streaming)") |
| 898 | print(f" /health — health check") |
| 899 | print(f" /backend — backend info") |
| 900 | print(f" /api/backend — studio backend info") |
| 901 | print(f" /api/models — list GGUF models") |
| 902 | print(f" /api/export — trigger HF→GGUF export") |
| 903 | print(f" /api/export/<job_id> — export job status") |
| 904 | print(f" /api/dataset — list datasets") |
| 905 | print(f" /api/chat — streaming chat (web UI)") |
| 906 | print(f" /api/train/metrics — training metrics SSE") |
| 907 | print() |
| 908 | |
| 909 | try: |
| 910 | server.serve_forever() |
| 911 | except KeyboardInterrupt: |
| 912 | print("\nShutting down...") |
| 913 | backend.stop() |
| 914 | server.server_close() |
| 915 | |
| 916 | |
| 917 | if __name__ == "__main__": |
| 918 | main() |