Skip to content

Latest commit

 

History

History
298 lines (241 loc) · 7.43 KB

File metadata and controls

298 lines (241 loc) · 7.43 KB

🚀 Guia de Integração Rápida - Agentes V4 + Chat Cyberpunk

⚡ 5 Minutos para Começar

Passo 1: Registrar Rotas (1 min)

// backend/src/app.ts
import chatAgentRoutes from '@/routes/chat-agent-integration.routes';

// Adicionar após outras rotas
app.use('/chat', chatAgentRoutes);

Passo 2: Criar Agente (2 min)

// backend/src/services/langchain/agents/my-agent.ts
import { InteractiveQuestion, askInteractiveQuestion, finalizeInteractiveSession } from '@/services/agent-chat-middleware';

export class MyAgent {
  private userId: string;
  private chatSessionId?: string;

  constructor(userId: string) {
    this.userId = userId;
  }

  @InteractiveQuestion('meu tópico')
  async execute() {
    // Perguntas geradas automaticamente
    return { status: 'ready' };
  }

  async processAnswer(question: any, answer: any) {
    if (!this.chatSessionId) throw new Error('No session');
    return askInteractiveQuestion(this.chatSessionId, question, answer);
  }

  async finalize() {
    if (!this.chatSessionId) throw new Error('No session');
    return finalizeInteractiveSession(this.chatSessionId);
  }
}

Passo 3: Usar no Frontend (2 min)

// frontend/src/components/ChatWithAgent.tsx
import { useMutation } from '@tanstack/react-query';
import CyberpunkChat from '@/components/cyberpunk/CyberpunkChat';

export function ChatWithAgent() {
  const startSession = useMutation(async () => {
    const res = await fetch('/chat/start-interactive-session', {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` },
      body: JSON.stringify({
        agentName: 'MyAgent',
        topic: 'meu tópico'
      })
    });
    return res.json();
  });

  return (
    <div>
      <button onClick={() => startSession.mutate()}>
        Iniciar Chat
      </button>
      {startSession.data && (
        <CyberpunkChat 
          sessionId={startSession.data.sessionId}
          questions={startSession.data.questions}
        />
      )}
    </div>
  );
}

📋 Checklist de Implementação

  • Registrar rotas em app.ts
  • Criar agente com @InteractiveQuestion
  • Testar endpoint /chat/start-interactive-session
  • Integrar com frontend
  • Testar fluxo completo
  • Deploy

🧪 Testar Endpoints

# 1. Iniciar sessão
curl -X POST http://localhost:3001/chat/start-interactive-session \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "agentName": "MyAgent",
    "topic": "meu tópico"
  }'

# Resposta esperada:
# {
#   "sessionId": "MyAgent_user123_1234567890",
#   "questions": [
#     {
#       "id": "q1",
#       "question": "Pergunta aqui?",
#       "type": "multiple_choice",
#       "options": ["opção1", "opção2"]
#     }
#   ],
#   "status": "session_started"
# }

# 2. Processar resposta
curl -X POST http://localhost:3001/chat/process-response \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "sessionId": "MyAgent_user123_1234567890",
    "question": {
      "id": "q1",
      "question": "Pergunta aqui?",
      "type": "multiple_choice",
      "options": ["opção1", "opção2"]
    },
    "answer": "opção1"
  }'

# Resposta esperada:
# {
#   "analysis": "Análise da resposta",
#   "confidence": 0.85,
#   "nextQuestions": [...],
#   "status": "response_processed"
# }

# 3. Finalizar sessão
curl -X POST http://localhost:3001/chat/finalize-session \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "sessionId": "MyAgent_user123_1234567890"
  }'

# Resposta esperada:
# {
#   "summary": "Resumo executivo",
#   "insights": ["insight1", "insight2"],
#   "recommendations": ["rec1", "rec2"],
#   "projections": [
#     {"label": "Q1", "value": 30},
#     {"label": "Q2", "value": 45}
#   ],
#   "status": "session_finalized"
# }

🎯 Exemplos Prontos

Strategic Planning Agent

import { StrategicPlanningAgentWithChat } from '@/services/langchain/agents/strategic-planning-agent-with-chat';

const agent = new StrategicPlanningAgentWithChat(userId);
const { questions } = await agent.generateStrategicPlan();
// Processar respostas...
const analysis = await agent.finalizePlan();

Research Agent

import { ResearchAgentWithChat } from '@/services/langchain/agents/strategic-planning-agent-with-chat';

const agent = new ResearchAgentWithChat(userId);
const { findings } = await agent.conductResearch('tema');
// Processar feedback...
const report = await agent.generateReport();

Sales Agent

import { SalesAgentWithChat } from '@/services/langchain/agents/strategic-planning-agent-with-chat';

const agent = new SalesAgentWithChat(userId);
const { qualification } = await agent.qualifyLead(leadInfo);
// Processar qualificação...
const proposal = await agent.generateProposal();

🔧 Troubleshooting

Erro: "Session not found"

✓ Verificar se sessionId está correto
✓ Verificar se sessão não expirou (timeout: 30 min)
✓ Verificar logs do servidor

Erro: "Missing required fields"

✓ Verificar se agentName está preenchido
✓ Verificar se topic está preenchido
✓ Verificar se Authorization header está presente

Perguntas não geradas

✓ Verificar conexão com Gemini
✓ Verificar GEMINI_API_KEY
✓ Verificar logs: docker-compose logs -f backend

Análise incompleta

✓ Verificar se todas as respostas foram processadas
✓ Aumentar timeout se necessário
✓ Verificar memória disponível

📊 Monitoramento

# Ver logs em tempo real
docker-compose logs -f backend

# Verificar saúde
curl http://localhost:3001/health

# Verificar performance
curl http://localhost:3001/metrics

🚀 Deploy

# Build
npm run build

# Deploy frontend
fly deploy --config fly.frontend.toml

# Deploy backend
fly deploy --config fly.backend.toml

# Verificar
curl https://liquid-ai-backend.fly.dev/health

📚 Documentação Completa

💡 Dicas

  1. Começar simples: Crie um agente básico primeiro
  2. Testar localmente: Use curl para testar endpoints
  3. Monitorar logs: Acompanhe os logs durante testes
  4. Otimizar prompts: Ajuste os prompts do Gemini conforme necessário
  5. Cacheamento: Use memória V4 para melhor performance

✅ Checklist Final

  • Rotas registradas
  • Agente criado
  • Endpoints testados
  • Frontend integrado
  • Fluxo completo funcionando
  • Logs monitorados
  • Performance aceitável
  • Deploy realizado

🎉 Pronto!

Você agora tem agentes V4 que podem fazer perguntas interativas através do chat cyberpunk!

┌─────────────────────────────────────┐
│   Agente V4 + Chat Cyberpunk        │
│                                     │
│  ✨ Perguntas interativas           │
│  📊 Análise contextual              │
│  🧠 Insights estratégicos           │
│  💾 Memória persistente             │
│  🚀 Performance otimizada           │
└─────────────────────────────────────┘

Criado com ❤️ para Liquid AI

Última atualização: 2025-12-19