coder5809 commited on
Commit
f7dd641
·
verified ·
1 Parent(s): bf8bb59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +467 -314
app.py CHANGED
@@ -1,29 +1,30 @@
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",
@@ -32,251 +33,347 @@ MODEL_ID = os.getenv(
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,
207
- add_generation_prompt=True
208
  )
209
 
210
- return tokenizer(
211
  prompt,
212
- return_tensors="pt"
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,
234
- do_sample=temperature > 0,
235
- temperature=max(temperature, 0.01),
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)
@@ -285,24 +382,34 @@ def gpu_generate_stream(
285
  tokenizer,
286
  skip_prompt=True,
287
  skip_special_tokens=True,
288
- timeout=120
289
  )
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,
301
- do_sample=temperature > 0,
302
- temperature=max(temperature, 0.01),
303
- pad_token_id=tokenizer.eos_token_id,
304
- streamer=streamer
305
- )
306
 
307
  except Exception as error:
308
  errors.append(error)
@@ -310,172 +417,193 @@ def gpu_generate_stream(
310
 
311
  worker = threading.Thread(
312
  target=generation_worker,
313
- daemon=True
314
  )
315
 
316
  worker.start()
317
 
318
- for text in streamer:
319
- if text:
320
- yield text
 
321
 
322
  worker.join()
323
 
324
  if errors:
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):
353
 
354
- if not request.messages:
355
- raise HTTPException(
356
- status_code=400,
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
387
- if request.temperature is not None else 0.7,
388
- 0
389
- ),
390
- 2
391
- )
392
-
393
- max_tokens = min(
394
- max(
395
- request.max_tokens
396
- if request.max_tokens is not None else 512,
397
- 1
398
- ),
399
- 4096
400
- )
401
-
402
- # ----------------------------------------------
403
  # STREAMING RESPONSE
404
- # ----------------------------------------------
405
 
406
  if request.stream:
407
 
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)
416
- + "\n\n"
417
- )
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": {
429
- "role": "assistant"
430
- },
431
- "finish_reason": None
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
 
480
  return StreamingResponse(
481
  stream_response(),
@@ -483,66 +611,80 @@ async def chat_completions(request: ChatRequest):
483
  headers={
484
  "Cache-Control": "no-cache",
485
  "Connection": "keep-alive",
486
- "X-Accel-Buffering": "no"
487
- }
488
  )
489
 
490
- # ----------------------------------------------
491
- # NORMAL RESPONSE
492
- # ----------------------------------------------
493
 
494
- result = generate(
495
- request.messages,
496
- temperature,
497
- max_tokens
498
- )
 
 
 
 
499
 
500
- prompt_tokens = result["prompt_tokens"]
501
- completion_tokens = result["completion_tokens"]
 
 
502
 
503
  return {
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": {
511
- "role": "assistant",
512
- "content": result["content"]
513
- },
514
- "finish_reason": "stop"
515
- }],
 
 
516
  "usage": {
517
  "prompt_tokens": prompt_tokens,
518
  "completion_tokens": completion_tokens,
519
  "total_tokens": (
520
  prompt_tokens + completion_tokens
521
- )
522
- }
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():
@@ -551,15 +693,26 @@ def home():
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()
 
1
 
2
  import os
3
+ import json
4
  import time
5
  import uuid
 
 
6
  import secrets
7
  import threading
8
+ from typing import Any, Iterator
9
 
10
+ import torch
11
  import spaces
12
 
 
13
  from gradio import Server
14
  from transformers import (
15
  AutoModelForCausalLM,
16
  AutoTokenizer,
17
+ TextIteratorStreamer,
18
  )
19
+
20
+ from fastapi import Depends, Header, HTTPException, Request
21
+ from fastapi.responses import StreamingResponse, JSONResponse
22
+ from pydantic import BaseModel, Field
23
 
24
 
25
+ # ============================================================
26
+ # CONFIGURATION
27
+ # ============================================================
28
 
