Update app.py
Browse files
app.py
CHANGED
|
@@ -7,7 +7,11 @@ import json
|
|
| 7 |
import threading
|
| 8 |
|
| 9 |
from gradio import Server
|
| 10 |
-
from transformers import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from fastapi import HTTPException
|
| 12 |
from fastapi.responses import StreamingResponse
|
| 13 |
from pydantic import BaseModel
|
|
@@ -30,6 +34,10 @@ print("Model loaded!")
|
|
| 30 |
app = Server(title="MyAPI")
|
| 31 |
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
class ChatRequest(BaseModel):
|
| 34 |
model: Optional[str] = MODEL_ID
|
| 35 |
messages: list[dict]
|
|
@@ -38,7 +46,11 @@ class ChatRequest(BaseModel):
|
|
| 38 |
stream: Optional[bool] = False
|
| 39 |
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
prompt = tokenizer.apply_chat_template(
|
| 43 |
messages,
|
| 44 |
tokenize=False,
|
|
@@ -51,10 +63,17 @@ def prepare_inputs(messages):
|
|
| 51 |
).to(model.device)
|
| 52 |
|
| 53 |
|
| 54 |
-
#
|
|
|
|
|
|
|
|
|
|
| 55 |
@app.api(name="generate")
|
| 56 |
@spaces.GPU(duration=120)
|
| 57 |
-
def run_inference(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
inputs = prepare_inputs(messages)
|
| 60 |
|
|
@@ -79,10 +98,17 @@ def run_inference(messages, temperature=0.7, max_tokens=512):
|
|
| 79 |
}
|
| 80 |
|
| 81 |
|
| 82 |
-
#
|
|
|
|
|
|
|
|
|
|
| 83 |
@app.api(name="generate_stream", stream_every=0.05)
|
| 84 |
@spaces.GPU(duration=120)
|
| 85 |
-
def run_streaming(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
inputs = prepare_inputs(messages)
|
| 88 |
|
|
@@ -114,6 +140,7 @@ def run_streaming(messages, temperature=0.7, max_tokens=512):
|
|
| 114 |
target=generate_in_thread,
|
| 115 |
daemon=True
|
| 116 |
)
|
|
|
|
| 117 |
worker.start()
|
| 118 |
|
| 119 |
for text in streamer:
|
|
@@ -126,41 +153,66 @@ def run_streaming(messages, temperature=0.7, max_tokens=512):
|
|
| 126 |
raise errors[0]
|
| 127 |
|
| 128 |
|
| 129 |
-
#
|
|
|
|
|
|
|
|
|
|
| 130 |
@app.post("/v1/chat/completions")
|
| 131 |
async def chat_completions(request: ChatRequest):
|
| 132 |
|
| 133 |
if not request.messages:
|
| 134 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
if any(
|
| 137 |
m.get("role") not in ("system", "user", "assistant")
|
| 138 |
or not isinstance(m.get("content"), str)
|
| 139 |
for m in request.messages
|
| 140 |
):
|
| 141 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
temperature = min(
|
| 144 |
-
max(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
2
|
| 146 |
)
|
| 147 |
|
| 148 |
max_tokens = min(
|
| 149 |
-
max(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
4096
|
| 151 |
)
|
| 152 |
|
| 153 |
-
#
|
|
|
|
|
|
|
|
|
|
| 154 |
if request.stream:
|
| 155 |
|
| 156 |
completion_id = "chatcmpl-" + uuid.uuid4().hex
|
| 157 |
created = int(time.time())
|
| 158 |
|
| 159 |
def event(data):
|
| 160 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
def stream_response():
|
| 163 |
|
|
|
|
| 164 |
yield event({
|
| 165 |
"id": completion_id,
|
| 166 |
"object": "chat.completion.chunk",
|
|
@@ -168,11 +220,14 @@ async def chat_completions(request: ChatRequest):
|
|
| 168 |
"model": MODEL_ID,
|
| 169 |
"choices": [{
|
| 170 |
"index": 0,
|
| 171 |
-
"delta": {
|
|
|
|
|
|
|
| 172 |
"finish_reason": None
|
| 173 |
}]
|
| 174 |
})
|
| 175 |
|
|
|
|
| 176 |
for token in run_streaming(
|
| 177 |
request.messages,
|
| 178 |
temperature,
|
|
@@ -185,11 +240,14 @@ async def chat_completions(request: ChatRequest):
|
|
| 185 |
"model": MODEL_ID,
|
| 186 |
"choices": [{
|
| 187 |
"index": 0,
|
| 188 |
-
"delta": {
|
|
|
|
|
|
|
| 189 |
"finish_reason": None
|
| 190 |
}]
|
| 191 |
})
|
| 192 |
|
|
|
|
| 193 |
yield event({
|
| 194 |
"id": completion_id,
|
| 195 |
"object": "chat.completion.chunk",
|
|
@@ -214,7 +272,10 @@ async def chat_completions(request: ChatRequest):
|
|
| 214 |
}
|
| 215 |
)
|
| 216 |
|
| 217 |
-
#
|
|
|
|
|
|
|
|
|
|
| 218 |
result = run_inference(
|
| 219 |
request.messages,
|
| 220 |
temperature,
|
|
@@ -240,11 +301,17 @@ async def chat_completions(request: ChatRequest):
|
|
| 240 |
"usage": {
|
| 241 |
"prompt_tokens": prompt_tokens,
|
| 242 |
"completion_tokens": completion_tokens,
|
| 243 |
-
"total_tokens":
|
|
|
|
|
|
|
| 244 |
}
|
| 245 |
}
|
| 246 |
|
| 247 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
@app.get("/")
|
| 249 |
def home():
|
| 250 |
return {
|
|
@@ -255,6 +322,10 @@ def home():
|
|
| 255 |
}
|
| 256 |
|
| 257 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
@app.get("/v1/models")
|
| 259 |
def models():
|
| 260 |
return {
|
|
@@ -267,5 +338,9 @@ def models():
|
|
| 267 |
}
|
| 268 |
|
| 269 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
if __name__ == "__main__":
|
| 271 |
app.launch()
|
|
|
|
| 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
|
|
|
|
| 34 |
app = Server(title="MyAPI")
|
| 35 |
|
| 36 |
|
| 37 |
+
# --------------------------------------------------
|
| 38 |
+
# REQUEST FORMAT
|
| 39 |
+
# --------------------------------------------------
|
| 40 |
+
|
| 41 |
class ChatRequest(BaseModel):
|
| 42 |
model: Optional[str] = MODEL_ID
|
| 43 |
messages: list[dict]
|
|
|
|
| 46 |
stream: Optional[bool] = False
|
| 47 |
|
| 48 |
|
| 49 |
+
# --------------------------------------------------
|
| 50 |
+
# INPUT PREPARATION
|
| 51 |
+
# --------------------------------------------------
|
| 52 |
+
|
| 53 |
+
def prepare_inputs(messages: list[dict]):
|
| 54 |
prompt = tokenizer.apply_chat_template(
|
| 55 |
messages,
|
| 56 |
tokenize=False,
|
|
|
|
| 63 |
).to(model.device)
|
| 64 |
|
| 65 |
|
| 66 |
+
# --------------------------------------------------
|
| 67 |
+
# NORMAL INFERENCE
|
| 68 |
+
# --------------------------------------------------
|
| 69 |
+
|
| 70 |
@app.api(name="generate")
|
| 71 |
@spaces.GPU(duration=120)
|
| 72 |
+
def run_inference(
|
| 73 |
+
messages: list[dict],
|
| 74 |
+
temperature: float = 0.7,
|
| 75 |
+
max_tokens: int = 512
|
| 76 |
+
) -> dict:
|
| 77 |
|
| 78 |
inputs = prepare_inputs(messages)
|
| 79 |
|
|
|
|
| 98 |
}
|
| 99 |
|
| 100 |
|
| 101 |
+
# --------------------------------------------------
|
| 102 |
+
# STREAMING INFERENCE
|
| 103 |
+
# --------------------------------------------------
|
| 104 |
+
|
| 105 |
@app.api(name="generate_stream", stream_every=0.05)
|
| 106 |
@spaces.GPU(duration=120)
|
| 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 |
|
|
|
|
| 140 |
target=generate_in_thread,
|
| 141 |
daemon=True
|
| 142 |
)
|
| 143 |
+
|
| 144 |
worker.start()
|
| 145 |
|
| 146 |
for text in streamer:
|
|
|
|
| 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):
|
| 162 |
|
| 163 |
if not request.messages:
|
| 164 |
+
raise HTTPException(
|
| 165 |
+
status_code=400,
|
| 166 |
+
detail="Messages cannot be empty"
|
| 167 |
+
)
|
| 168 |
|
| 169 |
if any(
|
| 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=400,
|
| 176 |
+
detail="Invalid message format"
|
| 177 |
+
)
|
| 178 |
|
| 179 |
temperature = min(
|
| 180 |
+
max(
|
| 181 |
+
request.temperature
|
| 182 |
+
if request.temperature is not None else 0.7,
|
| 183 |
+
0
|
| 184 |
+
),
|
| 185 |
2
|
| 186 |
)
|
| 187 |
|
| 188 |
max_tokens = min(
|
| 189 |
+
max(
|
| 190 |
+
request.max_tokens
|
| 191 |
+
if request.max_tokens is not None else 512,
|
| 192 |
+
1
|
| 193 |
+
),
|
| 194 |
4096
|
| 195 |
)
|
| 196 |
|
| 197 |
+
# ----------------------------------------------
|
| 198 |
+
# SSE STREAMING
|
| 199 |
+
# ----------------------------------------------
|
| 200 |
+
|
| 201 |
if request.stream:
|
| 202 |
|
| 203 |
completion_id = "chatcmpl-" + uuid.uuid4().hex
|
| 204 |
created = int(time.time())
|
| 205 |
|
| 206 |
def event(data):
|
| 207 |
+
return (
|
| 208 |
+
"data: "
|
| 209 |
+
+ json.dumps(data, ensure_ascii=False)
|
| 210 |
+
+ "\n\n"
|
| 211 |
+
)
|
| 212 |
|
| 213 |
def stream_response():
|
| 214 |
|
| 215 |
+
# Initial assistant role
|
| 216 |
yield event({
|
| 217 |
"id": completion_id,
|
| 218 |
"object": "chat.completion.chunk",
|
|
|
|
| 220 |
"model": MODEL_ID,
|
| 221 |
"choices": [{
|
| 222 |
"index": 0,
|
| 223 |
+
"delta": {
|
| 224 |
+
"role": "assistant"
|
| 225 |
+
},
|
| 226 |
"finish_reason": None
|
| 227 |
}]
|
| 228 |
})
|
| 229 |
|
| 230 |
+
# Generated content
|
| 231 |
for token in run_streaming(
|
| 232 |
request.messages,
|
| 233 |
temperature,
|
|
|
|
| 240 |
"model": MODEL_ID,
|
| 241 |
"choices": [{
|
| 242 |
"index": 0,
|
| 243 |
+
"delta": {
|
| 244 |
+
"content": token
|
| 245 |
+
},
|
| 246 |
"finish_reason": None
|
| 247 |
}]
|
| 248 |
})
|
| 249 |
|
| 250 |
+
# Completion
|
| 251 |
yield event({
|
| 252 |
"id": completion_id,
|
| 253 |
"object": "chat.completion.chunk",
|
|
|
|
| 272 |
}
|
| 273 |
)
|
| 274 |
|
| 275 |
+
# ----------------------------------------------
|
| 276 |
+
# NORMAL NON-STREAMING RESPONSE
|
| 277 |
+
# ----------------------------------------------
|
| 278 |
+
|
| 279 |
result = run_inference(
|
| 280 |
request.messages,
|
| 281 |
temperature,
|
|
|
|
| 301 |
"usage": {
|
| 302 |
"prompt_tokens": prompt_tokens,
|
| 303 |
"completion_tokens": completion_tokens,
|
| 304 |
+
"total_tokens": (
|
| 305 |
+
prompt_tokens + completion_tokens
|
| 306 |
+
)
|
| 307 |
}
|
| 308 |
}
|
| 309 |
|
| 310 |
|
| 311 |
+
# --------------------------------------------------
|
| 312 |
+
# HEALTH CHECK
|
| 313 |
+
# --------------------------------------------------
|
| 314 |
+
|
| 315 |
@app.get("/")
|
| 316 |
def home():
|
| 317 |
return {
|
|
|
|
| 322 |
}
|
| 323 |
|
| 324 |
|
| 325 |
+
# --------------------------------------------------
|
| 326 |
+
# MODEL LIST
|
| 327 |
+
# --------------------------------------------------
|
| 328 |
+
|
| 329 |
@app.get("/v1/models")
|
| 330 |
def models():
|
| 331 |
return {
|
|
|
|
| 338 |
}
|
| 339 |
|
| 340 |
|
| 341 |
+
# --------------------------------------------------
|
| 342 |
+
# START SERVER
|
| 343 |
+
# --------------------------------------------------
|
| 344 |
+
|
| 345 |
if __name__ == "__main__":
|
| 346 |
app.launch()
|