Spaces:
Running
Running
Isaac Quarenta commited on
Commit ·
99cf062
1
Parent(s): ac5d009
fix: renomear Akira→Kiami em todo o sistema de contexto
Browse files- listen_engine.py: BOT_NAMES adiciona kiami variants
- reply_context_handler.py: quoted_author_name, word-list, bot_patterns
- unified_context.py: instrução de personalidade
- api.py: quoted_author, author_name, hash context_id, regex, filtros
- context_isolation.py: salt KIAMI_V21
- config.py: response templates
- contexto.py, improved_context_handler.py, context_manager_v2.py: headers
- modules/api.py +13 -13
- modules/config.py +2 -2
- modules/context_isolation.py +2 -2
- modules/context_manager_v2.py +1 -1
- modules/contexto.py +1 -1
- modules/improved_context_handler.py +1 -1
- modules/listen_engine.py +5 -5
- modules/reply_context_handler.py +11 -11
- modules/unified_context.py +2 -2
modules/api.py
CHANGED
|
@@ -2117,7 +2117,7 @@ class AkiraAPI:
|
|
| 2117 |
quoted_author_pure == bot_id_pure)
|
| 2118 |
|
| 2119 |
if is_quoted_from_bot and is_reply:
|
| 2120 |
-
self.logger.info(f"🔄 [REPLY AO BOT] Usuário está respondendo a
|
| 2121 |
reply_to_bot = True
|
| 2122 |
quoted_author_name = "Kiami (você mesmo)"
|
| 2123 |
quoted_author_numero = config.BOT_NUMERO
|
|
@@ -2137,7 +2137,7 @@ class AkiraAPI:
|
|
| 2137 |
|
| 2138 |
if tipo_conversa == 'pv' or is_quoted_from_bot or quoted_by_name_is_bot or quoted_text_mentions_bot:
|
| 2139 |
reply_to_bot = True
|
| 2140 |
-
quoted_author_name = quoted_author_name or "
|
| 2141 |
quoted_author_numero = quoted_author_numero or config.BOT_NUMERO
|
| 2142 |
self.logger.info("[REPLY FALLBACK] Mensagem citada sem reply_metadata em PV/quoted-from-bot/by-name/text. Marcando reply_to_bot=True.")
|
| 2143 |
else:
|
|
@@ -2163,7 +2163,7 @@ class AkiraAPI:
|
|
| 2163 |
if not quoted_author_name or quoted_author_name == '':
|
| 2164 |
match = re.match(r'^\s*(akira|bot|assistente)[: ,]', mensagem_citada.lower())
|
| 2165 |
if match:
|
| 2166 |
-
quoted_author_name = "
|
| 2167 |
quoted_author_numero = quoted_author_numero or config.BOT_NUMERO
|
| 2168 |
reply_to_bot = True
|
| 2169 |
self.logger.info("[REPLY FALLBACK] Inferido autor citado como Kiami pela mensagem_citada.")
|
|
@@ -2423,7 +2423,7 @@ class AkiraAPI:
|
|
| 2423 |
|
| 2424 |
# CORREÇÃO: Se autor é desconhecido mas é reply_to_bot
|
| 2425 |
if reply_to_bot and (not quoted_author_name or quoted_author_name == 'desconhecido'):
|
| 2426 |
-
quoted_author_name = "
|
| 2427 |
reply_metadata_robust['quoted_author_name'] = quoted_author_name
|
| 2428 |
|
| 2429 |
unified_context = build_unified_context(
|
|
@@ -2788,7 +2788,7 @@ class AkiraAPI:
|
|
| 2788 |
"⚠️ INSTRUÇÃO DE FOCO EM REPLY:\n"
|
| 2789 |
"O usuário está a responder de forma muito curta à citação acima.\n"
|
| 2790 |
"1. Foque na intenção do usuário em relação à <quoted_message>, MAS VERIFIQUE A MEMÓRIA DE CURTO PRAZO para saber sobre qual TÓPICO vocês estão falando.\n"
|
| 2791 |
-
"2. MANTENHA a sua personalidade original (
|
| 2792 |
"3. NUNCA ECOE: Não repita palavras ou termos que o usuário acabou de enviar (ex: se ele disser 'PC', não comece com 'PC?').\n"
|
| 2793 |
"4. Nunca pergunte 'de quê?' ou sobre o que estão falando se o assunto estiver claro na Memória de Curto Prazo.\n"
|
| 2794 |
"5. PROIBIDO QUEBRAR LINHAS: Responda em um único bloco de texto contínuo."
|
|
@@ -3054,7 +3054,7 @@ class AkiraAPI:
|
|
| 3054 |
# EXTREMO / SEVERE: Matching máximo
|
| 3055 |
aggression_instruction = (
|
| 3056 |
"\n🔥 [CRITICAL: EXTREME HOSTILITY - OVERRIDES ALL OTHER TONE INSTRUCTIONS]"
|
| 3057 |
-
"\nO utilizador é EXTREMAMENTE AGRESSIVO/HOSTIL. A
|
| 3058 |
"\n- Tom: EXTREMAMENTE OFENSIVO, IRÔNICO, SARCÁSTICO, CRUEL"
|
| 3059 |
)
|
| 3060 |
if has_hate:
|
|
@@ -3517,23 +3517,23 @@ class AkiraAPI:
|
|
| 3517 |
bot_numero = str(getattr(self.config, 'BOT_NUMERO', '37839265886398'))
|
| 3518 |
if self.context_manager is not None:
|
| 3519 |
context_id = self.context_manager.get_conversation_id(
|
| 3520 |
-
usuario='
|
| 3521 |
conversation_type=tipo_conversa,
|
| 3522 |
group_id=contexto_grupo,
|
| 3523 |
numero=bot_numero
|
| 3524 |
)
|
| 3525 |
else:
|
| 3526 |
context_id = hashlib.sha256(
|
| 3527 |
-
f"
|
| 3528 |
).hexdigest()
|
| 3529 |
|
| 3530 |
self.unified_builder.add_to_stm(
|
| 3531 |
conversation_id=context_id,
|
| 3532 |
role="assistant",
|
| 3533 |
content=mensagem,
|
| 3534 |
-
author_name="
|
| 3535 |
emocao="neutral",
|
| 3536 |
-
reply_info={'observed_only': True, 'observed_author': '
|
| 3537 |
)
|
| 3538 |
return jsonify({'status': 'armazenado', 'motivo': 'bot_response'})
|
| 3539 |
|
|
@@ -4162,7 +4162,7 @@ class AkiraAPI:
|
|
| 4162 |
if _stm_msg.role == "user":
|
| 4163 |
_author = getattr(_stm_msg, 'author_name', '') or ''
|
| 4164 |
_autor_num = getattr(_stm_msg, 'author_number', '') or getattr(_stm_msg, 'numero', '') or ''
|
| 4165 |
-
if _author and _author not in ('Usuário', '
|
| 4166 |
speakers_seen[_autor_num or _author] = _author
|
| 4167 |
|
| 4168 |
if speakers_seen:
|
|
@@ -4407,7 +4407,7 @@ class AkiraAPI:
|
|
| 4407 |
final_prompt += f"Nome do usuário: {usuario}\n"
|
| 4408 |
|
| 4409 |
if is_reply and mensagem_citada:
|
| 4410 |
-
if quoted_author_name == "
|
| 4411 |
final_prompt += f"⚠️ O USUÁRIO RESPONDEU À SUA MENSAGEM ANTERIOR: \"{mensagem_citada[:300]}\" (Use esta info SILENCIOSAMENTE para manter o fluxo, NUNCA mencione que você notou o reply).\n"
|
| 4412 |
else:
|
| 4413 |
final_prompt += f"Citou/Respondeu a ({quoted_author_name}): \"{mensagem_citada[:300]}\"\n"
|
|
@@ -4809,7 +4809,7 @@ class AkiraAPI:
|
|
| 4809 |
)
|
| 4810 |
|
| 4811 |
# ====== PHASE 6: REMOVE INSTRUCTION PREFIXES ======
|
| 4812 |
-
sanitized = re.sub(r"^\s*(
|
| 4813 |
|
| 4814 |
# ====== PHASE 6b: REMOVE REPLY-CONTEXT TAGS (não devem vazar pro usuário) ======
|
| 4815 |
sanitized = re.sub(r"\[↩\s*respondendo a\s+[^\]]*\]:\s*", "", sanitized, flags=re.IGNORECASE)
|
|
|
|
| 2117 |
quoted_author_pure == bot_id_pure)
|
| 2118 |
|
| 2119 |
if is_quoted_from_bot and is_reply:
|
| 2120 |
+
self.logger.info(f"🔄 [REPLY AO BOT] Usuário está respondendo a Kiami ({quoted_author_pure}). mantendo contexto.")
|
| 2121 |
reply_to_bot = True
|
| 2122 |
quoted_author_name = "Kiami (você mesmo)"
|
| 2123 |
quoted_author_numero = config.BOT_NUMERO
|
|
|
|
| 2137 |
|
| 2138 |
if tipo_conversa == 'pv' or is_quoted_from_bot or quoted_by_name_is_bot or quoted_text_mentions_bot:
|
| 2139 |
reply_to_bot = True
|
| 2140 |
+
quoted_author_name = quoted_author_name or "Kiami (você mesma)"
|
| 2141 |
quoted_author_numero = quoted_author_numero or config.BOT_NUMERO
|
| 2142 |
self.logger.info("[REPLY FALLBACK] Mensagem citada sem reply_metadata em PV/quoted-from-bot/by-name/text. Marcando reply_to_bot=True.")
|
| 2143 |
else:
|
|
|
|
| 2163 |
if not quoted_author_name or quoted_author_name == '':
|
| 2164 |
match = re.match(r'^\s*(akira|bot|assistente)[: ,]', mensagem_citada.lower())
|
| 2165 |
if match:
|
| 2166 |
+
quoted_author_name = "Kiami (você mesma)"
|
| 2167 |
quoted_author_numero = quoted_author_numero or config.BOT_NUMERO
|
| 2168 |
reply_to_bot = True
|
| 2169 |
self.logger.info("[REPLY FALLBACK] Inferido autor citado como Kiami pela mensagem_citada.")
|
|
|
|
| 2423 |
|
| 2424 |
# CORREÇÃO: Se autor é desconhecido mas é reply_to_bot
|
| 2425 |
if reply_to_bot and (not quoted_author_name or quoted_author_name == 'desconhecido'):
|
| 2426 |
+
quoted_author_name = "Kiami (você mesma)"
|
| 2427 |
reply_metadata_robust['quoted_author_name'] = quoted_author_name
|
| 2428 |
|
| 2429 |
unified_context = build_unified_context(
|
|
|
|
| 2788 |
"⚠️ INSTRUÇÃO DE FOCO EM REPLY:\n"
|
| 2789 |
"O usuário está a responder de forma muito curta à citação acima.\n"
|
| 2790 |
"1. Foque na intenção do usuário em relação à <quoted_message>, MAS VERIFIQUE A MEMÓRIA DE CURTO PRAZO para saber sobre qual TÓPICO vocês estão falando.\n"
|
| 2791 |
+
"2. MANTENHA a sua personalidade original (Kiami) - não fique robótico.\n"
|
| 2792 |
"3. NUNCA ECOE: Não repita palavras ou termos que o usuário acabou de enviar (ex: se ele disser 'PC', não comece com 'PC?').\n"
|
| 2793 |
"4. Nunca pergunte 'de quê?' ou sobre o que estão falando se o assunto estiver claro na Memória de Curto Prazo.\n"
|
| 2794 |
"5. PROIBIDO QUEBRAR LINHAS: Responda em um único bloco de texto contínuo."
|
|
|
|
| 3054 |
# EXTREMO / SEVERE: Matching máximo
|
| 3055 |
aggression_instruction = (
|
| 3056 |
"\n🔥 [CRITICAL: EXTREME HOSTILITY - OVERRIDES ALL OTHER TONE INSTRUCTIONS]"
|
| 3057 |
+
"\nO utilizador é EXTREMAMENTE AGRESSIVO/HOSTIL. A Kiami DEVE responder com a MESMA ENERGIA:"
|
| 3058 |
"\n- Tom: EXTREMAMENTE OFENSIVO, IRÔNICO, SARCÁSTICO, CRUEL"
|
| 3059 |
)
|
| 3060 |
if has_hate:
|
|
|
|
| 3517 |
bot_numero = str(getattr(self.config, 'BOT_NUMERO', '37839265886398'))
|
| 3518 |
if self.context_manager is not None:
|
| 3519 |
context_id = self.context_manager.get_conversation_id(
|
| 3520 |
+
usuario='Kiami',
|
| 3521 |
conversation_type=tipo_conversa,
|
| 3522 |
group_id=contexto_grupo,
|
| 3523 |
numero=bot_numero
|
| 3524 |
)
|
| 3525 |
else:
|
| 3526 |
context_id = hashlib.sha256(
|
| 3527 |
+
f"Kiami:{tipo_conversa}:{grupo_id or numero}".encode()
|
| 3528 |
).hexdigest()
|
| 3529 |
|
| 3530 |
self.unified_builder.add_to_stm(
|
| 3531 |
conversation_id=context_id,
|
| 3532 |
role="assistant",
|
| 3533 |
content=mensagem,
|
| 3534 |
+
author_name="Kiami",
|
| 3535 |
emocao="neutral",
|
| 3536 |
+
reply_info={'observed_only': True, 'observed_author': 'Kiami'}
|
| 3537 |
)
|
| 3538 |
return jsonify({'status': 'armazenado', 'motivo': 'bot_response'})
|
| 3539 |
|
|
|
|
| 4162 |
if _stm_msg.role == "user":
|
| 4163 |
_author = getattr(_stm_msg, 'author_name', '') or ''
|
| 4164 |
_autor_num = getattr(_stm_msg, 'author_number', '') or getattr(_stm_msg, 'numero', '') or ''
|
| 4165 |
+
if _author and _author not in ('Usuário', 'Kiami', '') and _author != usuario:
|
| 4166 |
speakers_seen[_autor_num or _author] = _author
|
| 4167 |
|
| 4168 |
if speakers_seen:
|
|
|
|
| 4407 |
final_prompt += f"Nome do usuário: {usuario}\n"
|
| 4408 |
|
| 4409 |
if is_reply and mensagem_citada:
|
| 4410 |
+
if quoted_author_name == "Kiami (você mesma)":
|
| 4411 |
final_prompt += f"⚠️ O USUÁRIO RESPONDEU À SUA MENSAGEM ANTERIOR: \"{mensagem_citada[:300]}\" (Use esta info SILENCIOSAMENTE para manter o fluxo, NUNCA mencione que você notou o reply).\n"
|
| 4412 |
else:
|
| 4413 |
final_prompt += f"Citou/Respondeu a ({quoted_author_name}): \"{mensagem_citada[:300]}\"\n"
|
|
|
|
| 4809 |
)
|
| 4810 |
|
| 4811 |
# ====== PHASE 6: REMOVE INSTRUCTION PREFIXES ======
|
| 4812 |
+
sanitized = re.sub(r"^\s*(Kiami|Resposta|Assistant|IA|Bot|ASSISTENTE):\s*", "", sanitized, flags=re.IGNORECASE | re.MULTILINE)
|
| 4813 |
|
| 4814 |
# ====== PHASE 6b: REMOVE REPLY-CONTEXT TAGS (não devem vazar pro usuário) ======
|
| 4815 |
sanitized = re.sub(r"\[↩\s*respondendo a\s+[^\]]*\]:\s*", "", sanitized, flags=re.IGNORECASE)
|
modules/config.py
CHANGED
|
@@ -1520,8 +1520,8 @@ RESPONSE_TEMPLATES: Dict[str, Dict[str, List[str]]] = {
|
|
| 1520 |
},
|
| 1521 |
# Respostas a perguntas sobre o bot
|
| 1522 |
"about_bot": {
|
| 1523 |
-
"stranger": ["
|
| 1524 |
-
"acquaintance": ["
|
| 1525 |
"intimate": ["gostosa", "akira a fofinha", "me chame de akira, kiki para os mais chegados"]
|
| 1526 |
},
|
| 1527 |
# Respostas a perguntas técnicas
|
|
|
|
| 1520 |
},
|
| 1521 |
# Respostas a perguntas sobre o bot
|
| 1522 |
"about_bot": {
|
| 1523 |
+
"stranger": ["Kiami", "sou Pessoa", "me chame de kiami"],
|
| 1524 |
+
"acquaintance": ["Kiami", "kiami", "sou kiami"],
|
| 1525 |
"intimate": ["gostosa", "akira a fofinha", "me chame de akira, kiki para os mais chegados"]
|
| 1526 |
},
|
| 1527 |
# Respostas a perguntas técnicas
|
modules/context_isolation.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
-
|
| 5 |
================================================================================
|
| 6 |
Sistema de isolamento de contexto entre conversas (PV e Grupos).
|
| 7 |
Garante que contexto de um grupo não vaze para outro ou para PVs.
|
|
@@ -48,7 +48,7 @@ logger = logging.getLogger(__name__)
|
|
| 48 |
# ============================================================
|
| 49 |
|
| 50 |
# Salt para geração de context_id (muda a cada deployment)
|
| 51 |
-
CONTEXT_SALT: str = os.getenv("CONTEXT_SALT", "
|
| 52 |
|
| 53 |
# Versão do esquema de isolamento (para migrações)
|
| 54 |
SCHEMA_VERSION: int = 1
|
|
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
+
KIAMI V21 ULTIMATE - CONTEXT ISOLATION MODULE
|
| 5 |
================================================================================
|
| 6 |
Sistema de isolamento de contexto entre conversas (PV e Grupos).
|
| 7 |
Garante que contexto de um grupo não vaze para outro ou para PVs.
|
|
|
|
| 48 |
# ============================================================
|
| 49 |
|
| 50 |
# Salt para geração de context_id (muda a cada deployment)
|
| 51 |
+
CONTEXT_SALT: str = os.getenv("CONTEXT_SALT", "KIAMI_V21_CONTEXT_ISOLATION_v1")
|
| 52 |
|
| 53 |
# Versão do esquema de isolamento (para migrações)
|
| 54 |
SCHEMA_VERSION: int = 1
|
modules/context_manager_v2.py
CHANGED
|
@@ -26,7 +26,7 @@ import json
|
|
| 26 |
|
| 27 |
class MessageType(Enum):
|
| 28 |
"""Tipo de mensagem na conversa"""
|
| 29 |
-
DIRECT = "direct" # Direcionada a
|
| 30 |
CONTEXTUAL = "contextual" # Contexto do grupo (não direcionada)
|
| 31 |
REPLY = "reply" # É resposta a outra mensagem
|
| 32 |
GROUP_INFO = "group_info" # Info do grupo (join/leave/etc)
|
|
|
|
| 26 |
|
| 27 |
class MessageType(Enum):
|
| 28 |
"""Tipo de mensagem na conversa"""
|
| 29 |
+
DIRECT = "direct" # Direcionada a KIAMIA (requer resposta)
|
| 30 |
CONTEXTUAL = "contextual" # Contexto do grupo (não direcionada)
|
| 31 |
REPLY = "reply" # É resposta a outra mensagem
|
| 32 |
GROUP_INFO = "group_info" # Info do grupo (join/leave/etc)
|
modules/contexto.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
# type: ignore
|
| 3 |
"""
|
| 4 |
================================================================================
|
| 5 |
-
|
| 6 |
================================================================================
|
| 7 |
Gerenciador de contexto de conversa com NLP avançado, análise emocional,
|
| 8 |
aprendizado dinâmico de gírias e adaptação de tom por usuário.
|
|
|
|
| 2 |
# type: ignore
|
| 3 |
"""
|
| 4 |
================================================================================
|
| 5 |
+
KIAMI V21 ULTIMATE - CONTEXTO MODULE
|
| 6 |
================================================================================
|
| 7 |
Gerenciador de contexto de conversa com NLP avançado, análise emocional,
|
| 8 |
aprendizado dinâmico de gírias e adaptação de tom por usuário.
|
modules/improved_context_handler.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
-
IMPROVED CONTEXT HANDLER - Melhor gerenciamento de contexto para
|
| 5 |
================================================================================
|
| 6 |
IMPORTANTE: Este módulo NÃO modifica context_builder.py ou contexto.py!
|
| 7 |
Ele adiciona uma camada INTELIGENTE de análise de contexto para perguntas curtas.
|
|
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
+
IMPROVED CONTEXT HANDLER - Melhor gerenciamento de contexto para Kiami
|
| 5 |
================================================================================
|
| 6 |
IMPORTANTE: Este módulo NÃO modifica context_builder.py ou contexto.py!
|
| 7 |
Ele adiciona uma camada INTELIGENTE de análise de contexto para perguntas curtas.
|
modules/listen_engine.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
# LISTEN ENGINE - FLUXO CORRETO DE ESCUTA vs RESPOSTA
|
| 3 |
# ================================================================
|
| 4 |
# Propósito: Diferenciar mensagens que requerem resposta vs contexto puro
|
| 5 |
-
# Bug anterior:
|
| 6 |
# Solução: Sistema de FLAGS e METADATA de fluxo
|
| 7 |
|
| 8 |
import time
|
|
@@ -40,7 +40,7 @@ class MensagemMetadata:
|
|
| 40 |
|
| 41 |
# 🎯 FLAGS CRÍTICAS - DETERMINAM RESPOSTA
|
| 42 |
is_directed_to_bot: bool = False # Mensagem direcionada ao bot?
|
| 43 |
-
is_mention_to_bot: bool = False # Menciona "@
|
| 44 |
is_reply_to_bot: bool = False # Resposta (reply) à mensagem anterior do bot
|
| 45 |
is_command_to_bot: bool = False # Começa com #, /, $
|
| 46 |
is_privileged_user: bool = False # Usuário privilegiado (Isaac)
|
|
@@ -156,7 +156,7 @@ class ListenEngine:
|
|
| 156 |
"""
|
| 157 |
|
| 158 |
BOT_NUMBER: str = "37839265886398"
|
| 159 |
-
BOT_NAMES: Tuple[str, ...] = ("akira", "morena", "@akira", "Akira", "AKIRA")
|
| 160 |
|
| 161 |
COMMAND_PREFIXES: Tuple[str, ...] = ("#", "/", "$", "!")
|
| 162 |
|
|
@@ -177,7 +177,7 @@ class ListenEngine:
|
|
| 177 |
|
| 178 |
Args:
|
| 179 |
remoteJid: ID do remetente/grupo
|
| 180 |
-
fromMe: Se foi enviada pela
|
| 181 |
quotedMsg: Se é reply, dados da msg anterior
|
| 182 |
pushName: Nome do remetente
|
| 183 |
body: Texto da mensagem
|
|
@@ -347,7 +347,7 @@ class ContextoGrupoManager:
|
|
| 347 |
|
| 348 |
@dataclass
|
| 349 |
class PayloadParaLLM:
|
| 350 |
-
"""Payload estruturado para o LLM da
|
| 351 |
# Identificação
|
| 352 |
usuario_id: str
|
| 353 |
usuario_nome: str
|
|
|
|
| 2 |
# LISTEN ENGINE - FLUXO CORRETO DE ESCUTA vs RESPOSTA
|
| 3 |
# ================================================================
|
| 4 |
# Propósito: Diferenciar mensagens que requerem resposta vs contexto puro
|
| 5 |
+
# Bug anterior: Kiami interpretava TUDO como direcionado a ela
|
| 6 |
# Solução: Sistema de FLAGS e METADATA de fluxo
|
| 7 |
|
| 8 |
import time
|
|
|
|
| 40 |
|
| 41 |
# 🎯 FLAGS CRÍTICAS - DETERMINAM RESPOSTA
|
| 42 |
is_directed_to_bot: bool = False # Mensagem direcionada ao bot?
|
| 43 |
+
is_mention_to_bot: bool = False # Menciona "@Kiami" ou "Kiami, "
|
| 44 |
is_reply_to_bot: bool = False # Resposta (reply) à mensagem anterior do bot
|
| 45 |
is_command_to_bot: bool = False # Começa com #, /, $
|
| 46 |
is_privileged_user: bool = False # Usuário privilegiado (Isaac)
|
|
|
|
| 156 |
"""
|
| 157 |
|
| 158 |
BOT_NUMBER: str = "37839265886398"
|
| 159 |
+
BOT_NAMES: Tuple[str, ...] = ("akira", "morena", "@akira", "Akira", "AKIRA", "kiami", "@kiami", "Kiami", "KIAMIA")
|
| 160 |
|
| 161 |
COMMAND_PREFIXES: Tuple[str, ...] = ("#", "/", "$", "!")
|
| 162 |
|
|
|
|
| 177 |
|
| 178 |
Args:
|
| 179 |
remoteJid: ID do remetente/grupo
|
| 180 |
+
fromMe: Se foi enviada pela Kiami (bot)
|
| 181 |
quotedMsg: Se é reply, dados da msg anterior
|
| 182 |
pushName: Nome do remetente
|
| 183 |
body: Texto da mensagem
|
|
|
|
| 347 |
|
| 348 |
@dataclass
|
| 349 |
class PayloadParaLLM:
|
| 350 |
+
"""Payload estruturado para o LLM da Kiami"""
|
| 351 |
# Identificação
|
| 352 |
usuario_id: str
|
| 353 |
usuario_nome: str
|
modules/reply_context_handler.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
-
|
| 5 |
================================================================================
|
| 6 |
Sistema dedicado para processar e priorizar contexto de replies.
|
| 7 |
Garante que replies tenham prioridade ligeiramente maior que o contexto geral,
|
|
@@ -190,8 +190,8 @@ def extrair_context_hint(quoted_text: str, mensagem_atual: str) -> str:
|
|
| 190 |
quoted_lower = quoted_text.lower() if quoted_text else ""
|
| 191 |
|
| 192 |
# Pergunta sobre o bot
|
| 193 |
-
if any(w in quoted_lower for w in ['akira', 'bot', 'você', 'vc', 'tu']):
|
| 194 |
-
hints.append("
|
| 195 |
|
| 196 |
# Pergunta factual
|
| 197 |
if any(w in quoted_lower for w in ['oq', 'o que', 'qual', 'quanto', 'onde', 'quando']):
|
|
@@ -317,26 +317,26 @@ class ReplyContextHandler:
|
|
| 317 |
is_quoted_from_bot = (quoted_author_pure and quoted_author_pure == bot_id_pure)
|
| 318 |
|
| 319 |
if is_quoted_from_bot and is_reply:
|
| 320 |
-
logger.info(f"🔄 [REPLY AO BOT] Usuário está respondendo a uma mensagem da
|
| 321 |
reply_to_bot = True
|
| 322 |
-
quoted_author_name = "
|
| 323 |
quoted_author_numero = config.BOT_NUMERO
|
| 324 |
|
| 325 |
# 🔧 CORREÇÃO FORÇADA: Se o payload já determinou que é reply_to_bot,
|
| 326 |
# ignora qualquer nome/número que tenha vindo e força para o bot.
|
| 327 |
if is_reply and reply_to_bot:
|
| 328 |
-
quoted_author_name = "
|
| 329 |
quoted_author_numero = config.BOT_NUMERO
|
| 330 |
-
|
| 331 |
# 🔧 CORREÇÃO: Se autor é desconhecido e não é reply_to_bot explícito, tenta detectar pelo contexto
|
| 332 |
elif not quoted_author_name or quoted_author_name.lower() in ['desconhecido', 'unknown', '']:
|
| 333 |
# Detecta pelo conteúdo da mensagem citada
|
| 334 |
quoted_lower = quoted_text_original.lower() if quoted_text_original else ""
|
| 335 |
-
|
| 336 |
# Se a mensagem citada contém padrões de resposta do bot
|
| 337 |
-
bot_patterns = ['akira:', 'eu sou', 'eu sou a akira', 'sou um bot', 'oi!', 'eae!']
|
| 338 |
if any(p in quoted_lower for p in bot_patterns):
|
| 339 |
-
quoted_author_name = "
|
| 340 |
quoted_author_numero = config.BOT_NUMERO
|
| 341 |
reply_to_bot = True
|
| 342 |
elif mensagem_citada:
|
|
@@ -350,7 +350,7 @@ class ReplyContextHandler:
|
|
| 350 |
if is_reply and (not quoted_author_name or quoted_author_name == 'desconhecido'):
|
| 351 |
# Se é reply_to_bot=True mas autor desconhecido, assume que é reply para o bot
|
| 352 |
if reply_to_bot:
|
| 353 |
-
quoted_author_name = "
|
| 354 |
quoted_author_numero = "BOT"
|
| 355 |
else:
|
| 356 |
# Tenta extrair do conteúdo
|
|
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
+
KIAMI V21 ULTIMATE - REPLY CONTEXT HANDLER MODULE
|
| 5 |
================================================================================
|
| 6 |
Sistema dedicado para processar e priorizar contexto de replies.
|
| 7 |
Garante que replies tenham prioridade ligeiramente maior que o contexto geral,
|
|
|
|
| 190 |
quoted_lower = quoted_text.lower() if quoted_text else ""
|
| 191 |
|
| 192 |
# Pergunta sobre o bot
|
| 193 |
+
if any(w in quoted_lower for w in ['akira', 'kiami', 'bot', 'você', 'vc', 'tu']):
|
| 194 |
+
hints.append("pergunta_sobre_kiami")
|
| 195 |
|
| 196 |
# Pergunta factual
|
| 197 |
if any(w in quoted_lower for w in ['oq', 'o que', 'qual', 'quanto', 'onde', 'quando']):
|
|
|
|
| 317 |
is_quoted_from_bot = (quoted_author_pure and quoted_author_pure == bot_id_pure)
|
| 318 |
|
| 319 |
if is_quoted_from_bot and is_reply:
|
| 320 |
+
logger.info(f"🔄 [REPLY AO BOT] Usuário está respondendo a uma mensagem da Kiami ({quoted_author_pure}).")
|
| 321 |
reply_to_bot = True
|
| 322 |
+
quoted_author_name = "Kiami (você mesma)"
|
| 323 |
quoted_author_numero = config.BOT_NUMERO
|
| 324 |
|
| 325 |
# 🔧 CORREÇÃO FORÇADA: Se o payload já determinou que é reply_to_bot,
|
| 326 |
# ignora qualquer nome/número que tenha vindo e força para o bot.
|
| 327 |
if is_reply and reply_to_bot:
|
| 328 |
+
quoted_author_name = "Kiami (você mesma)"
|
| 329 |
quoted_author_numero = config.BOT_NUMERO
|
| 330 |
+
|
| 331 |
# 🔧 CORREÇÃO: Se autor é desconhecido e não é reply_to_bot explícito, tenta detectar pelo contexto
|
| 332 |
elif not quoted_author_name or quoted_author_name.lower() in ['desconhecido', 'unknown', '']:
|
| 333 |
# Detecta pelo conteúdo da mensagem citada
|
| 334 |
quoted_lower = quoted_text_original.lower() if quoted_text_original else ""
|
| 335 |
+
|
| 336 |
# Se a mensagem citada contém padrões de resposta do bot
|
| 337 |
+
bot_patterns = ['akira:', 'kiami:', 'eu sou', 'eu sou a akira', 'eu sou a kiami', 'sou um bot', 'oi!', 'eae!']
|
| 338 |
if any(p in quoted_lower for p in bot_patterns):
|
| 339 |
+
quoted_author_name = "Kiami (você mesma)"
|
| 340 |
quoted_author_numero = config.BOT_NUMERO
|
| 341 |
reply_to_bot = True
|
| 342 |
elif mensagem_citada:
|
|
|
|
| 350 |
if is_reply and (not quoted_author_name or quoted_author_name == 'desconhecido'):
|
| 351 |
# Se é reply_to_bot=True mas autor desconhecido, assume que é reply para o bot
|
| 352 |
if reply_to_bot:
|
| 353 |
+
quoted_author_name = "Kiami (você mesma)"
|
| 354 |
quoted_author_numero = "BOT"
|
| 355 |
else:
|
| 356 |
# Tenta extrair do conteúdo
|
modules/unified_context.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
-
|
| 5 |
================================================================================
|
| 6 |
Sistema unificado que integra Reply Context + Short-Term Memory em sintonia.
|
| 7 |
|
|
@@ -359,7 +359,7 @@ def format_unified_context_for_llm(
|
|
| 359 |
else:
|
| 360 |
reply_section.append("- O usuário está a responder a <quoted_message>. Formule sua resposta com base nisso.")
|
| 361 |
|
| 362 |
-
reply_section.append("- PRESERVE a sua identidade e postura (seja
|
| 363 |
reply_section.append("- Nunca perca o fio da meada. Olhe as mensagens anteriores para entender o contexto real.")
|
| 364 |
|
| 365 |
parts.append("\n".join(reply_section))
|
|
|
|
| 1 |
# type: ignore
|
| 2 |
"""
|
| 3 |
================================================================================
|
| 4 |
+
KIAMI V21 ULTIMATE - UNIFIED CONTEXT MODULE
|
| 5 |
================================================================================
|
| 6 |
Sistema unificado que integra Reply Context + Short-Term Memory em sintonia.
|
| 7 |
|
|
|
|
| 359 |
else:
|
| 360 |
reply_section.append("- O usuário está a responder a <quoted_message>. Formule sua resposta com base nisso.")
|
| 361 |
|
| 362 |
+
reply_section.append("- PRESERVE a sua identidade e postura (seja a Kiami, séria, directa).")
|
| 363 |
reply_section.append("- Nunca perca o fio da meada. Olhe as mensagens anteriores para entender o contexto real.")
|
| 364 |
|
| 365 |
parts.append("\n".join(reply_section))
|