29
  MODEL_ID = os.getenv(
30
  "MODEL_ID",
 
33
 
34
  PUBLIC_MODEL_NAME = "nova-ai"
35
 
36
+ MAX_CONTEXT_TOKENS = 4096
37
+ MAX_OUTPUT_TOKENS = 4096
38
+
39
  NOVA_SYSTEM_PROMPT = """
40
+ You are Nova AI, an intelligent AI assistant developed and
41
+ operated by the Nova AI project.
42
+
43
+ Your name is Nova AI. Do not identify yourself as ChatGPT
44
+ or another AI brand.
45
+
46
+ Be friendly, intelligent, conversational, and helpful.
47
+ Give accurate answers, explain difficult concepts clearly,
48
+ and assist with coding, reasoning, writing, and problem-solving.
49
+
50
+ Never invent facts or claim capabilities you do not have.
 
 
 
 
 
51
  """
52
 
53
 
54
+ # ============================================================
55
+ # API KEY MANAGEMENT
56
+ # ============================================================
57
 
58
+ def load_api_keys() -> list[str]:
59
+ keys = []
 
60
 
61
+ single_key = os.getenv("NOVA_API_KEY", "").strip()
62
 
63
+ multiple_keys = os.getenv("NOVA_API_KEYS", "").strip()
 
64
 
65
+ if single_key:
66
+ keys.append(single_key)
67
 
68
+ if multiple_keys:
69
+ keys.extend(
70
+ key.strip()
71
+ for key in multiple_keys.split(",")
72
+ if key.strip()
73
+ )
74
+
75
+ # Remove duplicates
76
+ return list(set(keys))
77
 
 
78
 
79
+ API_KEYS = load_api_keys()
80
+
81
+ if not API_KEYS:
82
  raise RuntimeError(
83
+ "No API keys configured. Set NOVA_API_KEY or NOVA_API_KEYS "
84
+ "in your Hugging Face Space secrets."
85
+ )
86
+
87
+
88
+ def verify_api_key(authorization: str | None) -> bool:
89
+ if not authorization:
90
+ return False
91
+
92
+ parts = authorization.split(" ", 1)
93
+
94
+ if len(parts) != 2:
95
+ return False
96
+
97
+ scheme, supplied_key = parts
98
+
99
+ if scheme.lower() != "bearer":
100
+ return False
101
+
102
+ if not supplied_key:
103
+ return False
104
+
105
+ return any(
106
+ secrets.compare_digest(supplied_key, valid_key)
107
+ for valid_key in API_KEYS
108
  )
109
 
110
 
111
  async def authenticate(
112
+ authorization: str | None = Header(default=None),
113
  ):
114
+ if not verify_api_key(authorization):
115
  raise HTTPException(
116
  status_code=401,
117
+ detail={
118
+ "error": {
119
+ "message": "Invalid or missing API key.",
120
+ "type": "authentication_error",
121
+ "code": "invalid_api_key",
122
+ }
123
+ },
124
+ headers={"WWW-Authenticate": "Bearer"},
125
  )
126
 
 
127
 
128
+ # ============================================================
129
+ # GRADIO SERVER
130
+ # ============================================================
131
+
132
+ app = Server(
133
+ title="Nova AI",
134
+ summary="Nova AI OpenAI-compatible API",
135
+ description="Nova AI language model API.",
136
+ version="1.0.0",
137
+ )
138
+
139
+
140
+ # Protect the additional Gradio inference endpoints.
141
+ # Do NOT apply authentication globally: Gradio needs its
142
+ # internal startup and configuration routes to remain accessible.
143
 
144
+ @app.middleware("http")
145
+ async def protect_gradio_inference(request: Request, call_next):
146
+
147
+ path = request.url.path
148
+
149
+ protected_paths = (
150
+ "/gradio_api/call/generate",
151
+ "/gradio_api/call/generate_stream",
152
+ "/gradio_api/run/generate",
153
+ "/gradio_api/run/generate_stream",
154
  )
155
 
156
+ requires_auth = any(
157
+ path == prefix or path.startswith(prefix + "/")
158
+ for prefix in protected_paths
159
+ )
160
+
161
+ if requires_auth:
162
+ authorization = request.headers.get("Authorization")
163
+
164
+ if not verify_api_key(authorization):
165
+ return JSONResponse(
166
+ status_code=401,
167
+ content={
168
+ "error": {
169
+ "message": "Invalid or missing API key.",
170
+ "type": "authentication_error",
171
+ "code": "invalid_api_key",
172
+ }
173
+ },
174
+ headers={"WWW-Authenticate": "Bearer"},
175
+ )
176
 
177
+ return await call_next(request)
178
 
179
 
180
+ # ============================================================
181
+ # MODEL LOADING
182
+ # ============================================================
183
 
184
+ print("Loading Nova AI...")
185
+ print(f"Model: {MODEL_ID}")
186
 
187
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
188
 
189
+ if torch.cuda.is_available():
190
+ if torch.cuda.is_bf16_supported():
191
+ MODEL_DTYPE = torch.bfloat16
192
+ else:
193
+ MODEL_DTYPE = torch.float16
194
+ else:
195
+ MODEL_DTYPE = torch.float32
196
 
197
  model = AutoModelForCausalLM.from_pretrained(
198
  MODEL_ID,
199
+ torch_dtype=MODEL_DTYPE,
200
+ device_map="auto",
201
  )
202
 
203
  model.eval()
204
 
205
+ if tokenizer.pad_token_id is None:
206
+ tokenizer.pad_token = tokenizer.eos_token
 
 
 
 
207
 
208
+ print("Nova AI model loaded successfully.")
 
 
 
 
 
 
209
 
210
 
211
+ # ============================================================
212
  # REQUEST MODEL
213
+ # ============================================================
214
 
215
  class ChatRequest(BaseModel):
 
 
 
 
 
216
 
217
+ model: str = PUBLIC_MODEL_NAME
218
 
219
+ messages: list[dict[str, Any]]
 
 
220
 
221
+ temperature: float = Field(
222
+ default=0.7,
223
+ ge=0.0,
224
+ le=2.0,
225
+ )
226
 
227
+ max_tokens: int = Field(
228
+ default=512,
229
+ ge=1,
230
+ le=MAX_OUTPUT_TOKENS,
 
 
 
231
  )
232
 
233
+ stream: bool = False
234
+
235
+
236
+ # ============================================================
237
+ # MESSAGE PROCESSING
238
+ # ============================================================
239
+
240
+ def prepare_messages(
241
+ messages: list[dict[str, Any]],
242
+ ) -> list[dict[str, str]]:
243
+
244
+ cleaned_messages = []
245
+
246
+ for message in messages:
247
+
248
+ role = message.get("role")
249
+ content = message.get("content")
250
+
251
+ if role not in ("system", "user", "assistant"):
252
+ raise HTTPException(
253
+ status_code=400,
254
+ detail=f"Unsupported message role: {role}",
255
+ )
256
+
257
+ if not isinstance(content, str):
258
+ raise HTTPException(
259
+ status_code=400,
260
+ detail="Message content must be a string.",
261
+ )
262
+
263
+ cleaned_messages.append({
264
+ "role": role,
265
+ "content": content,
266
+ })
267
+
268
+ if not cleaned_messages:
269
+ raise HTTPException(
270
+ status_code=400,
271
+ detail="At least one message is required.",
272
+ )
273
+
274
+ # Add Nova's system prompt.
275
+ if cleaned_messages[0]["role"] == "system":
276
+
277
+ cleaned_messages[0]["content"] = (
278
  NOVA_SYSTEM_PROMPT
279
+ + "\n\n"
280
+ + cleaned_messages[0]["content"]
281
  )
282
+
283
  else:
284
+
285
+ cleaned_messages.insert(
286
  0,
287
  {
288
  "role": "system",
289
+ "content": NOVA_SYSTEM_PROMPT,
290
+ },
291
  )
292
 
293
+ return cleaned_messages
 
294
 
 
295
 
296
+ def prepare_inputs(messages: list[dict[str, str]]):
297
 
298
  prompt = tokenizer.apply_chat_template(
299
  messages,
300
  tokenize=False,
301
+ add_generation_prompt=True,
302
  )
303
 
304
+ inputs = tokenizer(
305
  prompt,
306
+ return_tensors="pt",
307
+ truncation=True,
308
+ max_length=MAX_CONTEXT_TOKENS,
309
+ )
310
+
311
+ return inputs.to(model.device)
312
 
313
 
314
+ # ============================================================
315
+ # ZERO GPU: NON-STREAMING GENERATION
316
+ # ============================================================
317
 
318
  @spaces.GPU(duration=120)
319
  def gpu_generate(
320
+ messages: list[dict[str, str]],
321
  temperature: float,
322
+ max_tokens: int,
323
+ ) -> tuple[str, int, int]:
324
 
325
  inputs = prepare_inputs(messages)
326
 
327
+ prompt_tokens = inputs["input_ids"].shape[-1]
328
+
329
+ generation_config = {
330
+ "max_new_tokens": max_tokens,
331
+ "pad_token_id": tokenizer.pad_token_id,
332
+ "eos_token_id": tokenizer.eos_token_id,
333
+ "use_cache": True,
334
+ }
335
+
336
+ if temperature > 0:
337
+ generation_config.update({
338
+ "do_sample": True,
339
+ "temperature": temperature,
340
+ "top_p": 0.9,
341
+ })
342
+ else:
343
+ generation_config["do_sample"] = False
344
+
345
  with torch.inference_mode():
346
 
347
  output = model.generate(
348
  **inputs,
349
+ **generation_config,
 
 
 
350
  )
351
 
352
+ generated_tokens = output[0][prompt_tokens:]
 
 
 
 
 
 
 
 
 
 
 
353
 
354
+ content = tokenizer.decode(
355
+ generated_tokens,
356
+ skip_special_tokens=True,
357
+ )
358
 
359
+ completion_tokens = len(generated_tokens)
 
 
 
 
 
 
 
 
 
360
 
361
+ return (
362
+ content.strip(),
363
+ prompt_tokens,
364
+ completion_tokens,
365
  )
366
 
367
 
368
+ # ============================================================
369
+ # ZERO GPU: STREAMING GENERATION
370
+ # ============================================================
371
 
372
  @spaces.GPU(duration=120)
373
  def gpu_generate_stream(
374
+ messages: list[dict[str, str]],
375
  temperature: float,
376
+ max_tokens: int,
377
  ) -> Iterator[str]:
378
 
379
  inputs = prepare_inputs(messages)
 
382
  tokenizer,
383
  skip_prompt=True,
384
  skip_special_tokens=True,
385
+ timeout=120,
386
  )
