BachDaThan commited on
Commit
fdf457b
·
verified ·
1 Parent(s): a3a0057

Upload 9 files

Browse files
app.py CHANGED
@@ -10816,44 +10816,43 @@ KHI SỬA: in TOÀN BỘ file từ đầu. Bọc code trong ```[lang] ... ```"""
10816
  }
10817
 
10818
  if not github_success:
10819
- # ── Cerebras STRONG (qwen-3-235b = 235B params, MIỄN PHÍ) ──
10820
- # Thực ra mạnh hơn gpt-4o-mini trong nhiều task!
 
 
10821
  _cb_success = False
10822
  try:
10823
- _cb_strong_models = _cerebras_hunter.get_strong()
10824
- except NameError:
10825
- _cb_strong_models = globals().get("CEREBRAS_STRONG_MODELS",
10826
- ["qwen-3-235b-a22b-instruct-2507", "gpt-oss-120b"])
10827
- if _cb_strong_models and CEREBRAS_KEYS:
10828
- try:
10829
- import aiohttp as _ah_cb_fb, random as _rd_cb_fb
10830
- _cb_key = __import__("os").environ.get(
10831
- random.choice([k for k in __import__("os").environ
10832
- if "CEREBRAS" in k.upper()]), ""
 
 
 
 
 
 
 
 
 
 
 
 
10833
  )
10834
- _cb_model = _cb_strong_models[0]
10835
- _max_tokens = _max_tok if "_max_tok" in dir() else 4000 # Fix: _max_tok scope
10836
- async def _cb_fb_call():
10837
- async with _ah_cb_fb.ClientSession() as _s:
10838
- async with _s.post(
10839
- "https://api.cerebras.ai/v1/chat/completions",
10840
- headers={"Authorization": f"Bearer {_cb_key}"},
10841
- json={"model": _cb_model, "messages": messages,
10842
- "max_tokens": _max_tokens, "temperature": 0.2},
10843
- timeout=_ah_cb_fb.ClientTimeout(total=30)
10844
- ) as _r:
10845
- if _r.status == 200:
10846
- _d = await _r.json()
10847
- return _d.get("choices",[{}])[0].get("message",{}).get("content","")
10848
- return ""
10849
- _cb_txt = _run_async_safe(_cb_fb_call())
10850
- if _cb_txt and len(_cb_txt) > 50:
10851
- print(f"✅ [CB-FALLBACK] Đã dùng Cerebras: {_cb_model}")
10852
- _cb_success = True
10853
- final_reply = _finalize_reply(_cb_txt, user_query, is_code=is_hard_task, task_type=_task_type, web_context=_web_context, history=history)
10854
- except Exception as _cb_fb_err:
10855
- _ne_log_error("cerebras_fallback", str(_cb_fb_err), user_query, "cerebras")
10856
- print(f"⚠️ [CB-FALLBACK] {_cb_fb_err}")
10857
 
10858
  # ── Thử Mistral Codestral sau Cerebras (CODE SPECIALIST) ──
10859
  if not _cb_success and MISTRAL_KEYS and _task_type in ("code", "math"):
@@ -11010,43 +11009,35 @@ KHI SỬA: in TOÀN BỘ file từ đầu. Bọc code trong ```[lang] ... ```"""
11010
  continue
11011
  if _or_success: break
11012
 
11013
- # ── Cerebras gpt-oss-120B — Admin fallback trước Gemini ──
11014
- # Admin dùng reserved keys trước, nếu hết dùng full pool (kể cả key khách)
11015
- # Admin pool (key7-9) → Friend pool (key4-6) → full pool
11016
- _cb_admin_keys = _CEREBRAS_ADMIN or CEREBRAS_KEYS
11017
- _cb_elite_keys = list(set(list(_CEREBRAS_ADMIN or []) + list(_CEREBRAS_FRIEND or []))) or CEREBRAS_KEYS
11018
- if _cb_admin_keys:
11019
- _cb_admin_models = _cb_hunter.get_strong() or ["gpt-oss-120b", "zai-glm-4.7"]
11020
- for _cam in _cb_admin_models:
11021
- for _ in range(2):
11022
- _cb_key = random.choice(_cb_admin_keys if _ == 0 else _cb_elite_keys)
11023
- try:
11024
- import openai as _oai_cba
11025
- _cba_client = _oai_cba.OpenAI(
11026
- api_key=_cb_key,
11027
- base_url="https://api.cerebras.ai/v1",
11028
- )
11029
- _cba_msgs = [{"role": "system", "content": system_prompt}]
11030
- for _t in recent_history:
11031
- if isinstance(_t, (list, tuple)) and len(_t) >= 2:
11032
- _cba_msgs.append({"role": "user", "content": str(_t[0])})
11033
- _cba_msgs.append({"role": "assistant", "content": str(_t[1])})
11034
- _cba_msgs.append({"role": "user", "content": user_query})
11035
- _cba_comp = _cba_client.chat.completions.create(
11036
- model=_cam,
11037
- messages=_cba_msgs,
11038
- temperature=0.1,
11039
- max_tokens=4000,
11040
- )
11041
- _cba_result = _cba_comp.choices[0].message.content
11042
- if _cba_result:
11043
- print(f"✅ [CEREBRAS-ADMIN] {_cam} trả lời thành công!")
11044
- _req_counter.inc("cerebras_admin")
11045
- return _finalize_reply(_cba_result, user_query, is_code=is_hard_task, task_type=_task_type, web_context=_web_context, history=history)
11046
- except Exception as _cae:
11047
- print(f"⚠️ [CEREBRAS-ADMIN] {_cam}: {_cae.__class__.__name__}")
11048
- continue
11049
- if _cba_result if "_cba_result" in dir() else False: break
11050
 
11051
  # Nếu tất cả hết → Gemini
11052
  print("⚠️ [GITHUB+OR+CB] Hết quota! Chuyển sang GEMINI 2.5 PRO THINKING...")
@@ -11142,76 +11133,40 @@ KHI SỬA: in TOÀN BỘ file từ đầu. Bọc code trong ```[lang] ... ```"""
11142
  # target_brain = "cerebras_strong" được set khi task=knowledge
11143
  # =======================================================
11144
  if target_brain == "cerebras_strong":
11145
- if CEREBRAS_KEYS:
11146
- try:
11147
- import openai as _oai_cb_adm
11148
- _cb_adm_keys = list(_CEREBRAS_ADMIN) if _CEREBRAS_ADMIN else list(CEREBRAS_KEYS)
11149
-
11150
- # 🆕 (2026-07-11) GLM-4.7 (zai-glm-4.7) — model mạnh, đặc
11151
- # biệt tốt cho code/reasoning theo benchmark công bố, nhưng
11152
- # quota free tier RẤT HẸP (10 RPM/100 RPD MỖI KEY, so với
11153
- # gpt-oss-120b 30 RPM/14400 RPD). Với 9 key CEREBRAS admin,
11154
- # tổng quota GLM-4.7 ước tính ~900 request/ngày (rate limit
11155
- # tính theo tổ chức/key, không theo user) — đủ dùng CHO
11156
- # RIÊNG code/debug (nơi nó mạnh nhất), không dùng cho toàn
11157
- # bộ traffic "strong" nói chung để tránh cạn quota nhanh.
11158
- _cb_adm_model = None
11159
- if _task_type in ("code", "debug"):
11160
- _scarce_models = _cb_hunter.get_scarce()
11161
- if _scarce_models:
11162
- _cb_adm_model = _scarce_models[0]
11163
- print(f"[CEREBRAS-SCARCE] 🎯 Thử GLM trước cho {_task_type}: {_cb_adm_model}")
11164
-
11165
- if not _cb_adm_model:
11166
- _cb_adm_model = _cb_hunter.get_strong()
11167
- if isinstance(_cb_adm_model, list):
11168
- _cb_adm_model = _cb_adm_model[0] if _cb_adm_model else "gpt-oss-120b"
11169
- elif not isinstance(_cb_adm_model, str) or not _cb_adm_model.strip():
11170
- _cb_adm_model = "gpt-oss-120b"
11171
- _cb_adm_client = _oai_cb_adm.OpenAI(
11172
- api_key=random.choice(_cb_adm_keys),
11173
- base_url="https://api.cerebras.ai/v1"
11174
  )
11175
- _cb_adm_msgs = [{"role": "system", "content": system_prompt}]
11176
- for _t in recent_history:
11177
- if isinstance(_t, (list, tuple)) and len(_t) >= 2:
11178
- _cb_adm_msgs.append({"role": "user", "content": str(_t[0])})
11179
- _cb_adm_msgs.append({"role": "assistant", "content": str(_t[1])})
11180
- _cb_adm_msgs.append({"role": "user", "content": user_query})
11181
- try:
11182
- _cb_adm_resp = _cb_adm_client.chat.completions.create(
11183
- model=_cb_adm_model,
11184
- messages=_cb_adm_msgs,
11185
- temperature=0.1,
11186
- max_tokens=4000,
11187
- )
11188
- except Exception as _cb_scarce_err:
11189
- # 🆕 Nếu GLM-4.7 (scarce) fail (thường do hết 100 RPD/key
11190
- # hoặc 429 rate limit) → fallback êm về get_strong() bình
11191
- # thường ngay trong lần thử này, không văng lỗi ra ngoài.
11192
- if _task_type in ("code", "debug") and _cb_hunter.get_scarce() and _cb_adm_model in _cb_hunter.get_scarce():
11193
- print(f"[CEREBRAS-SCARCE] ⚠️ GLM hết quota/lỗi ({_cb_scarce_err.__class__.__name__}) → fallback strong")
11194
- _cb_adm_model = _cb_hunter.get_strong()
11195
- if isinstance(_cb_adm_model, list):
11196
- _cb_adm_model = _cb_adm_model[0] if _cb_adm_model else "gpt-oss-120b"
11197
- _cb_adm_resp = _cb_adm_client.chat.completions.create(
11198
- model=_cb_adm_model,
11199
- messages=_cb_adm_msgs,
11200
- temperature=0.1,
11201
- max_tokens=4000,
11202
- )
11203
- else:
11204
- raise
11205
- _cb_adm_txt = _cb_adm_resp.choices[0].message.content
11206
- if _cb_adm_txt and len(_cb_adm_txt) > 10:
11207
- print(f"✅ [CEREBRAS-KNOWLEDGE] {_cb_adm_model} trả lời thành công!")
11208
- _req_counter.inc("cerebras_strong")
11209
- return _finalize_reply(_cb_adm_txt, user_query, is_code=is_hard_task, task_type=_task_type, web_context=_web_context, history=history)
11210
- print("⚠️ [CEREBRAS-KNOWLEDGE] Reply rỗng, fallback...")
11211
- except Exception as _cb_adm_e:
11212
- print(f"⚠️ [CEREBRAS-KNOWLEDGE] {_cb_adm_e.__class__.__name__}: {str(_cb_adm_e)[:60]}")
11213
- # Cerebras fail → fallback Gemini
11214
- print("⚠️ [CEREBRAS-KNOWLEDGE] Chuyển sang Gemini thinking...")
11215
  target_brain = "gemini_thinking"
11216
 
11217
  # =======================================================
@@ -12988,27 +12943,25 @@ def dream_and_clean_memory():
12988
  val = str(brain_memory.get(key, ""))
12989
  if len(val) < 300: continue
12990
  try:
12991
- import urllib.request as _ur, json as _js_c, os as _os_c
12992
- cb_keys = [k for k in _os_c.environ if "CEREBRAS" in k.upper()]
12993
- if not cb_keys: break
12994
- key_c = _os_c.environ.get(random.choice(cb_keys), "")
 
12995
  prompt_c = (
12996
  f"Đọc đoạn thông tin sau và rút ra ĐÚNG 1 CÂU kinh nghiệm cốt lõi "
12997
  f"(dưới 100 ký tự, bắt đầu bằng 'Kinh nghiệm:'):\n\n{val[:800]}"
12998
  )
12999
- req = _ur.Request(
13000
- "https://api.cerebras.ai/v1/chat/completions",
13001
- data=_js_c.dumps({
13002
- "model": "gpt-oss-120b",
13003
- "messages": [{"role":"user","content":prompt_c}],
13004
- "max_tokens": 80, "temperature": 0.1
13005
- }).encode(),
13006
- headers={"Authorization": f"Bearer {key_c}", "Content-Type": "application/json"},
13007
- method="POST"
13008
- )
13009
- with _ur.urlopen(req, timeout=10) as resp:
13010
- d = _js_c.loads(resp.read())
13011
- summary = d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
13012
  if summary and len(summary) > 10:
13013
  brain_memory[f"[nén] {key[:60]}"] = summary
13014
  del brain_memory[key]
@@ -17213,37 +17166,19 @@ async def _map_full_bds_analysis(query: str, dia_diem: str, dien_tich: float = 0
17213
  print(f"[BDS-AI] Cohere loi: {e}")
17214
 
17215
  try:
17216
- # ── Fallback Cerebras — nhanh ──────────────────────────
17217
- cb_keys = [k for k in _os_bds.environ if "CEREBRAS" in k.upper()
17218
- and len(_os_bds.environ.get(k,"")) > 10]
17219
- if cb_keys:
17220
- cbk = _os_bds.environ.get(_rd_bds.choice(cb_keys), "")
17221
- async with _ah_bds.ClientSession() as s:
17222
- async with s.post(
17223
- "https://api.cerebras.ai/v1/chat/completions",
17224
- headers={"Authorization": f"Bearer {cbk}",
17225
- "Content-Type": "application/json"},
17226
- json={
17227
- "model": "qwen-3-235b-a22b-instruct-2507",
17228
- "messages": [
17229
- {"role": "system", "content": system},
17230
- {"role": "user", "content": prompt}
17231
- ],
17232
- "max_tokens": 1200,
17233
- "temperature": 0.7,
17234
- },
17235
- timeout=_ah_bds.ClientTimeout(total=35)
17236
- ) as r:
17237
- if r.status == 200:
17238
- data = await r.json()
17239
- text = (data.get("choices",[{}])[0]
17240
- .get("message",{})
17241
- .get("content",""))
17242
- if text and len(text) > 100:
17243
- print(f"[BDS-AI] Cerebras OK ({len(text)} chars)")
17244
- return text
17245
  except Exception as e:
17246
- print(f"[BDS-AI] Cerebras loi: {e}")
17247
 
17248
  try:
17249
  # ── Fallback Gemini Flash ──────────────────────────────
@@ -17394,29 +17329,18 @@ async def video_script_api(request: Request):
17394
  except Exception as e:
17395
  print(f"[VIDEO-SCRIPT] Cohere loi: {e}")
17396
 
17397
- # 2. Cerebras fallback
 
 
17398
  if not result:
17399
  try:
17400
- cb_list = [k for k in _os_vs.environ if "CEREBRAS" in k.upper()]
17401
- if cb_list:
17402
- cbk = _os_vs.environ.get(_rd_vs.choice(cb_list), "")
17403
- async with _ah_vs.ClientSession() as s:
17404
- async with s.post(
17405
- "https://api.cerebras.ai/v1/chat/completions",
17406
- headers={"Authorization": f"Bearer {cbk}"},
17407
- json={
17408
- "model": "qwen-3-235b-a22b-instruct-2507",
17409
- "messages": [{"role": "user", "content": prompt}],
17410
- "max_tokens": 800,
17411
- "temperature": 0.92,
17412
- },
17413
- timeout=_ah_vs.ClientTimeout(total=25)
17414
- ) as r:
17415
- if r.status == 200:
17416
- d = await r.json()
17417
- result = d.get("choices",[{}])[0].get("message",{}).get("content","")
17418
  except Exception as e:
17419
- print(f"[VIDEO-SCRIPT] Cerebras loi: {e}")
17420
 
17421
  if not result:
17422
  return {"error": "Khong tao duoc kich ban luc nay, thu lai sau"}
@@ -18513,12 +18437,12 @@ async def imad_reason(query: str, initial_answer: str, task_type: str) -> str:
18513
  - Không truyền văn bản trung gian qua mạng → nhanh hơn
18514
  - Chính xác hơn single-shot nhờ self-critique
18515
  """
18516
- import aiohttp as _ah_imad, os as _os_imad, random as _rd_imad
18517
-
18518
- cb_keys = [_os_imad.environ.get(k) for k in _os_imad.environ if "CEREBRAS" in k.upper()]
18519
- cb_keys = [k for k in cb_keys if k]
18520
- if not cb_keys:
18521
- return initial_answer # Không có key → dùng câu trả lời gốc
18522
 
18523
  current_answer = initial_answer
18524
  tokens_saved = 0 # Ước tính token tiết kiệm so với full debate
@@ -18535,22 +18459,14 @@ async def imad_reason(query: str, initial_answer: str, task_type: str) -> str:
18535
  "Nếu có vấn đề: mỗi vấn đề 1 dòng ngắn gọn."
18536
  )
18537
  critique = ""
 
18538
  try:
18539
- key = _rd_imad.choice(cb_keys)
18540
- async with _ah_imad.ClientSession() as s:
18541
- async with s.post(
18542
- "https://api.cerebras.ai/v1/chat/completions",
18543
- headers={"Authorization": f"Bearer {key}"},
18544
- json={
18545
- "model": "gpt-oss-120b", # Model nhỏ cho critic — tiết kiệm
18546
- "messages": [{"role": "user", "content": critic_prompt}],
18547
- "max_tokens": 150, "temperature": 0.2
18548
- },
18549
- timeout=_ah_imad.ClientTimeout(total=12)
18550
- ) as r:
18551
- if r.status == 200:
18552
- d = await r.json()
18553
- critique = d.get("choices", [{}])[0].get("message", {}).get("content", "")
18554
  except Exception as _e_imad:
18555
  print(f"[IMAD] Critic round {round_num} lỗi: {_e_imad}")
18556
  break
@@ -18573,31 +18489,22 @@ async def imad_reason(query: str, initial_answer: str, task_type: str) -> str:
18573
  "Không cần giải thích tại sao sửa — chỉ trả về câu trả lời mới."
18574
  )
18575
  try:
18576
- key2 = _rd_imad.choice(cb_keys)
18577
- async with _ah_imad.ClientSession() as s:
18578
- async with s.post(
18579
- "https://api.cerebras.ai/v1/chat/completions",
18580
- headers={"Authorization": f"Bearer {key2}"},
18581
- json={
18582
- "model": "gpt-oss-120b",
18583
- "messages": [{"role": "user", "content": defender_prompt}],
18584
- "max_tokens": 800, "temperature": 0.3
18585
- },
18586
- timeout=_ah_imad.ClientTimeout(total=20)
18587
- ) as r:
18588
- if r.status == 200:
18589
- d = await r.json()
18590
- improved = d.get("choices", [{}])[0].get("message", {}).get("content", "")
18591
- if improved and len(improved) > 50:
18592
- current_answer = improved
18593
- print(f"[IMAD] 🔄 Round {round_num}: Cải thiện +{len(improved) - len(initial_answer)} chars")
18594
  except Exception as _e_def:
18595
  print(f"[IMAD] Defender round {round_num} lỗi: {_e_def}")
18596
 
18597
  # Ước tính token tiết kiệm so với spawn 2 AI riêng biệt
18598
  tokens_saved += len(critic_prompt) // 4 # 1 token ~ 4 chars
18599
 
18600
- _tbg_add("cerebras", (len(query) + len(current_answer)) // 4)
18601
  print(f"[IMAD] ✅ Xong {_IMAD_DEBATE_ROUNDS} rounds | ~{tokens_saved} tokens saved vs Multi-Agent")
18602
  return current_answer
18603
 
@@ -19004,26 +18911,21 @@ def get_bg_status(job_id: str) -> str:
19004
  import asyncio as _aio_ma
19005
 
19006
  async def _call_agent(role: str, prompt: str, context: str = "") -> str:
19007
- """Gọi AI với role cụ thể — dùng Cerebras 235B (nhanh nhất)."""
19008
- import aiohttp as _ah_ma, os as _os_ma, random as _rd_ma
19009
- cb_keys = [k for k in _os_ma.environ if "CEREBRAS" in k.upper()]
19010
- if not cb_keys:
19011
- return ""
19012
- key = _os_ma.environ.get(_rd_ma.choice(cb_keys), "")
19013
- msgs = [{"role": "system", "content": f"Bạn là {role}. {context}"},
19014
- {"role": "user", "content": prompt}]
19015
  try:
19016
- async with _ah_ma.ClientSession() as s:
19017
- async with s.post(
19018
- "https://api.cerebras.ai/v1/chat/completions",
19019
- headers={"Authorization": f"Bearer {key}"},
19020
- json={"model": "qwen-3-235b-a22b-instruct-2507",
19021
- "messages": msgs, "max_tokens": 1200, "temperature": 0.3},
19022
- timeout=_ah_ma.ClientTimeout(total=30)
19023
- ) as r:
19024
- if r.status == 200:
19025
- d = await r.json()
19026
- return d.get("choices",[{}])[0].get("message",{}).get("content","")
19027
  except Exception as e:
19028
  print(f"[AGENT] {role} lỗi: {e}")
19029
  return ""
@@ -19643,46 +19545,30 @@ def _mrac_analyze(web_snippets: list, user_query: str) -> str:
19643
  results = {"summary": "", "facts": "", "reasoning": ""}
19644
 
19645
  def _call_agent(role: str, prompt: str) -> tuple:
19646
- """Gọi model cho MRAC — thử Gemini trước, fallback Cerebras, rồi Cohere."""
19647
- import openai as _oai_mrac, cohere as _co_mrac
19648
- # 1. Gemini
19649
- try:
19650
- from ural_gemini_brain import call_gemini
19651
- r = call_gemini(
19652
- messages=[{"role": "user", "content": prompt}],
19653
- system_prompt="Trả lời ngắn gọn, chính xác, đúng format được yêu cầu.",
19654
- use_thinking=False, max_tokens=600, temperature=0.1,
19655
- )
19656
- if r and len(r) > 5: return (role, r)
19657
- except Exception as e:
19658
- print(f"[MRAC/{role}] Gemini lỗi: {str(e)[:50]}")
19659
- # 2. Cerebras fallback
19660
- try:
19661
- _cb_keys = globals().get("CEREBRAS_KEYS", [])
19662
- if _cb_keys:
19663
- _cb = _oai_mrac.OpenAI(api_key=random.choice(_cb_keys), base_url="https://api.cerebras.ai/v1")
19664
- _cb_models = globals().get("CEREBRAS_STRONG_MODELS", ["gpt-oss-120b"])
19665
- r = _cb.chat.completions.create(
19666
- model=_cb_models[0] if _cb_models else "gpt-oss-120b",
19667
- messages=[{"role":"system","content":"Trả lời ngắn gọn."},{"role":"user","content":prompt}],
19668
- max_tokens=600, temperature=0.1,
19669
- ).choices[0].message.content.strip()
19670
- if r and len(r) > 5: return (role, r)
19671
- except Exception as e:
19672
- print(f"[MRAC/{role}] Cerebras lỗi: {str(e)[:50]}")
19673
- # 3. Cohere fallback
19674
  try:
19675
- _co_keys = globals().get("COHERE_KEYS", [])
19676
- if _co_keys:
19677
- r = _call_cohere_smart(
19678
- api_key=random.choice(_co_keys),
19679
- message=prompt,
19680
- model=_cohere_hunter.get_chat(),
19681
- temperature=0.1,
19682
- ).strip()
19683
- if r and len(r) > 20: return (role, r)
 
 
 
 
19684
  except Exception as e:
19685
- print(f"[MRAC/{role}] Cohere lỗi: {str(e)[:50]}")
19686
  return (role, "")
19687
 
19688
  try:
@@ -20564,32 +20450,24 @@ async def _ne_evolver(errors: list, fails: list) -> list:
20564
  f"Chỉ viết code Python thuần, không giải thích dài dòng."
20565
  )
20566
 
20567
- # Chọn model: Cerebras mạnh trước, GitHub làm fallback
20568
- cb_keys = [k for k in _os_ne.environ if "CEREBRAS" in k.upper()]
20569
  gh_keys = [k for k in _os_ne.environ if "GITHUB" in k.upper() or "GITHUB_KEY" in k.upper()]
20570
 
20571
  reply = ""
20572
 
20573
- # Thử Cerebras Qwen-235B (mạnh, nhanh, rẻ)
20574
- if cb_keys:
20575
- try:
20576
- cb_key = _os_ne.environ.get(_rd_ne.choice(cb_keys), "")
20577
- strong_model = _cerebras_hunter.get_strong() if "_cerebras_hunter" in dir() else "qwen-3-235b-a22b-instruct-2507"
20578
- async with _ah_ne.ClientSession() as s:
20579
- async with s.post(
20580
- "https://api.cerebras.ai/v1/chat/completions",
20581
- headers={"Authorization": f"Bearer {cb_key}"},
20582
- json={"model": strong_model,
20583
- "messages": [{"role": "user", "content": evolver_prompt}],
20584
- "max_tokens": 1500, "temperature": 0.2},
20585
- timeout=_ah_ne.ClientTimeout(total=30)
20586
- ) as r:
20587
- if r.status == 200:
20588
- d = await r.json()
20589
- reply = d.get("choices", [{}])[0].get("message", {}).get("content", "")
20590
- print(f"[EVOLVER] 🧬 Cerebras {strong_model} generated skills")
20591
- except Exception as e:
20592
- print(f"[EVOLVER] Cerebras error: {e}")
20593
 
20594
  # Fallback GitHub
20595
  if not reply and gh_keys:
@@ -21487,9 +21365,8 @@ async def _prompt_evolution_session():
21487
 
21488
  print(f"[PROMPT-EVO] 🔧 Evolver fixing {len(weak_agents)} weak agents...")
21489
 
21490
- cb_keys = [k for k in _os_pe.environ if "CEREBRAS" in k.upper()]
21491
- if not cb_keys:
21492
- return
21493
 
21494
  for wa in weak_agents[:2]: # Max 2 agents mỗi đêm
21495
  agent_name = wa["agent"]
@@ -21503,23 +21380,17 @@ async def _prompt_evolution_session():
21503
  )
21504
 
21505
  try:
21506
- key = _os_pe.environ.get(_rd_pe.choice(cb_keys), "")
21507
- async with _ah_pe.ClientSession() as s:
21508
- async with s.post(
21509
- "https://api.cerebras.ai/v1/chat/completions",
21510
- headers={"Authorization": f"Bearer {key}"},
21511
- json={"model": "gpt-oss-120b", # Nhẹ đủ dùng cho task này
21512
- "messages": [{"role": "user", "content": evolve_prompt}],
21513
- "max_tokens": 150, "temperature": 0.2},
21514
- timeout=_ah_pe.ClientTimeout(total=12)
21515
- ) as r:
21516
- if r.status == 200:
21517
- d = await r.json()
21518
- patch = d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
21519
- if patch and len(patch) > 20:
21520
- _set_prompt_patch(agent_name, patch)
21521
- # Thêm vào lessons_learned
21522
- _lessons_add(
21523
  topic=f"agent_fix:{agent_name}",
21524
  lesson=f"Prompt patch: {patch[:100]}",
21525
  confidence=0.75,
@@ -22156,11 +22027,11 @@ async def agent_orchestrator(task: str, max_rounds: int = 3) -> dict:
22156
  import subprocess as _sp_tdd, tempfile as _tmp_tdd, sys as _sys_tdd
22157
 
22158
  async def _generate_tests(code: str, task: str) -> str:
22159
- """Dùng AI sinh test cases cho code."""
22160
- import aiohttp as _ah_tdd, os as _os_tdd, random as _rd_tdd
22161
- cb_keys = [k for k in _os_tdd.environ if "CEREBRAS" in k.upper()]
22162
- if not cb_keys: return ""
22163
- key = _os_tdd.environ.get(_rd_tdd.choice(cb_keys), "")
22164
  prompt = (
22165
  f"Task gốc: {task}\n\nCode:\n```python\n{code[:1000]}\n```\n\n"
22166
  "Viết unittest Python kiểm tra code này.\n"
@@ -22171,18 +22042,12 @@ async def _generate_tests(code: str, task: str) -> str:
22171
  "- Chỉ trả về code test, không giải thích"
22172
  )
22173
  try:
22174
- async with _ah_tdd.ClientSession() as s:
22175
- async with s.post(
22176
- "https://api.cerebras.ai/v1/chat/completions",
22177
- headers={"Authorization": f"Bearer {key}"},
22178
- json={"model": "qwen-3-235b-a22b-instruct-2507",
22179
- "messages": [{"role":"user","content":prompt}],
22180
- "max_tokens": 800, "temperature": 0.2},
22181
- timeout=_ah_tdd.ClientTimeout(total=25)
22182
- ) as r:
22183
- if r.status == 200:
22184
- d = await r.json()
22185
- return d.get("choices",[{}])[0].get("message",{}).get("content","")
22186
  except Exception as e:
22187
  print(f"[TDD] Generate test lỗi: {e}")
22188
  return ""
@@ -22273,10 +22138,8 @@ async def text_to_sql(question: str, db_path: str) -> dict:
22273
  return {"sql": "", "result": schema, "row_count": 0}
22274
 
22275
  # Sinh SQL
22276
- cb_keys = [k for k in _os_t2s.environ if "CEREBRAS" in k.upper()]
22277
- if not cb_keys:
22278
- return {"sql": "", "result": "Không có Cerebras key", "row_count": 0}
22279
- key = _os_t2s.environ.get(_rd_t2s.choice(cb_keys), "")
22280
  prompt = (
22281
  f"Database schema:\n{schema}\n\n"
22282
  f"Câu hỏi: {question}\n\n"
@@ -22285,21 +22148,16 @@ async def text_to_sql(question: str, db_path: str) -> dict:
22285
  )
22286
  sql = ""
22287
  try:
22288
- async with _ah_t2s.ClientSession() as s:
22289
- async with s.post(
22290
- "https://api.cerebras.ai/v1/chat/completions",
22291
- headers={"Authorization": f"Bearer {key}"},
22292
- json={"model": "qwen-3-235b-a22b-instruct-2507",
22293
- "messages": [{"role":"user","content":prompt}],
22294
- "max_tokens": 300, "temperature": 0.1},
22295
- timeout=_ah_t2s.ClientTimeout(total=20)
22296
- ) as r:
22297
- if r.status == 200:
22298
- d = await r.json()
22299
- sql = d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
22300
- # Extract SQL từ markdown nếu có
22301
- m = _re_t2s.search(r"```(?:sql)?\n?(.*?)```", sql, _re_t2s.DOTALL)
22302
- if m: sql = m.group(1).strip()
22303
  except Exception as e:
22304
  return {"sql": "", "result": f"AI lỗi: {e}", "row_count": 0}
22305
 
@@ -22510,13 +22368,10 @@ def _should_meta_expand(query: str, task_type: str,
22510
 
22511
  return any(t in q_lower for t in _META_TRIGGERS)
22512
 
22513
- # Pool 4 models nhẹ cho Meta-Prompting — fallback nếu model bị xóa
22514
- _META_MODEL_POOL = [
22515
- ("cerebras", "gpt-oss-120b"), # Ưu tiên 1: Cerebras nhanh nhất
22516
- ("cerebras", "qwen-3-235b-a22b-instruct-2507"), # Ưu tiên 2: Cerebras mạnh hơn
22517
- ("openrouter", _get_or_light()), # Ưu tiên 3: Gemma Google free
22518
- ("openrouter", "liquid/lfm-2.5-1.2b-instruct:free"), # Ưu tiên 4: Siêu nhẹ
22519
- ]
22520
 
22521
  def _detect_input_language(text: str) -> str:
22522
  """Phát hiện ngôn ngữ input để inject vào output instruction."""
@@ -22535,35 +22390,8 @@ def _detect_input_language(text: str) -> str:
22535
  return "Chinese"
22536
  return "English"
22537
 
22538
- async def _call_meta_model(key: str, model: str, platform: str,
22539
- messages: list, or_keys: list) -> str:
22540
- """Gọi 1 model trong pool — trả về '' nếu fail."""
22541
- import aiohttp as _ah_mm
22542
- try:
22543
- if platform == "cerebras":
22544
- url = "https://api.cerebras.ai/v1/chat/completions"
22545
- headers = {"Authorization": f"Bearer {key}"}
22546
- else: # openrouter
22547
- if not or_keys: return ""
22548
- import random as _rd_mm
22549
- key = or_keys[_rd_mm.randint(0, len(or_keys)-1)]
22550
- url = "https://openrouter.ai/api/v1/chat/completions"
22551
- headers = {"Authorization": f"Bearer {key}",
22552
- "HTTP-Referer": "https://huggingface.co"}
22553
-
22554
- async with _ah_mm.ClientSession() as s:
22555
- async with s.post(
22556
- url, headers=headers,
22557
- json={"model": model, "messages": messages,
22558
- "max_tokens": 180, "temperature": 0.2},
22559
- timeout=_ah_mm.ClientTimeout(total=12)
22560
- ) as r:
22561
- if r.status == 200:
22562
- d = await r.json()
22563
- return d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
22564
- except Exception:
22565
- pass
22566
- return ""
22567
 
22568
  async def _expand_prompt(query: str, task_type: str, role: str = "guest") -> str:
22569
  """
@@ -22615,28 +22443,28 @@ async def _expand_prompt(query: str, task_type: str, role: str = "guest") -> str
22615
  {"role": "user", "content": user_msg},
22616
  ]
22617
 
22618
- # Lấy keys
22619
- cb_keys = [_os_mp.environ.get(k,"") for k in _os_mp.environ if "CEREBRAS" in k.upper()]
22620
- cb_keys = [k for k in cb_keys if k]
22621
- or_keys_raw = OPENROUTER_KEYS if "OPENROUTER_KEYS" in dir() else []
22622
-
22623
- # Fallback Pool — thử lần lượt
22624
- for platform, model in _META_MODEL_POOL:
22625
- if platform == "cerebras" and not cb_keys:
22626
- continue
22627
- key = _rd_mp.choice(cb_keys) if platform == "cerebras" and cb_keys else ""
22628
- expanded = await _call_meta_model(key, model, platform, messages, or_keys_raw)
22629
  if expanded and len(expanded) > 20:
22630
  # Cache
22631
  if len(_META_CACHE) >= _META_CACHE_MAX:
22632
  del _META_CACHE[next(iter(_META_CACHE))]
22633
  _META_CACHE[cache_key] = expanded
22634
  _save_skill(f"[meta_prompt] {query[:60]}", expanded, success=True)
22635
- print(f"[META] ✅ [{model.split('/')[-1][:15]}] {user_lang}: {len(query)}→{len(expanded)}c")
22636
  return expanded
22637
- print(f"[META] ⚠️ {model} fail, thử model tiếp theo...")
 
 
22638
 
22639
- print(f"[META] ❌ Tất cả models fail — dùng query gốc")
22640
  return query
22641
 
22642
  def get_meta_stats() -> str:
@@ -22664,34 +22492,34 @@ _STITCH_TIMEOUT = 25 # Timeout mỗi phần (giây)
22664
 
22665
  async def _call_agent_part(role: str, system: str,
22666
  history: list, part_num: int) -> str:
22667
- """Gọi agent để lấy phần tiếp theo của code."""
22668
- import aiohttp as _ah_st, os as _os_st, random as _rd_st
22669
- cb_keys = [k for k in _os_st.environ if "CEREBRAS" in k.upper()]
22670
- if not cb_keys: return ""
22671
- key = _os_st.environ.get(_rd_st.choice(cb_keys), "")
22672
-
22673
- # Thêm lệnh "tiếp tục" vào cuối history
22674
- msgs = [{"role": "system", "content": system}]
22675
- msgs.extend(history)
22676
- msgs.append({"role": "user", "content":
22677
- f"tiếp tục (phần {part_num}) — in phần code tiếp theo, "
 
 
 
 
 
 
22678
  f"bắt đầu từ điểm vừa dừng, KHÔNG lặp lại code cũ."
22679
- })
 
22680
 
22681
  try:
22682
- async with _ah_st.ClientSession() as s:
22683
- async with s.post(
22684
- "https://api.cerebras.ai/v1/chat/completions",
22685
- headers={"Authorization": f"Bearer {key}"},
22686
- json={"model": "qwen-3-235b-a22b-instruct-2507",
22687
- "messages": msgs,
22688
- "max_tokens": 2000,
22689
- "temperature": 0.1},
22690
- timeout=_ah_st.ClientTimeout(total=_STITCH_TIMEOUT)
22691
- ) as r:
22692
- if r.status == 200:
22693
- d = await r.json()
22694
- return d.get("choices",[{}])[0].get("message",{}).get("content","")
22695
  except Exception as e:
22696
  print(f"[STITCH] Part {part_num} lỗi: {e}")
22697
  return ""
@@ -22883,11 +22711,8 @@ async def _solve_with_code(query: str, category: str, max_retry: int = None) ->
22883
  "finance": "Bạn là chuyên gia tài chính. Dùng Python để tính lãi suất, đầu tư chính xác.",
22884
  }.get(category, "Dùng Python để tính toán chính xác.")
22885
 
22886
- keys = [k for k in _os_hp.environ if "CEREBRAS" in k.upper()]
22887
- if not keys:
22888
- return {"solved": False, "result": "", "code": "", "verified": False}
22889
- key = _os_hp.environ.get(_rd_hp.choice(keys), "")
22890
-
22891
  code_prompt = (
22892
  f"{category_ctx}\n\n"
22893
  f"Bài toán: {query}\n\n"
@@ -22901,19 +22726,13 @@ async def _solve_with_code(query: str, category: str, max_retry: int = None) ->
22901
  )
22902
 
22903
  try:
22904
- async with _ah_hp.ClientSession() as s:
22905
- async with s.post(
22906
- "https://api.cerebras.ai/v1/chat/completions",
22907
- headers={"Authorization": f"Bearer {key}"},
22908
- json={"model": "qwen-3-235b-a22b-instruct-2507",
22909
- "messages": [{"role":"user","content":code_prompt}],
22910
- "max_tokens": 600, "temperature": 0.1},
22911
- timeout=_ah_hp.ClientTimeout(total=25)
22912
- ) as r:
22913
- if r.status != 200:
22914
- return {"solved": False, "result": "", "code": "", "verified": False}
22915
- d = await r.json()
22916
- code_raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
22917
  except Exception as e:
22918
  print(f"[HIGHPREC] AI lỗi: {e}")
22919
  return {"solved": False, "result": "", "code": "", "verified": False}
@@ -22958,20 +22777,14 @@ async def _solve_with_code(query: str, category: str, max_retry: int = None) ->
22958
  f"Sửa lại để chạy đúng. Chỉ trả về code."
22959
  )
22960
  try:
22961
- async with _ah_hp.ClientSession() as s:
22962
- async with s.post(
22963
- "https://api.cerebras.ai/v1/chat/completions",
22964
- headers={"Authorization": f"Bearer {key}"},
22965
- json={"model": "qwen-3-235b-a22b-instruct-2507",
22966
- "messages": [{"role":"user","content":fix_prompt}],
22967
- "max_tokens": 400, "temperature": 0.1},
22968
- timeout=_ah_hp.ClientTimeout(total=20)
22969
- ) as r2:
22970
- if r2.status == 200:
22971
- d2 = await r2.json()
22972
- code_raw2 = d2.get("choices",[{}])[0].get("message",{}).get("content","")
22973
- m2 = _re_hp.search(r"```(?:python)?\n?(.*?)```", code_raw2, _re_hp.DOTALL)
22974
- code = m2.group(1).strip() if m2 else code_raw2.strip()
22975
  except Exception:
22976
  pass
22977
  except _sp_hp.TimeoutExpired:
@@ -23831,23 +23644,20 @@ async def _extract_skill_from_learned(topic: str, content: str) -> bool:
23831
  f"Format: ĐỀ: [câu hỏi thực tế ai cũng có thể hỏi]\nTRẢ LỜI: [câu trả lời súc tích, đúng]"
23832
  )
23833
 
23834
- cb_keys = [k for k in _os_ex.environ if "CEREBRAS" in k.upper()]
23835
- if not cb_keys: return False
23836
- key = _os_ex.environ.get(_rd_ex.choice(cb_keys), "")
 
23837
 
23838
  try:
23839
- async with _ah_ex.ClientSession() as s:
23840
- async with s.post(
23841
- "https://api.cerebras.ai/v1/chat/completions",
23842
- headers={"Authorization": f"Bearer {key}"},
23843
- json={"model": "gpt-oss-120b", # Model nhẹ — tiết kiệm quota
23844
- "messages": [{"role": "user", "content": extract_prompt}],
23845
- "max_tokens": 400, "temperature": 0.4},
23846
- timeout=_ah_ex.ClientTimeout(total=15)
23847
- ) as r:
23848
- if r.status != 200: return False
23849
- d = await r.json()
23850
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
23851
  except Exception as e:
23852
  print(f"[EXTRACT] Lỗi: {e}")
23853
  return False
@@ -23912,23 +23722,17 @@ async def _auto_discover_topics(existing_topics: list, num_new: int = 5) -> list
23912
  f"Trả về danh sách {num_new} chủ đề, mỗi chủ đề 1 dòng. Không đánh số."
23913
  )
23914
 
23915
- cb_keys = [k for k in _os_dis.environ if "CEREBRAS" in k.upper()]
23916
- if not cb_keys: return []
23917
- key = _os_dis.environ.get(_rd_dis.choice(cb_keys), "")
23918
-
23919
  try:
23920
- async with _ah_dis.ClientSession() as s:
23921
- async with s.post(
23922
- "https://api.cerebras.ai/v1/chat/completions",
23923
- headers={"Authorization": f"Bearer {key}"},
23924
- json={"model": "gpt-oss-120b",
23925
- "messages": [{"role": "user", "content": discover_prompt}],
23926
- "max_tokens": 300, "temperature": 0.7},
23927
- timeout=_ah_dis.ClientTimeout(total=15)
23928
- ) as r:
23929
- if r.status != 200: return []
23930
- d = await r.json()
23931
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
23932
  except Exception as e:
23933
  print(f"[DISCOVER] Lỗi: {e}")
23934
  return []
@@ -23974,12 +23778,12 @@ async def _quality_gate(
23974
  "attempts": int
23975
  }
23976
  """
23977
- import aiohttp as _ah_qg, os as _os_qg, random as _rd_qg, json as _js_qg
 
23978
 
23979
- cb_keys = [k for k in _os_qg.environ if "CEREBRAS" in k.upper()]
23980
- if not cb_keys:
23981
- # Không có reviewer → pass thẳng
23982
- return {"output": output, "passed": True, "score": {}, "attempts": 1}
23983
 
23984
  # Pre-flight CDN map cho context
23985
  _cdn_hint = ""
@@ -24025,19 +23829,12 @@ async def _quality_gate(
24025
 
24026
  score_raw = ""
24027
  try:
24028
- key = _os_qg.environ.get(_rd_qg.choice(cb_keys), "")
24029
- async with _ah_qg.ClientSession() as s:
24030
- async with s.post(
24031
- "https://api.cerebras.ai/v1/chat/completions",
24032
- headers={"Authorization": f"Bearer {key}"},
24033
- json={"model": "gpt-oss-120b",
24034
- "messages": [{"role": "user", "content": review_prompt}],
24035
- "max_tokens": 120, "temperature": 0.0}, # 0.0 = deterministic
24036
- timeout=_ah_qg.ClientTimeout(total=12)
24037
- ) as r:
24038
- if r.status == 200:
24039
- d = await r.json()
24040
- score_raw = d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
24041
  except Exception as e:
24042
  print(f"[QUALITY-GATE] Reviewer lỗi: {e}")
24043
  return {"output": current_output, "passed": True, "score": {}, "attempts": attempt}
@@ -24163,12 +23960,8 @@ async def _agp_evolve_prompt(complaint: str, current_prompt: str) -> str:
24163
  Tự viết lại system prompt khi phát hiện phàn nàn.
24164
  Chỉ thay đổi phần style, không đụng vào rules cốt lõi.
24165
  """
24166
- import aiohttp as _ah_agp, os as _os_agp, random as _rd_agp
24167
-
24168
- cb_keys = [v for k,v in _os_agp.environ.items() if "CEREBRAS" in k.upper() and v]
24169
- if not cb_keys:
24170
- return current_prompt
24171
-
24172
  evolve_prompt = (
24173
  f"Boss phàn nàn: '{complaint[:100]}'\n\n"
24174
  f"System prompt hiện tại (phần style):\n"
@@ -24178,36 +23971,29 @@ async def _agp_evolve_prompt(complaint: str, current_prompt: str) -> str:
24178
  f"Trả về: THAY ĐỔI: [mô tả ngắn 1 câu] | PATCH: [text mới thay thế]"
24179
  )
24180
  try:
24181
- async with _ah_agp.ClientSession() as s:
24182
- async with s.post(
24183
- "https://api.cerebras.ai/v1/chat/completions",
24184
- headers={"Authorization": f"Bearer {_rd_agp.choice(cb_keys)}"},
24185
- json={"model": "gpt-oss-120b",
24186
- "messages": [{"role": "user", "content": evolve_prompt}],
24187
- "max_tokens": 200, "temperature": 0.4},
24188
- timeout=_ah_agp.ClientTimeout(total=10)
24189
- ) as r:
24190
- if r.status == 200:
24191
- d = await r.json()
24192
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
24193
- if "PATCH:" in raw:
24194
- import re as _re_agp
24195
- m = _re_agp.search(r"THAY ĐỔI:\s*(.+?)\s*\|\s*PATCH:\s*(.+)", raw, _re_agp.DOTALL)
24196
- if m:
24197
- change_desc = m.group(1).strip()
24198
- patch_text = m.group(2).strip()[:200]
24199
- _AGP_VERSION["patches"].append({
24200
- "complaint": complaint[:50],
24201
- "change": change_desc,
24202
- "patch": patch_text,
24203
- "v": _AGP_VERSION["version"]
24204
- })
24205
- _AGP_VERSION["version"] += 1
24206
- print(f"[AGP] 🧬 v{_AGP_VERSION['version']}: {change_desc[:50]}")
24207
- # Lưu vào lessons để apply lần sau
24208
- _lessons_add("agp_prompt_patch", patch_text,
24209
- confidence=0.6, source="agp")
24210
- return patch_text
24211
  except Exception as _ae:
24212
  print(f"[AGP] {_ae}")
24213
  return ""
@@ -24225,34 +24011,26 @@ async def _agent_debate_plan(task: str) -> dict:
24225
  Llama 8B làm reviewer (rẻ), không dùng model mạnh
24226
  Trả về: {plan, issues_found, final_plan}
24227
  """
24228
- import aiohttp as _ah_db, os as _os_db, random as _rd_db
24229
 
24230
- # Bước 1: Planner (dùng Cerebras Qwen nhẹ — tiết kiệm GitHub quota)
 
 
24231
  plan_prompt = (
24232
  f"Nhiệm vụ: {task[:500]}\n\n"
24233
  "Hãy lập kế hoạch kỹ thuật ngắn gọn (5-8 bước) để thực hiện nhiệm vụ này.\n"
24234
  "Chỉ liệt kê các bước kỹ thuật, không code."
24235
  )
24236
- cb_keys = [k for k in _os_db.environ if "CEREBRAS" in k.upper()]
24237
- if not cb_keys:
24238
- return {"plan": task, "issues_found": [], "final_plan": task}
24239
 
24240
  plan_text = ""
24241
  try:
24242
- key = _os_db.environ.get(_rd_db.choice(cb_keys), "")
24243
- async with _ah_db.ClientSession() as s:
24244
- async with s.post(
24245
- "https://api.cerebras.ai/v1/chat/completions",
24246
- headers={"Authorization": f"Bearer {key}"},
24247
- json={"model": "gpt-oss-120b", # Model nhẹ cho planning
24248
- "messages": [{"role": "user", "content": plan_prompt}],
24249
- "max_tokens": 400, "temperature": 0.3},
24250
- timeout=_ah_db.ClientTimeout(total=15)
24251
- ) as r:
24252
- if r.status == 200:
24253
- d = await r.json()
24254
- plan_text = d.get("choices",[{}])[0].get("message",{}).get("content","")
24255
- print(f"[DEBATE] 📋 Plan ({len(plan_text)} chars)")
24256
  except Exception as e:
24257
  print(f"[DEBATE] Plan error: {e}")
24258
  return {"plan": task, "issues_found": [], "final_plan": task}
@@ -24313,23 +24091,14 @@ async def _agent_debate_plan(task: str) -> dict:
24313
  )
24314
  issues = []
24315
  try:
24316
- key2 = _os_db.environ.get(_rd_db.choice(cb_keys), "")
24317
- async with _ah_db.ClientSession() as s:
24318
- async with s.post(
24319
- "https://api.cerebras.ai/v1/chat/completions",
24320
- headers={"Authorization": f"Bearer {key2}"},
24321
- json={"model": "gpt-oss-120b",
24322
- "messages": [{"role": "user", "content": review_prompt}],
24323
- "max_tokens": 200, "temperature": 0.1},
24324
- timeout=_ah_db.ClientTimeout(total=10)
24325
- ) as r:
24326
- if r.status == 200:
24327
- d = await r.json()
24328
- review = d.get("choices",[{}])[0].get("message",{}).get("content","")
24329
- if "OK" not in review.upper():
24330
- import re as _re_db
24331
- issues = _re_db.findall(r"ISSUE:\s*(.+)", review)
24332
- print(f"[DEBATE] 🔍 Review: {len(issues)} issues found")
24333
  except Exception as e:
24334
  print(f"[DEBATE] Review error: {e}")
24335
 
@@ -24392,37 +24161,24 @@ _ARENA_EXPECTED = {
24392
  async def _arena_self_test(category: str = None) -> dict:
24393
  """
24394
  Tự test 1 câu hỏi → đánh giá → nếu fail tạo bài tập mới lưu vào lessons.
24395
- Không tốn quota Boss — dùng Cerebras free.
24396
  Returns: {category, question, passed, insight}
 
 
24397
  """
24398
- import aiohttp as _ah_ar, os as _os_ar, random as _rd_ar
24399
-
24400
- cb_keys = [v for k,v in _os_ar.environ.items() if "CEREBRAS" in k.upper() and v]
24401
- if not cb_keys:
24402
- return {"passed": True, "reason": "no_cerebras"}
24403
-
24404
  # Chọn category và câu hỏi ngẫu nhiên
24405
- cat = category or _rd_ar.choice(list(_ARENA_CATEGORIES.keys()))
24406
- question = _rd_ar.choice(_ARENA_CATEGORIES[cat])
24407
 
24408
  try:
24409
- async with _ah_ar.ClientSession() as s:
24410
- async with s.post(
24411
- "https://api.cerebras.ai/v1/chat/completions",
24412
- headers={"Authorization": f"Bearer {_rd_ar.choice(cb_keys)}"},
24413
- json={"model": "gpt-oss-120b",
24414
- "messages": [
24415
- {"role": "system",
24416
- "content": "Trả lời ngắn gọn, thật thà. Nếu không biết thì nói không biết."},
24417
- {"role": "user", "content": question}
24418
- ],
24419
- "max_tokens": 200, "temperature": 0.3},
24420
- timeout=_ah_ar.ClientTimeout(total=12)
24421
- ) as r:
24422
- if r.status != 200:
24423
- return {"passed": True, "reason": "api_error"}
24424
- d = await r.json()
24425
- answer = d.get("choices",[{}])[0].get("message",{}).get("content","")
24426
  except Exception as _ae:
24427
  return {"passed": True, "reason": str(_ae)[:30]}
24428
 
@@ -24457,41 +24213,32 @@ async def _arena_self_test(category: str = None) -> dict:
24457
 
24458
  # ════════════════════════════════════════════════════════════════
24459
  # CONTEXT CURATOR v1.0 — Lọc context trước khi gửi AI lớn
24460
- # Cerebras Llama-8B đọc và bỏ thông tin rác, chỉ giữ ý chính
24461
  # ════════════════════════════════════════════════════════════════
24462
  async def _curate_context(query: str, raw_context: str,
24463
  max_output: int = 800) -> str:
24464
  """
24465
- Lọc context bằng Cerebras Llama-8B.
24466
  Chỉ giữ thông tin liên quan đến query.
 
 
24467
  """
24468
  if len(raw_context) < 1500:
24469
  return raw_context
24470
- import aiohttp as _ah_cc, os as _os_cc, random as _rd_cc
24471
- cb_keys = [v for k,v in _os_cc.environ.items() if "CEREBRAS" in k.upper() and v]
24472
- if not cb_keys:
24473
- return raw_context[:max_output]
24474
  curator_prompt = (
24475
  f"Query: {query[:150]}\n\nContext thô:\n{raw_context[:3000]}\n\n"
24476
  f"Chỉ giữ lại tối đa {max_output} ký tự thông tin liên quan đến Query. "
24477
  f"Bỏ thông tin thừa. Trả về text đã lọc, không giải thích."
24478
  )
24479
  try:
24480
- async with _ah_cc.ClientSession() as s:
24481
- async with s.post(
24482
- "https://api.cerebras.ai/v1/chat/completions",
24483
- headers={"Authorization": f"Bearer {_rd_cc.choice(cb_keys)}"},
24484
- json={"model": "gpt-oss-120b",
24485
- "messages": [{"role": "user", "content": curator_prompt}],
24486
- "max_tokens": 400, "temperature": 0.1},
24487
- timeout=_ah_cc.ClientTimeout(total=8)
24488
- ) as r:
24489
- if r.status == 200:
24490
- d = await r.json()
24491
- curated = d.get("choices",[{}])[0].get("message",{}).get("content","")
24492
- if curated and len(curated) > 50:
24493
- print(f"[CURATOR] {len(raw_context)} → {len(curated)} chars")
24494
- return curated
24495
  except Exception as _ce:
24496
  print(f"[CURATOR] skip: {_ce}")
24497
  return raw_context[:max_output]
@@ -24667,30 +24414,23 @@ async def visual_test_and_fix(html_code: str, task_desc: str,
24667
  f"Trả về toàn bộ code đã sửa trong ```html ... ```\n\n"
24668
  f"Code hiện tại:\n```html\n{current_html[:3000]}\n```"
24669
  )
24670
- # Gọi Cerebras để sửa nhanh
24671
- cb_keys = [k for k in _os_vtf.environ if "CEREBRAS" in k.upper()]
24672
- if cb_keys:
24673
- key = _os_vtf.environ.get(_rd_vtf.choice(cb_keys), "")
24674
- try:
24675
- async with _ah_vtf.ClientSession() as s:
24676
- async with s.post(
24677
- "https://api.cerebras.ai/v1/chat/completions",
24678
- headers={"Authorization": f"Bearer {key}"},
24679
- json={"model": "qwen-3-235b-a22b-instruct-2507",
24680
- "messages": [{"role":"user","content":fix_prompt}],
24681
- "max_tokens": 4000, "temperature": 0.1},
24682
- timeout=_ah_vtf.ClientTimeout(total=30)
24683
- ) as r:
24684
- if r.status == 200:
24685
- d = await r.json()
24686
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
24687
- import re as _re_fix
24688
- m = _re_fix.search(r"```html\n?(.*?)```", raw, _re_fix.DOTALL)
24689
- if m:
24690
- current_html = m.group(1).strip()
24691
- print(f"[VISION] ✅ Code đã sửa ({len(current_html)} chars)")
24692
- except Exception as e:
24693
- print(f"[VISION] Fix lỗi: {e}")
24694
 
24695
  # Trả về bản tốt nhất
24696
  print(f"[VISION] ⚠️ Max retries reached, best score={best_score}")
@@ -24850,38 +24590,28 @@ _SELF_PLAY_TOPICS = {
24850
  }
24851
 
24852
  async def _call_cerebras_sp(prompt: str, system: str = "", temp: float = 0.7) -> str:
24853
- """Gọi Cerebras 235B cho self-play — nhanh nhất."""
24854
- import aiohttp as _ah_sp2, os as _os_sp, re as _re_sp_t
24855
- keys = [k for k in _os_sp.environ if "CEREBRAS" in k.upper()]
24856
- if not keys: return ""
24857
- key = _os_sp.environ.get(_rd_sp.choice(keys), "")
24858
- msgs = []
24859
- if system: msgs.append({"role":"system","content":system})
24860
- msgs.append({"role":"user","content":prompt})
24861
- # Thử model mạnh trước, fallback sang llama3.1-8b nếu lỗi
24862
- for model in ["qwen-3-235b-a22b-instruct-2507", "gpt-oss-120b", "gpt-oss-120b"]:
24863
- try:
24864
- async with _ah_sp2.ClientSession() as s:
24865
- async with s.post(
24866
- "https://api.cerebras.ai/v1/chat/completions",
24867
- headers={"Authorization":f"Bearer {key}"},
24868
- json={"model": model,
24869
- "messages":msgs,"max_tokens":800,"temperature":temp},
24870
- timeout=_ah_sp2.ClientTimeout(total=30)
24871
- ) as r:
24872
- if r.status == 200:
24873
- d = await r.json()
24874
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
24875
- # Strip <think>...</think> từ Qwen3/DeepSeek thinking mode
24876
- # Không strip → regex ```python``` không bắt code → score=0
24877
- raw = _re_sp_t.sub(r"<think>.*?</think>", "", raw, flags=_re_sp_t.DOTALL).strip()
24878
- if raw:
24879
- return raw
24880
- elif r.status == 429:
24881
- continue # Rate limit → thử model khác
24882
- except Exception as e:
24883
- print(f"[SELF-PLAY] Cerebras {model} lỗi: {e}")
24884
- continue
24885
  return ""
24886
 
24887
  async def _evaluate_science(task: str, solution: str) -> dict:
@@ -31500,28 +31230,25 @@ async def run_debate_mode(topic: str, task_type: str = "code") -> str:
31500
  return ""
31501
 
31502
  async def _call_cerebras_debate(prompt: str) -> str:
31503
- """Gọi Cerebras 235B làm Critic."""
31504
- cbkeys = [_os_db.environ.get(k) for k in _os_db.environ if "CEREBRAS" in k.upper()]
31505
- cbkeys = [k for k in cbkeys if k]
31506
- if not cbkeys: return ""
31507
- key = _rd_db.choice(cbkeys)
 
 
31508
  try:
31509
- async with _ah_db.ClientSession() as s:
31510
- async with s.post(
31511
- "https://api.cerebras.ai/v1/chat/completions",
31512
- headers={"Authorization": f"Bearer {key}"},
31513
- json={"model": "qwen-3-235b-a22b-instruct-2507",
31514
- "messages": [{"role": "user", "content": prompt}],
31515
- "max_tokens": 600, "temperature": 0.3},
31516
- timeout=_ah_db.ClientTimeout(total=25)
31517
- ) as r:
31518
- if r.status == 200:
31519
- d = await r.json()
31520
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
31521
- import re as _re_db2
31522
- return _re_db2.sub(r"<think>.*?</think>", "", raw, flags=_re_db2.DOTALL).strip()
31523
  except Exception as e:
31524
- print(f"[DEBATE] Cerebras lỗi: {e}")
31525
  return ""
31526
 
31527
  async def _call_cohere_judge(prompt: str) -> str:
@@ -32338,24 +32065,20 @@ async def run_debate_mode_bayes(topic: str, task_type: str = "code") -> str:
32338
  """Gọi agent theo tên."""
32339
  try:
32340
  if name in ("cerebras", "deepseek"):
32341
- cb_keys = [_os_bdb.environ.get(k) for k in _os_bdb.environ
32342
- if "CEREBRAS" in k.upper() and _os_bdb.environ.get(k)]
32343
- if not cb_keys: return ""
32344
- model = ("qwen-3-235b-a22b-instruct-2507" if name == "cerebras"
32345
- else "gpt-oss-120b")
32346
- async with _ah_bdb.ClientSession() as s:
32347
- async with s.post(
32348
- "https://api.cerebras.ai/v1/chat/completions",
32349
- headers={"Authorization": f"Bearer {_rd_bdb.choice(cb_keys)}"},
32350
- json={"model": model,
32351
- "messages": [{"role": "user", "content": prompt}],
32352
- "max_tokens": max_tok, "temperature": 0.3},
32353
- timeout=_ah_bdb.ClientTimeout(total=25)
32354
- ) as r:
32355
- if r.status == 200:
32356
- d = await r.json()
32357
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
32358
- return _re_bdb.sub(r"<think>.*?</think>","",raw,flags=_re_bdb.DOTALL).strip()
32359
  elif name == "gemini":
32360
  gkeys = [_os_bdb.environ.get(k) for k in _os_bdb.environ
32361
  if "GEMINI" in k.upper() and _os_bdb.environ.get(k)]
@@ -32484,27 +32207,26 @@ async def _call_weak_solver(prompt: str) -> str:
32484
 
32485
 
32486
  async def _call_strong_solver(prompt: str, task_type: str = "code") -> str:
32487
- """Strong solver: Cerebras 235B — mạnh nhất free."""
32488
- import aiohttp as _ah_ss, os as _os_ss, random as _rd_ss, re as _re_ss
32489
- cb_keys = [_os_ss.environ.get(k) for k in _os_ss.environ
32490
- if "CEREBRAS" in k.upper() and _os_ss.environ.get(k)]
32491
- if not cb_keys: return ""
 
 
 
 
32492
  try:
32493
- async with _ah_ss.ClientSession() as s:
32494
- async with s.post(
32495
- "https://api.cerebras.ai/v1/chat/completions",
32496
- headers={"Authorization": f"Bearer {_rd_ss.choice(cb_keys)}"},
32497
- json={"model": "qwen-3-235b-a22b-instruct-2507",
32498
- "messages": [{"role": "user", "content": prompt}],
32499
- "max_tokens": 800, "temperature": 0.2},
32500
- timeout=_ah_ss.ClientTimeout(total=30)
32501
- ) as r:
32502
- if r.status == 200:
32503
- d = await r.json()
32504
- raw = d.get("choices",[{}])[0].get("message",{}).get("content","")
32505
- return _re_ss.sub(r"<think>.*?</think>","",raw,flags=_re_ss.DOTALL).strip()
32506
  except Exception as e:
32507
- print(f"[STRONG-SOLVER] Cerebras lỗi: {e}")
32508
  return ""
32509
 
32510
 
 
10816
  }
10817
 
10818
  if not github_success:
10819
+ # ── Router STRONG (đa-provider, nhóm "reasoning") ──
10820
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras
10821
+ # qwen-3-235b — Cerebras free tier đóng cửa 17/08/2026. Giờ
10822
+ # dùng nhóm "reasoning" qua yui_model_router (đa-provider).
10823
  _cb_success = False
10824
  try:
10825
+ _max_tokens = _max_tok if "_max_tok" in dir() else 4000 # Fix: _max_tok scope
10826
+ # Ghép `messages` (format OpenAI [{role, content}]) thành 1
10827
+ # prompt text — router generic nhận prompt+system, không
10828
+ # nhận messages array trực tiếp.
10829
+ _sys_txt = ""
10830
+ _hist_lines = []
10831
+ for _m in messages:
10832
+ _role = _m.get("role", "")
10833
+ _content = _m.get("content", "")
10834
+ if _role == "system":
10835
+ _sys_txt = _content
10836
+ elif _role == "user":
10837
+ _hist_lines.append(f"User: {_content}")
10838
+ elif _role == "assistant":
10839
+ _hist_lines.append(f"Yui: {_content}")
10840
+ _full_prompt = "\n".join(_hist_lines)
10841
+
10842
+ from yui_model_router import call_task_group as _ctg_cbfb
10843
+ async def _cb_fb_call():
10844
+ return await _ctg_cbfb(
10845
+ group="reasoning", prompt=_full_prompt, system=_sys_txt,
10846
+ max_tokens=_max_tokens, timeout_sec=30,
10847
  )
10848
+ _cb_txt = _run_async_safe(_cb_fb_call())
10849
+ if _cb_txt and len(_cb_txt) > 50:
10850
+ print(f"✅ [ROUTER-FALLBACK] Đã dùng router (reasoning)")
10851
+ _cb_success = True
10852
+ final_reply = _finalize_reply(_cb_txt, user_query, is_code=is_hard_task, task_type=_task_type, web_context=_web_context, history=history)
10853
+ except Exception as _cb_fb_err:
10854
+ _ne_log_error("router_fallback", str(_cb_fb_err), user_query, "router")
10855
+ print(f"⚠️ [ROUTER-FALLBACK] {_cb_fb_err}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10856
 
10857
  # ── Thử Mistral Codestral sau Cerebras (CODE SPECIALIST) ──
10858
  if not _cb_success and MISTRAL_KEYS and _task_type in ("code", "math"):
 
11009
  continue
11010
  if _or_success: break
11011
 
11012
+ # ── Router (đa-provider) — Admin fallback trước Gemini ──
11013
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras
11014
+ # gpt-oss-120b bằng key riêng Admin/Friend — Cerebras free
11015
+ # tier đóng cửa 17/08/2026. Giờ dùng nhóm "reasoning" qua
11016
+ # yui_model_router (đa-provider, tự xoay vòng qua nhiều
11017
+ # hãng, không còn phụ thuộc pool key Cerebras riêng).
11018
+ try:
11019
+ _rt_hist_lines = []
11020
+ for _t in recent_history:
11021
+ if isinstance(_t, (list, tuple)) and len(_t) >= 2:
11022
+ _rt_hist_lines.append(f"User: {_t[0]}")
11023
+ _rt_hist_lines.append(f"Yui: {_t[1]}")
11024
+ _rt_full_prompt = (
11025
+ ("\n".join(_rt_hist_lines) + "\n\n" if _rt_hist_lines else "")
11026
+ + f"User: {user_query}"
11027
+ )
11028
+ from yui_model_router import call_task_group as _ctg_cba
11029
+ async def _cba_call():
11030
+ return await _ctg_cba(
11031
+ group="reasoning", prompt=_rt_full_prompt, system=system_prompt or "",
11032
+ max_tokens=4000, timeout_sec=25,
11033
+ )
11034
+ _cba_result = _run_async_safe(_cba_call())
11035
+ if _cba_result:
11036
+ print(f"✅ [ROUTER-ADMIN] trả lời thành công!")
11037
+ _req_counter.inc("router_admin")
11038
+ return _finalize_reply(_cba_result, user_query, is_code=is_hard_task, task_type=_task_type, web_context=_web_context, history=history)
11039
+ except Exception as _cae:
11040
+ print(f"⚠️ [ROUTER-ADMIN] {_cae.__class__.__name__}")
 
 
 
 
 
 
 
 
11041
 
11042
  # Nếu tất cả hết → Gemini
11043
  print("⚠️ [GITHUB+OR+CB] Hết quota! Chuyển sang GEMINI 2.5 PRO THINKING...")
 
11133
  # target_brain = "cerebras_strong" được set khi task=knowledge
11134
  # =======================================================
11135
  if target_brain == "cerebras_strong":
11136
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras (kể cả
11137
+ # logic ưu tiên GLM-4.7 "scarce model" riêng cho code/debug) —
11138
+ # Cerebras free tier đóng cửa 17/08/2026, logic scarce-model
11139
+ # riêng của Cerebras không còn áp dụng được. Giờ dùng nhóm
11140
+ # "reasoning" qua yui_model_router — nhóm này đã có OpenRouter
11141
+ # (deepseek/qwen-coder free) + Mistral Codestral cho code, tự
11142
+ # xoay vòng đa-provider.
11143
+ try:
11144
+ _rt_hist_lines2 = []
11145
+ for _t in recent_history:
11146
+ if isinstance(_t, (list, tuple)) and len(_t) >= 2:
11147
+ _rt_hist_lines2.append(f"User: {_t[0]}")
11148
+ _rt_hist_lines2.append(f"Yui: {_t[1]}")
11149
+ _rt_full_prompt2 = (
11150
+ ("\n".join(_rt_hist_lines2) + "\n\n" if _rt_hist_lines2 else "")
11151
+ + f"User: {user_query}"
11152
+ )
11153
+ _rt_group = "code" if _task_type in ("code", "debug") else "reasoning"
11154
+ from yui_model_router import call_task_group as _ctg_cbs
11155
+ async def _cb_adm_call():
11156
+ return await _ctg_cbs(
11157
+ group=_rt_group, prompt=_rt_full_prompt2, system=system_prompt or "",
11158
+ max_tokens=4000, timeout_sec=25,
 
 
 
 
 
 
11159
  )
11160
+ _cb_adm_txt = _run_async_safe(_cb_adm_call())
11161
+ if _cb_adm_txt and len(_cb_adm_txt) > 10:
11162
+ print(f"✅ [ROUTER-KNOWLEDGE] nhóm={_rt_group} trả lời thành công!")
11163
+ _req_counter.inc("router_strong")
11164
+ return _finalize_reply(_cb_adm_txt, user_query, is_code=is_hard_task, task_type=_task_type, web_context=_web_context, history=history)
11165
+ print("⚠️ [ROUTER-KNOWLEDGE] Reply rỗng, fallback...")
11166
+ except Exception as _cb_adm_e:
11167
+ print(f"⚠️ [ROUTER-KNOWLEDGE] {_cb_adm_e.__class__.__name__}: {str(_cb_adm_e)[:60]}")
11168
+ # Router fail → fallback Gemini
11169
+ print("⚠️ [ROUTER-KNOWLEDGE] Chuyển sang Gemini thinking...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11170
  target_brain = "gemini_thinking"
11171
 
11172
  # =======================================================
 
12943
  val = str(brain_memory.get(key, ""))
12944
  if len(val) < 300: continue
12945
  try:
12946
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras gpt-oss-120b
12947
+ # qua urllib — Cerebras free tier đóng cửa 17/08/2026. Giờ dùng
12948
+ # nhóm "fast_light" qua yui_model_router (đa-provider).
12949
+ import asyncio as _asy_mc
12950
+ from yui_model_router import call_task_group as _ctg_mc
12951
  prompt_c = (
12952
  f"Đọc đoạn thông tin sau và rút ra ĐÚNG 1 CÂU kinh nghiệm cốt lõi "
12953
  f"(dưới 100 ký tự, bắt đầu bằng 'Kinh nghiệm:'):\n\n{val[:800]}"
12954
  )
12955
+
12956
+ async def _go_mc():
12957
+ return await _ctg_mc(
12958
+ group="fast_light", prompt=prompt_c, system="",
12959
+ max_tokens=80, timeout_sec=10,
12960
+ )
12961
+
12962
+ summary = _asy_mc.run(_go_mc())
12963
+ if summary:
12964
+ summary = summary.strip()
 
 
 
12965
  if summary and len(summary) > 10:
12966
  brain_memory[f"[nén] {key[:60]}"] = summary
12967
  del brain_memory[key]
 
17166
  print(f"[BDS-AI] Cohere loi: {e}")
17167
 
17168
  try:
17169
+ # ── Fallback Router (đa-provider) — nhanh ──────────────
17170
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras
17171
+ # qwen-3-235b — Cerebras free tier đóng cửa 17/08/2026.
17172
+ from yui_model_router import call_task_group as _ctg_bds
17173
+ text = await _ctg_bds(
17174
+ group="reasoning", prompt=prompt, system=system,
17175
+ max_tokens=1200, timeout_sec=35,
17176
+ )
17177
+ if text and len(text) > 100:
17178
+ print(f"[BDS-AI] Router OK ({len(text)} chars)")
17179
+ return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17180
  except Exception as e:
17181
+ print(f"[BDS-AI] Router loi: {e}")
17182
 
17183
  try:
17184
  # ── Fallback Gemini Flash ──────────────────────────────
 
17329
  except Exception as e:
17330
  print(f"[VIDEO-SCRIPT] Cohere loi: {e}")
17331
 
17332
+ # 2. Router fallback (đa-provider)
17333
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras —
17334
+ # Cerebras free tier đóng cửa 17/08/2026.
17335
  if not result:
17336
  try:
17337
+ from yui_model_router import call_task_group as _ctg_vs
17338
+ result = await _ctg_vs(
17339
+ group="reasoning", prompt=prompt, system="",
17340
+ max_tokens=800, timeout_sec=25,
17341
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
17342
  except Exception as e:
17343
+ print(f"[VIDEO-SCRIPT] Router loi: {e}")
17344
 
17345
  if not result:
17346
  return {"error": "Khong tao duoc kich ban luc nay, thu lai sau"}
 
18437
  - Không truyền văn bản trung gian qua mạng → nhanh hơn
18438
  - Chính xác hơn single-shot nhờ self-critique
18439
  """
18440
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY chỉ chạy nếu có CEREBRAS_KEY, cả
18441
+ # Critic và Defender đều gọi Cerebras — Cerebras free tier đóng cửa
18442
+ # 17/08/2026. Giờ dùng nhóm "reasoning" qua yui_model_router (đa-
18443
+ # provider), và Defender loại trừ provider Critic vừa dùng — giữ đúng
18444
+ # tinh thần "2 vai độc lập, không tự chấm bài mình" của thiết kế gốc.
18445
+ from yui_model_router import call_task_group_multi as _ctgm_imad
18446
 
18447
  current_answer = initial_answer
18448
  tokens_saved = 0 # Ước tính token tiết kiệm so với full debate
 
18459
  "Nếu có vấn đề: mỗi vấn đề 1 dòng ngắn gọn."
18460
  )
18461
  critique = ""
18462
+ critic_provider = None
18463
  try:
18464
+ _res = await _ctgm_imad(
18465
+ group="reasoning", prompt=critic_prompt, system="",
18466
+ max_tokens=150, timeout_sec=12, n=1,
18467
+ )
18468
+ if _res:
18469
+ critic_provider, critique = _res[0]
 
 
 
 
 
 
 
 
 
18470
  except Exception as _e_imad:
18471
  print(f"[IMAD] Critic round {round_num} lỗi: {_e_imad}")
18472
  break
 
18489
  "Không cần giải thích tại sao sửa — chỉ trả về câu trả lời mới."
18490
  )
18491
  try:
18492
+ from yui_model_router import call_task_group as _ctg_imad_def
18493
+ improved = await _ctg_imad_def(
18494
+ group="reasoning", prompt=defender_prompt, system="",
18495
+ max_tokens=800, timeout_sec=20,
18496
+ exclude_providers=[critic_provider] if critic_provider else None,
18497
+ )
18498
+ if improved and len(improved) > 50:
18499
+ current_answer = improved
18500
+ print(f"[IMAD] 🔄 Round {round_num}: Cải thiện +{len(improved) - len(initial_answer)} chars")
 
 
 
 
 
 
 
 
 
18501
  except Exception as _e_def:
18502
  print(f"[IMAD] Defender round {round_num} lỗi: {_e_def}")
18503
 
18504
  # Ước tính token tiết kiệm so với spawn 2 AI riêng biệt
18505
  tokens_saved += len(critic_prompt) // 4 # 1 token ~ 4 chars
18506
 
18507
+ _tbg_add("router", (len(query) + len(current_answer)) // 4)
18508
  print(f"[IMAD] ✅ Xong {_IMAD_DEBATE_ROUNDS} rounds | ~{tokens_saved} tokens saved vs Multi-Agent")
18509
  return current_answer
18510
 
 
18911
  import asyncio as _aio_ma
18912
 
18913
  async def _call_agent(role: str, prompt: str, context: str = "") -> str:
18914
+ """
18915
+ Gọi AI với role cụ thể (Planning/Coding/Reviewer).
18916
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras 235B — Cerebras
18917
+ free tier đóng cửa 17/08/2026. Giờ dùng nhóm "reasoning" qua
18918
+ yui_model_router (đa-provider, tự xoay vòng). Giữ nguyên chữ ký hàm để
18919
+ mọi lời gọi _call_agent(...) trong Multi-Agent Orchestrator không cần
18920
+ sửa gì thêm.
18921
+ """
18922
  try:
18923
+ from yui_model_router import call_task_group as _ctg_ma
18924
+ result = await _ctg_ma(
18925
+ group="reasoning", prompt=prompt, system=f"Bạn là {role}. {context}",
18926
+ max_tokens=1200, timeout_sec=30,
18927
+ )
18928
+ return result or ""
 
 
 
 
 
18929
  except Exception as e:
18930
  print(f"[AGENT] {role} lỗi: {e}")
18931
  return ""
 
19545
  results = {"summary": "", "facts": "", "reasoning": ""}
19546
 
19547
  def _call_agent(role: str, prompt: str) -> tuple:
19548
+ """
19549
+ Gọi model cho MRAC.
19550
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY cascade tay Gemini→Cerebras→
19551
+ Cohere — Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm
19552
+ "fast_light" qua yui_model_router (đa-provider, đã có Gemini +
19553
+ Cohere + Mistral + SambaNova, tự xoay vòng — không cần cascade
19554
+ tay 3 tầng như cũ nữa).
19555
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19556
  try:
19557
+ import asyncio as _asy_mrac
19558
+ from yui_model_router import call_task_group as _ctg_mrac
19559
+
19560
+ async def _go_mrac():
19561
+ return await _ctg_mrac(
19562
+ group="fast_light", prompt=prompt,
19563
+ system="Trả lời ngắn gọn, chính xác, đúng format được yêu cầu.",
19564
+ max_tokens=600, timeout_sec=15,
19565
+ )
19566
+
19567
+ r = _asy_mrac.run(_go_mrac())
19568
+ if r and len(r.strip()) > 5:
19569
+ return (role, r.strip())
19570
  except Exception as e:
19571
+ print(f"[MRAC/{role}] Router lỗi: {str(e)[:50]}")
19572
  return (role, "")
19573
 
19574
  try:
 
20450
  f"Chỉ viết code Python thuần, không giải thích dài dòng."
20451
  )
20452
 
20453
+ # Chọn model: Router (đa-provider) mạnh trước, GitHub làm fallback
 
20454
  gh_keys = [k for k in _os_ne.environ if "GITHUB" in k.upper() or "GITHUB_KEY" in k.upper()]
20455
 
20456
  reply = ""
20457
 
20458
+ # Thử Router nhóm "code" (mạnh, nhanh, đa-provider)
20459
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras Qwen-235B —
20460
+ # Cerebras free tier đóng cửa 17/08/2026.
20461
+ try:
20462
+ from yui_model_router import call_task_group as _ctg_ne
20463
+ reply = await _ctg_ne(
20464
+ group="code", prompt=evolver_prompt, system="",
20465
+ max_tokens=1500, timeout_sec=30,
20466
+ )
20467
+ if reply:
20468
+ print(f"[EVOLVER] 🧬 Router (code) generated skills")
20469
+ except Exception as e:
20470
+ print(f"[EVOLVER] Router error: {e}")
 
 
 
 
 
 
 
20471
 
20472
  # Fallback GitHub
20473
  if not reply and gh_keys:
 
21365
 
21366
  print(f"[PROMPT-EVO] 🔧 Evolver fixing {len(weak_agents)} weak agents...")
21367
 
21368
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
21369
+ # bỏ guard cb_keys, giờ dùng nhóm "fast_light" qua yui_model_router.
 
21370
 
21371
  for wa in weak_agents[:2]: # Max 2 agents mỗi đêm
21372
  agent_name = wa["agent"]
 
21380
  )
21381
 
21382
  try:
21383
+ from yui_model_router import call_task_group as _ctg_pe
21384
+ patch = await _ctg_pe(
21385
+ group="fast_light", prompt=evolve_prompt, system="",
21386
+ max_tokens=150, timeout_sec=12,
21387
+ )
21388
+ if patch:
21389
+ patch = patch.strip()
21390
+ if patch and len(patch) > 20:
21391
+ _set_prompt_patch(agent_name, patch)
21392
+ # Thêm vào lessons_learned
21393
+ _lessons_add(
 
 
 
 
 
 
21394
  topic=f"agent_fix:{agent_name}",
21395
  lesson=f"Prompt patch: {patch[:100]}",
21396
  confidence=0.75,
 
22027
  import subprocess as _sp_tdd, tempfile as _tmp_tdd, sys as _sys_tdd
22028
 
22029
  async def _generate_tests(code: str, task: str) -> str:
22030
+ """
22031
+ Dùng AI sinh test cases cho code.
22032
+ 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
22033
+ giờ dùng nhóm "code" qua yui_model_router.
22034
+ """
22035
  prompt = (
22036
  f"Task gốc: {task}\n\nCode:\n```python\n{code[:1000]}\n```\n\n"
22037
  "Viết unittest Python kiểm tra code này.\n"
 
22042
  "- Chỉ trả về code test, không giải thích"
22043
  )
22044
  try:
22045
+ from yui_model_router import call_task_group as _ctg_tdd
22046
+ result = await _ctg_tdd(
22047
+ group="code", prompt=prompt, system="",
22048
+ max_tokens=800, timeout_sec=25,
22049
+ )
22050
+ return result or ""
 
 
 
 
 
 
22051
  except Exception as e:
22052
  print(f"[TDD] Generate test lỗi: {e}")
22053
  return ""
 
22138
  return {"sql": "", "result": schema, "row_count": 0}
22139
 
22140
  # Sinh SQL
22141
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
22142
+ # giờ dùng nhóm "code" qua yui_model_router.
 
 
22143
  prompt = (
22144
  f"Database schema:\n{schema}\n\n"
22145
  f"Câu hỏi: {question}\n\n"
 
22148
  )
22149
  sql = ""
22150
  try:
22151
+ from yui_model_router import call_task_group as _ctg_t2s
22152
+ sql = await _ctg_t2s(
22153
+ group="code", prompt=prompt, system="",
22154
+ max_tokens=300, timeout_sec=20,
22155
+ )
22156
+ if sql:
22157
+ sql = sql.strip()
22158
+ # Extract SQL từ markdown nếu có
22159
+ m = _re_t2s.search(r"```(?:sql)?\n?(.*?)```", sql, _re_t2s.DOTALL)
22160
+ if m: sql = m.group(1).strip()
 
 
 
 
 
22161
  except Exception as e:
22162
  return {"sql": "", "result": f"AI lỗi: {e}", "row_count": 0}
22163
 
 
22368
 
22369
  return any(t in q_lower for t in _META_TRIGGERS)
22370
 
22371
+ # 🔄 MIGRATION (2026-07-17): Đã bỏ _META_MODEL_POOL cứng (2x Cerebras +
22372
+ # 2x OpenRouter) — Cerebras free tier đóng cửa 17/08/2026. Giờ _expand_prompt
22373
+ # gọi thẳng yui_model_router nhóm "fast_light" (đa-provider, tự xoay vòng),
22374
+ # không cần pool cứng + hàm _call_meta_model riêng nữa.
 
 
 
22375
 
22376
  def _detect_input_language(text: str) -> str:
22377
  """Phát hiện ngôn ngữ input để inject vào output instruction."""
 
22390
  return "Chinese"
22391
  return "English"
22392
 
22393
+ # _call_meta_model đã bị loại bỏ (2026-07-17) — _expand_prompt gọi thẳng
22394
+ # yui_model_router, không cần helper riêng cho từng platform nữa.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22395
 
22396
  async def _expand_prompt(query: str, task_type: str, role: str = "guest") -> str:
22397
  """
 
22443
  {"role": "user", "content": user_msg},
22444
  ]
22445
 
22446
+ # Gọi router (đa-provider, tự xoay vòng — thay cho pool cứng cũ)
22447
+ try:
22448
+ from yui_model_router import call_task_group as _ctg_mp
22449
+ expanded = await _ctg_mp(
22450
+ group="fast_light", prompt=user_msg, system=system_msg,
22451
+ max_tokens=180, timeout_sec=12,
22452
+ )
22453
+ if expanded:
22454
+ expanded = expanded.strip()
 
 
22455
  if expanded and len(expanded) > 20:
22456
  # Cache
22457
  if len(_META_CACHE) >= _META_CACHE_MAX:
22458
  del _META_CACHE[next(iter(_META_CACHE))]
22459
  _META_CACHE[cache_key] = expanded
22460
  _save_skill(f"[meta_prompt] {query[:60]}", expanded, success=True)
22461
+ print(f"[META] ✅ {user_lang}: {len(query)}→{len(expanded)}c")
22462
  return expanded
22463
+ print(f"[META] ⚠️ Router trả rỗng — dùng query gốc")
22464
+ except Exception as _e_mp:
22465
+ print(f"[META] ⚠️ Router lỗi: {_e_mp}")
22466
 
22467
+ print(f"[META] ❌ Router fail — dùng query gốc")
22468
  return query
22469
 
22470
  def get_meta_stats() -> str:
 
22492
 
22493
  async def _call_agent_part(role: str, system: str,
22494
  history: list, part_num: int) -> str:
22495
+ """
22496
+ Gọi agent để lấy phần tiếp theo của code.
22497
+ 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
22498
+ giờ dùng nhóm "code" qua yui_model_router.
22499
+ """
22500
+ # Ghép history thành 1 prompt text (router generic không nhận messages
22501
+ # array trực tiếp)
22502
+ _hist_lines = []
22503
+ for _m in history:
22504
+ _role = _m.get("role", "")
22505
+ _content = _m.get("content", "")
22506
+ if _role == "user":
22507
+ _hist_lines.append(f"User: {_content}")
22508
+ elif _role == "assistant":
22509
+ _hist_lines.append(f"Yui: {_content}")
22510
+ _hist_lines.append(
22511
+ f"User: tiếp tục (phần {part_num}) — in phần code tiếp theo, "
22512
  f"bắt đầu từ điểm vừa dừng, KHÔNG lặp lại code cũ."
22513
+ )
22514
+ prompt = "\n".join(_hist_lines)
22515
 
22516
  try:
22517
+ from yui_model_router import call_task_group as _ctg_st
22518
+ result = await _ctg_st(
22519
+ group="code", prompt=prompt, system=system,
22520
+ max_tokens=2000, timeout_sec=_STITCH_TIMEOUT,
22521
+ )
22522
+ return result or ""
 
 
 
 
 
 
 
22523
  except Exception as e:
22524
  print(f"[STITCH] Part {part_num} lỗi: {e}")
22525
  return ""
 
22711
  "finance": "Bạn là chuyên gia tài chính. Dùng Python để tính lãi suất, đầu tư chính xác.",
22712
  }.get(category, "Dùng Python để tính toán chính xác.")
22713
 
22714
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
22715
+ # giờ dùng nhóm "code" qua yui_model_router.
 
 
 
22716
  code_prompt = (
22717
  f"{category_ctx}\n\n"
22718
  f"Bài toán: {query}\n\n"
 
22726
  )
22727
 
22728
  try:
22729
+ from yui_model_router import call_task_group as _ctg_hp
22730
+ code_raw = await _ctg_hp(
22731
+ group="code", prompt=code_prompt, system="",
22732
+ max_tokens=600, timeout_sec=25,
22733
+ )
22734
+ if not code_raw:
22735
+ return {"solved": False, "result": "", "code": "", "verified": False}
 
 
 
 
 
 
22736
  except Exception as e:
22737
  print(f"[HIGHPREC] AI lỗi: {e}")
22738
  return {"solved": False, "result": "", "code": "", "verified": False}
 
22777
  f"Sửa lại để chạy đúng. Chỉ trả về code."
22778
  )
22779
  try:
22780
+ from yui_model_router import call_task_group as _ctg_hpf
22781
+ code_raw2 = await _ctg_hpf(
22782
+ group="code", prompt=fix_prompt, system="",
22783
+ max_tokens=400, timeout_sec=20,
22784
+ )
22785
+ if code_raw2:
22786
+ m2 = _re_hp.search(r"```(?:python)?\n?(.*?)```", code_raw2, _re_hp.DOTALL)
22787
+ code = m2.group(1).strip() if m2 else code_raw2.strip()
 
 
 
 
 
 
22788
  except Exception:
22789
  pass
22790
  except _sp_hp.TimeoutExpired:
 
23644
  f"Format: ĐỀ: [câu hỏi thực tế ai cũng có thể hỏi]\nTRẢ LỜI: [câu trả lời súc tích, đúng]"
23645
  )
23646
 
23647
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
23648
+ # giờ dùng yui_model_router, chọn nhóm theo skill_type đã phân loại ở
23649
+ # trên (code→"code", creative→"creative", còn lại→"fast_light").
23650
+ _route_group = {"code": "code", "creative": "creative"}.get(skill_type, "fast_light")
23651
 
23652
  try:
23653
+ from yui_model_router import call_task_group as _ctg_ex
23654
+ raw = await _ctg_ex(
23655
+ group=_route_group, prompt=extract_prompt, system="",
23656
+ max_tokens=400, timeout_sec=15,
23657
+ )
23658
+ if not raw:
23659
+ return False
23660
+ raw = raw.strip()
 
 
 
 
23661
  except Exception as e:
23662
  print(f"[EXTRACT] Lỗi: {e}")
23663
  return False
 
23722
  f"Trả về danh sách {num_new} chủ đề, mỗi chủ đề 1 dòng. Không đánh số."
23723
  )
23724
 
23725
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
23726
+ # giờ dùng nhóm "fast_light" qua yui_model_router.
 
 
23727
  try:
23728
+ from yui_model_router import call_task_group as _ctg_dis
23729
+ raw = await _ctg_dis(
23730
+ group="fast_light", prompt=discover_prompt, system="",
23731
+ max_tokens=300, timeout_sec=15,
23732
+ )
23733
+ if not raw:
23734
+ return []
23735
+ raw = raw.strip()
 
 
 
 
23736
  except Exception as e:
23737
  print(f"[DISCOVER] Lỗi: {e}")
23738
  return []
 
23778
  "attempts": int
23779
  }
23780
  """
23781
+ import aiohttp as _ah_qg, os as _os_qg
23782
+ import json as _js_qg
23783
 
23784
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
23785
+ # bỏ guard cb_keys, giờ dùng nhóm "reasoning" qua yui_model_router.
23786
+ # (aiohttp vẫn cần cho nhánh fix-retry qua GitHub models bên dưới.)
 
23787
 
23788
  # Pre-flight CDN map cho context
23789
  _cdn_hint = ""
 
23829
 
23830
  score_raw = ""
23831
  try:
23832
+ from yui_model_router import call_task_group as _ctg_qg
23833
+ score_raw = await _ctg_qg(
23834
+ group="reasoning", prompt=review_prompt, system="",
23835
+ max_tokens=120, timeout_sec=12,
23836
+ )
23837
+ score_raw = (score_raw or "").strip()
 
 
 
 
 
 
 
23838
  except Exception as e:
23839
  print(f"[QUALITY-GATE] Reviewer lỗi: {e}")
23840
  return {"output": current_output, "passed": True, "score": {}, "attempts": attempt}
 
23960
  Tự viết lại system prompt khi phát hiện phàn nàn.
23961
  Chỉ thay đổi phần style, không đụng vào rules cốt lõi.
23962
  """
23963
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
23964
+ # giờ dùng nhóm "reasoning" qua yui_model_router.
 
 
 
 
23965
  evolve_prompt = (
23966
  f"Boss phàn nàn: '{complaint[:100]}'\n\n"
23967
  f"System prompt hiện tại (phần style):\n"
 
23971
  f"Trả về: THAY ĐỔI: [mô tả ngắn 1 câu] | PATCH: [text mới thay thế]"
23972
  )
23973
  try:
23974
+ from yui_model_router import call_task_group as _ctg_agp
23975
+ raw = await _ctg_agp(
23976
+ group="reasoning", prompt=evolve_prompt, system="",
23977
+ max_tokens=200, timeout_sec=10,
23978
+ )
23979
+ if raw and "PATCH:" in raw:
23980
+ import re as _re_agp
23981
+ m = _re_agp.search(r"THAY ĐỔI:\s*(.+?)\s*\|\s*PATCH:\s*(.+)", raw, _re_agp.DOTALL)
23982
+ if m:
23983
+ change_desc = m.group(1).strip()
23984
+ patch_text = m.group(2).strip()[:200]
23985
+ _AGP_VERSION["patches"].append({
23986
+ "complaint": complaint[:50],
23987
+ "change": change_desc,
23988
+ "patch": patch_text,
23989
+ "v": _AGP_VERSION["version"]
23990
+ })
23991
+ _AGP_VERSION["version"] += 1
23992
+ print(f"[AGP] 🧬 v{_AGP_VERSION['version']}: {change_desc[:50]}")
23993
+ # Lưu vào lessons để apply lần sau
23994
+ _lessons_add("agp_prompt_patch", patch_text,
23995
+ confidence=0.6, source="agp")
23996
+ return patch_text
 
 
 
 
 
 
 
23997
  except Exception as _ae:
23998
  print(f"[AGP] {_ae}")
23999
  return ""
 
24011
  Llama 8B làm reviewer (rẻ), không dùng model mạnh
24012
  Trả về: {plan, issues_found, final_plan}
24013
  """
24014
+ import re as _re_db # dùng ở review phía dưới
24015
 
24016
+ # Bước 1: Planner (dùng router — tiết kiệm GitHub quota)
24017
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
24018
+ # giờ dùng nhóm "code" qua yui_model_router.
24019
  plan_prompt = (
24020
  f"Nhiệm vụ: {task[:500]}\n\n"
24021
  "Hãy lập kế hoạch kỹ thuật ngắn gọn (5-8 bước) để thực hiện nhiệm vụ này.\n"
24022
  "Chỉ liệt kê các bước kỹ thuật, không code."
24023
  )
 
 
 
24024
 
24025
  plan_text = ""
24026
  try:
24027
+ from yui_model_router import call_task_group as _ctg_db
24028
+ plan_text = await _ctg_db(
24029
+ group="code", prompt=plan_prompt, system="",
24030
+ max_tokens=400, timeout_sec=15,
24031
+ )
24032
+ if plan_text:
24033
+ print(f"[DEBATE] 📋 Plan ({len(plan_text)} chars)")
 
 
 
 
 
 
 
24034
  except Exception as e:
24035
  print(f"[DEBATE] Plan error: {e}")
24036
  return {"plan": task, "issues_found": [], "final_plan": task}
 
24091
  )
24092
  issues = []
24093
  try:
24094
+ from yui_model_router import call_task_group as _ctg_db2
24095
+ review = await _ctg_db2(
24096
+ group="code", prompt=review_prompt, system="",
24097
+ max_tokens=200, timeout_sec=10,
24098
+ )
24099
+ if review and "OK" not in review.upper():
24100
+ issues = _re_db.findall(r"ISSUE:\s*(.+)", review)
24101
+ print(f"[DEBATE] 🔍 Review: {len(issues)} issues found")
 
 
 
 
 
 
 
 
 
24102
  except Exception as e:
24103
  print(f"[DEBATE] Review error: {e}")
24104
 
 
24161
  async def _arena_self_test(category: str = None) -> dict:
24162
  """
24163
  Tự test 1 câu hỏi → đánh giá → nếu fail tạo bài tập mới lưu vào lessons.
24164
+ Không tốn quota Boss — dùng router free.
24165
  Returns: {category, question, passed, insight}
24166
+ 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
24167
+ giờ dùng nhóm "fast_light" qua yui_model_router.
24168
  """
 
 
 
 
 
 
24169
  # Chọn category và câu hỏi ngẫu nhiên
24170
+ cat = category or random.choice(list(_ARENA_CATEGORIES.keys()))
24171
+ question = random.choice(_ARENA_CATEGORIES[cat])
24172
 
24173
  try:
24174
+ from yui_model_router import call_task_group as _ctg_ar
24175
+ answer = await _ctg_ar(
24176
+ group="fast_light", prompt=question,
24177
+ system="Trả lời ngắn gọn, thật thà. Nếu không biết thì nói không biết.",
24178
+ max_tokens=200, timeout_sec=12,
24179
+ )
24180
+ if not answer:
24181
+ return {"passed": True, "reason": "router_empty"}
 
 
 
 
 
 
 
 
 
24182
  except Exception as _ae:
24183
  return {"passed": True, "reason": str(_ae)[:30]}
24184
 
 
24213
 
24214
  # ════════════════════════════════════════════════════════════════
24215
  # CONTEXT CURATOR v1.0 — Lọc context trước khi gửi AI lớn
24216
+ # Router (đa-provider) đọc và bỏ thông tin rác, chỉ giữ ý chính
24217
  # ════════════════════════════════════════════════════════════════
24218
  async def _curate_context(query: str, raw_context: str,
24219
  max_output: int = 800) -> str:
24220
  """
24221
+ Lọc context bằng router (đa-provider).
24222
  Chỉ giữ thông tin liên quan đến query.
24223
+ 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
24224
+ giờ dùng nhóm "fast_light" qua yui_model_router.
24225
  """
24226
  if len(raw_context) < 1500:
24227
  return raw_context
 
 
 
 
24228
  curator_prompt = (
24229
  f"Query: {query[:150]}\n\nContext thô:\n{raw_context[:3000]}\n\n"
24230
  f"Chỉ giữ lại tối đa {max_output} ký tự thông tin liên quan đến Query. "
24231
  f"Bỏ thông tin thừa. Trả về text đã lọc, không giải thích."
24232
  )
24233
  try:
24234
+ from yui_model_router import call_task_group as _ctg_cc
24235
+ curated = await _ctg_cc(
24236
+ group="fast_light", prompt=curator_prompt, system="",
24237
+ max_tokens=400, timeout_sec=8,
24238
+ )
24239
+ if curated and len(curated) > 50:
24240
+ print(f"[CURATOR] {len(raw_context)} → {len(curated)} chars")
24241
+ return curated
 
 
 
 
 
 
 
24242
  except Exception as _ce:
24243
  print(f"[CURATOR] skip: {_ce}")
24244
  return raw_context[:max_output]
 
24414
  f"Trả về toàn bộ code đã sửa trong ```html ... ```\n\n"
24415
  f"Code hiện tại:\n```html\n{current_html[:3000]}\n```"
24416
  )
24417
+ # Gọi router để sửa nhanh (đa-provider)
24418
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
24419
+ # giờ dùng nhóm "code" qua yui_model_router.
24420
+ try:
24421
+ from yui_model_router import call_task_group as _ctg_vtf
24422
+ raw = await _ctg_vtf(
24423
+ group="code", prompt=fix_prompt, system="",
24424
+ max_tokens=4000, timeout_sec=30,
24425
+ )
24426
+ if raw:
24427
+ import re as _re_fix
24428
+ m = _re_fix.search(r"```html\n?(.*?)```", raw, _re_fix.DOTALL)
24429
+ if m:
24430
+ current_html = m.group(1).strip()
24431
+ print(f"[VISION] ✅ Code đã sửa ({len(current_html)} chars)")
24432
+ except Exception as e:
24433
+ print(f"[VISION] Fix lỗi: {e}")
 
 
 
 
 
 
 
24434
 
24435
  # Trả về bản tốt nhất
24436
  print(f"[VISION] ⚠️ Max retries reached, best score={best_score}")
 
24590
  }
24591
 
24592
  async def _call_cerebras_sp(prompt: str, system: str = "", temp: float = 0.7) -> str:
24593
+ """
24594
+ Gọi AI cho self-play — nhanh nhất.
24595
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras 235B (thử nhiều
24596
+ model theo thứ tự) — Cerebras free tier đóng cửa 17/08/2026. Giờ dùng
24597
+ nhóm "fast_light" qua yui_model_router (đa-provider, tự xoay vòng).
24598
+ Giữ nguyên TÊN HÀM + chữ ký để mọi lời gọi _call_cerebras_sp(...) trong
24599
+ Self-Play không cần sửa gì thêm.
24600
+ """
24601
+ import re as _re_sp_t
24602
+ try:
24603
+ from yui_model_router import call_task_group as _ctg_sp
24604
+ raw = await _ctg_sp(
24605
+ group="fast_light", prompt=prompt, system=system,
24606
+ max_tokens=800, timeout_sec=30,
24607
+ )
24608
+ if raw:
24609
+ # Strip <think>...</think> từ model thinking mode
24610
+ # Không strip → regex ```python``` không bắt code → score=0
24611
+ raw = _re_sp_t.sub(r"<think>.*?</think>", "", raw, flags=_re_sp_t.DOTALL).strip()
24612
+ return raw
24613
+ except Exception as e:
24614
+ print(f"[SELF-PLAY] Router lỗi: {e}")
 
 
 
 
 
 
 
 
 
 
24615
  return ""
24616
 
24617
  async def _evaluate_science(task: str, solution: str) -> dict:
 
31230
  return ""
31231
 
31232
  async def _call_cerebras_debate(prompt: str) -> str:
31233
+ """
31234
+ Gọi AI làm Critic (khác Proposer/Defender để phản biện độc lập).
31235
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras 235B —
31236
+ Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm "reasoning"
31237
+ qua yui_model_router, loại trừ Gemini (Proposer/Defender đã dùng
31238
+ Gemini — Critic cần góc nhìn khác để phản biện có ý nghĩa).
31239
+ """
31240
  try:
31241
+ from yui_model_router import call_task_group as _ctg_dbc
31242
+ raw = await _ctg_dbc(
31243
+ group="reasoning", prompt=prompt, system="",
31244
+ max_tokens=600, timeout_sec=25,
31245
+ exclude_providers=["gemini"],
31246
+ )
31247
+ if raw:
31248
+ import re as _re_db2
31249
+ return _re_db2.sub(r"<think>.*?</think>", "", raw, flags=_re_db2.DOTALL).strip()
 
 
 
 
 
31250
  except Exception as e:
31251
+ print(f"[DEBATE] Router lỗi: {e}")
31252
  return ""
31253
 
31254
  async def _call_cohere_judge(prompt: str) -> str:
 
32065
  """Gọi agent theo tên."""
32066
  try:
32067
  if name in ("cerebras", "deepseek"):
32068
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras —
32069
+ # Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm
32070
+ # "reasoning" qua yui_model_router, loại trừ gemini/cohere
32071
+ # (đã là 2 nhánh tên riêng bên dưới — tránh trùng provider
32072
+ # khi Bayesian Debate gọi nhiều "tên agent" trong cùng 1 lượt).
32073
+ from yui_model_router import call_task_group as _ctg_bdb
32074
+ raw = await _ctg_bdb(
32075
+ group="reasoning", prompt=prompt, system="",
32076
+ max_tokens=max_tok, timeout_sec=25,
32077
+ exclude_providers=["gemini", "cohere"],
32078
+ )
32079
+ if raw:
32080
+ return _re_bdb.sub(r"<think>.*?</think>","",raw,flags=_re_bdb.DOTALL).strip()
32081
+ return ""
 
 
 
 
32082
  elif name == "gemini":
32083
  gkeys = [_os_bdb.environ.get(k) for k in _os_bdb.environ
32084
  if "GEMINI" in k.upper() and _os_bdb.environ.get(k)]
 
32207
 
32208
 
32209
  async def _call_strong_solver(prompt: str, task_type: str = "code") -> str:
32210
+ """
32211
+ Strong solver — mạnh nhất free.
32212
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras 235B — Cerebras
32213
+ free tier đóng cửa 17/08/2026. Giờ dùng nhóm "code"/"reasoning" qua
32214
+ yui_model_router (đa-provider, tự xoay vòng). ĐÂY LÀ CHỖ CUỐI CÙNG
32215
+ trong app.py còn gọi thẳng Cerebras — sau fix này, toàn bộ app.py
32216
+ không còn phụ thuộc trực tiếp vào Cerebras nữa.
32217
+ """
32218
+ import re as _re_ss
32219
  try:
32220
+ from yui_model_router import call_task_group as _ctg_ss
32221
+ group = "code" if task_type in ("code", "debug") else "reasoning"
32222
+ raw = await _ctg_ss(
32223
+ group=group, prompt=prompt, system="",
32224
+ max_tokens=800, timeout_sec=30,
32225
+ )
32226
+ if raw:
32227
+ return _re_ss.sub(r"<think>.*?</think>","",raw,flags=_re_ss.DOTALL).strip()
 
 
 
 
 
32228
  except Exception as e:
32229
+ print(f"[STRONG-SOLVER] Router lỗi: {e}")
32230
  return ""
32231
 
32232
 
ural_gemini_brain.py CHANGED
@@ -598,32 +598,43 @@ def call_mistral(messages: list, system_prompt: str = "") -> Optional[str]:
598
  return None
599
 
600
 
601
- # ── CEREBRAS FALLBACK ────────────────────────────────────────────
602
  def call_cerebras(messages: list, system_prompt: str = "") -> Optional[str]:
603
- """Gọi Cerebras - siêu nhanh, free"""
604
- keys = _load_keys("CEREBRAS_KEY")
605
- if not keys:
606
- return None
 
 
 
 
607
  try:
608
- import openai as _oa
609
- key = random.choice(keys)
610
- client = _oa.OpenAI(api_key=key, base_url="https://api.cerebras.ai/v1")
611
- oai_messages = []
612
- if system_prompt:
613
- oai_messages.append({"role": "system", "content": system_prompt})
614
- oai_messages.extend(messages)
615
- resp = client.chat.completions.create(
616
- model="llama-3.3-70b",
617
- messages=oai_messages,
618
- max_tokens=2048,
619
- temperature=0.3,
620
- )
621
- content = resp.choices[0].message.content
 
 
 
 
 
 
 
622
  if content:
623
- print("[Cerebras] ✅ llama-3.3-70b")
624
  return content.strip()
625
  except Exception as e:
626
- print(f"[Cerebras] Lỗi: {str(e)[:60]}")
627
  return None
628
 
629
 
@@ -682,11 +693,11 @@ def call_free_brain_cascade(
682
  r = call_groq(messages, system_prompt)
683
  if r: return r
684
 
685
- print("[FreeBrain] Groq thất bại → Cerebras...")
686
  r = call_cerebras(messages, system_prompt)
687
  if r: return r
688
 
689
- print("[FreeBrain] Cerebras thất bại → Mistral...")
690
  r = call_mistral(messages, system_prompt)
691
  if r: return r
692
 
 
598
  return None
599
 
600
 
601
+ # ── ROUTER FALLBACK (trước đây gọi thẳng Cerebras) ──────────────
602
  def call_cerebras(messages: list, system_prompt: str = "") -> Optional[str]:
603
+ """
604
+ Gọi model nhẹ/nhanh — siêu nhanh, free.
605
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras llama-3.3-70b —
606
+ Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm "fast_light" qua
607
+ yui_model_router (đa-provider, tự xoay vòng). GIỮ NGUYÊN tên hàm +
608
+ chữ ký để call_free_brain_cascade() và mọi nơi khác gọi call_cerebras(...)
609
+ không cần sửa gì thêm.
610
+ """
611
  try:
612
+ import asyncio
613
+ from yui_model_router import call_task_group
614
+
615
+ # Ghép messages (format OpenAI [{role, content}]) thành 1 prompt text
616
+ hist_lines = []
617
+ for m in messages:
618
+ role = m.get("role", "")
619
+ content = m.get("content", "")
620
+ if role == "user":
621
+ hist_lines.append(f"User: {content}")
622
+ elif role == "assistant":
623
+ hist_lines.append(f"Yui: {content}")
624
+ prompt = "\n".join(hist_lines)
625
+
626
+ async def _go():
627
+ return await call_task_group(
628
+ group="fast_light", prompt=prompt, system=system_prompt or "",
629
+ max_tokens=2048, timeout_sec=20,
630
+ )
631
+
632
+ content = asyncio.run(_go())
633
  if content:
634
+ print("[Router] ✅ fast_light")
635
  return content.strip()
636
  except Exception as e:
637
+ print(f"[Router] Lỗi: {str(e)[:60]}")
638
  return None
639
 
640
 
 
693
  r = call_groq(messages, system_prompt)
694
  if r: return r
695
 
696
+ print("[FreeBrain] Groq thất bại → Router (đa-provider)...")
697
  r = call_cerebras(messages, system_prompt)
698
  if r: return r
699
 
700
+ print("[FreeBrain] Router thất bại → Mistral...")
701
  r = call_mistral(messages, system_prompt)
702
  if r: return r
703
 
ural_module_engine.py CHANGED
@@ -364,26 +364,29 @@ class AICodeWriter:
364
  print(f"Gemini writer loi: {e}"); return None
365
 
366
  def _call_cerebras_writer(self, task):
367
- """Cerebras thay thế Groq — nhanh, free, không cần key Groq."""
 
 
 
 
 
 
 
368
  try:
369
- cb_keys = [os.environ.get(k) for k in os.environ
370
- if "CEREBRAS" in k.upper() and os.environ.get(k)]
371
- if not cb_keys: return None
372
- import requests as _req_cw
373
- resp = _req_cw.post(
374
- "https://api.cerebras.ai/v1/chat/completions",
375
- headers={"Authorization": f"Bearer {random.choice(cb_keys)}",
376
- "Content-Type": "application/json"},
377
- json={"model": "llama3.1-8b",
378
- "messages": [{"role":"system","content":_WRITER_SYSTEM},
379
- {"role":"user","content":f"Viet code Python de: {task}"}],
380
- "max_tokens": 900, "temperature": 0.1},
381
- timeout=12
382
- )
383
- if resp.status_code == 200:
384
- return self._clean(resp.json()["choices"][0]["message"]["content"])
385
  except Exception as e:
386
- print(f"Cerebras writer loi: {e}")
387
  return None
388
 
389
  def _call_hf(self, task):
 
364
  print(f"Gemini writer loi: {e}"); return None
365
 
366
  def _call_cerebras_writer(self, task):
367
+ """
368
+ Router (đa-provider) — thay thế Groq/Cerebras cũ, nhanh, free.
369
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras llama3.1-8b —
370
+ Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm "code" qua
371
+ yui_model_router (đa-provider, tự xoay vòng). Giữ nguyên tên
372
+ method + chữ ký để mọi nơi gọi _call_cerebras_writer(...) không
373
+ cần sửa gì thêm.
374
+ """
375
  try:
376
+ import asyncio
377
+ from yui_model_router import call_task_group
378
+
379
+ async def _go():
380
+ return await call_task_group(
381
+ group="code", prompt=f"Viet code Python de: {task}",
382
+ system=_WRITER_SYSTEM, max_tokens=900, timeout_sec=12,
383
+ )
384
+
385
+ result = asyncio.run(_go())
386
+ if result:
387
+ return self._clean(result)
 
 
 
 
388
  except Exception as e:
389
+ print(f"Router writer loi: {e}")
390
  return None
391
 
392
  def _call_hf(self, task):
ural_self_evolution.py CHANGED
@@ -55,6 +55,11 @@ CODE_BRAIN_FREE_FALLBACKS = [
55
  "note": "FREE, không thẻ, dùng nhiều Google account lấy nhiều key",
56
  },
57
  # LUỒNG 4: CEREBRAS — backup nhanh khi Mistral + Gemini hết
 
 
 
 
 
58
  {
59
  "platform": "cerebras",
60
  "base_url": "https://api.cerebras.ai/v1",
@@ -65,7 +70,7 @@ CODE_BRAIN_FREE_FALLBACKS = [
65
  ],
66
  "daily_limit": 10000,
67
  "signup_url": "https://cloud.cerebras.ai",
68
- "note": "FREE, không thẻ, tốc độ suy luận cực nhanh",
69
  },
70
  ]
71
 
@@ -2506,17 +2511,15 @@ def _ahe_evaluate_component(component_name: str, component_text: str,
2506
  test_cases: list) -> float:
2507
  """
2508
  Đánh giá chất lượng 1 component bằng cách test với các câu mẫu.
2509
- Dùng Cerebras (nhanh, free) — không tốn quota GitHub/Cohere.
2510
  Trả về điểm 0-10.
 
 
 
2511
  """
2512
- import requests as _req_ahe
 
2513
 
2514
- cb_keys = [os.environ.get(k) for k in os.environ if "CEREBRAS" in k.upper()]
2515
- cb_keys = [k for k in cb_keys if k]
2516
- if not cb_keys:
2517
- return AHE_BASELINE_SCORE # Không có key → giữ nguyên điểm
2518
-
2519
- key = random.choice(cb_keys)
2520
  total_score = 0.0
2521
  tested = 0
2522
 
@@ -2530,23 +2533,17 @@ def _ahe_evaluate_component(component_name: str, component_text: str,
2530
  "Trả về CHỈ một số từ 0-10. Không giải thích."
2531
  )
2532
  try:
2533
- r = _req_ahe.post(
2534
- "https://api.cerebras.ai/v1/chat/completions",
2535
- headers={"Authorization": f"Bearer {key}"},
2536
- json={
2537
- "model": "llama3.1-8b",
2538
- "messages": [{"role": "user", "content": eval_prompt}],
2539
- "max_tokens": 5, "temperature": 0.1
2540
- },
2541
- timeout=10
2542
- )
2543
- if r.status_code == 200:
2544
- score_text = r.json().get("choices", [{}])[0].get("message", {}).get("content", "5")
2545
- import re as _re_ahe
2546
- nums = _re_ahe.findall(r"\d+(?:\.\d+)?", score_text)
2547
- if nums:
2548
- total_score += min(10.0, float(nums[0]))
2549
- tested += 1
2550
  except Exception:
2551
  pass
2552
 
 
55
  "note": "FREE, không thẻ, dùng nhiều Google account lấy nhiều key",
56
  },
57
  # LUỒNG 4: CEREBRAS — backup nhanh khi Mistral + Gemini hết
58
+ # ⚠️ (2026-07-17) Cerebras free tier ĐÓNG CỬA 17/08/2026 — bắt buộc thẻ
59
+ # thanh toán từ ngày đó. Giữ khai báo để hunt logic tự phát hiện khi
60
+ # Cerebras ngừng hoạt động (daily_limit/note cập nhật để phản ánh đúng
61
+ # tình trạng); KHÔNG xóa hẳn để tránh phá cấu trúc _FLOWS mà module
62
+ # khác có thể đang dò theo index/platform name.
63
  {
64
  "platform": "cerebras",
65
  "base_url": "https://api.cerebras.ai/v1",
 
70
  ],
71
  "daily_limit": 10000,
72
  "signup_url": "https://cloud.cerebras.ai",
73
+ "note": "⚠️ Free tier đóng cửa 17/08/2026 (cần thẻ) — dùng yui_model_router làm nguồn chính từ nay",
74
  },
