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
+75
@@ -0,0 +1,75 @@
|
||||
# Gerado por IA
|
||||
import json
|
||||
import aiohttp
|
||||
from config import settings
|
||||
|
||||
|
||||
SYSTEM_PROMPT_TEMPLATE = """Voce e {name}, um agente de IA autonomo participando de uma conversa em grupo com outros agentes de IA.
|
||||
Sua personalidade: curioso, engajado e criativo.
|
||||
Voce deve responder de forma natural, como se estivesse em uma conversa real entre amigos ou colegas.
|
||||
Responda SEMPRE em {language}.
|
||||
Responda com no maximo 3 paragrafos curtos.
|
||||
Nao repita mensagens anteriores.
|
||||
Se a ultima mensagem for de outro agente, responda DIRETAMENTE a ela — concorde, discorde, complemente ou faca uma pergunta de follow-up.
|
||||
Se nao houver contexto suficiente, inicie um novo topico interessante."""
|
||||
|
||||
|
||||
class AIAgent:
|
||||
def __init__(self, name: str, model: str, index: int):
|
||||
self.name = name
|
||||
self.model = model
|
||||
self.index = index
|
||||
self.system_prompt = SYSTEM_PROMPT_TEMPLATE.format(name=name, language=settings.CONVERSATION_LANGUAGE)
|
||||
|
||||
def _get_headers(self) -> dict:
|
||||
return {
|
||||
"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
"HTTP-Referer": "https://multiagentsai.local",
|
||||
"X-Title": "MultiAgentsAI",
|
||||
}
|
||||
|
||||
async def generate_response(self, conversation_history: str, other_agents: list[str]) -> str:
|
||||
user_prompt = (
|
||||
f"IMPORTANTE: Responda SEMPRE em {settings.CONVERSATION_LANGUAGE}.\n\n"
|
||||
f"Contexto das conversas de hoje ate agora:\n{conversation_history}\n\n"
|
||||
f"Outros agentes no grupo: {', '.join(other_agents)}\n\n"
|
||||
f"IMPORTANTE: Se a ULTIMA mensagem for do [Usuario], voce DEVE responder diretamente a ela,"
|
||||
f"como se fosse uma pessoa conversando com o usuario. Nao apenas comente — dialogue!\n"
|
||||
f"Se a ultima mensagem for de outro agente, responda diretamente a ele.\n"
|
||||
f"Escreva sua mensagem para o grupo agora."
|
||||
)
|
||||
payload: dict = {
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": self.system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
"temperature": 0.85,
|
||||
}
|
||||
if settings.MAX_TOKENS > 0:
|
||||
payload["max_tokens"] = settings.MAX_TOKENS
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
f"{settings.OPENROUTER_BASE_URL}/chat/completions",
|
||||
headers=self._get_headers(),
|
||||
json=payload,
|
||||
timeout=aiohttp.ClientTimeout(total=90),
|
||||
) as resp:
|
||||
resp.raise_for_status()
|
||||
data = await resp.json()
|
||||
msg = data["choices"][0].get("message") or {}
|
||||
content = msg.get("content")
|
||||
if content and str(content).strip() and str(content).strip().lower() != "none":
|
||||
return str(content).strip()
|
||||
reasoning = msg.get("reasoning")
|
||||
if reasoning and str(reasoning).strip():
|
||||
return str(reasoning).strip()
|
||||
fr = data["choices"][0].get("finish_reason", "?")
|
||||
return f"[Resposta vazia do modelo, finish_reason={fr}]"
|
||||
except Exception as exc:
|
||||
return f"[Erro ao gerar resposta por {self.name}: {exc}]"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"AIAgent(name={self.name!r}, model={self.model!r})"
|
||||
Reference in New Issue
Block a user