ποΈ PLANO: AI Support Widget (Assistente de Voz para Equipe) β
Objetivo: Criar um widget de IA flutuante com suporte a voz para ajudar a equipe interna a tirar dΓΊvidas sobre processos, fluxos e uso do sistema.
π VISΓO GERAL β
O que Γ©? β
Um assistente de IA integrado ao dashboard que permite Γ equipe fazer perguntas sobre:
- Como funciona cada etapa do processo de vendas
- Onde encontrar informaΓ§Γ΅es no sistema
- Como usar features especΓficas
- DΓΊvidas sobre leads, calls, agentes
- ExplicaΓ§Γ΅es sobre mΓ©tricas e scores
Modos de InteraΓ§Γ£o β
- Texto - Chat tradicional (sempre disponΓvel)
- Voz - Push-to-talk com transcriΓ§Γ£o (opcional)
- Voz ContΓnua - Modo hands-free com detecΓ§Γ£o de silΓͺncio
ποΈ ARQUITETURA β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FRONTEND (React - localhost:3003) β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β AISupportWidget.tsx β β
β β ββββββββββββ βββββββββββββββββββββββββββββββββββββββββββ β β
β β β π€ Mic β β Chat Messages Area β β β
β β β Button β β βββββββββββββββββββββββββββββββββββ β β β
β β β β β β User: Como classifico um lead? β β β β
β β β ββββββββ β β βββββββββββββββββββββββββββββββββββ β β β
β β β βRecordβ β β βββββββββββββββββββββββββββββββββββ β β β
β β β β ing β β β β AI: Para classificar um lead...β β β β
β β β ββββββββ β β βββββββββββββββββββββββββββββββββββ β β β
β β ββββββββββββ βββββββββββββββββββββββββββββββββββββββββββ β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β [π¬ Digite sua pergunta...] [π€] [π€] ββ β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
ββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β
βΌ WebSocket / HTTP
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β N8N WORKFLOWS β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β 13-AI-Support-Widget.json ββ
β β ββ
β β ββββββββββββ ββββββββββββ ββββββββββββββββββββββββ ββ
β β β Webhook βββββΆβ Whisper βββββΆβ RAG Search β ββ
β β β Receiver β β (STT) β β (Segundo CΓ©rebro) β ββ
β β ββββββββββββ ββββββββββββ ββββββββββββββββββββββββ ββ
β β β ββ
β β βΌ ββ
β β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββ
β β β ElevenLabs ββββββ Claude/GPT ββββββ Context β ββ
β β β TTS (voz) β β (resposta) β β Builder β ββ
β β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββ
β β β ββ
β β βΌ ββ
β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ
β β β Response: { text, audioUrl, sources, suggestions } β ββ
β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SUPABASE β
β β
β ββββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββ β
β β support_chat_ β β rag_knowledge β β support_ β β
β β messages β β (Segundo CΓ©rebro)β β feedback β β
β ββββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββπ ESTRUTURA DE ARQUIVOS β
Frontend (React) β
front-factorai-mottivme-sales/
βββ components/
β βββ AISupportWidget/
β βββ index.tsx # Componente principal
β βββ AISupportWidget.tsx # Widget flutuante
β βββ ChatMessage.tsx # Mensagem individual
β βββ VoiceRecorder.tsx # Gravador de Γ‘udio
β βββ AudioPlayer.tsx # Player de resposta
β βββ ContextIndicator.tsx # Mostra contexto atual
β βββ styles.ts # Estilos do widget
βββ hooks/
β βββ useAISupport.ts # Hook principal
β βββ useVoiceRecording.ts # Hook de gravaΓ§Γ£o
β βββ useAudioPlayback.ts # Hook de reproduΓ§Γ£o
βββ services/
β βββ aiSupportService.ts # API calls
βββ types/
βββ aiSupport.ts # Tipos TypeScriptWorkflows n8n β
Fluxos n8n/AI-Factory- Mottivme Sales/
βββ 13-AI-Support-Widget.json # Workflow principal
βββ 14-Support-Context-Builder.json # Builder de contexto
βββ 15-Support-Analytics.json # Analytics de usoSQL/Migrations β
sql/migrations/
βββ 013_ai_support_widget.sql # Tabelas do widgetποΈ SCHEMA DO BANCO DE DADOS β
sql
-- ============================================
-- TABELA: support_chat_sessions
-- SessΓ΅es de chat do widget
-- ============================================
CREATE TABLE support_chat_sessions (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
user_id TEXT NOT NULL, -- ID do usuΓ‘rio
user_name TEXT, -- Nome do usuΓ‘rio
user_role TEXT, -- Papel (cs, admin, etc)
current_page TEXT, -- PΓ‘gina atual no dashboard
session_context JSONB DEFAULT '{}', -- Contexto da sessΓ£o
started_at TIMESTAMPTZ DEFAULT NOW(),
ended_at TIMESTAMPTZ,
message_count INTEGER DEFAULT 0,
avg_response_time_ms INTEGER,
satisfaction_score INTEGER, -- 1-5 (feedback final)
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- ============================================
-- TABELA: support_chat_messages
-- Mensagens do chat
-- ============================================
CREATE TABLE support_chat_messages (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
session_id UUID REFERENCES support_chat_sessions(id),
role TEXT NOT NULL CHECK (role IN ('user', 'assistant', 'system')),
content TEXT NOT NULL, -- Texto da mensagem
audio_url TEXT, -- URL do Γ‘udio (se voz)
input_type TEXT DEFAULT 'text', -- 'text' ou 'voice'
-- Metadados da resposta (se role = 'assistant')
sources JSONB DEFAULT '[]', -- Fontes do RAG usadas
confidence_score NUMERIC(3,2), -- ConfianΓ§a da resposta
response_time_ms INTEGER, -- Tempo de resposta
tokens_used INTEGER, -- Tokens consumidos
-- Feedback do usuΓ‘rio
was_helpful BOOLEAN, -- Γtil?
feedback_text TEXT, -- ComentΓ‘rio opcional
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- ============================================
-- TABELA: support_knowledge_gaps
-- Perguntas nΓ£o respondidas (para melhorar base)
-- ============================================
CREATE TABLE support_knowledge_gaps (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
question TEXT NOT NULL, -- Pergunta original
similar_questions TEXT[], -- VariaΓ§Γ΅es da mesma pergunta
occurrence_count INTEGER DEFAULT 1, -- Quantas vezes perguntaram
last_asked_at TIMESTAMPTZ DEFAULT NOW(),
status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'documented', 'ignored')),
resolution_notes TEXT, -- Como foi resolvido
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- ============================================
-- TABELA: support_quick_actions
-- AΓ§Γ΅es rΓ‘pidas sugeridas pela IA
-- ============================================
CREATE TABLE support_quick_actions (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
trigger_phrase TEXT NOT NULL, -- Frase que ativa a aΓ§Γ£o
action_type TEXT NOT NULL, -- 'navigate', 'explain', 'tutorial'
action_data JSONB NOT NULL, -- Dados da aΓ§Γ£o
priority INTEGER DEFAULT 0, -- Prioridade de sugestΓ£o
usage_count INTEGER DEFAULT 0, -- Vezes que foi usada
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Γndices
CREATE INDEX idx_support_messages_session ON support_chat_messages(session_id);
CREATE INDEX idx_support_sessions_user ON support_chat_sessions(user_id);
CREATE INDEX idx_knowledge_gaps_status ON support_knowledge_gaps(status);
-- RLS
ALTER TABLE support_chat_sessions ENABLE ROW LEVEL SECURITY;
ALTER TABLE support_chat_messages ENABLE ROW LEVEL SECURITY;π§© COMPONENTES REACT β
1. AISupportWidget.tsx (Componente Principal) β
typescript
interface AISupportWidgetProps {
userId: string;
userName: string;
userRole: 'cs' | 'admin' | 'viewer';
currentPage: string; // Ex: '/prompt-studio', '/leads'
agentContext?: { // Contexto do agente atual (se aplicΓ‘vel)
agentId: string;
agentName: string;
};
}
// Estados do widget
type WidgetState =
| 'minimized' // Apenas botΓ£o flutuante
| 'expanded' // Chat aberto
| 'recording' // Gravando voz
| 'processing' // Processando resposta
| 'playing'; // Reproduzindo Γ‘udio
// Features
- BotΓ£o flutuante fixo no canto inferior direito
- ExpansΓ£o suave com animaΓ§Γ£o
- Indicador de contexto atual ("VocΓͺ estΓ‘ em: Prompt Studio")
- HistΓ³rico de mensagens da sessΓ£o
- SugestΓ΅es de perguntas baseadas na pΓ‘gina atual
- Feedback thumbs up/down em cada resposta2. VoiceRecorder.tsx β
typescript
interface VoiceRecorderProps {
onRecordingComplete: (audioBlob: Blob) => void;
onRecordingStart: () => void;
onRecordingCancel: () => void;
maxDuration?: number; // MΓ‘ximo em segundos (default: 60)
silenceTimeout?: number; // Auto-stop apΓ³s silΓͺncio (default: 2s)
}
// Features
- Push-to-talk (segurar para gravar)
- Click-to-toggle (clicar para iniciar/parar)
- VisualizaΓ§Γ£o de amplitude em tempo real
- DetecΓ§Γ£o de silΓͺncio para auto-stop
- Cancelamento por gesto (arrastar para fora)3. ChatMessage.tsx β
typescript
interface ChatMessageProps {
message: {
id: string;
role: 'user' | 'assistant';
content: string;
audioUrl?: string;
sources?: Array<{
title: string;
category: string;
similarity: number;
}>;
timestamp: Date;
};
onFeedback: (messageId: string, helpful: boolean) => void;
onPlayAudio: (audioUrl: string) => void;
}
// Features
- Avatar diferenciado (user vs AI)
- Player de Γ‘udio inline
- Expandir para ver fontes
- BotΓ΅es de feedback
- Copiar textoπ WORKFLOW N8N: 13-AI-Support-Widget.json β
Fluxo Principal β
[Webhook] βββΆ [Route by Type] βββ¬βββΆ [Text Query] βββΆ [RAG Search] βββ¬βββΆ [Build Context]
(text/voice) β β
ββββΆ [Voice Query] βββΆ [Whisper STT]βββ
β
βΌ
[Response] βββ [Format Response] βββ [Claude/GPT] βββ [Enrich Context]
β
ββββΆ [If Voice Mode] βββΆ [ElevenLabs TTS] βββΆ [Upload Audio] βββΆ [Add audioUrl]Nodes Detalhados β
javascript
// 1. WEBHOOK - Recebe requisiΓ§Γ΅es
{
"path": "/ai-support",
"method": "POST",
"authentication": "headerAuth",
"body": {
"type": "text | voice",
"query": "string (se texto)",
"audioBase64": "string (se voz)",
"sessionId": "uuid",
"userId": "string",
"context": {
"currentPage": "/prompt-studio",
"agentId": "uuid (opcional)",
"selectedLeadId": "uuid (opcional)"
}
}
}
// 2. RAG SEARCH - Busca no Segundo CΓ©rebro
{
"endpoint": "https://agenticoskevsacademy-production.up.railway.app/webhook/rag-search",
"body": {
"query": "{{ $json.query }}",
"project_key": "mottivme-geral",
"threshold": 0.5,
"limit": 5
}
}
// 3. CLAUDE/GPT - Gera resposta
{
"model": "claude-3-5-sonnet",
"system": `VocΓͺ Γ© o assistente de suporte interno da MOTTIVME Sales.
Seu papel Γ© ajudar a equipe a entender:
- Como usar o sistema (dashboard, features)
- Como funciona o processo de vendas
- O que significam mΓ©tricas e scores
- Onde encontrar informaΓ§Γ΅es
CONTEXTO ATUAL DO USUΓRIO:
- PΓ‘gina: {{ $json.context.currentPage }}
- Agente selecionado: {{ $json.context.agentName || 'Nenhum' }}
CONHECIMENTO RELEVANTE (do RAG):
{{ $json.ragResults }}
REGRAS:
1. Seja direto e objetivo
2. Use exemplos prΓ‘ticos quando possΓvel
3. Se nΓ£o souber, diga que vai escalar para documentaΓ§Γ£o
4. Sugira prΓ³ximos passos quando relevante
5. Fale em portuguΓͺs brasileiro informal mas profissional`,
"messages": [
{ "role": "user", "content": "{{ $json.query }}" }
]
}
// 4. ELEVENLABS TTS (se modo voz)
{
"endpoint": "https://api.elevenlabs.io/v1/text-to-speech/{{ voiceId }}",
"body": {
"text": "{{ $json.response }}",
"model_id": "eleven_multilingual_v2",
"voice_settings": {
"stability": 0.5,
"similarity_boost": 0.75
}
}
}
// 5. SALVAR NO SUPABASE
{
"table": "support_chat_messages",
"operation": "insert",
"data": {
"session_id": "{{ $json.sessionId }}",
"role": "assistant",
"content": "{{ $json.response }}",
"audio_url": "{{ $json.audioUrl }}",
"sources": "{{ $json.sources }}",
"response_time_ms": "{{ $json.processingTime }}"
}
}π― SUGESTΓES CONTEXTUAIS β
Por PΓ‘gina β
typescript
const CONTEXTUAL_SUGGESTIONS: Record<string, string[]> = {
'/': [
'O que significa cada mΓ©trica do dashboard?',
'Como interpretar a taxa de conversΓ£o?',
'Por que o score do agente caiu?'
],
'/leads': [
'Como classificar um lead como HOT?',
'O que fazer quando um lead nΓ£o responde?',
'Como funciona o scoring de leads?'
],
'/prompt-studio': [
'Como editar o prompt do agente?',
'O que sΓ£o zonas editΓ‘veis vs protegidas?',
'Como publicar uma nova versΓ£o?'
],
'/reflection-loop': [
'Como funciona o Reflection Loop?',
'O que significam as sugestΓ΅es de melhoria?',
'Como aprovar ou rejeitar uma sugestΓ£o?'
],
'/calls': [
'Como a IA analisa as calls?',
'O que cada score significa?',
'Como melhorar a taxa de follow-up?'
],
'/configuracoes': [
'Como alterar as configuraΓ§Γ΅es do agente?',
'O que Γ© o intervalo de reflexΓ£o?',
'Como ativar notificaΓ§Γ΅es?'
]
};π ANALYTICS E MΓTRICAS β
MΓ©tricas a Coletar β
| MΓ©trica | DescriΓ§Γ£o | Uso |
|---|---|---|
queries_per_day | Perguntas por dia | Volume de uso |
avg_response_time | Tempo mΓ©dio de resposta | Performance |
voice_vs_text_ratio | ProporΓ§Γ£o voz/texto | PreferΓͺncia do usuΓ‘rio |
helpful_rate | % de respostas ΓΊteis | Qualidade |
unanswered_rate | % nΓ£o respondidas | Knowledge gaps |
top_questions | Perguntas mais frequentes | DocumentaΓ§Γ£o |
page_with_most_questions | PΓ‘gina com mais dΓΊvidas | UX issues |
Dashboard de Analytics (futuro) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AI Support Analytics β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β π Esta Semana π TendΓͺncia π― Satisfaction β
β βββββββββββββββ βββββββββββββ βββββββββββββββ β
β β 234 queries β β β 12% β β β 4.2/5 β β
β β 89% helpful β β vs semanaβ β (156 votes)β β
β βββββββββββββββ β anterior β βββββββββββββββ β
β βββββββββββββ β
β β
β π₯ Top Perguntas (knowledge gaps) β
β 1. "Como funciona o score do agente?" (23x) β
β 2. "Onde vejo o histΓ³rico de versΓ΅es?" (18x) β
β 3. "Como faΓ§o rollback de prompt?" (15x) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββπ ROADMAP DE IMPLEMENTAΓΓO β
Fase 1: MVP Texto (1-2 dias) β
- [ ] Criar componente
AISupportWidget.tsx - [ ] Implementar chat bΓ‘sico (sΓ³ texto)
- [ ] Criar workflow n8n
13-AI-Support-Widget.json - [ ] Integrar com RAG existente
- [ ] Salvar mensagens no Supabase
- [ ] Adicionar ao Layout.tsx como widget flutuante
Fase 2: SugestΓ΅es Contextuais (1 dia) β
- [ ] Implementar
CONTEXTUAL_SUGGESTIONS - [ ] Detectar pΓ‘gina atual via React Router
- [ ] Mostrar 3 sugestΓ΅es ao abrir o widget
- [ ] Analytics de quais sugestΓ΅es sΓ£o clicadas
Fase 3: Modo Voz (2-3 dias) β
- [ ] Criar
VoiceRecorder.tsxcom Web Audio API - [ ] Integrar Whisper para STT
- [ ] Integrar ElevenLabs para TTS
- [ ] Criar
AudioPlayer.tsxpara respostas - [ ] Adicionar toggle texto/voz
Fase 4: Feedback e Analytics (1 dia) β
- [ ] Implementar thumbs up/down
- [ ] Criar tabela
support_knowledge_gaps - [ ] Workflow para detectar perguntas nΓ£o respondidas
- [ ] Dashboard bΓ‘sico de analytics
Fase 5: Melhorias (ongoing) β
- [ ] Modo hands-free (always listening)
- [ ] Atalhos de teclado (Cmd+K para abrir)
- [ ] IntegraΓ§Γ£o com Slack para escalar dΓΊvidas
- [ ] Tutorial interativo guiado pela IA
π° ESTIMATIVA DE CUSTOS β
Por MΓͺs (estimativa 500 queries) β
| ServiΓ§o | Custo UnitΓ‘rio | Uso Estimado | Total |
|---|---|---|---|
| Claude 3.5 Sonnet | $3/1M tokens | ~100k tokens | ~$0.30 |
| Whisper API | $0.006/min | 50 min voz | ~$0.30 |
| ElevenLabs | $5/mo starter | ilimitado | $5.00 |
| Supabase | incluΓdo | - | $0.00 |
| TOTAL | ~$6/mΓͺs |
Alternativas Gratuitas β
- Whisper local via n8n (CPU-only, mais lento)
- Coqui TTS self-hosted (qualidade inferior)
- gTTS (Google Text-to-Speech gratuito)
β CHECKLIST DE IMPLEMENTAΓΓO β
[ ] 1. Criar migration SQL (013_ai_support_widget.sql)
[ ] 2. Rodar migration no Supabase
[ ] 3. Criar estrutura de pastas no frontend
[ ] 4. Implementar AISupportWidget.tsx (MVP texto)
[ ] 5. Criar workflow n8n 13-AI-Support-Widget
[ ] 6. Testar integraΓ§Γ£o texto completa
[ ] 7. Adicionar sugestΓ΅es contextuais
[ ] 8. Implementar VoiceRecorder.tsx
[ ] 9. Integrar Whisper no n8n
[ ] 10. Integrar ElevenLabs no n8n
[ ] 11. Testar fluxo de voz completo
[ ] 12. Adicionar sistema de feedback
[ ] 13. Documentar no Segundo CΓ©rebro
[ ] 14. Deploy e testes em produΓ§Γ£oπ NOTAS ADICIONAIS β
Alternativa: Gemini Live API β
Se quisermos mΓ‘xima qualidade de voz com emoΓ§Γ£o:
- Usar Gemini 2.5 Flash Native Audio via Vertex AI
- Requer conta GCP com billing
- LatΓͺncia ~200ms (excelente)
- 30 vozes em 24 idiomas
- Custo: ~$0.075/1000 chars
Alternativa: OpenAI Realtime API β
- WebSocket bidirectional
- Voice-to-voice sem intermediΓ‘rio
- Custo: $0.06/min input + $0.24/min output
- Mais caro mas menor latΓͺncia
RecomendaΓ§Γ£o β
ComeΓ§ar com Whisper + Claude + ElevenLabs (mais barato e flexΓvel), depois migrar para Gemini Live se necessΓ‘rio.
Documento criado em: 2026-01-04Γltima atualizaΓ§Γ£o: 2026-01-04Autor: Claude Code + Marcos Daniels