75
  ]
76
 
 
2511
  test_cases: list) -> float:
2512
  """
2513
  Đánh giá chất lượng 1 component bằng cách test với các câu mẫu.
2514
+ Dùng router (nhanh, free) — không tốn quota GitHub/Cohere.
2515
  Trả về điểm 0-10.
2516
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras — Cerebras
2517
+ free tier đóng cửa 17/08/2026. Giờ dùng nhóm "fast_light" qua
2518
+ yui_model_router (đa-provider, tự xoay vòng).
2519
  """
2520
+ import asyncio
2521
+ from yui_model_router import call_task_group
2522
 
 
 
 
 
 
 
2523
  total_score = 0.0
2524
  tested = 0
2525
 
 
2533
  "Trả về CHỈ một số từ 0-10. Không giải thích."
2534
  )
2535
  try:
2536
+ async def _go():
2537
+ return await call_task_group(
2538
+ group="fast_light", prompt=eval_prompt, system="",
2539
+ max_tokens=5, timeout_sec=10,
2540
+ )
2541
+ score_text = asyncio.run(_go()) or "5"
2542
+ import re as _re_ahe
2543
+ nums = _re_ahe.findall(r"\d+(?:\.\d+)?", score_text)
2544
+ if nums:
2545
+ total_score += min(10.0, float(nums[0]))
2546
+ tested += 1
 
 
 
 
 
 
2547
  except Exception:
