// backend/src/app.ts
import chatAgentRoutes from '@/routes/chat-agent-integration.routes';
// Adicionar após outras rotas
app.use('/chat', chatAgentRoutes);// 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);
}
}// 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>
);
}- Registrar rotas em
app.ts - Criar agente com
@InteractiveQuestion - Testar endpoint
/chat/start-interactive-session - Integrar com frontend
- Testar fluxo completo
- Deploy
# 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"
# }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();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();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();✓ Verificar se sessionId está correto
✓ Verificar se sessão não expirou (timeout: 30 min)
✓ Verificar logs do servidor
✓ Verificar se agentName está preenchido
✓ Verificar se topic está preenchido
✓ Verificar se Authorization header está presente
✓ Verificar conexão com Gemini
✓ Verificar GEMINI_API_KEY
✓ Verificar logs: docker-compose logs -f backend
✓ Verificar se todas as respostas foram processadas
✓ Aumentar timeout se necessário
✓ Verificar memória disponível
# 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# 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- Começar simples: Crie um agente básico primeiro
- Testar localmente: Use curl para testar endpoints
- Monitorar logs: Acompanhe os logs durante testes
- Otimizar prompts: Ajuste os prompts do Gemini conforme necessário
- Cacheamento: Use memória V4 para melhor performance
- Rotas registradas
- Agente criado
- Endpoints testados
- Frontend integrado
- Fluxo completo funcionando
- Logs monitorados
- Performance aceitável
- Deploy realizado
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