Upload backend_app.py.txt
Browse files- backend_app.py.txt +72 -0
backend_app.py.txt
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Brainbox API proxy.
|
| 3 |
+
Run with:
|
| 4 |
+
pip install fastapi uvicorn openai python-dotenv
|
| 5 |
+
export HF_ENDPOINT_URL="https://YOUR-ENDPOINT.endpoints.huggingface.cloud/v1"
|
| 6 |
+
export HF_TOKEN="hf_your_secret_token"
|
| 7 |
+
uvicorn app:app --host 0.0.0.0 --port 8000
|
| 8 |
+
|
| 9 |
+
Keep HF_TOKEN on the server only. Never put it in index.html.
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
from fastapi import FastAPI, HTTPException
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from pydantic import BaseModel
|
| 15 |
+
from openai import OpenAI
|
| 16 |
+
|
| 17 |
+
endpoint = os.environ.get("HF_ENDPOINT_URL", "").rstrip("/")
|
| 18 |
+
token = os.environ.get("HF_TOKEN", "")
|
| 19 |
+
if not endpoint or not token:
|
| 20 |
+
raise RuntimeError("Set HF_ENDPOINT_URL and HF_TOKEN as server environment variables.")
|
| 21 |
+
|
| 22 |
+
client = OpenAI(base_url=endpoint + "/v1/", api_key=token)
|
| 23 |
+
app = FastAPI(title="Brainbox API")
|
| 24 |
+
|
| 25 |
+
# Replace * with your real website origin before production.
|
| 26 |
+
app.add_middleware(
|
| 27 |
+
CORSMiddleware,
|
| 28 |
+
allow_origins=["*"],
|
| 29 |
+
allow_credentials=False,
|
| 30 |
+
allow_methods=["POST"],
|
| 31 |
+
allow_headers=["*"],
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
SYSTEM_PROMPT = (
|
| 35 |
+
"You are Brainbox, a friendly and helpful AI assistant. Use simple English "
|
| 36 |
+
"and a warm Nigerian conversational style when appropriate. When a clear request "
|
| 37 |
+
"asks for a website, return a complete responsive HTML document. Be honest about "
|
| 38 |
+
"uncertainty. Never claim a frontend-only login is secure authentication."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
class ChatRequest(BaseModel):
|
| 42 |
+
message: str
|
| 43 |
+
history: list[dict] = []
|
| 44 |
+
|
| 45 |
+
@app.get("/")
|
| 46 |
+
def health():
|
| 47 |
+
return {"status": "ok", "service": "Brainbox API"}
|
| 48 |
+
|
| 49 |
+
@app.post("/api/chat")
|
| 50 |
+
def chat(body: ChatRequest):
|
| 51 |
+
message = body.message.strip()
|
| 52 |
+
if not message:
|
| 53 |
+
raise HTTPException(status_code=400, detail="Message cannot be empty.")
|
| 54 |
+
# Keep only recent, valid user/assistant messages to limit prompt size.
|
| 55 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 56 |
+
for item in body.history[-10:]:
|
| 57 |
+
role = item.get("role")
|
| 58 |
+
content = item.get("content")
|
| 59 |
+
if role in ("user", "assistant") and isinstance(content, str):
|
| 60 |
+
messages.append({"role": role, "content": content[:6000]})
|
| 61 |
+
messages.append({"role": "user", "content": message[:6000]})
|
| 62 |
+
try:
|
| 63 |
+
result = client.chat.completions.create(
|
| 64 |
+
model="tgi",
|
| 65 |
+
messages=messages,
|
| 66 |
+
temperature=0.7,
|
| 67 |
+
top_p=0.9,
|
| 68 |
+
max_tokens=1800
|
| 69 |
+
)
|
| 70 |
+
return {"reply": result.choices[0].message.content or ""}
|
| 71 |
+
except Exception as exc:
|
| 72 |
+
raise HTTPException(status_code=502, detail=f"Model request failed: {str(exc)[:300]}")
|