Spaces:
adrianrossv
/
Running

File size: 56,733 Bytes
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
 
 
127213d
90ad646
127213d
90ad646
127213d
90ad646
 
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
127213d
 
 
 
 
90ad646
127213d
 
 
90ad646
127213d
 
 
90ad646
127213d
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
127213d
 
90ad646
127213d
 
90ad646
127213d
 
90ad646
127213d
 
 
 
 
 
 
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
 
127213d
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
127213d
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
 
127213d
 
90ad646
127213d
 
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ad646
127213d
 
 
 
 
 
 
 
 
90ad646
127213d
90ad646
127213d
90ad646
127213d
 
 
90ad646
127213d
 
 
 
90ad646
127213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
"""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):                                       # <think>…</think> dentro de un mensaje previo del asistente
    m = re.match(r"^\s*<think>(.*?)</think>\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):
    """<bos><system>…<end>[turnos previos]<user>…<end>[<tool><search>…<end>]<assistant><think>[<|/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"""<!DOCTYPE html>
<html lang="es"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<title>Milo · MiloX1</title>
<style>
:root{--bg:#f2f2f7;--card:#fff;--text:#1c1c1e;--sub:#6e6e73;--line:rgba(60,60,67,.16);--blue:#007aff;--fill:rgba(120,120,128,.12);--bot:#e9e9eb;--glass:rgba(242,242,247,.74)}
@media(prefers-color-scheme:dark){:root{--bg:#000;--card:#1c1c1e;--text:#f5f5f7;--sub:#98989f;--line:rgba(84,84,88,.55);--blue:#0a84ff;--fill:rgba(120,120,128,.24);--bot:#26262a;--glass:rgba(0,0,0,.62)}}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{height:100%;margin:0}
body{background:var(--bg);color:var(--text);font:16px/1.4 -apple-system,BlinkMacSystemFont,"SF Pro Text","Helvetica Neue",Arial,sans-serif;display:flex;flex-direction:column;-webkit-font-smoothing:antialiased}
header{display:flex;align-items:center;gap:12px;padding:calc(10px + env(safe-area-inset-top)) 16px 10px;background:var(--glass);-webkit-backdrop-filter:saturate(180%) blur(22px);backdrop-filter:saturate(180%) blur(22px);border-bottom:1px solid var(--line);z-index:5}
.logo{width:38px;height:38px;border-radius:10px;background:linear-gradient(145deg,#5ac8fa,#007aff 55%,#5856d6);color:#fff;display:grid;place-items:center;font-weight:700}
.t{flex:1;line-height:1.15}.t b{font-size:18px;letter-spacing:-.02em}.t small{display:block;color:var(--sub);font-size:12px}
.ib{border:0;background:var(--fill);color:var(--text);height:34px;padding:0 12px;border-radius:17px;font:inherit;font-size:14px;font-weight:600;cursor:pointer}
main{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:8px;max-width:760px;width:100%;margin:0 auto}
.empty{margin:auto;text-align:center;color:var(--sub)}.empty .logo{width:64px;height:64px;font-size:28px;border-radius:16px;margin:0 auto 12px}.empty b{display:block;color:var(--text);font-size:20px}
.b{max-width:82%;padding:9px 14px;border-radius:20px;white-space:pre-wrap;word-wrap:break-word;animation:in .2s ease}
@keyframes in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.user{align-self:flex-end;background:var(--blue);color:#fff;border-bottom-right-radius:6px}
.bot{align-self:flex-start;background:var(--bot);border-bottom-left-radius:6px}
.bot.err{color:#ff453a}
.typing:empty::after{content:"●●●";letter-spacing:3px;color:var(--sub);animation:bl 1s infinite}
@keyframes bl{50%{opacity:.3}}
.chip{align-self:flex-start;font-size:13px;color:var(--sub);background:var(--fill);border-radius:999px;padding:4px 12px}
.src{align-self:flex-start;max-width:82%;font-size:13px;color:var(--sub);display:flex;flex-wrap:wrap;gap:6px}
.src a,.src span{background:var(--fill);color:var(--text);text-decoration:none;border-radius:999px;padding:3px 10px}
form{display:flex;gap:8px;align-items:flex-end;padding:10px 12px calc(10px + env(safe-area-inset-bottom));background:var(--glass);-webkit-backdrop-filter:saturate(180%) blur(22px);backdrop-filter:saturate(180%) blur(22px);border-top:1px solid var(--line)}
form .in{flex:1;max-width:720px;margin:0 auto;display:flex;gap:8px;align-items:flex-end;width:100%}
textarea{flex:1;resize:none;border:1px solid var(--line);background:var(--card);color:var(--text);border-radius:20px;padding:9px 14px;font:inherit;max-height:140px;outline:0}
textarea:focus{border-color:var(--blue)}
#s{width:36px;height:36px;border-radius:50%;border:0;background:var(--blue);color:#fff;cursor:pointer;display:grid;place-items:center;flex:none}
#s:disabled{opacity:.4}
.ov{position:fixed;inset:0;background:rgba(0,0,0,.35);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);display:none;place-items:center;padding:20px;z-index:20}
.ov.on{display:grid}
.sh{width:min(100%,420px);background:var(--card);border-radius:22px;padding:20px;box-shadow:0 20px 60px rgba(0,0,0,.35)}
.sh h3{margin:0 0 12px}.sh label{display:flex;justify-content:space-between;color:var(--sub);font-size:14px;margin-top:12px}
.sh input[type=range]{width:100%}.sh p{color:var(--sub);font-size:13px;margin:14px 0 0}
.ib.on{background:var(--blue);color:#fff}
.th{align-self:flex-start;max-width:82%;font-size:13px;color:var(--sub);background:var(--fill);border-radius:14px;padding:6px 12px;white-space:pre-wrap;word-wrap:break-word}
.th summary{cursor:pointer;font-weight:600}
</style></head><body>
<header><div class="logo">M</div><div class="t"><b>Milo</b><small id="sub">MiloX1</small></div><button class="ib" id="web" style="display:none">🔎 Web</button><button class="ib" id="think" style="display:none">💭 Pensar</button><button class="ib" id="cfg">Ajustes</button><button class="ib" id="clr">Nuevo</button></header>
<main id="chat"><div class="empty" id="empty"><div class="logo">M</div><b>Hola, soy Milo</b>Escribe un mensaje para empezar.</div></main>
<form id="f"><div class="in"><textarea id="t" rows="1" placeholder="Escribe un mensaje"></textarea><button id="s" type="submit" aria-label="Enviar"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg></button></div></form>
<div class="ov" id="ov"><div class="sh"><h3>Ajustes</h3>
<label>Creatividad (temperature) <span id="vt">0.6</span></label><input type="range" id="temp" min="0" max="1.2" step="0.05" value="0.6">
<label>Longitud máxima (tokens) <span id="vm">1024</span></label><input type="range" id="max" min="32" max="4000" step="8" value="1024">
<label>top_p <span id="vp">0.9</span></label><input type="range" id="topp" min="0.1" max="1" step="0.05" value="0.9">
<p id="ctx"></p><button class="ib" id="ok" style="margin-top:14px;width:100%">Listo</button></div></div>
<script>
const $=s=>document.querySelector(s);
let info={web:false},hist=[],busy=false,webOn=false,thinkOn=false,key=localStorage.getItem('milox_key')||'';
function askKey(){key=prompt('Este Space pide una clave de acceso (API_KEY):')||'';localStorage.setItem('milox_key',key)}
fetch('/info').then(r=>r.json()).then(d=>{info=d;initWeb();initThink();$('#sub').textContent=d.model_name+(d.web?' · búsqueda web':'');$('#ctx').textContent=(d.use_context?'Milo recuerda la conversación (hasta '+d.context+' tokens).':'Cada mensaje se responde por separado, sin memoria de la conversación.')+(d.web?(d.web_mode==='always'?' Busca en la web en cada mensaje.':' Activa «🔎 Web» para que busque en internet.'):'');if(d.auth_required&&!key)askKey()}).catch(()=>{});
function initWeb(){const b=$('#web');if(!info.web)return;if(info.web_mode==='always'){webOn=true;return}b.style.display='';b.onclick=()=>{webOn=!webOn;b.classList.toggle('on',webOn)}}
function initThink(){const b=$('#think');if(!info.thinking)return;b.style.display='';thinkOn=!!info.thinking_default;b.classList.toggle('on',thinkOn);b.onclick=()=>{thinkOn=!thinkOn;b.classList.toggle('on',thinkOn)}}
function add(role,text){const e=$('#empty');if(e)e.remove();const d=document.createElement('div');d.className='b '+role;d.textContent=text;$('#chat').appendChild(d);d.scrollIntoView({block:'end'});return d}
function grow(){const t=$('#t');t.style.height='auto';t.style.height=Math.min(t.scrollHeight,140)+'px'}
function showWeb(w,out){
  const chip=document.createElement('div');chip.className='chip';chip.textContent='🔎 Busqué: '+w.query;out.parentNode.insertBefore(chip,out);
  window._srcs=w.sources||[];
}
function showSources(){
  const s=window._srcs||[];if(!s.length)return;const d=document.createElement('div');d.className='src';
  s.forEach(x=>{const ok=/^https?:\/\//.test(x.url||'');const e=document.createElement(ok?'a':'span');e.textContent='['+x.n+'] '+(x.title||'fuente');if(ok){e.href=x.url;e.target='_blank';e.rel='noopener'}d.appendChild(e)});
  $('#chat').appendChild(d);d.scrollIntoView({block:'end'});
}
async function send(){
  const text=$('#t').value.trim();if(!text||busy)return;$('#t').value='';grow();
  add('user',text);const out=add('bot','');out.classList.add('typing');busy=true;$('#s').disabled=true;window._srcs=[];
  hist.push({role:'user',content:text});
  const msgs=info.use_context?hist.slice(-30):[{role:'user',content:text}];
  try{
    const r=await fetch('/v1/chat/completions',{method:'POST',headers:Object.assign({'Content-Type':'application/json'},key?{Authorization:'Bearer '+key}:{}),
      body:JSON.stringify({messages:msgs,stream:true,temperature:+$('#temp').value,top_p:+$('#topp').value,max_tokens:+$('#max').value,web_search:(info.web&&info.web_mode!=='always')?webOn:undefined,thinking:info.thinking?thinkOn:undefined})});
    if(r.status===401){askKey();throw new Error('Falta la clave de acceso.')}
    if(!r.ok)throw new Error('Error del servidor ('+r.status+')');
    const rd=r.body.getReader(),dec=new TextDecoder();let buf='',full='',tfull='',tbox=null;
    while(true){const x=await rd.read();if(x.done)break;buf+=dec.decode(x.value,{stream:true});const parts=buf.split('\n\n');buf=parts.pop();
      for(const p of parts){if(p.indexOf('data: ')!==0)continue;const j=p.slice(6);if(j==='[DONE]')continue;
        try{const o=JSON.parse(j);if(o.web_search){showWeb(o.web_search,out)}
          const dl=o.choices&&o.choices[0]&&o.choices[0].delta||{};const rc=dl.reasoning_content;if(rc){if(!tbox){tbox=document.createElement('details');tbox.className='th';tbox.open=true;tbox.innerHTML='<summary>💭 Pensando…</summary><div></div>';out.parentNode.insertBefore(tbox,out)}tfull+=rc;tbox.lastChild.textContent=tfull;tbox.scrollIntoView({block:'end'})}
          const c=dl.content;if(c){if(tbox){tbox.open=false;tbox.firstChild.textContent='💭 Pensamiento'}full+=c;out.textContent=full;out.scrollIntoView({block:'end'})}}catch(e){}}}
    out.classList.remove('typing');if(!full&&tfull){full=tfull;out.textContent=full;if(tbox)tbox.remove()}if(!full)out.textContent='(sin respuesta)';else hist.push({role:'assistant',content:full});showSources();
  }catch(e){hist.pop();out.classList.remove('typing');out.classList.add('err');out.textContent='⚠ '+e.message}
  busy=false;$('#s').disabled=false;$('#t').focus();
}
$('#f').onsubmit=e=>{e.preventDefault();send()};
$('#t').addEventListener('input',grow);
$('#t').addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send()}});
$('#clr').onclick=()=>{hist=[];$('#chat').innerHTML='<div class="empty" id="empty"><div class="logo">M</div><b>Hola, soy Milo</b>Escribe un mensaje para empezar.</div>'};
$('#cfg').onclick=()=>$('#ov').classList.add('on');$('#ok').onclick=()=>$('#ov').classList.remove('on');
$('#ov').onclick=e=>{if(e.target.id==='ov')$('#ov').classList.remove('on')};
[['temp','vt'],['max','vm'],['topp','vp']].forEach(([a,b])=>$('#'+a).oninput=()=>$('#'+b).textContent=$('#'+a).value);
</script></body></html>"""

# ----------------------------- 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")))