Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
from fastapi import FastAPI, HTTPException
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from pydantic import BaseModel
|
| 7 |
+
from typing import List, Optional
|
| 8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
+
|
| 10 |
+
MODEL_ID = "ApolloAIs/phoebus-3.1-1.5b-merged"
|
| 11 |
+
|
| 12 |
+
# Load model on CPU (Free Tier)
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 14 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 15 |
+
MODEL_ID,
|
| 16 |
+
torch_dtype=torch.float32,
|
| 17 |
+
device_map="cpu"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
app = FastAPI()
|
| 21 |
+
|
| 22 |
+
app.add_middleware(
|
| 23 |
+
CORSMiddleware,
|
| 24 |
+
allow_origins=["*"],
|
| 25 |
+
allow_credentials=True,
|
| 26 |
+
allow_methods=["*"],
|
| 27 |
+
allow_headers=["*"],
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
class Message(BaseModel):
|
| 31 |
+
role: str
|
| 32 |
+
content: str
|
| 33 |
+
|
| 34 |
+
class ChatRequest(BaseModel):
|
| 35 |
+
messages: List[Message]
|
| 36 |
+
temperature: Optional[float] = 0.7
|
| 37 |
+
max_tokens: Optional[int] = 256
|
| 38 |
+
|
| 39 |
+
def format_emem_cell64(claim: str) -> str:
|
| 40 |
+
encoded = base64.b64encode(claim.encode("utf-8")).decode("utf-8")[:12]
|
| 41 |
+
return f"emem:fact:cell64_{encoded}"
|
| 42 |
+
|
| 43 |
+
@app.get("/status")
|
| 44 |
+
def status():
|
| 45 |
+
return {"status": "online", "model": "Phoebus 3.1"}
|
| 46 |
+
|
| 47 |
+
@app.post("/v1/chat/completions")
|
| 48 |
+
def chat_api(req: ChatRequest):
|
| 49 |
+
try:
|
| 50 |
+
user_msg = req.messages[-1].content
|
| 51 |
+
context = ""
|
| 52 |
+
|
| 53 |
+
if "search" in user_msg.lower():
|
| 54 |
+
context += "\n\n[TinyFish]: Telemetry and spatial validation indexed."
|
| 55 |
+
|
| 56 |
+
if "location" in user_msg.lower() or "coordinates" in user_msg.lower():
|
| 57 |
+
receipt = format_emem_cell64(user_msg)
|
| 58 |
+
context += f"\n\n[Vortx emem]: Attach spatial receipt `{receipt}`."
|
| 59 |
+
|
| 60 |
+
formatted_messages = [m.model_dump() for m in req.messages]
|
| 61 |
+
if context:
|
| 62 |
+
formatted_messages[-1]["content"] += context
|
| 63 |
+
|
| 64 |
+
prompt = tokenizer.apply_chat_template(
|
| 65 |
+
formatted_messages,
|
| 66 |
+
tokenize=False,
|
| 67 |
+
add_generation_prompt=True
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
outputs = model.generate(
|
| 73 |
+
**inputs,
|
| 74 |
+
max_new_tokens=req.max_tokens,
|
| 75 |
+
temperature=req.temperature,
|
| 76 |
+
do_sample=True,
|
| 77 |
+
pad_token_id=tokenizer.eos_token_id
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
reply = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
|
| 81 |
+
return {"choices": [{"message": {"role": "assistant", "content": reply}}]}
|
| 82 |
+
except Exception as e:
|
| 83 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 84 |
+
|
| 85 |
+
# Mount FastAPI inside Gradio
|
| 86 |
+
def gradio_chat(user_message, history):
|
| 87 |
+
req = ChatRequest(messages=[{"role": "user", "content": user_message}])
|
| 88 |
+
res = chat_api(req)
|
| 89 |
+
return res["choices"][0]["message"]["content"]
|
| 90 |
+
|
| 91 |
+
demo = gr.ChatInterface(fn=gradio_chat, title="Phoebus 3.1 API Engine")
|
| 92 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|