Spaces:
Running
Running
| # 🧠 GUIA DE INTEGRAÇÃO - LSTM MEMORY SYSTEM | |
| **Versão:** 1.0 | |
| **Data:** 10/04/2026 | |
| **Para:** Desenvolvedores integrando LSTM Memory | |
| --- | |
| ## 📋 O QUE É O LSTM MEMORY SYSTEM? | |
| Sistema de memória que funciona **100% transparente** para criar "resumos mentais" de conversas: | |
| - ✅ **Mentais** - Usuário não vê os resumos | |
| - ✅ **Contextualizados** - Entende tópicos, perguntas pendentes, padrões | |
| - ✅ **Isolados** - Cada usuário/grupo tem seu próprio contexto | |
| - ✅ **Automáticos** - Recuperados quando modelo precisa | |
| - ✅ **Persistentes** - Armazenados em DB para sessões futuras | |
| --- | |
| ## 🎯 EXEMPLO PRÁTICO | |
| ### Conversa Real com Belmira: | |
| ``` | |
| Belmira: "Fale tudo sobre anemia falciforme" | |
| Akira: "Anemia falciforme é doença genética da hemoglobina..." | |
| Belmira: "Eu não falei inglês" | |
| Akira: "Respondi em português. Você pediu tudo explicado." | |
| Belmira: "Poxa" | |
| Akira: "O quê?" | |
| Belmira: "cura? tratamento?" | |
| Akira: ??? ANTES: "De quê?" ← CONTEXTO PERDIDO | |
| DEPOIS: Entende que é sobre anemia! ← ✅ CERTO | |
| ``` | |
| ### O Que Acontece Mentalmente (Oculto): | |
| ``` | |
| [LSTM MENTAL PROCESSING - NÃO VISÍVEL] | |
| Msg 1: "Fale tudo sobre anemia falciforme" | |
| ├─ Topic: "anemia falciforme" | |
| ├─ Subtopics: ["definição", "genética", "hemoglobina"] | |
| └─ Pattern: "perguntador" | |
| Msg 2: "Eu não falei inglês" | |
| └─ [Contexto continua: anemia falciforme] | |
| Msg 3: "Poxa" | |
| └─ [Contexto continua: anemia falciforme] | |
| Msg 4: "cura? tratamento?" | |
| ├─ Detecta pergunta sobre "cura/tratamento" | |
| ├─ LSTM busca no histórico: tópico é "anemia falciforme" | |
| ├─ Conecta: "cura" → deve ser sobre "anemia falciforme" | |
| └─ Modelo usa contexto automaticamente ✅ | |
| ``` | |
| --- | |
| ## 🔧 ARQUITETURA | |
| ### Fluxo de Dados: | |
| ``` | |
| User Message | |
| ↓ | |
| short_term_memory (100 msgs) | |
| ↓ (simultaneous) | |
| ├─→ Reply Handler (resposta direto) | |
| │ ├─→ Context Builder | |
| │ └─→ API Call (Mistral/Gemini/etc) | |
| │ | |
| └─→ LSTM Memory (async) | |
| ├─ Processa em background | |
| ├─ Extrai tema, subtópicos | |
| ├─ Detecta perguntas pendentes | |
| ├─ Armazena em DB | |
| └─ (Modelo usa quando precisa) | |
| ``` | |
| ### Tabelas no DB: | |
| ```sql | |
| lstm_contexto | |
| ├─ context_id (PK) | |
| ├─ numero_usuario | |
| ├─ topic_principal (tema atual) | |
| ├─ subtopicas (list) | |
| ├─ conversation_path (histórico de temas) | |
| ├─ last_key_message (última msg importante) | |
| ├─ emotional_state | |
| ├─ interaction_pattern (perguntador, narrativo, etc) | |
| ├─ unanswered_questions (perguntas pendentes) | |
| ├─ assumed_knowledge (o que ele sabe) | |
| ├─ contradictions (inconsistências) | |
| └─ metadata | |
| lstm_message_links | |
| ├─ context_id (FK) | |
| ├─ message_id | |
| ├─ parent_message_id | |
| ├─ topic_changed | |
| ├─ created_at | |
| └─ relevance_score | |
| ``` | |
| --- | |
| ## 🚀 INTEGRAÇÃO PASSO A PASSO | |
| ### 1️⃣ Em `reply_context_handler.py` | |
| Disparar LSTM processing quando mensagem chega: | |
| ```python | |
| from modules.lstm_memory_system import get_lstm_memory_system | |
| from modules.context_isolation import ContextIsolation | |
| class ReplyContextHandler: | |
| def __init__(self, db, llm_client): | |
| self.lstm = get_lstm_memory_system(db, ContextIsolation(db)) | |
| self.llm_client = llm_client | |
| def handle_user_message(self, numero_usuario: str, message: str, grupo_id: Optional[str] = None): | |
| """Processa mensagem de usuário.""" | |
| # 1. Gerar context_id | |
| context_id = self._generate_context_id(numero_usuario, grupo_id) | |
| # 2. Processar short-term memory (síncrono) | |
| short_memory = self.short_term_memory.add_message( | |
| context_id=context_id, | |
| role='user', | |
| content=message, | |
| timestamp=time.time() | |
| ) | |
| # 3. ✅ DISPARAR LSTM PROCESSING (ASSÍNCRONO) | |
| if self.lstm: | |
| parent_msg = short_memory[-2] if len(short_memory) > 1 else None | |
| parent_id = parent_msg.get('id') if parent_msg else None | |
| self.lstm.process_message_async( | |
| context_id=context_id, | |
| numero_usuario=numero_usuario, | |
| message=message, | |
| role='user', | |
| parent_message_id=parent_id, | |
| llm_client=self.llm_client # Para análise com LLM | |
| ) | |
| # 4. Construir contexto para resposta | |
| context = self._build_context(numero_usuario, context_id, short_memory) | |
| # 5. Gerar resposta (model não espera LSTM) | |
| response = self.generate_response(context, message) | |
| # 6. Adicionar resposta à memória | |
| self.short_term_memory.add_message( | |
| context_id=context_id, | |
| role='assistant', | |
| content=response, | |
| timestamp=time.time() | |
| ) | |
| # 7. ✅ PROCESSAR RESPOSTA TAMBÉM EM LSTM | |
| if self.lstm: | |
| self.lstm.process_message_async( | |
| context_id=context_id, | |
| numero_usuario=numero_usuario, | |
| message=response, | |
| role='assistant', | |
| parent_message_id=short_memory[-1].get('id') | |
| ) | |
| return response | |
| def _build_context(self, numero_usuario, context_id, short_memory): | |
| """Constrói contexto com LSTM + short_term.""" | |
| context = { | |
| 'numero_usuario': numero_usuario, | |
| 'short_term_messages': short_memory, # Últimas 100 | |
| } | |
| # ✅ ADICIONAR LSTM CONTEXT (AUTOMÁTICO) | |
| if self.lstm: | |
| lstm_context = self.lstm.get_lstm_context_for_model( | |
| context_id=context_id, | |
| numero_usuario=numero_usuario | |
| ) | |
| context['lstm_context'] = lstm_context | |
| return context | |
| ``` | |
| ### 2️⃣ Em `context_builder.py` | |
| Usar LSTM context na construção do prompt: | |
| ```python | |
| from modules.lstm_memory_system import get_lstm_memory_system | |
| class ContextBuilder: | |
| def __init__(self, db): | |
| self.lstm = get_lstm_memory_system(db) | |
| def build_full_context(self, user_id, short_memory, lstm_context=None): | |
| """Constrói contexto completo para o modelo.""" | |
| # Se não temos LSTM context, recuperar agora | |
| if lstm_context is None and self.lstm: | |
| context_id = self._get_context_id(user_id) | |
| lstm_context = self.lstm.get_lstm_context_for_model( | |
| context_id=context_id, | |
| numero_usuario=user_id | |
| ) | |
| # ═══════════════════════════════════════════════════════ | |
| # CONTEXTO DUAL: Direto + LSTM (Ambos Transparentes) | |
| # ═══════════════════════════════════════════════════════ | |
| context_data = { | |
| # 1. Contexto Direto (últimas mensagens) | |
| "direct_context": { | |
| "recent_messages": short_memory[-5:], # Últimas 5 | |
| "conversation_type": "direct_interaction" | |
| }, | |
| # 2. Contexto LSTM (memória mental) | |
| "lstm_context": lstm_context or {}, | |
| } | |
| # ✅ INSTRUÇÃO PARA MODELO USAR AMBOS | |
| context_data["instruction"] = """ | |
| Use dois tipos de contexto simultaneamente: | |
| 1. DIRETO: Mensagens das últimas trocas (direct_context) | |
| 2. MENTAL: Contexto histórico (lstm_context) | |
| Exemplo: | |
| - Pergunta direto: "cura? tratamento?" | |
| - Contexto mental: {topic_principal: "anemia falciforme"} | |
| - Modelo conecta automaticamente | |
| """ | |
| return context_data | |
| def build_system_prompt_with_lstm(self, lstm_context=None): | |
| """Constrói system prompt enriquecido com LSTM.""" | |
| base_prompt = """Você é Akira, assistente angolana inteligente...""" | |
| if lstm_context and lstm_context.get('topic_principal'): | |
| # ✅ Injetar contexto mental no prompt | |
| mental_summary = lstm_context.get('mental_summary_text', '') | |
| lstm_injection = f""" | |
| ## 🧠 CONTEXTO INTERNO (MEMÓRIA MENTAL - NÃO MOSTRE ISTO AO USUÁRIO) | |
| Contexto da conversa atual (processado internamente): | |
| {mental_summary} | |
| Perguntas pendentes a responder: {json.dumps(lstm_context.get('unanswered_questions', [])[:3])} | |
| Padrão de interação deste usuário: {lstm_context.get('interaction_pattern', 'unknown')} | |
| **INSTRUÇÃO:** Use este contexto para conectar tópicos e entender a conversa naturalmente. | |
| Tópico principal atual: {lstm_context.get('topic_principal')} | |
| Não mencione que está usando "contexto mental" ou "LSTM" - responda naturalmente. | |
| """ | |
| return base_prompt + "\n" + lstm_injection | |
| return base_prompt | |
| ``` | |
| ### 3️⃣ Em `api.py` | |
| Usar contexto LSTM ao chamar APIs: | |
| ```python | |
| from modules.lstm_memory_system import get_lstm_memory_system | |
| class UnifiedLLMClient: | |
| def __init__(self, db): | |
| self.lstm = get_lstm_memory_system(db) | |
| def generate(self, user_prompt, context_history): | |
| """Gera resposta usando LSTM context.""" | |
| # ✅ Recuperar LSTM context se disponível | |
| lstm_context = None | |
| if self.lstm and hasattr(self, 'current_context_id'): | |
| lstm_context = self.lstm.get_lstm_context_for_model( | |
| context_id=self.current_context_id, | |
| numero_usuario=self.current_user_id | |
| ) | |
| # ✅ Injetar no system prompt | |
| from modules.context_builder import ContextBuilder | |
| cb = ContextBuilder(self.db) | |
| system_prompt = cb.build_system_prompt_with_lstm(lstm_context) | |
| # Chamar qualquer provedor (Mistral, Gemini, etc) | |
| messages = [ | |
| {"role": "system", "content": system_prompt}, | |
| *context_history, | |
| {"role": "user", "content": user_prompt} | |
| ] | |
| response = self._call_llm(messages) | |
| return response | |
| ``` | |
| ### 4️⃣ Em `persona_tracker.py` | |
| Usar LSTM context para atualizar persona: | |
| ```python | |
| class PersonaTracker: | |
| def __init__(self, db, llm_client): | |
| self.db = db | |
| self.llm_client = llm_client | |
| from modules.lstm_memory_system import get_lstm_memory_system | |
| self.lstm = get_lstm_memory_system(db) | |
| def track_background(self, numero_usuario: str, historico_recente): | |
| """Rastreia persona usando LSTM context.""" | |
| if numero_usuario in self.processing_users: | |
| return | |
| # ✅ Recuperar LSTM context | |
| context_id = self._get_context_id(numero_usuario) | |
| lstm_context = None | |
| if self.lstm: | |
| lstm_context = self.lstm.get_lstm_context_for_model( | |
| context_id=context_id, | |
| numero_usuario=numero_usuario | |
| ) | |
| self.processing_users.add(numero_usuario) | |
| thread = threading.Thread( | |
| target=self._analyze_with_lstm, | |
| args=(numero_usuario, historico_recente, lstm_context), | |
| daemon=True | |
| ) | |
| thread.start() | |
| def _analyze_with_lstm(self, numero_usuario, historico, lstm_context): | |
| """Analisa persona usando contexto LSTM.""" | |
| # ✅ Usar LSTM context para melhor análise | |
| if lstm_context: | |
| contexto_info = f""" | |
| Contexto da conversa: {lstm_context.get('topic_principal')} | |
| Padrão de interação: {lstm_context.get('interaction_pattern')} | |
| Conhecimento demonstrado: {lstm_context.get('assumed_knowledge')} | |
| """ | |
| else: | |
| contexto_info = "" | |
| prompt = f""" | |
| Analise a persona deste usuário. Use também o contexto da conversa: | |
| {contexto_info} | |
| Mensagens: | |
| {historico} | |
| Retorne JSON com personalidade atualizada. | |
| """ | |
| # ... rest of analysis | |
| ``` | |
| --- | |
| ## 📊 FLUXO COMPLETO DE EXEMPLO | |
| ### Cenário: Belmira faz 3 perguntas sobre anemia | |
| ``` | |
| ┌─────────────────────────────────────────────────────────────┐ | |
| │ Msg 1: "Fale tudo sobre anemia falciforme" │ | |
| └─────────────────────────────────────────────────────────────┘ | |
| ↓ | |
| [Processing] | |
| ├─ Short-Term Memory: Add to [context_id_belmira] | |
| ├─ [ASYNC] LSTM: | |
| │ ├─ Extrai tema: "anemia falciforme" | |
| │ ├─ Subtópicos: ["definição", "genética"] | |
| │ ├─ Pattern: "perguntador" | |
| │ └─ Salva em DB (lstm_contexto) | |
| └─ Build Context: | |
| ├─ short_memory: [msg1] | |
| ├─ lstm_context: {topic: "anemia falciforme", ...} | |
| └─ System Prompt + LSTM Injection | |
| ↓ | |
| Akira Responde: "Anemia falciforme é..." | |
| ↓ | |
| [ASYNC] LSTM processa resposta: | |
| ├─ Detecta que resposta está no tópico | |
| └─ Atualiza last_key_message | |
| ┌─────────────────────────────────────────────────────────────┐ | |
| │ Msg 2: "Eu não falei inglês" │ | |
| └─────────────────────────────────────────────────────────────┘ | |
| ↓ | |
| [Processing] | |
| ├─ Short-Term Memory: Add to [context_id_belmira] | |
| ├─ [ASYNC] LSTM: | |
| │ ├─ Analisa mensagem: "não é pergunta direto" | |
| │ ├─ Contexto continua: "anemia falciforme" | |
| │ └─ Detecta: possível confusão ou desacordo | |
| └─ Build Context: | |
| ├─ short_memory: [msg1, resposta_akira, msg2] | |
| ├─ lstm_context: {topic: CONTINUA "anemia falciforme"} | |
| └─ Akira sabe contexto | |
| ↓ | |
| Akira Responde: "Respondi em português..." | |
| ┌─────────────────────────────────────────────────────────────┐ | |
| │ Msg 3: "cura? tratamento?" │ | |
| └─────────────────────────────────────────────────────────────┘ | |
| ↓ | |
| [Processing] | |
| ├─ Short-Term Memory: Add [msg3] | |
| ├─ [ASYNC] LSTM: | |
| │ ├─ Detecta pergunta: "cura? tratamento?" | |
| │ ├─ Busca LSTM: "De quê?" ← NOT IN LSTM! | |
| │ ├─ Procura no histórico mental | |
| │ ├─ Encontra: topic_principal = "anemia falciforme" | |
| │ └─ Conecta automaticamente! ✅ | |
| └─ Build Context: | |
| ├─ short_memory: [últimas 5] | |
| ├─ lstm_context: { | |
| │ topic: "anemia falciforme", | |
| │ unanswered_questions: [ | |
| │ "cura de anemia falciforme?", | |
| │ "tratamento de anemia?" | |
| │ ] | |
| │ } | |
| └─ Model vê contexto: | |
| "pergunta sobre anemia falciforme!" | |
| ↓ | |
| ✅ Akira Responde Corretamente: | |
| "Para anemia falciforme, tratamentos incluem..." | |
| (Sabe que é sobre a doença, não pergunta "de quê?") | |
| ``` | |
| --- | |
| ## 🔐 ISOLAMENTO E SEGURANÇA | |
| ### Garantir Isolamento Total: | |
| ```python | |
| # ✅ CORRETO: Context isolado por usuário/grupo | |
| context_id = f"{numero_usuario}:{grupo_id}:{tipo}" | |
| lstm_context = self.lstm.get_lstm_context_for_model(context_id) | |
| # ✅ CADA USUÁRIO VEHE APENAS SEU LSTM: | |
| - Belmira vê apenas {context_id: "belmira:None:pv"} | |
| - Isaac vê apenas {context_id: "isaac:None:pv"} | |
| - Grupo X vê apenas {context_id: "user:grupo_x:group"} | |
| # ❌ NUNCA MISTURAR CONTEXTOS | |
| lstm_belmira = get_lstm_for("belmira") # ✅ | |
| lstm_isaac = get_lstm_for("isaac") # ✅ | |
| # Se um usuário vê contexto do outro = VAZAMENTO ❌ | |
| ``` | |
| ### Validação de Isolamento: | |
| ```python | |
| def validate_context_isolation(numero_usuario, context_id): | |
| """Valida que contexto pertence ao usuário.""" | |
| # Extrair usuario do context_id | |
| user_in_context = context_id.split(':')[0] | |
| # Verificar | |
| assert user_in_context == numero_usuario, "Context isolation violated!" | |
| return True | |
| ``` | |
| --- | |
| ## 📈 MONITORAMENTO | |
| ### Logs de LSTM: | |
| ``` | |
| ✅ LSTM Memory System inicializado | |
| ✅ Tabelas LSTM inicializadas | |
| ✅ LSTM summary salvo: context_id_belmira | |
| ✅ LSTM context for model retrieved: anemia falciforme topic | |
| ⚠️ Erro ao processar LSTM: [erro] | |
| ❌ Context isolation violated! | |
| ``` | |
| ### Debugging: | |
| ```python | |
| # Ver resumo mental de um usuário | |
| lstm = get_lstm_memory_system() | |
| summary = lstm.get_lstm_context_for_model("belmira", "belmira") | |
| print(json.dumps(summary, indent=2)) | |
| # Ver histórico com contexto | |
| history = lstm.get_conversation_history_with_context("belmira:None:pv") | |
| print(history['mental_summary']) | |
| ``` | |
| --- | |
| ## ✅ CHECKLIST DE IMPLEMENTAÇÃO | |
| - [ ] `lstm_memory_system.py` criado ✅ | |
| - [ ] Tabelas LSTM criadas em `database.py` | |
| - [ ] `reply_context_handler.py` chama `process_message_async()` | |
| - [ ] `context_builder.py` injeta LSTM context no prompt | |
| - [ ] `api.py` usa system prompt com LSTM injection | |
| - [ ] `persona_tracker.py` usa LSTM context | |
| - [ ] Isolamento testado (usuários não veem contextos um do outro) | |
| - [ ] Testes de LSTM extraction funcionam | |
| - [ ] Logs funcionando corretamente | |
| - [ ] Documentação atualizada | |
| --- | |
| ## 🎯 RESULTADO ESPERADO | |
| ### Antes (Sem LSTM): | |
| ``` | |
| Belmira: "cura? tratamento?" | |
| Akira: "De quê?" ❌ Perdeu contexto | |
| ``` | |
| ### Depois (Com LSTM): | |
| ``` | |
| Belmira: "cura? tratamento?" | |
| Akira: "Para anemia falciforme, os tratamentos incluem..." ✅ Mantém contexto mentalmente! | |
| ``` | |
| ### O Usuário NÃO vê: | |
| - Resumos mentais | |
| - Tabelas LSTM | |
| - Processamento async | |
| - Extrações de tópico | |
| ### O Usuário SÓ vê: | |
| - Respostas inteligentes com contexto correto ✅ | |
| --- | |
| **Status:** 🚀 Pronto para integração | |
| **Complexidade:** ⭐⭐⭐⭐ (Média) | |
| **Impacto:** 🎯 ENORME - Contextalização perfeita | |