gemma-coder-api / app.py
ryan33121's picture
Update app.py
add7e8f verified
Raw History Blame
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]
@app.get("/")
def read_root():
return {"message": "Server is up!"}
@app.post("/v1/chat/completions")
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))