Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
from typing import List, Optional, Dict, Any
|
| 4 |
+
|
| 5 |
+
from fastapi import FastAPI, HTTPException
|
| 6 |
+
from pydantic import BaseModel, Field
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
# ===== Config =====
|
| 10 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 11 |
+
ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 12 |
+
|
| 13 |
+
DEFAULT_MODEL = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct")
|
| 14 |
+
|
| 15 |
+
# ===== FastAPI (OpenAI-ish) =====
|
| 16 |
+
api = FastAPI(title="My Hosted-Model Proxy (API + UI)")
|
| 17 |
+
|
| 18 |
+
class ChatMessage(BaseModel):
|
| 19 |
+
role: str
|
| 20 |
+
content: str
|
| 21 |
+
|
| 22 |
+
class ChatReq(BaseModel):
|
| 23 |
+
model: str = Field(default=DEFAULT_MODEL)
|
| 24 |
+
messages: List[ChatMessage]
|
| 25 |
+
max_tokens: int = Field(default=256, ge=1, le=2048)
|
| 26 |
+
temperature: float = Field(default=0.7, ge=0.0, le=2.0)
|
| 27 |
+
stream: bool = False
|
| 28 |
+
|
| 29 |
+
@api.get("/health")
|
| 30 |
+
def health():
|
| 31 |
+
return {"status": "ok", "model_default": DEFAULT_MODEL, "proxying": True}
|
| 32 |
+
|
| 33 |
+
@api.get("/v1/models")
|
| 34 |
+
def models():
|
| 35 |
+
return {"object": "list", "data": [{"id": DEFAULT_MODEL, "object": "model", "owned_by": "hf-router"}]}
|
| 36 |
+
|
| 37 |
+
@api.post("/v1/chat/completions")
|
| 38 |
+
def chat(req: ChatReq):
|
| 39 |
+
if not HF_TOKEN:
|
| 40 |
+
raise HTTPException(500, "HF_TOKEN missing. Add it in Space Settings → Secrets as HF_TOKEN.")
|
| 41 |
+
|
| 42 |
+
payload = req.model_dump()
|
| 43 |
+
# Convert Pydantic messages to plain dicts
|
| 44 |
+
payload["messages"] = [m.model_dump() for m in req.messages]
|
| 45 |
+
|
| 46 |
+
r = requests.post(
|
| 47 |
+
ROUTER_URL,
|
| 48 |
+
headers={
|
| 49 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 50 |
+
"Content-Type": "application/json",
|
| 51 |
+
},
|
| 52 |
+
json=payload,
|
| 53 |
+
timeout=120,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Router errors are still JSON; keep them readable
|
| 57 |
+
try:
|
| 58 |
+
out = r.json()
|
| 59 |
+
except Exception:
|
| 60 |
+
raise HTTPException(502, f"Router returned non-JSON: {r.text[:500]}")
|
| 61 |
+
|
| 62 |
+
if r.status_code >= 400:
|
| 63 |
+
raise HTTPException(r.status_code, out)
|
| 64 |
+
|
| 65 |
+
return out
|
| 66 |
+
|
| 67 |
+
# ===== Gradio UI =====
|
| 68 |
+
def ui_chat(user_message: str, history: list, model: str, temperature: float, max_tokens: int):
|
| 69 |
+
"""
|
| 70 |
+
history: list of [user, assistant] pairs from Gradio
|
| 71 |
+
"""
|
| 72 |
+
messages: List[Dict[str, str]] = []
|
| 73 |
+
# Optional system prompt to make it feel natural
|
| 74 |
+
messages.append({"role": "system", "content": "Be natural, concise, and helpful."})
|
| 75 |
+
|
| 76 |
+
for u, a in history:
|
| 77 |
+
messages.append({"role": "user", "content": u})
|
| 78 |
+
messages.append({"role": "assistant", "content": a})
|
| 79 |
+
|
| 80 |
+
messages.append({"role": "user", "content": user_message})
|
| 81 |
+
|
| 82 |
+
req = {
|
| 83 |
+
"model": model,
|
| 84 |
+
"messages": messages,
|
| 85 |
+
"temperature": float(temperature),
|
| 86 |
+
"max_tokens": int(max_tokens),
|
| 87 |
+
"stream": False,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
if not HF_TOKEN:
|
| 91 |
+
return "HF_TOKEN is missing. Add it in Space Settings → Secrets as HF_TOKEN."
|
| 92 |
+
|
| 93 |
+
r = requests.post(
|
| 94 |
+
ROUTER_URL,
|
| 95 |
+
headers={"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"},
|
| 96 |
+
json=req,
|
| 97 |
+
timeout=120,
|
| 98 |
+
)
|
| 99 |
+
data = r.json()
|
| 100 |
+
if r.status_code >= 400:
|
| 101 |
+
return f"Error: {data}"
|
| 102 |
+
|
| 103 |
+
return data["choices"][0]["message"]["content"]
|
| 104 |
+
|
| 105 |
+
with gr.Blocks(title="My AI (Hosted Model) — UI + API") as demo:
|
| 106 |
+
gr.Markdown("## 💬 Chat UI (Hosted model via HF Router)\nThis Space also exposes an **OpenAI-style API** at `/v1/chat/completions`.")
|
| 107 |
+
|
| 108 |
+
with gr.Row():
|
| 109 |
+
model_dd = gr.Textbox(value=DEFAULT_MODEL, label="Model", interactive=True)
|
| 110 |
+
with gr.Row():
|
| 111 |
+
temp = gr.Slider(0, 2, value=0.7, step=0.1, label="Temperature")
|
| 112 |
+
mx = gr.Slider(32, 1024, value=256, step=16, label="Max tokens")
|
| 113 |
+
|
| 114 |
+
gr.ChatInterface(
|
| 115 |
+
fn=lambda msg, hist: ui_chat(msg, hist, model_dd.value, temp.value, mx.value),
|
| 116 |
+
title="Chat",
|
| 117 |
+
description="Type a message. This calls the hosted model and returns the assistant response.",
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
gr.Markdown(
|
| 121 |
+
"**API endpoints:**\n"
|
| 122 |
+
"- `GET /health`\n"
|
| 123 |
+
"- `GET /v1/models`\n"
|
| 124 |
+
"- `POST /v1/chat/completions`\n"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# Mount Gradio onto FastAPI at /
|
| 128 |
+
app = gr.mount_gradio_app(api, demo, path="/")
|