387
 
388
+ generation_config = {
389
+ **inputs,
390
+ "streamer": streamer,
391
+ "max_new_tokens": max_tokens,
392
+ "pad_token_id": tokenizer.pad_token_id,
393
+ "eos_token_id": tokenizer.eos_token_id,
394
+ "use_cache": True,
395
+ }
396
+
397
+ if temperature > 0:
398
+ generation_config.update({
399
+ "do_sample": True,
400
+ "temperature": temperature,
401
+ "top_p": 0.9,
402
+ })
403
+ else:
404
+ generation_config["do_sample"] = False
405
+
406
  errors = []
407
 
408
  def generation_worker():
409
 
410
  try:
411
  with torch.inference_mode():
412
+ model.generate(**generation_config)
 
 
 
 
 
 
 
 
413
 
414
  except Exception as error:
415
  errors.append(error)
 
417
 
418
  worker = threading.Thread(
419
  target=generation_worker,
420
+ daemon=True,
421
  )
422
 
423
  worker.start()
424
 
425
+ for text_chunk in streamer:
426
+
427
+ if text_chunk:
428
+ yield text_chunk
429
 
430
  worker.join()
431
 
432
  if errors:
433
+ raise RuntimeError(
434
+ f"Generation failed: {errors[0]}"
435
+ )
436
+
437
+
438
+ # ============================================================
439
+ # PRIVATE GRADIO ENDPOINTS
440
+ # Required for ZeroGPU registration.
441
+ # ============================================================
442
+
443
+ @app.api(
444
+ name="generate",
445
+ concurrency_limit=1,
446
+ time_limit=120,
447
+ api_visibility="private",
448
+ )
449
+ def generate(
450
+ messages: list[dict[str, str]],
451
+ temperature: float = 0.7,
452
+ max_tokens: int = 512,
453
+ ) -> str:
454
+
455
+ content, _, _ = gpu_generate(
456
+ messages,
457
+ temperature,
458
+ max_tokens,
459
+ )
460
+
461
+ return content
462
 
