""" plugins/ai.py — Chat con IA usando Groq (llama3-70b). Comandos: .ai <texto> — Envía un mensaje al chat de IA .ia <texto> — Alias de .ai .reset — Resetea la conversación (limpia historial) Requisito: Variable de entorno GROQ_API_KEY (consola.groq.com → API Keys) pip install groq """ import asyncio from pyrogram import filters from pyrogram.types import Message from bot import app from config import Config P = Config.CMD_PREFIX # ── Historial de conversación (en memoria por sesión) ──────────────────────── _history: list[dict] = [] _groq_client = None _SYSTEM_PROMPT = ( "Eres un asistente inteligente y directo. " "Responde siempre en español de forma clara, precisa y sin rodeos. " "Puedes usar formato Markdown compatible con Telegram: **negrita**, `código`, etc." ) def _get_client(): """Inicializa el cliente Groq de forma lazy.""" global _groq_client if _groq_client is None: key = Config.GROQ_API_KEY if not key: return None try: from groq import Groq _groq_client = Groq(api_key=key) except ImportError: return None return _groq_client async def _tmp(client, chat_id: int, text: str, delay: int = 7): m = await client.send_message(chat_id, text) await asyncio.sleep(delay) await m.delete() # ── .ai / .ia ──────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command(["ai", "ia"], prefixes=P)) async def cmd_ai(client, msg: Message): global _history args = msg.text.split(None, 1) await msg.delete() user_input = "" if len(args) >= 2: user_input = args[1].strip() elif msg.reply_to_message: user_input = ( msg.reply_to_message.text or msg.reply_to_message.caption or "" ) if not user_input: await _tmp(client, msg.chat.id, f"❓ **Uso:** `{P}ai <texto>` o responde a un mensaje con `{P}ai`") return groq = _get_client() if groq is None: await _tmp(client, msg.chat.id, "❌ **GROQ_API_KEY** no configurada.\n" "Añádela en HF Spaces → Settings → Secrets.") return status = await client.send_message(msg.chat.id, "💭 **Pensando...**") try: _history.append({"role": "user", "content": user_input}) completion = groq.chat.completions.create( model="llama3-70b-8192", messages=[ {"role": "system", "content": _SYSTEM_PROMPT}, *_history[-20:], # Últimos 20 turnos de contexto ], max_tokens=4096, temperature=0.7, ) reply = completion.choices[0].message.content or "(sin respuesta)" _history.append({"role": "assistant", "content": reply}) if len(reply) <= 4000: await status.edit(f"🤖 **IA:**\n\n{reply}") else: await status.delete() chunks = [reply[i:i+4000] for i in range(0, len(reply), 4000)] for chunk in chunks: await client.send_message(msg.chat.id, chunk) except Exception as e: await status.edit(f"❌ **Error Groq:** `{e}`") # ── .reset ──────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("reset", prefixes=P)) async def cmd_reset(client, msg: Message): global _history _history = [] await msg.edit("🔄 **Conversación reseteada.** El historial de IA fue borrado.") await asyncio.sleep(5) await msg.delete()