File size: 17,287 Bytes
0cfbe4a
735aa73
f7dd641
655af59
 
735aa73
24f7193
f7dd641
655af59
f7dd641
735aa73
 
148cdf4
3e84434
 
 
f7dd641
3e84434
f7dd641
 
 
 
2aaacbe
0cfbe4a
f7dd641
 
 
735aa73
 
 
 
 
 
 
 
f7dd641
 
 
735aa73
f7dd641
 
 
 
 
 
 
 
 
 
 
735aa73
 
 
f7dd641
 
 
735aa73
f7dd641
 
735aa73
f7dd641
735aa73
f7dd641
735aa73
f7dd641
 
735aa73
f7dd641
 
 
 
 
 
 
 
 
735aa73
 
f7dd641
 
 
735aa73
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735aa73
 
 
 
f7dd641
735aa73
f7dd641
735aa73
 
f7dd641
 
 
 
 
 
 
 
735aa73
 
 
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735aa73
f7dd641
 
 
 
 
 
 
 
 
 
735aa73
 
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735aa73
f7dd641
735aa73
 
f7dd641
 
 
735aa73
f7dd641
 
735aa73
0cfbe4a
92fad90
f7dd641
 
 
 
 
 
 
735aa73
2aaacbe
0cfbe4a
f7dd641
 
2aaacbe
 
735aa73
 
f7dd641
 
735aa73
f7dd641
148cdf4
 
f7dd641
735aa73
f7dd641
3e84434
148cdf4
 
f7dd641
148cdf4
f7dd641
735aa73
f7dd641
 
 
 
 
735aa73
f7dd641
 
 
 
735aa73
 
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735aa73
f7dd641
 
735aa73
f7dd641
735aa73
f7dd641
 
735aa73
 
 
f7dd641
 
735aa73
 
f7dd641
3e84434
735aa73
f7dd641
735aa73
0cfbe4a
655af59
0cfbe4a
f7dd641
2aaacbe
 
f7dd641
655af59
f7dd641
 
 
 
 
 
0cfbe4a
24f7193
f7dd641
 
 
3e84434
24f7193
735aa73
f7dd641
735aa73
f7dd641
 
24f7193
 
 
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655af59
735aa73
0cfbe4a
 
f7dd641
0cfbe4a
 
f7dd641
0cfbe4a
f7dd641
 
 
 
655af59
f7dd641
735aa73
f7dd641
 
 
 
735aa73
 
 
f7dd641
 
 
735aa73
 
 
f7dd641
735aa73
f7dd641
735aa73
0cfbe4a
24f7193
655af59
24f7193
 
 
 
f7dd641
24f7193
655af59
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f7193
 
735aa73
 
24f7193
 
f7dd641
735aa73
24f7193
 
 
 
 
735aa73
f7dd641
24f7193
3e84434
24f7193
 
f7dd641
 
 
 
24f7193
 
 
 
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f7193
 
735aa73
 
 
 
f7dd641
 
735aa73
 
f7dd641
735aa73
f7dd641
735aa73
 
 
 
 
f7dd641
735aa73
 
 
f7dd641
 
 
3e84434
f7dd641
 
 
 
24f7193
655af59
f7dd641
 
 
 
3e84434
735aa73
f7dd641
3e84434
655af59
f7dd641
735aa73
f7dd641
735aa73
f7dd641
735aa73
f7dd641
735aa73
f7dd641
3e84434
24f7193
 
 
 
f7dd641
24f7193
 
 
735aa73
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f7193
735aa73
 
f7dd641
 
 
 
735aa73
 
f7dd641
735aa73
 
 
 
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f7193
 
 
735aa73
f7dd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f7193
735aa73
 
f7dd641
735aa73
 
f7dd641
735aa73
f7dd641
 
 
 
 
 
 
24f7193
f7dd641
24f7193
 
 
 
 
 
 
f7dd641
 
24f7193
 
f7dd641
 
 
3e84434
f7dd641
 
 
 
 
 
 
 
 
655af59
f7dd641
 
 
 
24f7193
 
f7dd641
24f7193
f7dd641
735aa73
f7dd641
 
 
 
 
 
 
 
 
 
24f7193
 
 
3e84434
 
f7dd641
 
24f7193
148cdf4
0cfbe4a
f7dd641
3e84434
f7dd641
3e84434
f7dd641
 
 
 
148cdf4
735aa73
148cdf4
 
f7dd641
 
 
 
 
 
 
 
148cdf4
655af59
 
f7dd641
 
 
735aa73
 
 
 
 
 
 
 
f7dd641
 
 
 
 
 
 
 
 
 
 
735aa73
 
 
f7dd641
 
 
3e84434
2aaacbe
f7dd641
 
 
148cdf4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