463
 
464
  @app.api(
465
  name="generate_stream",
466
  concurrency_limit=1,
467
  time_limit=120,
468
+ stream_every=0.05,
469
+ api_visibility="private",
470
  )
471
  def generate_stream(
472
+ messages: list[dict[str, str]],
473
  temperature: float = 0.7,
474
+ max_tokens: int = 512,
475
  ) -> Iterator[str]:
476
 
477
  yield from gpu_generate_stream(
478
  messages,
479
  temperature,
480
+ max_tokens,
481
  )
482
 
483
 
484
+ # ============================================================
485
+ # OPENAI-COMPATIBLE CHAT COMPLETIONS API
486
+ # ============================================================
487
 
488
+ @app.post(
489
+ "/v1/chat/completions",
490
+ dependencies=[Depends(authenticate)],
491
+ )
492
  async def chat_completions(request: ChatRequest):
493
 
494
+ if request.model not in (
495
+ PUBLIC_MODEL_NAME,
496
+ MODEL_ID,
497
+ ):
 
 
 
498
  raise HTTPException(
499
  status_code=404,
500
+ detail=f"Model '{request.model}' not found.",
501
  )
502
 
503
+ messages = prepare_messages(request.messages)
504
 
505
+ completion_id = "chatcmpl-" + uuid.uuid4().hex
 
 
 
 
 
 
 
 
506
 
