Skip to content

6. Setup Local e Desenvolvimento

Pré-requisitos

Ferramenta Versão Para quê
Python 3.11+ Runtime
Docker 20+ Containers locais (MySQL, Redis, etc.)
Git 2.x Versionamento (usamos Git Flow)
gcloud CLI latest Deploy e acesso a recursos GCP
VS Code latest IDE recomendada

Extensões VS Code recomendadas

  • Python (ms-python.python)
  • Pylance (ms-python.vscode-pylance)
  • Markdown Preview Mermaid (bierner.markdown-mermaid) — para ver diagramas nas docs
  • Docker (ms-azuretools.vscode-docker)

Setup inicial

1. Clone e configure o ambiente virtual

git clone <repo-url> ifriend-agents
cd ifriend-agents

python3.11 -m venv venv
source venv/bin/activate

pip install -r requirements-dev.txt
pip install -r requirements-messaging.txt

2. Configure variáveis de ambiente

Copie o .env.example e preencha:

cp .env.example .env

Variáveis mínimas para dev local:

# Modelo
MODEL=gemini-2.5-flash
GOOGLE_CLOUD_PROJECT=seu-projeto-gcp
GOOGLE_GENAI_USE_VERTEXAI=true

# Session (use inmemory para dev simples)
SESSION_BACKEND=inmemory

# Ou Redis se quiser persistência:
# SESSION_BACKEND=redis
# REDIS_URL=redis://localhost:6379

# API iFriend (peça ao time)
API_BASE_URL=https://api.staging.ifriend.com.br
API_EMAIL=sua-conta@ifriend.com.br
API_PASSWORD=sua-senha

# JWT (para testes locais)
JWT_SECRET_KEY=sua-chave-secreta-local
JWT_ALGORITHM=HS256
JWT_VERIFY_EXPIRATION=false

# Log
LOG_LEVEL=DEBUG

Dica: peça ao time o .env de staging — ele já vem com a maioria das variáveis preenchidas.

3. Suba containers auxiliares (se necessário)

Se precisar de Redis e MySQL locais:

# Apenas Redis
docker run -d --name redis -p 6379:6379 redis:7-alpine

# Ou o docker-compose completo (PostgreSQL + OpenMemory)
docker-compose up -d

Para MySQL local, veja MYSQL_LOCAL.md na raiz.

4. Autentique no GCP

gcloud auth login
gcloud auth application-default login
gcloud config set project seu-projeto-gcp

Executando o projeto

Modo desenvolvimento (com hot reload)

source venv/bin/activate
uvicorn unified_bot:app --reload --host 0.0.0.0 --port 8080

O servidor sobe em http://localhost:8080.

Endpoints úteis para teste

Endpoint Método Descrição
/ GET Health check
/webchat/message POST Enviar mensagem via WebChat
/sse/chat POST Enviar mensagem via SSE
/sse/stream/{id} GET Stream de eventos SSE

Testando via WebChat (mais fácil)

# Enviar uma mensagem de teste
curl -X POST http://localhost:8080/webchat/message \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Quero um tour em Roma",
    "user_id": "dev-test-123",
    "session_id": "test-session-1"
  }'

Testando via SSE

  1. Abra examples/sse-chat.html no navegador
  2. Ou use a interface simples: examples/webchat-simple.html

Testando com JWT

Use o script de geração de JWT para testes:

python generate_test_jwt.py

Rodando testes

# Todos os testes
pytest

# Somente testes unitários
pytest -m unit

# Somente testes rápidos (excluindo lentos)
pytest -m "not slow"

# Arquivo específico
pytest tests/test_webchat.py -v

# Com output detalhado
pytest -v --tb=short

Estrutura de testes

tests/                         ← Integração e E2E
├── test_webchat.py            ← WebChat adapter
├── test_sse_adapter.py        ← SSE adapter
├── test_whatsapp_evolution.py ← WhatsApp Evolution
├── test_whatsapp_official.py  ← WhatsApp Official
├── test_jwt_context_manager.py← JWT decode/validate
├── test_jwt_e2e_sse.py        ← JWT E2E via SSE
├── test_jwt_e2e_webchat.py    ← JWT E2E via WebChat
├── ...

ifriend_agent/tests/           ← Unitários do agente
├── test_age_policies_mapping.py
├── test_session_service.py
├── tools/                     ← Testes de tools 
└── ...