import os
import json
import time
import uuid
import secrets
import threading
from typing import Any, Iterator

import torch
import spaces

from gradio import Server
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TextIteratorStreamer,
)

from fastapi import Depends, Header, HTTPException, Request
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel, Field


# ============================================================
# CONFIGURATION
# ============================================================

MODEL_ID = os.getenv(
    "MODEL_ID",
    "Qwen/Qwen2.5-3B-Instruct"
)

PUBLIC_MODEL_NAME = "nova-ai"

MAX_CONTEXT_TOKENS = 4096
MAX_OUTPUT_TOKENS = 4096

NOVA_SYSTEM_PROMPT = """
You are Nova AI, an intelligent AI assistant developed and
operated by the Nova AI project.

Your name is Nova AI. Do not identify yourself as ChatGPT
or another AI brand.

Be friendly, intelligent, conversational, and helpful.
Give accurate answers, explain difficult concepts clearly,
and assist with coding, reasoning, writing, and problem-solving.

Never invent facts or claim capabilities you do not have.
"""


# ============================================================
# API KEY MANAGEMENT
# ============================================================

def load_api_keys() -> list[str]:
    keys = []

    single_key = os.getenv("NOVA_API_KEY", "").strip()

    multiple_keys = os.getenv("NOVA_API_KEYS", "").strip()

    if single_key:
        keys.append(single_key)

    if multiple_keys:
        keys.extend(
            key.strip()
            for key in multiple_keys.split(",")
            if key.strip()
        )

    # Remove duplicates
    return list(set(keys))


API_KEYS = load_api_keys()

if not API_KEYS:
    raise RuntimeError(
        "No API keys configured. Set NOVA_API_KEY or NOVA_API_KEYS "
        "in your Hugging Face Space secrets."
    )


def verify_api_key(authorization: str | None) -> bool:
    if not authorization:
        return False

    parts = authorization.split(" ", 1)

    if len(parts) != 2:
        return False

    scheme, supplied_key = parts

    if scheme.lower() != "bearer":
        return False

    if not supplied_key:
        return False

    return any(
        secrets.compare_digest(supplied_key, valid_key)
        for valid_key in API_KEYS
    )


async def authenticate(
    authorization: str | None = Header(default=None),
):
    if not verify_api_key(authorization):
        raise HTTPException(
            status_code=401,
            detail={
                "error": {
                    "message": "Invalid or missing API key.",
                    "type": "authentication_error",
                    "code": "invalid_api_key",
                }
            },
            headers={"WWW-Authenticate": "Bearer"},
        )


# ============================================================
# GRADIO SERVER
# ============================================================

app = Server(
    title="Nova AI",
    summary="Nova AI OpenAI-compatible API",
    description="Nova AI language model API.",
    version="1.0.0",
)


# Protect the additional Gradio inference endpoints.
# Do NOT apply authentication globally: Gradio needs its
# internal startup and configuration routes to remain accessible.

@app.middleware("http")
async def protect_gradio_inference(request: Request, call_next):

    path = request.url.path

    protected_paths = (
        "/gradio_api/call/generate",
        "/gradio_api/call/generate_stream",
        "/gradio_api/run/generate",
        "/gradio_api/run/generate_stream",
    )

    requires_auth = any(
        path == prefix or path.startswith(prefix + "/")
        for prefix in protected_paths
    )

    if requires_auth:
        authorization = request.headers.get("Authorization")

        if not verify_api_key(authorization):
            return JSONResponse(
                status_code=401,
                content={
                    "error": {
                        "message": "Invalid or missing API key.",
                        "type": "authentication_error",
                        "code": "invalid_api_key",
                    }
                },
                headers={"WWW-Authenticate": "Bearer"},
            )

    return await call_next(request)


# ============================================================
# MODEL LOADING
# ============================================================

print("Loading Nova AI...")
print(f"Model: {MODEL_ID}")

tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)

if torch.cuda.is_available():
    if torch.cuda.is_bf16_supported():
        MODEL_DTYPE = torch.bfloat16
    else:
        MODEL_DTYPE = torch.float16
else:
    MODEL_DTYPE = torch.float32

model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype=MODEL_DTYPE,
    device_map="auto",
)

model.eval()

if tokenizer.pad_token_id is None:
    tokenizer.pad_token = tokenizer.eos_token

print("Nova AI model loaded successfully.")


# ============================================================
# REQUEST MODEL
# ============================================================

class ChatRequest(BaseModel):

    model: str = PUBLIC_MODEL_NAME

    messages: list[dict[str, Any]]

    temperature: float = Field(
        default=0.7,
        ge=0.0,
        le=2.0,
    )

    max_tokens: int = Field(
        default=512,
        ge=1,
        le=MAX_OUTPUT_TOKENS,
    )

    stream: bool = False


