|
| 1 | +"""Gemma inference view. |
| 2 | +
|
| 3 | +The Llama constructor is patched automatically by `wildedge run --integrations gguf` |
| 4 | +via sitecustomize.py — load/unload/inference events are tracked without any |
| 5 | +wildedge imports here. |
| 6 | +
|
| 7 | +On macOS, waitress (thread-pool, no fork) is used as the WSGI server. |
| 8 | +Metal is initialised once at startup in the main process and shared safely |
| 9 | +across request threads. gunicorn (fork-based) requires llama-cpp-python built |
| 10 | +without Metal on macOS (CMAKE_ARGS="-DGGML_METAL=OFF"). |
| 11 | +""" |
| 12 | + |
| 13 | +import json |
| 14 | +import os |
| 15 | +import threading |
| 16 | + |
| 17 | +from django.http import JsonResponse |
| 18 | +from django.views.decorators.csrf import csrf_exempt |
| 19 | +from django.views.decorators.http import require_POST |
| 20 | +from llama_cpp import Llama |
| 21 | + |
| 22 | +REPO = "bartowski/gemma-2-2b-it-GGUF" |
| 23 | +FILE = "gemma-2-2b-it-Q4_K_M.gguf" |
| 24 | + |
| 25 | +_llm = Llama.from_pretrained( |
| 26 | + repo_id=REPO, |
| 27 | + filename=FILE, |
| 28 | + n_ctx=512, |
| 29 | + n_gpu_layers=int(os.environ.get("GPU_LAYERS", "-1")), |
| 30 | + verbose=False, |
| 31 | +) |
| 32 | + |
| 33 | +# Llama inference is not thread-safe on a single context — serialise requests. |
| 34 | +_llm_lock = threading.Lock() |
| 35 | + |
| 36 | + |
| 37 | +@csrf_exempt |
| 38 | +@require_POST |
| 39 | +def infer(request): |
| 40 | + try: |
| 41 | + body = json.loads(request.body) |
| 42 | + except json.JSONDecodeError: |
| 43 | + return JsonResponse({"error": "invalid JSON"}, status=400) |
| 44 | + |
| 45 | + prompt = body.get("prompt", "").strip() |
| 46 | + if not prompt: |
| 47 | + return JsonResponse({"error": "prompt is required"}, status=400) |
| 48 | + |
| 49 | + with _llm_lock: |
| 50 | + result = _llm(prompt, max_tokens=256, temperature=0.7) |
| 51 | + |
| 52 | + text = result["choices"][0]["text"].strip() |
| 53 | + return JsonResponse({"response": text}) |
0 commit comments