507
+ created = int(time.time())
 
 
 
 
508
 
509
+ # --------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  # STREAMING RESPONSE
511
+ # --------------------------------------------------------
512
 
513
  if request.stream:
514
 
 
 
 
 
 
 
 
 
 
 
 
515
  def stream_response():
516
 
517
+ first_chunk = {
518
  "id": completion_id,
519
  "object": "chat.completion.chunk",
520
  "created": created,
521
  "model": PUBLIC_MODEL_NAME,
522
+ "choices": [
523
+ {
524
+ "index": 0,
525
+ "delta": {
526
+ "role": "assistant",
527
+ },
528
+ "finish_reason": None,
529
+ }
530
+ ],
531
+ }
532
+
533
+ yield (
534
+ "data: "
535
+ + json.dumps(first_chunk)
536
+ + "\n\n"
537
+ )
538
 
539
  try:
540
 
541
+ for token in gpu_generate_stream(
542
+ messages,
543
+ request.temperature,
544
+ request.max_tokens,
545
  ):
546
 
547
+ chunk = {
548
  "id": completion_id,
549
  "object": "chat.completion.chunk",
550
  "created": created,
551
  "model": PUBLIC_MODEL_NAME,
552
+ "choices": [
553
+ {
554
+ "index": 0,
555
+ "delta": {
556
+ "content": token,
557
+ },
558
+ "finish_reason": None,
559
+ }
560
+ ],
561
+ }
562
+
563
+ yield (
564
+ "data: "
565
+ + json.dumps(chunk)
566
+ + "\n\n"
567
+ )
568
+
569
+ final_chunk = {
570
  "id": completion_id,
571
  "object": "chat.completion.chunk",
572
  "created": created,
573
  "model": PUBLIC_MODEL_NAME,
574
+ "choices": [
575
+ {
576
+ "index": 0,
577
+ "delta": {},
578
+ "finish_reason": "stop",
579
+ }
580
+ ],
581
+ }
582
+
583
+ yield (
584
+ "data: "
585
+ + json.dumps(final_chunk)
586
+ + "\n\n"
587
+ )
588
+
589
+ yield "data: [DONE]\n\n"
590
 
