nova-ai / app.py
coder5809's picture
Update app.py
f7dd641 verified
Raw History Blame Contribute Delete
17.3 kB
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()