-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.py
More file actions
941 lines (833 loc) · 29.4 KB
/
Copy pathserver.py
File metadata and controls
941 lines (833 loc) · 29.4 KB
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
import json
import os
import re
import ssl
import time
import sqlite3
import shutil
import subprocess
import tempfile
import urllib.parse
import urllib.request
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
ROOT = Path(__file__).resolve().parent
SITE_DIR = ROOT / "site"
DATA_DIR = ROOT / "data"
CHAT_DIR = DATA_DIR / "chat_sessions"
LOG_FILE = DATA_DIR / "chat_logs.jsonl"
DATA_DIR.mkdir(parents=True, exist_ok=True)
CHAT_DIR.mkdir(parents=True, exist_ok=True)
def load_env_file(p):
try:
if not p.exists() or not p.is_file():
return
for raw in p.read_text(encoding="utf-8", errors="replace").splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
k, v = line.split("=", 1)
key = k.strip()
if not key:
continue
val = v.strip()
if (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):
val = val[1:-1]
if key not in os.environ:
os.environ[key] = val
except Exception:
return
def load_env_files():
env_path = os.getenv("MINIMAX_ENV_FILE", "").strip()
if env_path:
load_env_file(Path(env_path))
load_env_file(ROOT / ".env.local")
load_env_file(ROOT / ".env")
load_env_files()
def now_ms():
return int(time.time() * 1000)
CPP_RUN_DIR = DATA_DIR / "cpp_runs"
CPP_RUN_DIR.mkdir(parents=True, exist_ok=True)
def cpp_find_compiler():
override = os.getenv("CPP_COMPILER", "").strip()
if override:
p = shutil.which(override) or override
return p
for name in ("g++", "clang++"):
p = shutil.which(name)
if p:
return p
return ""
def cpp_compile(code, timeout_sec=10.0):
compiler = cpp_find_compiler()
if not compiler:
return {"ok": False, "error": "未找到 C++ 编译器(g++/clang++)。请先安装 MinGW-w64 或 LLVM,并确保编译器在 PATH 中。"}
tmpdir = Path(tempfile.mkdtemp(prefix="cpp_", dir=str(CPP_RUN_DIR)))
src = tmpdir / "main.cpp"
exe = tmpdir / ("main.exe" if os.name == "nt" else "main.out")
src.write_text(str(code or ""), encoding="utf-8", errors="replace")
cmd = [compiler, str(src), "-std=c++17", "-O2", "-pipe", "-o", str(exe)]
t0 = time.time()
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_sec)
except subprocess.TimeoutExpired:
return {"ok": False, "error": "编译超时", "cmd": cmd}
except Exception as e:
return {"ok": False, "error": str(e), "cmd": cmd}
dt = int((time.time() - t0) * 1000)
out = (p.stdout or "")[-20000:]
err = (p.stderr or "")[-20000:]
if p.returncode != 0 or not exe.exists():
return {"ok": False, "error": "编译失败", "stdout": out, "stderr": err, "exitCode": p.returncode, "timeMs": dt, "cmd": cmd}
return {"ok": True, "exe": str(exe), "stdout": out, "stderr": err, "exitCode": p.returncode, "timeMs": dt, "cmd": cmd}
def cpp_run_exe(exe_path, stdin_text, timeout_sec=2.0):
t0 = time.time()
try:
p = subprocess.run(
[str(exe_path)],
input=str(stdin_text or ""),
capture_output=True,
text=True,
timeout=timeout_sec,
)
dt = int((time.time() - t0) * 1000)
out = (p.stdout or "")[-200000:]
err = (p.stderr or "")[-200000:]
return {"ok": True, "stdout": out, "stderr": err, "exitCode": p.returncode, "timeMs": dt, "timedOut": False}
except subprocess.TimeoutExpired as e:
dt = int((time.time() - t0) * 1000)
out = (getattr(e, "stdout", "") or "")[-200000:]
err = (getattr(e, "stderr", "") or "")[-200000:]
return {"ok": True, "stdout": out, "stderr": err, "exitCode": -1, "timeMs": dt, "timedOut": True}
except Exception as e:
dt = int((time.time() - t0) * 1000)
return {"ok": False, "error": str(e), "timeMs": dt}
def cpp_cleanup_path(p):
try:
if not p:
return
d = Path(p).resolve().parent
if d.exists() and d.is_dir() and str(d).startswith(str(CPP_RUN_DIR.resolve())):
shutil.rmtree(d, ignore_errors=True)
except Exception:
return
def normalize_text_output(s, check=None):
check = check if isinstance(check, dict) else {}
t = str(s or "").replace("\r\n", "\n").replace("\r", "\n")
if check.get("ignoreTrailingSpaces") is not False:
t = "\n".join([ln.rstrip() for ln in t.split("\n")])
if check.get("trim") is not False:
t = t.strip()
if check.get("ignoreWhitespace"):
t = re.sub(r"\s+", " ", t).strip()
return t
def cpp_compare_output(got, expected, check=None):
g = normalize_text_output(got, check)
e = normalize_text_output(expected, check)
return g == e
SQL_DATASETS_PATH = SITE_DIR / "sql_datasets.json"
_SQL_DATASETS_CACHE = None
def load_sql_datasets():
global _SQL_DATASETS_CACHE
if _SQL_DATASETS_CACHE is not None:
return _SQL_DATASETS_CACHE
try:
if not SQL_DATASETS_PATH.exists():
_SQL_DATASETS_CACHE = {}
return _SQL_DATASETS_CACHE
obj = json.loads(SQL_DATASETS_PATH.read_text(encoding="utf-8", errors="replace"))
_SQL_DATASETS_CACHE = obj if isinstance(obj, dict) else {}
return _SQL_DATASETS_CACHE
except Exception:
_SQL_DATASETS_CACHE = {}
return _SQL_DATASETS_CACHE
def strip_sql_comments(sql):
s = str(sql or "")
s = re.sub(r"/\*[\s\S]*?\*/", " ", s)
s = re.sub(r"--[^\n]*", " ", s)
return s
def is_select_only(sql):
s = strip_sql_comments(sql).strip()
if not s:
return False
parts = [p.strip() for p in s.split(";") if p.strip()]
if len(parts) != 1:
return False
head = parts[0].lstrip()
m = re.match(r"^([A-Za-z]+)", head)
if not m:
return False
first = m.group(1).lower()
if first not in ("select", "with"):
return False
bad = [
"insert",
"update",
"delete",
"drop",
"alter",
"create",
"replace",
"pragma",
"attach",
"detach",
"vacuum",
"reindex",
"analyze",
"transaction",
"begin",
"commit",
"rollback",
]
s2 = re.sub(r"\s+", " ", head.lower())
for kw in bad:
if re.search(rf"\b{re.escape(kw)}\b", s2):
return False
return True
def sql_make_conn():
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
return conn
def sql_apply_dataset(conn, ds):
if not ds or not isinstance(ds, dict):
return
tables = ds.get("tables")
if not isinstance(tables, list):
return
cur = conn.cursor()
for t in tables:
if not isinstance(t, dict):
continue
name = str(t.get("name") or "").strip()
cols = t.get("columns")
rows = t.get("rows")
if not name or not isinstance(cols, list) or not isinstance(rows, list):
continue
col_defs = []
col_names = []
for c in cols:
if not isinstance(c, dict):
continue
cn = str(c.get("name") or "").strip()
ct = str(c.get("type") or "TEXT").strip() or "TEXT"
if not cn:
continue
col_names.append(cn)
col_defs.append(f'"{cn}" {ct}')
if not col_defs:
continue
cur.execute(f'CREATE TABLE "{name}" ({", ".join(col_defs)});')
if rows:
placeholders = ", ".join(["?"] * len(col_names))
cols_sql = ", ".join([f'"{x}"' for x in col_names])
cur.executemany(f'INSERT INTO "{name}" ({cols_sql}) VALUES ({placeholders});', rows)
conn.commit()
def sql_fetch_result(cur, limit=200):
cols = [d[0] for d in (cur.description or [])]
out_rows = []
n = 0
for r in cur.fetchall():
if n >= limit:
break
if isinstance(r, sqlite3.Row):
out_rows.append([r[c] for c in cols])
else:
out_rows.append(list(r))
n += 1
return {"columns": cols, "rows": out_rows, "truncated": n >= limit}
def sql_normalize_value(v):
if v is None:
return None
if isinstance(v, float):
if v == 0:
return 0.0
return float(f"{v:.10g}")
return v
def sql_normalize_result(res, check=None):
check = check if isinstance(check, dict) else {}
rows = res.get("rows") if isinstance(res, dict) else None
cols = res.get("columns") if isinstance(res, dict) else None
if not isinstance(rows, list) or not isinstance(cols, list):
return {"columns": [], "rows": []}
norm_rows = []
for r in rows:
if not isinstance(r, list):
continue
norm_rows.append([sql_normalize_value(x) for x in r])
row_order_matters = bool(check.get("rowOrderMatters")) if "rowOrderMatters" in check else False
if not row_order_matters:
norm_rows = sorted(norm_rows, key=lambda x: json.dumps(x, ensure_ascii=False, sort_keys=True))
return {"columns": cols, "rows": norm_rows}
def sql_compare(user_res, exp_res, check=None):
u = sql_normalize_result(user_res, check)
e = sql_normalize_result(exp_res, check)
col_order_matters = bool(check.get("colOrderMatters")) if isinstance(check, dict) and "colOrderMatters" in check else True
if col_order_matters:
if u["columns"] != e["columns"]:
return False, "列不一致"
if u["rows"] != e["rows"]:
return False, "结果行不一致"
return True, ""
u_map = {str(c): i for i, c in enumerate(u["columns"])}
e_map = {str(c): i for i, c in enumerate(e["columns"])}
if set(u_map.keys()) != set(e_map.keys()):
return False, "列集合不一致"
cols = sorted(u_map.keys())
u_rows = [[r[u_map[c]] for c in cols] for r in u["rows"]]
e_rows = [[r[e_map[c]] for c in cols] for r in e["rows"]]
if u_rows != e_rows:
return False, "结果行不一致"
return True, ""
def safe_session_id(session_id):
s = re.sub(r"[^a-zA-Z0-9_-]+", "_", str(session_id or "")).strip("_")
if not s:
s = f"s_{now_ms()}"
return s[:80]
def session_path(session_id):
return CHAT_DIR / f"{safe_session_id(session_id)}.json"
def read_session_messages(session_id):
p = session_path(session_id)
if not p.exists():
return []
try:
with p.open("r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return [m for m in data if isinstance(m, dict)]
return []
except Exception:
return []
def write_session_messages(session_id, messages):
p = session_path(session_id)
tmp = p.with_suffix(".json.tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(messages, f, ensure_ascii=False)
tmp.replace(p)
def append_global_log(obj):
try:
line = json.dumps(obj, ensure_ascii=False)
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception:
pass
def minimax_config():
api_key = os.getenv("MINIMAX_API_KEY", "").strip()
if not api_key:
api_key = os.getenv("ANTHROPIC_API_KEY", "").strip()
group_id = os.getenv("MINIMAX_GROUP_ID", "").strip()
api_style = os.getenv("MINIMAX_API_STYLE", "minimax").strip().lower() or "minimax"
base_url = os.getenv("MINIMAX_BASE_URL", "https://api.minimax.chat/v1").strip()
url = os.getenv("MINIMAX_URL", "").strip()
if not url:
if api_style == "anthropic":
url = "https://api.anthropic.com/v1/messages"
else:
url = f"{base_url.rstrip('/')}/text/chatcompletion_v2"
model_default = "MiniMax-M2.7" if api_style == "anthropic" else "MiniMax-M2.7-highspeed"
model = os.getenv("MINIMAX_MODEL", model_default).strip()
if api_style != "anthropic" and model.lower().startswith("abab"):
model = model_default
timeout = float(os.getenv("MINIMAX_TIMEOUT_SEC", "60").strip() or "60")
return {
"api_key": api_key,
"group_id": group_id,
"api_style": api_style,
"url": url,
"model": model,
"timeout": timeout,
}
def load_text_file(p):
try:
with p.open("r", encoding="utf-8") as f:
return f.read()
except Exception:
return ""
def load_system_prompt():
default_prompt = (
"你是一个风控/机器学习入门学习助手。"
"要求:用小白能懂的语言回答,先给结论,再用生活类比解释,再给一个简单例子。"
"如果用户给了题目,请逐个选项解释为什么对/错。"
"遇到数学题/公式/推导时,用可复制的 LaTeX 输出,并给必要的变量含义。"
"不要输出任何敏感信息,也不要要求用户提供银行卡号、验证码等。"
)
env_path = os.getenv("MINIMAX_SOUL_FILE", "").strip()
candidates = []
if env_path:
candidates.append(Path(env_path))
candidates.append(ROOT / "soul.md")
candidates.append(ROOT / "bot_soul.md")
for p in candidates:
if not p:
continue
try:
if p.exists() and p.is_file():
txt = load_text_file(p).strip()
if txt:
return txt
except Exception:
continue
return default_prompt
SYSTEM_PROMPT = load_system_prompt()
def minimax_extract_text(resp_json):
if isinstance(resp_json, dict):
content_list = resp_json.get("content")
if isinstance(content_list, list) and content_list:
out = []
for blk in content_list:
if not isinstance(blk, dict):
continue
t = blk.get("type")
if t == "text":
txt = blk.get("text")
if isinstance(txt, str) and txt.strip():
out.append(txt)
elif t == "thinking":
th = blk.get("thinking")
if isinstance(th, str) and th.strip():
out.append(f"Thinking:\n{th}")
if out:
return "\n\n".join(out).strip()
choices = resp_json.get("choices")
if isinstance(choices, list) and choices:
ch0 = choices[0]
if isinstance(ch0, dict):
msg = ch0.get("message")
if isinstance(msg, dict):
for k in ("content", "text"):
v = msg.get(k)
if isinstance(v, str) and v.strip():
return v
for k in ("text", "output_text", "content"):
v = ch0.get(k)
if isinstance(v, str) and v.strip():
return v
for k in ("reply", "output", "answer", "result"):
v = resp_json.get(k)
if isinstance(v, str) and v.strip():
return v
return ""
def minimax_detect_error(resp_json):
if not isinstance(resp_json, dict):
return ""
err = resp_json.get("error")
if isinstance(err, dict):
msg = err.get("message")
if isinstance(msg, str) and msg.strip():
return msg
base_resp = resp_json.get("base_resp")
if isinstance(base_resp, dict):
code = base_resp.get("status_code")
msg = base_resp.get("status_msg")
if isinstance(code, int) and code != 0:
return str(msg or f"base_resp.status_code={code}")
return ""
def call_minimax(messages):
cfg = minimax_config()
if not cfg["api_key"]:
raise RuntimeError("MINIMAX_API_KEY 未设置")
url = cfg["url"]
ssl_insecure = (os.getenv("MINIMAX_INSECURE_SSL", "") or "").strip() in ("1", "true", "TRUE", "yes", "YES")
ca_bundle = (os.getenv("MINIMAX_CA_BUNDLE", "") or "").strip()
disable_tls13 = (os.getenv("MINIMAX_TLS_NO_TLS13", "") or "").strip() in ("1", "true", "TRUE", "yes", "YES")
if ssl_insecure:
ctx = ssl._create_unverified_context()
else:
ctx = ssl.create_default_context(cafile=ca_bundle if ca_bundle else None)
if disable_tls13:
ctx.options |= getattr(ssl, "OP_NO_TLSv1_3", 0)
if cfg["api_style"] == "anthropic":
system_text = ""
if messages and isinstance(messages[0], dict) and messages[0].get("role") == "system":
system_text = str(messages[0].get("content") or "")
conv = messages[1:]
else:
conv = messages
anth_messages = []
for m in conv:
if not isinstance(m, dict):
continue
role = m.get("role")
content = m.get("content")
if role not in ("user", "assistant"):
continue
if not isinstance(content, str) or not content.strip():
continue
anth_messages.append({"role": role, "content": [{"type": "text", "text": content}]})
payload = {
"model": cfg["model"],
"max_tokens": 1024,
"temperature": 0.2,
"system": system_text,
"messages": anth_messages,
}
headers = {
"x-api-key": cfg["api_key"],
"anthropic-version": os.getenv("ANTHROPIC_VERSION", "2023-06-01").strip() or "2023-06-01",
"Content-Type": "application/json",
}
else:
payload = {
"model": cfg["model"],
"messages": messages,
"temperature": 0.2,
"max_tokens": 1024,
"stream": False,
}
headers = {"Authorization": f"Bearer {cfg['api_key']}", "Content-Type": "application/json"}
if cfg["group_id"]:
u = urllib.parse.urlsplit(url)
q = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
q.setdefault("GroupId", cfg["group_id"])
url = urllib.parse.urlunsplit((u.scheme, u.netloc, u.path, urllib.parse.urlencode(q), u.fragment))
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=cfg["timeout"], context=ctx) as resp:
status = getattr(resp, "status", 200)
raw = resp.read().decode("utf-8", errors="replace")
except urllib.error.HTTPError as e:
status = getattr(e, "code", 500) or 500
raw = (e.read() or b"").decode("utf-8", errors="replace")
try:
obj = json.loads(raw)
except Exception:
obj = {"raw": raw}
return status, obj
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(SITE_DIR), **kwargs)
def end_headers(self):
self.send_header("Cache-Control", "no-store")
return super().end_headers()
def send_json(self, obj, status=200):
payload = json.dumps(obj, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def read_json_body(self):
try:
n = int(self.headers.get("Content-Length") or "0")
except Exception:
n = 0
if n <= 0:
return {}
raw = self.rfile.read(n).decode("utf-8", errors="replace")
try:
obj = json.loads(raw)
return obj if isinstance(obj, dict) else {}
except Exception:
return {}
def do_GET(self):
if self.path.startswith("/api/chat/sessions"):
u = urllib.parse.urlsplit(self.path)
qs = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
q = (qs.get("q") or "").strip().lower()
try:
limit = int(qs.get("limit") or "60")
except Exception:
limit = 60
limit = max(1, min(limit, 300))
items = []
for p in CHAT_DIR.glob("*.json"):
try:
if not p.is_file():
continue
sid = p.stem
msgs = read_session_messages(sid)
last = None
for m in reversed(msgs):
c = m.get("content")
if isinstance(c, str) and c.strip():
last = m
break
first_user = None
for m in msgs:
if m.get("role") == "user":
c = m.get("content")
if isinstance(c, str) and c.strip():
first_user = c.strip()
break
def clean_preview(s):
t = str(s or "").strip()
t = re.sub(r"^#{1,6}\s*", "", t)
t = t.strip("`").strip()
return t
title = clean_preview((first_user or (last.get("content").strip() if last else "") or sid).splitlines()[0])
title = title[:80]
last_content = (last.get("content").strip() if last and isinstance(last.get("content"), str) else "")
last_line = clean_preview(last_content.splitlines()[0] if last_content else "")
last_line = last_line[:120]
updated_at = 0
try:
updated_at = int(max(p.stat().st_mtime * 1000, int(last.get("ts") or 0) if last else 0))
except Exception:
updated_at = int(p.stat().st_mtime * 1000)
hay = f"{sid}\n{title}\n{last_line}".lower()
if q and q not in hay:
continue
items.append(
{
"session_id": sid,
"updated_at": updated_at,
"title": title,
"last_role": last.get("role") if last else "",
"last": last_line,
"message_count": len(msgs),
}
)
except Exception:
continue
items.sort(key=lambda x: x.get("updated_at", 0), reverse=True)
self.send_json(items[:limit], 200)
return
if self.path.startswith("/api/chat/history"):
u = urllib.parse.urlsplit(self.path)
qs = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
session_id = qs.get("session_id", "")
msgs = read_session_messages(session_id)
self.send_json(msgs, 200)
return
try:
u = urllib.parse.urlsplit(self.path)
if u.path == "/":
self.path = "/index.html"
except Exception:
if self.path == "/":
self.path = "/index.html"
return super().do_GET()
def do_POST(self):
if self.path.startswith("/api/sql/run"):
body = self.read_json_body()
dataset_id = str(body.get("datasetId") or body.get("dataset_id") or "").strip()
sql = body.get("sql") or ""
reference_sql = body.get("referenceSql") or body.get("reference_sql") or ""
check = body.get("check") if isinstance(body.get("check"), dict) else {}
if not dataset_id:
self.send_json({"error": "datasetId 不能为空"}, 400)
return
if not is_select_only(sql):
self.send_json({"error": "仅允许执行单条 SELECT / WITH 查询"}, 400)
return
datasets = load_sql_datasets()
ds = datasets.get(dataset_id)
if not isinstance(ds, dict):
self.send_json({"error": f"未找到数据集:{dataset_id}"}, 404)
return
try:
conn = sql_make_conn()
sql_apply_dataset(conn, ds)
cur = conn.cursor()
cur.execute(sql)
user_res = sql_fetch_result(cur)
except Exception as e:
try:
conn.close()
except Exception:
pass
self.send_json({"ok": False, "error": str(e)}, 200)
return
expected_res = None
ok = None
reason = ""
if reference_sql:
if not is_select_only(reference_sql):
ok = False
reason = "参考答案 SQL 非 SELECT"
else:
try:
cur2 = conn.cursor()
cur2.execute(reference_sql)
expected_res = sql_fetch_result(cur2)
ok, reason = sql_compare(user_res, expected_res, check)
except Exception as e:
ok = False
reason = f"参考答案执行失败:{e}"
try:
conn.close()
except Exception:
pass
self.send_json(
{
"ok": ok,
"reason": reason,
"user": user_res,
"expected": expected_res,
},
200,
)
return
if self.path.startswith("/api/cpp/run"):
body = self.read_json_body()
code = body.get("code") or ""
stdin_text = body.get("stdin") or body.get("input") or ""
mode = str(body.get("mode") or "run").strip().lower()
tests = body.get("tests") if isinstance(body.get("tests"), list) else []
try:
tl_ms = int(body.get("timeLimitMs") or 2000)
except Exception:
tl_ms = 2000
tl_ms = max(200, min(tl_ms, 15000))
check = body.get("check") if isinstance(body.get("check"), dict) else {}
if not str(code).strip():
self.send_json({"error": "code 不能为空"}, 400)
return
if len(str(code)) > 200000:
self.send_json({"error": "code 过长(上限 200KB)"}, 400)
return
if len(str(stdin_text)) > 200000:
self.send_json({"error": "stdin 过长(上限 200KB)"}, 400)
return
if mode == "judge" and len(tests) == 0:
self.send_json({"error": "该题未配置测试用例,无法判题"}, 400)
return
comp = cpp_compile(code, timeout_sec=10.0)
if not comp.get("ok"):
self.send_json({"compile": comp, "ok": False}, 200)
return
exe_path = comp.get("exe")
try:
if mode == "judge":
results = []
all_ok = True
idx = 0
for t in tests:
idx += 1
if not isinstance(t, dict):
continue
tin = t.get("input") or ""
tout = t.get("output") or ""
tcheck = t.get("check") if isinstance(t.get("check"), dict) else check
run = cpp_run_exe(exe_path, tin, timeout_sec=float(tl_ms) / 1000.0)
if not run.get("ok"):
all_ok = False
results.append({"index": idx, "ok": False, "error": run.get("error", "")})
continue
if run.get("timedOut"):
all_ok = False
results.append(
{
"index": idx,
"ok": False,
"timedOut": True,
"stdout": run.get("stdout", ""),
"stderr": run.get("stderr", ""),
"exitCode": run.get("exitCode", 0),
"timeMs": run.get("timeMs", 0),
}
)
continue
passed = cpp_compare_output(run.get("stdout", ""), tout, tcheck)
if not passed:
all_ok = False
results.append(
{
"index": idx,
"ok": bool(passed),
"stdout": run.get("stdout", ""),
"stderr": run.get("stderr", ""),
"expected": str(tout),
"exitCode": run.get("exitCode", 0),
"timeMs": run.get("timeMs", 0),
}
)
self.send_json({"ok": bool(all_ok), "compile": comp, "tests": results}, 200)
return
run = cpp_run_exe(exe_path, stdin_text, timeout_sec=float(tl_ms) / 1000.0)
self.send_json({"compile": comp, "run": run}, 200)
return
finally:
cpp_cleanup_path(exe_path)
if self.path.startswith("/api/minimax/chat"):
body = self.read_json_body()
session_id = body.get("session_id") or body.get("sessionId") or ""
message = body.get("message") or ""
context = body.get("context") or ""
session_id = safe_session_id(session_id)
message = str(message).strip()
context = str(context).strip()
if not message:
self.send_json({"error": "message 不能为空"}, 400)
return
history = read_session_messages(session_id)
history_trimmed = history[-20:]
mm_messages = [{"role": "system", "content": load_system_prompt()}]
for m in history_trimmed:
role = m.get("role")
content = m.get("content")
if role in ("user", "assistant") and isinstance(content, str) and content.strip():
mm_messages.append({"role": role, "content": content})
user_content = message
if context:
user_content = f"{message}\n\n【当前题目】\n{context}"
mm_messages.append({"role": "user", "content": user_content})
history.append({"role": "user", "content": message, "ts": now_ms()})
try:
status, resp_json = call_minimax(mm_messages)
except Exception as e:
append_global_log({"ts": now_ms(), "session_id": session_id, "ok": False, "error": str(e), "req": {"message": message}})
write_session_messages(session_id, history)
self.send_json({"error": str(e)}, 500)
return
reply = minimax_extract_text(resp_json).strip()
api_err = minimax_detect_error(resp_json)
if status < 200 or status >= 300:
append_global_log(
{
"ts": now_ms(),
"session_id": session_id,
"ok": False,
"status": status,
"req": {"message": message, "context": bool(context)},
"resp": resp_json,
}
)
write_session_messages(session_id, history)
self.send_json({"error": f"MiniMax API 错误:HTTP {status}", "details": resp_json}, 502)
return
if api_err:
append_global_log(
{
"ts": now_ms(),
"session_id": session_id,
"ok": False,
"status": status,
"req": {"message": message, "context": bool(context)},
"resp": resp_json,
}
)
write_session_messages(session_id, history)
hint = ""
if "not support model" in api_err or "not support" in api_err:
hint = (
"你当前套餐不支持该模型。请在命令行设置 $env:MINIMAX_MODEL 为你账号支持的模型名后重试。"
"\n可先依次尝试:MiniMax-M2.7-highspeed、MiniMax-M2.7、MiniMax-M2.5-highspeed、MiniMax-M2.5、MiniMax-M2.1、MiniMax-M2。"
"\n如果你使用的是 minimax.io 平台,也可设置 $env:MINIMAX_BASE_URL='https://api.minimax.io/v1' 后重试。"
)
self.send_json({"error": f"MiniMax 返回错误:{api_err}", "hint": hint, "details": resp_json}, 502)
return
assistant_content = reply or json.dumps(resp_json, ensure_ascii=False)
history.append({"role": "assistant", "content": assistant_content, "ts": now_ms()})
write_session_messages(session_id, history)
append_global_log(
{
"ts": now_ms(),
"session_id": session_id,
"ok": True,
"req": {"message": message, "context": bool(context)},
"resp": resp_json,
}
)
self.send_json({"reply": assistant_content}, 200)
return
self.send_json({"error": "Not found"}, 404)
def main():
port = int((os.getenv("PORT", "5173") or "5173").strip() or "5173")
host = (os.getenv("HOST", "127.0.0.1") or "127.0.0.1").strip() or "127.0.0.1"
httpd = ThreadingHTTPServer((host, port), Handler)
httpd.serve_forever()
if __name__ == "__main__":
main()