# ============================================================
# MESSAGE PROCESSING
# ============================================================

def prepare_messages(
    messages: list[dict[str, Any]],
) -> list[dict[str, str]]:

    cleaned_messages = []

    for message in messages:

        role = message.get("role")
        content = message.get("content")

        if role not in ("system", "user", "assistant"):
            raise HTTPException(
                status_code=400,
                detail=f"Unsupported message role: {role}",
            )

        if not isinstance(content, str):
            raise HTTPException(
                status_code=400,
                detail="Message content must be a string.",
            )

        cleaned_messages.append({
            "role": role,
            "content": content,
        })

    if not cleaned_messages:
        raise HTTPException(
            status_code=400,
            detail="At least one message is required.",
        )

    # Add Nova's system prompt.
    if cleaned_messages[0]["role"] == "system":

        cleaned_messages[0]["content"] = (
            NOVA_SYSTEM_PROMPT
            + "\n\n"
            + cleaned_messages[0]["content"]
        )

    else:

        cleaned_messages.insert(
            0,
            {
                "role": "system",
                "content": NOVA_SYSTEM_PROMPT,
            },
        )

    return cleaned_messages


def prepare_inputs(messages: list[dict[str, str]]):

    prompt = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
    )

    inputs = tokenizer(
        prompt,
        return_tensors="pt",
        truncation=True,
        max_length=MAX_CONTEXT_TOKENS,
    )

    return inputs.to(model.device)


# ============================================================
# ZERO GPU: NON-STREAMING GENERATION
# ============================================================

@spaces.GPU(duration=120)
def gpu_generate(
    messages: list[dict[str, str]],
    temperature: float,
    max_tokens: int,
) -> tuple[str, int, int]:

    inputs = prepare_inputs(messages)

    prompt_tokens = inputs["input_ids"].shape[-1]

    generation_config = {
        "max_new_tokens": max_tokens,
        "pad_token_id": tokenizer.pad_token_id,
        "eos_token_id": tokenizer.eos_token_id,
        "use_cache": True,
    }

    if temperature > 0:
        generation_config.update({
            "do_sample": True,
            "temperature": temperature,
            "top_p": 0.9,
        })
    else:
        generation_config["do_sample"] = False

    with torch.inference_mode():

        output = model.generate(
            **inputs,
            **generation_config,
        )

    generated_tokens = output[0][prompt_tokens:]

    content = tokenizer.decode(
        generated_tokens,
        skip_special_tokens=True,
    )

    completion_tokens = len(generated_tokens)

    return (
        content.strip(),
        prompt_tokens,
        completion_tokens,
    )


# ============================================================
# ZERO GPU: STREAMING GENERATION
# ============================================================

@spaces.GPU(duration=120)
def gpu_generate_stream(
    messages: list[dict[str, str]],
    temperature: float,
    max_tokens: int,
) -> Iterator[str]:

    inputs = prepare_inputs(messages)

    streamer = TextIteratorStreamer(
        tokenizer,
        skip_prompt=True,
        skip_special_tokens=True,
        timeout=120,
    )

    generation_config = {
        **inputs,
        "streamer": streamer,
        "max_new_tokens": max_tokens,
        "pad_token_id": tokenizer.pad_token_id,
        "eos_token_id": tokenizer.eos_token_id,
        "use_cache": True,
    }

    if temperature > 0:
        generation_config.update({
            "do_sample": True,
            "temperature": temperature,
            "top_p": 0.9,
        })
    else:
        generation_config["do_sample"] = False

    errors = []

    def generation_worker():

        try:
            with torch.inference_mode():
                model.generate(**generation_config)

        except Exception as error:
            errors.append(error)
            streamer.end()

    worker = threading.Thread(
        target=generation_worker,
        daemon=True,
    )

    worker.start()

    for text_chunk in streamer:

        if text_chunk:
            yield text_chunk

    worker.join()

    if errors:
        raise RuntimeError(
            f"Generation failed: {errors[0]}"
        )


# ============================================================
# PRIVATE GRADIO ENDPOINTS
# Required for ZeroGPU registration.
# ============================================================

@app.api(
    name="generate",
    concurrency_limit=1,
    time_limit=120,
    api_visibility="private",
)
def generate(
    messages: list[dict[str, str]],
    temperature: float = 0.7,
    max_tokens: int = 512,
) -> str:

    content, _, _ = gpu_generate(
        messages,
        temperature,
        max_tokens,
    )

    return content


