Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import subprocess
|
|
| 4 |
import re
|
| 5 |
|
| 6 |
# =============================================================
|
| 7 |
-
# 1. Bootstrap
|
| 8 |
# =============================================================
|
| 9 |
def bootstrap_llama_cpp():
|
| 10 |
print("Bootstrapping llama-cpp-python...")
|
|
@@ -42,9 +42,9 @@ except (ImportError, RuntimeError, OSError):
|
|
| 42 |
from llama_cpp import Llama
|
| 43 |
|
| 44 |
import spaces
|
| 45 |
-
from typing import List, Literal, Optional
|
| 46 |
from pydantic import BaseModel, Field
|
| 47 |
-
from fastapi import HTTPException, Header
|
| 48 |
import gradio as gr
|
| 49 |
|
| 50 |
# =============================================================
|
|
@@ -69,14 +69,11 @@ SYSTEM_PROMPT = (
|
|
| 69 |
"earnings, and low traffic delays."
|
| 70 |
)
|
| 71 |
|
| 72 |
-
# =============================================================
|
| 73 |
-
# 3. Core ZeroGPU Inference function
|
| 74 |
-
# =============================================================
|
| 75 |
@spaces.GPU
|
| 76 |
-
def
|
| 77 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 78 |
-
if
|
| 79 |
-
for m in
|
| 80 |
messages.append({"role": m["role"], "content": m["content"]})
|
| 81 |
messages.append({"role": "user", "content": prompt})
|
| 82 |
response = llm.create_chat_completion(
|
|
@@ -85,7 +82,7 @@ def generate_response(prompt: str, history_messages: list = None) -> str:
|
|
| 85 |
return response["choices"][0]["message"]["content"]
|
| 86 |
|
| 87 |
# =============================================================
|
| 88 |
-
#
|
| 89 |
# =============================================================
|
| 90 |
@spaces.GPU
|
| 91 |
def gradio_chat(user_message, history):
|
|
@@ -95,7 +92,7 @@ def gradio_chat(user_message, history):
|
|
| 95 |
hist_formatted.append({"role": "user", "content": user_msg})
|
| 96 |
if bot_msg:
|
| 97 |
hist_formatted.append({"role": "assistant", "content": bot_msg})
|
| 98 |
-
return
|
| 99 |
|
| 100 |
demo = gr.ChatInterface(
|
| 101 |
fn=gradio_chat,
|
|
@@ -104,7 +101,7 @@ demo = gr.ChatInterface(
|
|
| 104 |
)
|
| 105 |
|
| 106 |
# =============================================================
|
| 107 |
-
#
|
| 108 |
# =============================================================
|
| 109 |
class HistoryMessage(BaseModel):
|
| 110 |
role: Literal["user", "assistant"]
|
|
@@ -113,15 +110,15 @@ class HistoryMessage(BaseModel):
|
|
| 113 |
class ChatRequest(BaseModel):
|
| 114 |
driver_id: Optional[str] = "DRV_DEFAULT"
|
| 115 |
driver_prompt: str = Field(min_length=1, max_length=2000)
|
|
|
|
| 116 |
current_zone_id: Optional[str] = None
|
| 117 |
history: List[HistoryMessage] = Field(default_factory=list)
|
| 118 |
|
| 119 |
-
|
| 120 |
-
def chat_endpoint(payload: ChatRequest, request: Request, x_api_key: Optional[str] = Header(None)):
|
| 121 |
if API_KEY and x_api_key != API_KEY:
|
| 122 |
raise HTTPException(status_code=401, detail="Unauthorized: Invalid API Key")
|
| 123 |
formatted_history = [{"role": m.role, "content": m.content} for m in payload.history]
|
| 124 |
-
answer =
|
| 125 |
return {
|
| 126 |
"status": "success",
|
| 127 |
"answer": answer,
|
|
@@ -129,8 +126,11 @@ def chat_endpoint(payload: ChatRequest, request: Request, x_api_key: Optional[st
|
|
| 129 |
"zone_context": payload.current_zone_id
|
| 130 |
}
|
| 131 |
|
|
|
|
|
|
|
|
|
|
| 132 |
# =============================================================
|
| 133 |
-
#
|
| 134 |
# =============================================================
|
| 135 |
if __name__ == "__main__":
|
| 136 |
demo.launch()
|
|
|
|
| 4 |
import re
|
| 5 |
|
| 6 |
# =============================================================
|
| 7 |
+
# 1. Bootstrap prebuilt llama-cpp-python
|
| 8 |
# =============================================================
|
| 9 |
def bootstrap_llama_cpp():
|
| 10 |
print("Bootstrapping llama-cpp-python...")
|
|
|
|
| 42 |
from llama_cpp import Llama
|
| 43 |
|
| 44 |
import spaces
|
| 45 |
+
from typing import List, Literal, Optional, Any
|
| 46 |
from pydantic import BaseModel, Field
|
| 47 |
+
from fastapi import HTTPException, Header
|
| 48 |
import gradio as gr
|
| 49 |
|
| 50 |
# =============================================================
|
|
|
|
| 69 |
"earnings, and low traffic delays."
|
| 70 |
)
|
| 71 |
|
|
|
|
|
|
|
|
|
|
| 72 |
@spaces.GPU
|
| 73 |
+
def run_inference(prompt: str, history: List[dict] = None) -> str:
|
| 74 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 75 |
+
if history:
|
| 76 |
+
for m in history:
|
| 77 |
messages.append({"role": m["role"], "content": m["content"]})
|
| 78 |
messages.append({"role": "user", "content": prompt})
|
| 79 |
response = llm.create_chat_completion(
|
|
|
|
| 82 |
return response["choices"][0]["message"]["content"]
|
| 83 |
|
| 84 |
# =============================================================
|
| 85 |
+
# 3. Gradio Interface (Satisfies ZeroGPU startup check)
|
| 86 |
# =============================================================
|
| 87 |
@spaces.GPU
|
| 88 |
def gradio_chat(user_message, history):
|
|
|
|
| 92 |
hist_formatted.append({"role": "user", "content": user_msg})
|
| 93 |
if bot_msg:
|
| 94 |
hist_formatted.append({"role": "assistant", "content": bot_msg})
|
| 95 |
+
return run_inference(user_message, hist_formatted)
|
| 96 |
|
| 97 |
demo = gr.ChatInterface(
|
| 98 |
fn=gradio_chat,
|
|
|
|
| 101 |
)
|
| 102 |
|
| 103 |
# =============================================================
|
| 104 |
+
# 4. Custom API Schemas (Matching CommitCon/src/phase5_api.py)
|
| 105 |
# =============================================================
|
| 106 |
class HistoryMessage(BaseModel):
|
| 107 |
role: Literal["user", "assistant"]
|
|
|
|
| 110 |
class ChatRequest(BaseModel):
|
| 111 |
driver_id: Optional[str] = "DRV_DEFAULT"
|
| 112 |
driver_prompt: str = Field(min_length=1, max_length=2000)
|
| 113 |
+
recommendation_data: Optional[dict[str, Any]] = None
|
| 114 |
current_zone_id: Optional[str] = None
|
| 115 |
history: List[HistoryMessage] = Field(default_factory=list)
|
| 116 |
|
| 117 |
+
def chat_endpoint(payload: ChatRequest, x_api_key: Optional[str] = Header(None, alias="X-API-Key")):
|
|
|
|
| 118 |
if API_KEY and x_api_key != API_KEY:
|
| 119 |
raise HTTPException(status_code=401, detail="Unauthorized: Invalid API Key")
|
| 120 |
formatted_history = [{"role": m.role, "content": m.content} for m in payload.history]
|
| 121 |
+
answer = run_inference(payload.driver_prompt, formatted_history)
|
| 122 |
return {
|
| 123 |
"status": "success",
|
| 124 |
"answer": answer,
|
|
|
|
| 126 |
"zone_context": payload.current_zone_id
|
| 127 |
}
|
| 128 |
|
| 129 |
+
# Register the POST /chat route directly into Gradio's underlying FastAPI router
|
| 130 |
+
demo.app.add_api_route("/chat", chat_endpoint, methods=["POST"])
|
| 131 |
+
|
| 132 |
# =============================================================
|
| 133 |
+
# 5. Native ZeroGPU Launch
|
| 134 |
# =============================================================
|
| 135 |
if __name__ == "__main__":
|
| 136 |
demo.launch()
|