Spaces:
Running
Running
Download app.py from ryan33121/gemma-coder-api: direct link, hf CLI and curl.
- Browser
- Download file 1.94 kB
-
https://huggingface.co/spaces/ryan33121/gemma-coder-api/resolve/ca9af7bf372074949d5100faee2b99ff44dbf3e2/app.py
- Command line
-
hf download hf://spaces/ryan33121/gemma-coder-api@ca9af7bf372074949d5100faee2b99ff44dbf3e2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ryan33121/gemma-coder-api/resolve/ca9af7bf372074949d5100faee2b99ff44dbf3e2/app.py
1.94 kB
| import json | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import StreamingResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from llama_cpp import Llama | |
| from huggingface_hub import hf_hub_download | |
| from pydantic import BaseModel | |
| from typing import List | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # 1. Load model with minimal resource allocation | |
| print("Loading model...") | |
| MODEL_PATH = hf_hub_download( | |
| repo_id="Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF", | |
| filename="qwen2.5-coder-1.5b-instruct-q4_k_m.gguf" | |
| ) | |
| # Crucial: n_gpu_layers=0 forces CPU, n_threads=1 saves RAM | |
| llm = Llama( | |
| model_path=MODEL_PATH, | |
| n_ctx=512, | |
| n_gpu_layers=0, | |
| n_threads=1 | |
| ) | |
| print("Model loaded successfully.") | |
| class ChatMessage(BaseModel): | |
| role: str | |
| content: str | |
| class ChatRequest(BaseModel): | |
| messages: List[ChatMessage] | |
| def read_root(): | |
| return {"message": "Server is up!"} | |
| async def chat_completion(request: ChatRequest): | |
| print("Received chat request...") # Check logs for this | |
| try: | |
| history = [{"role": msg.role, "content": msg.content} for msg in request.messages] | |
| def stream_generator(): | |
| print("Starting inference...") # Check logs for this | |
| response_stream = llm.create_chat_completion( | |
| messages=history, | |
| temperature=0.2, | |
| stream=True | |
| ) | |
| for chunk in response_stream: | |
| yield f"data: {json.dumps(chunk)}\n\n" | |
| yield "data: [DONE]\n\n" | |
| print("Inference finished.") # Check logs for this | |
| return StreamingResponse(stream_generator(), media_type="text/event-stream") | |
| except Exception as e: | |
| print(f"ERROR: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) |