Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 4 |
+
from fastapi.responses import StreamingResponse
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
from llama_cpp import Llama
|
| 8 |
+
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
# Enable CORS for frontend integration
|
| 12 |
+
app.add_middleware(
|
| 13 |
+
CORSMiddleware,
|
| 14 |
+
allow_origins=["*"],
|
| 15 |
+
allow_credentials=True,
|
| 16 |
+
allow_methods=["*"],
|
| 17 |
+
allow_headers=["*"],
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# Download the Gemma model from Hugging Face Hub if not cached locally
|
| 21 |
+
MODEL_FILE = "gemma-4-E2B-it-IQ4_NL.gguf"
|
| 22 |
+
if not os.path.exists(MODEL_FILE):
|
| 23 |
+
print("Downloading Gemma model, please wait...")
|
| 24 |
+
hf_hub_download(
|
| 25 |
+
repo_id="unsloth/gemma-4-E2B-it-GGUF",
|
| 26 |
+
filename=MODEL_FILE,
|
| 27 |
+
local_dir="."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Initialize local LLM instance with 2048 context length
|
| 31 |
+
llm = Llama(model_path=f"./{MODEL_FILE}", n_ctx=2048, n_threads=2)
|
| 32 |
+
|
| 33 |
+
@app.post("/v1/chat/completions")
|
| 34 |
+
async def chat_completion(request: Request):
|
| 35 |
+
# Secure the endpoint using a custom API Bearer Token
|
| 36 |
+
api_key = request.headers.get("Authorization")
|
| 37 |
+
if api_key != f"Bearer {os.environ.get('MY_SECRET_KEY', 'default_pass')}":
|
| 38 |
+
raise HTTPException(status_code=401, detail="Unauthorized access.")
|
| 39 |
+
|
| 40 |
+
body = await request.json()
|
| 41 |
+
messages = body.get("messages", [])
|
| 42 |
+
|
| 43 |
+
# Format chat history into standard LLM prompt template
|
| 44 |
+
prompt = ""
|
| 45 |
+
for msg in messages:
|
| 46 |
+
role = msg.get("role")
|
| 47 |
+
content = msg.get("content")
|
| 48 |
+
prompt += f"<|im_start|>{role}\n{content}<|im_end|>\n"
|
| 49 |
+
prompt += "<|im_start|>assistant\n"
|
| 50 |
+
|
| 51 |
+
# Generate streaming response from the model
|
| 52 |
+
output = llm(prompt, max_tokens=512, stream=True)
|
| 53 |
+
|
| 54 |
+
def stream_generator():
|
| 55 |
+
for chunk in output:
|
| 56 |
+
token = chunk['choices'][0]['text']
|
| 57 |
+
data = {"choices": [{"delta": {"content": token}, "finish_reason": None}]}
|
| 58 |
+
yield f"data: {json.dumps(data)}\n\n"
|
| 59 |
+
yield "data: [DONE]\n\n"
|
| 60 |
+
|
| 61 |
+
return StreamingResponse(stream_generator(), media_type="text/event-stream")
|