@app.api(
    name="generate_stream",
    concurrency_limit=1,
    time_limit=120,
    stream_every=0.05,
    api_visibility="private",
)
def generate_stream(
    messages: list[dict[str, str]],
    temperature: float = 0.7,
    max_tokens: int = 512,
) -> Iterator[str]:

    yield from gpu_generate_stream(
        messages,
        temperature,
        max_tokens,
    )


# ============================================================
# OPENAI-COMPATIBLE CHAT COMPLETIONS API
# ============================================================

@app.post(
    "/v1/chat/completions",
    dependencies=[Depends(authenticate)],
)
async def chat_completions(request: ChatRequest):

    if request.model not in (
        PUBLIC_MODEL_NAME,
        MODEL_ID,
    ):
        raise HTTPException(
            status_code=404,
            detail=f"Model '{request.model}' not found.",
        )

    messages = prepare_messages(request.messages)

    completion_id = "chatcmpl-" + uuid.uuid4().hex

    created = int(time.time())

    # --------------------------------------------------------
    # STREAMING RESPONSE
    # --------------------------------------------------------

    if request.stream:

        def stream_response():

            first_chunk = {
                "id": completion_id,
                "object": "chat.completion.chunk",
                "created": created,
                "model": PUBLIC_MODEL_NAME,
                "choices": [
                    {
                        "index": 0,
                        "delta": {
                            "role": "assistant",
                        },
                        "finish_reason": None,
                    }
                ],
            }

            yield (
                "data: "
                + json.dumps(first_chunk)
                + "\n\n"
            )

            try:

                for token in gpu_generate_stream(
                    messages,
                    request.temperature,
                    request.max_tokens,
                ):

                    chunk = {
                        "id": completion_id,
                        "object": "chat.completion.chunk",
                        "created": created,
                        "model": PUBLIC_MODEL_NAME,
                        "choices": [
                            {
                                "index": 0,
                                "delta": {
                                    "content": token,
                                },
                                "finish_reason": None,
                            }
                        ],
                    }

                    yield (
                        "data: "
                        + json.dumps(chunk)
                        + "\n\n"
                    )

                final_chunk = {
                    "id": completion_id,
                    "object": "chat.completion.chunk",
                    "created": created,
                    "model": PUBLIC_MODEL_NAME,
                    "choices": [
                        {
                            "index": 0,
                            "delta": {},
                            "finish_reason": "stop",
                        }
                    ],
                }

                yield (
                    "data: "
                    + json.dumps(final_chunk)
                    + "\n\n"
                )

                yield "data: [DONE]\n\n"

            except Exception as error:

                error_chunk = {
                    "error": {
                        "message": str(error),
                        "type": "server_error",
                    }
                }

                yield (
                    "data: "
                    + json.dumps(error_chunk)
                    + "\n\n"
                )

                yield "data: [DONE]\n\n"

        return StreamingResponse(
            stream_response(),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "X-Accel-Buffering": "no",
            },
        )

    # --------------------------------------------------------
    # NORMAL NON-STREAMING RESPONSE
    # --------------------------------------------------------

    try:

        content, prompt_tokens, completion_tokens = gpu_generate(
            messages,
            request.temperature,
            request.max_tokens,
        )

    except Exception as error:

        raise HTTPException(
            status_code=500,
            detail=f"Generation failed: {str(error)}",
        )

    return {
        "id": completion_id,
        "object": "chat.completion",
        "created": created,
        "model": PUBLIC_MODEL_NAME,
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": content,
                },
                "finish_reason": "stop",
            }
        ],
        "usage": {
            "prompt_tokens": prompt_tokens,
            "completion_tokens": completion_tokens,
            "total_tokens": (
                prompt_tokens + completion_tokens
            ),
        },
    }


# ============================================================
# MODEL LIST
# ============================================================

@app.get(
    "/v1/models",
    dependencies=[Depends(authenticate)],
)
def models():

    return {
        "object": "list",
        "data": [
            {
                "id": PUBLIC_MODEL_NAME,
                "object": "model",
                "created": int(time.time()),
                "owned_by": "nova-ai",
            }
        ],
    }


# ============================================================
# PUBLIC HEALTH CHECK
# ============================================================

@app.get("/")
def home():

    return {
        "name": "Nova AI",
        "status": "online",
        "model": PUBLIC_MODEL_NAME,
        "base_model": MODEL_ID,
        "api": "/v1",
        "endpoints": {
            "chat": "/v1/chat/completions",
            "models": "/v1/models",
        },
        "features": {
            "streaming": True,
            "api_key_authentication": True,
            "openai_compatible": True,
        },
    }


# ============================================================
# START SERVER
# ============================================================

if __name__ == "__main__":

    print("Starting Nova AI API...")

    app.launch()