225 lines
5.9 KiB
Markdown
225 lines
5.9 KiB
Markdown
# 🔧 Referência de API & Código
|
|
|
|
Referência técnica para o código do Antigravity Brain.
|
|
|
|
---
|
|
|
|
## 📦 Módulos Principais
|
|
|
|
### src/config.py
|
|
|
|
Hub central de configuração.
|
|
|
|
```python
|
|
from src.config import Config
|
|
|
|
# Obter configuração LLM
|
|
llm_config = Config.get_llm_config(mode="smart") # ou "fast"
|
|
# Retorna: {"model": "gemini/...", "temperature": 0.7, "api_key": "..."}
|
|
|
|
# Obter configuração de Memória
|
|
mem_config = Config.get_mem0_config()
|
|
# Retorna: {"llm": {...}, "embedder": {...}, "vector_store": {...}}
|
|
|
|
# Obter token do Telegram
|
|
token = Config.get_telegram_token()
|
|
```
|
|
|
|
---
|
|
|
|
### src/agents/factory.py
|
|
|
|
Criação de agentes a partir de arquivos de persona.
|
|
|
|
```python
|
|
from src.agents.factory import AgentFactory
|
|
|
|
# Criar agente com ferramentas padrão
|
|
agent = AgentFactory.create_agent("arthur-mendes", model_tier="smart")
|
|
|
|
# Criar agente com ferramentas específicas
|
|
from src.tools.zabbix import ZabbixValidatorTool
|
|
agent = AgentFactory.create_agent(
|
|
"arthur-mendes",
|
|
specific_tools=[ZabbixValidatorTool()],
|
|
model_tier="smart"
|
|
)
|
|
|
|
# Listar personas disponíveis
|
|
personas = AgentFactory.list_available_personas()
|
|
# Retorna: ["persona-arthur-mendes", "persona-gus-fring", ...]
|
|
|
|
# Carregar conhecimento corporativo
|
|
knowledge = AgentFactory.load_knowledge_base()
|
|
# Retorna string concatenada de todos os arquivos standards/*.md
|
|
```
|
|
|
|
---
|
|
|
|
### src/crews/definitions.py
|
|
|
|
Montagem e gerenciamento de crews.
|
|
|
|
```python
|
|
from src.crews.definitions import CrewDefinitions
|
|
|
|
# Obter crews disponíveis
|
|
crews = CrewDefinitions.get_available_crews()
|
|
# Retorna: ["Engenharia de Infra (Zabbix)", "Auditoria de Segurança", ...]
|
|
|
|
# Montar uma crew
|
|
crew = CrewDefinitions.assemble_crew(
|
|
crew_name="Engenharia de Infra (Zabbix)",
|
|
inputs={"topic": "Validar este template"}
|
|
)
|
|
|
|
# Executar crew
|
|
result = crew.kickoff(inputs={"topic": "Sua tarefa aqui"})
|
|
```
|
|
|
|
---
|
|
|
|
### src/router.py
|
|
|
|
Roteamento inteligente de requisições usando LLM.
|
|
|
|
```python
|
|
from src.router import SmartRouter
|
|
|
|
# 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("Criar um novo agente")
|
|
# Retorna: "RH & Evolução"
|
|
```
|
|
|
|
---
|
|
|
|
### src/memory/wrapper.py
|
|
|
|
Ferramentas de memória com rate limiting.
|
|
|
|
```python
|
|
from src.memory.wrapper import SearchMemoryTool, SaveMemoryTool, MemoryWrapper
|
|
|
|
# Obter cliente de memória
|
|
client = MemoryWrapper.get_client()
|
|
|
|
# Usar como ferramentas (tipicamente atribuídas a agentes)
|
|
search_tool = SearchMemoryTool()
|
|
result = search_tool._run(query="O que sabemos sobre Zabbix?")
|
|
|
|
save_tool = SaveMemoryTool()
|
|
result = save_tool._run(fact="O servidor roda na porta 8000")
|
|
```
|
|
|
|
---
|
|
|
|
## 🔧 Ferramentas Disponíveis
|
|
|
|
### Ferramentas de Memória (src/memory/wrapper.py)
|
|
|
|
| Ferramenta | Entrada | Saída |
|
|
|------------|---------|-------|
|
|
| `SearchMemoryTool` | `query: str` | Memórias encontradas ou "Nenhuma informação relevante" |
|
|
| `SaveMemoryTool` | `fact: str` | "Salvo com sucesso" ou erro |
|
|
|
|
### Ferramentas de Evolução (src/tools/evolution.py)
|
|
|
|
| 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 |
|
|
|
|
### Ferramentas Zabbix (src/tools/zabbix.py)
|
|
|
|
| Ferramenta | Entrada | Saída |
|
|
|------------|---------|-------|
|
|
| `ZabbixValidatorTool` | `file_path: str` | Relatório de validação |
|
|
| `UUIDFixerTool` | `file_path: str` | Caminho do arquivo corrigido |
|
|
|
|
---
|
|
|
|
## 🎭 Formato de Arquivo de Persona
|
|
|
|
```yaml
|
|
---
|
|
description: Descrição curta
|
|
llm_config:
|
|
provider: default # openai, gemini, ollama, default
|
|
---
|
|
|
|
# 👤 Persona: Nome
|
|
|
|
**Papel:** Cargo
|
|
**Objetivo:** Objetivo principal
|
|
|
|
## 🧠 História
|
|
|
|
Texto de personalidade e histórico...
|
|
```
|
|
|
|
### Campos Parseados
|
|
|
|
| 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 | `{}` |
|
|
|
|
---
|
|
|
|
## 🌐 Variáveis de Ambiente
|
|
|
|
| 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 |
|
|
|
|
---
|
|
|
|
## 🔄 Constantes de Rate Limiting
|
|
|
|
Em `src/memory/wrapper.py`:
|
|
|
|
```python
|
|
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
|
|
```
|
|
|
|
---
|
|
|
|
## 🐳 Serviços Docker
|
|
|
|
| Serviço | Porta | Propósito |
|
|
|---------|-------|-----------|
|
|
| `app` | 8000 | Interface web Chainlit |
|
|
| `qdrant` | 6333 | Banco de dados vetorial |
|
|
| `telegram_listener` | - | Bot Telegram (opcional) |
|
|
|
|
---
|
|
|
|
## 📝 Logs
|
|
|
|
```python
|
|
import logging
|
|
logger = logging.getLogger("AntigravityMemory") # Módulo de memória
|
|
logger = logging.getLogger("AntigravityConfig") # Módulo de configuração
|
|
```
|
|
|
|
Logs aparecem no Docker: `docker logs antigravity_brain -f`
|