Spaces:
Paused
Paused
Upload 9 files
Browse files- app.py +493 -771
- ural_gemini_brain.py +34 -23
- ural_module_engine.py +21 -18
- ural_self_evolution.py +23 -26
- yui_continuous_evolution.py +21 -53
- yui_empire_council.py +21 -35
- yui_imagination_engine.py +15 -27
- yui_new_modules.py +85 -85
- yui_skill_library.py +14 -17
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 |
-
# ──
|
| 10820 |
-
#
|
|
|
|
|
|
|
| 10821 |
_cb_success = False
|
| 10822 |
try:
|
| 10823 |
-
|
| 10824 |
-
|
| 10825 |
-
|
| 10826 |
-
|
| 10827 |
-
|
| 10828 |
-
|
| 10829 |
-
|
| 10830 |
-
|
| 10831 |
-
|
| 10832 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10833 |
)
|
| 10834 |
-
|
| 10835 |
-
|
| 10836 |
-
|
| 10837 |
-
|
| 10838 |
-
|
| 10839 |
-
|
| 10840 |
-
|
| 10841 |
-
|
| 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 |
-
# ──
|
| 11014 |
-
#
|
| 11015 |
-
#
|
| 11016 |
-
|
| 11017 |
-
|
| 11018 |
-
|
| 11019 |
-
|
| 11020 |
-
|
| 11021 |
-
|
| 11022 |
-
|
| 11023 |
-
|
| 11024 |
-
|
| 11025 |
-
|
| 11026 |
-
|
| 11027 |
-
|
| 11028 |
-
|
| 11029 |
-
|
| 11030 |
-
|
| 11031 |
-
|
| 11032 |
-
|
| 11033 |
-
|
| 11034 |
-
|
| 11035 |
-
|
| 11036 |
-
|
| 11037 |
-
|
| 11038 |
-
|
| 11039 |
-
|
| 11040 |
-
|
| 11041 |
-
|
| 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 |
-
|
| 11146 |
-
|
| 11147 |
-
|
| 11148 |
-
|
| 11149 |
-
|
| 11150 |
-
|
| 11151 |
-
|
| 11152 |
-
|
| 11153 |
-
|
| 11154 |
-
|
| 11155 |
-
|
| 11156 |
-
|
| 11157 |
-
|
| 11158 |
-
|
| 11159 |
-
|
| 11160 |
-
|
| 11161 |
-
|
| 11162 |
-
|
| 11163 |
-
|
| 11164 |
-
|
| 11165 |
-
|
| 11166 |
-
|
| 11167 |
-
|
| 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 |
-
|
| 11176 |
-
|
| 11177 |
-
|
| 11178 |
-
|
| 11179 |
-
|
| 11180 |
-
|
| 11181 |
-
|
| 11182 |
-
|
| 11183 |
-
|
| 11184 |
-
|
| 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 |
-
|
| 12992 |
-
|
| 12993 |
-
|
| 12994 |
-
|
|
|
|
| 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 |
-
|
| 13000 |
-
|
| 13001 |
-
|
| 13002 |
-
"
|
| 13003 |
-
|
| 13004 |
-
|
| 13005 |
-
|
| 13006 |
-
|
| 13007 |
-
|
| 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
|
| 17217 |
-
|
| 17218 |
-
|
| 17219 |
-
|
| 17220 |
-
|
| 17221 |
-
|
| 17222 |
-
|
| 17223 |
-
|
| 17224 |
-
|
| 17225 |
-
|
| 17226 |
-
|
| 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]
|
| 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.
|
|
|
|
|
|
|
| 17398 |
if not result:
|
| 17399 |
try:
|
| 17400 |
-
|
| 17401 |
-
|
| 17402 |
-
|
| 17403 |
-
|
| 17404 |
-
|
| 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]
|
| 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 |
-
|
| 18517 |
-
|
| 18518 |
-
|
| 18519 |
-
|
| 18520 |
-
|
| 18521 |
-
|
| 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 |
-
|
| 18540 |
-
|
| 18541 |
-
|
| 18542 |
-
|
| 18543 |
-
|
| 18544 |
-
|
| 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 |
-
|
| 18577 |
-
|
| 18578 |
-
|
| 18579 |
-
|
| 18580 |
-
|
| 18581 |
-
|
| 18582 |
-
|
| 18583 |
-
|
| 18584 |
-
|
| 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("
|
| 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 |
-
"""
|
| 19008 |
-
|
| 19009 |
-
|
| 19010 |
-
|
| 19011 |
-
|
| 19012 |
-
|
| 19013 |
-
|
| 19014 |
-
|
| 19015 |
try:
|
| 19016 |
-
|
| 19017 |
-
|
| 19018 |
-
|
| 19019 |
-
|
| 19020 |
-
|
| 19021 |
-
|
| 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 |
-
"""
|
| 19647 |
-
|
| 19648 |
-
|
| 19649 |
-
|
| 19650 |
-
|
| 19651 |
-
|
| 19652 |
-
|
| 19653 |
-
|
| 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 |
-
|
| 19676 |
-
|
| 19677 |
-
|
| 19678 |
-
|
| 19679 |
-
|
| 19680 |
-
|
| 19681 |
-
|
| 19682 |
-
|
| 19683 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19684 |
except Exception as e:
|
| 19685 |
-
print(f"[MRAC/{role}]
|
| 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:
|
| 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ử
|
| 20574 |
-
|
| 20575 |
-
|
| 20576 |
-
|
| 20577 |
-
|
| 20578 |
-
|
| 20579 |
-
|
| 20580 |
-
|
| 20581 |
-
|
| 20582 |
-
|
| 20583 |
-
|
| 20584 |
-
|
| 20585 |
-
|
| 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 |
-
|
| 21491 |
-
|
| 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 |
-
|
| 21507 |
-
|
| 21508 |
-
|
| 21509 |
-
|
| 21510 |
-
|
| 21511 |
-
|
| 21512 |
-
|
| 21513 |
-
|
| 21514 |
-
|
| 21515 |
-
|
| 21516 |
-
|
| 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 |
-
"""
|
| 22160 |
-
|
| 22161 |
-
|
| 22162 |
-
|
| 22163 |
-
|
| 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 |
-
|
| 22175 |
-
|
| 22176 |
-
|
| 22177 |
-
|
| 22178 |
-
|
| 22179 |
-
|
| 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 |
-
|
| 22277 |
-
|
| 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 |
-
|
| 22289 |
-
|
| 22290 |
-
|
| 22291 |
-
|
| 22292 |
-
|
| 22293 |
-
|
| 22294 |
-
|
| 22295 |
-
|
| 22296 |
-
|
| 22297 |
-
|
| 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 |
-
#
|
| 22514 |
-
|
| 22515 |
-
|
| 22516 |
-
|
| 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 |
-
|
| 22539 |
-
|
| 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 |
-
#
|
| 22619 |
-
|
| 22620 |
-
|
| 22621 |
-
|
| 22622 |
-
|
| 22623 |
-
|
| 22624 |
-
|
| 22625 |
-
if
|
| 22626 |
-
|
| 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] ✅
|
| 22636 |
return expanded
|
| 22637 |
-
print(f"[META] ⚠️
|
|
|
|
|
|
|
| 22638 |
|
| 22639 |
-
print(f"[META] ❌
|
| 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 |
-
"""
|
| 22668 |
-
|
| 22669 |
-
|
| 22670 |
-
|
| 22671 |
-
|
| 22672 |
-
|
| 22673 |
-
#
|
| 22674 |
-
|
| 22675 |
-
|
| 22676 |
-
|
| 22677 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 22683 |
-
|
| 22684 |
-
|
| 22685 |
-
|
| 22686 |
-
|
| 22687 |
-
|
| 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 |
-
|
| 22887 |
-
|
| 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 |
-
|
| 22905 |
-
|
| 22906 |
-
|
| 22907 |
-
|
| 22908 |
-
|
| 22909 |
-
|
| 22910 |
-
|
| 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 |
-
|
| 22962 |
-
|
| 22963 |
-
|
| 22964 |
-
|
| 22965 |
-
|
| 22966 |
-
|
| 22967 |
-
|
| 22968 |
-
|
| 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 |
-
|
| 23835 |
-
|
| 23836 |
-
|
|
|
|
| 23837 |
|
| 23838 |
try:
|
| 23839 |
-
|
| 23840 |
-
|
| 23841 |
-
|
| 23842 |
-
|
| 23843 |
-
|
| 23844 |
-
|
| 23845 |
-
|
| 23846 |
-
|
| 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 |
-
|
| 23916 |
-
|
| 23917 |
-
key = _os_dis.environ.get(_rd_dis.choice(cb_keys), "")
|
| 23918 |
-
|
| 23919 |
try:
|
| 23920 |
-
|
| 23921 |
-
|
| 23922 |
-
|
| 23923 |
-
|
| 23924 |
-
|
| 23925 |
-
|
| 23926 |
-
|
| 23927 |
-
|
| 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
|
|
|
|
| 23978 |
|
| 23979 |
-
|
| 23980 |
-
|
| 23981 |
-
|
| 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 |
-
|
| 24029 |
-
|
| 24030 |
-
|
| 24031 |
-
|
| 24032 |
-
|
| 24033 |
-
|
| 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 |
-
|
| 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 |
-
|
| 24182 |
-
|
| 24183 |
-
|
| 24184 |
-
|
| 24185 |
-
|
| 24186 |
-
|
| 24187 |
-
|
| 24188 |
-
|
| 24189 |
-
|
| 24190 |
-
|
| 24191 |
-
|
| 24192 |
-
|
| 24193 |
-
|
| 24194 |
-
|
| 24195 |
-
|
| 24196 |
-
|
| 24197 |
-
|
| 24198 |
-
|
| 24199 |
-
|
| 24200 |
-
|
| 24201 |
-
|
| 24202 |
-
|
| 24203 |
-
|
| 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
|
| 24229 |
|
| 24230 |
-
# Bước 1: Planner (dùng
|
|
|
|
|
|
|
| 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 |
-
|
| 24243 |
-
|
| 24244 |
-
|
| 24245 |
-
|
| 24246 |
-
|
| 24247 |
-
|
| 24248 |
-
|
| 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 |
-
|
| 24317 |
-
|
| 24318 |
-
|
| 24319 |
-
|
| 24320 |
-
|
| 24321 |
-
|
| 24322 |
-
|
| 24323 |
-
|
| 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
|
| 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
|
| 24406 |
-
question =
|
| 24407 |
|
| 24408 |
try:
|
| 24409 |
-
|
| 24410 |
-
|
| 24411 |
-
|
| 24412 |
-
|
| 24413 |
-
|
| 24414 |
-
|
| 24415 |
-
|
| 24416 |
-
|
| 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 |
-
#
|
| 24461 |
# ════════════════════════════════════════════════════════════════
|
| 24462 |
async def _curate_context(query: str, raw_context: str,
|
| 24463 |
max_output: int = 800) -> str:
|
| 24464 |
"""
|
| 24465 |
-
Lọc context bằng
|
| 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 |
-
|
| 24481 |
-
|
| 24482 |
-
|
| 24483 |
-
|
| 24484 |
-
|
| 24485 |
-
|
| 24486 |
-
|
| 24487 |
-
|
| 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
|
| 24671 |
-
|
| 24672 |
-
|
| 24673 |
-
|
| 24674 |
-
|
| 24675 |
-
|
| 24676 |
-
|
| 24677 |
-
|
| 24678 |
-
|
| 24679 |
-
|
| 24680 |
-
|
| 24681 |
-
|
| 24682 |
-
|
| 24683 |
-
|
| 24684 |
-
|
| 24685 |
-
|
| 24686 |
-
|
| 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 |
-
"""
|
| 24854 |
-
|
| 24855 |
-
|
| 24856 |
-
|
| 24857 |
-
|
| 24858 |
-
|
| 24859 |
-
|
| 24860 |
-
|
| 24861 |
-
|
| 24862 |
-
|
| 24863 |
-
|
| 24864 |
-
|
| 24865 |
-
|
| 24866 |
-
|
| 24867 |
-
|
| 24868 |
-
|
| 24869 |
-
|
| 24870 |
-
|
| 24871 |
-
|
| 24872 |
-
|
| 24873 |
-
|
| 24874 |
-
|
| 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 |
-
"""
|
| 31504 |
-
|
| 31505 |
-
|
| 31506 |
-
|
| 31507 |
-
|
|
|
|
|
|
|
| 31508 |
try:
|
| 31509 |
-
|
| 31510 |
-
|
| 31511 |
-
|
| 31512 |
-
|
| 31513 |
-
|
| 31514 |
-
|
| 31515 |
-
|
| 31516 |
-
|
| 31517 |
-
|
| 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]
|
| 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 |
-
|
| 32342 |
-
|
| 32343 |
-
|
| 32344 |
-
|
| 32345 |
-
|
| 32346 |
-
|
| 32347 |
-
|
| 32348 |
-
|
| 32349 |
-
|
| 32350 |
-
|
| 32351 |
-
|
| 32352 |
-
|
| 32353 |
-
|
| 32354 |
-
|
| 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 |
-
"""
|
| 32488 |
-
|
| 32489 |
-
|
| 32490 |
-
|
| 32491 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32492 |
try:
|
| 32493 |
-
|
| 32494 |
-
|
| 32495 |
-
|
| 32496 |
-
|
| 32497 |
-
|
| 32498 |
-
|
| 32499 |
-
|
| 32500 |
-
|
| 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]
|
| 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 |
-
# ──
|
| 602 |
def call_cerebras(messages: list, system_prompt: str = "") -> Optional[str]:
|
| 603 |
-
"""
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 607 |
try:
|
| 608 |
-
import
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
)
|
| 621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
if content:
|
| 623 |
-
print("[
|
| 624 |
return content.strip()
|
| 625 |
except Exception as e:
|
| 626 |
-
print(f"[
|
| 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 →
|
| 686 |
r = call_cerebras(messages, system_prompt)
|
| 687 |
if r: return r
|
| 688 |
|
| 689 |
-
print("[FreeBrain]
|
| 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 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
try:
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 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"
|
| 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": "
|
| 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
|
| 2510 |
Trả về điểm 0-10.
|
|
|
|
|
|
|
|
|
|
| 2511 |
"""
|
| 2512 |
-
import
|
|
|
|
| 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 |
-
|
| 2534 |
-
|
| 2535 |
-
|
| 2536 |
-
|
| 2537 |
-
|
| 2538 |
-
|
| 2539 |
-
|
| 2540 |
-
|
| 2541 |
-
|
| 2542 |
-
|
| 2543 |
-
|
| 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 |
-
"""
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 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
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 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 |
-
"""
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 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 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 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.
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 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": "
|
| 22 |
routing = {
|
| 23 |
-
"code": {"provider": "
|
| 24 |
-
"math": {"provider": "
|
| 25 |
-
"creative": {"provider": "gemini",
|
| 26 |
-
"research": {"provider": "mistral",
|
| 27 |
-
"reasoning": {"provider": "
|
| 28 |
-
"simple": {"provider": "
|
| 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
|
|
|
|
| 38 |
print(f"[CONDUCTOR] Task={task_type} -> {provider}/{model_name}")
|
| 39 |
reply = None
|
| 40 |
try:
|
| 41 |
-
if provider == "
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 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->
|
| 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 |
-
|
| 90 |
-
|
| 91 |
try:
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 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 -
|
| 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 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 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 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
| 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(
|
| 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 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 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 |
-
|
| 624 |
-
|
| 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
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
)
|
| 655 |
-
if
|
| 656 |
return None
|
| 657 |
-
content =
|
| 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:
|