saske560's picture
Upload 18 files
5321464 verified
Raw History Blame Contribute Delete
4.01 kB
"""
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()