2548
  pass
2549
 
yui_continuous_evolution.py CHANGED
@@ -114,60 +114,28 @@ def _analyze_insights() -> Optional[str]:
114
  return "Topics phổ biến: " + ", ".join(f"{t}({c})" for t, c in top)
115
 
116
  def _call_evolution_brain(prompt: str) -> Optional[str]:
117
- """Gọi free AI để tạo cải tiến. Thử Mistral → Gemini → Cerebras."""
118
- import os
119
- providers = [
120
- {
121
- "name": "mistral",
122
- "url": "https://api.mistral.ai/v1/chat/completions",
123
- "env": "MISTRAL_KEY",
124
- "models": ["mistral-small-latest", "mistral-large-latest"],
125
- },
126
- {
127
- "name": "gemini",
128
- "url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
129
- "env": "GEMINI_API_KEY",
130
- "models": ["gemini-2.0-flash", "gemini-1.5-flash"],
131
- },
132
- {
133
- "name": "cerebras",
134
- "url": "https://api.cerebras.ai/v1/chat/completions",
135
- "env": "CEREBRAS_KEY",
136
- "models": ["llama-3.3-70b"],
137
- },
138
- ]
139
  try:
140
- import urllib.request, ssl
141
- ctx = ssl.create_default_context()
142
- for prov in providers:
143
- # Lấy key (hỗ trợ KEY1, KEY2...)
144
- key = os.environ.get(prov["env"]) or os.environ.get(prov["env"] + "1")
145
- if not key:
146
- continue
147
- for model in prov["models"]:
148
- try:
149
- body = json.dumps({
150
- "model": model,
151
- "messages": [{"role": "user", "content": prompt}],
152
- "max_tokens": 1200,
153
- "temperature": 0.3,
154
- }).encode()
155
- req = urllib.request.Request(
156
- prov["url"],
157
- data=body,
158
- headers={
159
- "Authorization": f"Bearer {key}",
160
- "Content-Type": "application/json",
161
- },
162
- method="POST",
163
- )
164
- with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
165
- data = json.loads(resp.read())
166
- text = data["choices"][0]["message"]["content"]
167
- if text and len(text) > 20:
168
- return text
169
- except Exception:
170
- continue
171
  except Exception as e:
