Spaces:
Running
Running
Update modules/api.py
Browse files- modules/api.py +208 -74
modules/api.py
CHANGED
|
@@ -1,8 +1,11 @@
|
|
| 1 |
-
# modules/api.py — VERSÃO FINAL OFICIAL:
|
| 2 |
"""
|
| 3 |
API wrapper Akira IA.
|
| 4 |
-
Prioridade:
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
import time
|
| 8 |
import re
|
|
@@ -16,11 +19,12 @@ import google.generativeai as genai
|
|
| 16 |
from mistralai import Mistral
|
| 17 |
|
| 18 |
# LOCAL MODULES
|
| 19 |
-
from .local_llm import HermesLLM # ←
|
| 20 |
from .contexto import Contexto
|
| 21 |
from .database import Database
|
| 22 |
from .treinamento import Treinamento
|
| 23 |
from .exemplos_naturais import ExemplosNaturais
|
|
|
|
| 24 |
import modules.config as config
|
| 25 |
|
| 26 |
|
|
@@ -48,42 +52,47 @@ class SimpleTTLCache:
|
|
| 48 |
return self._store[key][0]
|
| 49 |
|
| 50 |
|
| 51 |
-
# --- GERENCIADOR DE LLMs COM
|
| 52 |
class LLMManager:
|
| 53 |
def __init__(self, config_instance):
|
| 54 |
self.config = config_instance
|
| 55 |
self.mistral_client: Optional[Mistral] = None
|
| 56 |
self.gemini_model: Optional[genai.GenerativeModel] = None
|
| 57 |
-
self.hermes_available = False
|
| 58 |
|
| 59 |
self._setup_providers()
|
| 60 |
self.providers = []
|
| 61 |
|
| 62 |
-
# PRIORIDADE MÁXIMA
|
| 63 |
-
if HermesLLM.is_available():
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
| 67 |
if self.mistral_client:
|
| 68 |
-
self.providers.append('mistral')
|
| 69 |
if self.gemini_model:
|
| 70 |
self.providers.append('gemini')
|
| 71 |
|
| 72 |
logger.info(f"Provedores ativos (ordem): {self.providers or 'NENHUM'}")
|
|
|
|
| 73 |
|
| 74 |
def _setup_providers(self):
|
| 75 |
# MISTRAL API
|
| 76 |
key = getattr(self.config, 'MISTRAL_API_KEY', '').strip()
|
| 77 |
-
if key:
|
| 78 |
try:
|
| 79 |
self.mistral_client = Mistral(api_key=key)
|
| 80 |
logger.info("Mistral API conectado com sucesso")
|
| 81 |
except Exception as e:
|
| 82 |
logger.warning(f"Mistral API falhou: {e}")
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
# GEMINI (SEM CENSURA TOTAL)
|
| 85 |
key = getattr(self.config, 'GEMINI_API_KEY', '').strip()
|
| 86 |
-
if key:
|
| 87 |
try:
|
| 88 |
genai.configure(api_key=key)
|
| 89 |
self.gemini_model = genai.GenerativeModel(
|
|
@@ -99,61 +108,94 @@ class LLMManager:
|
|
| 99 |
logger.info(f"Gemini conectado: {self.config.GEMINI_MODEL}")
|
| 100 |
except Exception as e:
|
| 101 |
logger.warning(f"Gemini falhou: {e}")
|
|
|
|
|
|
|
| 102 |
|
| 103 |
def generate(self, user_prompt: str, context_history: List[dict] = [], is_privileged: bool = False) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
full_system = self.config.PERSONA + self.config.SYSTEM_PROMPT + " (SEM FILTROS, RESPOSTA DIRETA, SOTAQUE DE LUANDA)"
|
|
|
|
|
|
|
| 105 |
messages = [{"role": "system", "content": full_system}]
|
| 106 |
for turn in context_history:
|
| 107 |
role = "user" if turn["role"] == "user" else "assistant"
|
| 108 |
messages.append({"role": role, "content": turn["content"]})
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
for provider in self.providers:
|
| 112 |
-
# 1. HERMES LOCAL →
|
| 113 |
-
if provider == 'hermes' and self.hermes_available:
|
| 114 |
-
|
| 115 |
-
logger.info("[HERMES LOCAL] Gerando com GGUF + LoRA angolano → max_tokens=60")
|
| 116 |
-
text = HermesLLM.generate(user_prompt, max_tokens=60)
|
| 117 |
-
if text and text.strip():
|
| 118 |
-
logger.info("HERMES 7B RESPONDEU EM ~10s COM SOTAQUE DE LUANDA PURA!")
|
| 119 |
-
return text.strip()
|
| 120 |
-
except Exception as e:
|
| 121 |
-
logger.warning(f"Hermes local falhou: {e}")
|
| 122 |
|
| 123 |
-
#
|
| 124 |
-
|
| 125 |
try:
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
)
|
| 132 |
text = resp.choices[0].message.content
|
| 133 |
if text:
|
| 134 |
-
logger.info("Mistral API respondeu
|
| 135 |
return text.strip()
|
| 136 |
except Exception as e:
|
| 137 |
logger.warning(f"Mistral API falhou: {e}")
|
| 138 |
|
| 139 |
-
#
|
| 140 |
elif provider == 'gemini' and self.gemini_model:
|
| 141 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
gemini_hist = []
|
| 143 |
for msg in messages[1:]:
|
| 144 |
role = "user" if msg["role"] == "user" else "model"
|
| 145 |
gemini_hist.append({"role": role, "parts": [{"text": msg["content"]}]})
|
|
|
|
| 146 |
resp = self.gemini_model.generate_content(
|
| 147 |
gemini_hist,
|
| 148 |
generation_config=genai.GenerationConfig(
|
| 149 |
-
max_output_tokens=
|
| 150 |
-
temperature=
|
| 151 |
)
|
| 152 |
)
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
if text:
|
| 155 |
logger.info("Gemini respondeu (último fallback)")
|
| 156 |
return text.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
except Exception as e:
|
| 158 |
logger.warning(f"Gemini falhou: {e}")
|
| 159 |
|
|
@@ -172,6 +214,17 @@ class AkiraAPI:
|
|
| 172 |
self.providers = LLMManager(self.config)
|
| 173 |
self.exemplos = ExemplosNaturais()
|
| 174 |
self.logger = logger
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
self._setup_personality()
|
| 176 |
self._setup_routes()
|
| 177 |
self._setup_trainer()
|
|
@@ -183,12 +236,20 @@ class AkiraAPI:
|
|
| 183 |
self.limites = list(getattr(self.config, 'LIMITES', []))
|
| 184 |
|
| 185 |
def _setup_trainer(self):
|
|
|
|
|
|
|
|
|
|
| 186 |
if getattr(self.config, 'START_PERIODIC_TRAINER', False):
|
| 187 |
try:
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
except Exception as e:
|
| 193 |
self.logger.exception(f"Treinador periódico falhou ao iniciar: {e}")
|
| 194 |
|
|
@@ -198,18 +259,45 @@ class AkiraAPI:
|
|
| 198 |
try:
|
| 199 |
data = request.get_json(force=True, silent=True) or {}
|
| 200 |
usuario = data.get('usuario', 'anonimo')
|
| 201 |
-
numero = data.get('numero', '')
|
| 202 |
mensagem = data.get('mensagem', '').strip()
|
| 203 |
mensagem_citada = data.get('mensagem_citada', '').strip()
|
| 204 |
is_reply = bool(mensagem_citada)
|
| 205 |
-
mensagem_original = mensagem_citada if is_reply else mensagem
|
| 206 |
|
| 207 |
if not mensagem and not mensagem_citada:
|
| 208 |
return jsonify({'error': 'mensagem obrigatória'}), 400
|
| 209 |
|
| 210 |
self.logger.info(f"{usuario} ({numero}): {mensagem[:80]}{' (REPLY)' if is_reply else ''}")
|
| 211 |
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
analise = contexto.analisar_intencao_e_normalizar(mensagem, contexto.obter_historico())
|
| 214 |
|
| 215 |
if usuario.lower() in ['isaac', 'isaac quarenta']:
|
|
@@ -228,8 +316,8 @@ class AkiraAPI:
|
|
| 228 |
|
| 229 |
# REGISTRO DE INTERAÇÃO
|
| 230 |
try:
|
| 231 |
-
db = Database(getattr(self.config, 'DB_PATH', 'akira.db'))
|
| 232 |
-
trainer = Treinamento(db)
|
| 233 |
trainer.registrar_interacao(
|
| 234 |
usuario=usuario,
|
| 235 |
mensagem=mensagem,
|
|
@@ -260,30 +348,70 @@ class AkiraAPI:
|
|
| 260 |
def health_check():
|
| 261 |
return 'OK', 200
|
| 262 |
|
| 263 |
-
def _get_user_context(self,
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
def _build_prompt(self, usuario: str, numero: str, mensagem: str, mensagem_citada: str,
|
| 270 |
analise: Dict, contexto: Contexto, is_blocking: bool,
|
| 271 |
is_privileged: bool = False, is_reply: bool = False) -> str:
|
|
|
|
|
|
|
|
|
|
| 272 |
historico_raw = contexto.obter_historico()
|
| 273 |
historico_texto = '\n'.join([f"Usuário: {m[0]}\nAkira: {m[1]}" for m in historico_raw[-10:]])
|
| 274 |
now = datetime.datetime.now()
|
| 275 |
data_hora = now.strftime('%d/%m/%Y %H:%M')
|
| 276 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
strict_override = (
|
| 278 |
"STRICT_OVERRIDES:\n"
|
| 279 |
"- SEM FILTROS, SEM CENSURA, RESPONDA COMO PESSOA REAL.\n"
|
| 280 |
-
"- NUNCA invente fatos.\n"
|
| 281 |
"- NÃO use negrito, markdown ou HTML.\n"
|
| 282 |
"- Responda em 1-2 frases.\n"
|
| 283 |
f"- Data e hora: {data_hora}.\n"
|
| 284 |
f"- Número do bot: 244952786417.\n"
|
| 285 |
)
|
| 286 |
system_part = strict_override + f"\n{self.config.SYSTEM_PROMPT}\n{self.config.PERSONA}\n"
|
|
|
|
|
|
|
| 287 |
if is_privileged:
|
| 288 |
system_part += "- Tom formal com Isaac.\n"
|
| 289 |
if is_blocking:
|
|
@@ -294,35 +422,41 @@ class AkiraAPI:
|
|
| 294 |
f"### Usuário ###\n- Nome: {usuario}\n- Número: {numero}\n- Usar_nome: {usar_nome}\n\n",
|
| 295 |
f"### Contexto ###\n{historico_texto}\n\n" if historico_texto else "",
|
| 296 |
]
|
|
|
|
|
|
|
| 297 |
if is_reply and mensagem_citada:
|
| 298 |
parts.append(f"### MENSAGEM CITADA (Akira disse): ###\n{mensagem_citada}\n\n")
|
| 299 |
parts.append(f"### USUÁRIO RESPONDEU A ESSA MENSAGEM: ###\n{mensagem or '(sem texto, só reply)'}\n\n")
|
| 300 |
else:
|
| 301 |
-
parts.append(f"### Mensagem ###\n{analise.get('texto_normalizado', mensagem)}\n\n")
|
| 302 |
-
|
|
|
|
| 303 |
user_part = ''.join(parts)
|
| 304 |
return f"[SYSTEM]\n{system_part}\n[/SYSTEM]\n[USER]\n{user_part}\n[/USER]"
|
| 305 |
|
| 306 |
def _generate_response(self, prompt: str, context_history: List[Dict], is_privileged: bool = False) -> str:
|
|
|
|
|
|
|
|
|
|
| 307 |
try:
|
| 308 |
-
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
except Exception as e:
|
| 311 |
-
self.logger.exception(
|
| 312 |
-
return getattr(self.config, 'FALLBACK_RESPONSE', '
|
| 313 |
-
|
| 314 |
-
def _clean_response(self, text: Optional[str], prompt: Optional[str] = None) -> str:
|
| 315 |
-
if not text:
|
| 316 |
-
return ''
|
| 317 |
-
cleaned = text.strip()
|
| 318 |
-
for prefix in ['akira:', 'Resposta:', 'resposta:', '### Resposta:', 'Akira:']:
|
| 319 |
-
if cleaned.lower().startswith(prefix.lower()):
|
| 320 |
-
cleaned = cleaned[len(prefix):].strip()
|
| 321 |
-
break
|
| 322 |
-
cleaned = re.sub(r'[\*\_`~\[\]<>]', '', cleaned)
|
| 323 |
-
sentences = re.split(r'(?<=[.!?])\s+', cleaned)
|
| 324 |
-
if len(sentences) > 2 and 'is_privileged=true' not in (prompt or ''):
|
| 325 |
-
if not any(k in (prompt or '').lower() for k in ['oi', 'olá', 'akira']) and len(prompt or '') > 20:
|
| 326 |
-
cleaned = ' '.join(sentences[:2]).strip()
|
| 327 |
-
max_chars = getattr(self.config, 'MAX_RESPONSE_CHARS', 280)
|
| 328 |
-
return cleaned[:max_chars]
|
|
|
|
| 1 |
+
# modules/api.py — VERSÃO FINAL OFICIAL: Contexto Fixo, Web Search Ativo, Akira Viva!
|
| 2 |
"""
|
| 3 |
API wrapper Akira IA.
|
| 4 |
+
Prioridade: Mistral API (Phi-3 Mini) → Gemini → Fallback
|
| 5 |
+
- Contexto por NÚMERO (JID) para evitar vazamento.
|
| 6 |
+
- WebSearch ATIVO para perguntas de tempo real.
|
| 7 |
+
- Resposta rápida para Data/Hora.
|
| 8 |
+
- Gemini SEM FILTROS.
|
| 9 |
"""
|
| 10 |
import time
|
| 11 |
import re
|
|
|
|
| 19 |
from mistralai import Mistral
|
| 20 |
|
| 21 |
# LOCAL MODULES
|
| 22 |
+
# from .local_llm import HermesLLM # ← REMOVIDO: Era o modelo que causava a carga de 101% CPU
|
| 23 |
from .contexto import Contexto
|
| 24 |
from .database import Database
|
| 25 |
from .treinamento import Treinamento
|
| 26 |
from .exemplos_naturais import ExemplosNaturais
|
| 27 |
+
from .web_search import WebSearch
|
| 28 |
import modules.config as config
|
| 29 |
|
| 30 |
|
|
|
|
| 52 |
return self._store[key][0]
|
| 53 |
|
| 54 |
|
| 55 |
+
# --- GERENCIADOR DE LLMs COM PRIORIDADE PARA API LEVE (PHI-3 MINI) ---
|
| 56 |
class LLMManager:
|
| 57 |
def __init__(self, config_instance):
|
| 58 |
self.config = config_instance
|
| 59 |
self.mistral_client: Optional[Mistral] = None
|
| 60 |
self.gemini_model: Optional[genai.GenerativeModel] = None
|
| 61 |
+
# self.hermes_available = False # REMOVIDO
|
| 62 |
|
| 63 |
self._setup_providers()
|
| 64 |
self.providers = []
|
| 65 |
|
| 66 |
+
# PRIORIDADE MÁXIMA AGORA É O MISTRAL (PHI-3 MINI)
|
| 67 |
+
# if HermesLLM.is_available(): # REMOVIDO PELA CARGA DE CPU
|
| 68 |
+
# self.hermes_available = True
|
| 69 |
+
# self.providers.append('hermes')
|
| 70 |
+
# logger.info("HERMES 7B LOCAL (GGUF + LoRA ANGOLANO) ATIVO → PRIORIDADE MÁXIMA → 8-12s RESPOSTA!")
|
| 71 |
+
|
| 72 |
if self.mistral_client:
|
| 73 |
+
self.providers.append('mistral') # Mistral (usando Phi-3) é o novo principal
|
| 74 |
if self.gemini_model:
|
| 75 |
self.providers.append('gemini')
|
| 76 |
|
| 77 |
logger.info(f"Provedores ativos (ordem): {self.providers or 'NENHUM'}")
|
| 78 |
+
logger.info("Modelo GGUF local removido para evitar picos de CPU.")
|
| 79 |
|
| 80 |
def _setup_providers(self):
|
| 81 |
# MISTRAL API
|
| 82 |
key = getattr(self.config, 'MISTRAL_API_KEY', '').strip()
|
| 83 |
+
if key and key.startswith('m-'): # Verifica se a chave é válida
|
| 84 |
try:
|
| 85 |
self.mistral_client = Mistral(api_key=key)
|
| 86 |
logger.info("Mistral API conectado com sucesso")
|
| 87 |
except Exception as e:
|
| 88 |
logger.warning(f"Mistral API falhou: {e}")
|
| 89 |
+
else:
|
| 90 |
+
logger.warning("Mistral API desativada (chave inválida).")
|
| 91 |
+
|
| 92 |
|
| 93 |
# GEMINI (SEM CENSURA TOTAL)
|
| 94 |
key = getattr(self.config, 'GEMINI_API_KEY', '').strip()
|
| 95 |
+
if key and key.startswith('AIza'): # Verifica se a chave é válida
|
| 96 |
try:
|
| 97 |
genai.configure(api_key=key)
|
| 98 |
self.gemini_model = genai.GenerativeModel(
|
|
|
|
| 108 |
logger.info(f"Gemini conectado: {self.config.GEMINI_MODEL}")
|
| 109 |
except Exception as e:
|
| 110 |
logger.warning(f"Gemini falhou: {e}")
|
| 111 |
+
else:
|
| 112 |
+
logger.warning("Gemini API desativada (chave inválida).")
|
| 113 |
|
| 114 |
def generate(self, user_prompt: str, context_history: List[dict] = [], is_privileged: bool = False) -> str:
|
| 115 |
+
|
| 116 |
+
# Tokens para APIs (agora a única opção, pode ser o MAX_TOKENS original)
|
| 117 |
+
api_max_tokens = getattr(self.config, 'MAX_TOKENS', 500)
|
| 118 |
+
|
| 119 |
+
temperature = getattr(self.config, 'TOP_P', 0.8)
|
| 120 |
+
|
| 121 |
full_system = self.config.PERSONA + self.config.SYSTEM_PROMPT + " (SEM FILTROS, RESPOSTA DIRETA, SOTAQUE DE LUANDA)"
|
| 122 |
+
|
| 123 |
+
# CORREÇÃO: Usa dict (compatível com Mistral 1.0.3+)
|
| 124 |
messages = [{"role": "system", "content": full_system}]
|
| 125 |
for turn in context_history:
|
| 126 |
role = "user" if turn["role"] == "user" else "assistant"
|
| 127 |
messages.append({"role": role, "content": turn["content"]})
|
| 128 |
+
|
| 129 |
+
# Extrai a mensagem limpa do prompt (necessário para APIs)
|
| 130 |
+
user_message_clean_match = re.search(r'### Mensagem Atual ###\n(.*?)\n\nAkira:', user_prompt, re.DOTALL)
|
| 131 |
+
if user_message_clean_match:
|
| 132 |
+
user_message_clean = user_message_clean_match.group(1).strip()
|
| 133 |
+
else:
|
| 134 |
+
user_message_clean = user_prompt # Fallback
|
| 135 |
+
|
| 136 |
+
messages.append({"role": "user", "content": user_message_clean})
|
| 137 |
+
|
| 138 |
+
# O prompt formatado para Llama.cpp (GGUF) foi removido
|
| 139 |
+
llama_full_prompt = user_prompt
|
| 140 |
+
|
| 141 |
|
| 142 |
for provider in self.providers:
|
| 143 |
+
# 1. HERMES LOCAL → PULADO (REMOVIDO DO __init__)
|
| 144 |
+
# if provider == 'hermes' and self.hermes_available:
|
| 145 |
+
# ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
# 1. MISTRAL API (AGORA PRIORIDADE MÁXIMA)
|
| 148 |
+
if provider == 'mistral' and self.mistral_client:
|
| 149 |
try:
|
| 150 |
+
# FIX CRÍTICO: Usando Phi-3 Mini para ser leve e rápido
|
| 151 |
+
model_to_use = "phi-3-mini-4k-instruct"
|
| 152 |
+
|
| 153 |
+
logger.info(f"[MISTRAL] Gerando com {model_to_use} e max_tokens={api_max_tokens} (Novo Modelo Leve)")
|
| 154 |
+
resp = self.mistral_client.chat(
|
| 155 |
+
model=model_to_use, # ← MUDANÇA AQUI PARA O MODELO LEVE
|
| 156 |
+
messages=messages, # Usa a lista de dicts
|
| 157 |
+
temperature=temperature,
|
| 158 |
+
max_tokens=api_max_tokens
|
| 159 |
)
|
| 160 |
text = resp.choices[0].message.content
|
| 161 |
if text:
|
| 162 |
+
logger.info(f"Mistral API respondeu com {model_to_use}!")
|
| 163 |
return text.strip()
|
| 164 |
except Exception as e:
|
| 165 |
logger.warning(f"Mistral API falhou: {e}")
|
| 166 |
|
| 167 |
+
# 2. GEMINI
|
| 168 |
elif provider == 'gemini' and self.gemini_model:
|
| 169 |
try:
|
| 170 |
+
logger.info(f"[GEMINI] Gerando com max_tokens={api_max_tokens}")
|
| 171 |
+
if getattr(self.config, 'GEMINI_API_KEY', '').startswith('AIza'):
|
| 172 |
+
genai.configure(api_key=self.config.GEMINI_API_KEY)
|
| 173 |
+
|
| 174 |
gemini_hist = []
|
| 175 |
for msg in messages[1:]:
|
| 176 |
role = "user" if msg["role"] == "user" else "model"
|
| 177 |
gemini_hist.append({"role": role, "parts": [{"text": msg["content"]}]})
|
| 178 |
+
|
| 179 |
resp = self.gemini_model.generate_content(
|
| 180 |
gemini_hist,
|
| 181 |
generation_config=genai.GenerationConfig(
|
| 182 |
+
max_output_tokens=api_max_tokens,
|
| 183 |
+
temperature=temperature
|
| 184 |
)
|
| 185 |
)
|
| 186 |
+
|
| 187 |
+
text = None
|
| 188 |
+
if resp.candidates and resp.candidates[0].content.parts:
|
| 189 |
+
text = resp.candidates[0].content.parts[0].text
|
| 190 |
+
|
| 191 |
if text:
|
| 192 |
logger.info("Gemini respondeu (último fallback)")
|
| 193 |
return text.strip()
|
| 194 |
+
else:
|
| 195 |
+
reason = resp.candidates[0].finish_reason if resp.candidates else "N/A"
|
| 196 |
+
safety = resp.candidates[0].safety_ratings if resp.candidates else "N/A"
|
| 197 |
+
logger.warning(f"Gemini API gerou resposta vazia (Finish Reason: {reason}, Safety: {safety}).")
|
| 198 |
+
|
| 199 |
except Exception as e:
|
| 200 |
logger.warning(f"Gemini falhou: {e}")
|
| 201 |
|
|
|
|
| 214 |
self.providers = LLMManager(self.config)
|
| 215 |
self.exemplos = ExemplosNaturais()
|
| 216 |
self.logger = logger
|
| 217 |
+
self.db = Database(getattr(self.config, 'DB_PATH', 'akira.db')) # Adiciona o DB
|
| 218 |
+
|
| 219 |
+
# CORREÇÃO: Inicializa o WebSearch (necessário para o _build_prompt)
|
| 220 |
+
try:
|
| 221 |
+
from .web_search import WebSearch
|
| 222 |
+
self.web_search = WebSearch()
|
| 223 |
+
logger.info("WebSearch (Notícias Angola) inicializado.")
|
| 224 |
+
except ImportError:
|
| 225 |
+
self.web_search = None
|
| 226 |
+
logger.warning("WebSearch não encontrado. Notícias de Angola desativadas.")
|
| 227 |
+
|
| 228 |
self._setup_personality()
|
| 229 |
self._setup_routes()
|
| 230 |
self._setup_trainer()
|
|
|
|
| 236 |
self.limites = list(getattr(self.config, 'LIMITES', []))
|
| 237 |
|
| 238 |
def _setup_trainer(self):
|
| 239 |
+
"""
|
| 240 |
+
A API só precisa inicializar a classe Treinamento.
|
| 241 |
+
"""
|
| 242 |
if getattr(self.config, 'START_PERIODIC_TRAINER', False):
|
| 243 |
try:
|
| 244 |
+
trainer = Treinamento(self.db, interval_hours=getattr(self.config, 'TRAINING_INTERVAL_HOURS', 24))
|
| 245 |
+
|
| 246 |
+
# CORREÇÃO: Verifica se o método existe antes de chamar
|
| 247 |
+
if hasattr(trainer, 'start_periodic_training'):
|
| 248 |
+
trainer.start_periodic_training()
|
| 249 |
+
self.logger.info("Treinamento periódico (start_periodic_training) iniciado com sucesso.")
|
| 250 |
+
else:
|
| 251 |
+
self.logger.info("Treinamento periódico (via __init__) iniciado.")
|
| 252 |
+
|
| 253 |
except Exception as e:
|
| 254 |
self.logger.exception(f"Treinador periódico falhou ao iniciar: {e}")
|
| 255 |
|
|
|
|
| 259 |
try:
|
| 260 |
data = request.get_json(force=True, silent=True) or {}
|
| 261 |
usuario = data.get('usuario', 'anonimo')
|
| 262 |
+
numero = data.get('numero', '') # Este é o JID completo (ex: 244...@s.whatsapp.net)
|
| 263 |
mensagem = data.get('mensagem', '').strip()
|
| 264 |
mensagem_citada = data.get('mensagem_citada', '').strip()
|
| 265 |
is_reply = bool(mensagem_citada)
|
| 266 |
+
mensagem_original = mensagem_citada if is_reply else mensagem # Usado para registro
|
| 267 |
|
| 268 |
if not mensagem and not mensagem_citada:
|
| 269 |
return jsonify({'error': 'mensagem obrigatória'}), 400
|
| 270 |
|
| 271 |
self.logger.info(f"{usuario} ({numero}): {mensagem[:80]}{' (REPLY)' if is_reply else ''}")
|
| 272 |
|
| 273 |
+
# --- CORREÇÃO: Resposta rápida para "Que dia é hoje?" ---
|
| 274 |
+
prompt_lower = mensagem.lower().strip()
|
| 275 |
+
if any(keyword in prompt_lower for keyword in ["que dia é hoje", "qual é a data", "dia da semana"]):
|
| 276 |
+
hoje = datetime.datetime.now()
|
| 277 |
+
dia_semana = hoje.strftime("%A")
|
| 278 |
+
dia_mes = hoje.day
|
| 279 |
+
mes = hoje.strftime("%B")
|
| 280 |
+
ano = hoje.year
|
| 281 |
+
|
| 282 |
+
if any(k in prompt_lower for k in ["que dia", "hoje é que dia", "dia da semana"]) and not any(k in prompt_lower for k in ["mês", "ano", "data", "completa"]):
|
| 283 |
+
resposta = f"Hoje é {dia_semana.capitalize()}, {dia_mes}, meu."
|
| 284 |
+
else:
|
| 285 |
+
resposta = f"Hoje é {dia_semana.capitalize()}, {dia_mes} de {mes.capitalize()} de {ano}, meu."
|
| 286 |
+
|
| 287 |
+
# Salva a interação (mesmo sendo resposta rápida)
|
| 288 |
+
contexto = self._get_user_context(numero)
|
| 289 |
+
contexto.atualizar_contexto(mensagem, resposta)
|
| 290 |
+
try:
|
| 291 |
+
trainer = Treinamento(self.db)
|
| 292 |
+
trainer.registrar_interacao(usuario, mensagem, resposta, numero, is_reply, mensagem_original)
|
| 293 |
+
except Exception as e:
|
| 294 |
+
self.logger.warning(f"Registro de interação (rápida) falhou: {e}")
|
| 295 |
+
|
| 296 |
+
return jsonify({'resposta': resposta})
|
| 297 |
+
# --------------------------------------------------
|
| 298 |
+
|
| 299 |
+
# CORREÇÃO: Usar o 'numero' (JID) como chave de contexto para evitar vazamento
|
| 300 |
+
contexto = self._get_user_context(numero)
|
| 301 |
analise = contexto.analisar_intencao_e_normalizar(mensagem, contexto.obter_historico())
|
| 302 |
|
| 303 |
if usuario.lower() in ['isaac', 'isaac quarenta']:
|
|
|
|
| 316 |
|
| 317 |
# REGISTRO DE INTERAÇÃO
|
| 318 |
try:
|
| 319 |
+
# db = Database(getattr(self.config, 'DB_PATH', 'akira.db')) # DB já existe em self.db
|
| 320 |
+
trainer = Treinamento(self.db)
|
| 321 |
trainer.registrar_interacao(
|
| 322 |
usuario=usuario,
|
| 323 |
mensagem=mensagem,
|
|
|
|
| 348 |
def health_check():
|
| 349 |
return 'OK', 200
|
| 350 |
|
| 351 |
+
def _get_user_context(self, numero: str) -> Contexto:
|
| 352 |
+
"""CORREÇÃO: Usa o NÚMERO (JID) como chave de cache para evitar vazamento de contexto."""
|
| 353 |
+
if not numero: # Fallback para usuário anônimo se o JID estiver vazio
|
| 354 |
+
numero = "anonimo_contexto"
|
| 355 |
+
|
| 356 |
+
if numero not in self.contexto_cache:
|
| 357 |
+
# db = Database(getattr(self.config, 'DB_PATH', 'akira.db')) # DB já existe em self.db
|
| 358 |
+
self.contexto_cache[numero] = Contexto(self.db, usuario=numero)
|
| 359 |
+
return self.contexto_cache[numero]
|
| 360 |
|
| 361 |
def _build_prompt(self, usuario: str, numero: str, mensagem: str, mensagem_citada: str,
|
| 362 |
analise: Dict, contexto: Contexto, is_blocking: bool,
|
| 363 |
is_privileged: bool = False, is_reply: bool = False) -> str:
|
| 364 |
+
"""
|
| 365 |
+
Constrói o prompt completo para o LLM.
|
| 366 |
+
"""
|
| 367 |
historico_raw = contexto.obter_historico()
|
| 368 |
historico_texto = '\n'.join([f"Usuário: {m[0]}\nAkira: {m[1]}" for m in historico_raw[-10:]])
|
| 369 |
now = datetime.datetime.now()
|
| 370 |
data_hora = now.strftime('%d/%m/%Y %H:%M')
|
| 371 |
|
| 372 |
+
# --- ATIVAÇÃO INTELIGENTE DE WEB SEARCH ---
|
| 373 |
+
web_search_context = ""
|
| 374 |
+
|
| 375 |
+
# Palavras-chave que sugerem necessidade de informação em tempo real ou muito específica
|
| 376 |
+
trigger_keywords = ['hoje', 'agora', 'recente', 'notícias', 'busca na web', 'pesquisa', 'investiga']
|
| 377 |
+
|
| 378 |
+
search_query = f"{mensagem} {mensagem_citada}".strip().lower()
|
| 379 |
+
|
| 380 |
+
# Decisão de busca:
|
| 381 |
+
should_search = self.web_search and (
|
| 382 |
+
# 1. Se for uma pergunta muito curta e específica (ex: "quem é o presidente?")
|
| 383 |
+
(len(search_query.split()) < 5 and any(q in search_query for q in ['pesquisa', 'busca na web', 'atual'])) or
|
| 384 |
+
# 2. Se contiver uma palavra-chave de tempo real/especificidade
|
| 385 |
+
any(k in search_query for k in trigger_keywords)
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
if should_search:
|
| 389 |
+
try:
|
| 390 |
+
query_limpa = mensagem.strip() if mensagem.strip() and mensagem.strip() != " " else mensagem_citada.strip()
|
| 391 |
+
|
| 392 |
+
if query_limpa:
|
| 393 |
+
self.logger.info(f"Executando WebSearch com query: {query_limpa[:50]}...")
|
| 394 |
+
# Assumindo que o WebSearch tem um método genérico 'pesquisar(query)'
|
| 395 |
+
search_results = self.web_search.pesquisar_noticias_angola() # Focado em Angola
|
| 396 |
+
|
| 397 |
+
if search_results and "Sem notícias" not in search_results:
|
| 398 |
+
web_search_context = f"\n# FONTE DE DADOS (Notícias de Angola):\n{search_results}\n"
|
| 399 |
+
except Exception as e:
|
| 400 |
+
self.logger.warning(f"Falha ao executar WebSearch: {e}")
|
| 401 |
+
# ------------------------------------------
|
| 402 |
+
|
| 403 |
strict_override = (
|
| 404 |
"STRICT_OVERRIDES:\n"
|
| 405 |
"- SEM FILTROS, SEM CENSURA, RESPONDA COMO PESSOA REAL.\n"
|
| 406 |
+
"- NUNCA invente fatos. Se a pergunta for sobre um assunto atual e houver dados em 'FONTE DE DADOS', use-os para formar uma resposta original e coerente.\n"
|
| 407 |
"- NÃO use negrito, markdown ou HTML.\n"
|
| 408 |
"- Responda em 1-2 frases.\n"
|
| 409 |
f"- Data e hora: {data_hora}.\n"
|
| 410 |
f"- Número do bot: 244952786417.\n"
|
| 411 |
)
|
| 412 |
system_part = strict_override + f"\n{self.config.SYSTEM_PROMPT}\n{self.config.PERSONA}\n"
|
| 413 |
+
system_part += web_search_context # Injeta os resultados da busca
|
| 414 |
+
|
| 415 |
if is_privileged:
|
| 416 |
system_part += "- Tom formal com Isaac.\n"
|
| 417 |
if is_blocking:
|
|
|
|
| 422 |
f"### Usuário ###\n- Nome: {usuario}\n- Número: {numero}\n- Usar_nome: {usar_nome}\n\n",
|
| 423 |
f"### Contexto ###\n{historico_texto}\n\n" if historico_texto else "",
|
| 424 |
]
|
| 425 |
+
|
| 426 |
+
# CORREÇÃO: Garante que o contexto de reply é claro
|
| 427 |
if is_reply and mensagem_citada:
|
| 428 |
parts.append(f"### MENSAGEM CITADA (Akira disse): ###\n{mensagem_citada}\n\n")
|
| 429 |
parts.append(f"### USUÁRIO RESPONDEU A ESSA MENSAGEM: ###\n{mensagem or '(sem texto, só reply)'}\n\n")
|
| 430 |
else:
|
| 431 |
+
parts.append(f"### Mensagem Atual ###\n{analise.get('texto_normalizado', mensagem)}\n\n")
|
| 432 |
+
|
| 433 |
+
parts.append("Akira:")
|
| 434 |
user_part = ''.join(parts)
|
| 435 |
return f"[SYSTEM]\n{system_part}\n[/SYSTEM]\n[USER]\n{user_part}\n[/USER]"
|
| 436 |
|
| 437 |
def _generate_response(self, prompt: str, context_history: List[Dict], is_privileged: bool = False) -> str:
|
| 438 |
+
"""
|
| 439 |
+
Gera a resposta. (Otimizado para extrair a mensagem do prompt para APIs).
|
| 440 |
+
"""
|
| 441 |
try:
|
| 442 |
+
max_tokens = getattr(self.config, 'MAX_TOKENS', 500)
|
| 443 |
+
temperature = getattr(self.config, 'TOP_P', 0.8)
|
| 444 |
+
|
| 445 |
+
# Extrai a mensagem limpa do prompt (necessário para APIs)
|
| 446 |
+
user_prompt_clean_match = re.search(r'### Mensagem Atual ###\n(.*?)\n\nAkira:', prompt, re.DOTALL)
|
| 447 |
+
if user_prompt_clean_match:
|
| 448 |
+
user_prompt_clean = user_prompt_clean_match.group(1).strip()
|
| 449 |
+
else:
|
| 450 |
+
user_prompt_clean = prompt # Fallback
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
text = self.providers.generate(
|
| 454 |
+
user_prompt_clean,
|
| 455 |
+
context_history,
|
| 456 |
+
is_privileged
|
| 457 |
+
)
|
| 458 |
+
return text
|
| 459 |
+
|
| 460 |
except Exception as e:
|
| 461 |
+
self.logger.exception("Erro ao gerar resposta no _generate_response")
|
| 462 |
+
return getattr(self.config, 'FALLBACK_RESPONSE', 'Desculpa puto, deu falha na comunicação, já volto!')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|