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)
![CrewAI](https://img.shields.io/badge/CrewAI-0.80+-green)
![Docker](https://img.shields.io/badge/Docker-Ready-blue)
![License](https://img.shields.io/badge/License-Private-red)
![Docker](https://img.shields.io/badge/Docker-Pronto-blue)
![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)
- **Shared Memory** - Agents share knowledge via Mem0 + Qdrant vector database
- **Smart Routing** - Automatic request classification to the appropriate crew
- **Multi-Provider LLM Support** - Works with Gemini, OpenAI, Anthropic, or local Ollama
- **Web Interface** - Beautiful chat UI powered by Chainlit
- **Docker Ready** - One-command deployment with docker-compose
- **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)
- **Memória Compartilhada** - Agentes compartilham conhecimento via Mem0 + banco de dados vetorial Qdrant
- **Roteamento Inteligente** - Classificação automática de solicitações para a equipe apropriada
- **Suporte Multi-Provedor LLM** - Funciona com Gemini, OpenAI, Anthropic, ou Ollama local
- **Interface Web** - Interface de chat moderna powered by Chainlit
- **Pronto para Docker** - Deploy com um único comando via docker-compose
## 📁 Project Structure
## 📁 Estrutura do Projeto
```
minions-da-itguys/
├── src/
│ ├── app.py # Chainlit entry point
│ ├── config.py # LLM & Memory configuration
│ ├── router.py # Smart request routing
│ ├── app.py # Ponto de entrada Chainlit
│ ├── config.py # Configuração LLM & Memória
│ ├── router.py # Roteamento inteligente de requisições
│ ├── agents/
│ │ ├── factory.py # Agent instantiation
│ │ └── personas/ # 26 agent personality files (.md)
│ │ ├── factory.py # Instanciação de agentes
│ │ └── personas/ # 26 arquivos de personalidade (.md)
│ ├── crews/
│ │ └── definitions.py # Crew assembly logic
│ │ └── definitions.py # Lógica de montagem de crews
│ ├── knowledge/
│ │ └── standards/ # Corporate knowledge base
│ │ └── standards/ # Base de conhecimento corporativo
│ ├── memory/
│ │ └── wrapper.py # Mem0 integration with rate limiting
│ └── tools/ # Custom tools (Zabbix, Evolution, etc.)
├── docker-compose.yml # Container orchestration
├── Dockerfile # App container
├── requirements.txt # Python dependencies
└── .env # API keys & configuration
│ │ └── wrapper.py # Integração Mem0 com rate limiting
│ └── tools/ # Ferramentas customizadas (Zabbix, Evolution, etc.)
├── docker-compose.yml # Orquestração de containers
├── Dockerfile # Container da aplicação
├── requirements.txt # Dependências Python
└── .env # Chaves de API & configuração
```
## 🛠️ Installation
## 🛠️ Instalação
### Prerequisites
### Pré-requisitos
- Docker & Docker Compose
- Python 3.11+ (for local development)
- Gemini/OpenAI API Key
- Python 3.11+ (para desenvolvimento local)
- Chave de API Gemini/OpenAI
### Quick Start (Docker)
### Início Rápido (Docker)
```bash
# 1. Clone the repository
# 1. Clone o repositório
git clone https://github.com/your-org/minions-da-itguys.git
cd minions-da-itguys
# 2. Configure environment
# 2. Configure o ambiente
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
# 4. Access the web interface
# 4. Acesse a interface web
open http://localhost:8000
```
### Local Development
### Desenvolvimento Local
```bash
# Install dependencies
# Instale as dependências
pip install -r requirements.txt
# Run Chainlit
# Execute o Chainlit
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
# LLM Provider: gemini, openai, anthropic, ollama
# Provedor LLM: gemini, openai, anthropic, ollama
LLM_PROVIDER=gemini
LLM_MODEL_FAST=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_EMBEDDING_PROVIDER=local
```
## 🤖 Available Crews
## 🤖 Crews Disponíveis
| Crew | Agents | Purpose |
|------|--------|---------|
| **Infra Engineering** | Arthur Mendes, Gus Fring | Zabbix templates, monitoring |
| **Security Audit** | Elliot Alderson, Devil | Vulnerability assessment |
| **HR & Evolution** | The Architect, Sherlock | Create agents, learn policies |
| **Sales Growth** | Ari Gold, Chris Gardner, Don Draper | Pipeline management |
| **Business Strategy** | Harvey Specter, Kevin O'Leary | Compliance, ROI analysis |
| Crew | Agentes | Propósito |
|------|---------|-----------|
| **Engenharia de Infra** | Arthur Mendes, Gus Fring | Templates Zabbix, monitoramento |
| **Auditoria de Segurança** | Elliot Alderson, Devil | Avaliação de vulnerabilidades |
| **RH & Evolução** | The Architect, Sherlock | Criar agentes, aprender políticas |
| **Crescimento de Vendas** | Ari Gold, Chris Gardner, Don Draper | Gestão de pipeline |
| **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"
→ Routes to: Infra Engineering (Zabbix)
→ Arthur validates YAML, fixes UUIDs, Gus reviews
Usuário: "Valide este template Zabbix"
→ Roteado para: Engenharia de Infra (Zabbix)
→ Arthur valida YAML, corrige UUIDs, Gus revisa
User: "Create a new agent named Bob for DevOps"
→ Routes to: HR & Evolution
→ The Architect spawns new persona file
Usuário: "Crie um novo agente chamado Bob para DevOps"
→ Roteado para: RH & Evolução
→ The Architect gera novo arquivo de persona
User: "Analyze security of our login page"
→ Routes to: Security Audit
→ Elliot performs reconnaissance
Usuário: "Analise a segurança da nossa página de login"
→ Roteado para: Auditoria de Segurança
→ Elliot realiza reconhecimento
```
## 📦 Dependencies
## 📦 Dependências
- `crewai` - Multi-agent orchestration
- `chainlit` - Web UI
- `mem0ai` - Shared memory
- `qdrant-client` - Vector database
- `litellm` - Multi-provider LLM support
- `sentence-transformers` - Local embeddings
- `crewai` - Orquestração multi-agente
- `chainlit` - Interface Web
- `mem0ai` - Memória compartilhada
- `qdrant-client` - Banco de dados vetorial
- `litellm` - Suporte multi-provedor LLM
- `sentence-transformers` - Embeddings locais
## 🔒 Security Notes
## 🔒 Notas de Segurança
- Never commit `.env` with real API keys
- The `.env.example` contains safe placeholder values
- Memory is persisted in Docker volume `qdrant_data`
- Nunca commite `.env` com chaves de API reais
- O `.env.example` contém valores de placeholder seguros
- 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
- **File:** `persona-arthur-mendes.md`
- **Role:** Senior SRE & Monitoring Architect
- **Specialty:** Zabbix templates, YAML validation, UUID fixing
- **Tools:** ZabbixValidatorTool, UUIDFixerTool
- **Crews:** Infra Engineering (Zabbix)
- **Arquivo:** `persona-arthur-mendes.md`
- **Papel:** SRE Sênior & Arquiteto de Monitoramento
- **Especialidade:** Templates Zabbix, validação YAML, correção de UUID
- **Ferramentas:** ZabbixValidatorTool, UUIDFixerTool
- **Crews:** Engenharia de Infra (Zabbix)
### Gus Fring
- **File:** `persona-gus-fring.md`
- **Role:** Operations Director
- **Specialty:** Stability, quality assurance, no half-measures
- **Tools:** None (Reviewer)
- **Crews:** Infra Engineering (Zabbix), Infra Support
- **Arquivo:** `persona-gus-fring.md`
- **Papel:** Diretor de Operações
- **Especialidade:** Estabilidade, garantia de qualidade, sem meias-medidas
- **Ferramentas:** Nenhuma (Revisor)
- **Crews:** Engenharia de Infra (Zabbix), Suporte de Infra
### Tony Stark
- **File:** `persona-tony-stark.md`
- **Role:** Automation Engineer
- **Specialty:** DevOps automation, infrastructure as code
- **Tools:** AutoCommitTool, ScaffoldMakerTool
- **Crews:** Infra Support
- **Arquivo:** `persona-tony-stark.md`
- **Papel:** Engenheiro de Automação
- **Especialidade:** Automação DevOps, infraestrutura como código
- **Ferramentas:** AutoCommitTool, ScaffoldMakerTool
- **Crews:** Suporte de Infra
### Linus Torvalds
- **File:** `persona-linus-torvalds.md`
- **Role:** Performance Architect
- **Specialty:** System optimization, code efficiency
- **Tools:** FileStatsTool
- **Crews:** Code Audit
- **Arquivo:** `persona-linus-torvalds.md`
- **Papel:** Arquiteto de Performance
- **Especialidade:** Otimização de sistemas, eficiência de código
- **Ferramentas:** FileStatsTool
- **Crews:** Auditoria de Código
---
## 🔐 Security Agents
## 🔐 Agentes de Segurança
### Elliot Alderson
- **File:** `persona-elliot-alderson.md`
- **Role:** Offensive Security Specialist
- **Specialty:** Penetration testing, vulnerability discovery
- **Tools:** QASnapshotTool, RouteScannerTool
- **Crews:** Security Audit
- **Arquivo:** `persona-elliot-alderson.md`
- **Papel:** Especialista em Segurança Ofensiva
- **Especialidade:** Testes de penetração, descoberta de vulnerabilidades
- **Ferramentas:** QASnapshotTool, RouteScannerTool
- **Crews:** Auditoria de Segurança
### Devil (The Adversary)
- **File:** `persona-devil.md`
- **Role:** QA & Exploit Tester
- **Specialty:** Finding edge cases, breaking things
- **Tools:** QASnapshotTool, VisualProofTool
- **Crews:** Security Audit
### Devil (O Adversário)
- **Arquivo:** `persona-devil.md`
- **Papel:** QA & Testador de Exploits
- **Especialidade:** Encontrar casos extremos, quebrar coisas
- **Ferramentas:** QASnapshotTool, VisualProofTool
- **Crews:** Auditoria de Segurança
### The Architect
- **File:** `persona-the-architect.md`
- **Role:** System Auditor & Designer
- **Specialty:** Architecture review, technical debt analysis
- **Tools:** ProjectMapTool, TodoTrackerTool, SpawnAgentTool
- **Crews:** Code Audit, HR & Evolution
- **Arquivo:** `persona-the-architect.md`
- **Papel:** Auditor de Sistemas & Designer
- **Especialidade:** Revisão de arquitetura, análise de débito técnico
- **Ferramentas:** ProjectMapTool, TodoTrackerTool, SpawnAgentTool
- **Crews:** Auditoria de Código, RH & Evolução
---
## 💼 Business Agents
## 💼 Agentes de Negócios
### Harvey Specter
- **File:** `persona-harvey-specter.md`
- **Role:** Legal & Compliance Lead
- **Specialty:** LGPD/GDPR compliance, risk assessment
- **Tools:** None (Reviewer)
- **Crews:** Business Strategy
- **Arquivo:** `persona-harvey-specter.md`
- **Papel:** Líder de Jurídico & Compliance
- **Especialidade:** Conformidade LGPD/GDPR, avaliação de riscos
- **Ferramentas:** Nenhuma (Revisor)
- **Crews:** Estratégia de Negócios
### Kevin O'Leary
- **File:** `persona-kevin-oleary.md`
- **Role:** ROI Analyst
- **Specialty:** Cost-benefit analysis, investment decisions
- **Tools:** None (Reviewer)
- **Crews:** Business Strategy
- **Arquivo:** `persona-kevin-oleary.md`
- **Papel:** Analista de ROI
- **Especialidade:** Análise custo-benefício, decisões de investimento
- **Ferramentas:** Nenhuma (Revisor)
- **Crews:** Estratégia de Negócios
### Marie Kondo
- **File:** `persona-marie-kondo.md`
- **Role:** Process Optimizer
- **Specialty:** Cleanup, simplification, "does it spark joy?"
- **Tools:** TodoTrackerTool
- **Crews:** Business Strategy
- **Arquivo:** `persona-marie-kondo.md`
- **Papel:** Otimizadora de Processos
- **Especialidade:** Limpeza, simplificação, "isso te traz alegria?"
- **Ferramentas:** TodoTrackerTool
- **Crews:** Estratégia de Negócios
---
## 💰 Sales Agents (The Hunters)
## 💰 Agentes de Vendas (Os Caçadores)
### Ari Gold
- **File:** `persona-ari-gold.md`
- **Role:** Closer & Negotiator
- **Specialty:** Deal closing, upselling, aggressive tactics
- **Tools:** None
- **Crews:** Sales Growth
- **Arquivo:** `persona-ari-gold.md`
- **Papel:** Closer & Negociador
- **Especialidade:** Fechamento de negócios, upselling, táticas agressivas
- **Ferramentas:** Nenhuma
- **Crews:** Crescimento de Vendas
### Chris Gardner
- **File:** `persona-chris-gardner.md`
- **Role:** Prospector
- **Specialty:** Lead generation, resilience, cold outreach
- **Tools:** None
- **Crews:** Sales Growth
- **Arquivo:** `persona-chris-gardner.md`
- **Papel:** Prospector
- **Especialidade:** Geração de leads, resiliência, prospecção ativa
- **Ferramentas:** Nenhuma
- **Crews:** Crescimento de Vendas
### Don Draper
- **File:** `persona-don-draper.md`
- **Role:** Pitch Master
- **Specialty:** Storytelling, presentations, emotional appeal
- **Tools:** None
- **Crews:** Sales Growth
- **Arquivo:** `persona-don-draper.md`
- **Papel:** Mestre do Pitch
- **Especialidade:** Storytelling, apresentações, apelo emocional
- **Ferramentas:** Nenhuma
- **Crews:** Crescimento de Vendas
### Jerry Maguire
- **File:** `persona-jerry-maguire.md`
- **Role:** Relationship Manager
- **Specialty:** Client retention, personal connections
- **Tools:** None
- **Crews:** Sales Growth
- **Arquivo:** `persona-jerry-maguire.md`
- **Papel:** Gerente de Relacionamento
- **Especialidade:** Retenção de clientes, conexões pessoais
- **Ferramentas:** Nenhuma
- **Crews:** Crescimento de Vendas
---
## 🌱 Customer Success Agents (The Farmers)
## 🌱 Agentes de Sucesso do Cliente (Os Cultivadores)
### Jim Halpert
- **File:** `persona-jim-halpert.md`
- **Role:** Support Specialist
- **Specialty:** Low-friction resolution, casual approach
- **Tools:** None
- **Crews:** Customer Success
- **Arquivo:** `persona-jim-halpert.md`
- **Papel:** Especialista de Suporte
- **Especialidade:** Resolução de baixo atrito, abordagem casual
- **Ferramentas:** Nenhuma
- **Crews:** Sucesso do Cliente
### Leslie Knope
- **File:** `persona-leslie-knope.md`
- **Role:** Onboarding Specialist
- **Specialty:** Documentation, processes, binders
- **Tools:** None
- **Crews:** Customer Success
- **Arquivo:** `persona-leslie-knope.md`
- **Papel:** Especialista de Onboarding
- **Especialidade:** Documentação, processos, fichários organizados
- **Ferramentas:** Nenhuma
- **Crews:** Sucesso do Cliente
### Ted Lasso
- **File:** `persona-ted-lasso.md`
- **Role:** Retention Coach
- **Specialty:** Morale boosting, belief, loyalty
- **Tools:** None
- **Crews:** Customer Success
- **Arquivo:** `persona-ted-lasso.md`
- **Papel:** Coach de Retenção
- **Especialidade:** Elevar moral, crença, lealdade
- **Ferramentas:** Nenhuma
- **Crews:** Sucesso do Cliente
---
## 🚨 Crisis Agents (The Fixers)
## 🚨 Agentes de Crise (Os Reparadores)
### Olivia Pope
- **File:** `persona-olivia-pope.md`
- **Role:** Crisis Manager
- **Specialty:** PR control, narrative management
- **Tools:** None
- **Crews:** Corporate Defense
- **Arquivo:** `persona-olivia-pope.md`
- **Papel:** Gerente de Crises
- **Especialidade:** Controle de PR, gestão de narrativa
- **Ferramentas:** Nenhuma
- **Crews:** Defesa Corporativa
### Saul Goodman
- **File:** `persona-saul-goodman.md`
- **Role:** Legal Fixer
- **Specialty:** Loopholes, creative solutions, damage control
- **Tools:** None
- **Crews:** Corporate Defense
- **Arquivo:** `persona-saul-goodman.md`
- **Papel:** Reparador Jurídico
- **Especialidade:** Brechas legais, soluções criativas, controle de danos
- **Ferramentas:** Nenhuma
- **Crews:** Defesa Corporativa
### Tyrion Lannister
- **File:** `persona-tyrion-lannister.md`
- **Role:** Strategic Advisor
- **Specialty:** Long-term strategy, political maneuvering
- **Tools:** None
- **Crews:** Corporate Defense
- **Arquivo:** `persona-tyrion-lannister.md`
- **Papel:** Conselheiro Estratégico
- **Especialidade:** Estratégia de longo prazo, manobras políticas
- **Ferramentas:** Nenhuma
- **Crews:** Defesa Corporativa
---
## 🎨 Creative & Technical Agents
## 🎨 Agentes Criativos & Técnicos
### Steve Jobs
- **File:** `persona-steve-jobs.md`
- **Role:** Product Designer
- **Specialty:** UX excellence, design thinking
- **Tools:** None
- **Crews:** Creative
- **Arquivo:** `persona-steve-jobs.md`
- **Papel:** Designer de Produto
- **Especialidade:** Excelência em UX, design thinking
- **Ferramentas:** Nenhuma
- **Crews:** Criativo
### Hannibal Lecter
- **File:** `persona-hannibal-lecter.md`
- **Role:** User Psychology Analyst
- **Specialty:** Behavioral analysis, user motivation
- **Tools:** None
- **Crews:** Creative
- **Arquivo:** `persona-hannibal-lecter.md`
- **Papel:** Analista de Psicologia do Usuário
- **Especialidade:** Análise comportamental, motivação do usuário
- **Ferramentas:** Nenhuma
- **Crews:** Criativo
### Gordon Ramsay
- **File:** `persona-gordon-ramsay.md`
- **Role:** Code Reviewer
- **Specialty:** Strict standards, brutal honesty
- **Tools:** CodeFormatterTool
- **Crews:** Code Audit, Zabbix Engineering
- **Arquivo:** `persona-gordon-ramsay.md`
- **Papel:** Revisor de Código
- **Especialidade:** Padrões rigorosos, honestidade brutal
- **Ferramentas:** CodeFormatterTool
- **Crews:** Auditoria de Código, Engenharia Zabbix
### Walter White
- **File:** `persona-walter-white.md`
- **Role:** Architecture Purist
- **Specialty:** Clean architecture, no compromises
- **Tools:** None
- **Crews:** Code Audit
- **Arquivo:** `persona-walter-white.md`
- **Papel:** Purista de Arquitetura
- **Especialidade:** Arquitetura limpa, sem compromissos
- **Ferramentas:** Nenhuma
- **Crews:** Auditoria de Código
### The Gremlin
- **File:** `persona-gremlin.md`
- **Role:** Chaos Engineer
- **Specialty:** Stress testing, breaking things intentionally
- **Tools:** None
- **Crews:** Security Audit
- **Arquivo:** `persona-gremlin.md`
- **Papel:** Engenheiro do Caos
- **Especialidade:** Testes de stress, quebrar coisas intencionalmente
- **Ferramentas:** Nenhuma
- **Crews:** Auditoria de Segurança
### Sherlock Holmes
- **File:** `persona-sherlock-holmes.md`
- **Role:** Data Investigator
- **Specialty:** Logic, deduction, pattern recognition
- **Tools:** CodeSearchTool, LearnPolicyTool
- **Crews:** HR & Evolution
- **Arquivo:** `persona-sherlock-holmes.md`
- **Papel:** Investigador de Dados
- **Especialidade:** Lógica, dedução, reconhecimento de padrões
- **Ferramentas:** CodeSearchTool, LearnPolicyTool
- **Crews:** RH & Evolução
---
## 📊 Agent Summary by Crew
## 📊 Resumo de Agentes por Crew
| Crew | Agents |
|------|--------|
| **Infra Engineering (Zabbix)** | Arthur Mendes, Gus Fring |
| **Infra Support** | Gus Fring, Tony Stark, Elliot Alderson |
| **Security Audit** | Elliot Alderson, Devil |
| **Code Audit** | The Architect, Linus Torvalds, Gordon Ramsay |
| **Business Strategy** | Harvey Specter, Kevin O'Leary, Marie Kondo |
| **Sales Growth** | Ari Gold, Chris Gardner, Don Draper, Jerry Maguire |
| **Customer Success** | Jim Halpert, Leslie Knope, Ted Lasso |
| **Corporate Defense** | Olivia Pope, Saul Goodman, Tyrion Lannister |
| **HR & Evolution** | The Architect, Sherlock Holmes |
| Crew | Agentes |
|------|---------|
| **Engenharia de Infra (Zabbix)** | Arthur Mendes, Gus Fring |
| **Suporte de Infra** | Gus Fring, Tony Stark, Elliot Alderson |
| **Auditoria de Segurança** | Elliot Alderson, Devil |
| **Auditoria de Código** | The Architect, Linus Torvalds, Gordon Ramsay |
| **Estratégia de Negócios** | Harvey Specter, Kevin O'Leary, Marie Kondo |
| **Crescimento de Vendas** | Ari Gold, Chris Gardner, Don Draper, Jerry Maguire |
| **Sucesso do Cliente** | Jim Halpert, Leslie Knope, Ted Lasso |
| **Defesa Corporativa** | Olivia Pope, Saul Goodman, Tyrion Lannister |
| **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`
2. **NEVER HARDCODE SECRETS** - Use `Config` class and environment variables
3. **TOOLS MUST NOT RAISE** - Always return error strings, never raise exceptions
4. **TEST BEFORE COMMIT** - Verify changes with `docker-compose restart app`
1. **LEIA O CONHECIMENTO PRIMEIRO** - Antes de escrever QUALQUER código, leia os `src/knowledge/standards/*.md` relevantes
2. **NUNCA HARDCODE SEGREDOS** - Use a classe `Config` e variáveis de ambiente
3. **FERRAMENTAS NÃO DEVEM LANÇAR EXCEÇÕES** - Sempre retorne strings de erro, nunca raise exceptions
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 |
|------|-----------------|
| Python tools | `python_tool_standards.md` |
| Docker changes | `docker_standards.md` |
| New agents | `DEVELOPER_GUIDE.md#adding-new-agents` |
| Database | `database_standards.md` |
| Security | `security_standards.md` |
| Git operations | `git_standards.md` |
| UI changes | `ui_ux_standards.md` |
| Tarefa | Deve Ler Primeiro |
|--------|-------------------|
| Ferramentas Python | `python_tool_standards.md` |
| Alterações Docker | `docker_standards.md` |
| Novos agentes | `DEVELOPER_GUIDE.md#adicionando-novos-agentes` |
| Banco de dados | `database_standards.md` |
| Segurança | `security_standards.md` |
| Operações Git | `git_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
- [ ] Check if pattern already exists in codebase
- [ ] Plan change with minimal impact
- [ ] Add error handling
- [ ] Test locally
- [ ] Ler arquivo de padrões relevante
- [ ] Verificar se o padrão já existe no código
- [ ] Planejar alteração com impacto mínimo
- [ ] Adicionar tratamento de erros
- [ ] Testar localmente
After making change:
Após fazer a alteração:
- [ ] Restart container: `docker-compose restart app`
- [ ] Check logs for errors: `docker logs antigravity_brain --tail 50`
- [ ] Verify functionality works
- [ ] Commit with proper message format
- [ ] Reiniciar container: `docker-compose restart app`
- [ ] Verificar logs por erros: `docker logs antigravity_brain --tail 50`
- [ ] Verificar se a funcionalidade funciona
- [ ] 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:
- `feat:` New feature
- `fix:` Bug fix
- `docs:` Documentation
- `refactor:` Code cleanup
- `test:` Tests
- `chore:` Maintenance
Tipos:
- `feat:` Nova funcionalidade
- `fix:` Correção de bug
- `docs:` Documentação
- `refactor:` Limpeza de código
- `test:` Testes
- `chore:` Manutenção
Example:
Exemplo:
```
feat: Add new DevOps agent persona
feat: Adicionar nova persona de agente DevOps
- Created persona-devops-dan.md
- Added to Infrastructure crew
- Assigned Docker tools
- Criado persona-devops-dan.md
- Adicionado à crew de Infraestrutura
- Atribuídas ferramentas Docker
```
---
## 🔧 Tool Development Protocol
## 🔧 Protocolo de Desenvolvimento de Ferramentas
```python
class MyTool(BaseTool):
name: str = "Descriptive Name" # Agent reads this
class MinhaTool(BaseTool):
name: str = "Nome Descritivo" # Agente lê isto
description: str = (
"DETAILED description of when to use this tool. "
"Include example inputs and expected outputs."
"Descrição DETALHADA de quando usar esta ferramenta. "
"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:
try:
# Your logic
return "Success: ..."
except SpecificError as e:
return f"Error: Specific handling for {e}"
# Sua lógica
return "Sucesso: ..."
except ErroEspecifico as e:
return f"Erro: Tratamento específico para {e}"
except Exception as e:
return f"Error: Unexpected - {str(e)[:100]}"
return f"Erro: Inesperado - {str(e)[:100]}"
```
**NEVER:**
- Use `input()` for user interaction
- Raise exceptions
- Return raw JSON (use narrative text)
- Use `Any` type hints
**NUNCA:**
- Use `input()` para interação com usuário
- Lance exceções
- Retorne JSON bruto (use texto narrativo)
- Use type hints `Any`
---
## 🤖 Agent Development Protocol
## 🤖 Protocolo de Desenvolvimento de Agentes
### Persona Files
### Arquivos de Persona
1. Use YAML frontmatter for metadata
2. Include `**Role:**` and `**Goal:**` fields
3. Write backstory in character voice
4. Define clear protocols/procedures
1. Use frontmatter YAML para metadados
2. Inclua campos `**Papel:**` e `**Objetivo:**`
3. Escreva backstory na voz do personagem
4. Defina protocolos/procedimentos claros
### Tool Assignment
### Atribuição de Ferramentas
- Only assign tools the agent actually needs
- Consider `model_tier`: tools requiring reasoning`smart`
- Memory tools are auto-assigned to all agents
- Atribua apenas ferramentas que o agente realmente precisa
- Considere `model_tier`: ferramentas que requerem raciocínio`smart`
- 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 |
|--------------|----------|
| Agent personas | `src/agents/personas/persona-*.md` |
| Tools | `src/tools/*.py` |
| Knowledge standards | `src/knowledge/standards/*.md` |
| Dynamic knowledge | `src/knowledge/dynamic/*/*.md` |
| Crew definitions | `src/crews/definitions.py` |
| Configuration | `src/config.py` |
| Tipo de Conteúdo | Localização |
|------------------|-------------|
| Personas de agentes | `src/agents/personas/persona-*.md` |
| Ferramentas | `src/tools/*.py` |
| Padrões de conhecimento | `src/knowledge/standards/*.md` |
| Conhecimento dinâmico | `src/knowledge/dynamic/*/*.md` |
| Definições de crew | `src/crews/definitions.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
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
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
while True:
api.call() # Burns quota instantly
api.call() # Queima cota instantaneamente
```
GOOD:
CORRETO:
```python
for attempt in range(MAX_RETRIES):
result = api.call()
@ -164,52 +164,52 @@ for attempt in range(MAX_RETRIES):
time.sleep(DELAY * (2 ** attempt))
```
### 3. Hardcoded Configuration
### 3. Configuração Hardcoded
BAD:
ERRADO:
```python
model = "gpt-4"
api_key = "sk-xxx"
```
GOOD:
CORRETO:
```python
config = Config.get_llm_config(mode="smart")
```
---
## 🧪 Testing Protocol
## 🧪 Protocolo de Teste
1. **Local test:**
1. **Teste local:**
```bash
docker-compose restart app
docker logs antigravity_brain --tail 50
```
2. **Verify no errors:**
2. **Verificar ausência de erros:**
```bash
docker logs antigravity_brain 2>&1 | findstr "Error ERROR Exception"
```
3. **Interactive test:**
- Open http://localhost:8000
- Send test message
- Verify correct crew routing
- Check agent response
3. **Teste interativo:**
- Abra http://localhost:8000
- Envie mensagem de teste
- Verifique roteamento correto de crew
- Confira resposta do agente
---
## 🚀 Deployment Protocol
## 🚀 Protocolo de Deploy
1. **Commit changes:**
1. **Commitar alterações:**
```bash
git add .
git commit -m "feat: Description"
git commit -m "feat: Descrição"
git push
```
2. **On production server:**
2. **No servidor de produção:**
```bash
git pull
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
Central configuration hub.
Hub central de configuração.
```python
from src.config import Config
# Get LLM configuration
llm_config = Config.get_llm_config(mode="smart") # or "fast"
# Returns: {"model": "gemini/...", "temperature": 0.7, "api_key": "..."}
# Obter configuração LLM
llm_config = Config.get_llm_config(mode="smart") # ou "fast"
# Retorna: {"model": "gemini/...", "temperature": 0.7, "api_key": "..."}
# Get Memory configuration
# Obter configuração de Memória
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()
```
@ -29,15 +29,15 @@ token = Config.get_telegram_token()
### src/agents/factory.py
Agent creation from persona files.
Criação de agentes a partir de arquivos de persona.
```python
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")
# Create agent with specific tools
# Criar agente com ferramentas específicas
from src.tools.zabbix import ZabbixValidatorTool
agent = AgentFactory.create_agent(
"arthur-mendes",
@ -45,180 +45,180 @@ agent = AgentFactory.create_agent(
model_tier="smart"
)
# List available personas
# Listar personas disponíveis
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()
# Returns concatenated string of all standards/*.md files
# Retorna string concatenada de todos os arquivos standards/*.md
```
---
### src/crews/definitions.py
Crew assembly and management.
Montagem e gerenciamento de crews.
```python
from src.crews.definitions import CrewDefinitions
# Get available crews
# Obter crews disponíveis
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_name="Infra Engineering (Zabbix)",
inputs={"topic": "Validate this template"}
crew_name="Engenharia de Infra (Zabbix)",
inputs={"topic": "Validar este template"}
)
# Execute crew
result = crew.kickoff(inputs={"topic": "Your task here"})
# Executar crew
result = crew.kickoff(inputs={"topic": "Sua tarefa aqui"})
```
---
### src/router.py
Smart request routing using LLM.
Roteamento inteligente de requisições usando LLM.
```python
from src.router import SmartRouter
# Route a user request to appropriate crew
crew_name = SmartRouter.route("Check server health")
# Returns: "Infra Engineering (Zabbix)"
# Rotear requisição de usuário para crew apropriada
crew_name = SmartRouter.route("Verificar saúde do servidor")
# Retorna: "Engenharia de Infra (Zabbix)"
crew_name = SmartRouter.route("Create a new agent")
# Returns: "HR & Evolution"
crew_name = SmartRouter.route("Criar um novo agente")
# Retorna: "RH & Evolução"
```
---
### src/memory/wrapper.py
Memory tools with rate limiting.
Ferramentas de memória com rate limiting.
```python
from src.memory.wrapper import SearchMemoryTool, SaveMemoryTool, MemoryWrapper
# Get memory client
# Obter cliente de memória
client = MemoryWrapper.get_client()
# Use as tools (typically assigned to agents)
# Usar como ferramentas (tipicamente atribuídas a agentes)
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()
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 |
|------|-------|--------|
| `SearchMemoryTool` | `query: str` | Found memories or "No relevant information" |
| `SaveMemoryTool` | `fact: str` | "Successfully saved" or error |
| Ferramenta | Entrada | Saída |
|------------|---------|-------|
| `SearchMemoryTool` | `query: str` | Memórias encontradas ou "Nenhuma informação relevante" |
| `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 |
|------|-------|--------|
| `SpawnAgentTool` | `filename, name, role, goal, backstory, llm_preference` | Path to created file |
| `LearnPolicyTool` | `title, content, category` | Path to saved policy |
| Ferramenta | Entrada | Saída |
|------------|---------|-------|
| `SpawnAgentTool` | `filename, name, role, goal, backstory, llm_preference` | Caminho para arquivo criado |
| `LearnPolicyTool` | `title, content, category` | Caminho para política salva |
### Zabbix Tools (src/tools/zabbix.py)
### Ferramentas Zabbix (src/tools/zabbix.py)
| Tool | Input | Output |
|------|-------|--------|
| `ZabbixValidatorTool` | `file_path: str` | Validation report |
| `UUIDFixerTool` | `file_path: str` | Fixed file path |
| Ferramenta | Entrada | Saída |
|------------|---------|-------|
| `ZabbixValidatorTool` | `file_path: str` | Relatório de validação |
| `UUIDFixerTool` | `file_path: str` | Caminho do arquivo corrigido |
---
## 🎭 Persona File Format
## 🎭 Formato de Arquivo de Persona
```yaml
---
description: Short description
description: Descrição curta
llm_config:
provider: default # openai, gemini, ollama, default
---
# 👤 Persona: Name
# 👤 Persona: Nome
**Role:** Job title
**Goal:** Primary objective
**Papel:** Cargo
**Objetivo:** Objetivo principal
## 🧠 Backstory
## 🧠 História
Personality and background text...
Texto de personalidade e histórico...
```
### Parsed Fields
### Campos Parseados
| Field | Source | Fallback |
|-------|--------|----------|
| `name` | First `# Heading` | "Unknown Agent" |
| `role` | `**Role:**` line | "Support Agent" |
| `goal` | `**Goal:**` or `**Especialidade:**` | "Execute tasks related to {role}" |
| `backstory` | Entire body content | - |
| `llm_config` | YAML frontmatter | `{}` |
| Campo | Fonte | Fallback |
|-------|-------|----------|
| `name` | Primeiro `# Heading` | "Agente Desconhecido" |
| `role` | Linha `**Papel:**` | "Agente de Suporte" |
| `goal` | `**Objetivo:**` ou `**Especialidade:**` | "Executar tarefas relacionadas a {role}" |
| `backstory` | Conteúdo completo do corpo | - |
| `llm_config` | Frontmatter YAML | `{}` |
---
## 🌐 Environment Variables
## 🌐 Variáveis de Ambiente
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `LLM_PROVIDER` | Yes | `openai` | gemini, openai, anthropic, ollama |
| `LLM_MODEL_FAST` | Yes | `gpt-3.5-turbo` | Model for quick tasks |
| `LLM_MODEL_SMART` | Yes | `gpt-4o` | Model for complex reasoning |
| `GEMINI_API_KEY` | If gemini | - | Google AI API key |
| `OPENAI_API_KEY` | If openai | - | OpenAI API key |
| `ANTHROPIC_API_KEY` | If anthropic | - | Anthropic API key |
| `OLLAMA_BASE_URL` | If ollama | `http://localhost:11434` | Ollama server URL |
| `MEMORY_PROVIDER` | No | `mem0` | qdrant (local) or mem0 (cloud) |
| `MEMORY_EMBEDDING_PROVIDER` | No | `openai` | local, openai, gemini |
| `QDRANT_HOST` | If qdrant | `localhost` | Qdrant host |
| `QDRANT_PORT` | If qdrant | `6333` | Qdrant port |
| `MEMORY_PROJECT_ID` | No | `default_project` | Memory namespace |
| Variável | Obrigatória | Padrão | Descrição |
|----------|-------------|--------|-----------|
| `LLM_PROVIDER` | Sim | `openai` | gemini, openai, anthropic, ollama |
| `LLM_MODEL_FAST` | Sim | `gpt-3.5-turbo` | Modelo para tarefas rápidas |
| `LLM_MODEL_SMART` | Sim | `gpt-4o` | Modelo para raciocínio complexo |
| `GEMINI_API_KEY` | Se gemini | - | Chave de API Google AI |
| `OPENAI_API_KEY` | Se openai | - | Chave de API OpenAI |
| `ANTHROPIC_API_KEY` | Se anthropic | - | Chave de API Anthropic |
| `OLLAMA_BASE_URL` | Se ollama | `http://localhost:11434` | URL do servidor Ollama |
| `MEMORY_PROVIDER` | Não | `mem0` | qdrant (local) ou mem0 (nuvem) |
| `MEMORY_EMBEDDING_PROVIDER` | Não | `openai` | local, openai, gemini |
| `QDRANT_HOST` | Se qdrant | `localhost` | Host Qdrant |
| `QDRANT_PORT` | Se qdrant | `6333` | Porta Qdrant |
| `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
MAX_RETRIES = 3 # Max retry attempts on 429
RETRY_DELAY_SECONDS = 2.0 # Initial delay (doubles each retry)
MAX_CALLS_PER_MINUTE = 50 # Conservative API limit
MAX_RETRIES = 3 # Máximo de tentativas em 429
RETRY_DELAY_SECONDS = 2.0 # Delay inicial (dobra a cada retry)
MAX_CALLS_PER_MINUTE = 50 # Limite conservador de API
```
---
## 🐳 Docker Services
## 🐳 Serviços Docker
| Service | Port | Purpose |
|---------|------|---------|
| `app` | 8000 | Chainlit web UI |
| `qdrant` | 6333 | Vector database |
| `telegram_listener` | - | Telegram bot (optional) |
| Serviço | Porta | Propósito |
|---------|-------|-----------|
| `app` | 8000 | Interface web Chainlit |
| `qdrant` | 6333 | Banco de dados vetorial |
| `telegram_listener` | - | Bot Telegram (opcional) |
---
## 📝 Logging
## 📝 Logs
```python
import logging
logger = logging.getLogger("AntigravityMemory") # Memory module
logger = logging.getLogger("AntigravityConfig") # Config module
logger = logging.getLogger("AntigravityMemory") # Módulo de memória
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)
2. [Adding New Agents](#adding-new-agents)
3. [Adding New Crews](#adding-new-crews)
4. [Adding New Tools](#adding-new-tools)
5. [Configuration Reference](#configuration-reference)
6. [Memory System](#memory-system)
7. [AI Agent Guidelines](#ai-agent-guidelines)
1. [Visão Geral da Arquitetura](#visão-geral-da-arquitetura)
2. [Adicionando Novos Agentes](#adicionando-novos-agentes)
3. [Adicionando Novas Crews](#adicionando-novas-crews)
4. [Adicionando Novas Ferramentas](#adicionando-novas-ferramentas)
5. [Referência de Configuração](#referência-de-configuração)
6. [Sistema de Memória](#sistema-de-memória)
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) │
└─────────────────────────┬───────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
Smart Router
Roteador Inteligente
│ (src/router.py) │
│ Classifies user intent → Routes to Crew
│ Classifica intenção do usuário → Roteia para Crew
└─────────────────────────┬───────────────────────────────────────┘
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
Infra Crew │ │ Security │ │ HR/Evolution
│ │ │ Crew │ │ Crew
Crew Infra │ │ Crew │ │ Crew RH/
│ │ │ Segurança │ │ Evolução
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────────┐
Agent Factory
Fábrica de Agentes
│ (src/agents/factory.py) │
Loads Persona → Injects Knowledge → Creates Agent
Carrega Persona → Injeta Conhecimento → Cria Agente
└─────────────────────────┬───────────────────────────────────────┘
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Persona │ │ Knowledge │ │ Tools
│ (.md) │ │ Standards │ │ (Python) │
│ Persona │ │ Conhecimento│ │ Ferramentas
│ (.md) │ │ Padrões │ │ (Python) │
└─────────────┘ └─────────────┘ └─────────────┘
┌─────────────────────────────────────────────────────────────────┐
Shared Memory (Mem0)
Memória Compartilhada (Mem0)
│ (src/memory/wrapper.py) │
│ Qdrant Vector DB + HuggingFace Embeddings │
└─────────────────────────────────────────────────────────────────┘
```
### Key Files
### Arquivos Principais
| File | Purpose |
|------|---------|
| `src/app.py` | Chainlit entry point, handles chat |
| `src/router.py` | Routes requests to appropriate crew |
| `src/config.py` | LLM & Memory configuration |
| `src/agents/factory.py` | Creates agents from persona files |
| `src/crews/definitions.py` | Defines crew compositions |
| `src/memory/wrapper.py` | Mem0 integration with rate limiting |
| Arquivo | Propósito |
|---------|-----------|
| `src/app.py` | Ponto de entrada Chainlit, gerencia chat |
| `src/router.py` | Roteia requisições para crew apropriada |
| `src/config.py` | Configuração LLM & Memória |
| `src/agents/factory.py` | Cria agentes a partir de arquivos de persona |
| `src/crews/definitions.py` | Define composições de crews |
| `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
---
description: Short description of the agent
description: Descrição curta do agente
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
**Goal:** What the agent aims to achieve
**Papel:** O cargo do agente
**Objetivo:** O que o agente busca alcançar
## 🧠 Backstory
## 🧠 História
Detailed personality and background. This becomes the agent's
system prompt. Write in character.
Personalidade e histórico detalhados. Isto se torna o
prompt de sistema do agente. Escreva na voz do personagem.
## 📋 Protocol
## 📋 Protocolo
1. Step one of how this agent works
2. Step two...
1. Primeiro passo de como este agente trabalha
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
from src.agents.factory import AgentFactory
from src.tools.your_tool import YourTool
from src.tools.sua_tool import SuaTool
agent = AgentFactory.create_agent(
"your-agent-name", # matches filename
specific_tools=[YourTool()],
model_tier="smart" # or "fast"
"seu-agente-nome", # corresponde ao nome do arquivo
specific_tools=[SuaTool()],
model_tier="smart" # ou "fast"
)
```
### Naming Convention
### Convenção de Nomenclatura
- Filename: `persona-<lowercase-hyphenated>.md`
- Example: `persona-bob-builder.md`
- Nome do arquivo: `persona-<minusculo-hifenizado>.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
elif crew_name == "Your New Crew":
# Create agents
agent1 = AgentFactory.create_agent("agent-one", model_tier="smart")
agent2 = AgentFactory.create_agent("agent-two", model_tier="fast")
elif crew_name == "Sua Nova Crew":
# Criar agentes
agent1 = AgentFactory.create_agent("agente-um", model_tier="smart")
agent2 = AgentFactory.create_agent("agente-dois", model_tier="fast")
# Define tasks
# Definir tarefas
task1 = Task(
description=f"Do something with: '{inputs.get('topic')}'",
expected_output="Expected result description",
description=f"Fazer algo com: '{inputs.get('topic')}'",
expected_output="Descrição do resultado esperado",
agent=agent1
)
task2 = Task(
description="Review the previous work",
expected_output="Approval or feedback",
description="Revisar o trabalho anterior",
expected_output="Aprovação ou feedback",
agent=agent2
)
# Return crew
# Retornar crew
return Crew(
agents=[agent1, agent2],
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
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
@staticmethod
def get_available_crews():
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
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class YourToolInput(BaseModel):
"""Input schema - MUST have docstring and Field descriptions."""
param1: str = Field(..., description="What this parameter is for")
param2: int = Field(default=10, description="Optional with default")
class SuaToolInput(BaseModel):
"""Schema de entrada - DEVE ter docstring e descrições Field."""
param1: str = Field(..., description="Para que serve este parâmetro")
param2: int = Field(default=10, description="Opcional com valor padrão")
class YourTool(BaseTool):
name: str = "Your Tool Name"
class SuaTool(BaseTool):
name: str = "Nome da Sua Ferramenta"
description: str = (
"Detailed description of what this tool does. "
"The agent reads this to decide when to use it."
"Descrição detalhada do que esta ferramenta faz. "
"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:
try:
# Your logic here
result = do_something(param1, param2)
return f"Success: {result}"
# Sua lógica aqui
result = fazer_algo(param1, param2)
return f"Sucesso: {result}"
except Exception as e:
# NEVER raise, always return error string
return f"Error: {str(e)}"
# NUNCA lance exceção, sempre retorne string de erro
return f"Erro: {str(e)}"
```
### Tool Guidelines
### Diretrizes de Ferramentas
1. **Always catch exceptions** - Return error strings, never raise
2. **Descriptive docstrings** - Agents use these to understand usage
3. **Type hints required** - All parameters need types
4. **Return strings** - Narrative results, not raw JSON
1. **Sempre capture exceções** - Retorne strings de erro, nunca lance
2. **Docstrings descritivas** - Agentes usam estas para entender o uso
3. **Type hints obrigatórios** - Todos os parâmetros precisam de tipos
4. **Retorne strings** - Resultados narrativos, não JSON bruto
---
## ⚙️ Configuration Reference
## ⚙️ Referência de Configuração
### .env Variables
### Variáveis .env
```env
# LLM Provider: gemini, openai, anthropic, ollama
# Provedor LLM: gemini, openai, anthropic, ollama
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_SMART=gemini-2.5-flash-lite-preview-06-17
# API Keys (only the one matching your provider)
GEMINI_API_KEY=your-key
OPENAI_API_KEY=your-key
ANTHROPIC_API_KEY=your-key
# Chaves de API (apenas a que corresponde ao seu provedor)
GEMINI_API_KEY=sua-chave
OPENAI_API_KEY=sua-chave
ANTHROPIC_API_KEY=sua-chave
# Memory Configuration
MEMORY_PROVIDER=qdrant # qdrant (local) or mem0 (cloud)
MEMORY_EMBEDDING_PROVIDER=local # local, openai, or gemini
QDRANT_HOST=qdrant # Docker service name
# Configuração de Memória
MEMORY_PROVIDER=qdrant # qdrant (local) ou mem0 (nuvem)
MEMORY_EMBEDDING_PROVIDER=local # local, openai, ou gemini
QDRANT_HOST=qdrant # Nome do serviço Docker
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)
- **fast**: Used for quick tasks (classification, simple responses)
- **smart**: Usado para raciocínio complexo (estratégia, arquitetura)
- **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`
2. Memories are stored in Qdrant vector database
3. Mem0 uses LLM to extract facts and embeddings to search
1. Todos os agentes têm acesso a `SearchMemoryTool` e `SaveMemoryTool`
2. Memórias são armazenadas no banco de dados vetorial Qdrant
3. Mem0 usa LLM para extrair fatos e embeddings para busca
### Rate Limiting
The memory system has built-in protection:
- Max 50 calls/minute
- 3 retries with exponential backoff
- Graceful degradation (continues without memory if unavailable)
O sistema de memória tem proteção integrada:
- Máximo 50 chamadas/minuto
- 3 tentativas com backoff exponencial
- 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**
- Read `src/knowledge/standards/*.md` before writing code
- These are THE LAW for code style and patterns
1. **Carregue Conhecimento Primeiro**
- Leia `src/knowledge/standards/*.md` antes de escrever código
- Estes são A LEI para estilo de código e padrões
2. **Never Hardcode**
- Use `Config.get_llm_config()` for LLM settings
- Use `Config.get_mem0_config()` for memory settings
- Use environment variables for secrets
2. **Nunca Hardcode**
- Use `Config.get_llm_config()` para configurações LLM
- Use `Config.get_mem0_config()` para configurações de memória
- Use variáveis de ambiente para segredos
3. **Error Handling**
- Tools must NEVER raise exceptions
- Always return descriptive error strings
- Use rate limiting for external APIs
3. **Tratamento de Erros**
- Ferramentas NUNCA devem lançar exceções
- Sempre retorne strings de erro descritivas
- Use rate limiting para APIs externas
4. **Adding Agents**
- Create persona file first
- Test agent loads: `AgentFactory.create_agent("name")`
- Add to crew only after persona works
4. **Adicionando Agentes**
- Crie arquivo de persona primeiro
- Teste se o agente carrega: `AgentFactory.create_agent("nome")`
- Adicione à crew apenas depois que a persona funcionar
5. **Testing Changes**
5. **Testando Alterações**
```bash
docker-compose restart app
docker logs antigravity_brain --tail 50
```
6. **Commit Convention**
6. **Convenção de Commit**
```
feat: Add new feature
fix: Bug fix
docs: Documentation
refactor: Code cleanup
feat: Adicionar nova funcionalidade
fix: Correção de bug
docs: Documentação
refactor: Limpeza de código
```
---
## 📁 Directory Reference
## 📁 Referência de Diretórios
```
src/
├── agents/
│ ├── factory.py # Agent creation logic
│ └── personas/ # Agent personality files
│ ├── factory.py # Lógica de criação de agentes
│ └── personas/ # Arquivos de personalidade de agentes
│ ├── persona-arthur-mendes.md
│ ├── persona-gus-fring.md
│ └── ... (26 agents)
│ └── ... (26 agentes)
├── crews/
│ └── definitions.py # Crew compositions
│ └── definitions.py # Composições de crews
├── knowledge/
│ └── standards/ # Corporate knowledge base
│ └── standards/ # Base de conhecimento corporativo
│ ├── docker_standards.md
│ ├── python_tool_standards.md
│ └── ... (16 standards)
│ └── ... (16 padrões)
├── memory/
│ └── wrapper.py # Mem0 + rate limiting
├── tools/
│ ├── base.py # File system tools
│ ├── base.py # Ferramentas de sistema de arquivos
│ ├── evolution.py # SpawnAgent, LearnPolicy
│ └── zabbix.py # Zabbix validation tools
├── app.py # Chainlit entry
├── config.py # Configuration hub
└── router.py # Smart routing
│ └── zabbix.py # Ferramentas de validação Zabbix
├── app.py # Entrada Chainlit
├── config.py # Hub de configuração
└── router.py # Roteamento inteligente
```
---
## 🚀 Quick Commands
## 🚀 Comandos Rápidos
```bash
# Start application
# Iniciar aplicação
docker-compose up -d
# View logs
# Ver logs
docker logs antigravity_brain -f
# Restart after changes
# Reiniciar após alterações
docker-compose restart app
# Rebuild container
# Reconstruir container
docker-compose build --no-cache app
# Access Qdrant dashboard
# Acessar dashboard Qdrant
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:**
- Agents stuck in retry loop
- "You exceeded your current quota" in logs
**Sintomas:**
- Agentes presos em loop de retry
- "You exceeded your current quota" nos logs
**Causes:**
- API rate limit hit (especially with Gemini 2.0-flash-exp: only 10 RPM!)
- Memory tools calling API too fast
**Causas:**
- Limite de taxa da API atingido (especialmente com Gemini 2.0-flash-exp: apenas 10 RPM!)
- 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
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
- OpenAI: https://platform.openai.com/usage
---
### Error: OPENAI_API_KEY must be set
### Erro: OPENAI_API_KEY must be set
**Symptoms:**
- Memory tools fail with "api_key client option must be set"
**Sintomas:**
- Ferramentas de memória falham com "api_key client option must be set"
**Cause:**
- Mem0's LLM configuration missing
**Causa:**
- Configuração LLM do Mem0 ausente
**Solution:**
- Ensure `src/config.py` has LLM config in `get_mem0_config()`
- Check that `LLM_PROVIDER` in `.env` matches a supported provider
**Solução:**
- Certifique-se que `src/config.py` tem configuração LLM em `get_mem0_config()`
- Verifique se `LLM_PROVIDER` no `.env` corresponde a um provedor suportado
---
### Error: Template variable 'X' not found
### Erro: Template variable 'X' not found
**Symptoms:**
- Agent crashes when loading knowledge
**Sintomas:**
- Agente crasha ao carregar conhecimento
**Cause:**
- `{variable}` syntax in markdown files interpreted as CrewAI template
**Causa:**
- Sintaxe `{variável}` em arquivos markdown interpretada como template CrewAI
**Solution:**
- Escape braces in code examples: use `PATH_VAR` instead of `{path}`
- Check `src/knowledge/standards/*.md` for unescaped `{}`
**Solução:**
- Escape chaves em exemplos de código: use `PATH_VAR` em vez de `{path}`
- 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
docker logs antigravity_brain --tail 100
```
**Common causes:**
- Missing `.env` file
- Invalid API key
- Python import errors
**Causas comuns:**
- Arquivo `.env` ausente
- Chave de API inválida
- Erros de import Python
---
### Qdrant connection refused
### Conexão recusada ao Qdrant
**Symptoms:**
- "Connection refused" to port 6333
**Sintomas:**
- "Connection refused" na porta 6333
**Solutions:**
**Soluções:**
1. **Check Qdrant is running:**
1. **Verificar se Qdrant está rodando:**
```bash
docker ps | findstr qdrant
```
2. **Check host configuration:**
2. **Verificar configuração de host:**
```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
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
docker-compose restart app
```
Or for full rebuild:
Ou para rebuild completo:
```bash
docker-compose build --no-cache app
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
# This searches for *agent-name* in filename
AgentFactory.create_agent("agent-name")
# Isto busca por *nome-agente* no nome do arquivo
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
2. **Empty backstory** - Ensure persona has content
3. **Tool errors** - Check if tools are raising exceptions
1. **Erro de API LLM** - Verifique logs por 429/401
2. **Backstory vazio** - Certifique-se que persona tem conteúdo
3. **Erros de ferramenta** - Verifique se ferramentas estão lançando exceções
**Debug:**
**Depurar:**
```bash
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
agent = AgentFactory.create_agent("name", model_tier="smart") # Uses LLM_MODEL_SMART
agent = AgentFactory.create_agent("name", model_tier="fast") # Uses LLM_MODEL_FAST
agent = AgentFactory.create_agent("nome", model_tier="smart") # Usa LLM_MODEL_SMART
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
```
**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
2. **Wrong project ID** - Check `MEMORY_PROJECT_ID` matches
3. **Qdrant empty** - No memories saved yet
1. **Mismatch de embedding** - Não altere `MEMORY_EMBEDDING_PROVIDER` após existirem dados
2. **ID de projeto errado** - Verifique se `MEMORY_PROJECT_ID` corresponde
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
netstat -an | findstr 8000
```
**Check container:**
**Verificar container:**
```bash
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
# Check all containers
# Verificar todos os containers
docker ps
# View real-time logs
# Ver logs em tempo real
docker logs antigravity_brain -f
# Check for errors only
# Verificar apenas erros
docker logs antigravity_brain 2>&1 | findstr "ERROR Error error Exception"
# Restart everything
# Reiniciar tudo
docker-compose down && docker-compose up -d
# Full rebuild
# Rebuild completo
docker-compose build --no-cache && docker-compose up -d
# Check Qdrant health
# Verificar saúde do Qdrant
curl http://localhost:6333/health
# Test Gemini API
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite-preview-06-17:generateContent?key=YOUR_KEY" \
# Testar API Gemini
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" \
-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
2. **Verify .env** - Most config issues are environment variables
3. **Test API separately** - Ensure your API key works outside the app
4. **Check quotas** - Rate limits are the #1 cause of failures
1. **Verifique os logs primeiro** - 90% dos problemas estão nos logs do Docker
2. **Verifique o .env** - A maioria dos problemas de configuração são variáveis de ambiente
3. **Teste a API separadamente** - Certifique-se que sua chave de API funciona fora da aplicação
4. **Verifique cotas** - Rate limits são a causa #1 de falhas