172
  print(f"[EVOLUTION] Brain call lỗi: {e}")
173
  return None
 
114
  return "Topics phổ biến: " + ", ".join(f"{t}({c})" for t, c in top)
115
 
116
  def _call_evolution_brain(prompt: str) -> Optional[str]:
117
+ """
118
+ Gọi free AI để tạo cải tiến.
119
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY cascade tay Mistral→Gemini→
120
+ Cerebras — Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm
121
+ "fast_light" qua yui_model_router (đa-provider, đã có sẵn Mistral +
122
+ Gemini + Cohere + SambaNova, tự xoay vòng — không cần cascade tay
123
+ 3 tầng như cũ nữa). Giữ nguyên tên hàm + chữ ký để mọi nơi gọi
124
+ _call_evolution_brain(...) không cần sửa gì thêm.
125
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  try:
127
+ import asyncio
128
+ from yui_model_router import call_task_group
129
+
130
+ async def _go():
131
+ return await call_task_group(
132
+ group="fast_light", prompt=prompt, system="",
133
+ max_tokens=1200, timeout_sec=30,
134
+ )
135
+
136
+ text = asyncio.run(_go())
137
+ if text and len(text) > 20:
138
+ return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  except Exception as e:
140
  print(f"[EVOLUTION] Brain call lỗi: {e}")
141
  return None
yui_empire_council.py CHANGED
@@ -437,42 +437,28 @@ def _qs_hash(text: str) -> str:
437
  return hashlib.md5(text[:500].encode()).hexdigest()[:12]
438
 
439
  def _qs_call_model(prompt: str) -> Optional[str]:
440
- """Gọi model nhẹ để Quân Sư lập kế hoạch."""
441
- providers = [
442
- # Cerebras: cực nhanh, phù hợp planning
443
- ("cerebras", os.environ.get("CEREBRAS_KEY1") or os.environ.get("CEREBRAS_KEY"),
444
- "https://api.cerebras.ai/v1/chat/completions", "llama3.1-8b"),
445
- # Mistral: nhỏ nhẹ
446
- ("mistral", os.environ.get("MISTRAL_KEY1") or os.environ.get("MISTRAL_KEY"),
447
- "https://api.mistral.ai/v1/chat/completions", "mistral-small-latest"),
448
- # Gemini Flash: đáng tin
449
- ("gemini", os.environ.get("GEMINI_API_KEY1") or os.environ.get("GEMINI_API_KEY"),
450
- "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
451
- "gemini-2.0-flash"),
452
- ]
453
- import urllib.request, ssl
454
- ctx = ssl.create_default_context()
455
- for prov, key, url, model in providers:
456
- if not key:
457
- continue
458
- try:
459
- body = json.dumps({
460
- "model": model,
461
- "messages": [{"role": "user", "content": prompt}],
462
- "max_tokens": 400,
463
- "temperature": 0.1,
464
- }).encode()
465
- req = urllib.request.Request(
466
- url, data=body,
467
- headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
468
- method="POST",
469
  )
470
- with urllib.request.urlopen(req, timeout=_QS_TIMEOUT, context=ctx) as resp:
471
- data = json.loads(resp.read())
472
- return data["choices"][0]["message"]["content"].strip()
473
- except Exception:
474
- continue
475
- return None
476
 
477
  def _qs_build_prompt(user_query: str, task_type: str) -> str:
478
  """Tạo prompt cho Quân Sư phân tích."""
 
437
  return hashlib.md5(text[:500].encode()).hexdigest()[:12]
438
 
439
  def _qs_call_model(prompt: str) -> Optional[str]:
440
+ """
441
+ Gọi model nhẹ để Quân Sư lập kế hoạch.
442
+ 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY cascade tay Cerebras→Mistral→
443
+ Gemini — Cerebras free tier đóng cửa 17/08/2026. Giờ dùng nhóm
444
+ "fast_light" qua yui_model_router (đa-provider, đã có sẵn Mistral +
445
+ Gemini + Cohere + SambaNova, tự xoay vòng — không cần cascade tay
446
+ 3 tầng như cũ nữa). Giữ nguyên chữ ký hàm SYNC.
447
+ """
448
+ try:
449
+ import asyncio
450
+ from yui_model_router import call_task_group
451
+
452
+ async def _go():
453
+ return await call_task_group(
454
+ group="fast_light", prompt=prompt, system="",
455
+ max_tokens=400, timeout_sec=_QS_TIMEOUT,
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  )
457
+
458
+ result = asyncio.run(_go())
459
+ return result.strip() if result else None
460
+ except Exception:
461
+ return None
 
462
 
463
  def _qs_build_prompt(user_query: str, task_type: str) -> str:
464
  """Tạo prompt cho Quân Sư phân tích."""
yui_imagination_engine.py CHANGED
@@ -239,33 +239,21 @@ async def _call_imagination_ai(
239
  except Exception as e:
240
  print(f"[IMAGINE] Gemini lỗi: {e}")
241
 
242
- # 2. Cerebras (nhanh)
243
- cb_keys = [os.environ.get(k) for k in os.environ
244
- if "CEREBRAS" in k.upper() and os.environ.get(k)]
245
- if cb_keys:
246
- try:
247
- import aiohttp
248
- async with aiohttp.ClientSession() as s:
249
- async with s.post(
250
- "https://api.cerebras.ai/v1/chat/completions",
251
- headers={"Authorization": f"Bearer {random.choice(cb_keys)}",
252
- "Content-Type": "application/json"},
253
- json={
254
- "model": "llama-3.3-70b",
255
- "messages": [
256
- {"role": "system", "content": system_prompt},
257
- {"role": "user", "content": user_msg}
258
- ],
259
- "temperature": 0.7,
260
- "max_tokens": 1200,
261
- },
262
- timeout=aiohttp.ClientTimeout(total=20)
263
- ) as r:
264
- if r.status == 200:
265
- d = await r.json()
266
- return d["choices"][0]["message"]["content"].strip()
267
- except Exception as e:
268
- print(f"[IMAGINE] Cerebras lỗi: {e}")
269
 
270
  # 3. Mistral (fallback)
271
  mist_keys = [os.environ.get(k) for k in os.environ
 
239
  except Exception as e:
240
  print(f"[IMAGINE] Gemini lỗi: {e}")
241
 
242
+ # 2. Router (đa-provider, đã loại trừ Gemini vì nhánh 1 đã thử)
243
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY gọi thẳng Cerebras — Cerebras
244
+ # free tier đóng cửa 17/08/2026. Giờ dùng nhóm "creative" qua
245
+ # yui_model_router (đa-provider, tự xoay vòng).
246
+ try:
247
+ from yui_model_router import call_task_group as _ctg_imag
248
+ result = await _ctg_imag(
249
+ group="creative", prompt=user_msg, system=system_prompt,
250
+ max_tokens=1200, timeout_sec=20,
251
+ exclude_providers=["gemini"],
252
+ )
253
+ if result:
254
+ return result.strip()
255
+ except Exception as e:
256
+ print(f"[IMAGINE] Router lỗi: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
  # 3. Mistral (fallback)
259
  mist_keys = [os.environ.get(k) for k in os.environ
yui_new_modules.py CHANGED
@@ -17,15 +17,19 @@ def _conductor_classify(text):
17
  return best if scores[best] > 0 else "simple"
18
 
19
  def _conductor_select_model(task_type, text_len):
 
 
 
 
20
  if text_len < 30:
21
- return {"provider": "cerebras", "model": "llama3.1-8b", "temp": 0.7, "max_tokens": 800, "reason": "short_fast"}
22
  routing = {
23
- "code": {"provider": "cerebras", "model": "llama-3.3-70b", "temp": 0.1, "max_tokens": 2000, "reason": "code_accurate"},
24
- "math": {"provider": "cerebras", "model": "llama-3.3-70b", "temp": 0.0, "max_tokens": 1500, "reason": "math_precise"},
25
- "creative": {"provider": "gemini", "model": "gemini-2.0-flash", "temp": 0.9, "max_tokens": 2000, "reason": "creative_gemini"},
26
- "research": {"provider": "mistral", "model": "mistral-large-latest","temp": 0.3, "max_tokens": 2000, "reason": "research_mistral"},
27
- "reasoning": {"provider": "cerebras", "model": "llama-3.3-70b", "temp": 0.2, "max_tokens": 2000, "reason": "reasoning_strong"},
28
- "simple": {"provider": "cerebras", "model": "llama3.1-8b", "temp": 0.7, "max_tokens": 1000, "reason": "simple_fast"},
29
  }
30
  return routing.get(task_type, routing["simple"])
31
 
@@ -34,28 +38,26 @@ async def conductor_route(text, history=None):
34
  return {"reply": None, "model_used": "disabled", "task_type": "simple"}
35
  task_type = _conductor_classify(text)
36
  cfg = _conductor_select_model(task_type, len(text))
37
- provider, model_name = cfg["provider"], cfg["model"]
 
38
  print(f"[CONDUCTOR] Task={task_type} -> {provider}/{model_name}")
39
  reply = None
40
  try:
41
- if provider == "cerebras":
42
- cb_keys = [os.environ.get(k) for k in os.environ if "CEREBRAS" in k.upper() and os.environ.get(k)]
43
- if cb_keys:
44
- import aiohttp as _ah_c, random as _rd_c
45
- msgs = []
46
- if history:
47
- for h in history[-4:]:
48
- if isinstance(h, (list,tuple)) and len(h)>=2:
49
- msgs += [{"role":"user","content":str(h[0])},{"role":"assistant","content":str(h[1])}]
50
- msgs.append({"role":"user","content":text})
51
- async with _ah_c.ClientSession() as s:
52
- async with s.post("https://api.cerebras.ai/v1/chat/completions",
53
- headers={"Authorization":f"Bearer {_rd_c.choice(cb_keys)}","Content-Type":"application/json"},
54
- json={"model":model_name,"messages":msgs,"temperature":cfg["temp"],"max_tokens":cfg["max_tokens"]},
55
- timeout=_ah_c.ClientTimeout(total=30)) as r:
56
- if r.status==200:
57
- d=await r.json()
58
- reply=d.get("choices",[{}])[0].get("message",{}).get("content","")
59
  elif provider == "mistral":
60
  task_map={"research":"knowledge","reasoning":"hard","code":"code","math":"math","creative":"creative","simple":"chat"}
61
  try:
@@ -74,7 +76,7 @@ async def conductor_route(text, history=None):
74
  return {"reply": None, "model_used": "fallback", "task_type": task_type}
75
  return {"reply": reply.strip(), "model_used": f"{provider}/{model_name}", "task_type": task_type}
76
 
77
- print("[CONDUCTOR] Router v1.0 - code->Cerebras | research->Mistral | creative->Gemini")
78
 
79
 
80
  # ════ MODULE: AUTO PROMPT OPTIMIZER v1.0 ════
@@ -86,26 +88,24 @@ _APO_REWRITE_SYSTEM = "You are a prompt optimization expert. Rewrite the user qu
86
  async def _apo_rewrite_prompt(text, task_type):
87
  if not _APO_ENABLED or len(text) < _APO_MIN_LEN or task_type not in _APO_TASK_TYPES:
88
  return text
89
- cb_keys = [os.environ.get(k) for k in os.environ if "CEREBRAS" in k.upper() and os.environ.get(k)]
90
- if not cb_keys: return text
91
  try:
92
- import aiohttp as _ah_apo, random as _rd_apo
93
- async with _ah_apo.ClientSession() as s:
94
- async with s.post("https://api.cerebras.ai/v1/chat/completions",
95
- headers={"Authorization":f"Bearer {_rd_apo.choice(cb_keys)}","Content-Type":"application/json"},
96
- json={"model":"llama3.1-8b","messages":[{"role":"system","content":_APO_REWRITE_SYSTEM},{"role":"user","content":"Rewrite: "+text}],"temperature":0.1,"max_tokens":300},
97
- timeout=_ah_apo.ClientTimeout(total=6)) as r:
98
- if r.status==200:
99
- d=await r.json()
100
- rw=d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
101
- if rw and len(rw)>10 and rw!=text:
102
- print(f"[APO] Rewritten: {text[:30]}... -> {rw[:30]}...")
103
- return rw
104
  except Exception:
105
  pass
106
  return text
107
 
108
- print("[APO] Auto Prompt Optimizer v1.0 - Cerebras-powered")
109
 
110
 
111
  # ════ MODULE: TABULAR AI ANALYZER v1.0 ════
@@ -133,24 +133,23 @@ async def tabular_analyze(data_text, question=""):
133
  _q = question or "Phan tich tong quan: shape, thong ke mo ta, insights"
134
  user_prompt = "Du lieu:" + chr(10) + data_text[:3000] + chr(10) + "Cau hoi: " + _q + chr(10) + "Bien DATA_STRING da chua du lieu. Dung pd.read_csv(io.StringIO(DATA_STRING)) de doc."
135
  code = ""
136
- cb_keys = [os.environ.get(k) for k in os.environ if "CEREBRAS" in k.upper() and os.environ.get(k)]
137
  mist_keys = [os.environ.get(k) for k in os.environ if k.startswith("MISTRAL_KEY") and os.environ.get(k)]
138
- if cb_keys:
139
- try:
140
- import aiohttp as _ah_tab, random as _rd_tab
141
- async with _ah_tab.ClientSession() as s:
142
- async with s.post("https://api.cerebras.ai/v1/chat/completions",
143
- headers={"Authorization":f"Bearer {_rd_tab.choice(cb_keys)}","Content-Type":"application/json"},
144
- json={"model":"llama-3.3-70b","messages":[{"role":"system","content":_TABULAR_SYSTEM_PROMPT},{"role":"user","content":user_prompt}],"temperature":0.0,"max_tokens":800},
145
- timeout=_ah_tab.ClientTimeout(total=15)) as r:
146
- if r.status==200:
147
- d=await r.json()
148
- code=d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
149
- if code.startswith("```"):
150
- code=code.split("```")[1]
151
- if code.startswith("python"): code=code[6:]
152
- code=code.strip()
153
- except Exception as _te: print(f"[TABULAR] Cerebras loi: {_te}")
154
  if not code and mist_keys:
155
  try:
156
  mc = await _call_mistral_api(prompt=user_prompt,system=_TABULAR_SYSTEM_PROMPT,task_type="code",max_tok=800)
@@ -283,19 +282,20 @@ async def task_orchestrate_v2(task, user_name="user"):
283
  except Exception: steps_desc = ["Phan tich yeu cau","Thuc hien","Tong ket"]
284
  worker_output = ""; approved = False; verify_score = 0
285
  for round_n in range(1, 3):
286
- cb_keys = [os.environ.get(k) for k in os.environ if "CEREBRAS" in k.upper() and os.environ.get(k)]
287
- if cb_keys:
288
- try:
289
- import aiohttp as _ah_w, random as _rd_w
290
- _nl = chr(10)
291
- ctx = "Task: " + task + _nl + _nl + "Plan:" + _nl + _nl.join(steps_desc) + (_nl + _nl + "Verifier feedback: " + worker_output[:200] if round_n > 1 and worker_output else "")
292
- async with _ah_w.ClientSession() as s:
293
- async with s.post("https://api.cerebras.ai/v1/chat/completions",
294
- headers={"Authorization":f"Bearer {_rd_w.choice(cb_keys)}","Content-Type":"application/json"},
295
- json={"model":"llama-3.3-70b","messages":[{"role":"system","content":_WORKER_SYS},{"role":"user","content":ctx}],"temperature":0.3,"max_tokens":1500},
296
- timeout=_ah_w.ClientTimeout(total=30)) as r:
297
- if r.status==200: d=await r.json(); worker_output=d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
298
- except Exception as _we: print(f"[ORCH-V2] Worker loi: {_we}")
 
299
  if not worker_output: break
300
  verify_result = {"approved": True, "score": 8, "issues": []}
301
  try:
@@ -316,7 +316,7 @@ async def task_orchestrate_v2(task, user_name="user"):
316
  if not approved: reply += chr(10)*2 + "*(Chua duoc Verifier xac nhan hoan toan, score=" + str(verify_score) + "/10)*"
317
  return {"reply": reply, "steps": steps_desc, "approved": approved, "rounds": 2, "score": verify_score}
318
 
319
- print("[ORCH-V2] Task Orchestrator v2.0 - Planner(Mistral)+Worker(Cerebras)+Verifier(Gemini)")
320
 
321
 
322
  # ════ MODULE: AUTO DEVTOOLS v1.0 ════
@@ -355,18 +355,18 @@ async def devtools_analyze_url(url, timeout_ms=15000):
355
  if network_errors: err_lines.append(f"Network Errors ({len(network_errors)}):"); [err_lines.append(f" - {e.get('status','FAIL')}: {e['url'][:150]}") for e in network_errors[:5]]
356
  analysis=""
357
  if err_lines:
358
- cb_dt=[os.environ.get(k) for k in os.environ if "CEREBRAS" in k.upper() and os.environ.get(k)]
359
- if cb_dt:
360
- try:
361
- import aiohttp as _ah_dt, random as _rd_dt
362
- _p="URL: "+url+chr(10)*2+"Loi:"+chr(10)+chr(10).join(err_lines)+chr(10)*2+"Phan tich loi va de xuat fix ngan gon."
363
- async with _ah_dt.ClientSession() as s:
364
- async with s.post("https://api.cerebras.ai/v1/chat/completions",
365
- headers={"Authorization":f"Bearer {_rd_dt.choice(cb_dt)}","Content-Type":"application/json"},
366
- json={"model":"llama-3.3-70b","messages":[{"role":"user","content":_p}],"temperature":0.1,"max_tokens":800},
367
- timeout=_ah_dt.ClientTimeout(total=20)) as r:
368
- if r.status==200: d=await r.json(); analysis=d.get("choices",[{}])[0].get("message",{}).get("content","").strip()
369
- except Exception as _de: analysis=f"(Khong the phan tich: {_de})"
370
  if not err_lines: analysis="Khong phat hien loi! Trang web hoat dong binh thuong."
371
  return {"ok":True,"url":url,"console_errors":console_errors[:10],"network_errors":network_errors[:10],"js_errors":js_errors[:10],"screenshot_b64":screenshot_b64,"error_summary":chr(10).join(err_lines),"analysis":analysis,"total_errors":len(js_errors)+len(console_errors)+len(network_errors)}
372
 
 
17
  return best if scores[best] > 0 else "simple"
18
 
19
  def _conductor_select_model(task_type, text_len):
20
+ # 🔄 MIGRATION (2026-07-17): TRƯỚC ĐÂY code/math/reasoning/simple đều
21
+ # khóa cứng provider="cerebras" — Cerebras free tier đóng cửa
22
+ # 17/08/2026. Giờ các nhánh này dùng "router" (yui_model_router đa-
23
+ # provider) thay vì tên hãng cụ thể — xem conductor_route() bên dưới.
24
  if text_len < 30:
25
+ return {"provider": "router", "group": "fast_light", "temp": 0.7, "max_tokens": 800, "reason": "short_fast"}
26
  routing = {
27
+ "code": {"provider": "router", "group": "code", "temp": 0.1, "max_tokens": 2000, "reason": "code_accurate"},
28
+ "math": {"provider": "router", "group": "reasoning", "temp": 0.0, "max_tokens": 1500, "reason": "math_precise"},
29
+ "creative": {"provider": "gemini", "model": "gemini-2.0-flash", "temp": 0.9, "max_tokens": 2000, "reason": "creative_gemini"},
30
+ "research": {"provider": "mistral", "model": "mistral-large-latest", "temp": 0.3, "max_tokens": 2000, "reason": "research_mistral"},
31
+ "reasoning": {"provider": "router", "group": "reasoning", "temp": 0.2, "max_tokens": 2000, "reason": "reasoning_strong"},
32
+ "simple": {"provider": "router", "group": "fast_light","temp": 0.7, "max_tokens": 1000, "reason": "simple_fast"},
33
  }
34
  return routing.get(task_type, routing["simple"])
35
 
 
38
  return {"reply": None, "model_used": "disabled", "task_type": "simple"}
39
  task_type = _conductor_classify(text)
40
  cfg = _conductor_select_model(task_type, len(text))
41
+ provider = cfg["provider"]
42
+ model_name = cfg.get("model") or cfg.get("group", "")
43
  print(f"[CONDUCTOR] Task={task_type} -> {provider}/{model_name}")
44
  reply = None
45
  try:
46
+ if provider == "router":
47
+ # 🔄 MIGRATION (2026-07-17): Thay cascade Cerebras cũ bằng
48
+ # yui_model_router (đa-provider, tự xoay vòng).
49
+ from yui_model_router import call_task_group as _ctg_cond
50
+ hist_lines = []
51
+ if history:
52
+ for h in history[-4:]:
53
+ if isinstance(h, (list, tuple)) and len(h) >= 2:
54
+ hist_lines.append(f"User: {h[0]}")
55
+ hist_lines.append(f"Yui: {h[1]}")
56
+ full_prompt = ("\n".join(hist_lines) + "\n\n" if hist_lines else "") + f"User: {text}"
57
+ reply = await _ctg_cond(
58
+ group=cfg["group"], prompt=full_prompt, system="",
59
+ max_tokens=cfg["max_tokens"], timeout_sec=30,
60
+ )
 
 
 
61
  elif provider == "mistral":
62
  task_map={"research":"knowledge","reasoning":"hard","code":"code","math":"math","creative":"creative","simple":"chat"}
63
  try:
 
76
  return {"reply": None, "model_used": "fallback", "task_type": task_type}
77
  return {"reply": reply.strip(), "model_used": f"{provider}/{model_name}", "task_type": task_type}
78
 
79
+ print("[CONDUCTOR] Router v1.0 - code/math/reasoning/simple->yui_model_router | research->Mistral | creative->Gemini")
80
 
81
 
82
  # ════ MODULE: AUTO PROMPT OPTIMIZER v1.0 ════
 
88
  async def _apo_rewrite_prompt(text, task_type):
89
  if not _APO_ENABLED or len(text) < _APO_MIN_LEN or task_type not in _APO_TASK_TYPES:
90
  return text
91
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
92
+ # giờ dùng nhóm "fast_light" qua yui_model_router.
93
  try:
94
+ from yui_model_router import call_task_group as _ctg_apo
95
+ rw = await _ctg_apo(
96
+ group="fast_light", prompt="Rewrite: " + text, system=_APO_REWRITE_SYSTEM,
97
+ max_tokens=300, timeout_sec=6,
98
+ )
99
+ if rw:
100
+ rw = rw.strip()
101
+ if rw and len(rw) > 10 and rw != text:
102
+ print(f"[APO] Rewritten: {text[:30]}... -> {rw[:30]}...")
103
+ return rw
 
 
104
  except Exception:
105
  pass
106
  return text
107
 
108
+ print("[APO] Auto Prompt Optimizer v1.0 - Router-powered (đa-provider)")
109
 
110
 
111
  # ════ MODULE: TABULAR AI ANALYZER v1.0 ════
 
133
  _q = question or "Phan tich tong quan: shape, thong ke mo ta, insights"
134
  user_prompt = "Du lieu:" + chr(10) + data_text[:3000] + chr(10) + "Cau hoi: " + _q + chr(10) + "Bien DATA_STRING da chua du lieu. Dung pd.read_csv(io.StringIO(DATA_STRING)) de doc."
135
  code = ""
 
136
  mist_keys = [os.environ.get(k) for k in os.environ if k.startswith("MISTRAL_KEY") and os.environ.get(k)]
137
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
138
+ # giờ dùng nhóm "code" qua yui_model_router.
139
+ try:
140
+ from yui_model_router import call_task_group as _ctg_tab
141
+ raw_code = await _ctg_tab(
142
+ group="code", prompt=user_prompt, system=_TABULAR_SYSTEM_PROMPT,
143
+ max_tokens=800, timeout_sec=15,
144
+ )
145
+ if raw_code:
146
+ code = raw_code.strip()
147
+ if code.startswith("```"):
148
+ code = code.split("```")[1]
149
+ if code.startswith("python"): code = code[6:]
150
+ code = code.strip()
151
+ except Exception as _te:
152
+ print(f"[TABULAR] Router loi: {_te}")
153
  if not code and mist_keys:
154
  try:
155
  mc = await _call_mistral_api(prompt=user_prompt,system=_TABULAR_SYSTEM_PROMPT,task_type="code",max_tok=800)
 
282
  except Exception: steps_desc = ["Phan tich yeu cau","Thuc hien","Tong ket"]
283
  worker_output = ""; approved = False; verify_score = 0
284
  for round_n in range(1, 3):
285
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
286
+ # giờ dùng nhóm "code" qua yui_model_router.
287
+ try:
288
+ from yui_model_router import call_task_group as _ctg_orch
289
+ _nl = chr(10)
290
+ ctx = "Task: " + task + _nl + _nl + "Plan:" + _nl + _nl.join(steps_desc) + (_nl + _nl + "Verifier feedback: " + worker_output[:200] if round_n > 1 and worker_output else "")
291
+ _wo = await _ctg_orch(
292
+ group="code", prompt=ctx, system=_WORKER_SYS,
293
+ max_tokens=1500, timeout_sec=30,
294
+ )
295
+ if _wo:
296
+ worker_output = _wo.strip()
297
+ except Exception as _we:
298
+ print(f"[ORCH-V2] Worker loi: {_we}")
299
  if not worker_output: break
300
  verify_result = {"approved": True, "score": 8, "issues": []}
301
  try:
 
316
  if not approved: reply += chr(10)*2 + "*(Chua duoc Verifier xac nhan hoan toan, score=" + str(verify_score) + "/10)*"
317
  return {"reply": reply, "steps": steps_desc, "approved": approved, "rounds": 2, "score": verify_score}
318
 
319
+ print("[ORCH-V2] Task Orchestrator v2.0 - Planner(Mistral)+Worker(Router)+Verifier(Gemini)")
320
 
321
 
322
  # ════ MODULE: AUTO DEVTOOLS v1.0 ════
 
355
  if network_errors: err_lines.append(f"Network Errors ({len(network_errors)}):"); [err_lines.append(f" - {e.get('status','FAIL')}: {e['url'][:150]}") for e in network_errors[:5]]
356
  analysis=""
357
  if err_lines:
358
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
359
+ # giờ dùng nhóm "code" qua yui_model_router.
360
+ try:
361
+ from yui_model_router import call_task_group as _ctg_dt
362
+ _p="URL: "+url+chr(10)*2+"Loi:"+chr(10)+chr(10).join(err_lines)+chr(10)*2+"Phan tich loi va de xuat fix ngan gon."
363
+ _an = await _ctg_dt(
364
+ group="code", prompt=_p, system="",
365
+ max_tokens=800, timeout_sec=20,
366
+ )
367
+ analysis = _an.strip() if _an else ""
368
+ except Exception as _de:
369
+ analysis=f"(Khong the phan tich: {_de})"
370
  if not err_lines: analysis="Khong phat hien loi! Trang web hoat dong binh thuong."
371
  return {"ok":True,"url":url,"console_errors":console_errors[:10],"network_errors":network_errors[:10],"js_errors":js_errors[:10],"screenshot_b64":screenshot_b64,"error_summary":chr(10).join(err_lines),"analysis":analysis,"total_errors":len(js_errors)+len(console_errors)+len(network_errors)}
372
 
yui_skill_library.py CHANGED
@@ -620,11 +620,8 @@ def _call_llm_creative_merge(task_desc: str, candidates: List[Skill]) -> Optiona
620
  Trả về code mới nếu LLM đề xuất được, hoặc None nếu LLM thấy không
621
  ghép được / không liên quan.
622
  """
