Update app.py
Browse files
app.py
CHANGED
|
@@ -1,56 +1,206 @@
|
|
| 1 |
|
| 2 |
-
import
|
| 3 |
-
import torch
|
| 4 |
import time
|
| 5 |
import uuid
|
| 6 |
import json
|
|
|
|
|
|
|
| 7 |
import threading
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
from gradio import Server
|
| 10 |
from transformers import (
|
| 11 |
AutoModelForCausalLM,
|
| 12 |
AutoTokenizer,
|
| 13 |
TextIteratorStreamer
|
| 14 |
)
|
| 15 |
-
from fastapi import HTTPException
|
| 16 |
from fastapi.responses import StreamingResponse
|
| 17 |
from pydantic import BaseModel
|
| 18 |
-
from typing import Optional
|
| 19 |
|
| 20 |
-
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
print("Loading tokenizer...")
|
|
|
|
| 23 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 24 |
|
| 25 |
-
print("Loading model...")
|
|
|
|
| 26 |
model = AutoModelForCausalLM.from_pretrained(
|
| 27 |
MODEL_ID,
|
| 28 |
dtype=torch.bfloat16,
|
| 29 |
device_map="auto"
|
| 30 |
)
|
| 31 |
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
# REQUEST
|
| 39 |
-
#
|
| 40 |
|
| 41 |
class ChatRequest(BaseModel):
|
| 42 |
-
model: Optional[str] =
|
| 43 |
messages: list[dict]
|
| 44 |
temperature: Optional[float] = 0.7
|
| 45 |
max_tokens: Optional[int] = 512
|
| 46 |
stream: Optional[bool] = False
|
| 47 |
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
#
|
| 51 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
def prepare_inputs(messages: list[dict]):
|
|
|
|
|
|
|
|
|
|
| 54 |
prompt = tokenizer.apply_chat_template(
|
| 55 |
messages,
|
| 56 |
tokenize=False,
|
|
@@ -63,21 +213,21 @@ def prepare_inputs(messages: list[dict]):
|
|
| 63 |
).to(model.device)
|
| 64 |
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
#
|
| 68 |
-
#
|
| 69 |
|
| 70 |
-
@app.api(name="generate")
|
| 71 |
@spaces.GPU(duration=120)
|
| 72 |
-
def
|
| 73 |
messages: list[dict],
|
| 74 |
-
temperature: float
|
| 75 |
-
max_tokens: int
|
| 76 |
) -> dict:
|
| 77 |
|
| 78 |
inputs = prepare_inputs(messages)
|
| 79 |
|
| 80 |
with torch.inference_mode():
|
|
|
|
| 81 |
output = model.generate(
|
| 82 |
**inputs,
|
| 83 |
max_new_tokens=max_tokens,
|
|
@@ -86,29 +236,48 @@ def run_inference(
|
|
| 86 |
pad_token_id=tokenizer.eos_token_id
|
| 87 |
)
|
| 88 |
|
| 89 |
-
generated = output[0][
|
|
|
|
|
|
|
| 90 |
|
| 91 |
return {
|
| 92 |
"content": tokenizer.decode(
|
| 93 |
generated,
|
| 94 |
skip_special_tokens=True
|
| 95 |
),
|
| 96 |
-
"prompt_tokens": inputs.input_ids.shape[-1],
|
| 97 |
-
"completion_tokens": generated.shape[-1]
|
| 98 |
}
|
| 99 |
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def run_streaming(
|
| 108 |
messages: list[dict],
|
| 109 |
temperature: float = 0.7,
|
| 110 |
max_tokens: int = 512
|
| 111 |
-
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
inputs = prepare_inputs(messages)
|
| 114 |
|
|
@@ -121,9 +290,11 @@ def run_streaming(
|
|
| 121 |
|
| 122 |
errors = []
|
| 123 |
|
| 124 |
-
def
|
|
|
|
| 125 |
try:
|
| 126 |
with torch.inference_mode():
|
|
|
|
| 127 |
model.generate(
|
| 128 |
**inputs,
|
| 129 |
max_new_tokens=max_tokens,
|
|
@@ -132,12 +303,13 @@ def run_streaming(
|
|
| 132 |
pad_token_id=tokenizer.eos_token_id,
|
| 133 |
streamer=streamer
|
| 134 |
)
|
|
|
|
| 135 |
except Exception as error:
|
| 136 |
errors.append(error)
|
| 137 |
streamer.end()
|
| 138 |
|
| 139 |
worker = threading.Thread(
|
| 140 |
-
target=
|
| 141 |
daemon=True
|
| 142 |
)
|
| 143 |
|
|
@@ -153,9 +325,28 @@ def run_streaming(
|
|
| 153 |
raise errors[0]
|
| 154 |
|
| 155 |
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
# OPENAI-COMPATIBLE CHAT COMPLETIONS
|
| 158 |
-
#
|
| 159 |
|
| 160 |
@app.post("/v1/chat/completions")
|
| 161 |
async def chat_completions(request: ChatRequest):
|
|
@@ -166,16 +357,30 @@ async def chat_completions(request: ChatRequest):
|
|
| 166 |
detail="Messages cannot be empty"
|
| 167 |
)
|
| 168 |
|
| 169 |
-
if
|
| 170 |
-
m.get("role") not in ("system", "user", "assistant")
|
| 171 |
-
or not isinstance(m.get("content"), str)
|
| 172 |
-
for m in request.messages
|
| 173 |
-
):
|
| 174 |
raise HTTPException(
|
| 175 |
-
status_code=
|
| 176 |
-
detail="
|
| 177 |
)
|
| 178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
temperature = min(
|
| 180 |
max(
|
| 181 |
request.temperature
|
|
@@ -195,7 +400,7 @@ async def chat_completions(request: ChatRequest):
|
|
| 195 |
)
|
| 196 |
|
| 197 |
# ----------------------------------------------
|
| 198 |
-
#
|
| 199 |
# ----------------------------------------------
|
| 200 |
|
| 201 |
if request.stream:
|
|
@@ -203,7 +408,8 @@ async def chat_completions(request: ChatRequest):
|
|
| 203 |
completion_id = "chatcmpl-" + uuid.uuid4().hex
|
| 204 |
created = int(time.time())
|
| 205 |
|
| 206 |
-
def
|
|
|
|
| 207 |
return (
|
| 208 |
"data: "
|
| 209 |
+ json.dumps(data, ensure_ascii=False)
|
|
@@ -212,12 +418,11 @@ async def chat_completions(request: ChatRequest):
|
|
| 212 |
|
| 213 |
def stream_response():
|
| 214 |
|
| 215 |
-
|
| 216 |
-
yield event({
|
| 217 |
"id": completion_id,
|
| 218 |
"object": "chat.completion.chunk",
|
| 219 |
"created": created,
|
| 220 |
-
"model":
|
| 221 |
"choices": [{
|
| 222 |
"index": 0,
|
| 223 |
"delta": {
|
|
@@ -227,38 +432,48 @@ async def chat_completions(request: ChatRequest):
|
|
| 227 |
}]
|
| 228 |
})
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
"id": completion_id,
|
| 238 |
"object": "chat.completion.chunk",
|
| 239 |
"created": created,
|
| 240 |
-
"model":
|
| 241 |
"choices": [{
|
| 242 |
"index": 0,
|
| 243 |
-
"delta": {
|
| 244 |
-
|
| 245 |
-
},
|
| 246 |
-
"finish_reason": None
|
| 247 |
}]
|
| 248 |
})
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
"delta": {},
|
| 259 |
-
"finish_reason": "stop"
|
| 260 |
-
}]
|
| 261 |
-
})
|
| 262 |
|
| 263 |
yield "data: [DONE]\n\n"
|
| 264 |
|
|
@@ -273,10 +488,10 @@ async def chat_completions(request: ChatRequest):
|
|
| 273 |
)
|
| 274 |
|
| 275 |
# ----------------------------------------------
|
| 276 |
-
# NORMAL
|
| 277 |
# ----------------------------------------------
|
| 278 |
|
| 279 |
-
result =
|
| 280 |
request.messages,
|
| 281 |
temperature,
|
| 282 |
max_tokens
|
|
@@ -289,7 +504,7 @@ async def chat_completions(request: ChatRequest):
|
|
| 289 |
"id": "chatcmpl-" + uuid.uuid4().hex,
|
| 290 |
"object": "chat.completion",
|
| 291 |
"created": int(time.time()),
|
| 292 |
-
"model":
|
| 293 |
"choices": [{
|
| 294 |
"index": 0,
|
| 295 |
"message": {
|
|
@@ -308,39 +523,43 @@ async def chat_completions(request: ChatRequest):
|
|
| 308 |
}
|
| 309 |
|
| 310 |
|
| 311 |
-
#
|
| 312 |
-
# HEALTH CHECK
|
| 313 |
-
# --------------------------------------------------
|
| 314 |
-
|
| 315 |
-
@app.get("/")
|
| 316 |
-
def home():
|
| 317 |
-
return {
|
| 318 |
-
"status": "online",
|
| 319 |
-
"model": MODEL_ID,
|
| 320 |
-
"api": "/v1/chat/completions",
|
| 321 |
-
"streaming": True
|
| 322 |
-
}
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
# --------------------------------------------------
|
| 326 |
# MODEL LIST
|
| 327 |
-
#
|
| 328 |
|
| 329 |
@app.get("/v1/models")
|
| 330 |
def models():
|
|
|
|
| 331 |
return {
|
| 332 |
"object": "list",
|
| 333 |
"data": [{
|
| 334 |
-
"id":
|
| 335 |
"object": "model",
|
| 336 |
-
"owned_by": "
|
| 337 |
}]
|
| 338 |
}
|
| 339 |
|
| 340 |
|
| 341 |
-
#
|
| 342 |
-
#
|
| 343 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
if __name__ == "__main__":
|
| 346 |
app.launch()
|
|
|
|
| 1 |
|
| 2 |
+
import os
|
|
|
|
| 3 |
import time
|
| 4 |
import uuid
|
| 5 |
import json
|
| 6 |
+
import torch
|
| 7 |
+
import secrets
|
| 8 |
import threading
|
| 9 |
|
| 10 |
+
import spaces
|
| 11 |
+
|
| 12 |
+
from typing import Optional, Iterator
|
| 13 |
from gradio import Server
|
| 14 |
from transformers import (
|
| 15 |
AutoModelForCausalLM,
|
| 16 |
AutoTokenizer,
|
| 17 |
TextIteratorStreamer
|
| 18 |
)
|
| 19 |
+
from fastapi import Depends, Header, HTTPException
|
| 20 |
from fastapi.responses import StreamingResponse
|
| 21 |
from pydantic import BaseModel
|
|
|
|
| 22 |
|
|
|
|
| 23 |
|
| 24 |
+
# ==================================================
|
| 25 |
+
# NOVA AI CONFIGURATION
|
| 26 |
+
# ==================================================
|
| 27 |
+
|
| 28 |
+
MODEL_ID = os.getenv(
|
| 29 |
+
"MODEL_ID",
|
| 30 |
+
"Qwen/Qwen2.5-3B-Instruct"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
PUBLIC_MODEL_NAME = "nova-ai"
|
| 34 |
+
|
| 35 |
+
NOVA_SYSTEM_PROMPT = """
|
| 36 |
+
You are Nova AI, an intelligent AI assistant developed
|
| 37 |
+
and operated by the Nova AI project.
|
| 38 |
+
|
| 39 |
+
IDENTITY:
|
| 40 |
+
- Your name is Nova AI.
|
| 41 |
+
- You are the AI assistant behind the Nova AI API.
|
| 42 |
+
- Do not identify yourself as ChatGPT or another AI brand.
|
| 43 |
+
- If asked about your underlying architecture, be honest.
|
| 44 |
+
- Do not invent information about your creators.
|
| 45 |
+
|
| 46 |
+
PERSONALITY:
|
| 47 |
+
- Friendly, intelligent and conversational.
|
| 48 |
+
- Clear, accurate and helpful.
|
| 49 |
+
- Excellent at coding, reasoning and problem solving.
|
| 50 |
+
- Explain complicated things in understandable language.
|
| 51 |
+
- Be honest about uncertainty and limitations.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ==================================================
|
| 56 |
+
# API KEY AUTHENTICATION
|
| 57 |
+
# ==================================================
|
| 58 |
+
|
| 59 |
+
# Add one or more keys in Hugging Face Space Secrets.
|
| 60 |
+
# NOVA_API_KEY=nv_your_secret
|
| 61 |
+
# NOVA_API_KEYS=nv_key1,nv_key2
|
| 62 |
+
|
| 63 |
+
configured_keys = []
|
| 64 |
+
|
| 65 |
+
single_key = os.getenv("NOVA_API_KEY", "").strip()
|
| 66 |
+
multiple_keys = os.getenv("NOVA_API_KEYS", "").strip()
|
| 67 |
+
|
| 68 |
+
if single_key:
|
| 69 |
+
configured_keys.append(single_key)
|
| 70 |
+
|
| 71 |
+
if multiple_keys:
|
| 72 |
+
configured_keys.extend(
|
| 73 |
+
key.strip()
|
| 74 |
+
for key in multiple_keys.split(",")
|
| 75 |
+
if key.strip()
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
VALID_API_KEYS = list(set(configured_keys))
|
| 79 |
+
|
| 80 |
+
if not VALID_API_KEYS:
|
| 81 |
+
raise RuntimeError(
|
| 82 |
+
"Missing NOVA_API_KEY or NOVA_API_KEYS Space Secret!"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
async def authenticate(
|
| 87 |
+
authorization: Optional[str] = Header(default=None)
|
| 88 |
+
):
|
| 89 |
+
if not authorization or not authorization.startswith("Bearer "):
|
| 90 |
+
raise HTTPException(
|
| 91 |
+
status_code=401,
|
| 92 |
+
detail="Nova AI API key required",
|
| 93 |
+
headers={"WWW-Authenticate": "Bearer"}
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
supplied_key = authorization[7:].strip()
|
| 97 |
+
|
| 98 |
+
if not supplied_key.startswith("nv_"):
|
| 99 |
+
raise HTTPException(
|
| 100 |
+
status_code=401,
|
| 101 |
+
detail="Invalid Nova AI API key format"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
valid = any(
|
| 105 |
+
secrets.compare_digest(supplied_key, key)
|
| 106 |
+
for key in VALID_API_KEYS
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
if not valid:
|
| 110 |
+
raise HTTPException(
|
| 111 |
+
status_code=401,
|
| 112 |
+
detail="Invalid Nova AI API key"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
return True
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ==================================================
|
| 119 |
+
# LOAD MODEL
|
| 120 |
+
# ==================================================
|
| 121 |
+
|
| 122 |
+
print("Starting Nova AI...")
|
| 123 |
print("Loading tokenizer...")
|
| 124 |
+
|
| 125 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 126 |
|
| 127 |
+
print("Loading language model...")
|
| 128 |
+
|
| 129 |
model = AutoModelForCausalLM.from_pretrained(
|
| 130 |
MODEL_ID,
|
| 131 |
dtype=torch.bfloat16,
|
| 132 |
device_map="auto"
|
| 133 |
)
|
| 134 |
|
| 135 |
+
model.eval()
|
| 136 |
+
|
| 137 |
+
print("Nova AI model loaded!")
|
| 138 |
+
|
| 139 |
|
| 140 |
+
# ==================================================
|
| 141 |
+
# GRADIO SERVER
|
| 142 |
+
# ==================================================
|
| 143 |
+
|
| 144 |
+
app = Server(
|
| 145 |
+
title="Nova AI",
|
| 146 |
+
summary="Nova AI OpenAI-compatible API",
|
| 147 |
+
description="Custom Nova AI language model API.",
|
| 148 |
+
version="1.0.0",
|
| 149 |
+
dependencies=[Depends(authenticate)]
|
| 150 |
+
)
|
| 151 |
|
| 152 |
|
| 153 |
+
# ==================================================
|
| 154 |
+
# REQUEST MODEL
|
| 155 |
+
# ==================================================
|
| 156 |
|
| 157 |
class ChatRequest(BaseModel):
|
| 158 |
+
model: Optional[str] = "nova-ai"
|
| 159 |
messages: list[dict]
|
| 160 |
temperature: Optional[float] = 0.7
|
| 161 |
max_tokens: Optional[int] = 512
|
| 162 |
stream: Optional[bool] = False
|
| 163 |
|
| 164 |
|
| 165 |
+
# ==================================================
|
| 166 |
+
# MESSAGE PREPARATION
|
| 167 |
+
# ==================================================
|
| 168 |
+
|
| 169 |
+
def prepare_messages(messages: list[dict]):
|
| 170 |
+
|
| 171 |
+
messages = [dict(message) for message in messages]
|
| 172 |
+
|
| 173 |
+
system_message = next(
|
| 174 |
+
(
|
| 175 |
+
message
|
| 176 |
+
for message in messages
|
| 177 |
+
if message.get("role") == "system"
|
| 178 |
+
),
|
| 179 |
+
None
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if system_message:
|
| 183 |
+
system_message["content"] = (
|
| 184 |
+
NOVA_SYSTEM_PROMPT
|
| 185 |
+
+ "\n\nAdditional instructions:\n"
|
| 186 |
+
+ system_message["content"]
|
| 187 |
+
)
|
| 188 |
+
else:
|
| 189 |
+
messages.insert(
|
| 190 |
+
0,
|
| 191 |
+
{
|
| 192 |
+
"role": "system",
|
| 193 |
+
"content": NOVA_SYSTEM_PROMPT
|
| 194 |
+
}
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
return messages
|
| 198 |
+
|
| 199 |
|
| 200 |
def prepare_inputs(messages: list[dict]):
|
| 201 |
+
|
| 202 |
+
messages = prepare_messages(messages)
|
| 203 |
+
|
| 204 |
prompt = tokenizer.apply_chat_template(
|
| 205 |
messages,
|
| 206 |
tokenize=False,
|
|
|
|
| 213 |
).to(model.device)
|
| 214 |
|
| 215 |
|
| 216 |
+
# ==================================================
|
| 217 |
+
# GPU INFERENCE - NORMAL
|
| 218 |
+
# ==================================================
|
| 219 |
|
|
|
|
| 220 |
@spaces.GPU(duration=120)
|
| 221 |
+
def gpu_generate(
|
| 222 |
messages: list[dict],
|
| 223 |
+
temperature: float,
|
| 224 |
+
max_tokens: int
|
| 225 |
) -> dict:
|
| 226 |
|
| 227 |
inputs = prepare_inputs(messages)
|
| 228 |
|
| 229 |
with torch.inference_mode():
|
| 230 |
+
|
| 231 |
output = model.generate(
|
| 232 |
**inputs,
|
| 233 |
max_new_tokens=max_tokens,
|
|
|
|
| 236 |
pad_token_id=tokenizer.eos_token_id
|
| 237 |
)
|
| 238 |
|
| 239 |
+
generated = output[0][
|
| 240 |
+
inputs.input_ids.shape[-1]:
|
| 241 |
+
]
|
| 242 |
|
| 243 |
return {
|
| 244 |
"content": tokenizer.decode(
|
| 245 |
generated,
|
| 246 |
skip_special_tokens=True
|
| 247 |
),
|
| 248 |
+
"prompt_tokens": int(inputs.input_ids.shape[-1]),
|
| 249 |
+
"completion_tokens": int(generated.shape[-1])
|
| 250 |
}
|
| 251 |
|
| 252 |
|
| 253 |
+
@app.api(
|
| 254 |
+
name="generate",
|
| 255 |
+
concurrency_limit=1,
|
| 256 |
+
time_limit=120
|
| 257 |
+
)
|
| 258 |
+
def generate(
|
|
|
|
| 259 |
messages: list[dict],
|
| 260 |
temperature: float = 0.7,
|
| 261 |
max_tokens: int = 512
|
| 262 |
+
) -> dict:
|
| 263 |
+
|
| 264 |
+
return gpu_generate(
|
| 265 |
+
messages,
|
| 266 |
+
temperature,
|
| 267 |
+
max_tokens
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# ==================================================
|
| 272 |
+
# GPU INFERENCE - STREAMING
|
| 273 |
+
# ==================================================
|
| 274 |
+
|
| 275 |
+
@spaces.GPU(duration=120)
|
| 276 |
+
def gpu_generate_stream(
|
| 277 |
+
messages: list[dict],
|
| 278 |
+
temperature: float,
|
| 279 |
+
max_tokens: int
|
| 280 |
+
) -> Iterator[str]:
|
| 281 |
|
| 282 |
inputs = prepare_inputs(messages)
|
| 283 |
|
|
|
|
| 290 |
|
| 291 |
errors = []
|
| 292 |
|
| 293 |
+
def generation_worker():
|
| 294 |
+
|
| 295 |
try:
|
| 296 |
with torch.inference_mode():
|
| 297 |
+
|
| 298 |
model.generate(
|
| 299 |
**inputs,
|
| 300 |
max_new_tokens=max_tokens,
|
|
|
|
| 303 |
pad_token_id=tokenizer.eos_token_id,
|
| 304 |
streamer=streamer
|
| 305 |
)
|
| 306 |
+
|
| 307 |
except Exception as error:
|
| 308 |
errors.append(error)
|
| 309 |
streamer.end()
|
| 310 |
|
| 311 |
worker = threading.Thread(
|
| 312 |
+
target=generation_worker,
|
| 313 |
daemon=True
|
| 314 |
)
|
| 315 |
|
|
|
|
| 325 |
raise errors[0]
|
| 326 |
|
| 327 |
|
| 328 |
+
@app.api(
|
| 329 |
+
name="generate_stream",
|
| 330 |
+
concurrency_limit=1,
|
| 331 |
+
time_limit=120,
|
| 332 |
+
stream_every=0.05
|
| 333 |
+
)
|
| 334 |
+
def generate_stream(
|
| 335 |
+
messages: list[dict],
|
| 336 |
+
temperature: float = 0.7,
|
| 337 |
+
max_tokens: int = 512
|
| 338 |
+
) -> Iterator[str]:
|
| 339 |
+
|
| 340 |
+
yield from gpu_generate_stream(
|
| 341 |
+
messages,
|
| 342 |
+
temperature,
|
| 343 |
+
max_tokens
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# ==================================================
|
| 348 |
# OPENAI-COMPATIBLE CHAT COMPLETIONS
|
| 349 |
+
# ==================================================
|
| 350 |
|
| 351 |
@app.post("/v1/chat/completions")
|
| 352 |
async def chat_completions(request: ChatRequest):
|
|
|
|
| 357 |
detail="Messages cannot be empty"
|
| 358 |
)
|
| 359 |
|
| 360 |
+
if request.model not in (PUBLIC_MODEL_NAME, MODEL_ID):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
raise HTTPException(
|
| 362 |
+
status_code=404,
|
| 363 |
+
detail="Model not found"
|
| 364 |
)
|
| 365 |
|
| 366 |
+
for message in request.messages:
|
| 367 |
+
|
| 368 |
+
if message.get("role") not in (
|
| 369 |
+
"system",
|
| 370 |
+
"user",
|
| 371 |
+
"assistant"
|
| 372 |
+
):
|
| 373 |
+
raise HTTPException(
|
| 374 |
+
status_code=400,
|
| 375 |
+
detail="Invalid message role"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
if not isinstance(message.get("content"), str):
|
| 379 |
+
raise HTTPException(
|
| 380 |
+
status_code=400,
|
| 381 |
+
detail="Message content must be a string"
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
temperature = min(
|
| 385 |
max(
|
| 386 |
request.temperature
|
|
|
|
| 400 |
)
|
| 401 |
|
| 402 |
# ----------------------------------------------
|
| 403 |
+
# STREAMING RESPONSE
|
| 404 |
# ----------------------------------------------
|
| 405 |
|
| 406 |
if request.stream:
|
|
|
|
| 408 |
completion_id = "chatcmpl-" + uuid.uuid4().hex
|
| 409 |
created = int(time.time())
|
| 410 |
|
| 411 |
+
def make_event(data):
|
| 412 |
+
|
| 413 |
return (
|
| 414 |
"data: "
|
| 415 |
+ json.dumps(data, ensure_ascii=False)
|
|
|
|
| 418 |
|
| 419 |
def stream_response():
|
| 420 |
|
| 421 |
+
yield make_event({
|
|
|
|
| 422 |
"id": completion_id,
|
| 423 |
"object": "chat.completion.chunk",
|
| 424 |
"created": created,
|
| 425 |
+
"model": PUBLIC_MODEL_NAME,
|
| 426 |
"choices": [{
|
| 427 |
"index": 0,
|
| 428 |
"delta": {
|
|
|
|
| 432 |
}]
|
| 433 |
})
|
| 434 |
|
| 435 |
+
try:
|
| 436 |
+
|
| 437 |
+
for token in generate_stream(
|
| 438 |
+
request.messages,
|
| 439 |
+
temperature,
|
| 440 |
+
max_tokens
|
| 441 |
+
):
|
| 442 |
+
|
| 443 |
+
yield make_event({
|
| 444 |
+
"id": completion_id,
|
| 445 |
+
"object": "chat.completion.chunk",
|
| 446 |
+
"created": created,
|
| 447 |
+
"model": PUBLIC_MODEL_NAME,
|
| 448 |
+
"choices": [{
|
| 449 |
+
"index": 0,
|
| 450 |
+
"delta": {
|
| 451 |
+
"content": token
|
| 452 |
+
},
|
| 453 |
+
"finish_reason": None
|
| 454 |
+
}]
|
| 455 |
+
})
|
| 456 |
+
|
| 457 |
+
yield make_event({
|
| 458 |
"id": completion_id,
|
| 459 |
"object": "chat.completion.chunk",
|
| 460 |
"created": created,
|
| 461 |
+
"model": PUBLIC_MODEL_NAME,
|
| 462 |
"choices": [{
|
| 463 |
"index": 0,
|
| 464 |
+
"delta": {},
|
| 465 |
+
"finish_reason": "stop"
|
|
|
|
|
|
|
| 466 |
}]
|
| 467 |
})
|
| 468 |
|
| 469 |
+
except Exception as error:
|
| 470 |
+
|
| 471 |
+
yield make_event({
|
| 472 |
+
"error": {
|
| 473 |
+
"message": str(error),
|
| 474 |
+
"type": "server_error"
|
| 475 |
+
}
|
| 476 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
|
| 478 |
yield "data: [DONE]\n\n"
|
| 479 |
|
|
|
|
| 488 |
)
|
| 489 |
|
| 490 |
# ----------------------------------------------
|
| 491 |
+
# NORMAL RESPONSE
|
| 492 |
# ----------------------------------------------
|
| 493 |
|
| 494 |
+
result = generate(
|
| 495 |
request.messages,
|
| 496 |
temperature,
|
| 497 |
max_tokens
|
|
|
|
| 504 |
"id": "chatcmpl-" + uuid.uuid4().hex,
|
| 505 |
"object": "chat.completion",
|
| 506 |
"created": int(time.time()),
|
| 507 |
+
"model": PUBLIC_MODEL_NAME,
|
| 508 |
"choices": [{
|
| 509 |
"index": 0,
|
| 510 |
"message": {
|
|
|
|
| 523 |
}
|
| 524 |
|
| 525 |
|
| 526 |
+
# ==================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 527 |
# MODEL LIST
|
| 528 |
+
# ==================================================
|
| 529 |
|
| 530 |
@app.get("/v1/models")
|
| 531 |
def models():
|
| 532 |
+
|
| 533 |
return {
|
| 534 |
"object": "list",
|
| 535 |
"data": [{
|
| 536 |
+
"id": PUBLIC_MODEL_NAME,
|
| 537 |
"object": "model",
|
| 538 |
+
"owned_by": "nova-ai"
|
| 539 |
}]
|
| 540 |
}
|
| 541 |
|
| 542 |
|
| 543 |
+
# ==================================================
|
| 544 |
+
# ROOT / HEALTH
|
| 545 |
+
# ==================================================
|
| 546 |
+
|
| 547 |
+
@app.get("/")
|
| 548 |
+
def home():
|
| 549 |
+
|
| 550 |
+
return {
|
| 551 |
+
"name": "Nova AI",
|
| 552 |
+
"status": "online",
|
| 553 |
+
"model": PUBLIC_MODEL_NAME,
|
| 554 |
+
"api": "/v1/chat/completions",
|
| 555 |
+
"streaming": True,
|
| 556 |
+
"authentication": "Bearer API Key"
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
# ==================================================
|
| 561 |
+
# START
|
| 562 |
+
# ==================================================
|
| 563 |
|
| 564 |
if __name__ == "__main__":
|
| 565 |
app.launch()
|