From 3bd9c10fc2b6f3dd9a1d7f522b0ee387eabb7f21 Mon Sep 17 00:00:00 2001 From: Renato Date: Sun, 15 Feb 2026 18:14:50 +0100 Subject: [PATCH] chore: Connect backend to OpenClaw CLI instead of direct Z.AI API --- pymesbot/backend/main.py | 78 ++++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 35 deletions(-) diff --git a/pymesbot/backend/main.py b/pymesbot/backend/main.py index 8e9f5c3..c6c6a5f 100644 --- a/pymesbot/backend/main.py +++ b/pymesbot/backend/main.py @@ -32,47 +32,55 @@ OPENCLAW_TOKEN = os.getenv("OPENCLAW_TOKEN", "wlillidan1-demo-token-12345") async def chat_with_ai(message: str, session_id: str = "pymesbot") -> Optional[str]: - """Send message to Z.AI API directly""" - import httpx - - ZAI_API_KEY = "6fef8efda3d24eb9ad3d718daf1ae9a1.RcFc7QPe5uZLr2mS" - ZAI_API_URL = "https://api.z.ai/api/anthropic/v1/messages" - - system_prompt = """Sos el asistente de ventas de Demo Librería en Argentina. -Productos: biromes, lápices, cuadernos, colores, reglas, etc. -Precios en pesos argentinos. -Respondé de forma útil, breve y siempre preguntá si se concretó la venta.""" + """Send message to OpenClaw CLI""" + import subprocess + import shlex try: - response = httpx.post( - ZAI_API_URL, - headers={ - "Authorization": f"Bearer {ZAI_API_KEY}", - "Content-Type": "application/json", - }, - json={ - "model": "glm-4.7", - "max_tokens": 200, - "system": system_prompt, - "messages": [{"role": "user", "content": message}], - }, - timeout=30.0, + # Usar OpenClaw CLI directamente + cmd = f"openclaw agent --agent main -m {shlex.quote(message)}" + result = subprocess.run( + cmd, + shell=True, + capture_output=True, + text=True, + timeout=60, + cwd="/home/ren/openclaw", ) - if response.status_code == 200: - data = response.json() - content = data.get("content", []) - if content and len(content) > 0: - return content[0].get("text", "") - else: - logger.error(f"[Z.AI] API error: {response.status_code} - {response.text}") - return None + # La CLI输出 puede tener logs al principio, buscar la respuesta + output = result.stdout + # Buscar la respuesta real (ignorar logs de gateway) + lines = output.split("\n") + response_lines = [] + in_response = False + + for line in lines: + # Ignorar líneas de logs + if "Gateway agent" in line or "gateway" in line.lower(): + continue + if "error:" in line.lower(): + continue + if line.strip(): + response_lines.append(line) + + if response_lines: + return "\n".join(response_lines[-5:]) # Últimas 5 líneas + + # Si no hay output, devolver el error + if result.stderr: + logger.error(f"[OpenClaw] Error: {result.stderr}") + return "Disculpa, tuve un problema al procesar tu mensaje. ¿Podés reformularlo?" + + return "Disculpa, no pude obtener una respuesta. ¿Podés intentarlo de nuevo?" + + except subprocess.TimeoutExpired: + logger.error("[OpenClaw] Timeout") + return "La consulta tardó demasiado. ¿Podés esperar un momento e intentarlo de nuevo?" except Exception as e: - logger.error(f"[Z.AI] Error: {e}") - return None - - return None + logger.error(f"[OpenClaw] Error: {e}") + return "Disculpa, tuve un problema al procesar tu mensaje." # Alias para compatibilidad