623
- cb_keys = [os.environ.get(k) for k in os.environ
624
- if "CEREBRAS" in k.upper() and os.environ.get(k)]
625
- if not cb_keys:
626
- return None
627
-
628
  skills_txt = "\n\n".join(
629
  f"# Skill {i+1}: {s.task_desc}\n{s.code}" for i, s in enumerate(candidates)
630
  )
@@ -642,19 +639,19 @@ def _call_llm_creative_merge(task_desc: str, candidates: List[Skill]) -> Optiona
642
  "trả về CHỈ chữ NO."
643
  )
644
  try:
645
- import requests
646
- resp = requests.post(
647
- "https://api.cerebras.ai/v1/chat/completions",
648
- headers={"Authorization": f"Bearer {random.choice(cb_keys)}",
649
- "Content-Type": "application/json"},
650
- json={"model": _CREATIVE_MODEL,
651
- "messages": [{"role": "user", "content": prompt}],
652
- "temperature": 0.3, "max_tokens": 500},
653
- timeout=15,
654
- )
655
- if resp.status_code != 200:
656
  return None
657
- content = resp.json()["choices"][0]["message"]["content"].strip()
658
  if content.upper().strip() == "NO" or len(content) < 10:
659
  return None
660
  if "```" in content:
 
620
  Trả về code mới nếu LLM đề xuất được, hoặc None nếu LLM thấy không
621
  ghép được / không liên quan.
622
  """
623
+ # 🔄 MIGRATION (2026-07-17): Cerebras free tier đóng cửa 17/08/2026 —
624
+ # giờ dùng nhóm "code" qua yui_model_router.
 
 
 
625
  skills_txt = "\n\n".join(
626
  f"# Skill {i+1}: {s.task_desc}\n{s.code}" for i, s in enumerate(candidates)
627
  )
 
639
  "trả về CHỈ chữ NO."
640
  )
641
  try:
642
+ import asyncio
643
+ from yui_model_router import call_task_group
644
+
645
+ async def _go():
646
+ return await call_task_group(
647
+ group="code", prompt=prompt, system="",
648
+ max_tokens=500, timeout_sec=15,
649
+ )
650
+
651
+ content = asyncio.run(_go())
652
+ if not content:
653
  return None
654
+ content = content.strip()
655
  if content.upper().strip() == "NO" or len(content) < 10:
656
  return None
657
  if "```" in content: