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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
Extra sampling parameters supported by the API: `top_k`, `repetition_penalty`, and `seed`.
|
| 3 |
"""
|
| 4 |
|
|
@@ -10,7 +588,7 @@ def _chat_ui_params(max_tokens, temperature, top_p, top_k, rep_pen):
|
|
| 10 |
"top_p": float(top_p),
|
| 11 |
"top_k": int(top_k),
|
| 12 |
"repetition_penalty": float(rep_pen),
|
| 13 |
-
"stop": ["
|
| 14 |
"seed": None,
|
| 15 |
}
|
| 16 |
|
|
@@ -86,7 +664,7 @@ with gr.Blocks(title=f"{MODEL_ID} API") as demo:
|
|
| 86 |
with gr.Tab("Text completion"):
|
| 87 |
with gr.Row():
|
| 88 |
with gr.Column():
|
| 89 |
-
prompt = gr.Textbox(label="Prompt", lines=6, value="
|
| 90 |
with gr.Accordion("Sampling", open=False):
|
| 91 |
max_tokens = gr.Slider(1, min(MAX_OUTPUT_TOKENS, MAX_NEW_TOKENS_LIMIT), value=min(128, MAX_OUTPUT_TOKENS, MAX_NEW_TOKENS_LIMIT), step=1, label="max_tokens")
|
| 92 |
temperature = gr.Slider(0, 2, value=0.8, step=0.05, label="temperature (0 = greedy)")
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gradio Space that hosts FlameF0X/TinyGPT behind an OpenAI-compatible API.
|
| 3 |
+
|
| 4 |
+
Endpoints (all under /v1):
|
| 5 |
+
GET /v1/models
|
| 6 |
+
POST /v1/completions (best fit for a base model)
|
| 7 |
+
POST /v1/chat/completions (uses the tokenizer chat template if it has one,
|
| 8 |
+
otherwise a simple "User:/Assistant:" fallback)
|
| 9 |
+
|
| 10 |
+
The Gradio playground is mounted at "/".
|
| 11 |
+
|
| 12 |
+
Optional environment variables / Space secrets:
|
| 13 |
+
MODEL_ID default "FlameF0X/TinyGPT"
|
| 14 |
+
API_KEY if set, requests must send "Authorization: Bearer <API_KEY>"
|
| 15 |
+
MAX_NEW_TOKENS hard cap on max_tokens per request (default 1024)
|
| 16 |
+
CONTEXT_WINDOW optional context window override, never above the model config
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import threading
|
| 22 |
+
import time
|
| 23 |
+
import uuid
|
| 24 |
+
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
|
| 25 |
+
|
| 26 |
+
import gradio as gr
|
| 27 |
+
import torch
|
| 28 |
+
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
| 29 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 30 |
+
from pydantic import BaseModel, ConfigDict
|
| 31 |
+
from transformers import (
|
| 32 |
+
StoppingCriteria,
|
| 33 |
+
StoppingCriteriaList,
|
| 34 |
+
TextIteratorStreamer,
|
| 35 |
+
pipeline,
|
| 36 |
+
set_seed,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# --------------------------------------------------------------------------- #
|
| 40 |
+
# Config + model loading
|
| 41 |
+
# --------------------------------------------------------------------------- #
|
| 42 |
+
MODEL_ID = os.getenv("MODEL_ID", "FlameF0X/TinyGPT")
|
| 43 |
+
API_KEY = os.getenv("API_KEY") # optional
|
| 44 |
+
MAX_NEW_TOKENS_LIMIT = int(os.getenv("MAX_NEW_TOKENS", "1024"))
|
| 45 |
+
DEFAULT_MAX_TOKENS = 256
|
| 46 |
+
|
| 47 |
+
DEVICE = 0 if torch.cuda.is_available() else -1
|
| 48 |
+
|
| 49 |
+
# Same call as in your snippet (plus a device); we reuse its model + tokenizer
|
| 50 |
+
# for generation so streaming and token accounting work.
|
| 51 |
+
pipe = pipeline(
|
| 52 |
+
"text-generation",
|
| 53 |
+
model=MODEL_ID,
|
| 54 |
+
trust_remote_code=True,
|
| 55 |
+
device=DEVICE,
|
| 56 |
+
)
|
| 57 |
+
tokenizer = pipe.tokenizer
|
| 58 |
+
model = pipe.model
|
| 59 |
+
model.eval()
|
| 60 |
+
|
| 61 |
+
# TinyGPT is a GPT-2 model with a 2,048-token context window. Derive the real
|
| 62 |
+
# limit from the loaded config instead of guessing or trusting tokenizer sentinels.
|
| 63 |
+
_config_context_candidates = [
|
| 64 |
+
getattr(model.config, key, None)
|
| 65 |
+
for key in ("n_positions", "max_position_embeddings", "n_ctx")
|
| 66 |
+
]
|
| 67 |
+
_config_context_candidates = [
|
| 68 |
+
int(value) for value in _config_context_candidates
|
| 69 |
+
if isinstance(value, (int, float)) and 0 < int(value) < 1_000_000
|
| 70 |
+
]
|
| 71 |
+
MODEL_CONTEXT_WINDOW = min(_config_context_candidates) if _config_context_candidates else 2048
|
| 72 |
+
_requested_context_window = os.getenv("CONTEXT_WINDOW")
|
| 73 |
+
if _requested_context_window:
|
| 74 |
+
try:
|
| 75 |
+
MODEL_CONTEXT_WINDOW = min(MODEL_CONTEXT_WINDOW, max(128, int(_requested_context_window)))
|
| 76 |
+
except ValueError as exc:
|
| 77 |
+
raise RuntimeError("CONTEXT_WINDOW must be an integer.") from exc
|
| 78 |
+
# Leave room for at least a small prompt, even if a client requests too many tokens.
|
| 79 |
+
MAX_OUTPUT_TOKENS = max(1, MODEL_CONTEXT_WINDOW - 64)
|
| 80 |
+
IS_TINYGPT = MODEL_ID.rstrip("/").lower() == "flamef0x/tinygpt"
|
| 81 |
+
|
| 82 |
+
if tokenizer.pad_token_id is None:
|
| 83 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 84 |
+
|
| 85 |
+
# One generation at a time (small model, usually CPU / single GPU Space).
|
| 86 |
+
GEN_LOCK = threading.Lock()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# --------------------------------------------------------------------------- #
|
| 90 |
+
# Generation core (shared by the API and the Gradio playground)
|
| 91 |
+
# --------------------------------------------------------------------------- #
|
| 92 |
+
class _Control(StoppingCriteria):
|
| 93 |
+
"""Lets us cancel generation (stop strings, client disconnect) and count tokens."""
|
| 94 |
+
|
| 95 |
+
def __init__(self, prompt_len: int):
|
| 96 |
+
self.prompt_len = prompt_len
|
| 97 |
+
self.generated = 0
|
| 98 |
+
self.cancel = threading.Event()
|
| 99 |
+
|
| 100 |
+
def __call__(self, input_ids, scores, **kwargs):
|
| 101 |
+
self.generated = input_ids.shape[1] - self.prompt_len
|
| 102 |
+
return torch.full(
|
| 103 |
+
(input_ids.shape[0],),
|
| 104 |
+
self.cancel.is_set(),
|
| 105 |
+
dtype=torch.bool,
|
| 106 |
+
device=input_ids.device,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _earliest_stop(text: str, stops: List[str]) -> int:
|
| 111 |
+
hits = [text.find(s) for s in stops]
|
| 112 |
+
hits = [h for h in hits if h >= 0]
|
| 113 |
+
return min(hits) if hits else -1
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def generate(prompt: str, p: Dict[str, Any]) -> Iterator[Tuple]:
|
| 117 |
+
"""
|
| 118 |
+
Yields:
|
| 119 |
+
("text", str) incremental text
|
| 120 |
+
("done", finish_reason, prompt_tokens, completion_tokens) once, at the end
|
| 121 |
+
"""
|
| 122 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 123 |
+
inputs.pop("token_type_ids", None)
|
| 124 |
+
prompt_len = inputs["input_ids"].shape[1]
|
| 125 |
+
if prompt_len == 0:
|
| 126 |
+
raise ValueError("The prompt must not be empty.")
|
| 127 |
+
|
| 128 |
+
# Reserve space for the requested continuation. For raw completions, truncate
|
| 129 |
+
# old tokens from the left; chat prompts are preferably trimmed by whole turns.
|
| 130 |
+
input_budget = max(1, MODEL_CONTEXT_WINDOW - p["max_tokens"])
|
| 131 |
+
if prompt_len > input_budget:
|
| 132 |
+
inputs["input_ids"] = inputs["input_ids"][:, -input_budget:]
|
| 133 |
+
if "attention_mask" in inputs:
|
| 134 |
+
inputs["attention_mask"] = inputs["attention_mask"][:, -input_budget:]
|
| 135 |
+
prompt_len = input_budget
|
| 136 |
+
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
| 137 |
+
|
| 138 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 139 |
+
ctl = _Control(prompt_len)
|
| 140 |
+
|
| 141 |
+
gen_kwargs: Dict[str, Any] = dict(
|
| 142 |
+
**inputs,
|
| 143 |
+
streamer=streamer,
|
| 144 |
+
stopping_criteria=StoppingCriteriaList([ctl]),
|
| 145 |
+
max_new_tokens=p["max_tokens"],
|
| 146 |
+
repetition_penalty=p["repetition_penalty"],
|
| 147 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 148 |
+
)
|
| 149 |
+
if p["temperature"] > 0:
|
| 150 |
+
gen_kwargs.update(
|
| 151 |
+
do_sample=True,
|
| 152 |
+
temperature=p["temperature"],
|
| 153 |
+
top_p=p["top_p"],
|
| 154 |
+
top_k=p["top_k"],
|
| 155 |
+
)
|
| 156 |
+
else:
|
| 157 |
+
gen_kwargs.update(do_sample=False)
|
| 158 |
+
|
| 159 |
+
errors: List[Exception] = []
|
| 160 |
+
|
| 161 |
+
def worker():
|
| 162 |
+
try:
|
| 163 |
+
with torch.inference_mode():
|
| 164 |
+
model.generate(**gen_kwargs)
|
| 165 |
+
except Exception as e: # make sure the streamer iterator can't hang
|
| 166 |
+
errors.append(e)
|
| 167 |
+
streamer.text_queue.put(streamer.stop_signal)
|
| 168 |
+
|
| 169 |
+
# TinyGPT sometimes starts generating the next speaker label after its answer.
|
| 170 |
+
# Always treat User: as a hard stop for this model, even if the client did not
|
| 171 |
+
# request stop strings. Keeping a partial-match buffer prevents leaking the
|
| 172 |
+
# marker when it arrives across multiple streamer chunks.
|
| 173 |
+
stops: List[str] = list(p["stop"])
|
| 174 |
+
if IS_TINYGPT and "User:" not in stops:
|
| 175 |
+
stops.append("User:")
|
| 176 |
+
holdback = max((len(s) for s in stops), default=1) - 1 # partial-match buffer
|
| 177 |
+
stop_hit = False
|
| 178 |
+
|
| 179 |
+
with GEN_LOCK:
|
| 180 |
+
if p.get("seed") is not None:
|
| 181 |
+
set_seed(int(p["seed"]))
|
| 182 |
+
thread = threading.Thread(target=worker, daemon=True)
|
| 183 |
+
thread.start()
|
| 184 |
+
buf = ""
|
| 185 |
+
try:
|
| 186 |
+
for chunk in streamer:
|
| 187 |
+
buf += chunk
|
| 188 |
+
if stops:
|
| 189 |
+
idx = _earliest_stop(buf, stops)
|
| 190 |
+
if idx >= 0:
|
| 191 |
+
if buf[:idx]:
|
| 192 |
+
yield ("text", buf[:idx])
|
| 193 |
+
buf = ""
|
| 194 |
+
stop_hit = True
|
| 195 |
+
ctl.cancel.set()
|
| 196 |
+
break
|
| 197 |
+
safe = len(buf) - holdback
|
| 198 |
+
if safe > 0:
|
| 199 |
+
yield ("text", buf[:safe])
|
| 200 |
+
buf = buf[safe:]
|
| 201 |
+
else:
|
| 202 |
+
yield ("text", buf)
|
| 203 |
+
buf = ""
|
| 204 |
+
if buf and not stop_hit:
|
| 205 |
+
yield ("text", buf)
|
| 206 |
+
finally:
|
| 207 |
+
# Also runs if the client disconnects and the generator is closed.
|
| 208 |
+
ctl.cancel.set()
|
| 209 |
+
thread.join()
|
| 210 |
+
|
| 211 |
+
if errors:
|
| 212 |
+
raise errors[0]
|
| 213 |
+
|
| 214 |
+
if stop_hit:
|
| 215 |
+
finish = "stop"
|
| 216 |
+
elif ctl.generated >= p["max_tokens"]:
|
| 217 |
+
finish = "length"
|
| 218 |
+
else:
|
| 219 |
+
finish = "stop" # EOS
|
| 220 |
+
yield ("done", finish, prompt_len, ctl.generated)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def run_full(prompt: str, p: Dict[str, Any]) -> Tuple[str, str, int, int]:
|
| 224 |
+
parts: List[str] = []
|
| 225 |
+
meta = ("stop", 0, 0)
|
| 226 |
+
for ev in generate(prompt, p):
|
| 227 |
+
if ev[0] == "text":
|
| 228 |
+
parts.append(ev[1])
|
| 229 |
+
else:
|
| 230 |
+
meta = ev[1:]
|
| 231 |
+
return "".join(parts), meta[0], meta[1], meta[2]
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# --------------------------------------------------------------------------- #
|
| 235 |
+
# Chat formatting
|
| 236 |
+
# --------------------------------------------------------------------------- #
|
| 237 |
+
def _flatten_content(content: Any) -> str:
|
| 238 |
+
if content is None:
|
| 239 |
+
return ""
|
| 240 |
+
if isinstance(content, str):
|
| 241 |
+
return content
|
| 242 |
+
if isinstance(content, list): # OpenAI "content parts"
|
| 243 |
+
return "".join(
|
| 244 |
+
part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") == "text"
|
| 245 |
+
)
|
| 246 |
+
return str(content)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _token_count(text: str) -> int:
|
| 250 |
+
"""Count tokenizer tokens without adding special tokens."""
|
| 251 |
+
return len(tokenizer.encode(text, add_special_tokens=False))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _render_tinygpt_prompt(system_text: str, dialogue: List[Dict[str, str]]) -> str:
|
| 255 |
+
"""Render TinyGPT conversation history in User: ... Assistant: format."""
|
| 256 |
+
parts: List[str] = []
|
| 257 |
+
if system_text:
|
| 258 |
+
# TinyGPT's published template has no system role. Retain system/developer
|
| 259 |
+
# instructions as a plain-text preamble rather than silently discarding them.
|
| 260 |
+
parts.append(f"System: {system_text}\n\n")
|
| 261 |
+
for message in dialogue:
|
| 262 |
+
if message["role"] == "user":
|
| 263 |
+
parts.append(f"User: {message['content']}\n\n")
|
| 264 |
+
elif message["role"] == "assistant":
|
| 265 |
+
parts.append(f"Assistant: {message['content']}\n\n")
|
| 266 |
+
return "".join(parts) + "Assistant: "
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def messages_to_prompt(
|
| 270 |
+
messages: List[Dict[str, Any]], max_input_tokens: Optional[int] = None
|
| 271 |
+
) -> str:
|
| 272 |
+
"""Format a full OpenAI messages history and fit it within the model context.
|
| 273 |
+
|
| 274 |
+
OpenAI chat endpoints are stateless: callers send prior user and assistant
|
| 275 |
+
messages on every turn. This function preserves that history and drops oldest
|
| 276 |
+
complete turns only when the model's context window requires it.
|
| 277 |
+
"""
|
| 278 |
+
if not isinstance(messages, list) or not messages:
|
| 279 |
+
raise ValueError("`messages` must be a non-empty list.")
|
| 280 |
+
|
| 281 |
+
normalized: List[Dict[str, str]] = []
|
| 282 |
+
system_parts: List[str] = []
|
| 283 |
+
for item in messages:
|
| 284 |
+
if not isinstance(item, dict):
|
| 285 |
+
raise ValueError("Each message must be an object with `role` and `content`.")
|
| 286 |
+
role = str(item.get("role", "user")).strip().lower()
|
| 287 |
+
content = _flatten_content(item.get("content")).strip()
|
| 288 |
+
if role in ("system", "developer"):
|
| 289 |
+
if content:
|
| 290 |
+
system_parts.append(content)
|
| 291 |
+
elif role in ("user", "assistant"):
|
| 292 |
+
normalized.append({"role": role, "content": content})
|
| 293 |
+
elif role == "tool":
|
| 294 |
+
# Tool execution itself is the client's responsibility. Preserve tool
|
| 295 |
+
# results in the context so the next assistant turn can use them.
|
| 296 |
+
tool_name = str(item.get("name", "tool"))
|
| 297 |
+
normalized.append({"role": "user", "content": f"[Tool result from {tool_name}]\n{content}"})
|
| 298 |
+
elif role == "function":
|
| 299 |
+
normalized.append({"role": "user", "content": f"[Function result]\n{content}"})
|
| 300 |
+
else:
|
| 301 |
+
raise ValueError(f"Unsupported message role: {role!r}.")
|
| 302 |
+
|
| 303 |
+
if not normalized:
|
| 304 |
+
raise ValueError("`messages` must contain at least one user or assistant message.")
|
| 305 |
+
|
| 306 |
+
system_text = "\n".join(system_parts)
|
| 307 |
+
|
| 308 |
+
if not IS_TINYGPT and getattr(tokenizer, "chat_template", None):
|
| 309 |
+
def render() -> str:
|
| 310 |
+
template_messages: List[Dict[str, str]] = []
|
| 311 |
+
if system_text:
|
| 312 |
+
template_messages.append({"role": "system", "content": system_text})
|
| 313 |
+
template_messages.extend(normalized)
|
| 314 |
+
return tokenizer.apply_chat_template(
|
| 315 |
+
template_messages, tokenize=False, add_generation_prompt=True
|
| 316 |
+
)
|
| 317 |
+
elif IS_TINYGPT:
|
| 318 |
+
def render() -> str:
|
| 319 |
+
return _render_tinygpt_prompt(system_text, normalized)
|
| 320 |
+
else:
|
| 321 |
+
# Fallback for models without an installed chat template.
|
| 322 |
+
labels = {"system": "System", "user": "User", "assistant": "Assistant"}
|
| 323 |
+
def render() -> str:
|
| 324 |
+
lines = []
|
| 325 |
+
if system_text:
|
| 326 |
+
lines.append(f"System: {system_text}")
|
| 327 |
+
lines.extend(f"{labels[m['role']]}: {m['content']}" for m in normalized)
|
| 328 |
+
return "\n".join(lines) + "\nAssistant:"
|
| 329 |
+
|
| 330 |
+
prompt = render()
|
| 331 |
+
if max_input_tokens is None or max_input_tokens < 1:
|
| 332 |
+
return prompt
|
| 333 |
+
|
| 334 |
+
# Shorten the system preamble first, but keep its beginning, where instructions
|
| 335 |
+
# such as the assistant's role usually live. Reserve most context for dialogue.
|
| 336 |
+
if system_text and _token_count(prompt) > max_input_tokens:
|
| 337 |
+
system_budget = min(_token_count(system_text), max(0, max_input_tokens // 4))
|
| 338 |
+
if system_budget:
|
| 339 |
+
system_ids = tokenizer.encode(system_text, add_special_tokens=False)[:system_budget]
|
| 340 |
+
system_text = tokenizer.decode(system_ids, skip_special_tokens=True)
|
| 341 |
+
else:
|
| 342 |
+
system_text = ""
|
| 343 |
+
prompt = render()
|
| 344 |
+
|
| 345 |
+
# Drop the oldest user turn and its assistant reply, never the newest request,
|
| 346 |
+
# until the remaining transcript fits.
|
| 347 |
+
while _token_count(prompt) > max_input_tokens and len(normalized) > 1:
|
| 348 |
+
remove_count = 1
|
| 349 |
+
if normalized[0]["role"] == "user" and len(normalized) > 1 and normalized[1]["role"] == "assistant":
|
| 350 |
+
remove_count = 2
|
| 351 |
+
del normalized[:remove_count]
|
| 352 |
+
prompt = render()
|
| 353 |
+
|
| 354 |
+
# A single exceptionally long message can itself exceed the context. Keep the
|
| 355 |
+
# tail of its content while preserving the role prefix and generation prompt.
|
| 356 |
+
if _token_count(prompt) > max_input_tokens and normalized:
|
| 357 |
+
last = normalized[-1]
|
| 358 |
+
original_content = last["content"]
|
| 359 |
+
last["content"] = ""
|
| 360 |
+
empty_prompt = render()
|
| 361 |
+
available = max(1, max_input_tokens - _token_count(empty_prompt) - 1)
|
| 362 |
+
content_ids = tokenizer.encode(original_content, add_special_tokens=False)
|
| 363 |
+
last["content"] = tokenizer.decode(content_ids[-available:], skip_special_tokens=True)
|
| 364 |
+
prompt = render()
|
| 365 |
+
# This can only happen with a very long system prefix or tiny custom limit.
|
| 366 |
+
if _token_count(prompt) > max_input_tokens:
|
| 367 |
+
prompt_ids = tokenizer.encode(prompt, add_special_tokens=False)[-max_input_tokens:]
|
| 368 |
+
prompt = tokenizer.decode(prompt_ids, skip_special_tokens=True)
|
| 369 |
+
|
| 370 |
+
return prompt
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# --------------------------------------------------------------------------- #
|
| 374 |
+
# OpenAI-compatible API
|
| 375 |
+
# --------------------------------------------------------------------------- #
|
| 376 |
+
class SamplingParams(BaseModel):
|
| 377 |
+
model_config = ConfigDict(extra="allow") # ignore unknown OpenAI params instead of 422
|
| 378 |
+
|
| 379 |
+
model: Optional[str] = None
|
| 380 |
+
max_tokens: Optional[int] = None
|
| 381 |
+
max_completion_tokens: Optional[int] = None
|
| 382 |
+
temperature: Optional[float] = 0.8
|
| 383 |
+
top_p: Optional[float] = 1.0
|
| 384 |
+
top_k: Optional[int] = 50 # extension
|
| 385 |
+
repetition_penalty: Optional[float] = 1.0 # extension
|
| 386 |
+
stop: Optional[Union[str, List[str]]] = None
|
| 387 |
+
seed: Optional[int] = None
|
| 388 |
+
stream: Optional[bool] = False
|
| 389 |
+
stream_options: Optional[Dict[str, Any]] = None
|
| 390 |
+
|
| 391 |
+
def to_params(self) -> Dict[str, Any]:
|
| 392 |
+
stops = [self.stop] if isinstance(self.stop, str) else list(self.stop or [])
|
| 393 |
+
max_tokens = self.max_completion_tokens or self.max_tokens or DEFAULT_MAX_TOKENS
|
| 394 |
+
return dict(
|
| 395 |
+
max_tokens=max(1, min(int(max_tokens), MAX_NEW_TOKENS_LIMIT, MAX_OUTPUT_TOKENS)),
|
| 396 |
+
temperature=float(self.temperature if self.temperature is not None else 0.8),
|
| 397 |
+
top_p=float(self.top_p if self.top_p is not None else 1.0),
|
| 398 |
+
top_k=int(self.top_k if self.top_k is not None else 50),
|
| 399 |
+
repetition_penalty=float(self.repetition_penalty or 1.0),
|
| 400 |
+
stop=[s for s in stops if s],
|
| 401 |
+
seed=self.seed,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class CompletionRequest(SamplingParams):
|
| 406 |
+
prompt: Union[str, List[str]] = ""
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
class ChatRequest(SamplingParams):
|
| 410 |
+
messages: List[Dict[str, Any]]
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def auth(authorization: Optional[str] = Header(default=None)):
|
| 414 |
+
if API_KEY and authorization != f"Bearer {API_KEY}":
|
| 415 |
+
raise HTTPException(status_code=401, detail="Invalid or missing API key.")
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def sse(obj: Any) -> str:
|
| 419 |
+
return f"data: {json.dumps(obj)}\n\n"
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def usage(pt: int, ct: int) -> Dict[str, int]:
|
| 423 |
+
return {"prompt_tokens": pt, "completion_tokens": ct, "total_tokens": pt + ct}
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
api = FastAPI(title="TinyGPT OpenAI-compatible API")
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@api.exception_handler(HTTPException)
|
| 430 |
+
async def openai_style_errors(_: Request, exc: HTTPException):
|
| 431 |
+
return JSONResponse(
|
| 432 |
+
status_code=exc.status_code,
|
| 433 |
+
content={"error": {"message": str(exc.detail), "type": "invalid_request_error", "code": exc.status_code}},
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
@api.get("/health")
|
| 438 |
+
def health():
|
| 439 |
+
return {"status": "ok", "model": MODEL_ID}
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
@api.get("/v1/models", dependencies=[Depends(auth)])
|
| 443 |
+
def list_models():
|
| 444 |
+
return {
|
| 445 |
+
"object": "list",
|
| 446 |
+
"data": [{"id": MODEL_ID, "object": "model", "created": 0, "owned_by": "FlameF0X"}],
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
@api.get("/v1/models/{model_id:path}", dependencies=[Depends(auth)])
|
| 451 |
+
def get_model(model_id: str):
|
| 452 |
+
return {"id": MODEL_ID, "object": "model", "created": 0, "owned_by": "FlameF0X"}
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
@api.post("/v1/completions", dependencies=[Depends(auth)])
|
| 456 |
+
def completions(req: CompletionRequest):
|
| 457 |
+
prompts = [req.prompt] if isinstance(req.prompt, str) else list(req.prompt)
|
| 458 |
+
if not prompts:
|
| 459 |
+
raise HTTPException(400, "`prompt` is required.")
|
| 460 |
+
p = req.to_params()
|
| 461 |
+
cid, created, name = f"cmpl-{uuid.uuid4().hex}", int(time.time()), req.model or MODEL_ID
|
| 462 |
+
|
| 463 |
+
if req.stream:
|
| 464 |
+
if len(prompts) != 1:
|
| 465 |
+
raise HTTPException(400, "Streaming supports a single prompt only.")
|
| 466 |
+
|
| 467 |
+
def stream():
|
| 468 |
+
try:
|
| 469 |
+
for ev in generate(prompts[0], p):
|
| 470 |
+
if ev[0] == "text":
|
| 471 |
+
yield sse({
|
| 472 |
+
"id": cid, "object": "text_completion", "created": created, "model": name,
|
| 473 |
+
"choices": [{"index": 0, "text": ev[1], "logprobs": None, "finish_reason": None}],
|
| 474 |
+
})
|
| 475 |
+
else:
|
| 476 |
+
_, finish, pt, ct = ev
|
| 477 |
+
yield sse({
|
| 478 |
+
"id": cid, "object": "text_completion", "created": created, "model": name,
|
| 479 |
+
"choices": [{"index": 0, "text": "", "logprobs": None, "finish_reason": finish}],
|
| 480 |
+
})
|
| 481 |
+
if (req.stream_options or {}).get("include_usage"):
|
| 482 |
+
yield sse({
|
| 483 |
+
"id": cid, "object": "text_completion", "created": created, "model": name,
|
| 484 |
+
"choices": [], "usage": usage(pt, ct),
|
| 485 |
+
})
|
| 486 |
+
except Exception as e:
|
| 487 |
+
yield sse({"error": {"message": str(e), "type": "server_error"}})
|
| 488 |
+
yield "data: [DONE]\n\n"
|
| 489 |
+
|
| 490 |
+
return StreamingResponse(stream(), media_type="text/event-stream")
|
| 491 |
+
|
| 492 |
+
choices, tot_pt, tot_ct = [], 0, 0
|
| 493 |
+
try:
|
| 494 |
+
for i, prompt in enumerate(prompts):
|
| 495 |
+
text, finish, pt, ct = run_full(prompt, p)
|
| 496 |
+
choices.append({"index": i, "text": text, "logprobs": None, "finish_reason": finish})
|
| 497 |
+
tot_pt, tot_ct = tot_pt + pt, tot_ct + ct
|
| 498 |
+
except ValueError as e:
|
| 499 |
+
raise HTTPException(400, str(e))
|
| 500 |
+
return {
|
| 501 |
+
"id": cid, "object": "text_completion", "created": created, "model": name,
|
| 502 |
+
"choices": choices, "usage": usage(tot_pt, tot_ct),
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
@api.post("/v1/chat/completions", dependencies=[Depends(auth)])
|
| 507 |
+
def chat_completions(req: ChatRequest):
|
| 508 |
+
if not req.messages:
|
| 509 |
+
raise HTTPException(400, "`messages` is required.")
|
| 510 |
+
p = req.to_params()
|
| 511 |
+
try:
|
| 512 |
+
prompt = messages_to_prompt(
|
| 513 |
+
req.messages, max_input_tokens=MODEL_CONTEXT_WINDOW - p["max_tokens"]
|
| 514 |
+
)
|
| 515 |
+
except ValueError as e:
|
| 516 |
+
raise HTTPException(400, str(e))
|
| 517 |
+
|
| 518 |
+
chat_p = dict(p)
|
| 519 |
+
cid, created, name = f"chatcmpl-{uuid.uuid4().hex}", int(time.time()), req.model or MODEL_ID
|
| 520 |
+
|
| 521 |
+
def chunk(delta: Dict[str, Any], finish: Optional[str] = None, **extra) -> str:
|
| 522 |
+
return sse({
|
| 523 |
+
"id": cid, "object": "chat.completion.chunk", "created": created, "model": name,
|
| 524 |
+
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}], **extra,
|
| 525 |
+
})
|
| 526 |
+
|
| 527 |
+
if req.stream:
|
| 528 |
+
def stream():
|
| 529 |
+
try:
|
| 530 |
+
yield chunk({"role": "assistant", "content": ""})
|
| 531 |
+
for ev in generate(prompt, chat_p):
|
| 532 |
+
if ev[0] == "text":
|
| 533 |
+
yield chunk({"content": ev[1]})
|
| 534 |
+
else:
|
| 535 |
+
_, finish, pt, ct = ev
|
| 536 |
+
yield chunk({}, finish)
|
| 537 |
+
if (req.stream_options or {}).get("include_usage"):
|
| 538 |
+
yield sse({
|
| 539 |
+
"id": cid, "object": "chat.completion.chunk", "created": created,
|
| 540 |
+
"model": name, "choices": [], "usage": usage(pt, ct),
|
| 541 |
+
})
|
| 542 |
+
except Exception as e:
|
| 543 |
+
yield sse({"error": {"message": str(e), "type": "server_error"}})
|
| 544 |
+
yield "data: [DONE]\n\n"
|
| 545 |
+
|
| 546 |
+
return StreamingResponse(stream(), media_type="text/event-stream")
|
| 547 |
+
|
| 548 |
+
try:
|
| 549 |
+
text, finish, pt, ct = run_full(prompt, chat_p)
|
| 550 |
+
except ValueError as e:
|
| 551 |
+
raise HTTPException(400, str(e))
|
| 552 |
+
return {
|
| 553 |
+
"id": cid, "object": "chat.completion", "created": created, "model": name,
|
| 554 |
+
"choices": [{
|
| 555 |
+
"index": 0,
|
| 556 |
+
"message": {"role": "assistant", "content": text.strip()},
|
| 557 |
+
"finish_reason": finish,
|
| 558 |
+
}],
|
| 559 |
+
"usage": usage(pt, ct),
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# --------------------------------------------------------------------------- #
|
| 564 |
+
# Gradio playground (mounted at "/")
|
| 565 |
+
# --------------------------------------------------------------------------- #
|
| 566 |
+
space_host = os.getenv("SPACE_HOST")
|
| 567 |
+
BASE_URL = f"https://{space_host}/v1" if space_host else "http://localhost:7860/v1"
|
| 568 |
+
|
| 569 |
+
DOCS = f"""
|
| 570 |
+
# {MODEL_ID} — OpenAI-compatible API
|
| 571 |
+
|
| 572 |
+
**Base URL:** `{BASE_URL}`
|
| 573 |
+
**Endpoints:** `GET /v1/models` · `POST /v1/completions` · `POST /v1/chat/completions` (streaming supported)
|
| 574 |
+
**Context window:** {MODEL_CONTEXT_WINDOW} tokens
|
| 575 |
+
**API key:** {"required (Space secret `API_KEY`)" if API_KEY else "not required (set the `API_KEY` secret to enable authentication)"}
|
| 576 |
+
|
| 577 |
+
The Chat Completions endpoint accepts the full OpenAI `messages` array on every request,
|
| 578 |
+
including previous user and assistant turns. The built-in chat tab keeps conversation history
|
| 579 |
+
for you. TinyGPT chat history is formatted as `User: ...` / `Assistant: ...`. For TinyGPT, generation stops at `User:` and that marker is never streamed to clients.
|
| 580 |
Extra sampling parameters supported by the API: `top_k`, `repetition_penalty`, and `seed`.
|
| 581 |
"""
|
| 582 |
|
|
|
|
| 588 |
"top_p": float(top_p),
|
| 589 |
"top_k": int(top_k),
|
| 590 |
"repetition_penalty": float(rep_pen),
|
| 591 |
+
"stop": ["User:"] if IS_TINYGPT else [],
|
| 592 |
"seed": None,
|
| 593 |
}
|
| 594 |
|
|
|
|
| 664 |
with gr.Tab("Text completion"):
|
| 665 |
with gr.Row():
|
| 666 |
with gr.Column():
|
| 667 |
+
prompt = gr.Textbox(label="Prompt", lines=6, value="User: How much is 1 + 1?\n\nAssistant:")
|
| 668 |
with gr.Accordion("Sampling", open=False):
|
| 669 |
max_tokens = gr.Slider(1, min(MAX_OUTPUT_TOKENS, MAX_NEW_TOKENS_LIMIT), value=min(128, MAX_OUTPUT_TOKENS, MAX_NEW_TOKENS_LIMIT), step=1, label="max_tokens")
|
| 670 |
temperature = gr.Slider(0, 2, value=0.8, step=0.05, label="temperature (0 = greedy)")
|