Fix: AI agent cleanup, telemetry and loop increase

This commit is contained in:
Marcos
2026-03-22 11:23:39 -03:00
parent 2fc19a88a2
commit 0d774f7486

View File

@@ -9,7 +9,7 @@ def get_llm_response(prompt: str, provider: str, cfg: dict) -> str:
"""Invoca o provedor de LLM configurado.""" """Invoca o provedor de LLM configurado."""
if provider == "gemini": if provider == "gemini":
api_key = cfg.get("gemini_api_key") or os.getenv("GEMINI_API_KEY") api_key = cfg.get("gemini_api_key") or os.getenv("GEMINI_API_KEY")
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}" url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}"
payload = {"contents": [{"parts": [{"text": prompt}]}]} payload = {"contents": [{"parts": [{"text": prompt}]}]}
res = requests.post(url, json=payload) res = requests.post(url, json=payload)
if res.status_code == 200: if res.status_code == 200:
@@ -87,12 +87,17 @@ Resposta: A memória RAM está operando com 20% de uso.
history_str += f"\nUsuário: {prompt}\n" history_str += f"\nUsuário: {prompt}\n"
current_iteration_history = history_str current_iteration_history = history_str
max_loops = 8 max_loops = 12
for _ in range(max_loops): print(f"--- INICIANDO AGENTE ({provider}) ---")
for i in range(max_loops):
print(f"\n[LOOP {i+1}/{max_loops}]")
full_prompt = system_prompt + current_iteration_history full_prompt = system_prompt + current_iteration_history
response = get_llm_response(full_prompt, provider, cfg) response = get_llm_response(full_prompt, provider, cfg)
print(f"PENSAMENTO:\n{response}")
# Procura por chamadas de ferramentas na resposta # Procura por chamadas de ferramentas na resposta
match = re.search(r"\[TOOL:(.*?)\](.*?)\[/TOOL\]", response, re.IGNORECASE | re.DOTALL) match = re.search(r"\[TOOL:(.*?)\](.*?)\[/TOOL\]", response, re.IGNORECASE | re.DOTALL)
@@ -100,20 +105,27 @@ Resposta: A memória RAM está operando com 20% de uso.
tool_name = match.group(1).strip() tool_name = match.group(1).strip()
arg = match.group(2).strip() arg = match.group(2).strip()
print(f"Agente usando ferramenta: {tool_name} -> {arg}") print(f"EXECUTANDO: {tool_name} | ARGS: {arg}")
if tool_name in AVAILABLE_TOOLS: if tool_name in AVAILABLE_TOOLS:
func = AVAILABLE_TOOLS[tool_name]["func"]
# Caso a ferramenta não aceite argumentos (ex: get_system_health)
if tool_name in ["get_system_health", "get_docker_stats"]: if tool_name in ["get_system_health", "get_docker_stats"]:
observation = AVAILABLE_TOOLS[tool_name]["func"]() observation = func()
else: else:
observation = AVAILABLE_TOOLS[tool_name]["func"](arg) observation = func(arg)
print(f"OBSERVAÇÃO (suprimida): {str(observation)[:200]}...")
else: else:
observation = f"Erro: Ferramenta '{tool_name}' não encontrada." observation = f"Erro: Ferramenta '{tool_name}' não encontrada."
print(f"ERRO: {observation}")
# Adiciona ao histórico do loop atual # Adiciona ao histórico do loop atual
current_iteration_history += f"\nAgente (Ação): {response}\nSISTEMA (Saída de {tool_name}): {observation}\n" current_iteration_history += f"\nAgente (Ação): {response}\nSISTEMA (Saída de {tool_name}): {observation}\n"
else: else:
# Se não tem comando, é a resposta final # Se não tem comando, é a resposta final
print("--- RESPOSTA FINAL ENCONTRADA ---")
return response return response
print("!!! ERRO: LIMITE DE TENTATIVAS ATINGIDO !!!")
return "O agente atingiu o limite de tentativas para esta tarefa." return "O agente atingiu o limite de tentativas para esta tarefa."