Upload folder using huggingface_hub
Browse files- .gitignore +1 -0
- __pycache__/main.cpython-312.pyc +0 -0
- main.py +191 -67
- static/app.js +84 -6
- static/index.html +11 -4
- static/style.css +42 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/__pycache__
|
__pycache__/main.cpython-312.pyc
CHANGED
|
Binary files a/__pycache__/main.cpython-312.pyc and b/__pycache__/main.cpython-312.pyc differ
|
|
|
main.py
CHANGED
|
@@ -5,6 +5,7 @@ import queue
|
|
| 5 |
import asyncio
|
| 6 |
import threading
|
| 7 |
import requests
|
|
|
|
| 8 |
from fastapi import FastAPI, Request
|
| 9 |
from fastapi.responses import JSONResponse, StreamingResponse, FileResponse
|
| 10 |
from fastapi.staticfiles import StaticFiles
|
|
@@ -14,7 +15,7 @@ from typing import List, Dict, Any, Optional
|
|
| 14 |
from llama_cpp import Llama
|
| 15 |
|
| 16 |
# Setup app
|
| 17 |
-
app = FastAPI(title="
|
| 18 |
|
| 19 |
# Add CORS Middleware to enable external API requests from other domains
|
| 20 |
app.add_middleware(
|
|
@@ -25,27 +26,53 @@ app.add_middleware(
|
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
# Configuration from Environment Variables
|
| 29 |
-
MODEL_REPO = os.environ.get("MODEL_REPO", "mradermacher/Mythos-nano-GGUF")
|
| 30 |
-
MODEL_FILE = os.environ.get("MODEL_FILE", "Mythos-nano.Q4_K_M.gguf")
|
| 31 |
CACHE_DIR = os.environ.get("HF_HOME", os.path.join(os.path.dirname(os.path.abspath(__file__)), ".cache"))
|
| 32 |
N_CTX = int(os.environ.get("N_CTX", "4096"))
|
| 33 |
NUM_THREADS = int(os.environ.get("NUM_THREADS", "2"))
|
| 34 |
N_GPU_LAYERS = int(os.environ.get("N_GPU_LAYERS", "0"))
|
| 35 |
|
| 36 |
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 37 |
-
model_path = os.path.join(CACHE_DIR, MODEL_FILE)
|
| 38 |
-
download_url = f"https://huggingface.co/{MODEL_REPO}/resolve/main/{MODEL_FILE}"
|
| 39 |
|
| 40 |
# Global model state
|
| 41 |
status = {
|
| 42 |
"state": "initializing", # initializing, downloading, loading, ready, error
|
|
|
|
|
|
|
| 43 |
"progress": 0.0,
|
| 44 |
"speed_mbps": 0.0,
|
| 45 |
"error": None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
"model_info": {
|
| 47 |
-
"repo": MODEL_REPO,
|
| 48 |
-
"filename": MODEL_FILE,
|
| 49 |
"ctx_len": N_CTX,
|
| 50 |
"threads": NUM_THREADS,
|
| 51 |
"gpu_layers": N_GPU_LAYERS
|
|
@@ -53,78 +80,125 @@ status = {
|
|
| 53 |
}
|
| 54 |
|
| 55 |
llm = None
|
|
|
|
| 56 |
|
| 57 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
global status, llm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
try:
|
| 60 |
-
|
| 61 |
-
print(f"Loading model from {model_path}...")
|
| 62 |
llm = Llama(
|
| 63 |
-
model_path=
|
| 64 |
n_ctx=N_CTX,
|
| 65 |
n_threads=NUM_THREADS,
|
| 66 |
n_gpu_layers=N_GPU_LAYERS
|
| 67 |
)
|
|
|
|
|
|
|
| 68 |
status["state"] = "ready"
|
| 69 |
status["progress"] = 100.0
|
| 70 |
-
print("Model loaded successfully and
|
| 71 |
except Exception as e:
|
| 72 |
status["state"] = "error"
|
| 73 |
-
status["error"] = f"Failed to load model: {str(e)}"
|
| 74 |
print(f"Error loading model: {e}")
|
| 75 |
|
| 76 |
-
def
|
| 77 |
global status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
try:
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
# Fetch metadata using HEAD to get content-length
|
| 81 |
response = requests.head(download_url, allow_redirects=True)
|
| 82 |
if response.status_code != 200:
|
| 83 |
raise Exception(f"Failed to fetch model metadata: HTTP {response.status_code}")
|
| 84 |
|
| 85 |
total_size = int(response.headers.get('content-length', 0))
|
| 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 |
-
if elapsed > 0:
|
| 112 |
-
status["speed_mbps"] = round((downloaded / (1024 * 1024)) / elapsed, 2)
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
|
| 117 |
except Exception as e:
|
| 118 |
status["state"] = "error"
|
| 119 |
-
status["error"] = f"
|
| 120 |
-
print(f"Error in
|
|
|
|
|
|
|
| 121 |
|
| 122 |
@app.on_event("startup")
|
| 123 |
def startup_event():
|
| 124 |
-
#
|
| 125 |
-
threading.Thread(target=
|
| 126 |
|
| 127 |
-
# API Schemas
|
| 128 |
class ChatMessage(BaseModel):
|
| 129 |
role: str
|
| 130 |
content: str
|
|
@@ -137,29 +211,53 @@ class ChatCompletionRequest(BaseModel):
|
|
| 137 |
max_tokens: Optional[int] = 2048
|
| 138 |
stream: Optional[bool] = False
|
| 139 |
|
|
|
|
|
|
|
|
|
|
| 140 |
# Endpoints
|
| 141 |
@app.get("/api/status")
|
| 142 |
def get_status():
|
|
|
|
| 143 |
return status
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
@app.get("/v1/models")
|
| 146 |
def get_models():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
return {
|
| 148 |
"object": "list",
|
| 149 |
-
"data":
|
| 150 |
-
{
|
| 151 |
-
"id": "mythos-nano",
|
| 152 |
-
"object": "model",
|
| 153 |
-
"created": int(time.time()),
|
| 154 |
-
"owned_by": "squ11z1"
|
| 155 |
-
}
|
| 156 |
-
]
|
| 157 |
}
|
| 158 |
|
| 159 |
async def stream_generator(request_dict: dict):
|
| 160 |
q = queue.Queue()
|
| 161 |
|
| 162 |
-
# The producer runs in a separate thread to avoid blocking the event loop
|
| 163 |
def producer():
|
| 164 |
try:
|
| 165 |
response = llm.create_chat_completion(
|
|
@@ -171,7 +269,7 @@ async def stream_generator(request_dict: dict):
|
|
| 171 |
)
|
| 172 |
for chunk in response:
|
| 173 |
q.put(chunk)
|
| 174 |
-
q.put(None)
|
| 175 |
except Exception as e:
|
| 176 |
q.put(e)
|
| 177 |
|
|
@@ -179,7 +277,6 @@ async def stream_generator(request_dict: dict):
|
|
| 179 |
|
| 180 |
loop = asyncio.get_event_loop()
|
| 181 |
while True:
|
| 182 |
-
# Fetch chunk without blocking
|
| 183 |
chunk = await loop.run_in_executor(None, q.get)
|
| 184 |
if chunk is None:
|
| 185 |
break
|
|
@@ -192,12 +289,43 @@ async def stream_generator(request_dict: dict):
|
|
| 192 |
@app.post("/v1/chat/completions")
|
| 193 |
async def chat_completions(request: ChatCompletionRequest):
|
| 194 |
global llm
|
| 195 |
-
|
|
|
|
|
|
|
| 196 |
return JSONResponse(
|
| 197 |
-
status_code=
|
| 198 |
-
content={"error": {"message": f"Model is not
|
| 199 |
)
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
request_dict = request.dict()
|
| 202 |
|
| 203 |
if request.stream:
|
|
@@ -206,7 +334,6 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 206 |
media_type="text/event-stream"
|
| 207 |
)
|
| 208 |
else:
|
| 209 |
-
# Run non-streaming prediction in a separate thread to keep FastAPI responsive
|
| 210 |
loop = asyncio.get_event_loop()
|
| 211 |
try:
|
| 212 |
response = await loop.run_in_executor(
|
|
@@ -229,13 +356,10 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 229 |
# Static file serving
|
| 230 |
@app.get("/")
|
| 231 |
async def read_index():
|
| 232 |
-
# Serves the main UI
|
| 233 |
return FileResponse("static/index.html")
|
| 234 |
|
| 235 |
-
# Mount directory for other assets
|
| 236 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 237 |
|
| 238 |
if __name__ == "__main__":
|
| 239 |
import uvicorn
|
| 240 |
-
# Bind to HF's default port
|
| 241 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 5 |
import asyncio
|
| 6 |
import threading
|
| 7 |
import requests
|
| 8 |
+
import gc
|
| 9 |
from fastapi import FastAPI, Request
|
| 10 |
from fastapi.responses import JSONResponse, StreamingResponse, FileResponse
|
| 11 |
from fastapi.staticfiles import StaticFiles
|
|
|
|
| 15 |
from llama_cpp import Llama
|
| 16 |
|
| 17 |
# Setup app
|
| 18 |
+
app = FastAPI(title="Multi-Model Hugging Face Space & API")
|
| 19 |
|
| 20 |
# Add CORS Middleware to enable external API requests from other domains
|
| 21 |
app.add_middleware(
|
|
|
|
| 26 |
allow_headers=["*"],
|
| 27 |
)
|
| 28 |
|
| 29 |
+
# Registry of supported models
|
| 30 |
+
SUPPORTED_MODELS = {
|
| 31 |
+
"mythos-nano": {
|
| 32 |
+
"repo": "mradermacher/Mythos-nano-GGUF",
|
| 33 |
+
"file": "Mythos-nano.Q4_K_M.gguf",
|
| 34 |
+
"name": "Mythos Nano (3B)"
|
| 35 |
+
},
|
| 36 |
+
"qwen-2.5-3b": {
|
| 37 |
+
"repo": "Qwen/Qwen2.5-3B-Instruct-GGUF",
|
| 38 |
+
"file": "qwen2.5-3b-instruct-q4_k_m.gguf",
|
| 39 |
+
"name": "Qwen 2.5 (3B) Instruct"
|
| 40 |
+
},
|
| 41 |
+
"llama-3.2-3b": {
|
| 42 |
+
"repo": "bartowski/Llama-3.2-3B-Instruct-GGUF",
|
| 43 |
+
"file": "Llama-3.2-3B-Instruct-Q4_K_M.gguf",
|
| 44 |
+
"name": "Llama 3.2 (3B) Instruct"
|
| 45 |
+
},
|
| 46 |
+
"claude-oss-350m": {
|
| 47 |
+
"repo": "squ11z1/claude-oss-350m",
|
| 48 |
+
"file": "claude-oss-350m-q4_k_m.gguf",
|
| 49 |
+
"name": "Claude OSS (350M)"
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
# Configuration from Environment Variables
|
|
|
|
|
|
|
| 54 |
CACHE_DIR = os.environ.get("HF_HOME", os.path.join(os.path.dirname(os.path.abspath(__file__)), ".cache"))
|
| 55 |
N_CTX = int(os.environ.get("N_CTX", "4096"))
|
| 56 |
NUM_THREADS = int(os.environ.get("NUM_THREADS", "2"))
|
| 57 |
N_GPU_LAYERS = int(os.environ.get("N_GPU_LAYERS", "0"))
|
| 58 |
|
| 59 |
os.makedirs(CACHE_DIR, exist_ok=True)
|
|
|
|
|
|
|
| 60 |
|
| 61 |
# Global model state
|
| 62 |
status = {
|
| 63 |
"state": "initializing", # initializing, downloading, loading, ready, error
|
| 64 |
+
"active_model": None,
|
| 65 |
+
"target_model": "mythos-nano",
|
| 66 |
"progress": 0.0,
|
| 67 |
"speed_mbps": 0.0,
|
| 68 |
"error": None,
|
| 69 |
+
"models": {
|
| 70 |
+
"mythos-nano": {"downloaded": False, "loaded": False, "name": SUPPORTED_MODELS["mythos-nano"]["name"]},
|
| 71 |
+
"qwen-2.5-3b": {"downloaded": False, "loaded": False, "name": SUPPORTED_MODELS["qwen-2.5-3b"]["name"]},
|
| 72 |
+
"llama-3.2-3b": {"downloaded": False, "loaded": False, "name": SUPPORTED_MODELS["llama-3.2-3b"]["name"]},
|
| 73 |
+
"claude-oss-350m": {"downloaded": False, "loaded": False, "name": SUPPORTED_MODELS["claude-oss-350m"]["name"]}
|
| 74 |
+
},
|
| 75 |
"model_info": {
|
|
|
|
|
|
|
| 76 |
"ctx_len": N_CTX,
|
| 77 |
"threads": NUM_THREADS,
|
| 78 |
"gpu_layers": N_GPU_LAYERS
|
|
|
|
| 80 |
}
|
| 81 |
|
| 82 |
llm = None
|
| 83 |
+
model_operation_lock = threading.Lock()
|
| 84 |
|
| 85 |
+
def update_downloaded_status():
|
| 86 |
+
global status
|
| 87 |
+
for model_id, info in SUPPORTED_MODELS.items():
|
| 88 |
+
model_file_path = os.path.join(CACHE_DIR, info["file"])
|
| 89 |
+
downloaded = False
|
| 90 |
+
try:
|
| 91 |
+
# Check if file exists and is larger than 100MB (valid model GGUF)
|
| 92 |
+
if os.path.exists(model_file_path) and os.path.getsize(model_file_path) > 100 * 1024 * 1024:
|
| 93 |
+
downloaded = True
|
| 94 |
+
except Exception:
|
| 95 |
+
pass
|
| 96 |
+
status["models"][model_id]["downloaded"] = downloaded
|
| 97 |
+
|
| 98 |
+
def unload_model():
|
| 99 |
+
global llm, status
|
| 100 |
+
if llm is not None:
|
| 101 |
+
print(f"Unloading active model: {status['active_model']} to free RAM...")
|
| 102 |
+
llm = None
|
| 103 |
+
for m_id in status["models"]:
|
| 104 |
+
status["models"][m_id]["loaded"] = False
|
| 105 |
+
status["active_model"] = None
|
| 106 |
+
gc.collect()
|
| 107 |
+
time.sleep(0.5)
|
| 108 |
+
print("Model unloaded successfully.")
|
| 109 |
+
|
| 110 |
+
def load_model_by_id(model_id: str):
|
| 111 |
global status, llm
|
| 112 |
+
if model_id not in SUPPORTED_MODELS:
|
| 113 |
+
raise ValueError(f"Model '{model_id}' is not supported.")
|
| 114 |
+
|
| 115 |
+
unload_model()
|
| 116 |
+
|
| 117 |
+
status["state"] = "loading"
|
| 118 |
+
status["target_model"] = model_id
|
| 119 |
+
info = SUPPORTED_MODELS[model_id]
|
| 120 |
+
model_file_path = os.path.join(CACHE_DIR, info["file"])
|
| 121 |
+
|
| 122 |
try:
|
| 123 |
+
print(f"Loading model '{model_id}' from {model_file_path}...")
|
|
|
|
| 124 |
llm = Llama(
|
| 125 |
+
model_path=model_file_path,
|
| 126 |
n_ctx=N_CTX,
|
| 127 |
n_threads=NUM_THREADS,
|
| 128 |
n_gpu_layers=N_GPU_LAYERS
|
| 129 |
)
|
| 130 |
+
status["active_model"] = model_id
|
| 131 |
+
status["models"][model_id]["loaded"] = True
|
| 132 |
status["state"] = "ready"
|
| 133 |
status["progress"] = 100.0
|
| 134 |
+
print(f"Model '{model_id}' loaded successfully and is ready.")
|
| 135 |
except Exception as e:
|
| 136 |
status["state"] = "error"
|
| 137 |
+
status["error"] = f"Failed to load model '{model_id}': {str(e)}"
|
| 138 |
print(f"Error loading model: {e}")
|
| 139 |
|
| 140 |
+
def setup_model_task(model_id: str):
|
| 141 |
global status
|
| 142 |
+
# Ensure sequential execution for model loading/swapping operations
|
| 143 |
+
acquired = model_operation_lock.acquire(blocking=False)
|
| 144 |
+
if not acquired:
|
| 145 |
+
print("Model lock is busy. Aborting duplicate model task.")
|
| 146 |
+
return
|
| 147 |
+
|
| 148 |
try:
|
| 149 |
+
update_downloaded_status()
|
| 150 |
+
info = SUPPORTED_MODELS[model_id]
|
| 151 |
+
model_file_path = os.path.join(CACHE_DIR, info["file"])
|
| 152 |
+
download_url = f"https://huggingface.co/{info['repo']}/resolve/main/{info['file']}"
|
| 153 |
+
|
| 154 |
# Fetch metadata using HEAD to get content-length
|
| 155 |
response = requests.head(download_url, allow_redirects=True)
|
| 156 |
if response.status_code != 200:
|
| 157 |
raise Exception(f"Failed to fetch model metadata: HTTP {response.status_code}")
|
| 158 |
|
| 159 |
total_size = int(response.headers.get('content-length', 0))
|
| 160 |
+
|
| 161 |
+
# Check if local file exists and matches target size
|
| 162 |
+
if not os.path.exists(model_file_path) or os.path.getsize(model_file_path) != total_size:
|
| 163 |
+
print(f"Model '{model_id}' is missing or size mismatch. Starting download...")
|
| 164 |
+
status["state"] = "downloading"
|
| 165 |
+
status["target_model"] = model_id
|
| 166 |
+
status["progress"] = 0.0
|
| 167 |
+
start_time = time.time()
|
| 168 |
+
downloaded = 0
|
| 169 |
+
|
| 170 |
+
with requests.get(download_url, stream=True) as r:
|
| 171 |
+
r.raise_for_status()
|
| 172 |
+
with open(model_file_path, 'wb') as f:
|
| 173 |
+
for chunk in r.iter_content(chunk_size=1024 * 1024): # 1MB chunks
|
| 174 |
+
if chunk:
|
| 175 |
+
f.write(chunk)
|
| 176 |
+
downloaded += len(chunk)
|
| 177 |
+
if total_size > 0:
|
| 178 |
+
status["progress"] = round((downloaded / total_size) * 100, 2)
|
| 179 |
+
|
| 180 |
+
elapsed = time.time() - start_time
|
| 181 |
+
if elapsed > 0:
|
| 182 |
+
status["speed_mbps"] = round((downloaded / (1024 * 1024)) / elapsed, 2)
|
| 183 |
+
|
| 184 |
+
print(f"Download of '{model_id}' completed.")
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
update_downloaded_status()
|
| 187 |
+
load_model_by_id(model_id)
|
| 188 |
|
| 189 |
except Exception as e:
|
| 190 |
status["state"] = "error"
|
| 191 |
+
status["error"] = f"Failed to setup model '{model_id}': {str(e)}"
|
| 192 |
+
print(f"Error in setup model task: {e}")
|
| 193 |
+
finally:
|
| 194 |
+
model_operation_lock.release()
|
| 195 |
|
| 196 |
@app.on_event("startup")
|
| 197 |
def startup_event():
|
| 198 |
+
# By default, setup mythos-nano on startup
|
| 199 |
+
threading.Thread(target=setup_model_task, args=("mythos-nano",), daemon=True).start()
|
| 200 |
|
| 201 |
+
# API Schemas
|
| 202 |
class ChatMessage(BaseModel):
|
| 203 |
role: str
|
| 204 |
content: str
|
|
|
|
| 211 |
max_tokens: Optional[int] = 2048
|
| 212 |
stream: Optional[bool] = False
|
| 213 |
|
| 214 |
+
class SelectModelRequest(BaseModel):
|
| 215 |
+
model: str
|
| 216 |
+
|
| 217 |
# Endpoints
|
| 218 |
@app.get("/api/status")
|
| 219 |
def get_status():
|
| 220 |
+
update_downloaded_status()
|
| 221 |
return status
|
| 222 |
|
| 223 |
+
@app.post("/api/select_model")
|
| 224 |
+
def select_model(request: SelectModelRequest):
|
| 225 |
+
global status
|
| 226 |
+
model_id = request.model
|
| 227 |
+
if model_id not in SUPPORTED_MODELS:
|
| 228 |
+
return JSONResponse(
|
| 229 |
+
status_code=400,
|
| 230 |
+
content={"error": f"Model '{model_id}' is not supported. Supported: {list(SUPPORTED_MODELS.keys())}"}
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
if status["active_model"] == model_id and status["state"] == "ready":
|
| 234 |
+
return {"status": "success", "message": f"Model '{model_id}' is already active."}
|
| 235 |
+
|
| 236 |
+
if status["target_model"] == model_id and status["state"] in ["downloading", "loading"]:
|
| 237 |
+
return {"status": "pending", "message": f"Model '{model_id}' is already being loaded/downloaded."}
|
| 238 |
+
|
| 239 |
+
# Run setup asynchronously
|
| 240 |
+
threading.Thread(target=setup_model_task, args=(model_id,), daemon=True).start()
|
| 241 |
+
return {"status": "pending", "message": f"Started swap/setup for model '{model_id}'."}
|
| 242 |
+
|
| 243 |
@app.get("/v1/models")
|
| 244 |
def get_models():
|
| 245 |
+
data = []
|
| 246 |
+
for model_id, info in SUPPORTED_MODELS.items():
|
| 247 |
+
data.append({
|
| 248 |
+
"id": model_id,
|
| 249 |
+
"object": "model",
|
| 250 |
+
"created": int(time.time()),
|
| 251 |
+
"owned_by": info["repo"].split("/")[0]
|
| 252 |
+
})
|
| 253 |
return {
|
| 254 |
"object": "list",
|
| 255 |
+
"data": data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
}
|
| 257 |
|
| 258 |
async def stream_generator(request_dict: dict):
|
| 259 |
q = queue.Queue()
|
| 260 |
|
|
|
|
| 261 |
def producer():
|
| 262 |
try:
|
| 263 |
response = llm.create_chat_completion(
|
|
|
|
| 269 |
)
|
| 270 |
for chunk in response:
|
| 271 |
q.put(chunk)
|
| 272 |
+
q.put(None)
|
| 273 |
except Exception as e:
|
| 274 |
q.put(e)
|
| 275 |
|
|
|
|
| 277 |
|
| 278 |
loop = asyncio.get_event_loop()
|
| 279 |
while True:
|
|
|
|
| 280 |
chunk = await loop.run_in_executor(None, q.get)
|
| 281 |
if chunk is None:
|
| 282 |
break
|
|
|
|
| 289 |
@app.post("/v1/chat/completions")
|
| 290 |
async def chat_completions(request: ChatCompletionRequest):
|
| 291 |
global llm
|
| 292 |
+
requested_model = request.model
|
| 293 |
+
|
| 294 |
+
if requested_model not in SUPPORTED_MODELS:
|
| 295 |
return JSONResponse(
|
| 296 |
+
status_code=400,
|
| 297 |
+
content={"error": {"message": f"Model '{requested_model}' is not supported.", "type": "invalid_request_error"}}
|
| 298 |
)
|
| 299 |
|
| 300 |
+
# If requested model is not loaded, we swap it on-the-fly
|
| 301 |
+
if status["active_model"] != requested_model or status["state"] != "ready":
|
| 302 |
+
update_downloaded_status()
|
| 303 |
+
if not status["models"][requested_model]["downloaded"]:
|
| 304 |
+
return JSONResponse(
|
| 305 |
+
status_code=503,
|
| 306 |
+
content={"error": {"message": f"Model '{requested_model}' is not downloaded yet. Please select and download it in the Web UI first.", "type": "service_unavailable"}}
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
# Acquire lock to perform safe model swapping
|
| 310 |
+
acquired = model_operation_lock.acquire(blocking=True, timeout=30.0)
|
| 311 |
+
if not acquired:
|
| 312 |
+
return JSONResponse(
|
| 313 |
+
status_code=503,
|
| 314 |
+
content={"error": {"message": "Server is busy loading another model. Please try again.", "type": "service_unavailable"}}
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
try:
|
| 318 |
+
if status["active_model"] != requested_model:
|
| 319 |
+
load_model_by_id(requested_model)
|
| 320 |
+
except Exception as e:
|
| 321 |
+
return JSONResponse(
|
| 322 |
+
status_code=500,
|
| 323 |
+
content={"error": {"message": f"Failed to load model '{requested_model}': {str(e)}", "type": "api_error"}}
|
| 324 |
+
)
|
| 325 |
+
finally:
|
| 326 |
+
model_operation_lock.release()
|
| 327 |
+
|
| 328 |
+
# Model is loaded, run inference
|
| 329 |
request_dict = request.dict()
|
| 330 |
|
| 331 |
if request.stream:
|
|
|
|
| 334 |
media_type="text/event-stream"
|
| 335 |
)
|
| 336 |
else:
|
|
|
|
| 337 |
loop = asyncio.get_event_loop()
|
| 338 |
try:
|
| 339 |
response = await loop.run_in_executor(
|
|
|
|
| 356 |
# Static file serving
|
| 357 |
@app.get("/")
|
| 358 |
async def read_index():
|
|
|
|
| 359 |
return FileResponse("static/index.html")
|
| 360 |
|
|
|
|
| 361 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 362 |
|
| 363 |
if __name__ == "__main__":
|
| 364 |
import uvicorn
|
|
|
|
| 365 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
static/app.js
CHANGED
|
@@ -39,9 +39,37 @@ const systemPromptInput = document.getElementById('system-prompt');
|
|
| 39 |
const tempSlider = document.getElementById('temp-slider');
|
| 40 |
const tempVal = document.getElementById('temp-val');
|
| 41 |
const tokensInput = document.getElementById('tokens-input');
|
|
|
|
| 42 |
|
| 43 |
const apiBaseUrl = document.getElementById('api-base-url');
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
// Custom Marked Renderer for premium code snippets
|
| 46 |
const renderer = new marked.Renderer();
|
| 47 |
renderer.code = function(code, language) {
|
|
@@ -165,6 +193,47 @@ function setupEventListeners() {
|
|
| 165 |
chatForm.dispatchEvent(new Event('submit'));
|
| 166 |
}
|
| 167 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
}
|
| 169 |
|
| 170 |
// Poll model download & loading status
|
|
@@ -176,7 +245,8 @@ async function pollStatus() {
|
|
| 176 |
const data = await res.json();
|
| 177 |
|
| 178 |
// Render system indicator stats
|
| 179 |
-
|
|
|
|
| 180 |
infoConfig.textContent = `ctx: ${data.model_info.ctx_len} | layers: ${data.model_info.gpu_layers}`;
|
| 181 |
|
| 182 |
if (data.state === 'ready') {
|
|
@@ -185,6 +255,10 @@ async function pollStatus() {
|
|
| 185 |
statusText.textContent = 'En l铆nea';
|
| 186 |
loadingOverlay.classList.remove('active');
|
| 187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
// Render chat history if loaded for first time
|
| 189 |
if (Object.keys(chats).length > 0 && !currentChatId) {
|
| 190 |
// Select first chat
|
|
@@ -200,7 +274,8 @@ async function pollStatus() {
|
|
| 200 |
statusDot.className = 'dot orange';
|
| 201 |
statusText.textContent = 'Descargando...';
|
| 202 |
loadingOverlay.classList.add('active');
|
| 203 |
-
|
|
|
|
| 204 |
progressBar.style.width = `${data.progress}%`;
|
| 205 |
downloadStats.style.display = 'flex';
|
| 206 |
downloadPercent.textContent = `${data.progress}%`;
|
|
@@ -210,7 +285,8 @@ async function pollStatus() {
|
|
| 210 |
statusDot.className = 'dot orange';
|
| 211 |
statusText.textContent = 'Cargando...';
|
| 212 |
loadingOverlay.classList.add('active');
|
| 213 |
-
|
|
|
|
| 214 |
progressBar.style.width = '100%';
|
| 215 |
downloadStats.style.display = 'none';
|
| 216 |
} else if (data.state === 'error') {
|
|
@@ -233,11 +309,13 @@ async function pollStatus() {
|
|
| 233 |
|
| 234 |
// Render the Welcome screen with suggestions
|
| 235 |
function renderWelcomeScreen() {
|
|
|
|
|
|
|
| 236 |
chatMessages.innerHTML = `
|
| 237 |
<div class="welcome-container">
|
| 238 |
<i data-lucide="bot" class="welcome-icon"></i>
|
| 239 |
-
<h1
|
| 240 |
-
<p
|
| 241 |
<div class="suggestions">
|
| 242 |
<div class="suggestion-card" onclick="useSuggestion(this)">
|
| 243 |
<h4>Resolver Ecuaci贸n</h4>
|
|
@@ -449,7 +527,7 @@ async function sendMessage() {
|
|
| 449 |
'Content-Type': 'application/json'
|
| 450 |
},
|
| 451 |
body: JSON.stringify({
|
| 452 |
-
model:
|
| 453 |
messages: messagesPayload,
|
| 454 |
temperature: temp,
|
| 455 |
max_tokens: maxTokens,
|
|
|
|
| 39 |
const tempSlider = document.getElementById('temp-slider');
|
| 40 |
const tempVal = document.getElementById('temp-val');
|
| 41 |
const tokensInput = document.getElementById('tokens-input');
|
| 42 |
+
const modelSelect = document.getElementById('model-select');
|
| 43 |
|
| 44 |
const apiBaseUrl = document.getElementById('api-base-url');
|
| 45 |
|
| 46 |
+
// Model Metadata for descriptions and welcome page text
|
| 47 |
+
const MODEL_METADATA = {
|
| 48 |
+
"mythos-nano": {
|
| 49 |
+
title: "Hola, soy Mythos-nano",
|
| 50 |
+
desc: "Un modelo de razonamiento y codificaci贸n de 3 mil millones de par谩metros optimizado para alto rendimiento."
|
| 51 |
+
},
|
| 52 |
+
"qwen-2.5-3b": {
|
| 53 |
+
title: "Hola, soy Qwen 2.5",
|
| 54 |
+
desc: "Un modelo generalista de 3 mil millones de par谩metros, l铆der en tareas de razonamiento, matem谩ticas y conversaci贸n."
|
| 55 |
+
},
|
| 56 |
+
"llama-3.2-3b": {
|
| 57 |
+
title: "Hola, soy Llama 3.2",
|
| 58 |
+
desc: "El modelo liviano y altamente optimizado de Meta, ideal para seguir instrucciones r谩pidas y asistencia general."
|
| 59 |
+
},
|
| 60 |
+
"claude-oss-350m": {
|
| 61 |
+
title: "Hola, soy Claude OSS",
|
| 62 |
+
desc: "Un modelo ultraligero de 350 millones de par谩metros basado en la arquitectura LFM 2.5, ideal para respuestas r谩pidas y dispositivos de bajos recursos."
|
| 63 |
+
}
|
| 64 |
+
};
|
| 65 |
+
|
| 66 |
+
const MODEL_NAMES = {
|
| 67 |
+
"mythos-nano": "Mythos Nano 3B",
|
| 68 |
+
"qwen-2.5-3b": "Qwen 2.5 3B",
|
| 69 |
+
"llama-3.2-3b": "Llama 3.2 3B",
|
| 70 |
+
"claude-oss-350m": "Claude OSS 350M"
|
| 71 |
+
};
|
| 72 |
+
|
| 73 |
// Custom Marked Renderer for premium code snippets
|
| 74 |
const renderer = new marked.Renderer();
|
| 75 |
renderer.code = function(code, language) {
|
|
|
|
| 193 |
chatForm.dispatchEvent(new Event('submit'));
|
| 194 |
}
|
| 195 |
});
|
| 196 |
+
|
| 197 |
+
// Model selection change handler
|
| 198 |
+
modelSelect.addEventListener('change', async (e) => {
|
| 199 |
+
const selectedModel = e.target.value;
|
| 200 |
+
try {
|
| 201 |
+
loadingOverlay.classList.add('active');
|
| 202 |
+
overlayStatusText.textContent = `Preparando modelo ${MODEL_NAMES[selectedModel]}...`;
|
| 203 |
+
progressBar.style.width = '10%';
|
| 204 |
+
downloadStats.style.display = 'none';
|
| 205 |
+
|
| 206 |
+
const res = await fetch('/api/select_model', {
|
| 207 |
+
method: 'POST',
|
| 208 |
+
headers: {
|
| 209 |
+
'Content-Type': 'application/json'
|
| 210 |
+
},
|
| 211 |
+
body: JSON.stringify({ model: selectedModel })
|
| 212 |
+
});
|
| 213 |
+
|
| 214 |
+
if (!res.ok) throw new Error("Error de comunicaci贸n con el servidor al cambiar de modelo");
|
| 215 |
+
|
| 216 |
+
// Update welcome screen descriptions if we are on it
|
| 217 |
+
const welcome = chatMessages.querySelector('.welcome-container');
|
| 218 |
+
if (welcome) {
|
| 219 |
+
updateWelcomeContent(selectedModel);
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
} catch (err) {
|
| 223 |
+
console.error("Error swapping model:", err);
|
| 224 |
+
alert(`Error al cambiar de modelo: ${err.message}`);
|
| 225 |
+
pollStatus(); // Recover display overlay
|
| 226 |
+
}
|
| 227 |
+
});
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
function updateWelcomeContent(modelId) {
|
| 231 |
+
const titleEl = document.getElementById('welcome-title');
|
| 232 |
+
const descEl = document.getElementById('welcome-desc');
|
| 233 |
+
const meta = MODEL_METADATA[modelId] || MODEL_METADATA['mythos-nano'];
|
| 234 |
+
|
| 235 |
+
if (titleEl) titleEl.textContent = meta.title;
|
| 236 |
+
if (descEl) descEl.textContent = meta.desc;
|
| 237 |
}
|
| 238 |
|
| 239 |
// Poll model download & loading status
|
|
|
|
| 245 |
const data = await res.json();
|
| 246 |
|
| 247 |
// Render system indicator stats
|
| 248 |
+
const activeName = data.active_model ? MODEL_NAMES[data.active_model] : "Ninguno";
|
| 249 |
+
infoRepo.textContent = activeName;
|
| 250 |
infoConfig.textContent = `ctx: ${data.model_info.ctx_len} | layers: ${data.model_info.gpu_layers}`;
|
| 251 |
|
| 252 |
if (data.state === 'ready') {
|
|
|
|
| 255 |
statusText.textContent = 'En l铆nea';
|
| 256 |
loadingOverlay.classList.remove('active');
|
| 257 |
|
| 258 |
+
if (data.active_model) {
|
| 259 |
+
modelSelect.value = data.active_model;
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
// Render chat history if loaded for first time
|
| 263 |
if (Object.keys(chats).length > 0 && !currentChatId) {
|
| 264 |
// Select first chat
|
|
|
|
| 274 |
statusDot.className = 'dot orange';
|
| 275 |
statusText.textContent = 'Descargando...';
|
| 276 |
loadingOverlay.classList.add('active');
|
| 277 |
+
const targetName = MODEL_NAMES[data.target_model] || data.target_model;
|
| 278 |
+
overlayStatusText.textContent = `Descargando modelo ${targetName} de Hugging Face...`;
|
| 279 |
progressBar.style.width = `${data.progress}%`;
|
| 280 |
downloadStats.style.display = 'flex';
|
| 281 |
downloadPercent.textContent = `${data.progress}%`;
|
|
|
|
| 285 |
statusDot.className = 'dot orange';
|
| 286 |
statusText.textContent = 'Cargando...';
|
| 287 |
loadingOverlay.classList.add('active');
|
| 288 |
+
const targetName = MODEL_NAMES[data.target_model] || data.target_model;
|
| 289 |
+
overlayStatusText.textContent = `Cargando modelo ${targetName} en memoria...`;
|
| 290 |
progressBar.style.width = '100%';
|
| 291 |
downloadStats.style.display = 'none';
|
| 292 |
} else if (data.state === 'error') {
|
|
|
|
| 309 |
|
| 310 |
// Render the Welcome screen with suggestions
|
| 311 |
function renderWelcomeScreen() {
|
| 312 |
+
const activeModel = modelSelect.value;
|
| 313 |
+
const meta = MODEL_METADATA[activeModel] || MODEL_METADATA['mythos-nano'];
|
| 314 |
chatMessages.innerHTML = `
|
| 315 |
<div class="welcome-container">
|
| 316 |
<i data-lucide="bot" class="welcome-icon"></i>
|
| 317 |
+
<h1 id="welcome-title">${meta.title}</h1>
|
| 318 |
+
<p id="welcome-desc">${meta.desc}</p>
|
| 319 |
<div class="suggestions">
|
| 320 |
<div class="suggestion-card" onclick="useSuggestion(this)">
|
| 321 |
<h4>Resolver Ecuaci贸n</h4>
|
|
|
|
| 527 |
'Content-Type': 'application/json'
|
| 528 |
},
|
| 529 |
body: JSON.stringify({
|
| 530 |
+
model: modelSelect.value,
|
| 531 |
messages: messagesPayload,
|
| 532 |
temperature: temp,
|
| 533 |
max_tokens: maxTokens,
|
static/index.html
CHANGED
|
@@ -71,13 +71,20 @@
|
|
| 71 |
|
| 72 |
<!-- Main Workspace -->
|
| 73 |
<main class="main-content">
|
| 74 |
-
<!-- Top Navbar -->
|
| 75 |
<header class="top-nav">
|
| 76 |
<div class="nav-left">
|
| 77 |
<button id="toggle-sidebar" class="icon-btn" title="Men煤">
|
| 78 |
<i data-lucide="menu"></i>
|
| 79 |
</button>
|
| 80 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
</div>
|
| 82 |
<div class="nav-right">
|
| 83 |
<button id="tab-chat-btn" class="nav-tab active">
|
|
@@ -99,8 +106,8 @@
|
|
| 99 |
<div id="chat-messages" class="chat-messages">
|
| 100 |
<div class="welcome-container">
|
| 101 |
<i data-lucide="bot" class="welcome-icon"></i>
|
| 102 |
-
<h1>Hola, soy Mythos-nano</h1>
|
| 103 |
-
<p>Un modelo de razonamiento y codificaci贸n de 3 mil millones de par谩metros optimizado para alto rendimiento.</p>
|
| 104 |
<div class="suggestions">
|
| 105 |
<div class="suggestion-card" onclick="useSuggestion(this)">
|
| 106 |
<h4>Resolver Ecuaci贸n</h4>
|
|
|
|
| 71 |
|
| 72 |
<!-- Main Workspace -->
|
| 73 |
<main class="main-content">
|
|
|
|
| 74 |
<header class="top-nav">
|
| 75 |
<div class="nav-left">
|
| 76 |
<button id="toggle-sidebar" class="icon-btn" title="Men煤">
|
| 77 |
<i data-lucide="menu"></i>
|
| 78 |
</button>
|
| 79 |
+
<div class="model-select-container">
|
| 80 |
+
<i data-lucide="cpu" class="select-icon"></i>
|
| 81 |
+
<select id="model-select" class="model-select">
|
| 82 |
+
<option value="mythos-nano" selected>Mythos Nano (3B)</option>
|
| 83 |
+
<option value="qwen-2.5-3b">Qwen 2.5 (3B) Instruct</option>
|
| 84 |
+
<option value="llama-3.2-3b">Llama 3.2 (3B) Instruct</option>
|
| 85 |
+
<option value="claude-oss-350m">Claude OSS (350M)</option>
|
| 86 |
+
</select>
|
| 87 |
+
</div>
|
| 88 |
</div>
|
| 89 |
<div class="nav-right">
|
| 90 |
<button id="tab-chat-btn" class="nav-tab active">
|
|
|
|
| 106 |
<div id="chat-messages" class="chat-messages">
|
| 107 |
<div class="welcome-container">
|
| 108 |
<i data-lucide="bot" class="welcome-icon"></i>
|
| 109 |
+
<h1 id="welcome-title">Hola, soy Mythos-nano</h1>
|
| 110 |
+
<p id="welcome-desc">Un modelo de razonamiento y codificaci贸n de 3 mil millones de par谩metros optimizado para alto rendimiento.</p>
|
| 111 |
<div class="suggestions">
|
| 112 |
<div class="suggestion-card" onclick="useSuggestion(this)">
|
| 113 |
<h4>Resolver Ecuaci贸n</h4>
|
static/style.css
CHANGED
|
@@ -1011,3 +1011,45 @@ input[type="range"]::-webkit-slider-thumb:hover {
|
|
| 1011 |
grid-template-columns: 1fr;
|
| 1012 |
}
|
| 1013 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1011 |
grid-template-columns: 1fr;
|
| 1012 |
}
|
| 1013 |
}
|
| 1014 |
+
|
| 1015 |
+
/* Model Selector Dropdown in Navbar */
|
| 1016 |
+
.model-select-container {
|
| 1017 |
+
display: flex;
|
| 1018 |
+
align-items: center;
|
| 1019 |
+
gap: 0.5rem;
|
| 1020 |
+
background: rgba(255, 255, 255, 0.03);
|
| 1021 |
+
border: 1px solid var(--border-glass);
|
| 1022 |
+
padding: 0.4rem 0.75rem;
|
| 1023 |
+
border-radius: 12px;
|
| 1024 |
+
transition: all 0.2s ease;
|
| 1025 |
+
}
|
| 1026 |
+
|
| 1027 |
+
.model-select-container:focus-within {
|
| 1028 |
+
border-color: var(--border-focus);
|
| 1029 |
+
box-shadow: var(--glow-primary);
|
| 1030 |
+
}
|
| 1031 |
+
|
| 1032 |
+
.select-icon {
|
| 1033 |
+
width: 16px;
|
| 1034 |
+
height: 16px;
|
| 1035 |
+
color: var(--color-primary);
|
| 1036 |
+
}
|
| 1037 |
+
|
| 1038 |
+
.model-select {
|
| 1039 |
+
background: transparent;
|
| 1040 |
+
border: none;
|
| 1041 |
+
color: var(--text-primary);
|
| 1042 |
+
font-family: var(--font-header);
|
| 1043 |
+
font-weight: 600;
|
| 1044 |
+
font-size: 0.95rem;
|
| 1045 |
+
outline: none;
|
| 1046 |
+
cursor: pointer;
|
| 1047 |
+
padding-right: 0.5rem;
|
| 1048 |
+
}
|
| 1049 |
+
|
| 1050 |
+
.model-select option {
|
| 1051 |
+
background-color: var(--bg-panel);
|
| 1052 |
+
color: var(--text-primary);
|
| 1053 |
+
padding: 0.5rem;
|
| 1054 |
+
}
|
| 1055 |
+
|