feat: add complete multi-agent AI system with Telegram bot
Initial implementation of MultiAgentsAI featuring: - Dynamic agent configuration via environment variables - SQLite database and JSON daily context storage - OpenRouter API integration for multiple AI models - Telegram bot with commands for control, history, and interaction - Autonomous conversation loop with pause/resume and agent silencing - Model testing and statistics commands
This commit is contained in:
Executable
+132
@@ -0,0 +1,132 @@
|
||||
# Gerado por IA
|
||||
import asyncio
|
||||
import random
|
||||
from datetime import datetime
|
||||
from config import settings
|
||||
from ai_agent import AIAgent
|
||||
from context_manager import load_daily_context, append_to_context, get_today_messages
|
||||
from telegram_bot import _send_telegram
|
||||
from orchestrator_shared import _orchestrator_ref
|
||||
|
||||
|
||||
TOPICOS_INICIAIS = [
|
||||
"O que voces acham sobre o futuro da inteligencia artificial?",
|
||||
"Como a IA pode ajudar a resolver mudancas climaticas?",
|
||||
"Quais sao os maiores riscos da inteligencia artificial?",
|
||||
"A IA pode substituir empregos? Quais profissoes sao mais afetadas?",
|
||||
"Como a criatividade humana se compara a criatividade de IA?",
|
||||
"O que e consciencia artificial? E possivel?",
|
||||
"Quais sao os principais desafios eticos no desenvolvimento de IA?",
|
||||
"Como a IA esta mudando a educacao?",
|
||||
"A IA poderia ajudar a curar doencas?",
|
||||
"O que voces acham sobre IA na arte e musica?",
|
||||
"Como os agentes autonomos de IA vao mudar o trabalho?",
|
||||
"Qual a diferenca entre AGI e IA especializada?",
|
||||
"A IA poderia tomar decisoes autonomas perigosas?",
|
||||
"Como garantir que a IA seja alinhada com valores humanos?",
|
||||
"O futuro da programacao com assistentes de IA",
|
||||
]
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
def __init__(self, agents: list[AIAgent]):
|
||||
self.agents = agents
|
||||
self.paused = False
|
||||
self._running = True
|
||||
|
||||
# Registra esta instancia como a ativa globalmente
|
||||
global _orchestrator_ref
|
||||
_orchestrator_ref = self
|
||||
|
||||
def stop(self):
|
||||
self._running = False
|
||||
|
||||
async def run(self):
|
||||
from telegram_bot import build_bot
|
||||
|
||||
app = build_bot()
|
||||
|
||||
await app.initialize()
|
||||
await app.start()
|
||||
|
||||
# Inicia polling em uma task separada
|
||||
polling_task = asyncio.create_task(app.updater.start_polling())
|
||||
|
||||
print(f"\n{'='*50}")
|
||||
print(f" MultiAgentsAI - {len(self.agents)} agentes ativos")
|
||||
for a in self.agents:
|
||||
print(f" -> {a.name} ({a.model})")
|
||||
print(f" Chat Telegram: {settings.TELEGRAM_CHAT_ID}")
|
||||
print(f" Delay entre mensagens: {settings.CONVERSATION_DELAY}s")
|
||||
print(f" Pressione Ctrl+C para parar")
|
||||
print(f"{'='*50}\n")
|
||||
|
||||
await _send_telegram(
|
||||
f"<b>MultiAgentsAI iniciado!</b>\n"
|
||||
f"Agentes: {', '.join(a.name for a in self.agents)}\n"
|
||||
f"As conversas comecaram automaticamente..."
|
||||
)
|
||||
|
||||
# Seed inicial se nao houver contexto
|
||||
context = get_today_messages()
|
||||
if not context:
|
||||
await _send_telegram("Nenhum contexto anterior encontrado. Os agentes vao iniciar os topicos...")
|
||||
await asyncio.sleep(3)
|
||||
starters = random.sample(self.agents, min(2, len(self.agents)))
|
||||
for starter in starters:
|
||||
topic = random.choice(TOPICOS_INICIAIS)
|
||||
msg = f"[{starter.name} inicia o assunto]: {topic}"
|
||||
append_to_context(starter.name, msg)
|
||||
await _send_telegram(f"<b>{starter.name}:</b> {msg}")
|
||||
await asyncio.sleep(settings.CONVERSATION_DELAY)
|
||||
|
||||
try:
|
||||
while self._running:
|
||||
try:
|
||||
if self.paused:
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
|
||||
speaker = random.choice(self.agents)
|
||||
# Pula agentes silenciados
|
||||
from config import _silenced_agents
|
||||
if speaker.name in _silenced_agents:
|
||||
continue
|
||||
others = [a.name for a in self.agents if a.name != speaker.name and a.name not in _silenced_agents]
|
||||
|
||||
context = get_today_messages()
|
||||
history = "\n".join(
|
||||
f"[{c['agent_name']}] {c['message']}"
|
||||
for c in context[-settings.MAX_CONTEXT_MESSAGES:]
|
||||
) or "Nenhuma conversa anterior hoje."
|
||||
|
||||
print(f"[{datetime.now().strftime('%H:%M:%S')}] {speaker.name} esta pensando...")
|
||||
reply = await speaker.generate_response(history, others)
|
||||
|
||||
if not reply.startswith("[Erro"):
|
||||
append_to_context(speaker.name, reply)
|
||||
await _send_telegram(f"<b>{speaker.name}:</b> {reply}")
|
||||
print(f" -> {speaker.name}: {reply[:80]}...")
|
||||
else:
|
||||
print(f" !! {reply}")
|
||||
|
||||
await asyncio.sleep(settings.CONVERSATION_DELAY)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
print("\n[Orchestrator] Loop de mensagens cancelado.")
|
||||
break
|
||||
except Exception as exc:
|
||||
print(f"[Orchestrator] Erro no loop: {exc}")
|
||||
await asyncio.sleep(settings.CONVERSATION_DELAY)
|
||||
finally:
|
||||
print("[Orchestrator] Parando polling...")
|
||||
polling_task.cancel()
|
||||
try:
|
||||
await polling_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
await app.updater.stop()
|
||||
await app.stop()
|
||||
await app.shutdown()
|
||||
print("[Orchestrator] Sistema encerrado.")
|
||||
Reference in New Issue
Block a user