docs: Traduzir documentação para português brasileiro

- README.md traduzido para PT-BR
- docs/AGENT_CATALOG.md traduzido para PT-BR
- docs/AI_AGENT_PROTOCOL.md traduzido para PT-BR
- docs/API_REFERENCE.md traduzido para PT-BR
- docs/DEVELOPER_GUIDE.md traduzido para PT-BR
- docs/TROUBLESHOOTING.md traduzido para PT-BR
This commit is contained in:
João Pedro Toledo Goncalves 2026-01-07 21:28:10 -03:00
parent 8add0e08c4
commit 5c04f26907
6 changed files with 696 additions and 696 deletions

150
README.md
View File

@ -1,141 +1,141 @@
# 🧠 Antigravity Brain - Enterprise AI Crew System # 🧠 Antigravity Brain - Sistema de IA Corporativo
A modular **CrewAI** application with shared memory, 26 specialized AI agents, and a web interface powered by **Chainlit**. Uma aplicação modular **CrewAI** com memória compartilhada, 26 agentes de IA especializados, e interface web powered by **Chainlit**.
![Python](https://img.shields.io/badge/Python-3.11+-blue) ![Python](https://img.shields.io/badge/Python-3.11+-blue)
![CrewAI](https://img.shields.io/badge/CrewAI-0.80+-green) ![CrewAI](https://img.shields.io/badge/CrewAI-0.80+-green)
![Docker](https://img.shields.io/badge/Docker-Ready-blue) ![Docker](https://img.shields.io/badge/Docker-Pronto-blue)
![License](https://img.shields.io/badge/License-Private-red) ![License](https://img.shields.io/badge/Licença-Privada-red)
## 🚀 Features ## 🚀 Funcionalidades
- **26 Specialized AI Agents** - From infrastructure (Arthur Mendes, Gus Fring) to sales (Ari Gold, Don Draper) to crisis management (Olivia Pope, Saul Goodman) - **26 Agentes de IA Especializados** - De infraestrutura (Arthur Mendes, Gus Fring) a vendas (Ari Gold, Don Draper) até gestão de crises (Olivia Pope, Saul Goodman)
- **Shared Memory** - Agents share knowledge via Mem0 + Qdrant vector database - **Memória Compartilhada** - Agentes compartilham conhecimento via Mem0 + banco de dados vetorial Qdrant
- **Smart Routing** - Automatic request classification to the appropriate crew - **Roteamento Inteligente** - Classificação automática de solicitações para a equipe apropriada
- **Multi-Provider LLM Support** - Works with Gemini, OpenAI, Anthropic, or local Ollama - **Suporte Multi-Provedor LLM** - Funciona com Gemini, OpenAI, Anthropic, ou Ollama local
- **Web Interface** - Beautiful chat UI powered by Chainlit - **Interface Web** - Interface de chat moderna powered by Chainlit
- **Docker Ready** - One-command deployment with docker-compose - **Pronto para Docker** - Deploy com um único comando via docker-compose
## 📁 Project Structure ## 📁 Estrutura do Projeto
``` ```
minions-da-itguys/ minions-da-itguys/
├── src/ ├── src/
│ ├── app.py # Chainlit entry point │ ├── app.py # Ponto de entrada Chainlit
│ ├── config.py # LLM & Memory configuration │ ├── config.py # Configuração LLM & Memória
│ ├── router.py # Smart request routing │ ├── router.py # Roteamento inteligente de requisições
│ ├── agents/ │ ├── agents/
│ │ ├── factory.py # Agent instantiation │ │ ├── factory.py # Instanciação de agentes
│ │ └── personas/ # 26 agent personality files (.md) │ │ └── personas/ # 26 arquivos de personalidade (.md)
│ ├── crews/ │ ├── crews/
│ │ └── definitions.py # Crew assembly logic │ │ └── definitions.py # Lógica de montagem de crews
│ ├── knowledge/ │ ├── knowledge/
│ │ └── standards/ # Corporate knowledge base │ │ └── standards/ # Base de conhecimento corporativo
│ ├── memory/ │ ├── memory/
│ │ └── wrapper.py # Mem0 integration with rate limiting │ │ └── wrapper.py # Integração Mem0 com rate limiting
│ └── tools/ # Custom tools (Zabbix, Evolution, etc.) │ └── tools/ # Ferramentas customizadas (Zabbix, Evolution, etc.)
├── docker-compose.yml # Container orchestration ├── docker-compose.yml # Orquestração de containers
├── Dockerfile # App container ├── Dockerfile # Container da aplicação
├── requirements.txt # Python dependencies ├── requirements.txt # Dependências Python
└── .env # API keys & configuration └── .env # Chaves de API & configuração
``` ```
## 🛠️ Installation ## 🛠️ Instalação
### Prerequisites ### Pré-requisitos
- Docker & Docker Compose - Docker & Docker Compose
- Python 3.11+ (for local development) - Python 3.11+ (para desenvolvimento local)
- Gemini/OpenAI API Key - Chave de API Gemini/OpenAI
### Quick Start (Docker) ### Início Rápido (Docker)
```bash ```bash
# 1. Clone the repository # 1. Clone o repositório
git clone https://github.com/your-org/minions-da-itguys.git git clone https://github.com/your-org/minions-da-itguys.git
cd minions-da-itguys cd minions-da-itguys
# 2. Configure environment # 2. Configure o ambiente
cp .env.example .env cp .env.example .env
# Edit .env with your API keys # Edite o .env com suas chaves de API
# 3. Start the application # 3. Inicie a aplicação
docker-compose up -d docker-compose up -d
# 4. Access the web interface # 4. Acesse a interface web
open http://localhost:8000 open http://localhost:8000
``` ```
### Local Development ### Desenvolvimento Local
```bash ```bash
# Install dependencies # Instale as dependências
pip install -r requirements.txt pip install -r requirements.txt
# Run Chainlit # Execute o Chainlit
chainlit run src/app.py --port 8000 chainlit run src/app.py --port 8000
``` ```
## ⚙️ Configuration ## ⚙️ Configuração
Edit `.env` to configure the AI backend: Edite o `.env` para configurar o backend de IA:
```env ```env
# LLM Provider: gemini, openai, anthropic, ollama # Provedor LLM: gemini, openai, anthropic, ollama
LLM_PROVIDER=gemini LLM_PROVIDER=gemini
LLM_MODEL_FAST=gemini-2.5-flash-lite-preview-06-17 LLM_MODEL_FAST=gemini-2.5-flash-lite-preview-06-17
LLM_MODEL_SMART=gemini-2.5-flash-lite-preview-06-17 LLM_MODEL_SMART=gemini-2.5-flash-lite-preview-06-17
GEMINI_API_KEY=your-api-key GEMINI_API_KEY=sua-chave-api
# Memory: qdrant (local) or mem0 (cloud) # Memória: qdrant (local) ou mem0 (nuvem)
MEMORY_PROVIDER=qdrant MEMORY_PROVIDER=qdrant
MEMORY_EMBEDDING_PROVIDER=local MEMORY_EMBEDDING_PROVIDER=local
``` ```
## 🤖 Available Crews ## 🤖 Crews Disponíveis
| Crew | Agents | Purpose | | Crew | Agentes | Propósito |
|------|--------|---------| |------|---------|-----------|
| **Infra Engineering** | Arthur Mendes, Gus Fring | Zabbix templates, monitoring | | **Engenharia de Infra** | Arthur Mendes, Gus Fring | Templates Zabbix, monitoramento |
| **Security Audit** | Elliot Alderson, Devil | Vulnerability assessment | | **Auditoria de Segurança** | Elliot Alderson, Devil | Avaliação de vulnerabilidades |
| **HR & Evolution** | The Architect, Sherlock | Create agents, learn policies | | **RH & Evolução** | The Architect, Sherlock | Criar agentes, aprender políticas |
| **Sales Growth** | Ari Gold, Chris Gardner, Don Draper | Pipeline management | | **Crescimento de Vendas** | Ari Gold, Chris Gardner, Don Draper | Gestão de pipeline |
| **Business Strategy** | Harvey Specter, Kevin O'Leary | Compliance, ROI analysis | | **Estratégia de Negócios** | Harvey Specter, Kevin O'Leary | Compliance, análise de ROI |
## 🧪 Usage Examples ## 🧪 Exemplos de Uso
``` ```
User: "Validate this Zabbix template" Usuário: "Valide este template Zabbix"
→ Routes to: Infra Engineering (Zabbix) → Roteado para: Engenharia de Infra (Zabbix)
→ Arthur validates YAML, fixes UUIDs, Gus reviews → Arthur valida YAML, corrige UUIDs, Gus revisa
User: "Create a new agent named Bob for DevOps" Usuário: "Crie um novo agente chamado Bob para DevOps"
→ Routes to: HR & Evolution → Roteado para: RH & Evolução
→ The Architect spawns new persona file → The Architect gera novo arquivo de persona
User: "Analyze security of our login page" Usuário: "Analise a segurança da nossa página de login"
→ Routes to: Security Audit → Roteado para: Auditoria de Segurança
→ Elliot performs reconnaissance → Elliot realiza reconhecimento
``` ```
## 📦 Dependencies ## 📦 Dependências
- `crewai` - Multi-agent orchestration - `crewai` - Orquestração multi-agente
- `chainlit` - Web UI - `chainlit` - Interface Web
- `mem0ai` - Shared memory - `mem0ai` - Memória compartilhada
- `qdrant-client` - Vector database - `qdrant-client` - Banco de dados vetorial
- `litellm` - Multi-provider LLM support - `litellm` - Suporte multi-provedor LLM
- `sentence-transformers` - Local embeddings - `sentence-transformers` - Embeddings locais
## 🔒 Security Notes ## 🔒 Notas de Segurança
- Never commit `.env` with real API keys - Nunca commite `.env` com chaves de API reais
- The `.env.example` contains safe placeholder values - O `.env.example` contém valores de placeholder seguros
- Memory is persisted in Docker volume `qdrant_data` - A memória é persistida no volume Docker `qdrant_data`
## 📝 License ## 📝 Licença
Private - ITGuys Internal Use Only Privada - Uso Interno ITGuys Apenas
--- ---
Built with ❤️ by ITGuys Feito com ❤️ pela ITGuys

View File

@ -1,235 +1,235 @@
# 🤖 Agent Catalog # 🤖 Catálogo de Agentes
Complete list of all 26 AI agents available in the Antigravity Brain system. Lista completa de todos os 26 agentes de IA disponíveis no sistema Antigravity Brain.
--- ---
## 🛠️ Infrastructure Agents ## 🛠️ Agentes de Infraestrutura
### Arthur Mendes ### Arthur Mendes
- **File:** `persona-arthur-mendes.md` - **Arquivo:** `persona-arthur-mendes.md`
- **Role:** Senior SRE & Monitoring Architect - **Papel:** SRE Sênior & Arquiteto de Monitoramento
- **Specialty:** Zabbix templates, YAML validation, UUID fixing - **Especialidade:** Templates Zabbix, validação YAML, correção de UUID
- **Tools:** ZabbixValidatorTool, UUIDFixerTool - **Ferramentas:** ZabbixValidatorTool, UUIDFixerTool
- **Crews:** Infra Engineering (Zabbix) - **Crews:** Engenharia de Infra (Zabbix)
### Gus Fring ### Gus Fring
- **File:** `persona-gus-fring.md` - **Arquivo:** `persona-gus-fring.md`
- **Role:** Operations Director - **Papel:** Diretor de Operações
- **Specialty:** Stability, quality assurance, no half-measures - **Especialidade:** Estabilidade, garantia de qualidade, sem meias-medidas
- **Tools:** None (Reviewer) - **Ferramentas:** Nenhuma (Revisor)
- **Crews:** Infra Engineering (Zabbix), Infra Support - **Crews:** Engenharia de Infra (Zabbix), Suporte de Infra
### Tony Stark ### Tony Stark
- **File:** `persona-tony-stark.md` - **Arquivo:** `persona-tony-stark.md`
- **Role:** Automation Engineer - **Papel:** Engenheiro de Automação
- **Specialty:** DevOps automation, infrastructure as code - **Especialidade:** Automação DevOps, infraestrutura como código
- **Tools:** AutoCommitTool, ScaffoldMakerTool - **Ferramentas:** AutoCommitTool, ScaffoldMakerTool
- **Crews:** Infra Support - **Crews:** Suporte de Infra
### Linus Torvalds ### Linus Torvalds
- **File:** `persona-linus-torvalds.md` - **Arquivo:** `persona-linus-torvalds.md`
- **Role:** Performance Architect - **Papel:** Arquiteto de Performance
- **Specialty:** System optimization, code efficiency - **Especialidade:** Otimização de sistemas, eficiência de código
- **Tools:** FileStatsTool - **Ferramentas:** FileStatsTool
- **Crews:** Code Audit - **Crews:** Auditoria de Código
--- ---
## 🔐 Security Agents ## 🔐 Agentes de Segurança
### Elliot Alderson ### Elliot Alderson
- **File:** `persona-elliot-alderson.md` - **Arquivo:** `persona-elliot-alderson.md`
- **Role:** Offensive Security Specialist - **Papel:** Especialista em Segurança Ofensiva
- **Specialty:** Penetration testing, vulnerability discovery - **Especialidade:** Testes de penetração, descoberta de vulnerabilidades
- **Tools:** QASnapshotTool, RouteScannerTool - **Ferramentas:** QASnapshotTool, RouteScannerTool
- **Crews:** Security Audit - **Crews:** Auditoria de Segurança
### Devil (The Adversary) ### Devil (O Adversário)
- **File:** `persona-devil.md` - **Arquivo:** `persona-devil.md`
- **Role:** QA & Exploit Tester - **Papel:** QA & Testador de Exploits
- **Specialty:** Finding edge cases, breaking things - **Especialidade:** Encontrar casos extremos, quebrar coisas
- **Tools:** QASnapshotTool, VisualProofTool - **Ferramentas:** QASnapshotTool, VisualProofTool
- **Crews:** Security Audit - **Crews:** Auditoria de Segurança
### The Architect ### The Architect
- **File:** `persona-the-architect.md` - **Arquivo:** `persona-the-architect.md`
- **Role:** System Auditor & Designer - **Papel:** Auditor de Sistemas & Designer
- **Specialty:** Architecture review, technical debt analysis - **Especialidade:** Revisão de arquitetura, análise de débito técnico
- **Tools:** ProjectMapTool, TodoTrackerTool, SpawnAgentTool - **Ferramentas:** ProjectMapTool, TodoTrackerTool, SpawnAgentTool
- **Crews:** Code Audit, HR & Evolution - **Crews:** Auditoria de Código, RH & Evolução
--- ---
## 💼 Business Agents ## 💼 Agentes de Negócios
### Harvey Specter ### Harvey Specter
- **File:** `persona-harvey-specter.md` - **Arquivo:** `persona-harvey-specter.md`
- **Role:** Legal & Compliance Lead - **Papel:** Líder de Jurídico & Compliance
- **Specialty:** LGPD/GDPR compliance, risk assessment - **Especialidade:** Conformidade LGPD/GDPR, avaliação de riscos
- **Tools:** None (Reviewer) - **Ferramentas:** Nenhuma (Revisor)
- **Crews:** Business Strategy - **Crews:** Estratégia de Negócios
### Kevin O'Leary ### Kevin O'Leary
- **File:** `persona-kevin-oleary.md` - **Arquivo:** `persona-kevin-oleary.md`
- **Role:** ROI Analyst - **Papel:** Analista de ROI
- **Specialty:** Cost-benefit analysis, investment decisions - **Especialidade:** Análise custo-benefício, decisões de investimento
- **Tools:** None (Reviewer) - **Ferramentas:** Nenhuma (Revisor)
- **Crews:** Business Strategy - **Crews:** Estratégia de Negócios
### Marie Kondo ### Marie Kondo
- **File:** `persona-marie-kondo.md` - **Arquivo:** `persona-marie-kondo.md`
- **Role:** Process Optimizer - **Papel:** Otimizadora de Processos
- **Specialty:** Cleanup, simplification, "does it spark joy?" - **Especialidade:** Limpeza, simplificação, "isso te traz alegria?"
- **Tools:** TodoTrackerTool - **Ferramentas:** TodoTrackerTool
- **Crews:** Business Strategy - **Crews:** Estratégia de Negócios
--- ---
## 💰 Sales Agents (The Hunters) ## 💰 Agentes de Vendas (Os Caçadores)
### Ari Gold ### Ari Gold
- **File:** `persona-ari-gold.md` - **Arquivo:** `persona-ari-gold.md`
- **Role:** Closer & Negotiator - **Papel:** Closer & Negociador
- **Specialty:** Deal closing, upselling, aggressive tactics - **Especialidade:** Fechamento de negócios, upselling, táticas agressivas
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Sales Growth - **Crews:** Crescimento de Vendas
### Chris Gardner ### Chris Gardner
- **File:** `persona-chris-gardner.md` - **Arquivo:** `persona-chris-gardner.md`
- **Role:** Prospector - **Papel:** Prospector
- **Specialty:** Lead generation, resilience, cold outreach - **Especialidade:** Geração de leads, resiliência, prospecção ativa
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Sales Growth - **Crews:** Crescimento de Vendas
### Don Draper ### Don Draper
- **File:** `persona-don-draper.md` - **Arquivo:** `persona-don-draper.md`
- **Role:** Pitch Master - **Papel:** Mestre do Pitch
- **Specialty:** Storytelling, presentations, emotional appeal - **Especialidade:** Storytelling, apresentações, apelo emocional
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Sales Growth - **Crews:** Crescimento de Vendas
### Jerry Maguire ### Jerry Maguire
- **File:** `persona-jerry-maguire.md` - **Arquivo:** `persona-jerry-maguire.md`
- **Role:** Relationship Manager - **Papel:** Gerente de Relacionamento
- **Specialty:** Client retention, personal connections - **Especialidade:** Retenção de clientes, conexões pessoais
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Sales Growth - **Crews:** Crescimento de Vendas
--- ---
## 🌱 Customer Success Agents (The Farmers) ## 🌱 Agentes de Sucesso do Cliente (Os Cultivadores)
### Jim Halpert ### Jim Halpert
- **File:** `persona-jim-halpert.md` - **Arquivo:** `persona-jim-halpert.md`
- **Role:** Support Specialist - **Papel:** Especialista de Suporte
- **Specialty:** Low-friction resolution, casual approach - **Especialidade:** Resolução de baixo atrito, abordagem casual
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Customer Success - **Crews:** Sucesso do Cliente
### Leslie Knope ### Leslie Knope
- **File:** `persona-leslie-knope.md` - **Arquivo:** `persona-leslie-knope.md`
- **Role:** Onboarding Specialist - **Papel:** Especialista de Onboarding
- **Specialty:** Documentation, processes, binders - **Especialidade:** Documentação, processos, fichários organizados
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Customer Success - **Crews:** Sucesso do Cliente
### Ted Lasso ### Ted Lasso
- **File:** `persona-ted-lasso.md` - **Arquivo:** `persona-ted-lasso.md`
- **Role:** Retention Coach - **Papel:** Coach de Retenção
- **Specialty:** Morale boosting, belief, loyalty - **Especialidade:** Elevar moral, crença, lealdade
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Customer Success - **Crews:** Sucesso do Cliente
--- ---
## 🚨 Crisis Agents (The Fixers) ## 🚨 Agentes de Crise (Os Reparadores)
### Olivia Pope ### Olivia Pope
- **File:** `persona-olivia-pope.md` - **Arquivo:** `persona-olivia-pope.md`
- **Role:** Crisis Manager - **Papel:** Gerente de Crises
- **Specialty:** PR control, narrative management - **Especialidade:** Controle de PR, gestão de narrativa
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Corporate Defense - **Crews:** Defesa Corporativa
### Saul Goodman ### Saul Goodman
- **File:** `persona-saul-goodman.md` - **Arquivo:** `persona-saul-goodman.md`
- **Role:** Legal Fixer - **Papel:** Reparador Jurídico
- **Specialty:** Loopholes, creative solutions, damage control - **Especialidade:** Brechas legais, soluções criativas, controle de danos
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Corporate Defense - **Crews:** Defesa Corporativa
### Tyrion Lannister ### Tyrion Lannister
- **File:** `persona-tyrion-lannister.md` - **Arquivo:** `persona-tyrion-lannister.md`
- **Role:** Strategic Advisor - **Papel:** Conselheiro Estratégico
- **Specialty:** Long-term strategy, political maneuvering - **Especialidade:** Estratégia de longo prazo, manobras políticas
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Corporate Defense - **Crews:** Defesa Corporativa
--- ---
## 🎨 Creative & Technical Agents ## 🎨 Agentes Criativos & Técnicos
### Steve Jobs ### Steve Jobs
- **File:** `persona-steve-jobs.md` - **Arquivo:** `persona-steve-jobs.md`
- **Role:** Product Designer - **Papel:** Designer de Produto
- **Specialty:** UX excellence, design thinking - **Especialidade:** Excelência em UX, design thinking
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Creative - **Crews:** Criativo
### Hannibal Lecter ### Hannibal Lecter
- **File:** `persona-hannibal-lecter.md` - **Arquivo:** `persona-hannibal-lecter.md`
- **Role:** User Psychology Analyst - **Papel:** Analista de Psicologia do Usuário
- **Specialty:** Behavioral analysis, user motivation - **Especialidade:** Análise comportamental, motivação do usuário
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Creative - **Crews:** Criativo
### Gordon Ramsay ### Gordon Ramsay
- **File:** `persona-gordon-ramsay.md` - **Arquivo:** `persona-gordon-ramsay.md`
- **Role:** Code Reviewer - **Papel:** Revisor de Código
- **Specialty:** Strict standards, brutal honesty - **Especialidade:** Padrões rigorosos, honestidade brutal
- **Tools:** CodeFormatterTool - **Ferramentas:** CodeFormatterTool
- **Crews:** Code Audit, Zabbix Engineering - **Crews:** Auditoria de Código, Engenharia Zabbix
### Walter White ### Walter White
- **File:** `persona-walter-white.md` - **Arquivo:** `persona-walter-white.md`
- **Role:** Architecture Purist - **Papel:** Purista de Arquitetura
- **Specialty:** Clean architecture, no compromises - **Especialidade:** Arquitetura limpa, sem compromissos
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Code Audit - **Crews:** Auditoria de Código
### The Gremlin ### The Gremlin
- **File:** `persona-gremlin.md` - **Arquivo:** `persona-gremlin.md`
- **Role:** Chaos Engineer - **Papel:** Engenheiro do Caos
- **Specialty:** Stress testing, breaking things intentionally - **Especialidade:** Testes de stress, quebrar coisas intencionalmente
- **Tools:** None - **Ferramentas:** Nenhuma
- **Crews:** Security Audit - **Crews:** Auditoria de Segurança
### Sherlock Holmes ### Sherlock Holmes
- **File:** `persona-sherlock-holmes.md` - **Arquivo:** `persona-sherlock-holmes.md`
- **Role:** Data Investigator - **Papel:** Investigador de Dados
- **Specialty:** Logic, deduction, pattern recognition - **Especialidade:** Lógica, dedução, reconhecimento de padrões
- **Tools:** CodeSearchTool, LearnPolicyTool - **Ferramentas:** CodeSearchTool, LearnPolicyTool
- **Crews:** HR & Evolution - **Crews:** RH & Evolução
--- ---
## 📊 Agent Summary by Crew ## 📊 Resumo de Agentes por Crew
| Crew | Agents | | Crew | Agentes |
|------|--------| |------|---------|
| **Infra Engineering (Zabbix)** | Arthur Mendes, Gus Fring | | **Engenharia de Infra (Zabbix)** | Arthur Mendes, Gus Fring |
| **Infra Support** | Gus Fring, Tony Stark, Elliot Alderson | | **Suporte de Infra** | Gus Fring, Tony Stark, Elliot Alderson |
| **Security Audit** | Elliot Alderson, Devil | | **Auditoria de Segurança** | Elliot Alderson, Devil |
| **Code Audit** | The Architect, Linus Torvalds, Gordon Ramsay | | **Auditoria de Código** | The Architect, Linus Torvalds, Gordon Ramsay |
| **Business Strategy** | Harvey Specter, Kevin O'Leary, Marie Kondo | | **Estratégia de Negócios** | Harvey Specter, Kevin O'Leary, Marie Kondo |
| **Sales Growth** | Ari Gold, Chris Gardner, Don Draper, Jerry Maguire | | **Crescimento de Vendas** | Ari Gold, Chris Gardner, Don Draper, Jerry Maguire |
| **Customer Success** | Jim Halpert, Leslie Knope, Ted Lasso | | **Sucesso do Cliente** | Jim Halpert, Leslie Knope, Ted Lasso |
| **Corporate Defense** | Olivia Pope, Saul Goodman, Tyrion Lannister | | **Defesa Corporativa** | Olivia Pope, Saul Goodman, Tyrion Lannister |
| **HR & Evolution** | The Architect, Sherlock Holmes | | **RH & Evolução** | The Architect, Sherlock Holmes |
--- ---
## 🆕 How to Create New Agents ## 🆕 Como Criar Novos Agentes
See [DEVELOPER_GUIDE.md](./DEVELOPER_GUIDE.md#adding-new-agents) Veja [DEVELOPER_GUIDE.md](./DEVELOPER_GUIDE.md#adicionando-novos-agentes)

View File

@ -1,162 +1,162 @@
# 🤖 AI Agent Protocol # 🤖 Protocolo para Agentes de IA
**READ THIS BEFORE WORKING ON THE CODEBASE** **LEIA ISTO ANTES DE TRABALHAR NO CÓDIGO**
This document defines the mandatory protocols for AI agents working on the Antigravity Brain project. Este documento define os protocolos obrigatórios para agentes de IA trabalhando no projeto Antigravity Brain.
--- ---
## 🎯 Prime Directives ## 🎯 Diretivas Primárias
1. **READ KNOWLEDGE FIRST** - Before writing ANY code, read relevant `src/knowledge/standards/*.md` 1. **LEIA O CONHECIMENTO PRIMEIRO** - Antes de escrever QUALQUER código, leia os `src/knowledge/standards/*.md` relevantes
2. **NEVER HARDCODE SECRETS** - Use `Config` class and environment variables 2. **NUNCA HARDCODE SEGREDOS** - Use a classe `Config` e variáveis de ambiente
3. **TOOLS MUST NOT RAISE** - Always return error strings, never raise exceptions 3. **FERRAMENTAS NÃO DEVEM LANÇAR EXCEÇÕES** - Sempre retorne strings de erro, nunca raise exceptions
4. **TEST BEFORE COMMIT** - Verify changes with `docker-compose restart app` 4. **TESTE ANTES DE COMMITAR** - Verifique alterações com `docker-compose restart app`
--- ---
## 📖 Required Reading by Task Type ## 📖 Leitura Obrigatória por Tipo de Tarefa
| Task | Must Read First | | Tarefa | Deve Ler Primeiro |
|------|-----------------| |--------|-------------------|
| Python tools | `python_tool_standards.md` | | Ferramentas Python | `python_tool_standards.md` |
| Docker changes | `docker_standards.md` | | Alterações Docker | `docker_standards.md` |
| New agents | `DEVELOPER_GUIDE.md#adding-new-agents` | | Novos agentes | `DEVELOPER_GUIDE.md#adicionando-novos-agentes` |
| Database | `database_standards.md` | | Banco de dados | `database_standards.md` |
| Security | `security_standards.md` | | Segurança | `security_standards.md` |
| Git operations | `git_standards.md` | | Operações Git | `git_standards.md` |
| UI changes | `ui_ux_standards.md` | | Alterações de UI | `ui_ux_standards.md` |
--- ---
## ✅ Code Change Checklist ## ✅ Checklist de Alteração de Código
Before making any change: Antes de fazer qualquer alteração:
- [ ] Read relevant standards file - [ ] Ler arquivo de padrões relevante
- [ ] Check if pattern already exists in codebase - [ ] Verificar se o padrão já existe no código
- [ ] Plan change with minimal impact - [ ] Planejar alteração com impacto mínimo
- [ ] Add error handling - [ ] Adicionar tratamento de erros
- [ ] Test locally - [ ] Testar localmente
After making change: Após fazer a alteração:
- [ ] Restart container: `docker-compose restart app` - [ ] Reiniciar container: `docker-compose restart app`
- [ ] Check logs for errors: `docker logs antigravity_brain --tail 50` - [ ] Verificar logs por erros: `docker logs antigravity_brain --tail 50`
- [ ] Verify functionality works - [ ] Verificar se a funcionalidade funciona
- [ ] Commit with proper message format - [ ] Commitar com formato de mensagem adequado
--- ---
## 📝 Commit Message Format ## 📝 Formato de Mensagem de Commit
``` ```
<type>: <short description> <tipo>: <descrição curta>
<optional body> <corpo opcional>
``` ```
Types: Tipos:
- `feat:` New feature - `feat:` Nova funcionalidade
- `fix:` Bug fix - `fix:` Correção de bug
- `docs:` Documentation - `docs:` Documentação
- `refactor:` Code cleanup - `refactor:` Limpeza de código
- `test:` Tests - `test:` Testes
- `chore:` Maintenance - `chore:` Manutenção
Example: Exemplo:
``` ```
feat: Add new DevOps agent persona feat: Adicionar nova persona de agente DevOps
- Created persona-devops-dan.md - Criado persona-devops-dan.md
- Added to Infrastructure crew - Adicionado à crew de Infraestrutura
- Assigned Docker tools - Atribuídas ferramentas Docker
``` ```
--- ---
## 🔧 Tool Development Protocol ## 🔧 Protocolo de Desenvolvimento de Ferramentas
```python ```python
class MyTool(BaseTool): class MinhaTool(BaseTool):
name: str = "Descriptive Name" # Agent reads this name: str = "Nome Descritivo" # Agente lê isto
description: str = ( description: str = (
"DETAILED description of when to use this tool. " "Descrição DETALHADA de quando usar esta ferramenta. "
"Include example inputs and expected outputs." "Inclua exemplos de entrada e saídas esperadas."
) )
args_schema: type = MyToolInput # Pydantic model with Field descriptions args_schema: type = MinhaToolInput # Modelo Pydantic com descrições Field
def _run(self, **kwargs) -> str: def _run(self, **kwargs) -> str:
try: try:
# Your logic # Sua lógica
return "Success: ..." return "Sucesso: ..."
except SpecificError as e: except ErroEspecifico as e:
return f"Error: Specific handling for {e}" return f"Erro: Tratamento específico para {e}"
except Exception as e: except Exception as e:
return f"Error: Unexpected - {str(e)[:100]}" return f"Erro: Inesperado - {str(e)[:100]}"
``` ```
**NEVER:** **NUNCA:**
- Use `input()` for user interaction - Use `input()` para interação com usuário
- Raise exceptions - Lance exceções
- Return raw JSON (use narrative text) - Retorne JSON bruto (use texto narrativo)
- Use `Any` type hints - Use type hints `Any`
--- ---
## 🤖 Agent Development Protocol ## 🤖 Protocolo de Desenvolvimento de Agentes
### Persona Files ### Arquivos de Persona
1. Use YAML frontmatter for metadata 1. Use frontmatter YAML para metadados
2. Include `**Role:**` and `**Goal:**` fields 2. Inclua campos `**Papel:**` e `**Objetivo:**`
3. Write backstory in character voice 3. Escreva backstory na voz do personagem
4. Define clear protocols/procedures 4. Defina protocolos/procedimentos claros
### Tool Assignment ### Atribuição de Ferramentas
- Only assign tools the agent actually needs - Atribua apenas ferramentas que o agente realmente precisa
- Consider `model_tier`: tools requiring reasoning`smart` - Considere `model_tier`: ferramentas que requerem raciocínio`smart`
- Memory tools are auto-assigned to all agents - Ferramentas de memória são auto-atribuídas a todos os agentes
--- ---
## 📁 File Placement Rules ## 📁 Regras de Localização de Arquivos
| Content Type | Location | | Tipo de Conteúdo | Localização |
|--------------|----------| |------------------|-------------|
| Agent personas | `src/agents/personas/persona-*.md` | | Personas de agentes | `src/agents/personas/persona-*.md` |
| Tools | `src/tools/*.py` | | Ferramentas | `src/tools/*.py` |
| Knowledge standards | `src/knowledge/standards/*.md` | | Padrões de conhecimento | `src/knowledge/standards/*.md` |
| Dynamic knowledge | `src/knowledge/dynamic/*/*.md` | | Conhecimento dinâmico | `src/knowledge/dynamic/*/*.md` |
| Crew definitions | `src/crews/definitions.py` | | Definições de crew | `src/crews/definitions.py` |
| Configuration | `src/config.py` | | Configuração | `src/config.py` |
--- ---
## ⚠️ Common Mistakes to Avoid ## ⚠️ Erros Comuns a Evitar
### 1. Variable Names in Standards ### 1. Nomes de Variáveis em Padrões
BAD: ERRADO:
```python ```python
return f"Error: File '{path}' not found" # {path} interpreted as template return f"Erro: Arquivo '{path}' não encontrado" # {path} interpretado como template
``` ```
GOOD: CORRETO:
```python ```python
return f"Error: File 'PATH_VAR' not found" # Escaped return f"Erro: Arquivo 'PATH_VAR' não encontrado" # Escapado
``` ```
### 2. Missing Rate Limiting ### 2. Rate Limiting Ausente
BAD: ERRADO:
```python ```python
while True: while True:
api.call() # Burns quota instantly api.call() # Queima cota instantaneamente
``` ```
GOOD: CORRETO:
```python ```python
for attempt in range(MAX_RETRIES): for attempt in range(MAX_RETRIES):
result = api.call() result = api.call()
@ -164,52 +164,52 @@ for attempt in range(MAX_RETRIES):
time.sleep(DELAY * (2 ** attempt)) time.sleep(DELAY * (2 ** attempt))
``` ```
### 3. Hardcoded Configuration ### 3. Configuração Hardcoded
BAD: ERRADO:
```python ```python
model = "gpt-4" model = "gpt-4"
api_key = "sk-xxx" api_key = "sk-xxx"
``` ```
GOOD: CORRETO:
```python ```python
config = Config.get_llm_config(mode="smart") config = Config.get_llm_config(mode="smart")
``` ```
--- ---
## 🧪 Testing Protocol ## 🧪 Protocolo de Teste
1. **Local test:** 1. **Teste local:**
```bash ```bash
docker-compose restart app docker-compose restart app
docker logs antigravity_brain --tail 50 docker logs antigravity_brain --tail 50
``` ```
2. **Verify no errors:** 2. **Verificar ausência de erros:**
```bash ```bash
docker logs antigravity_brain 2>&1 | findstr "Error ERROR Exception" docker logs antigravity_brain 2>&1 | findstr "Error ERROR Exception"
``` ```
3. **Interactive test:** 3. **Teste interativo:**
- Open http://localhost:8000 - Abra http://localhost:8000
- Send test message - Envie mensagem de teste
- Verify correct crew routing - Verifique roteamento correto de crew
- Check agent response - Confira resposta do agente
--- ---
## 🚀 Deployment Protocol ## 🚀 Protocolo de Deploy
1. **Commit changes:** 1. **Commitar alterações:**
```bash ```bash
git add . git add .
git commit -m "feat: Description" git commit -m "feat: Descrição"
git push git push
``` ```
2. **On production server:** 2. **No servidor de produção:**
```bash ```bash
git pull git pull
docker-compose build --no-cache app docker-compose build --no-cache app
@ -218,4 +218,4 @@ config = Config.get_llm_config(mode="smart")
--- ---
**Remember:** Quality over speed. Read the standards. Test your changes. **Lembre-se:** Qualidade acima de velocidade. Leia os padrões. Teste suas alterações.

View File

@ -1,27 +1,27 @@
# 🔧 API & Code Reference # 🔧 Referência de API & Código
Technical reference for the Antigravity Brain codebase. Referência técnica para o código do Antigravity Brain.
--- ---
## 📦 Core Modules ## 📦 Módulos Principais
### src/config.py ### src/config.py
Central configuration hub. Hub central de configuração.
```python ```python
from src.config import Config from src.config import Config
# Get LLM configuration # Obter configuração LLM
llm_config = Config.get_llm_config(mode="smart") # or "fast" llm_config = Config.get_llm_config(mode="smart") # ou "fast"
# Returns: {"model": "gemini/...", "temperature": 0.7, "api_key": "..."} # Retorna: {"model": "gemini/...", "temperature": 0.7, "api_key": "..."}
# Get Memory configuration # Obter configuração de Memória
mem_config = Config.get_mem0_config() mem_config = Config.get_mem0_config()
# Returns: {"llm": {...}, "embedder": {...}, "vector_store": {...}} # Retorna: {"llm": {...}, "embedder": {...}, "vector_store": {...}}
# Get Telegram token # Obter token do Telegram
token = Config.get_telegram_token() token = Config.get_telegram_token()
``` ```
@ -29,15 +29,15 @@ token = Config.get_telegram_token()
### src/agents/factory.py ### src/agents/factory.py
Agent creation from persona files. Criação de agentes a partir de arquivos de persona.
```python ```python
from src.agents.factory import AgentFactory from src.agents.factory import AgentFactory
# Create agent with default tools # Criar agente com ferramentas padrão
agent = AgentFactory.create_agent("arthur-mendes", model_tier="smart") agent = AgentFactory.create_agent("arthur-mendes", model_tier="smart")
# Create agent with specific tools # Criar agente com ferramentas específicas
from src.tools.zabbix import ZabbixValidatorTool from src.tools.zabbix import ZabbixValidatorTool
agent = AgentFactory.create_agent( agent = AgentFactory.create_agent(
"arthur-mendes", "arthur-mendes",
@ -45,180 +45,180 @@ agent = AgentFactory.create_agent(
model_tier="smart" model_tier="smart"
) )
# List available personas # Listar personas disponíveis
personas = AgentFactory.list_available_personas() personas = AgentFactory.list_available_personas()
# Returns: ["persona-arthur-mendes", "persona-gus-fring", ...] # Retorna: ["persona-arthur-mendes", "persona-gus-fring", ...]
# Load corporate knowledge # Carregar conhecimento corporativo
knowledge = AgentFactory.load_knowledge_base() knowledge = AgentFactory.load_knowledge_base()
# Returns concatenated string of all standards/*.md files # Retorna string concatenada de todos os arquivos standards/*.md
``` ```
--- ---
### src/crews/definitions.py ### src/crews/definitions.py
Crew assembly and management. Montagem e gerenciamento de crews.
```python ```python
from src.crews.definitions import CrewDefinitions from src.crews.definitions import CrewDefinitions
# Get available crews # Obter crews disponíveis
crews = CrewDefinitions.get_available_crews() crews = CrewDefinitions.get_available_crews()
# Returns: ["Infra Engineering (Zabbix)", "Security Audit", ...] # Retorna: ["Engenharia de Infra (Zabbix)", "Auditoria de Segurança", ...]
# Assemble a crew # Montar uma crew
crew = CrewDefinitions.assemble_crew( crew = CrewDefinitions.assemble_crew(
crew_name="Infra Engineering (Zabbix)", crew_name="Engenharia de Infra (Zabbix)",
inputs={"topic": "Validate this template"} inputs={"topic": "Validar este template"}
) )
# Execute crew # Executar crew
result = crew.kickoff(inputs={"topic": "Your task here"}) result = crew.kickoff(inputs={"topic": "Sua tarefa aqui"})
``` ```
--- ---
### src/router.py ### src/router.py
Smart request routing using LLM. Roteamento inteligente de requisições usando LLM.
```python ```python
from src.router import SmartRouter from src.router import SmartRouter
# Route a user request to appropriate crew # Rotear requisição de usuário para crew apropriada
crew_name = SmartRouter.route("Check server health") crew_name = SmartRouter.route("Verificar saúde do servidor")
# Returns: "Infra Engineering (Zabbix)" # Retorna: "Engenharia de Infra (Zabbix)"
crew_name = SmartRouter.route("Create a new agent") crew_name = SmartRouter.route("Criar um novo agente")
# Returns: "HR & Evolution" # Retorna: "RH & Evolução"
``` ```
--- ---
### src/memory/wrapper.py ### src/memory/wrapper.py
Memory tools with rate limiting. Ferramentas de memória com rate limiting.
```python ```python
from src.memory.wrapper import SearchMemoryTool, SaveMemoryTool, MemoryWrapper from src.memory.wrapper import SearchMemoryTool, SaveMemoryTool, MemoryWrapper
# Get memory client # Obter cliente de memória
client = MemoryWrapper.get_client() client = MemoryWrapper.get_client()
# Use as tools (typically assigned to agents) # Usar como ferramentas (tipicamente atribuídas a agentes)
search_tool = SearchMemoryTool() search_tool = SearchMemoryTool()
result = search_tool._run(query="What do we know about Zabbix?") result = search_tool._run(query="O que sabemos sobre Zabbix?")
save_tool = SaveMemoryTool() save_tool = SaveMemoryTool()
result = save_tool._run(fact="The server runs on port 8000") result = save_tool._run(fact="O servidor roda na porta 8000")
``` ```
--- ---
## 🔧 Available Tools ## 🔧 Ferramentas Disponíveis
### Memory Tools (src/memory/wrapper.py) ### Ferramentas de Memória (src/memory/wrapper.py)
| Tool | Input | Output | | Ferramenta | Entrada | Saída |
|------|-------|--------| |------------|---------|-------|
| `SearchMemoryTool` | `query: str` | Found memories or "No relevant information" | | `SearchMemoryTool` | `query: str` | Memórias encontradas ou "Nenhuma informação relevante" |
| `SaveMemoryTool` | `fact: str` | "Successfully saved" or error | | `SaveMemoryTool` | `fact: str` | "Salvo com sucesso" ou erro |
### Evolution Tools (src/tools/evolution.py) ### Ferramentas de Evolução (src/tools/evolution.py)
| Tool | Input | Output | | Ferramenta | Entrada | Saída |
|------|-------|--------| |------------|---------|-------|
| `SpawnAgentTool` | `filename, name, role, goal, backstory, llm_preference` | Path to created file | | `SpawnAgentTool` | `filename, name, role, goal, backstory, llm_preference` | Caminho para arquivo criado |
| `LearnPolicyTool` | `title, content, category` | Path to saved policy | | `LearnPolicyTool` | `title, content, category` | Caminho para política salva |
### Zabbix Tools (src/tools/zabbix.py) ### Ferramentas Zabbix (src/tools/zabbix.py)
| Tool | Input | Output | | Ferramenta | Entrada | Saída |
|------|-------|--------| |------------|---------|-------|
| `ZabbixValidatorTool` | `file_path: str` | Validation report | | `ZabbixValidatorTool` | `file_path: str` | Relatório de validação |
| `UUIDFixerTool` | `file_path: str` | Fixed file path | | `UUIDFixerTool` | `file_path: str` | Caminho do arquivo corrigido |
--- ---
## 🎭 Persona File Format ## 🎭 Formato de Arquivo de Persona
```yaml ```yaml
--- ---
description: Short description description: Descrição curta
llm_config: llm_config:
provider: default # openai, gemini, ollama, default provider: default # openai, gemini, ollama, default
--- ---
# 👤 Persona: Name # 👤 Persona: Nome
**Role:** Job title **Papel:** Cargo
**Goal:** Primary objective **Objetivo:** Objetivo principal
## 🧠 Backstory ## 🧠 História
Personality and background text... Texto de personalidade e histórico...
``` ```
### Parsed Fields ### Campos Parseados
| Field | Source | Fallback | | Campo | Fonte | Fallback |
|-------|--------|----------| |-------|-------|----------|
| `name` | First `# Heading` | "Unknown Agent" | | `name` | Primeiro `# Heading` | "Agente Desconhecido" |
| `role` | `**Role:**` line | "Support Agent" | | `role` | Linha `**Papel:**` | "Agente de Suporte" |
| `goal` | `**Goal:**` or `**Especialidade:**` | "Execute tasks related to {role}" | | `goal` | `**Objetivo:**` ou `**Especialidade:**` | "Executar tarefas relacionadas a {role}" |
| `backstory` | Entire body content | - | | `backstory` | Conteúdo completo do corpo | - |
| `llm_config` | YAML frontmatter | `{}` | | `llm_config` | Frontmatter YAML | `{}` |
--- ---
## 🌐 Environment Variables ## 🌐 Variáveis de Ambiente
| Variable | Required | Default | Description | | Variável | Obrigatória | Padrão | Descrição |
|----------|----------|---------|-------------| |----------|-------------|--------|-----------|
| `LLM_PROVIDER` | Yes | `openai` | gemini, openai, anthropic, ollama | | `LLM_PROVIDER` | Sim | `openai` | gemini, openai, anthropic, ollama |
| `LLM_MODEL_FAST` | Yes | `gpt-3.5-turbo` | Model for quick tasks | | `LLM_MODEL_FAST` | Sim | `gpt-3.5-turbo` | Modelo para tarefas rápidas |
| `LLM_MODEL_SMART` | Yes | `gpt-4o` | Model for complex reasoning | | `LLM_MODEL_SMART` | Sim | `gpt-4o` | Modelo para raciocínio complexo |
| `GEMINI_API_KEY` | If gemini | - | Google AI API key | | `GEMINI_API_KEY` | Se gemini | - | Chave de API Google AI |
| `OPENAI_API_KEY` | If openai | - | OpenAI API key | | `OPENAI_API_KEY` | Se openai | - | Chave de API OpenAI |
| `ANTHROPIC_API_KEY` | If anthropic | - | Anthropic API key | | `ANTHROPIC_API_KEY` | Se anthropic | - | Chave de API Anthropic |
| `OLLAMA_BASE_URL` | If ollama | `http://localhost:11434` | Ollama server URL | | `OLLAMA_BASE_URL` | Se ollama | `http://localhost:11434` | URL do servidor Ollama |
| `MEMORY_PROVIDER` | No | `mem0` | qdrant (local) or mem0 (cloud) | | `MEMORY_PROVIDER` | Não | `mem0` | qdrant (local) ou mem0 (nuvem) |
| `MEMORY_EMBEDDING_PROVIDER` | No | `openai` | local, openai, gemini | | `MEMORY_EMBEDDING_PROVIDER` | Não | `openai` | local, openai, gemini |
| `QDRANT_HOST` | If qdrant | `localhost` | Qdrant host | | `QDRANT_HOST` | Se qdrant | `localhost` | Host Qdrant |
| `QDRANT_PORT` | If qdrant | `6333` | Qdrant port | | `QDRANT_PORT` | Se qdrant | `6333` | Porta Qdrant |
| `MEMORY_PROJECT_ID` | No | `default_project` | Memory namespace | | `MEMORY_PROJECT_ID` | Não | `default_project` | Namespace de memória |
--- ---
## 🔄 Rate Limiting Constants ## 🔄 Constantes de Rate Limiting
In `src/memory/wrapper.py`: Em `src/memory/wrapper.py`:
```python ```python
MAX_RETRIES = 3 # Max retry attempts on 429 MAX_RETRIES = 3 # Máximo de tentativas em 429
RETRY_DELAY_SECONDS = 2.0 # Initial delay (doubles each retry) RETRY_DELAY_SECONDS = 2.0 # Delay inicial (dobra a cada retry)
MAX_CALLS_PER_MINUTE = 50 # Conservative API limit MAX_CALLS_PER_MINUTE = 50 # Limite conservador de API
``` ```
--- ---
## 🐳 Docker Services ## 🐳 Serviços Docker
| Service | Port | Purpose | | Serviço | Porta | Propósito |
|---------|------|---------| |---------|-------|-----------|
| `app` | 8000 | Chainlit web UI | | `app` | 8000 | Interface web Chainlit |
| `qdrant` | 6333 | Vector database | | `qdrant` | 6333 | Banco de dados vetorial |
| `telegram_listener` | - | Telegram bot (optional) | | `telegram_listener` | - | Bot Telegram (opcional) |
--- ---
## 📝 Logging ## 📝 Logs
```python ```python
import logging import logging
logger = logging.getLogger("AntigravityMemory") # Memory module logger = logging.getLogger("AntigravityMemory") # Módulo de memória
logger = logging.getLogger("AntigravityConfig") # Config module logger = logging.getLogger("AntigravityConfig") # Módulo de configuração
``` ```
Logs appear in Docker: `docker logs antigravity_brain -f` Logs aparecem no Docker: `docker logs antigravity_brain -f`

View File

@ -1,153 +1,153 @@
# 📖 Antigravity Brain - Developer Documentation # 📖 Antigravity Brain - Documentação para Desenvolvedores
Complete guide for developers and AI agents working on this project. Guia completo para desenvolvedores e agentes de IA trabalhando neste projeto.
## 📑 Table of Contents ## 📑 Índice
1. [Architecture Overview](#architecture-overview) 1. [Visão Geral da Arquitetura](#visão-geral-da-arquitetura)
2. [Adding New Agents](#adding-new-agents) 2. [Adicionando Novos Agentes](#adicionando-novos-agentes)
3. [Adding New Crews](#adding-new-crews) 3. [Adicionando Novas Crews](#adicionando-novas-crews)
4. [Adding New Tools](#adding-new-tools) 4. [Adicionando Novas Ferramentas](#adicionando-novas-ferramentas)
5. [Configuration Reference](#configuration-reference) 5. [Referência de Configuração](#referência-de-configuração)
6. [Memory System](#memory-system) 6. [Sistema de Memória](#sistema-de-memória)
7. [AI Agent Guidelines](#ai-agent-guidelines) 7. [Diretrizes para Agentes de IA](#diretrizes-para-agentes-de-ia)
--- ---
## 🏗️ Architecture Overview ## 🏗️ Visão Geral da Arquitetura
``` ```
┌─────────────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────────────┐
│ Chainlit Web UI Interface Web Chainlit │
│ (src/app.py:8000) │ │ (src/app.py:8000) │
└─────────────────────────┬───────────────────────────────────────┘ └─────────────────────────┬───────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────────────┐
Smart Router Roteador Inteligente
│ (src/router.py) │ │ (src/router.py) │
│ Classifies user intent → Routes to Crew │ Classifica intenção do usuário → Roteia para Crew
└─────────────────────────┬───────────────────────────────────────┘ └─────────────────────────┬───────────────────────────────────────┘
┌───────────────┼───────────────┐ ┌───────────────┼───────────────┐
▼ ▼ ▼ ▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
Infra Crew │ │ Security │ │ HR/Evolution Crew Infra │ │ Crew │ │ Crew RH/
│ │ │ Crew │ │ Crew │ │ │ Segurança │ │ Evolução
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼
┌─────────────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────────────┐
Agent Factory Fábrica de Agentes
│ (src/agents/factory.py) │ │ (src/agents/factory.py) │
Loads Persona → Injects Knowledge → Creates Agent Carrega Persona → Injeta Conhecimento → Cria Agente
└─────────────────────────┬───────────────────────────────────────┘ └─────────────────────────┬───────────────────────────────────────┘
┌───────────────┼───────────────┐ ┌───────────────┼───────────────┐
▼ ▼ ▼ ▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Persona │ │ Knowledge │ │ Tools │ Persona │ │ Conhecimento│ │ Ferramentas
│ (.md) │ │ Standards │ │ (Python) │ │ (.md) │ │ Padrões │ │ (Python) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
┌─────────────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────────────┐
Shared Memory (Mem0) Memória Compartilhada (Mem0)
│ (src/memory/wrapper.py) │ │ (src/memory/wrapper.py) │
│ Qdrant Vector DB + HuggingFace Embeddings │ │ Qdrant Vector DB + HuggingFace Embeddings │
└─────────────────────────────────────────────────────────────────┘ └─────────────────────────────────────────────────────────────────┘
``` ```
### Key Files ### Arquivos Principais
| File | Purpose | | Arquivo | Propósito |
|------|---------| |---------|-----------|
| `src/app.py` | Chainlit entry point, handles chat | | `src/app.py` | Ponto de entrada Chainlit, gerencia chat |
| `src/router.py` | Routes requests to appropriate crew | | `src/router.py` | Roteia requisições para crew apropriada |
| `src/config.py` | LLM & Memory configuration | | `src/config.py` | Configuração LLM & Memória |
| `src/agents/factory.py` | Creates agents from persona files | | `src/agents/factory.py` | Cria agentes a partir de arquivos de persona |
| `src/crews/definitions.py` | Defines crew compositions | | `src/crews/definitions.py` | Define composições de crews |
| `src/memory/wrapper.py` | Mem0 integration with rate limiting | | `src/memory/wrapper.py` | Integração Mem0 com rate limiting |
--- ---
## 🤖 Adding New Agents ## 🤖 Adicionando Novos Agentes
### Step 1: Create Persona File ### Passo 1: Criar Arquivo de Persona
Create `src/agents/personas/persona-<name>.md`: Crie `src/agents/personas/persona-<nome>.md`:
```markdown ```markdown
--- ---
description: Short description of the agent description: Descrição curta do agente
llm_config: llm_config:
provider: default # or: openai, gemini, ollama provider: default # ou: openai, gemini, ollama
--- ---
# 👤 Persona: Agent Name # 👤 Persona: Nome do Agente
**Role:** The agent's job title **Papel:** O cargo do agente
**Goal:** What the agent aims to achieve **Objetivo:** O que o agente busca alcançar
## 🧠 Backstory ## 🧠 História
Detailed personality and background. This becomes the agent's Personalidade e histórico detalhados. Isto se torna o
system prompt. Write in character. prompt de sistema do agente. Escreva na voz do personagem.
## 📋 Protocol ## 📋 Protocolo
1. Step one of how this agent works 1. Primeiro passo de como este agente trabalha
2. Step two... 2. Segundo passo...
``` ```
### Step 2: Register in Factory (Optional) ### Passo 2: Registrar na Fábrica (Opcional)
If agent needs special tools, update `src/crews/definitions.py`: Se o agente precisa de ferramentas especiais, atualize `src/crews/definitions.py`:
```python ```python
from src.agents.factory import AgentFactory from src.agents.factory import AgentFactory
from src.tools.your_tool import YourTool from src.tools.sua_tool import SuaTool
agent = AgentFactory.create_agent( agent = AgentFactory.create_agent(
"your-agent-name", # matches filename "seu-agente-nome", # corresponde ao nome do arquivo
specific_tools=[YourTool()], specific_tools=[SuaTool()],
model_tier="smart" # or "fast" model_tier="smart" # ou "fast"
) )
``` ```
### Naming Convention ### Convenção de Nomenclatura
- Filename: `persona-<lowercase-hyphenated>.md` - Nome do arquivo: `persona-<minusculo-hifenizado>.md`
- Example: `persona-bob-builder.md` - Exemplo: `persona-bob-builder.md`
--- ---
## 👥 Adding New Crews ## 👥 Adicionando Novas Crews
### Step 1: Define Crew in definitions.py ### Passo 1: Definir Crew em definitions.py
Edit `src/crews/definitions.py`: Edite `src/crews/definitions.py`:
```python ```python
elif crew_name == "Your New Crew": elif crew_name == "Sua Nova Crew":
# Create agents # Criar agentes
agent1 = AgentFactory.create_agent("agent-one", model_tier="smart") agent1 = AgentFactory.create_agent("agente-um", model_tier="smart")
agent2 = AgentFactory.create_agent("agent-two", model_tier="fast") agent2 = AgentFactory.create_agent("agente-dois", model_tier="fast")
# Define tasks # Definir tarefas
task1 = Task( task1 = Task(
description=f"Do something with: '{inputs.get('topic')}'", description=f"Fazer algo com: '{inputs.get('topic')}'",
expected_output="Expected result description", expected_output="Descrição do resultado esperado",
agent=agent1 agent=agent1
) )
task2 = Task( task2 = Task(
description="Review the previous work", description="Revisar o trabalho anterior",
expected_output="Approval or feedback", expected_output="Aprovação ou feedback",
agent=agent2 agent=agent2
) )
# Return crew # Retornar crew
return Crew( return Crew(
agents=[agent1, agent2], agents=[agent1, agent2],
tasks=[task1, task2], tasks=[task1, task2],
@ -156,218 +156,218 @@ elif crew_name == "Your New Crew":
) )
``` ```
### Step 2: Register in Router ### Passo 2: Registrar no Roteador
Edit `src/router.py` prompt: Edite o prompt em `src/router.py`:
```python ```python
prompt = f""" prompt = f"""
AVAILABLE CREWS: CREWS DISPONÍVEIS:
... ...
6. 'Your New Crew': Description of when to use this crew. 6. 'Sua Nova Crew': Descrição de quando usar esta crew.
""" """
``` ```
### Step 3: Add to Crew List ### Passo 3: Adicionar à Lista de Crews
In `src/crews/definitions.py`: Em `src/crews/definitions.py`:
```python ```python
@staticmethod @staticmethod
def get_available_crews(): def get_available_crews():
return [ return [
... ...
"Your New Crew", "Sua Nova Crew",
] ]
``` ```
--- ---
## 🔧 Adding New Tools ## 🔧 Adicionando Novas Ferramentas
### Step 1: Create Tool File ### Passo 1: Criar Arquivo de Ferramenta
Create `src/tools/your_tools.py`: Crie `src/tools/suas_tools.py`:
```python ```python
from crewai.tools import BaseTool from crewai.tools import BaseTool
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
class YourToolInput(BaseModel): class SuaToolInput(BaseModel):
"""Input schema - MUST have docstring and Field descriptions.""" """Schema de entrada - DEVE ter docstring e descrições Field."""
param1: str = Field(..., description="What this parameter is for") param1: str = Field(..., description="Para que serve este parâmetro")
param2: int = Field(default=10, description="Optional with default") param2: int = Field(default=10, description="Opcional com valor padrão")
class YourTool(BaseTool): class SuaTool(BaseTool):
name: str = "Your Tool Name" name: str = "Nome da Sua Ferramenta"
description: str = ( description: str = (
"Detailed description of what this tool does. " "Descrição detalhada do que esta ferramenta faz. "
"The agent reads this to decide when to use it." "O agente lê isto para decidir quando usar."
) )
args_schema: type = YourToolInput args_schema: type = SuaToolInput
def _run(self, param1: str, param2: int = 10) -> str: def _run(self, param1: str, param2: int = 10) -> str:
try: try:
# Your logic here # Sua lógica aqui
result = do_something(param1, param2) result = fazer_algo(param1, param2)
return f"Success: {result}" return f"Sucesso: {result}"
except Exception as e: except Exception as e:
# NEVER raise, always return error string # NUNCA lance exceção, sempre retorne string de erro
return f"Error: {str(e)}" return f"Erro: {str(e)}"
``` ```
### Tool Guidelines ### Diretrizes de Ferramentas
1. **Always catch exceptions** - Return error strings, never raise 1. **Sempre capture exceções** - Retorne strings de erro, nunca lance
2. **Descriptive docstrings** - Agents use these to understand usage 2. **Docstrings descritivas** - Agentes usam estas para entender o uso
3. **Type hints required** - All parameters need types 3. **Type hints obrigatórios** - Todos os parâmetros precisam de tipos
4. **Return strings** - Narrative results, not raw JSON 4. **Retorne strings** - Resultados narrativos, não JSON bruto
--- ---
## ⚙️ Configuration Reference ## ⚙️ Referência de Configuração
### .env Variables ### Variáveis .env
```env ```env
# LLM Provider: gemini, openai, anthropic, ollama # Provedor LLM: gemini, openai, anthropic, ollama
LLM_PROVIDER=gemini LLM_PROVIDER=gemini
# Model names (used for both agents and memory) # Nomes de modelos (usados para agentes e memória)
LLM_MODEL_FAST=gemini-2.5-flash-lite-preview-06-17 LLM_MODEL_FAST=gemini-2.5-flash-lite-preview-06-17
LLM_MODEL_SMART=gemini-2.5-flash-lite-preview-06-17 LLM_MODEL_SMART=gemini-2.5-flash-lite-preview-06-17
# API Keys (only the one matching your provider) # Chaves de API (apenas a que corresponde ao seu provedor)
GEMINI_API_KEY=your-key GEMINI_API_KEY=sua-chave
OPENAI_API_KEY=your-key OPENAI_API_KEY=sua-chave
ANTHROPIC_API_KEY=your-key ANTHROPIC_API_KEY=sua-chave
# Memory Configuration # Configuração de Memória
MEMORY_PROVIDER=qdrant # qdrant (local) or mem0 (cloud) MEMORY_PROVIDER=qdrant # qdrant (local) ou mem0 (nuvem)
MEMORY_EMBEDDING_PROVIDER=local # local, openai, or gemini MEMORY_EMBEDDING_PROVIDER=local # local, openai, ou gemini
QDRANT_HOST=qdrant # Docker service name QDRANT_HOST=qdrant # Nome do serviço Docker
QDRANT_PORT=6333 QDRANT_PORT=6333
MEMORY_PROJECT_ID=your_project # Namespace for memories MEMORY_PROJECT_ID=seu_projeto # Namespace para memórias
``` ```
### Model Tiers ### Níveis de Modelo
- **smart**: Used for complex reasoning (strategy, architecture) - **smart**: Usado para raciocínio complexo (estratégia, arquitetura)
- **fast**: Used for quick tasks (classification, simple responses) - **fast**: Usado para tarefas rápidas (classificação, respostas simples)
--- ---
## 🧠 Memory System ## 🧠 Sistema de Memória
### How It Works ### Como Funciona
1. All agents have access to `SearchMemoryTool` and `SaveMemoryTool` 1. Todos os agentes têm acesso a `SearchMemoryTool` e `SaveMemoryTool`
2. Memories are stored in Qdrant vector database 2. Memórias são armazenadas no banco de dados vetorial Qdrant
3. Mem0 uses LLM to extract facts and embeddings to search 3. Mem0 usa LLM para extrair fatos e embeddings para busca
### Rate Limiting ### Rate Limiting
The memory system has built-in protection: O sistema de memória tem proteção integrada:
- Max 50 calls/minute - Máximo 50 chamadas/minuto
- 3 retries with exponential backoff - 3 tentativas com backoff exponencial
- Graceful degradation (continues without memory if unavailable) - Degradação graciosa (continua sem memória se indisponível)
### Memory Scope ### Escopo de Memória
All memories are scoped to `MEMORY_PROJECT_ID`. Change this to isolate different projects. Todas as memórias são escopadas para `MEMORY_PROJECT_ID`. Altere isto para isolar diferentes projetos.
--- ---
## 🤖 AI Agent Guidelines ## 🤖 Diretrizes para Agentes de IA
### For AI Agents Working on This Codebase ### Para Agentes de IA Trabalhando Neste Código
> **READ BEFORE MAKING CHANGES** > **LEIA ANTES DE FAZER ALTERAÇÕES**
1. **Load Knowledge First** 1. **Carregue Conhecimento Primeiro**
- Read `src/knowledge/standards/*.md` before writing code - Leia `src/knowledge/standards/*.md` antes de escrever código
- These are THE LAW for code style and patterns - Estes são A LEI para estilo de código e padrões
2. **Never Hardcode** 2. **Nunca Hardcode**
- Use `Config.get_llm_config()` for LLM settings - Use `Config.get_llm_config()` para configurações LLM
- Use `Config.get_mem0_config()` for memory settings - Use `Config.get_mem0_config()` para configurações de memória
- Use environment variables for secrets - Use variáveis de ambiente para segredos
3. **Error Handling** 3. **Tratamento de Erros**
- Tools must NEVER raise exceptions - Ferramentas NUNCA devem lançar exceções
- Always return descriptive error strings - Sempre retorne strings de erro descritivas
- Use rate limiting for external APIs - Use rate limiting para APIs externas
4. **Adding Agents** 4. **Adicionando Agentes**
- Create persona file first - Crie arquivo de persona primeiro
- Test agent loads: `AgentFactory.create_agent("name")` - Teste se o agente carrega: `AgentFactory.create_agent("nome")`
- Add to crew only after persona works - Adicione à crew apenas depois que a persona funcionar
5. **Testing Changes** 5. **Testando Alterações**
```bash ```bash
docker-compose restart app docker-compose restart app
docker logs antigravity_brain --tail 50 docker logs antigravity_brain --tail 50
``` ```
6. **Commit Convention** 6. **Convenção de Commit**
``` ```
feat: Add new feature feat: Adicionar nova funcionalidade
fix: Bug fix fix: Correção de bug
docs: Documentation docs: Documentação
refactor: Code cleanup refactor: Limpeza de código
``` ```
--- ---
## 📁 Directory Reference ## 📁 Referência de Diretórios
``` ```
src/ src/
├── agents/ ├── agents/
│ ├── factory.py # Agent creation logic │ ├── factory.py # Lógica de criação de agentes
│ └── personas/ # Agent personality files │ └── personas/ # Arquivos de personalidade de agentes
│ ├── persona-arthur-mendes.md │ ├── persona-arthur-mendes.md
│ ├── persona-gus-fring.md │ ├── persona-gus-fring.md
│ └── ... (26 agents) │ └── ... (26 agentes)
├── crews/ ├── crews/
│ └── definitions.py # Crew compositions │ └── definitions.py # Composições de crews
├── knowledge/ ├── knowledge/
│ └── standards/ # Corporate knowledge base │ └── standards/ # Base de conhecimento corporativo
│ ├── docker_standards.md │ ├── docker_standards.md
│ ├── python_tool_standards.md │ ├── python_tool_standards.md
│ └── ... (16 standards) │ └── ... (16 padrões)
├── memory/ ├── memory/
│ └── wrapper.py # Mem0 + rate limiting │ └── wrapper.py # Mem0 + rate limiting
├── tools/ ├── tools/
│ ├── base.py # File system tools │ ├── base.py # Ferramentas de sistema de arquivos
│ ├── evolution.py # SpawnAgent, LearnPolicy │ ├── evolution.py # SpawnAgent, LearnPolicy
│ └── zabbix.py # Zabbix validation tools │ └── zabbix.py # Ferramentas de validação Zabbix
├── app.py # Chainlit entry ├── app.py # Entrada Chainlit
├── config.py # Configuration hub ├── config.py # Hub de configuração
└── router.py # Smart routing └── router.py # Roteamento inteligente
``` ```
--- ---
## 🚀 Quick Commands ## 🚀 Comandos Rápidos
```bash ```bash
# Start application # Iniciar aplicação
docker-compose up -d docker-compose up -d
# View logs # Ver logs
docker logs antigravity_brain -f docker logs antigravity_brain -f
# Restart after changes # Reiniciar após alterações
docker-compose restart app docker-compose restart app
# Rebuild container # Reconstruir container
docker-compose build --no-cache app docker-compose build --no-cache app
# Access Qdrant dashboard # Acessar dashboard Qdrant
open http://localhost:6333/dashboard open http://localhost:6333/dashboard
``` ```
--- ---
Built with ❤️ by ITGuys | Last Updated: 2026-01-07 Feito com ❤️ pela ITGuys | Última Atualização: 2026-01-07

View File

@ -1,114 +1,114 @@
# 🔥 Troubleshooting Guide # 🔥 Guia de Solução de Problemas
Common issues and solutions for the Antigravity Brain system. Problemas comuns e soluções para o sistema Antigravity Brain.
--- ---
## 🚨 API Errors ## 🚨 Erros de API
### Error: 429 RESOURCE_EXHAUSTED (Quota Exceeded) ### Erro: 429 RESOURCE_EXHAUSTED (Cota Excedida)
**Symptoms:** **Sintomas:**
- Agents stuck in retry loop - Agentes presos em loop de retry
- "You exceeded your current quota" in logs - "You exceeded your current quota" nos logs
**Causes:** **Causas:**
- API rate limit hit (especially with Gemini 2.0-flash-exp: only 10 RPM!) - Limite de taxa da API atingido (especialmente com Gemini 2.0-flash-exp: apenas 10 RPM!)
- Memory tools calling API too fast - Ferramentas de memória chamando API muito rapidamente
**Solutions:** **Soluções:**
1. **Switch to higher-quota model:** 1. **Mudar para modelo com cota maior:**
```env ```env
LLM_MODEL_FAST=gemini-2.5-flash-lite-preview-06-17 # 4000 RPM LLM_MODEL_FAST=gemini-2.5-flash-lite-preview-06-17 # 4000 RPM
``` ```
2. **Wait for quota reset** (typically 1 minute) 2. **Aguardar reset de cota** (tipicamente 1 minuto)
3. **Check current quota:** 3. **Verificar cota atual:**
- Gemini: https://console.cloud.google.com/apis/api/generativelanguage.googleapis.com/quotas - Gemini: https://console.cloud.google.com/apis/api/generativelanguage.googleapis.com/quotas
- OpenAI: https://platform.openai.com/usage - OpenAI: https://platform.openai.com/usage
--- ---
### Error: OPENAI_API_KEY must be set ### Erro: OPENAI_API_KEY must be set
**Symptoms:** **Sintomas:**
- Memory tools fail with "api_key client option must be set" - Ferramentas de memória falham com "api_key client option must be set"
**Cause:** **Causa:**
- Mem0's LLM configuration missing - Configuração LLM do Mem0 ausente
**Solution:** **Solução:**
- Ensure `src/config.py` has LLM config in `get_mem0_config()` - Certifique-se que `src/config.py` tem configuração LLM em `get_mem0_config()`
- Check that `LLM_PROVIDER` in `.env` matches a supported provider - Verifique se `LLM_PROVIDER` no `.env` corresponde a um provedor suportado
--- ---
### Error: Template variable 'X' not found ### Erro: Template variable 'X' not found
**Symptoms:** **Sintomas:**
- Agent crashes when loading knowledge - Agente crasha ao carregar conhecimento
**Cause:** **Causa:**
- `{variable}` syntax in markdown files interpreted as CrewAI template - Sintaxe `{variável}` em arquivos markdown interpretada como template CrewAI
**Solution:** **Solução:**
- Escape braces in code examples: use `PATH_VAR` instead of `{path}` - Escape chaves em exemplos de código: use `PATH_VAR` em vez de `{path}`
- Check `src/knowledge/standards/*.md` for unescaped `{}` - Verifique `src/knowledge/standards/*.md` por `{}` não escapados
--- ---
## 🐳 Docker Issues ## 🐳 Problemas com Docker
### Container keeps restarting ### Container continua reiniciando
**Check logs:** **Verificar logs:**
```bash ```bash
docker logs antigravity_brain --tail 100 docker logs antigravity_brain --tail 100
``` ```
**Common causes:** **Causas comuns:**
- Missing `.env` file - Arquivo `.env` ausente
- Invalid API key - Chave de API inválida
- Python import errors - Erros de import Python
--- ---
### Qdrant connection refused ### Conexão recusada ao Qdrant
**Symptoms:** **Sintomas:**
- "Connection refused" to port 6333 - "Connection refused" na porta 6333
**Solutions:** **Soluções:**
1. **Check Qdrant is running:** 1. **Verificar se Qdrant está rodando:**
```bash ```bash
docker ps | findstr qdrant docker ps | findstr qdrant
``` ```
2. **Check host configuration:** 2. **Verificar configuração de host:**
```env ```env
QDRANT_HOST=qdrant # Docker service name, NOT localhost QDRANT_HOST=qdrant # Nome do serviço Docker, NÃO localhost
``` ```
3. **Restart Qdrant:** 3. **Reiniciar Qdrant:**
```bash ```bash
docker-compose restart qdrant docker-compose restart qdrant
``` ```
--- ---
### Changes not reflected ### Alterações não refletidas
**Problem:** Code changes don't appear after saving **Problema:** Alterações de código não aparecem após salvar
**Solution:** **Solução:**
```bash ```bash
docker-compose restart app docker-compose restart app
``` ```
Or for full rebuild: Ou para rebuild completo:
```bash ```bash
docker-compose build --no-cache app docker-compose build --no-cache app
docker-compose up -d docker-compose up -d
@ -116,131 +116,131 @@ docker-compose up -d
--- ---
## 🤖 Agent Issues ## 🤖 Problemas com Agentes
### Agent not found ### Agente não encontrado
**Error:** `No persona found matching 'agent-name'` **Erro:** `No persona found matching 'nome-agente'`
**Solutions:** **Soluções:**
1. **Check filename matches:** 1. **Verificar se nome do arquivo corresponde:**
``` ```
src/agents/personas/persona-<exact-name>.md src/agents/personas/persona-<nome-exato>.md
``` ```
2. **Use correct search pattern:** 2. **Usar padrão de busca correto:**
```python ```python
# This searches for *agent-name* in filename # Isto busca por *nome-agente* no nome do arquivo
AgentFactory.create_agent("agent-name") AgentFactory.create_agent("nome-agente")
``` ```
--- ---
### Agent loads but doesn't respond ### Agente carrega mas não responde
**Possible causes:** **Possíveis causas:**
1. **LLM API error** - Check logs for 429/401 1. **Erro de API LLM** - Verifique logs por 429/401
2. **Empty backstory** - Ensure persona has content 2. **Backstory vazio** - Certifique-se que persona tem conteúdo
3. **Tool errors** - Check if tools are raising exceptions 3. **Erros de ferramenta** - Verifique se ferramentas estão lançando exceções
**Debug:** **Depurar:**
```bash ```bash
docker logs antigravity_brain 2>&1 | findstr "Error ERROR Exception" docker logs antigravity_brain 2>&1 | findstr "Error ERROR Exception"
``` ```
--- ---
### Agent using wrong model ### Agente usando modelo errado
**Check:** Ensure `model_tier` is set correctly: **Verificar:** Certifique-se que `model_tier` está configurado corretamente:
```python ```python
agent = AgentFactory.create_agent("name", model_tier="smart") # Uses LLM_MODEL_SMART agent = AgentFactory.create_agent("nome", model_tier="smart") # Usa LLM_MODEL_SMART
agent = AgentFactory.create_agent("name", model_tier="fast") # Uses LLM_MODEL_FAST agent = AgentFactory.create_agent("nome", model_tier="fast") # Usa LLM_MODEL_FAST
``` ```
--- ---
## 🧠 Memory Issues ## 🧠 Problemas com Memória
### Memory not saving ### Memória não salva
**Check Qdrant dashboard:** **Verificar dashboard Qdrant:**
``` ```
http://localhost:6333/dashboard http://localhost:6333/dashboard
``` ```
**Verify collection exists:** Should see `itguys_antigravity_v1` (or your `MEMORY_PROJECT_ID`) **Verificar se collection existe:** Deve ver `itguys_antigravity_v1` (ou seu `MEMORY_PROJECT_ID`)
--- ---
### Memory search returns nothing ### Busca de memória não retorna nada
**Possible causes:** **Possíveis causas:**
1. **Embedding mismatch** - Don't change `MEMORY_EMBEDDING_PROVIDER` after data exists 1. **Mismatch de embedding** - Não altere `MEMORY_EMBEDDING_PROVIDER` após existirem dados
2. **Wrong project ID** - Check `MEMORY_PROJECT_ID` matches 2. **ID de projeto errado** - Verifique se `MEMORY_PROJECT_ID` corresponde
3. **Qdrant empty** - No memories saved yet 3. **Qdrant vazio** - Nenhuma memória salva ainda
--- ---
## 🌐 Web UI Issues ## 🌐 Problemas com Interface Web
### Chainlit not loading ### Chainlit não carrega
**Check port:** **Verificar porta:**
```bash ```bash
netstat -an | findstr 8000 netstat -an | findstr 8000
``` ```
**Check container:** **Verificar container:**
```bash ```bash
docker logs antigravity_brain | findstr -i "error" docker logs antigravity_brain | findstr -i "error"
``` ```
--- ---
### "Could not reach server" toast ### Toast "Could not reach server"
**Cause:** Usually LLM API timeout or error **Causa:** Geralmente timeout ou erro de API LLM
**Solution:** Check API key and quota **Solução:** Verifique chave de API e cota
--- ---
## 📋 Quick Diagnostic Commands ## 📋 Comandos de Diagnóstico Rápido
```bash ```bash
# Check all containers # Verificar todos os containers
docker ps docker ps
# View real-time logs # Ver logs em tempo real
docker logs antigravity_brain -f docker logs antigravity_brain -f
# Check for errors only # Verificar apenas erros
docker logs antigravity_brain 2>&1 | findstr "ERROR Error error Exception" docker logs antigravity_brain 2>&1 | findstr "ERROR Error error Exception"
# Restart everything # Reiniciar tudo
docker-compose down && docker-compose up -d docker-compose down && docker-compose up -d
# Full rebuild # Rebuild completo
docker-compose build --no-cache && docker-compose up -d docker-compose build --no-cache && docker-compose up -d
# Check Qdrant health # Verificar saúde do Qdrant
curl http://localhost:6333/health curl http://localhost:6333/health
# Test Gemini API # Testar API Gemini
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite-preview-06-17:generateContent?key=YOUR_KEY" \ curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite-preview-06-17:generateContent?key=SUA_CHAVE" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{"contents":[{"parts":[{"text":"Hello"}]}]}' -d '{"contents":[{"parts":[{"text":"Olá"}]}]}'
``` ```
--- ---
## 🆘 Getting Help ## 🆘 Obtendo Ajuda
1. **Check logs first** - 90% of issues are in Docker logs 1. **Verifique os logs primeiro** - 90% dos problemas estão nos logs do Docker
2. **Verify .env** - Most config issues are environment variables 2. **Verifique o .env** - A maioria dos problemas de configuração são variáveis de ambiente
3. **Test API separately** - Ensure your API key works outside the app 3. **Teste a API separadamente** - Certifique-se que sua chave de API funciona fora da aplicação
4. **Check quotas** - Rate limits are the #1 cause of failures 4. **Verifique cotas** - Rate limits são a causa #1 de falhas