File size: 22,624 Bytes
c8d30bc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 | # agents/debate_engine.py
# ๅ่ฝ๏ผ3 ่ผช่พฏ่ซๅผๆ + Judge Sub-Agent
# ๆถๆงไพๆ๏ผDu et al. (2023) "Improving Factuality and Reasoning in LLMs through Multiagent Debate"
# ICML 2023, arXiv:2305.14325
#
# ่จญ่จๅๅ๏ผไพ่ช่ซๆ๏ผ๏ผ
# - ๅคๅ็จ็ซ LLM ๅฏฆไพ๏ผAnalyst / Critic ๅ่ช็จ็ซ๏ผ
# - ๆๅค 3 ่ผช่ฟญไปฃ๏ผๅ ฑ้
ฌ้ๆธ๏ผ3 ่ผชๅพๆ็่ถจ็ทฉ๏ผ
# - ็กๅ
ฑ่ญ โ ็ฌฌไธๆน Judge sub-agent ไปฒ่ฃ
# - ๅฎๅ
จๆง้ ๅ๏ผๅๅไฟๅฎ๏ผ้ซไผฐ้ขจ้ชๆฏไฝไผฐๅฎๅ
จ๏ผ
#
# ๅ
ฑ่ญๅฎ็พฉ๏ผ
# Analyst ่ Critic ็ๆด้ซ้ขจ้ช็ญ็ด็ธๅทฎ โค 1 ็ด
# (ไพๅฆ HIGH vs CRITICAL ไธๅ
ฑ่ญ๏ผHIGH vs HIGH ๅ
ฑ่ญ)
from __future__ import annotations
import json
import logging
import time
from typing import Any
from crewai import Agent, Task, Crew, Process
from config import SYSTEM_CONSTITUTION, get_llm, degradation_status
logger = logging.getLogger("ThreatHunter.debate_engine")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ้ขจ้ช็ญ็ดๆ ๅฐ๏ผ็จๆผๅ
ฑ่ญๅคๅฎ๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
RISK_LEVELS: dict[str, int] = {
"LOW": 1,
"MEDIUM": 2,
"HIGH": 3,
"CRITICAL": 4,
}
MAX_DEBATE_ROUNDS = 3
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Judge Sub-Agent ๆงๅปบ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_judge_agent() -> Agent:
"""
Judge sub-agent๏ผ็จ็ซ็ฌฌไธๆน่ฃๆฑบ่
ใ
่จญ่จๅๅ๏ผDu et al. 2023๏ผ๏ผ
- ไธๆฏ Analyst ไนไธๆฏ Critic ็ๅปถไผธ
- ๆถๅฐๅฎๆด่พฏ่ซ็ด้ๅพ๏ผ้ธๆๆๆ้่ผฏๆฏๆ็็ซๅ ด
- ๅฎๅ
จๆง้ ๅๅๅไฟๅฎ๏ผๅฏงๅฏ้ซไผฐ้ขจ้ช๏ผ
"""
return Agent(
role="Security Arbitration Judge",
goal=(
"Review the complete debate history between Analyst and Critic. "
"Select the most logically supported risk assessment. "
"In case of equal evidence, err on the side of caution (higher risk). "
"Output a final JSON verdict."
),
backstory=(
f"{SYSTEM_CONSTITUTION}\n\n"
"You are an impartial security arbitration judge. You were not involved in the debate. "
"Your task is to read both sides' arguments and render a final, binding verdict. "
"You must cite which round's argument was most persuasive and why. "
"In security contexts, when evidence is ambiguous, choose the MORE SEVERE rating."
),
llm=get_llm(),
verbose=True,
max_iter=3,
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ่พฏ่ซๅผๆ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class DebateEngine:
"""
ๅฏฆไฝ Du et al. (2023) Multiagent Debate ๆฉๅถใ
ๆต็จ๏ผ
Round 1: Analyst ๆๅบๅๅง็ซๅ ด โ Critic ่ณช็
Round 2: Analyst ๆดๆฐ็ซๅ ด๏ผๅซ Critic ๅ้ฅ๏ผโ Critic ๅ่ฉ
Round 3: Analyst ๆ็ต็ซๅ ด โ Critic ๆ็ต่ฉๅค
Final: ่ฅ 3 ่ผชๅพไป็กๅ
ฑ่ญ โ Judge sub-agent ไปฒ่ฃ
"""
def __init__(self, max_rounds: int = MAX_DEBATE_ROUNDS):
self.max_rounds = max_rounds
self.min_rounds_with_findings = min(2, max_rounds)
def run_debate(
self,
analyst_output: dict[str, Any],
input_type: str = "pkg",
on_progress: Any = None,
) -> dict[str, Any]:
"""
ๅท่กๅฎๆด่พฏ่ซๆต็จใ
Args:
analyst_output: Analyst ็ๅๅงๅๆ็ตๆ๏ผๆฅ่ช run_analyst_pipeline๏ผ
input_type: ่ผธๅ
ฅ้กๅ๏ผpkg/code/config ็ญ๏ผๅฝฑ้ฟ Critic skill ้ธๆ๏ผ
on_progress: SSE ้ฒๅบฆๅ่ชฟ
Returns:
ๆ็ต่ฃๆฑบ็ตๆ๏ผๆ ผๅผๅ run_critic_pipeline ่ผธๅบ๏ผ
"""
from agents.critic import run_critic_pipeline
t0 = time.time()
history: list[dict[str, Any]] = []
current_analyst_output = analyst_output
consensus = False
consensus_round = 0
early_stop_reason = ""
final_critic_result: dict[str, Any] = {}
has_findings = self._has_findings(analyst_output)
logger.info("[DEBATE] Starting %d-round debate (Du et al. 2023)", self.max_rounds)
if on_progress:
try:
on_progress("debate", "RUNNING", {"step": "starting", "max_rounds": self.max_rounds})
except Exception:
pass
for round_num in range(1, self.max_rounds + 1):
logger.info("[DEBATE] Round %d/%d starting", round_num, self.max_rounds)
if on_progress:
try:
on_progress("debate", "RUNNING", {
"step": f"round_{round_num}",
"round": round_num,
"max_rounds": self.max_rounds,
})
except Exception:
pass
# โโ Critic ่ฉๅฏฉ Analyst ็็ถ่ผช็ซๅ ด โโโโโโโโโโโโโโ
# ๆณจๅ
ฅ็ถ่ผชไธไธๆ๏ผ่ฎ Critic ็ฅ้้ๆฏ็ฌฌๅนพ่ผช
round_context = dict(current_analyst_output)
round_context["_debate_round"] = round_num
round_context["_debate_max_rounds"] = self.max_rounds
if history:
round_context["_prev_critic_challenges"] = history[-1].get("critic", {}).get("challenges", [])
try:
critic_result = run_critic_pipeline(round_context, input_type=input_type)
except Exception as e:
logger.warning("[DEBATE] Round %d Critic failed: %s โ using maintain verdict", round_num, e)
critic_result = {
"verdict": "MAINTAIN",
"weighted_score": 70.0,
"challenges": [],
"reasoning": f"Critic failed in round {round_num}: {e}",
"_degraded": True,
}
history.append({
"round": round_num,
"analyst": current_analyst_output,
"critic": critic_result,
})
final_critic_result = critic_result
# โโ ๅ
ฑ่ญๅคๅฎ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if self._check_consensus(current_analyst_output, critic_result):
if has_findings and round_num < self.min_rounds_with_findings and not critic_result.get("no_challenge"):
logger.info(
"[DEBATE] Consensus detected at round %d, continuing to minimum %d rounds because findings exist",
round_num,
self.min_rounds_with_findings,
)
if round_num < self.max_rounds:
current_analyst_output = self._analyst_rebuttal(
current_analyst_output, critic_result, round_num
)
continue
consensus = True
consensus_round = round_num
early_stop_reason = "consensus_after_min_rounds" if has_findings else "no_findings"
logger.info(
"[DEBATE] Consensus reached at round %d | "
"analyst_risk=%s | critic_verdict=%s",
round_num,
self._get_analyst_risk(current_analyst_output),
critic_result.get("verdict", "UNKNOWN"),
)
break
# โโ Analyst ๆดๆฐ็ซๅ ด๏ผๅซ Critic ๅ้ฅ๏ผโโโโโโโโโโโ
if round_num < self.max_rounds:
current_analyst_output = self._analyst_rebuttal(
current_analyst_output, critic_result, round_num
)
# โโ ๆ็ต่ฃๆฑบ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
elapsed_ms = int((time.time() - t0) * 1000)
if consensus:
logger.info(
"[DEBATE] โ
Consensus after %d/%d rounds | elapsed=%dms",
consensus_round, self.max_rounds, elapsed_ms,
)
result = dict(final_critic_result)
result["_debate_meta"] = {
"consensus": True,
"consensus_round": consensus_round,
"total_rounds": round_num,
"elapsed_ms": elapsed_ms,
"method": "multiagent_debate_Du2023",
"early_stop_reason": early_stop_reason,
"rounds": self._summarize_rounds(history),
}
return result
else:
logger.warning(
"[DEBATE] โ ๏ธ No consensus after %d rounds โ invoking Judge sub-agent",
self.max_rounds,
)
return self._judge_verdict(history, elapsed_ms)
# โโ ็งๆ่ผๅฉๆนๆณ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _check_consensus(self, analyst_output: dict, critic_result: dict) -> bool:
"""
ๅ
ฑ่ญๅคๅฎ๏ผ้ขจ้ช็ญ็ด็ธๅทฎ โค 1 ็ด่ฆ็บๅ
ฑ่ญใ
CRITICAL vs HIGH โ ไธๅ
ฑ่ญ๏ผๅทฎ 1 ็ด๏ผ่ฆ็บ้็๏ผไฟ็่พฏ่ซ๏ผ
CRITICAL vs CRITICAL โ ๅ
ฑ่ญ
HIGH vs MEDIUM โ ไธๅ
ฑ่ญ
HIGH vs HIGH โ ๅ
ฑ่ญ
Critic verdict=MAINTAIN โ ็ดๆฅๅ
ฑ่ญ๏ผCritic ๅๆ Analyst๏ผ
"""
# Critic ็ดๆฅๅๆ โ ๅ
ฑ่ญ
verdict = critic_result.get("verdict", "MAINTAIN")
if verdict == "MAINTAIN":
return True
# Critic ๆ็ขบ่ฆๆฑ้็ด โ ้่ฆ็นผ็บ่พฏ่ซ
if verdict == "DOWNGRADE":
analyst_risk = self._get_analyst_risk(analyst_output)
a_level = RISK_LEVELS.get(analyst_risk, 2)
# Downgrade ไปฃ่กจ Critic ่ช็บๆ้ไธ็ด๏ผๅฆๆๅๆธๅทฒๅค ไฝๅๆฅๅ
score = critic_result.get("weighted_score", 70)
if score >= 80: # Critic ่ฉๅ้ซ๏ผ่ชชๆ Analyst ็ซๅ ดๅผท
return True
return False
# ๅ
ถไปๆ
ๆณ๏ผESCALATE ็ญ๏ผโโ ็ๅๆธ
score = critic_result.get("weighted_score", 70)
return score >= 75
def _has_findings(self, analyst_output: dict[str, Any]) -> bool:
"""ๅคๆท Analyst ๆฏๅฆ็็ๆ็ผ็พ้
๏ผๆ็ผ็พๆ่ณๅฐ้่ฆ็ฌฌไบ่ผชไบคๅ่ณช็ใ"""
for key in ("analysis", "vulnerabilities", "code_patterns", "code_patterns_summary"):
value = analyst_output.get(key)
if isinstance(value, list) and len(value) > 0:
return True
return False
def _summarize_rounds(self, history: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""็ข็่ผ้ๅๅๆ่ฆ๏ผไพ UI/ๆธฌ่ฉฆ็ขบ่ช่พฏ่ซๆฒๆ่ขซ็ฌฌไธ่ผชๅๆใ"""
rounds = []
for entry in history:
critic = entry.get("critic", {})
analyst = entry.get("analyst", {})
rounds.append({
"round": entry.get("round"),
"analyst_risk": self._get_analyst_risk(analyst),
"critic_verdict": critic.get("verdict"),
"critic_score": critic.get("weighted_score"),
"challenge_count": len(critic.get("challenges", [])),
})
return rounds
def _get_analyst_risk(self, analyst_output: dict) -> str:
"""ๅพ Analyst ่ผธๅบๆๅๆด้ซ้ขจ้ช็ญ็ด"""
analysis = analyst_output.get("analysis", [])
if not analysis:
return "UNKNOWN"
# ๅๆ้ซๅด้ๆง
max_level = 0
max_name = "UNKNOWN"
for entry in analysis:
sev = entry.get("severity") or entry.get("adjusted_risk", "MEDIUM")
level = RISK_LEVELS.get(sev, 0)
if level > max_level:
max_level = level
max_name = sev
return max_name
@staticmethod
def _normalize_challenge(challenge: Any) -> dict[str, str]:
"""Support both string[] contracts and object-style challenge records."""
if isinstance(challenge, dict):
return {
"type": str(challenge.get("type") or "challenge"),
"description": str(challenge.get("description") or challenge.get("text") or challenge),
}
return {"type": "challenge", "description": str(challenge)}
def _analyst_rebuttal(
self,
analyst_output: dict,
critic_result: dict,
round_num: int,
) -> dict:
"""
Analyst ๆดๆฐ็ซๅ ด๏ผ็ฐกๅ็๏ผๆณจๅ
ฅ Critic ๆๆฐไธฆไฟฎๆน reasoning๏ผ
ๅจๅฎๆดๅฏฆไฝไธญ๏ผ้่ฃกๆ่ฉฒ้ๆฐๅผๅซ Analyst LLMใ
็ฎๅ็บ่ผ้ๅฏฆไฝ๏ผ็ดๆฅๅจ่ผธๅบไธญๆณจๅ
ฅ Critic ๅ้ฅ๏ผ
่ฎไธไธ่ผช็ Critic ็ๅฐๆดๆฐๅพ็ไธไธๆใ
"""
updated = dict(analyst_output)
challenges = [
self._normalize_challenge(challenge)
for challenge in critic_result.get("challenges", [])
]
updated["_critic_challenges_r"] = {
"round": round_num,
"challenges": challenges,
"critic_verdict": critic_result.get("verdict"),
"critic_score": critic_result.get("weighted_score", 70),
}
# ๆดๆฐ reasoning๏ผๆจๆณจ Analyst ๅทฒ็ๅฐ Critic ๅ้ฅ
if updated.get("analysis"):
for entry in updated["analysis"]:
if "reasoning" in entry:
entry["reasoning"] = (
f"[Round {round_num} rebuttal after Critic verdict={critic_result.get('verdict')}: "
f"challenges={[c.get('type') for c in challenges[:3]]}] "
+ entry["reasoning"]
)
logger.info(
"[DEBATE] Round %d analyst rebuttal: addressed %d challenges",
round_num, len(challenges),
)
return updated
def _judge_verdict(
self,
debate_history: list[dict],
elapsed_ms: int,
) -> dict[str, Any]:
"""
Judge sub-agent ไปฒ่ฃ๏ผ็กๅ
ฑ่ญๆ็ฑ็ฌฌไธๆน่ฃๆฑบใ
ๅๅ๏ผDu et al. 2023 + ๅฎๅ
จๆงไฟๅฎๅๅ๏ผ๏ผ
- ้ฑ่ฎๅฎๆด่พฏ่ซ็ด้
- ้ธๆๆๆ้่ผฏๆฏๆ็็ซๅ ด
- ่ฅ่ญๆ็ธ็ถ๏ผ้ธ MORE SEVERE๏ผๅฎๅ
จๆงๅไฟๅฎ๏ผ
"""
t_judge = time.time()
logger.info("[DEBATE] Invoking Judge sub-agent...")
# ๆบๅ่พฏ่ซๆ่ฆๆๅญ
debate_summary = self._format_debate_history(debate_history)
try:
judge_agent = _build_judge_agent()
task_desc = (
f"DEBATE HISTORY ({len(debate_history)} rounds):\n\n"
f"{debate_summary}\n\n"
f"No consensus was reached after {len(debate_history)} rounds.\n\n"
f"Your task:\n"
f"1. Review all rounds of argument and counter-argument\n"
f"2. Identify which side presented stronger evidence\n"
f"3. If evidence is equal, choose the HIGHER risk level (security-conservative principle)\n"
f"4. Output a JSON verdict with:\n"
f" {{\"verdict\": \"MAINTAIN|DOWNGRADE|ESCALATE\", "
f"\"weighted_score\": 0-100, "
f"\"reasoning\": \"...\", "
f"\"winning_round\": 1-3, "
f"\"judge_note\": \"...\"}}\n\n"
f"Output ONLY the JSON, no other text."
)
task = Task(
description=task_desc,
expected_output="Pure JSON judge verdict",
agent=judge_agent,
)
crew = Crew(
agents=[judge_agent],
tasks=[task],
process=Process.sequential,
verbose=False,
)
result_str = str(crew.kickoff()).strip()
# ่งฃๆ JSON
import re
if "```json" in result_str:
result_str = result_str.split("```json")[1].split("```")[0].strip()
elif "```" in result_str:
parts = result_str.split("```")
if len(parts) >= 3:
result_str = parts[1].strip()
judge_verdict = json.loads(result_str)
judge_elapsed = int((time.time() - t_judge) * 1000)
logger.info(
"[DEBATE] Judge verdict: %s (score=%s) in %dms",
judge_verdict.get("verdict"),
judge_verdict.get("weighted_score"),
judge_elapsed,
)
judge_verdict["_debate_meta"] = {
"consensus": False,
"total_rounds": len(debate_history),
"judge_invoked": True,
"judge_elapsed_ms": judge_elapsed,
"total_elapsed_ms": elapsed_ms + judge_elapsed,
"method": "multiagent_debate_Du2023_with_judge",
"rounds": self._summarize_rounds(debate_history),
}
return judge_verdict
except Exception as e:
logger.error("[DEBATE] Judge sub-agent failed: %s โ falling back to last Critic result", e)
degradation_status.degrade("DebateJudge", str(e))
# Fallback๏ผๅๆๅพไธ่ผช็ Critic ็ตๆ๏ผๅผทๅถ็บ MAINTAIN๏ผไฟๅฎ๏ผ
last_critic = debate_history[-1].get("critic", {}) if debate_history else {}
fallback = dict(last_critic)
fallback["verdict"] = "MAINTAIN" # ไฟๅฎ๏ผ็ถญๆ Analyst ็ซๅ ด
fallback["_debate_meta"] = {
"consensus": False,
"total_rounds": len(debate_history),
"judge_invoked": True,
"judge_failed": True,
"judge_error": str(e),
"total_elapsed_ms": elapsed_ms,
"method": "multiagent_debate_Du2023_judge_fallback",
"rounds": self._summarize_rounds(debate_history),
}
return fallback
def _format_debate_history(self, history: list[dict]) -> str:
"""ๅฐ่พฏ่ซ็ด้ๆ ผๅผๅ็บๅฏ่ฎๅญไธฒ๏ผไพ Judge ้ฑ่ฎ"""
lines = []
for entry in history:
r = entry.get("round", "?")
analyst = entry.get("analyst", {})
critic = entry.get("critic", {})
# Analyst ็ซๅ ดๆ่ฆ
risk = self._get_analyst_risk(analyst)
findings_count = len(analyst.get("analysis", []))
lines.append(f"=== Round {r} ===")
lines.append(f"ANALYST: overall_risk={risk}, findings={findings_count}")
# ๅๅ 2 ๅ finding ็ reasoning
for f in analyst.get("analysis", [])[:2]:
lines.append(f" - [{f.get('severity')}] {f.get('cwe_id', f.get('cve_id', 'N/A'))}: {f.get('reasoning', '')[:100]}")
# Critic ็ซๅ ดๆ่ฆ
verdict = critic.get("verdict", "UNKNOWN")
score = critic.get("weighted_score", "?")
lines.append(f"CRITIC: verdict={verdict}, score={score}")
for raw_ch in critic.get("challenges", [])[:2]:
ch = self._normalize_challenge(raw_ch)
lines.append(f" - Challenge [{ch.get('type')}]: {ch.get('description', '')[:100]}")
lines.append("")
return "\n".join(lines)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ไพฟๅฉๅฝๅผ๏ผๆดๅ้ฒ main.py ็ๆฅๅฃ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def run_debate_pipeline(
analyst_output: dict[str, Any],
input_type: str = "pkg",
on_progress: Any = None,
) -> dict[str, Any]:
"""
ๅท่กๅฎๆด่พฏ่ซๆต็จ็้ ๅฑคๅฝๅผใ
็ดๆฅๆฟๆ main.py ไธญ็ๅฎ่ผช Critic ๅผๅซใ
Args:
analyst_output: Analyst ็ๅๅงๅๆ็ตๆ
input_type: ่ผธๅ
ฅ้กๅ
on_progress: SSE ้ฒๅบฆๅ่ชฟ
Returns:
่พฏ่ซๆ็ต่ฃๆฑบ๏ผๆ ผๅผๅ run_critic_pipeline ่ผธๅบ๏ผ
้ๅ _debate_meta ๆฌไฝ็ด้่พฏ่ซ็ๆ
๏ผ
"""
engine = DebateEngine(max_rounds=MAX_DEBATE_ROUNDS)
try:
return engine.run_debate(analyst_output, input_type=input_type, on_progress=on_progress)
except Exception as e:
logger.error("[DEBATE] DebateEngine failed: %s โ falling back to single Critic", e)
degradation_status.degrade("DebateEngine", str(e))
# ๅฎๅ
จ้็ด๏ผ้ๅๅฎ่ผช Critic๏ผๅๆฌ่ก็บ๏ผ
try:
from agents.critic import run_critic_pipeline
result = run_critic_pipeline(analyst_output, input_type=input_type)
result["_debate_meta"] = {
"consensus": None,
"engine_failed": True,
"error": str(e),
"fallback": "single_round_critic",
}
return result
except Exception as e2:
logger.error("[DEBATE] Critic fallback also failed: %s", e2)
return {
"verdict": "MAINTAIN",
"weighted_score": 60.0,
"challenges": [],
"reasoning": f"Debate engine and Critic both failed: {e} / {e2}",
"_degraded": True,
"_debate_meta": {"engine_failed": True, "critic_failed": True},
}
|