Engineer 2 Setup Guide¶
Quick start guide for setting up the backend orchestrator with mem0 integration.
Prerequisites¶
- Python 3.11+
- PostgreSQL 14+
- Redis 6+
- mem0 account (API key already configured)
Quick Start¶
1. Environment Setup¶
# Copy environment template (already done - .env created with mem0 key)
# Add your Anthropic and OpenAI API keys to .env
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
2. Install mem0¶
3. Test mem0 Connection¶
Create test_mem0.py:
import os
from mem0 import Memory
from dotenv import load_dotenv
load_dotenv()
# Initialize mem0 client
memory = Memory(api_key=os.getenv("MEM0_API_KEY"))
# Test: Add a memory
result = memory.add(
"User is a college student studying Computer Science",
user_id="test_user_sage",
metadata={"type": "factual", "source": "test"}
)
print(f"✅ Memory added: {result}")
# Test: Search memories
results = memory.search(
"What does the user study?",
user_id="test_user_sage",
limit=5
)
print(f"✅ Search results: {results}")
# Test: Get all memories
all_memories = memory.get_all(user_id="test_user_sage")
print(f"✅ All memories: {all_memories}")
print("\n🎉 mem0 connection successful!")
Run the test:
4. Database Setup¶
# Start PostgreSQL and Redis (using Docker Compose)
docker-compose up -d postgres redis
# Run migrations
alembic upgrade head
5. Run the Orchestrator¶
# Development mode
uvicorn app.main:app --reload --port 8000
# Test the health endpoint
curl http://localhost:8000/orchestrator/heartbeat
mem0 Configuration¶
API Key Location¶
- Stored in
.envfile (already configured) - Key:
MEM0_API_KEY=m0_...(example) - NEVER commit
.envto git (it's in.gitignore)
Namespace Strategy¶
Direct Mode (1:1 conversations):
Group Mode (group chats):
Basic Operations¶
from mem0 import Memory
memory = Memory(api_key=os.getenv("MEM0_API_KEY"))
# Add memory
memory.add(
"User is stressed about Thursday's 5 back-to-back meetings",
user_id="usr_123_sage",
metadata={
"type": "emotional",
"source": "direct_message",
"timestamp": "2025-11-03T14:30:00",
"sensitivity": "normal"
}
)
# Search relevant memories
results = memory.search(
query="What's stressing the user?",
user_id="usr_123_sage",
limit=5
)
# Delete memory (for "forget that" command)
memory.delete(memory_id="mem_abc123")
# Get all memories (for debugging/export)
all_memories = memory.get_all(user_id="usr_123_sage")
Project Structure¶
archety/
├── app/
│ ├── main.py # FastAPI app
│ ├── orchestrator/
│ │ ├── message_router.py # Route direct vs group
│ │ ├── direct_handler.py # Handle 1:1 conversations
│ │ ├── group_handler.py # Handle group chats
│ ├── persona/
│ │ ├── engine.py # Persona logic
│ │ ├── styler.py # Natural language generation
│ │ ├── passports/ # Persona config JSONs
│ │ ├── sage.json
│ │ ├── echo.json
│ ├── memory/
│ │ ├── mem0_service.py # mem0 integration layer
│ │ ├── relationship.py # Trust/rapport tracking
│ ├── superpowers/
│ │ ├── agent_base.py # Base agent class
│ │ ├── calendar_stress.py # CalendarStressAgent
│ │ ├── gmail_mindreader.py # GmailMindReaderAgent
│ │ ├── deadline_stabilizer.py
│ ├── oauth/
│ │ ├── google.py # Google OAuth flow
│ │ ├── token_manager.py # Token encryption/refresh
│ ├── models/
│ │ ├── database.py # SQLAlchemy models
│ │ ├── schemas.py # Pydantic schemas
│ ├── utils/
│ │ ├── intent_classifier.py
│ │ ├── llm_client.py # Claude/GPT wrapper
├── alembic/ # Database migrations
├── tests/
│ ├── test_mem0_integration.py
│ ├── test_group_privacy.py # CRITICAL: test no leaks
│ ├── test_persona.py
├── .env # Environment variables (not in git)
├── .env.example # Template
├── .gitignore
├── requirements.txt
├── docker-compose.yml
├── ENGINEER_2_MVP_PLAN.md # Full implementation plan
└── SETUP.md # This file
Key Implementation Notes¶
1. Memory Privacy (CRITICAL)¶
NEVER query 1:1 direct mode memories in group mode:
# ✅ CORRECT
def search_memories(user_id, persona_id, is_group, chat_guid, query):
if is_group:
namespace = f"group_{chat_guid}" # ONLY group namespace
else:
namespace = f"{user_id}_{persona_id}" # ONLY direct namespace
return memory.search(query, user_id=namespace, limit=5)
# ❌ WRONG - DO NOT DO THIS
def search_memories_wrong(user_id, persona_id, query):
# This queries direct namespace even in group mode
return memory.search(query, user_id=f"{user_id}_{persona_id}", limit=5)
2. Relationship State (Our Logic, Not mem0)¶
Store trust/rapport/stage in PostgreSQL, not mem0:
# After each conversation, update:
relationship_state = db.query(RelationshipState).filter_by(user_id=user_id).first()
relationship_state.trust_score += calculate_trust_delta(message)
relationship_state.rapport_score += calculate_rapport_delta(message)
relationship_state.stage = determine_stage(relationship_state.trust_score, relationship_state.rapport_score)
db.commit()
3. Consent Messaging¶
Use product-provided copy templates (stored in config):
CONSENT_TEMPLATES = {
"calendar_first_offer": "I can peek at your calendar and tell you where you're gonna burn out 🔥 — tap to let me look: {auth_link}",
"calendar_post_auth": "Got it. I can see your Thursday now and it's illegal. Wanna hear the damage report?",
# ... more templates
}
Testing Checklist¶
Before considering MVP complete:
- mem0 connection works
- Direct mode memories stored and recalled correctly
- Group mode uses separate namespace
- CRITICAL: No 1:1 memory leaks into group chats (integration test)
- OAuth flow works (Google Calendar + Gmail)
- Superpowers trigger correctly on intent
- Persona consistency across multiple messages
- Relationship stage progresses naturally
- "Forget that" command deletes memories
- Scheduled messages fire at correct time
- Response time p95 < 6s
Troubleshooting¶
mem0 API Errors¶
# Check API key is loaded
import os
print(os.getenv("MEM0_API_KEY")) # Should print key
# Test connection
from mem0 import Memory
memory = Memory(api_key=os.getenv("MEM0_API_KEY"))
Memory Not Recalling¶
- Check namespace is correct (
{user_id}_{persona_id}) - Verify memories were added successfully
- Increase search limit (try
limit=10) - Check mem0 dashboard for stored memories
Group Privacy Leaks¶
- Run integration test:
pytest tests/test_group_privacy.py -v - Verify
is_groupflag is correctly set - Ensure code never queries direct namespace when
is_group=True
Next Steps¶
- ✅ mem0 API key configured
- Set up PostgreSQL and Redis
- Install Python dependencies
- Test mem0 connection
- Start implementing Phase 1 (Orchestrator foundation)
- Follow
ENGINEER_2_MVP_PLAN.mdfor full implementation details
Support¶
- mem0 docs: https://docs.mem0.ai
- FastAPI docs: https://fastapi.tiangolo.com
- PRD: See
prd.mdin project root - Full plan: See
ENGINEER_2_MVP_PLAN.md
🚀 Ready to build!