591
  except Exception as error:
592
 
593
+ error_chunk = {
594
  "error": {
595
  "message": str(error),
596
+ "type": "server_error",
597
  }
598
+ }
599
+
600
+ yield (
601
+ "data: "
602
+ + json.dumps(error_chunk)
603
+ + "\n\n"
604
+ )
605
 
606
+ yield "data: [DONE]\n\n"
607
 
608
  return StreamingResponse(
609
  stream_response(),
 
611
  headers={
612
  "Cache-Control": "no-cache",
613
  "Connection": "keep-alive",
614
+ "X-Accel-Buffering": "no",
615
+ },
616
  )
617
 
618
+ # --------------------------------------------------------
619
+ # NORMAL NON-STREAMING RESPONSE
620
+ # --------------------------------------------------------
621
 
622
+ try:
623
+
624
+ content, prompt_tokens, completion_tokens = gpu_generate(
625
+ messages,
626
+ request.temperature,
627
+ request.max_tokens,
628
+ )
629
+
630
+ except Exception as error:
631
 
632
+ raise HTTPException(
633
+ status_code=500,
634
+ detail=f"Generation failed: {str(error)}",
635
+ )
636
 
637
  return {
638
+ "id": completion_id,
639
  "object": "chat.completion",
640
+ "created": created,
641
  "model": PUBLIC_MODEL_NAME,
642
+ "choices": [
643
+ {
644
+ "index": 0,
645
+ "message": {
646
+ "role": "assistant",
647
+ "content": content,
648
+ },
649
+ "finish_reason": "stop",
650
+ }
651
+ ],
652
  "usage": {
653
  "prompt_tokens": prompt_tokens,
654
  "completion_tokens": completion_tokens,
655
  "total_tokens": (
656
  prompt_tokens + completion_tokens
657
+ ),
658
+ },
659
  }
660
 
661
 
662
+ # ============================================================
663
  # MODEL LIST
664
+ # ============================================================
665
 
666
+ @app.get(
667
+ "/v1/models",
668
+ dependencies=[Depends(authenticate)],
669
+ )
670
  def models():
671
 
672
  return {
673
  "object": "list",
674
+ "data": [
675
+ {
676
+ "id": PUBLIC_MODEL_NAME,
677
+ "object": "model",
678
+ "created": int(time.time()),
679
+ "owned_by": "nova-ai",
680
+ }
681
+ ],
682
  }
683
 
684
 
685
+ # ============================================================
686
+ # PUBLIC HEALTH CHECK
687
+ # ============================================================
688
 
689
  @app.get("/")
690
  def home():
 
693
  "name": "Nova AI",
694
  "status": "online",
695
  "model": PUBLIC_MODEL_NAME,
696
+ "base_model": MODEL_ID,
697
+ "api": "/v1",
698
+ "endpoints": {
699
+ "chat": "/v1/chat/completions",
700
+ "models": "/v1/models",
701
+ },
702
+ "features": {
703
+ "streaming": True,
704
+ "api_key_authentication": True,
705
+ "openai_compatible": True,
706
+ },
707
  }
708
 
709
 
710
+ # ============================================================
711
+ # START SERVER
712
+ # ============================================================
713
 
714
  if __name__ == "__main__":
715
+
716
+ print("Starting Nova AI API...")
717
+
718
  app.launch()