Download app.py from new-arc/opaiv2: direct link, hf CLI and curl.
- Browser
- Download file 29.9 kB
-
https://huggingface.co/spaces/new-arc/opaiv2/resolve/main/app.py
- Command line
-
hf download hf://spaces/new-arc/opaiv2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/new-arc/opaiv2/resolve/main/app.py
29.9 kB
| import json | |
| import logging | |
| import os | |
| import re | |
| import threading | |
| import time | |
| import uuid | |
| from typing import Any, Callable, Dict, List, Optional, Union | |
| from fastapi import Depends, FastAPI, Header, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import StreamingResponse | |
| from huggingface_hub import hf_hub_download | |
| from pydantic import BaseModel, Field | |
| # --------------------------------------------------------------------------- | |
| # Configuration | |
| # --------------------------------------------------------------------------- | |
| def _env_str(name: str, default: Optional[str] = None) -> Optional[str]: | |
| val = os.environ.get(name) | |
| if val is None: | |
| return default | |
| val = val.strip() | |
| return val if val else default | |
| GGUF_REPO = _env_str("GGUF_REPO", "Qwen/Qwen2.5-1.5B-Instruct-GGUF") | |
| GGUF_FILE = _env_str("GGUF_FILE", "qwen2.5-1.5b-instruct-q4_k_m.gguf") | |
| PUBLIC_MODEL_ID = _env_str("PUBLIC_MODEL_ID", "qwen2.5-1.5b") | |
| CHAT_FORMAT = _env_str("CHAT_FORMAT") | |
| DEFAULT_MAX_TOKENS = int(os.environ.get("DEFAULT_MAX_TOKENS", "512")) | |
| N_CTX = int(os.environ.get("N_CTX", "1024")) | |
| N_THREADS = int(os.environ.get("N_THREADS", "2")) | |
| N_THREADS_BATCH = _env_str("N_THREADS_BATCH") | |
| N_BATCH = _env_str("N_BATCH") | |
| N_UBATCH = _env_str("N_UBATCH") | |
| def _env_bool(name: str, default: bool) -> bool: | |
| val = os.environ.get(name) | |
| if val is None: | |
| return default | |
| return val.strip().lower() in {"1", "true", "yes", "on"} | |
| FLASH_ATTN = _env_bool("FLASH_ATTN", True) | |
| USE_MMAP = _env_bool("USE_MMAP", True) | |
| USE_MLOCK = _env_bool("USE_MLOCK", False) | |
| NUMA = _env_bool("NUMA", False) | |
| LLAMA_VERBOSE = _env_bool("LLAMA_VERBOSE", True) | |
| ENABLE_BENCH = _env_bool("ENABLE_BENCH", False) | |
| ENABLE_TOOL_CALLS = _env_bool("ENABLE_TOOL_CALLS", True) | |
| ENABLE_TOOL_HEURISTICS = _env_bool("ENABLE_TOOL_HEURISTICS", True) | |
| LAST_PERF: dict = {} | |
| BENCH_JOBS: Dict[str, Dict[str, Any]] = {} | |
| LAST_REQUEST: Dict[str, Any] = {} | |
| logger = logging.getLogger(__name__) | |
| logging.basicConfig(level=logging.INFO) | |
| app = FastAPI(title="Qwen GGUF OpenAI-Compatible API") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def _patch_generation_chat_template_support(llama_cpp_module: Any) -> None: | |
| chat_format_mod = getattr(llama_cpp_module, "llama_chat_format", None) | |
| formatter_cls = getattr(chat_format_mod, "Jinja2ChatFormatter", None) if chat_format_mod else None | |
| if formatter_cls is None or getattr(formatter_cls, "_opt_ai_generation_patch", False): | |
| return | |
| original_init = formatter_cls.__init__ | |
| generation_tag_pattern = re.compile(r"{%-?\s*(end)?generation\s*-?%}") | |
| def patched_init(self, *args, **kwargs): | |
| template = kwargs.get("template") | |
| if template is None and args: | |
| template = args[0] | |
| if isinstance(template, str) and "generation" in template: | |
| sanitized = generation_tag_pattern.sub("", template) | |
| if sanitized != template: | |
| logger.info("Sanitized unsupported Jinja generation tags in GGUF chat template") | |
| if "template" in kwargs: | |
| kwargs["template"] = sanitized | |
| else: | |
| args = (sanitized, *args[1:]) | |
| return original_init(self, *args, **kwargs) | |
| formatter_cls.__init__ = patched_init | |
| formatter_cls._opt_ai_generation_patch = True | |
| def _load_model(): | |
| import llama_cpp | |
| from llama_cpp import Llama | |
| logger.info( | |
| "llama_cpp_python version: %s (%s)", | |
| getattr(llama_cpp, "__version__", "unknown"), | |
| getattr(llama_cpp, "__file__", "unknown"), | |
| ) | |
| logger.info("Downloading %s / %s ...", GGUF_REPO, GGUF_FILE) | |
| model_path = hf_hub_download(repo_id=GGUF_REPO, filename=GGUF_FILE) | |
| logger.info("Model downloaded to %s", model_path) | |
| n_threads_batch = int(N_THREADS_BATCH) if N_THREADS_BATCH else None | |
| n_batch = int(N_BATCH) if N_BATCH else None | |
| n_ubatch = int(N_UBATCH) if N_UBATCH else None | |
| kwargs = { | |
| "model_path": model_path, | |
| "n_ctx": N_CTX, | |
| "n_threads": N_THREADS, | |
| "use_mmap": USE_MMAP, | |
| "use_mlock": USE_MLOCK, | |
| "numa": NUMA, | |
| "n_gpu_layers": 0, # CPU-only | |
| "flash_attn": FLASH_ATTN, | |
| "verbose": LLAMA_VERBOSE, | |
| } | |
| if n_threads_batch is not None: | |
| kwargs["n_threads_batch"] = n_threads_batch | |
| if n_batch is not None: | |
| kwargs["n_batch"] = n_batch | |
| if n_ubatch is not None: | |
| kwargs["n_ubatch"] = n_ubatch | |
| if CHAT_FORMAT: | |
| kwargs["chat_format"] = CHAT_FORMAT | |
| logger.info( | |
| "Loading model with n_ctx=%s n_threads=%s flash_attn=%s use_mmap=%s use_mlock=%s numa=%s n_batch=%s n_ubatch=%s n_threads_batch=%s chat_format=%s verbose=%s", | |
| kwargs["n_ctx"], | |
| kwargs["n_threads"], | |
| kwargs["flash_attn"], | |
| kwargs["use_mmap"], | |
| kwargs["use_mlock"], | |
| kwargs["numa"], | |
| kwargs.get("n_batch"), | |
| kwargs.get("n_ubatch"), | |
| kwargs.get("n_threads_batch"), | |
| kwargs.get("chat_format"), | |
| kwargs["verbose"], | |
| ) | |
| try: | |
| llm = Llama(**kwargs) | |
| except Exception as exc: | |
| if "unknown tag 'generation'" in str(exc): | |
| logger.info("Retrying model load after enabling GGUF generation-tag compatibility") | |
| _patch_generation_chat_template_support(llama_cpp) | |
| llm = Llama(**kwargs) | |
| else: | |
| logger.exception("llama.cpp failed to load %s from repo %s", GGUF_FILE, GGUF_REPO) | |
| raise | |
| except BaseException: | |
| logger.exception("llama.cpp failed to load %s from repo %s", GGUF_FILE, GGUF_REPO) | |
| raise | |
| logger.info("Model loaded successfully!") | |
| return llm | |
| LLM = _load_model() | |
| def _record_perf(**kwargs: Any) -> None: | |
| LAST_PERF.update(kwargs) | |
| LAST_PERF["updated_at"] = int(time.time()) | |
| def _extract_json_payload(text: str) -> Optional[Dict[str, Any]]: | |
| text = text.strip() | |
| if text.startswith("```"): | |
| parts = text.split("```", 2) | |
| if len(parts) >= 2: | |
| text = parts[1].strip() | |
| if text.startswith("json"): | |
| text = text[4:].strip() | |
| try: | |
| return json.loads(text) | |
| except Exception: | |
| return None | |
| def _normalize_tool_calls(tool_calls: List[Dict[str, Any]]) -> List[Dict[str, Any]]: | |
| normalized = [] | |
| for i, call in enumerate(tool_calls): | |
| fn = call.get("function") or {} | |
| name = fn.get("name") or call.get("name") | |
| args = fn.get("arguments") or call.get("arguments") or {} | |
| if isinstance(args, dict): | |
| args = json.dumps(args) | |
| normalized.append( | |
| { | |
| "id": call.get("id") or f"call_{i+1}", | |
| "type": "function", | |
| "function": {"name": name, "arguments": args}, | |
| } | |
| ) | |
| return normalized | |
| def _sanitize_tool_schema(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]: | |
| sanitized = [] | |
| for tool in tools: | |
| t = json.loads(json.dumps(tool)) | |
| fn = t.get("function") or {} | |
| params = fn.get("parameters") or {} | |
| props = params.get("properties") | |
| if isinstance(props, dict): | |
| for key, val in list(props.items()): | |
| if isinstance(val, str): | |
| lower = val.strip().lower() | |
| if lower.startswith("@{type=") and lower.endswith("}"): | |
| type_name = lower[len("@{type="):-1].strip() | |
| props[key] = {"type": type_name} | |
| elif lower in {"string", "number", "integer", "boolean", "object", "array"}: | |
| props[key] = {"type": lower} | |
| fn["parameters"] = params | |
| t["function"] = fn | |
| sanitized.append(t) | |
| return sanitized | |
| def _last_user_text(messages: List[Dict[str, str]]) -> str: | |
| for msg in reversed(messages): | |
| if msg.get("role") == "user": | |
| return msg.get("content", "") | |
| return "" | |
| def _should_use_tool(text: str) -> bool: | |
| low = text.lower() | |
| if len(low) < 8: | |
| return False | |
| keywords = [ | |
| "search", | |
| "latest", | |
| "today", | |
| "news", | |
| "current", | |
| "price", | |
| "weather", | |
| "find", | |
| "lookup", | |
| "look up", | |
| "who is", | |
| "what is", | |
| "when is", | |
| "where is", | |
| "stock", | |
| "rate", | |
| "score", | |
| ] | |
| return any(k in low for k in keywords) | |
| def _heuristic_tool_call( | |
| messages: List[Dict[str, str]], | |
| tools: List[Dict[str, Any]], | |
| forced_tool: Optional[str], | |
| ) -> Optional[List[Dict[str, Any]]]: | |
| if not ENABLE_TOOL_HEURISTICS or not tools: | |
| return None | |
| if forced_tool: | |
| tool_name = forced_tool | |
| else: | |
| if not _should_use_tool(_last_user_text(messages)): | |
| return None | |
| tool_name = tools[0].get("function", {}).get("name") or tools[0].get("name") | |
| if not tool_name: | |
| return None | |
| args = {"input": _last_user_text(messages)} | |
| return _normalize_tool_calls( | |
| [ | |
| { | |
| "id": "call_1", | |
| "type": "function", | |
| "function": {"name": tool_name, "arguments": args}, | |
| } | |
| ] | |
| ) | |
| def _run_tool_router( | |
| messages: List[Dict[str, str]], | |
| tools: List[Dict[str, Any]], | |
| forced_tool: Optional[str], | |
| ) -> Optional[List[Dict[str, Any]]]: | |
| if not ENABLE_TOOL_CALLS: | |
| return None | |
| tool_list = json.dumps(tools, ensure_ascii=True) | |
| instruction = ( | |
| "You are a tool caller. Given the user conversation and the available tools, " | |
| "decide whether to call a tool. If you call a tool, respond with ONLY valid JSON " | |
| "in the format: {\"tool_calls\": [{\"id\":\"call_1\",\"type\":\"function\"," | |
| "\"function\":{\"name\":\"TOOL_NAME\",\"arguments\":\"JSON_STRING\"}}]}. " | |
| "If no tool should be called, respond with ONLY: {\"tool_calls\": []}." | |
| ) | |
| if forced_tool: | |
| instruction += f" You MUST call the tool named \"{forced_tool}\"." | |
| tool_messages = [{"role": "system", "content": instruction}] | |
| tool_messages.extend(messages) | |
| result = LLM.create_chat_completion( | |
| messages=tool_messages, | |
| max_tokens=256, | |
| temperature=0.0, | |
| top_p=1.0, | |
| stream=False, | |
| ) | |
| content = result["choices"][0]["message"]["content"] | |
| payload = _extract_json_payload(content) | |
| if not payload or "tool_calls" not in payload: | |
| return None | |
| calls = payload.get("tool_calls") or [] | |
| if not isinstance(calls, list): | |
| return None | |
| return _normalize_tool_calls(calls) | |
| # --------------------------------------------------------------------------- | |
| # Pydantic schemas | |
| # --------------------------------------------------------------------------- | |
| class ChatMessage(BaseModel): | |
| role: str | |
| content: str | |
| class ChatCompletionRequest(BaseModel): | |
| model: str | |
| messages: List[ChatMessage] | |
| max_tokens: Optional[int] = Field(default=None, alias="maxTokens") | |
| temperature: Optional[float] = 0.7 | |
| top_p: Optional[float] = Field(default=0.9, alias="topP") | |
| stream: Optional[bool] = False | |
| streaming: Optional[bool] = False | |
| tools: Optional[List[Dict[str, Any]]] = None | |
| tool_choice: Optional[Any] = None | |
| functions: Optional[List[Dict[str, Any]]] = None | |
| function_call: Optional[Any] = None | |
| class Config: | |
| extra = "allow" | |
| populate_by_name = True | |
| def _resolve_tools(req: "ChatCompletionRequest") -> (List[Dict[str, Any]], Optional[str]): | |
| req_data = req.dict(by_alias=True) | |
| tools = req_data.get("tools") or [] | |
| if not tools and req_data.get("functions"): | |
| tools = [{"type": "function", "function": f} for f in req_data["functions"]] | |
| tool_choice = req_data.get("tool_choice") | |
| if tool_choice is None: | |
| tool_choice = req_data.get("function_call") | |
| forced_tool = None | |
| if isinstance(tool_choice, dict): | |
| fn = tool_choice.get("function") or {} | |
| forced_tool = fn.get("name") or tool_choice.get("name") | |
| elif isinstance(tool_choice, str): | |
| if tool_choice == "none": | |
| return tools, None | |
| if tool_choice != "auto": | |
| forced_tool = tool_choice | |
| return _sanitize_tool_schema(tools), forced_tool | |
| class CompletionRequest(BaseModel): | |
| model: str | |
| prompt: Union[str, List[str]] | |
| max_tokens: Optional[int] = Field(default=None, alias="maxTokens") | |
| temperature: Optional[float] = 0.7 | |
| top_p: Optional[float] = Field(default=0.9, alias="topP") | |
| stream: Optional[bool] = False | |
| streaming: Optional[bool] = False | |
| class Config: | |
| extra = "allow" | |
| populate_by_name = True | |
| class BenchRequest(BaseModel): | |
| repo: Optional[str] = None | |
| file: Optional[str] = None | |
| prompt: Optional[str] = None | |
| max_tokens: int = 128 | |
| repeats: int = 1 | |
| warmup: bool = False | |
| class ModelData(BaseModel): | |
| id: str | |
| object: str = "model" | |
| owned_by: str = "huggingface" | |
| class ModelList(BaseModel): | |
| object: str = "list" | |
| data: List[ModelData] | |
| # --------------------------------------------------------------------------- | |
| # Auth | |
| # --------------------------------------------------------------------------- | |
| def _require_api_key(authorization: Optional[str] = Header(default=None)) -> str: | |
| expected = os.environ.get("API_KEY") | |
| if not expected: | |
| raise HTTPException(status_code=500, detail="API_KEY is not set") | |
| if not authorization or not authorization.startswith("Bearer "): | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Unauthorized", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| token = authorization.split(" ", 1)[1].strip() | |
| if token != expected: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Unauthorized", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| return token | |
| # --------------------------------------------------------------------------- | |
| # Endpoints | |
| # --------------------------------------------------------------------------- | |
| def list_models(api_key: str = Depends(_require_api_key)): | |
| return ModelList(data=[ModelData(id=PUBLIC_MODEL_ID)]) | |
| def chat_completions(req: ChatCompletionRequest, api_key: str = Depends(_require_api_key)): | |
| LAST_REQUEST.update({"endpoint": "chat", "payload": req.dict(by_alias=True), "updated_at": int(time.time())}) | |
| req_id = uuid.uuid4().hex | |
| max_tokens = req.max_tokens or DEFAULT_MAX_TOKENS | |
| temperature = req.temperature if req.temperature is not None else 0.7 | |
| top_p = req.top_p if req.top_p is not None else 0.9 | |
| messages = [{"role": m.role, "content": "" if m.content is None else m.content} for m in req.messages] | |
| want_stream = bool(req.stream) or bool(req.streaming) | |
| t0 = time.perf_counter() | |
| tools, forced_tool = _resolve_tools(req) | |
| if tools: | |
| tool_calls = _run_tool_router(messages, tools, forced_tool) | |
| if tool_calls is None or len(tool_calls) == 0: | |
| tool_calls = _heuristic_tool_call(messages, tools, forced_tool) | |
| if tool_calls is not None and len(tool_calls) > 0: | |
| response = { | |
| "id": f"chatcmpl-{req_id}", | |
| "object": "chat.completion", | |
| "created": int(time.time()), | |
| "model": PUBLIC_MODEL_ID, | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "message": { | |
| "role": "assistant", | |
| "content": "", | |
| "tool_calls": tool_calls, | |
| }, | |
| "finish_reason": "tool_calls", | |
| } | |
| ], | |
| "usage": { | |
| "prompt_tokens": 0, | |
| "completion_tokens": 0, | |
| "total_tokens": 0, | |
| }, | |
| } | |
| if want_stream: | |
| def tool_stream(): | |
| chunk = { | |
| "id": response["id"], | |
| "object": "chat.completion.chunk", | |
| "created": response["created"], | |
| "model": PUBLIC_MODEL_ID, | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "delta": {"content": "", "tool_calls": tool_calls}, | |
| "finish_reason": "tool_calls", | |
| } | |
| ], | |
| } | |
| yield f"data: {json.dumps(chunk)}\n\n" | |
| yield "data: [DONE]\n\n" | |
| return StreamingResponse(tool_stream(), media_type="text/event-stream") | |
| return response | |
| if want_stream: | |
| stream_iter = LLM.create_chat_completion( | |
| messages=messages, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| stream=True, | |
| ) | |
| def stream_generator(): | |
| in_think_block = False | |
| first_chunk_time = None | |
| chunk_count = 0 | |
| for chunk in stream_iter: | |
| chunk_count += 1 | |
| if first_chunk_time is None: | |
| first_chunk_time = time.perf_counter() | |
| _record_perf( | |
| last_request_id=req_id, | |
| last_stream=True, | |
| last_ttft_s=first_chunk_time - t0, | |
| last_prompt_chars=len(str(messages)), | |
| last_chunk_count=None, | |
| last_total_s=None, | |
| ) | |
| # Intercept and strip <think> blocks on the fly | |
| if "choices" in chunk and len(chunk["choices"]) > 0: | |
| choice = chunk["choices"][0] | |
| delta = choice.setdefault("delta", {}) | |
| content = delta.get("content") | |
| if not isinstance(content, str): | |
| delta.setdefault("content", "") | |
| yield f"data: {json.dumps(chunk)}\n\n" | |
| continue | |
| if "<think>" in content: | |
| in_think_block = True | |
| content = content.split("<think>")[0] | |
| # If there's still content before <think>, yield it first | |
| if in_think_block: | |
| if "</think>" in content: | |
| in_think_block = False | |
| content = content.split("</think>")[-1].lstrip('\n') | |
| else: | |
| content = "" # Suppress output while thinking | |
| delta["content"] = content | |
| has_non_content_delta = any(k != "content" for k in delta.keys()) | |
| if content or has_non_content_delta or choice.get("finish_reason") is not None: | |
| yield f"data: {json.dumps(chunk)}\n\n" | |
| else: | |
| yield f"data: {json.dumps(chunk)}\n\n" | |
| total = time.perf_counter() - t0 | |
| _record_perf( | |
| last_request_id=req_id, | |
| last_stream=True, | |
| last_total_s=total, | |
| last_chunk_count=chunk_count, | |
| ) | |
| yield "data: [DONE]\n\n" | |
| return StreamingResponse( | |
| stream_generator(), media_type="text/event-stream" | |
| ) | |
| try: | |
| result = LLM.create_chat_completion( | |
| messages=messages, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| stream=False, | |
| ) | |
| except Exception as exc: | |
| logger.exception("Generation failed") | |
| raise HTTPException( | |
| status_code=500, detail=f"Generation error: {exc}" | |
| ) from exc | |
| elapsed = time.perf_counter() - t0 | |
| choices = result.get("choices") or [] | |
| if not choices: | |
| result["choices"] = [{"index": 0, "message": {"role": "assistant", "content": ""}, "finish_reason": "stop"}] | |
| choices = result["choices"] | |
| message = choices[0].setdefault("message", {"role": "assistant", "content": ""}) | |
| content = message.get("content") or "" | |
| # Strip <think> block from non-streaming response | |
| if "<think>" in content and "</think>" in content: | |
| content = content.split("</think>")[-1].lstrip('\n') | |
| elif "<think>" in content: | |
| content = content.split("<think>")[0] | |
| message["content"] = content | |
| _record_perf( | |
| last_request_id=req_id, | |
| last_stream=False, | |
| last_ttft_s=elapsed, | |
| last_total_s=elapsed, | |
| last_prompt_chars=len(str(messages)), | |
| last_completion_chars=len(content), | |
| ) | |
| logger.info("Chat completed in %.2fs - %d chars", elapsed, len(content)) | |
| return result | |
| def completions(req: CompletionRequest, api_key: str = Depends(_require_api_key)): | |
| LAST_REQUEST.update({"endpoint": "completions", "payload": req.dict(by_alias=True), "updated_at": int(time.time())}) | |
| req_id = uuid.uuid4().hex | |
| if isinstance(req.prompt, list): | |
| prompt = req.prompt[0] if req.prompt else "" | |
| else: | |
| prompt = req.prompt | |
| max_tokens = req.max_tokens or DEFAULT_MAX_TOKENS | |
| temperature = req.temperature if req.temperature is not None else 0.7 | |
| top_p = req.top_p if req.top_p is not None else 0.9 | |
| want_stream = bool(req.stream) or bool(req.streaming) | |
| t0 = time.perf_counter() | |
| if want_stream: | |
| stream_iter = LLM.create_completion( | |
| prompt=prompt, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| stream=True, | |
| ) | |
| def stream_generator(): | |
| first_chunk_time = None | |
| chunk_count = 0 | |
| for chunk in stream_iter: | |
| chunk_count += 1 | |
| if first_chunk_time is None: | |
| first_chunk_time = time.perf_counter() | |
| _record_perf( | |
| last_request_id=req_id, | |
| last_stream=True, | |
| last_ttft_s=first_chunk_time - t0, | |
| last_prompt_chars=len(prompt), | |
| last_chunk_count=None, | |
| last_total_s=None, | |
| ) | |
| yield f"data: {json.dumps(chunk)}\n\n" | |
| total = time.perf_counter() - t0 | |
| _record_perf( | |
| last_request_id=req_id, | |
| last_stream=True, | |
| last_total_s=total, | |
| last_chunk_count=chunk_count, | |
| ) | |
| yield "data: [DONE]\n\n" | |
| return StreamingResponse( | |
| stream_generator(), media_type="text/event-stream" | |
| ) | |
| try: | |
| result = LLM.create_completion( | |
| prompt=prompt, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| stream=False, | |
| ) | |
| except Exception as exc: | |
| logger.exception("Generation failed") | |
| raise HTTPException( | |
| status_code=500, detail=f"Generation error: {exc}" | |
| ) from exc | |
| elapsed = time.perf_counter() - t0 | |
| _record_perf( | |
| last_request_id=req_id, | |
| last_stream=False, | |
| last_ttft_s=elapsed, | |
| last_total_s=elapsed, | |
| last_prompt_chars=len(prompt), | |
| ) | |
| logger.info("Completion in %.2fs", elapsed) | |
| return result | |
| def debug_echo(req: ChatCompletionRequest, api_key: str = Depends(_require_api_key)): | |
| return { | |
| "id": f"chatcmpl-debug-{uuid.uuid4().hex}", | |
| "object": "chat.completion", | |
| "created": int(time.time()), | |
| "model": PUBLIC_MODEL_ID, | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "message": { | |
| "role": "assistant", | |
| "content": "Debug echo: this is a test response.", | |
| }, | |
| "finish_reason": "stop", | |
| } | |
| ], | |
| "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}, | |
| } | |
| def _run_bench_internal( | |
| req_data: Dict[str, Any], | |
| on_progress: Optional[Callable[[Dict[str, Any]], None]] = None, | |
| ) -> Dict[str, Any]: | |
| import bench as bench_mod | |
| repo = req_data.get("repo") or GGUF_REPO | |
| file = req_data.get("file") or GGUF_FILE | |
| prompt = req_data.get("prompt") or "Write a short answer about CPU inference." | |
| max_tokens = max(1, int(req_data.get("max_tokens", 128))) | |
| repeats = max(1, min(int(req_data.get("repeats", 1)), 3)) | |
| warmup = bool(req_data.get("warmup", False)) | |
| if on_progress: | |
| on_progress( | |
| { | |
| "stage": "download", | |
| "repo": repo, | |
| "file": file, | |
| "updated_at": int(time.time()), | |
| } | |
| ) | |
| model_path = bench_mod._load_model_path(repo, file) | |
| configs = bench_mod._default_configs() | |
| if warmup: | |
| try: | |
| bench_mod._run_once(model_path, prompt, max_tokens, configs[0]) | |
| except Exception: | |
| pass | |
| results = [] | |
| total_configs = len(configs) | |
| for idx, cfg in enumerate(configs, start=1): | |
| if on_progress: | |
| on_progress( | |
| { | |
| "stage": "benchmark", | |
| "config": cfg.get("name"), | |
| "config_index": idx, | |
| "config_total": total_configs, | |
| "updated_at": int(time.time()), | |
| } | |
| ) | |
| samples = [] | |
| errors = [] | |
| for _ in range(repeats): | |
| try: | |
| metrics = bench_mod._run_once(model_path, prompt, max_tokens, cfg) | |
| samples.append(metrics) | |
| except Exception as exc: | |
| errors.append(str(exc)) | |
| if samples: | |
| ttft_avg = sum(s["ttft_s"] for s in samples) / len(samples) | |
| total_avg = sum(s["total_s"] for s in samples) / len(samples) | |
| chunk_avg = sum(s["chunk_count"] for s in samples) / len(samples) | |
| else: | |
| ttft_avg = None | |
| total_avg = None | |
| chunk_avg = None | |
| results.append( | |
| { | |
| "name": cfg["name"], | |
| "config": cfg, | |
| "runs": len(samples), | |
| "ttft_avg_s": ttft_avg, | |
| "total_avg_s": total_avg, | |
| "chunk_avg": chunk_avg, | |
| "errors": errors, | |
| } | |
| ) | |
| ok = [r for r in results if r["total_avg_s"] is not None] | |
| best = sorted(ok, key=lambda r: (r["total_avg_s"], r["ttft_avg_s"]))[0] if ok else None | |
| env_lines = bench_mod._env_lines(best["config"]) if best else [] | |
| return { | |
| "repo": repo, | |
| "file": file, | |
| "prompt_chars": len(prompt), | |
| "max_tokens": max_tokens, | |
| "repeats": repeats, | |
| "results": results, | |
| "best": best, | |
| "recommended_env": env_lines, | |
| } | |
| def _bench_job_runner(job_id: str, req_data: Dict[str, Any]) -> None: | |
| def _progress(update: Dict[str, Any]) -> None: | |
| BENCH_JOBS[job_id].update({"progress": update, "updated_at": int(time.time())}) | |
| try: | |
| result = _run_bench_internal(req_data, on_progress=_progress) | |
| BENCH_JOBS[job_id].update( | |
| { | |
| "status": "done", | |
| "result": result, | |
| "finished_at": int(time.time()), | |
| } | |
| ) | |
| except Exception as exc: | |
| BENCH_JOBS[job_id].update( | |
| { | |
| "status": "error", | |
| "error": str(exc), | |
| "finished_at": int(time.time()), | |
| } | |
| ) | |
| def debug_bench( | |
| req: BenchRequest, | |
| api_key: str = Depends(_require_api_key), | |
| sync: bool = False, | |
| ): | |
| if not ENABLE_BENCH: | |
| raise HTTPException( | |
| status_code=403, | |
| detail="Benchmarking disabled. Set ENABLE_BENCH=1 and restart.", | |
| ) | |
| req_data = req.dict() | |
| if sync: | |
| return _run_bench_internal(req_data) | |
| job_id = uuid.uuid4().hex | |
| BENCH_JOBS[job_id] = { | |
| "status": "running", | |
| "started_at": int(time.time()), | |
| "progress": {"stage": "queued", "updated_at": int(time.time())}, | |
| } | |
| thread = threading.Thread( | |
| target=_bench_job_runner, args=(job_id, req_data), daemon=True | |
| ) | |
| thread.start() | |
| return {"job_id": job_id, "status": "running"} | |
| def debug_bench_status(job_id: str, api_key: str = Depends(_require_api_key)): | |
| job = BENCH_JOBS.get(job_id) | |
| if not job: | |
| raise HTTPException(status_code=404, detail="Unknown job_id") | |
| return job | |
| def debug_last_request(api_key: str = Depends(_require_api_key)): | |
| return LAST_REQUEST | |
| def debug_perf(api_key: str = Depends(_require_api_key)): | |
| return { | |
| "last": LAST_PERF, | |
| "config": { | |
| "n_ctx": N_CTX, | |
| "n_threads": N_THREADS, | |
| "n_threads_batch": int(N_THREADS_BATCH) if N_THREADS_BATCH else None, | |
| "n_batch": int(N_BATCH) if N_BATCH else None, | |
| "n_ubatch": int(N_UBATCH) if N_UBATCH else None, | |
| "use_mmap": USE_MMAP, | |
| "use_mlock": USE_MLOCK, | |
| "numa": NUMA, | |
| "flash_attn": FLASH_ATTN, | |
| "model_repo": GGUF_REPO, | |
| "model_file": GGUF_FILE, | |
| }, | |
| } | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run("app:app", host="0.0.0.0", port=7860) | |