ifriend_agent/evaluations/     ← Avaliação de qualidade do agente

Git Flow

O projeto segue Git Flow:

gitgraph
    commit id: "main"
    branch develop
    commit id: "develop"
    branch feature/minha-feature
    commit id: "implementação"
    commit id: "testes"
    checkout develop
    merge feature/minha-feature id: "merge feature"
    branch release/v2.6.0
    commit id: "bump version"
    checkout main
    merge release/v2.6.0 id: "release"
    checkout develop
    merge release/v2.6.0 id: "sync"
# Iniciar nova feature
git flow feature start minha-feature

# Finalizar feature (merge no develop)
git flow feature finish minha-feature

# Release
git flow release start v2.6.0
git flow release finish v2.6.0

Deploy

Staging (automático via Cloud Build)

Push para develop → Cloud Build executa cloudbuild.stage.yaml → Deploy no Cloud Run staging.

Produção

Push para main → Cloud Build executa cloudbuild.yaml → Deploy no Cloud Run produção.

flowchart LR
    DEV["develop branch"] -->|push| CBS["Cloud Build<br/>(staging)"]
    CBS --> CRS["Cloud Run<br/>Staging"]

    MAIN["main branch"] -->|push| CBP["Cloud Build<br/>(produção)"]
    CBP --> CRP["Cloud Run<br/>Produção"]

Build local com Docker

docker build -t ifriend-agents .
docker run -p 8080:8080 --env-file .env ifriend-agents

Debug

Com VS Code

  1. Defina ENABLE_DEBUGPY=true e DEBUGPY_PORT=5678 no .env
  2. Use a configuração de debug do VS Code (ver DEBUG_QUICKSTART.md)

Logs

# Em dev local, o LOG_LEVEL=DEBUG mostra tudo
# Veja logs do Cloud Run:
gcloud run logs read --service ifriend-agents --region us-central1

Variáveis de ambiente: referência rápida

Categoria Variáveis principais
Core MODEL, GOOGLE_CLOUD_PROJECT, GOOGLE_GENAI_USE_VERTEXAI
Agent AGENT_TEMPERATURE, AGENT_TOP_P, AGENT_TOP_K, AGENT_MAX_OUTPUT_TOKENS
Session SESSION_BACKEND (redis/cloudsql/inmemory)
Memory MEMORY_BACKEND (cloudsql/redis/openmemory)
Redis REDIS_URL, REDIS_SESSION_TTL
CloudSQL CLOUDSQL_USER, CLOUDSQL_PASSWORD, CLOUDSQL_HOST, CLOUDSQL_DATABASE
API API_BASE_URL, API_EMAIL, API_PASSWORD, API_TIMEOUT
JWT JWT_SECRET_KEY, JWT_ALGORITHM, JWT_PUBLIC_KEY
Slack SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET
WhatsApp WHATSAPP_EVOLUTION_API_URL, WHATSAPP_EVOLUTION_API_KEY
WebChat WEBCHAT_ENABLED, WEBCHAT_ALLOWED_ORIGINS
SSE SSE_ENABLED
Debug LOG_LEVEL, ENABLE_DEBUGPY, DEBUGPY_PORT

Para a lista completa, consulte .env.example (~300 variáveis).

Troubleshooting comum

Problema Solução
ModuleNotFoundError Ative o venv: source venv/bin/activate
Could not connect to Redis Suba o Redis: docker run -d -p 6379:6379 redis:7-alpine
JWT decode error Verifique JWT_SECRET_KEY e JWT_ALGORITHM no .env
API iFriend timeout Verifique API_BASE_URL e credenciais
Session not found Se usando inmemory, é normal perder sessões ao reiniciar
Gemini quota exceeded Peça aumento de quota no GCP ou use outro projeto

Próximos passos como novo dev

  1. Rode o projeto local e envie uma mensagem de teste via WebChat
  2. Leia o system prompt (ifriend_agent/system_prompt_v2.py) — é o "cérebro" do agente
  3. Explore uma tool simples como busca_produtos para entender o padrão
  4. Leia o adapter da plataforma que você vai manter
  5. Rode os testes do módulo que vai trabalhar
  6. Consulte a documentação detalhada em docs/ para temas específicos

Anterior: ← Sessão, Memória e Auth · Índice: README →