fix: 允许 Agent 持续自主诊断

This commit is contained in:
cnbugs
2026-07-25 12:50:38 +08:00
parent fdac1eaffc
commit 47abfef238
2 changed files with 74 additions and 4 deletions
+27 -4
View File
@@ -2,6 +2,7 @@
import json
import re
import uuid
from collections import Counter
import httpx
from backend.config import AI_API_BASE, AI_API_KEY, AI_MODEL
from backend.agent_tools import classify_kubectl_command, execute_kubectl
@@ -96,7 +97,7 @@ async def _complete_chat(messages: list[dict]) -> str:
async def run_diagnostic_agent(
report: str,
question: str = "",
max_steps: int = 6,
max_steps: int = 30,
execution_mode: str = "ai",
):
"""自主诊断循环:AI 模式执行只读命令,手动模式等待用户执行。"""
@@ -112,8 +113,11 @@ async def run_diagnostic_agent(
{"role": "user", "content": user_content},
]
command_counts = Counter()
if execution_mode == "ai":
initial_command = "kubectl get nodes -o wide"
command_counts[initial_command] += 1
yield {
"type": "command", "step": 0, "command": initial_command,
"reason": "建立集群节点状态基线,确保 AI 执行模式实际采集现场证据",
@@ -141,6 +145,23 @@ async def run_diagnostic_agent(
command = action["command"]
reason = action.get("reason", "AI 需要更多集群证据")
command_counts[command] += 1
if command_counts[command] > 2:
messages.extend([
{"role": "assistant", "content": content},
{
"role": "user",
"content": (
f"命令 {command!r} 已重复执行两次,不能再次执行。"
"请基于已有输出选择不同的只读诊断命令,或在证据充分时返回 final。"
),
},
])
yield {
"type": "command_rejected", "command": command,
"reason": "相同命令已执行两次,请更换诊断方向",
}
continue
try:
decision = classify_kubectl_command(command)
except ValueError as exc:
@@ -185,9 +206,11 @@ async def run_diagnostic_agent(
])
yield {
"type": "final",
"content": f"已达到自主诊断最大轮次({max_steps}),请根据上方命令输出继续人工排查。",
"model": AI_MODEL,
"type": "error",
"message": (
f"自主诊断已达到安全上限({max_steps} 轮),但 Agent 仍未形成有效结论。"
"系统已停止继续执行以避免无限循环,请检查是否重复执行相同命令或 AI 服务响应异常。"
),
}