"""MiloX1 MoE 250M (fine-tune de chat, 100% español): API compatible con OpenAI + chat web + búsqueda web + razonamiento (thinking) desactivable.
Formato EXACTO de los notebooks MiloX1_Finetune / Refuerzo_RL MoE250M:
<|bos|><|system|>…<|end|><|user|>…<|end|>[<|tool|><|search|>consulta + resultados<|end|>]
<|assistant|><|think|><|/think|>\n (razonamiento APAGADO, por defecto)
<|assistant|><|think|>\n (razonamiento ENCENDIDO: el modelo escribe el pensamiento, <|/think|>, y luego la respuesta)
Razonamiento: se activa por petición con "thinking": true (o /pensar al inicio del mensaje); THINKING_DEFAULT=1 lo deja encendido por defecto.
El pensamiento se devuelve aparte en `reasoning_content` (message / delta), igual que DeepSeek/Qwen3.
La búsqueda la decide y la ejecuta ESTA app (no el modelo). La arquitectura va incluida en este archivo (no usa transformers).
Con USE_CONTEXT=0 (por defecto) cada mensaje se responde por separado; con USE_CONTEXT=1 recuerda la conversación (ventana 4096).
"""
import os, re, math, time, uuid, json, threading, urllib.request, urllib.parse
from dataclasses import dataclass
from typing import List, Optional, Union, Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastapi import FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, HTMLResponse
from pydantic import BaseModel
from tokenizers import Tokenizer
from huggingface_hub import hf_hub_download
# ----------------------------- arquitectura MiloX1 MoE 250M (idéntica a la del entrenamiento) -----------------------------
@dataclass
class Cfg:
vocab: int = 32768
d: int = 768
n_layers: int = 14
n_dense_layers: int = 1
n_heads: int = 12
n_kv: int = 4
d_dense: int = 2048
d_shared: int = 512
n_experts: int = 12
top_k: int = 2
ffe: int = 512
max_pos: int = 4096
rope_theta: float = 500000.0
eps: float = 1e-6
cf: float = 1.5
bias_rate: float = 1e-3
rz: float = 1e-4
class RMSNorm(nn.Module):
def __init__(self, d, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d)); self.eps = eps
def forward(self, x):
dt = x.dtype; xf = x.float()
xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
return xf.to(dt) * self.weight.to(dt)
def rope_cache(hd, maxlen, theta, device=None):
inv = 1.0 / (theta ** (torch.arange(0, hd, 2, dtype=torch.float32, device=device) / hd))
t = torch.arange(maxlen, dtype=torch.float32, device=device)
fr = torch.outer(t, inv); emb = torch.cat([fr, fr], dim=-1)
return emb.cos(), emb.sin()
def rot_half(x):
x1, x2 = x.chunk(2, dim=-1)
return torch.cat([-x2, x1], dim=-1)
def apply_rope(x, cos, sin):
cos = cos.to(x.dtype)[None, None]; sin = sin.to(x.dtype)[None, None]
return x * cos + rot_half(x) * sin
class Attention(nn.Module):
def __init__(self, c):
super().__init__()
self.H, self.KV, self.hd = c.n_heads, c.n_kv, c.d // c.n_heads
self.qkv_proj = nn.Linear(c.d, (self.H + 2 * self.KV) * self.hd, bias=False)
self.o_proj = nn.Linear(self.H * self.hd, c.d, bias=False)
self.q_norm = RMSNorm(self.hd, c.eps); self.k_norm = RMSNorm(self.hd, c.eps)
def forward(self, x, cos, sin, past=None, use_cache=False):
B, T, _ = x.shape
q_dim = self.H * self.hd; kv_dim = self.KV * self.hd
q, k, v = self.qkv_proj(x).split([q_dim, kv_dim, kv_dim], dim=-1)
q = q.view(B, T, self.H, self.hd).transpose(1, 2)
k = k.view(B, T, self.KV, self.hd).transpose(1, 2)
v = v.view(B, T, self.KV, self.hd).transpose(1, 2)
q = apply_rope(self.q_norm(q), cos, sin); k = apply_rope(self.k_norm(k), cos, sin)
if past is not None:
k = torch.cat([past[0], k], dim=2); v = torch.cat([past[1], v], dim=2)
kv = (k, v) if use_cache else None
if self.KV != self.H:
r = self.H // self.KV
k = k.repeat_interleave(r, dim=1); v = v.repeat_interleave(r, dim=1)
y = F.scaled_dot_product_attention(q, k, v, is_causal=(past is None and T > 1))
y = y.transpose(1, 2).contiguous().view(B, T, self.H * self.hd)
return self.o_proj(y), kv
class DenseSwiGLU(nn.Module):
def __init__(self, d, hidden):
super().__init__()
self.w13 = nn.Linear(d, 2 * hidden, bias=False)
self.w2 = nn.Linear(hidden, d, bias=False)
def forward(self, x):
g, u = self.w13(x).chunk(2, dim=-1)
return self.w2(F.silu(g) * u)
class MoE(nn.Module):
def __init__(self, c):
super().__init__()
self.E, self.k, self.cf, self.ffe = c.n_experts, c.top_k, c.cf, c.ffe
self.bias_rate = c.bias_rate
self.shared = DenseSwiGLU(c.d, c.d_shared)
self.gate = nn.Linear(c.d, c.n_experts, bias=False)
self.w13 = nn.Parameter(torch.empty(c.n_experts, c.d, 2 * c.ffe))
self.w2 = nn.Parameter(torch.empty(c.n_experts, c.ffe, c.d))
self.register_buffer("expert_bias", torch.zeros(c.n_experts, dtype=torch.float32))
self.register_buffer("load_accum", torch.zeros(c.n_experts, dtype=torch.float32), persistent=False)
def forward(self, x):
B, T, d = x.shape; N = B * T; xf = x.reshape(N, d)
sh_out = self.shared(xf)
with torch.autocast(device_type=xf.device.type, enabled=False):
logits = F.linear(xf.float(), self.gate.weight.float())
scores = logits.sigmoid()
_, topi = (scores + self.expert_bias).topk(self.k, dim=-1)
topv = scores.gather(-1, topi)
topv = topv / topv.sum(-1, keepdim=True).clamp_min(1e-6)
rz_loss = None
if self.training:
with torch.no_grad():
assign = torch.zeros_like(scores).scatter_(1, topi, 1.0)
self.load_accum.add_(assign.sum(0))
rz_loss = torch.logsumexp(logits, dim=-1).pow(2).mean()
routed = self._dispatch_capacity(xf, topi, topv)
else:
routed = self._dispatch_small(xf, topi, topv) if N <= 8 else self._dispatch_loop(xf, topi, topv)
return (sh_out + routed).view(B, T, d), rz_loss
@torch.no_grad()
def update_bias(self):
tot = self.load_accum.sum()
if tot > 0:
self.expert_bias.add_(self.bias_rate * torch.sign((tot / self.E) - self.load_accum))
self.expert_bias.clamp_(-2.0, 2.0); self.load_accum.zero_()
def _dispatch_capacity(self, xf, topi, topv):
N, d = xf.shape; E, k = self.E, self.k
C = int(math.ceil(N * k / E * self.cf)); C = ((C + 7) // 8) * 8
flat_e = topi.t().reshape(-1); flat_w = topv.t().reshape(-1)
tok = torch.arange(N, device=xf.device).repeat(k)
onehot = (flat_e.unsqueeze(1) == torch.arange(E, device=xf.device)).to(torch.int32)
pos = (onehot.cumsum(0) * onehot).sum(1) - 1; keep = pos < C
slot = torch.where(keep, flat_e * C + pos, torch.full_like(pos, E * C))
buf = xf.new_zeros(E * C + 1, d).index_copy(0, slot, xf[tok])
xin = buf[:E * C].view(E, C, d)
g, u = torch.bmm(xin, self.w13.to(xin.dtype)).chunk(2, dim=-1)
y = torch.bmm(F.silu(g) * u, self.w2.to(xin.dtype))
ypad = torch.cat([y.reshape(E * C, d), y.new_zeros(1, d)], 0)
return (ypad[slot] * (flat_w * keep).to(y.dtype).unsqueeze(-1)).view(k, N, d).sum(0).to(xf.dtype)
def _dispatch_small(self, xf, topi, topv):
xg = xf.to(self.w13.dtype)
g, u = torch.einsum("nd,nkdf->nkf", xg, self.w13[topi]).chunk(2, dim=-1)
y = torch.einsum("nkf,nkfd->nkd", F.silu(g) * u, self.w2[topi])
return (y * topv.unsqueeze(-1).to(y.dtype)).sum(1).to(xf.dtype)
def _dispatch_loop(self, xf, topi, topv):
N, d = xf.shape; out = torch.zeros_like(xf)
flat_e = topi.reshape(-1); flat_w = topv.reshape(-1)
tok = torch.arange(N, device=xf.device).repeat_interleave(self.k); xg = xf.to(self.w13.dtype)
for e in range(self.E):
sel = (flat_e == e).nonzero(as_tuple=True)[0]
if sel.numel() == 0: continue
t = tok[sel]; xe = xg[t]
g, u = (xe @ self.w13[e]).chunk(2, dim=-1)
out.index_add_(0, t, (((F.silu(g) * u) @ self.w2[e]) * flat_w[sel].unsqueeze(-1)).to(out.dtype))
return out
class Block(nn.Module):
def __init__(self, c, is_moe):
super().__init__()
self.is_moe = is_moe
self.input_layernorm = RMSNorm(c.d, c.eps)
self.self_attn = Attention(c)
self.post_attention_layernorm = RMSNorm(c.d, c.eps)
self.mlp = MoE(c) if is_moe else DenseSwiGLU(c.d, c.d_dense)
def forward(self, x, cos, sin, past=None, use_cache=False):
h, kv = self.self_attn(self.input_layernorm(x), cos, sin, past, use_cache)
x = x + h
if self.is_moe: m, rz = self.mlp(self.post_attention_layernorm(x))
else: m = self.mlp(self.post_attention_layernorm(x)); rz = None
return x + m, kv, rz
class Inner(nn.Module):
def __init__(self, c):
super().__init__()
self.embed_tokens = nn.Embedding(c.vocab, c.d)
self.layers = nn.ModuleList([Block(c, is_moe=(i >= c.n_dense_layers)) for i in range(c.n_layers)])
self.norm = RMSNorm(c.d, c.eps)
class MiloXModel(nn.Module):
def __init__(self, c: Cfg):
super().__init__()
self.c = c; self.model = Inner(c)
self.lm_head = nn.Linear(c.d, c.vocab, bias=False)
self.lm_head.weight = self.model.embed_tokens.weight
self.grad_ckpt = False; self.rebuild_rope()
def n_params(self):
return sum(p.numel() for p in self.parameters())
def n_active(self):
c = self.c; n_moe = c.n_layers - c.n_dense_layers
return self.n_params() - n_moe * (c.n_experts - c.top_k) * 3 * c.d * c.ffe
def rebuild_rope(self):
dev = self.model.embed_tokens.weight.device
cos, sin = rope_cache(self.c.d // self.c.n_heads, self.c.max_pos, self.c.rope_theta, dev)
self.register_buffer("cos", cos, persistent=False); self.register_buffer("sin", sin, persistent=False)
@torch.no_grad()
def update_moe_biases(self):
for layer in self.model.layers:
if layer.is_moe: layer.mlp.update_bias()
def forward(self, idx, past=None, start_pos=0, use_cache=False):
B, T = idx.shape; x = self.model.embed_tokens(idx)
cos = self.cos[start_pos:start_pos + T]; sin = self.sin[start_pos:start_pos + T]
new = []
for i, layer in enumerate(self.model.layers):
x, kv, _ = layer(x, cos, sin, past[i] if past is not None else None, use_cache)
new.append(kv)
x = self.model.norm(x)
return self.lm_head(x[:, -1:]), (new if use_cache else None)
# ----------------------------- configuración (variables del Space) -----------------------------
MODEL_ID = os.getenv("MODEL_ID", "Hiakeu/MiloX1").strip() # repo del MODELO en el Hub (milox1_chat.pt + tokenizer.json)
MODEL_NAME = os.getenv("MODEL_NAME", "MiloX1")
MODEL_FILE = os.getenv("MODEL_FILE", "milox1_chat.pt") # archivo de pesos del repo (si no existe, usa model.safetensors + config.json)
USE_CONTEXT = os.getenv("USE_CONTEXT", "0") == "1" # 0 = cada mensaje por separado (por defecto) · 1 = recuerda la conversación
API_KEY = os.getenv("API_KEY", "") # vacío = API abierta
HF_TOKEN = (os.getenv("HF_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN") or "").strip() or None # solo si el repo del modelo es privado
DEFAULT_TEMP = float(os.getenv("TEMP", "0.6")) # temperatura por defecto (con búsqueda web se limita a 0.35, como en el notebook)
THINKING_DEFAULT = os.getenv("THINKING_DEFAULT", "0") == "1" # 0 = razonamiento apagado salvo que la petición lo pida · 1 = encendido por defecto
ALLOW_THINKING = os.getenv("ALLOW_THINKING", "1") == "1" # 0 = ignora thinking:true (siempre apagado)
ALLOW_CLIENT_SYSTEM = os.getenv("ALLOW_CLIENT_SYSTEM", "0") == "1" # 0 = siempre el prompt de sistema del entrenamiento
WEB_SEARCH_URL = os.getenv("WEB_SEARCH_URL", "") # TU buscador (POST JSON). Vacío = sin buscador propio
WEB_SEARCH_KEY = os.getenv("WEB_SEARCH_KEY", "")
WEB_BUILTIN = os.getenv("WEB_BUILTIN", "0") == "1" # 1 = buscador integrado (DuckDuckGo si está `ddgs`, si no Wikipedia)
WEB_LANG = os.getenv("WEB_LANG", "es") # idioma de Wikipedia para el buscador integrado
WEB_MAX_RESULTS = max(1, min(int(os.getenv("WEB_MAX_RESULTS", "4")), 5))
WEB_AVAILABLE = bool(WEB_SEARCH_URL) or WEB_BUILTIN
# off = nunca · request = solo cuando la petición trae web_search:true (botón 🔎 del chat) · always = en cada mensaje
# ("auto" de la versión anterior = request: este fine-tune NO decide cuándo buscar, lo decide la app)
WEB_MODE = {"auto": "request"}.get(os.getenv("WEB_MODE", "").lower(), os.getenv("WEB_MODE", "").lower())
if WEB_MODE not in ("off", "request", "always"): WEB_MODE = "request" if WEB_AVAILABLE else "off"
if not WEB_AVAILABLE: WEB_MODE = "off"
MAX_GEN = int(os.getenv("MAX_GEN", "4000")) # máximo de tokens a generar por respuesta (el contexto del modelo es 4096: prompt + respuesta)
DEFAULT_MAX_TOKENS = int(os.getenv("DEFAULT_MAX_TOKENS", str(MAX_GEN))) # si el cliente no pide max_tokens: el modelo decide cuándo parar (<|end|>); baja este valor si tu CPU es lenta
WEB_BLOCK_TOKENS = 420 # tamaño máximo del bloque de búsqueda (igual que en el entrenamiento)
# Estos dos textos deben ser IGUALES a los del notebook de fine-tune.
SYSTEM_CHAT = ("Eres Milo, un asistente de IA amable, claro y honesto, creado por HIAKEU y basado en el modelo MiloX. "
"Respondes en español de forma directa y natural. Si no sabes algo con seguridad, lo dices.")
SYSTEM_WEB = ("Eres Milo, un asistente de IA. Recibes resultados de una búsqueda web. Responde con tus propias palabras "
"usando solo esa información, cita las fuentes como [1], [2], y si los resultados no bastan, dilo.")
device = "cuda" if torch.cuda.is_available() else "cpu"
def usable_cpus():
n = os.cpu_count() or 2
try: n = min(n, len(os.sched_getaffinity(0))) # núcleos permitidos al proceso
except Exception: pass
try: # límite real del contenedor (cgroup v2 / v1)
q, p = open("/sys/fs/cgroup/cpu.max").read().split()
if q != "max": n = min(n, max(1, int(math.ceil(int(q) / int(p)))))
except Exception:
try:
q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read()); p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read())
if q > 0: n = min(n, max(1, int(math.ceil(q / p))))
except Exception: pass
return max(1, n)
if device == "cpu":
N_THREADS = int(os.getenv("NUM_THREADS", usable_cpus()))
torch.set_num_threads(N_THREADS)
try: torch.set_num_interop_threads(1)
except Exception: pass
print(f"[MiloX] CPU: {N_THREADS} hilos (de {os.cpu_count()} que ve el sistema)")
HERE = os.path.dirname(os.path.abspath(__file__))
def _diagnose_repo():
"""Explica POR QUÉ falla la descarga (un repo privado sin token también devuelve 404)."""
from huggingface_hub import HfApi
msg = [f"No se pudo acceder al repo del modelo '{MODEL_ID}' en el Hub."]
try:
who = HfApi().whoami(token=HF_TOKEN)["name"] if HF_TOKEN else None
except Exception:
who = None
if HF_TOKEN: msg.append("· HF_TOKEN está definido pero es inválido o caducó (genera uno nuevo con permiso 'Read').")
if not HF_TOKEN:
msg.append("· HF_TOKEN NO está definido. Si el repo es privado, Hugging Face responde 404 (igual que si no existiera).")
msg.append(" → Space > Settings > Variables and secrets > New secret: HF_TOKEN = tu token (permiso Read).")
elif who:
msg.append(f"· Token válido (usuario: {who}), pero el repo no existe con ese nombre o ese usuario no tiene acceso.")
msg.append("· Comprueba el nombre exacto (mayúsculas incluidas): debe ser 'usuario/repo' y existir en huggingface.co.")
msg.append(" → Si el nombre es otro, define la variable MODEL_ID en el Space (p. ej. MODEL_ID=tuusuario/MiloX1-250M).")
msg.append("· Alternativa: sube tokenizer.json y milox1_chat.pt (o model.safetensors + config.json) junto a app.py; se usan directamente.")
return "\n".join(msg)
_diag_done = False
def fetch(name, required=True):
global _diag_done
if os.path.exists(os.path.join(HERE, name)): return os.path.join(HERE, name) # si subes los archivos al propio Space, los usa directo
try: return hf_hub_download(repo_id=MODEL_ID, filename=name, token=HF_TOKEN)
except Exception as e:
from huggingface_hub.errors import RepositoryNotFoundError, GatedRepoError, HfHubHTTPError
repo_problem = isinstance(e, (RepositoryNotFoundError, GatedRepoError))
if repo_problem and not _diag_done: # el repo en sí falla: dilo claro (una sola vez) y para
_diag_done = True
raise SystemExit("\n[MiloX] ERROR\n" + _diagnose_repo()) from None
if required: raise
print(f"[MiloX] {name} no está en {MODEL_ID}: {repr(e)[:80]}"); return None
tok = Tokenizer.from_file(fetch("tokenizer.json"))
SPECIALS = ["<|pad|>", "<|bos|>", "<|eos|>", "<|system|>", "<|user|>", "<|assistant|>", "<|end|>", "<|tool|>", "<|search|>", "<|think|>", "<|/think|>"]
if [tok.token_to_id(s) for s in SPECIALS] != list(range(11)):
raise RuntimeError(f"El tokenizer de {MODEL_ID} no es el de MiloX1 MoE 250M (tokens especiales distintos; debe incluir <|think|> y <|/think|>).")
PAD, BOS, EOS, SYS, USR, AST, END, TOOL, SEARCH, THINK, ETHINK = range(11)
def load_weights():
p = fetch(MODEL_FILE, required=False)
if p:
try: ck = torch.load(p, map_location="cpu", weights_only=True)
except Exception as e:
print("[MiloX] weights_only falló, cargo sin esa restricción (tu propio archivo):", repr(e)[:80]); ck = torch.load(p, map_location="cpu", weights_only=False)
return Cfg(**{k: v for k, v in ck["cfg"].items() if k in Cfg.__dataclass_fields__}), ck["model"], (ck.get("chat") or {})
from safetensors.torch import load_file # alternativa: model.safetensors + config.json
cj = json.load(open(fetch("config.json"), encoding="utf-8"))
cfg = Cfg(**{k: v for k, v in cj.items() if k in Cfg.__dataclass_fields__})
return cfg, load_file(fetch("model.safetensors")), {}
cfg, state, CHAT_META = load_weights()
if isinstance(CHAT_META.get("system_chat"), str): SYSTEM_CHAT = CHAT_META["system_chat"] # los mismos textos con los que se entrenó
if isinstance(CHAT_META.get("system_web"), str): SYSTEM_WEB = CHAT_META["system_web"]
model = MiloXModel(cfg)
_missing, _unexpected = model.load_state_dict(state, strict=False)
if [k for k in _missing if k != "lm_head.weight"] or _unexpected:
raise RuntimeError(f"Los pesos no coinciden con la arquitectura. Faltan: {_missing} | Sobran: {_unexpected}")
del state
model = (model.half() if device == "cuda" else model.float()).to(device).eval()
model.rebuild_rope()
MAX_POS = int(cfg.max_pos)
EOS_IDS = [END, EOS] # el modelo cierra cada respuesta con <|end|>
BANNED = torch.tensor([PAD, BOS, SYS, USR, AST, TOOL, SEARCH, THINK], device=device) # nunca debe escribir estos tokens de control
BAN_ETHINK = torch.tensor([ETHINK], device=device) # <|/think|> solo es válido mientras razona
LOCK = threading.Lock()
# ----------------------------- texto → tokens (misma plantilla que el entrenamiento) -----------------------------
def clean_text(s):
s = str(s if s is not None else "").replace("\r\n", "\n")
s = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", " ", s)
return s.replace("<|", "< |").strip() # el texto del usuario/web nunca puede invocar tokens especiales
def enc(text):
return tok.encode(clean_text(text)).ids
NL = tok.encode("\n").ids
def split_inline_think(text): # … dentro de un mensaje previo del asistente
m = re.match(r"^\s*(.*?)\s*(.*)$", str(text), flags=re.S)
return m.group(2).strip() if m else str(text).strip()
print(f"[MiloX] {MODEL_ID} en {device} | {model.n_params()/1e6:.1f}M params ({model.n_active()/1e6:.1f}M activos) | contexto {MAX_POS} | web={WEB_MODE} | historial={'sí' if USE_CONTEXT else 'no'} | thinking={'on' if THINKING_DEFAULT else 'off'}{'' if ALLOW_THINKING else ' (bloqueado)'} | temp={DEFAULT_TEMP}")
# ----------------------------- búsqueda web → bloque <|tool|><|search|> -----------------------------
def clean_snip(t, words=None):
t = re.sub(r"https?://\S+|www\.\S+", " ", str(t or "")) # sin URLs dentro del texto
t = re.sub(r"<\|[^>]{0,40}\|>", " ", t)
t = re.sub(r"[\x00-\x1f\x7f]", " ", t)
t = t.replace("[", "(").replace("]", ")") # evita falsas citas [n]
t = " ".join(t.split())
return " ".join(t.split()[:words]) if words else t
def domain_of(r):
d = str(r.get("domain") or "").strip()
if not d:
s = str(r.get("url") or r.get("source") or r.get("href") or "")
m = re.match(r"^(?:https?://)?(?:www\.)?([^/\s]+)", s)
d = m.group(1) if m else s
return clean_snip(d)[:40] or "web"
def text_of(r):
return r.get("text") or r.get("snippet") or r.get("body") or r.get("content") or ""
def render_search(query, results, max_tokens=WEB_BLOCK_TOKENS):
"""→ (texto del bloque, lista de resultados usados). Mismo formato y recorte que el notebook."""
q = clean_snip(query).replace("?", " ").replace("¿", " ")
q = " ".join(q.split())[:200]
rs = [r for r in (results or []) if isinstance(r, dict) and (r.get("title") or text_of(r))][:5]
if not rs: return f"consulta: {q}\nSin resultados.", []
n, snip = len(rs), 70
while True:
lines = [f"consulta: {q}"]
for i, r in enumerate(rs[:n], 1):
lines.append(f"[{i}] {clean_snip(r.get('title'), 16)} ({domain_of(r)})\n{clean_snip(text_of(r), snip)}")
text = "\n".join(lines)
if len(enc(text)) <= max_tokens: return text, rs[:n]
if n > 3: n -= 1
elif snip > 20: snip -= 10
elif n > 1: n -= 1
else: return text, rs[:n]
CHITCHAT = re.compile(r"^\s*(hola|buenas|gracias|muchas gracias|ok|vale|listo|perfecto|adi[oó]s|hasta luego|hi|hello|thanks|thank you|bye)\b[\s\.\!\?¡¿,]*$", re.I)
def make_query(text):
"""Sin contexto: la consulta es solo el mensaje actual."""
return " ".join(str(text).replace("?", " ").replace("¿", " ").split())[:200]
def builtin_search(query, n):
try:
try: from ddgs import DDGS
except ImportError: from duckduckgo_search import DDGS
rs = DDGS().text(query, max_results=n) or []
out = [{"title": r.get("title", ""), "url": r.get("href") or r.get("url", ""), "text": r.get("body", "")} for r in rs]
out = [r for r in out if r["title"] or r["text"]]
if out: return out[:n]
except Exception as e: print("[web] ddgs no disponible:", repr(e)[:100])
qs = urllib.parse.urlencode(dict(action="query", format="json", generator="search", gsrsearch=query, gsrlimit=n,
prop="extracts", exintro=1, explaintext=1, exlimit="max", exchars=600))
req = urllib.request.Request(f"https://{WEB_LANG}.wikipedia.org/w/api.php?{qs}", headers={"User-Agent": "MiloX1-Space/2.0"})
with urllib.request.urlopen(req, timeout=12) as r: data = json.loads(r.read().decode("utf-8", "replace"))
pages = sorted(((data.get("query") or {}).get("pages") or {}).values(), key=lambda p: p.get("index", 99))
return [{"title": p["title"], "url": f"https://{WEB_LANG}.wikipedia.org/wiki/" + urllib.parse.quote(p["title"].replace(" ", "_")),
"text": p.get("extract", "")} for p in pages if p.get("extract")][:n]
def call_search(query):
"""Tu buscador: POST {"query","max_results"} → {"results":[{"title","url","text"|"snippet","domain"?}]}. Sin URL: buscador integrado."""
if not WEB_SEARCH_URL: return builtin_search(query, WEB_MAX_RESULTS)
payload = json.dumps({"query": query, "max_results": WEB_MAX_RESULTS}).encode("utf-8")
headers = {"Content-Type": "application/json"}
if WEB_SEARCH_KEY: headers["Authorization"] = "Bearer " + WEB_SEARCH_KEY
req = urllib.request.Request(WEB_SEARCH_URL, data=payload, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=15) as r: data = json.loads(r.read().decode("utf-8", "replace"))
res = data.get("results")
if not isinstance(res, list) or not res: # el buscador solo entregó un texto ya armado
ctx = data.get("context")
res = [{"title": "Resultado de búsqueda", "text": ctx}] if isinstance(ctx, str) and ctx.strip() else []
return res[:WEB_MAX_RESULTS]
def do_search(user_text):
"""Hace UNA búsqueda con el mensaje del usuario → (bloque, info) o (None, None) si no corresponde."""
if CHITCHAT.match(user_text): return None, None # saludos/gracias: sin búsqueda (igual que en el entrenamiento)
q = make_query(user_text)
try: res = call_search(q)
except Exception as e:
print("[web] error en el buscador:", repr(e)[:160]); res = []
block, used = render_search(q, res)
return block, {"query": q, "sources": [{"n": i, "title": clean_snip(r.get("title"), 20) or "fuente", "url": str(r.get("url") or "")}
for i, r in enumerate(used, 1)]}
def fit_client_tool(tool, user_text):
"""Si el cliente ya trae su propio resultado (rol 'tool'), lo deja en el formato del bloque y dentro del límite."""
t = clean_text(tool)
if not t.lower().startswith("consulta:"): t = "consulta: " + make_query(user_text) + "\n" + t
while len(enc(t)) > WEB_BLOCK_TOKENS:
lines = t.split("\n")
t = "\n".join(lines[:-1]) if len(lines) > 2 else t[:int(len(t) * 0.8)]
return t
# ----------------------------- mensajes de la API → último turno → ids -----------------------------
def flat(content):
if content is None: return ""
if isinstance(content, str): return content
parts = []
for p in content:
if isinstance(p, str): parts.append(p)
elif isinstance(p, dict) and p.get("type") in (None, "text", "input_text"): parts.append(str(p.get("text", "")))
return "\n".join(parts)
ROLE_MAP = {"system": "system", "developer": "system", "user": "user", "assistant": "assistant", "tool": "tool", "function": "tool"}
def to_turn(msgs):
"""→ (historial [{'role','text'}], texto del ÚLTIMO mensaje del usuario o None, texto 'tool' asociado o None, system del cliente o None).
Con USE_CONTEXT=0 el historial se ignora y solo cuenta el último mensaje del usuario."""
turns, tool, sysm = [], None, None
for x in msgs:
r = ROLE_MAP.get(x.role, "user"); c = flat(x.content).strip()[:12000]
if r == "system":
if ALLOW_CLIENT_SYSTEM and c: sysm = clean_text(c)[:1500]
elif r == "tool":
if c: tool = c
elif r == "assistant":
tool = None # ese turno ya fue contestado
c = split_inline_think(c)
if c:
if turns and turns[-1]["role"] == "assistant": turns[-1]["text"] += "\n" + c
elif turns: turns.append({"role": "assistant", "text": c})
else:
if not c: continue
if turns and turns[-1]["role"] == "user": turns[-1]["text"] += "\n" + c # mensajes de usuario seguidos = un solo turno
else: turns.append({"role": "user", "text": c})
if not turns or turns[-1]["role"] != "user": return [], None, None, sysm
history = turns[:-1] if USE_CONTEXT else []
return history, turns[-1]["text"], tool, sysm
def build_ids(history, user_text, tool_text, system_text, max_new, think=False):
"""…[turnos previos]…[…][<|/think|>]\\n. → (ids, max_new).
Turnos previos del asistente: siempre con el pensamiento vacío (en el historial solo va la respuesta final)."""
use_tool = tool_text is not None
head = [BOS, SYS] + enc(system_text or (SYSTEM_WEB if use_tool else SYSTEM_CHAT)) + [END]
tool_ids = ([TOOL, SEARCH] + enc(tool_text) + [END]) if use_tool else []
asst_open = [AST, THINK] + NL if think else [AST, THINK, ETHINK] + NL
u = enc(user_text)[-max(64, MAX_POS - len(head) - len(tool_ids) - len(asst_open) - 100):]
tail = [USR] + u + [END] + tool_ids + asst_open
max_new = max(48, min(max_new, MAX_POS - len(head) - len(tail) - 1))
budget = MAX_POS - max_new - len(head) - len(tail)
kept, used = [], 0
pairs = [(history[i], history[i + 1]) for i in range(len(history) - 2, -1, -2) if history[i]["role"] == "user" and history[i + 1]["role"] == "assistant"]
for a, b in pairs: # de lo más reciente a lo más antiguo, mientras quepa
seg = [USR] + enc(a["text"]) + [END] + [AST, THINK, ETHINK] + NL + enc(b["text"]) + [END]
if used + len(seg) > budget: break
kept = seg + kept; used += len(seg)
return head + kept + tail, max_new
# ----------------------------- razonamiento (thinking) activable por petición -----------------------------
def _truthy(v):
"""True/False/None a partir de bool, número o texto ('on','off','enabled','none','low'…). None = no especificado."""
if v is None: return None
if isinstance(v, bool): return v
if isinstance(v, (int, float)): return v != 0
if isinstance(v, dict): # {"type":"enabled"|"disabled"} (estilo Anthropic/DeepSeek) o {"enabled":bool}
if "enabled" in v: return _truthy(v["enabled"])
return _truthy(v.get("type"))
s = str(v).strip().lower()
if s in ("1", "true", "on", "yes", "si", "sí", "enabled", "enable", "low", "medium", "high", "minimal", "auto", "think", "thinking"): return True
if s in ("0", "false", "off", "no", "disabled", "disable", "none", "null", ""): return False
return None
CMD_THINK = re.compile(r"^\s*/(pensar|think|razonar)\b[ \t]*", re.I)
CMD_NOTHINK = re.compile(r"^\s*/(no_?think|no_?pensar|directo|nothink)\b[ \t]*", re.I)
def resolve_thinking(req, user_text):
"""→ (razonar: bool, texto del usuario sin el comando). Prioridad: campo de la petición > comando /pensar | /no_think > THINKING_DEFAULT."""
ctk = req.chat_template_kwargs if isinstance(req.chat_template_kwargs, dict) else {}
explicit = None
for v in (req.thinking, req.enable_thinking, req.reasoning, req.razonar, req.reasoning_effort, ctk.get("enable_thinking"), ctk.get("thinking")):
explicit = _truthy(v)
if explicit is not None: break
cmd = None
if CMD_THINK.match(user_text): cmd = True; user_text = CMD_THINK.sub("", user_text, count=1)
elif CMD_NOTHINK.match(user_text): cmd = False; user_text = CMD_NOTHINK.sub("", user_text, count=1)
want = explicit if explicit is not None else (cmd if cmd is not None else THINKING_DEFAULT)
return bool(want and ALLOW_THINKING), (user_text.strip() or user_text)
# ----------------------------- generación (KV-cache + top-k / top-p / min-p / penalización de repetición / no-repeat n-grama) -----------------------------
def gen_kwargs(r, max_new, use_web, think=False):
t = r.temperature if r.temperature is not None else DEFAULT_TEMP
if use_web: t = min(t, 0.35) # con resultados web: respuesta más fiel (igual que el notebook)
rp = r.repetition_penalty if r.repetition_penalty is not None else (1.05 if use_web else 1.06)
mn = int(max_new) * 2 if think else int(max_new) # el pensamiento gasta tokens: doble presupuesto (como el notebook)
return dict(max_new=min(mn, MAX_GEN * (2 if think else 1)), temperature=float(t), top_p=r.top_p if r.top_p is not None else 0.9,
top_k=r.top_k if r.top_k is not None else 40, rep=float(rp), min_p=0.05, ngram=4, think=think)
@torch.inference_mode()
def _prefill(ids):
return model(torch.tensor([ids], device=device), use_cache=True, start_pos=0)
@torch.inference_mode()
def _decode(nxt, past, pos):
return model(torch.tensor([[nxt]], device=device), past=past, start_pos=pos, use_cache=True)
@torch.inference_mode()
def _sample(logits, seen, kw, step, bad, closed):
lg = logits[0, -1].float()
lg[BANNED] = -float("inf")
if not kw.get("think") or closed: lg[BAN_ETHINK] = -float("inf") # sin razonamiento (o ya cerrado) nunca escribe <|/think|>
if step == 0: lg[END] = -float("inf"); lg[EOS] = -float("inf") # nunca una respuesta vacía
if kw["rep"] != 1.0 and seen:
ids_t = torch.tensor(list(set(seen)), device=lg.device); sc = lg[ids_t]
lg[ids_t] = torch.where(sc > 0, sc / kw["rep"], sc * kw["rep"])
if bad: lg[torch.tensor(list(bad), device=lg.device)] = -float("inf")
if kw["temperature"] <= 0: return int(lg.argmax())
lg = lg / max(kw["temperature"], 1e-3)
if kw["top_k"] and kw["top_k"] > 0:
v, _ = torch.topk(lg, min(int(kw["top_k"]), lg.numel())); lg[lg < v[-1]] = -float("inf")
probs = F.softmax(lg, dim=-1)
if kw.get("min_p", 0) > 0:
probs = torch.where(probs >= kw["min_p"] * probs.max(), probs, torch.zeros_like(probs)); probs = probs / probs.sum()
if kw["top_p"] < 1.0:
sp, si = torch.sort(probs, descending=True); sp[sp.cumsum(0) - sp > kw["top_p"]] = 0
probs = torch.zeros_like(probs).scatter_(0, si, sp); probs = probs / probs.sum()
return int(torch.multinomial(probs, 1))
def token_stream(ids, kw):
"""Genera ids de uno en uno (incluye <|/think|> si razona). El candado se toma solo durante cada paso del modelo."""
ids = list(ids)
room = MAX_POS - len(ids) - 1 # prompt + respuesta comparten el contexto (también con razonamiento ×2)
if room >= 48: kw["max_new"] = max(1, min(int(kw["max_new"]), room))
else: ids = ids[-(MAX_POS - 49):]; kw["max_new"] = 48
kw["_finish"] = "length"; t0 = time.time(); n = 0
with LOCK:
logits, past = _prefill(ids)
t1 = time.time(); pos = len(ids); seen = []; gen_ids = []; ngr = {}; closed = False; hist = []
ng = int(kw.get("ngram") or 0)
if ng >= 2 and kw["max_new"] > 600: ng = max(ng, 6) # respuestas largas: n-grama mayor (no veta frases legítimas repetidas)
try:
for step in range(kw["max_new"]):
bad = ngr.get(tuple(gen_ids[-(ng - 1):])) if ng >= 2 and len(gen_ids) >= ng - 1 else None
with LOCK:
nxt = _sample(logits, seen, kw, step, bad, closed)
if nxt in EOS_IDS: kw["_finish"] = "stop"; break
yield nxt; n += 1
hist.append(nxt)
if n >= 256 and n % 64 == 0 and len(set(hist[-256:])) < 26: break # bucle degenerado (≤25 tokens distintos en los últimos 256): corta; finish = length
if nxt == ETHINK: closed = True
if ng >= 2:
if len(gen_ids) >= ng - 1: ngr.setdefault(tuple(gen_ids[-(ng - 1):]), set()).add(nxt)
gen_ids.append(nxt)
if nxt > ETHINK: seen.append(nxt)
if pos >= MAX_POS: break
with LOCK:
logits, past = _decode(nxt, past, pos)
pos += 1
finally:
dt = max(1e-6, time.time() - t1)
print(f"[gen] prompt {len(ids)} tok ({t1 - t0:.1f}s) | salida {n} tok en {dt:.1f}s ({n / dt:.1f} tok/s) | think={kw.get('think')} | {kw['_finish']}", flush=True)
def run(ids, kw):
"""→ (respuesta, pensamiento, nº tokens, finish_reason)."""
think_ids, ans_ids, in_think, n = [], [], bool(kw.get("think")), 0
for t in token_stream(ids, kw):
n += 1
if t == ETHINK: in_think = False; continue
(think_ids if in_think else ans_ids).append(t)
ans = tok.decode(ans_ids, skip_special_tokens=True).strip(); th = tok.decode(think_ids, skip_special_tokens=True).strip()
if kw.get("think") and not ans and th: ans, th = th, "" # no llegó a cerrar el pensamiento: lo escrito es la respuesta
return ans, th, n, kw.get("_finish", "stop")
def stream_tokens(ids, kw):
"""Genera (tipo, trozo) con tipo 'think' | 'answer' (evita cortar caracteres UTF-8 a la mitad).
Si razona y el pensamiento nunca se cierra, devuelve ('fallback', texto) con lo escrito para que el cliente lo trate como respuesta."""
think_ids, ans_ids, in_think = [], [], bool(kw.get("think"))
printed = {"think": "", "answer": ""}; first = {"think": True, "answer": True}
try:
for t in token_stream(ids, kw):
if t == ETHINK: in_think = False; continue
kind = "think" if in_think else "answer"; cur = think_ids if in_think else ans_ids
cur.append(t); text = tok.decode(cur, skip_special_tokens=True)
if text.endswith("\ufffd"): continue
piece = text[len(printed[kind]):]; printed[kind] = text
if first[kind]: piece = piece.lstrip()
if piece: first[kind] = False; yield kind, piece
if kw.get("think") and in_think and think_ids: yield "fallback", ""
except Exception as e:
print("[gen] error:", repr(e)[:160])
def sse(obj): return "data: " + json.dumps(obj, ensure_ascii=False) + "\n\n"
def web_enabled(req):
if req.web_search is False or not WEB_AVAILABLE: return False
return req.web_search is True or WEB_MODE == "always"
# ----------------------------- esquemas -----------------------------
class Msg(BaseModel):
role: str
content: Union[str, List[Any], None] = ""
class ChatReq(BaseModel):
model: Optional[str] = None
messages: List[Msg]
temperature: Optional[float] = None # por defecto 0.6 (con búsqueda web se limita a 0.35)
top_p: Optional[float] = None
top_k: Optional[int] = None
max_tokens: Optional[int] = None # por defecto DEFAULT_MAX_TOKENS
max_completion_tokens: Optional[int] = None
stream: bool = False
repetition_penalty: Optional[float] = None
web_search: Optional[bool] = None # extensión: true = buscar en la web, false = no buscar
# razonamiento (thinking): true = razona antes de responder · false = responde directo · omitido = THINKING_DEFAULT
thinking: Optional[Union[bool, str, dict]] = None # true/false · "enabled"/"disabled" · {"type":"enabled"}
enable_thinking: Optional[bool] = None # alias estilo Qwen3
reasoning: Optional[Union[bool, str, dict]] = None # alias
razonar: Optional[bool] = None # alias en español
reasoning_effort: Optional[str] = None # alias estilo OpenAI: "none"/"off" = apagado; "low"/"medium"/"high" = encendido
chat_template_kwargs: Optional[dict] = None # {"enable_thinking": true}
class CompReq(BaseModel):
model: Optional[str] = None
prompt: Union[str, List[str]]
temperature: float = 0.6
top_p: float = 0.9
top_k: int = 40
max_tokens: Optional[int] = 256
repetition_penalty: float = 1.06
app = FastAPI(title="MiloX1 API", version="3.0")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
def check_auth(authorization):
if API_KEY and authorization != f"Bearer {API_KEY}":
raise HTTPException(status_code=401, detail={"error": {"message": "API key inválida", "type": "invalid_request_error", "code": "invalid_api_key"}})
# ----------------------------- endpoints -----------------------------
@app.get("/info")
def info():
return {"name": "MiloX1 MoE 250M (compatible con OpenAI)", "model": MODEL_ID, "model_name": MODEL_NAME, "device": device, "context": MAX_POS,
"use_context": USE_CONTEXT, "params_m": round(model.n_params() / 1e6, 1), "active_params_m": round(model.n_active() / 1e6, 1), "temperature": DEFAULT_TEMP, "auth_required": bool(API_KEY), "web": WEB_AVAILABLE, "web_mode": WEB_MODE,
"web_backend": "url" if WEB_SEARCH_URL else ("integrado" if WEB_BUILTIN else None), "chat_format": "milox-chat-v2-think",
"thinking": ALLOW_THINKING, "thinking_default": THINKING_DEFAULT,
"endpoints": ["/v1/models", "/v1/chat/completions", "/v1/completions", "/health", "/docs"]}
@app.get("/", response_class=HTMLResponse)
def home():
return CHAT_HTML
@app.get("/health")
def health():
return {"status": "ok", "device": device}
@app.get("/v1/models")
def models(authorization: Optional[str] = Header(None)):
check_auth(authorization)
return {"object": "list", "data": [{"id": MODEL_NAME, "object": "model", "created": 0, "owned_by": "hiakeu"}]}
@app.post("/v1/chat/completions")
def chat_completions(req: ChatReq, authorization: Optional[str] = Header(None)):
check_auth(authorization)
history, user_text, client_tool, client_system = to_turn(req.messages)
if not user_text:
raise HTTPException(400, detail={"error": {"message": "el último mensaje debe ser del usuario", "type": "invalid_request_error"}})
think, user_text = resolve_thinking(req, user_text) # thinking: true/false en la petición, /pensar, o THINKING_DEFAULT
max_new = min(req.max_completion_tokens or req.max_tokens or DEFAULT_MAX_TOKENS, MAX_GEN)
web = web_enabled(req)
cid, created, name = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time()), req.model or MODEL_NAME
def prepare(): # → (bloque de búsqueda | None, info web | None)
if client_tool: return fit_client_tool(client_tool, user_text), None
if web: return do_search(user_text)
return None, None
if not req.stream:
tool_text, winfo = prepare()
ids, mn = build_ids(history, user_text, tool_text, client_system, max_new, think)
text, th, n_out, finish = run(ids, gen_kwargs(req, mn, tool_text is not None, think))
msg = {"role": "assistant", "content": text}
if think: msg["reasoning_content"] = th
resp = {"id": cid, "object": "chat.completion", "created": created, "model": name, "thinking": think,
"choices": [{"index": 0, "message": msg, "finish_reason": finish}],
"usage": {"prompt_tokens": len(ids), "completion_tokens": n_out, "total_tokens": len(ids) + n_out}}
if winfo: resp["web_search"] = winfo
return resp
def gen():
base = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": name}
yield sse({**base, "thinking": think, "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}]})
try: tool_text, winfo = prepare()
except Exception as e: print("[web] fallo:", repr(e)[:160]); tool_text, winfo = None, None
if winfo: yield sse({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": None}], "web_search": winfo})
ids, mn = build_ids(history, user_text, tool_text, client_system, max_new, think)
n_ans = 0
for kind, piece in stream_tokens(ids, gen_kwargs(req, mn, tool_text is not None, think)):
if kind == "think": yield sse({**base, "choices": [{"index": 0, "delta": {"reasoning_content": piece}, "finish_reason": None}]})
elif kind == "answer": n_ans += len(piece); yield sse({**base, "choices": [{"index": 0, "delta": {"content": piece}, "finish_reason": None}]})
elif kind == "fallback" and n_ans == 0: yield sse({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": None}], "thinking_unclosed": True})
yield sse({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]})
yield "data: [DONE]\n\n"
return StreamingResponse(gen(), media_type="text/event-stream")
@app.post("/v1/completions")
def completions(req: CompReq, authorization: Optional[str] = Header(None)):
check_auth(authorization)
prompt = req.prompt if isinstance(req.prompt, str) else (req.prompt[0] if req.prompt else "")
max_new = min(req.max_tokens or 256, MAX_GEN)
ids = enc(prompt)
max_new = max(48, min(max_new, MAX_POS - len(ids) - 1)) # prompt y respuesta comparten el contexto
ids = ids[-(MAX_POS - max_new):] # texto libre (sin plantilla de chat)
kw = dict(max_new=int(max_new), temperature=float(req.temperature), top_p=req.top_p, top_k=req.top_k, rep=float(req.repetition_penalty), min_p=0.05, ngram=4, think=False)
text, _, n_out, finish = run(ids, kw)
return {"id": "cmpl-" + uuid.uuid4().hex[:24], "object": "text_completion", "created": int(time.time()), "model": req.model or MODEL_NAME,
"choices": [{"index": 0, "text": text, "finish_reason": finish}],
"usage": {"prompt_tokens": len(ids), "completion_tokens": n_out, "total_tokens": len(ids) + n_out}}
# ----------------------------- chat web -----------------------------
CHAT_HTML = r"""
Milo · MiloX1
M
MiloMiloX1
M
Hola, soy MiloEscribe un mensaje para empezar.
Ajustes
"""
# ----------------------------- arranque -----------------------------
# Funciona con `python app.py` y también con `uvicorn app:app --host 0.0.0.0 --port 7860`.
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))