Budgit Backend - Technical Architecture
1. Backend Architecture (Structure & Tools) ✅
The backend acts as the coordination layer - it orchestrates intelligence, doesn't make decisions itself.
Responsibility
Implementation
File
Maintain user state and history
UserService + PostgreSQL
app/services/user_service.py
Route requests to AI agents
AgentOrchestrator
app/agents/orchestrator.py
Store decisions and outcomes
DecisionService + PostgreSQL
app/services/decision_service.py
Manage goal context and behavior patterns
UserService + LearningAgent
app/services/user_service.py, app/agents/learning_agent.py
Feed analytics and observability
ObservabilityService + AnalyticsService
app/services/observability_service.py
Backend Tools:
✅ Python/FastAPI - Modern async Python framework
✅ Google Gemini - AI inference (FREE tier: 60 req/min)
✅ PostgreSQL (Supabase compatible) - Persistent data storage
✅ Redis - Short-term memory and risk-state caching
2. Data Layer (Conceptual Models) ✅
Data layer designed around decisions, not transactions .
Stored Concept
Model
File
User profiles & preferences
User, UserProfile
app/models/db_models.py, app/models/schemas.py
Purchase considerations
PurchaseContext
app/models/schemas.py
Decision outcomes (buy/wait/decline)
Decision, DecisionOutcome
app/models/db_models.py, app/models/schemas.py
Behavioral patterns & triggers
UserPattern
app/models/db_models.py
Financial goals and progress
Goal, FinancialGoal
app/models/db_models.py, app/models/schemas.py
3. AI Agent System (Multi-Agent Structure) ✅
Multiple specialized agents, each responsible for one cognitive task .
Agent
Responsibility
File
Context Agent
Understands purchase situation, assesses risk based on time, price, category, history
app/agents/context_agent.py
Question Agent
Generates reflective, non-judgmental questions, adapts style to user
app/agents/question_agent.py
Opportunity Cost Agent
Translates cost into meaningful trade-offs, connects spending to active goals
app/agents/opportunity_cost_agent.py
Decision Coach Agent
Summarizes reasoning, hands control back to user
app/agents/decision_coach_agent.py
Learning Agent
Analyzes outcomes, updates behavior patterns, improves future interventions
app/agents/learning_agent.py
Orchestrator: app/agents/orchestrator.py - Coordinates all agents in the intervention flow.
4. Observability & Opik Setup ✅
What Is Tracked
Implementation
Conversation completion rates
observability.stats["completed_interventions"]
Decision outcomes (buy vs wait vs decline)
observability.record_decision()
Money saved per user
observability.stats["total_money_saved"]
Effectiveness of different question strategies
observability.stats["question_effectiveness"]
AI response latency and quality
Agent traces with duration_ms, tokens_used
Tools:
✅ Opik (Comet) - AI interaction observability and evaluation (app/services/observability_service.py)
✅ Built-in Analytics - User behavior insights (app/services/analytics_service.py)
✅ Error Tracking - observability.record_error() (Sentry-ready)
📁 Complete Folder Structure
budgit-backend/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI application entry
│ │
│ ├── api/
│ │ └── routes/
│ │ ├── purchase.py # Main intervention endpoints
│ │ ├── users.py # User management
│ │ ├── decisions.py # Decision history
│ │ ├── analytics.py # Dashboard data
│ │ └── observability.py # Metrics & monitoring
│ │
│ ├── agents/ # Multi-Agent AI System
│ │ ├── base_agent.py # Base class with Claude API
│ │ ├── context_agent.py # Risk assessment
│ │ ├── question_agent.py # Reflective questions
│ │ ├── opportunity_cost_agent.py # Trade-off analysis
│ │ ├── decision_coach_agent.py # Summary & handoff
│ │ ├── learning_agent.py # Pattern learning
│ │ └── orchestrator.py # Agent coordination
│ │
│ ├── core/
│ │ └── config.py # Settings & environment
│ │
│ ├── db/
│ │ └── database.py # PostgreSQL/SQLAlchemy setup
│ │
│ ├── models/
│ │ ├── schemas.py # Pydantic request/response models
│ │ └── db_models.py # SQLAlchemy ORM models
│ │
│ └── services/
│ ├── user_service.py # User data management
│ ├── decision_service.py # Decision history
│ ├── analytics_service.py # Dashboard analytics
│ ├── cache_service.py # Redis caching
│ └── observability_service.py # Opik + metrics
│
├── tests/
│ └── test_intervention.py
│
├── requirements.txt
├── run.py # Quick start script
├── Dockerfile
├── docker-compose.yml # Full stack setup
└── .env.example
# 1. Set up environment
cp .env.example .env
# Edit .env and add your GEMINI_API_KEY (get it free at https://aistudio.google.com/apikey)
# 2. Install dependencies
pip install -r requirements.txt
# 3. Run the server
python run.py
# 4. Open API docs
open http://localhost:8000/docs
Method
Endpoint
Description
POST
/api/v1/purchase/intervene
Trigger purchase intervention
POST
/api/v1/purchase/decide
Record user decision
GET
/api/v1/purchase/session/{id}
Get session details
GET
/api/v1/purchase/risk-state/{user_id}
Get cached risk state
Method
Endpoint
Description
GET
/api/v1/users/{id}
Get user profile
POST
/api/v1/users/
Create user
PUT
/api/v1/users/{id}/goals
Update goals
Method
Endpoint
Description
GET
/api/v1/analytics/{user_id}
Get user analytics
GET
/api/v1/analytics/{user_id}/triggers
Get spending triggers
GET
/api/v1/analytics/{user_id}/savings
Get savings summary
Method
Endpoint
Description
GET
/api/v1/observability/stats
System-wide stats
GET
/api/v1/observability/agents
Agent performance
GET
/api/v1/observability/question-effectiveness
Question strategy metrics
POST
/api/v1/observability/feedback/{session_id}
Submit quality feedback
📊 Example Intervention Request
curl -X POST http://localhost:8000/api/v1/purchase/intervene \
-H " Content-Type: application/json" \
-d ' {
"purchase": {
"user_id": "user_123",
"item_name": "Sony WH-1000XM5 Headphones",
"item_price": 189.99,
"category": "tech",
"retailer": "Amazon",
"time_of_day": "night",
"day_of_week": "Sunday",
"is_sale": false
}
}'
User considers purchase
│
▼
┌───────────────────┐
│ Frontend sends │
│ PurchaseContext │
└────────┬──────────┘
│
▼
┌───────────────────────────────────────────────────────┐
│ ORCHESTRATOR │
│ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │
│ │ Context │ │ Question │ │ Opportunity │ │
│ │ Agent │──│ Agent │──│ Cost Agent │ │
│ └─────────────┘ └─────────────┘ └──────────────┘ │
│ │ │ │
│ └────────────────┬───────────────────┘ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Decision Coach │ │
│ │ Agent │ │
│ └─────────────────┘ │
└───────────────────────────┬───────────────────────────┘
│
▼
InterventionResponse
(questions, costs, summary)
│
▼
User makes decision
│
▼
┌─────────────────┐
│ Learning Agent │
│ updates patterns│
└─────────────────┘
│
▼
┌─────────────────┐
│ Observability │
│ logs everything│
└─────────────────┘
Add authentication - Integrate Clerk or JWT auth
Connect real database - Set up Supabase/PostgreSQL
Deploy - Use Docker Compose or deploy to AWS/Vercel
Frontend integration - Connect to Next.js frontend
Price intelligence - Add price comparison API integration