Skip to content

Architecture

1. System Architecture Overview

graph TB
    subgraph "Frontend (React + TypeScript)"
        UI[User Interface]
        AC[Auth Context]
        CC[Chat Context]
        API[API Service Layer]
    end

    subgraph "Backend (FastAPI + Python)"
        FE[FastAPI Endpoints]
        BL[Business Logic Services]
        MS[Memory Service]
        ADK[Google ADK Agents]
    end

    subgraph "Databases"
        PG[(PostgreSQL<br/>Application Data)]
        NEO[(Neo4j<br/>Memory Graph)]
    end

    subgraph "External APIs"
        GEMINI[Google Gemini<br/>AI Models]
        OPENAI[OpenAI<br/>Memory Embeddings]
        YF[Yahoo Finance<br/>Market Data]
        FINN[Finnhub<br/>Social Sentiment]
        FMP[FMP<br/>Financial Data]
        NEWS[NewsAPI<br/>Financial News]
    end

    subgraph "Observability"
        OPIK[Opik<br/>Agent Tracking]
    end

    UI --> AC
    UI --> CC
    CC --> API
    API -->|HTTP/REST| FE
    FE --> BL
    BL --> ADK
    BL --> MS
    BL --> PG
    MS --> NEO

    ADK --> GEMINI
    MS --> OPENAI
    BL --> YF
    BL --> FINN
    BL --> FMP
    BL --> NEWS
    ADK --> OPIK

    style UI fill:#61dafb
    style CC fill:#61dafb
    style API fill:#61dafb
    style FE fill:#009485
    style BL fill:#009485
    style ADK fill:#ff6b6b
    style MS fill:#4ecdc4
    style PG fill:#336791
    style NEO fill:#008cc1

2. AI Agent Architecture (Google ADK)

graph TD
    subgraph "Google ADK Framework"
        MANAGER[Quantbot Manager<br/>Orchestrator Agent]

        subgraph "Specialized Agents"
            PA[Portfolio Advisor<br/>Investment Analysis]
            MA[Market Analyst<br/>Real-time Data]
            NA[News Analyst<br/>Sentiment Analysis]
            RA[Risk Assessor<br/>Risk Management]
            GA[General Assistant<br/>Fallback Agent]
        end

        subgraph "Tool Categories"
            MT[Market Tools<br/>Stock data, prices]
            PT[Portfolio Tools<br/>Holdings, performance]
            NT[News Tools<br/>Search, sentiment]
            RT[Risk Tools<br/>VaR, calculations]
            FT[Finnhub Tools<br/>Social sentiment]
            FMPT[FMP Tools<br/>Financial data]
        end
    end

    subgraph "Configuration"
        CONFIG[config.yaml<br/>Agent blueprints]
        PROMPTS[Prompt Library<br/>Specialized prompts]
        MEMORY_CB[Memory Callbacks<br/>Auto-save conversations]
    end

    MANAGER --> PA
    MANAGER --> MA
    MANAGER --> NA
    MANAGER --> RA
    MANAGER --> GA

    PA --> PT
    PA --> MT
    MA --> MT
    MA --> FT
    MA --> FMPT
    NA --> NT
    RA --> RT
    GA --> MT

    CONFIG --> MANAGER
    PROMPTS --> MANAGER
    MEMORY_CB --> MANAGER

    style MANAGER fill:#ff6b6b
    style PA fill:#4ecdc4
    style MA fill:#45b7d1
    style NA fill:#96ceb4
    style RA fill:#feca57
    style GA fill:#ff9ff3

3. Memory System Architecture (Neo4j + Graphiti)

graph TB
    subgraph "Memory Management"
        MM[Memory Manager<br/>graphiti-core]
        EP[Episode Storage<br/>Conversations]
        ES[Entity Storage<br/>Extracted entities]
        ED[Edge Storage<br/>Relationships]
    end

    subgraph "Neo4j Graph Database"
        NODES[(Nodes<br/>Users, Episodes, Entities)]
        EDGES[(Edges<br/>Relationships, Connections)]
        EMBED[(Embeddings<br/>Vector similarities)]
    end

    subgraph "Memory Operations"
        STORE[Store Episode<br/>Save conversation]
        SEARCH[Search Memory<br/>Semantic similarity]
        EXTRACT[Extract Entities<br/>Auto-extraction]
        RELATE[Build Relations<br/>Connect concepts]
    end

    subgraph "User Isolation"
        GROUP[Group IDs<br/>User segregation]
        PERM[Permissions<br/>Data access control]
    end

    MM --> EP
    MM --> ES
    MM --> ED

    EP --> NODES
    ES --> NODES
    ED --> EDGES

    STORE --> MM
    SEARCH --> MM
    EXTRACT --> MM
    RELATE --> MM

    GROUP --> NODES
    PERM --> EDGES

    MM -.-> OPENAI[OpenAI Embeddings<br/>Semantic search]

    style MM fill:#4ecdc4
    style NODES fill:#008cc1
    style EDGES fill:#008cc1
    style EMBED fill:#008cc1
    style GROUP fill:#feca57

4. Database Architecture

graph TB
    subgraph "PostgreSQL - Application Data"
        USERS[users<br/>Authentication]
        PORTFOLIO[portfolios<br/>Investment containers]
        HOLDINGS[holdings<br/>Stock positions]
        APIKEYS[user_api_keys<br/>Encrypted keys]
        PREFS[user_preferences<br/>Settings]
        TOKENS[refresh_tokens<br/>JWT management]

        subgraph "ADK Integration"
            SESSIONS[adk_chat_sessions<br/>Session management]
            MESSAGES[adk_messages<br/>Conversation history]
        end
    end

    subgraph "Neo4j - Memory Graph"
        EPISODES[Episode Nodes<br/>Conversation units]
        ENTITIES[Entity Nodes<br/>Extracted concepts]
        RELATIONS[Relationship Edges<br/>Connections]
        GROUPS[Group Nodes<br/>User isolation]
    end

    USERS --> PORTFOLIO
    PORTFOLIO --> HOLDINGS
    USERS --> APIKEYS
    USERS --> PREFS
    USERS --> TOKENS
    USERS --> SESSIONS
    SESSIONS --> MESSAGES

    GROUPS --> EPISODES
    EPISODES --> ENTITIES
    ENTITIES --> RELATIONS

    style USERS fill:#336791
    style PORTFOLIO fill:#336791
    style EPISODES fill:#008cc1
    style ENTITIES fill:#008cc1
    style GROUPS fill:#feca57

5. API Request Flow - AI Chat

sequenceDiagram
    participant U as User
    participant F as Frontend
    participant A as Auth Context
    participant B as Backend API
    participant ADK as Google ADK
    participant M as Memory Manager
    participant G as Gemini AI
    participant N as Neo4j

    U->>F: Types message
    F->>A: Check authentication
    A->>F: Return JWT token
    F->>B: POST /api/v1/chat/ (with auth)
    B->>ADK: Create agent instance
    ADK->>M: Search relevant memories
    M->>N: Query graph database
    N-->>M: Return related conversations
    M-->>ADK: Context from memory
    ADK->>G: Send prompt with context
    G-->>ADK: AI response with tool calls
    ADK->>ADK: Execute tools (market data, etc.)
    ADK->>M: Store conversation episode
    M->>N: Save to graph
    ADK-->>B: Complete response
    B-->>F: JSON response
    F->>U: Display AI message

6. Frontend Component Architecture

graph TD
    subgraph "App Shell"
        APP[App.tsx<br/>Main Router]
        AUTH[AuthContext<br/>Global auth state]
        PRIVATE[PrivateRoute<br/>Auth protection]
    end

    subgraph "Core Pages"
        LOGIN[LoginPage<br/>Authentication]
        CHAT[ChatPage<br/>AI conversation]
        PORTFOLIO[PortfolioPage<br/>Investment tracking]
        SETTINGS[SettingsPage<br/>Configuration]
        PREFS[PreferencesPage<br/>User setup]
    end

    subgraph "Chat Components"
        CONTAINER[ChatContainer<br/>Message display]
        INPUT[MessageInput<br/>User input]
        MESSAGE[Message<br/>Individual messages]
        TOOLS[ToolResults<br/>Data visualization]
    end

    subgraph "Portfolio Components"
        SUMMARY[PortfolioSummary<br/>Overview]
        STOCKS[StockList<br/>Holdings display]
        FORMS[AddStockForm<br/>Position management]
    end

    subgraph "Shared Components"
        HEADER[Header<br/>Navigation]
        SIDEBAR[Sidebar<br/>Menu]
        CARDS[DataCards<br/>Stock/News display]
        LOADING[LoadingStates<br/>UI feedback]
    end

    APP --> AUTH
    AUTH --> PRIVATE
    PRIVATE --> LOGIN
    PRIVATE --> CHAT
    PRIVATE --> PORTFOLIO
    PRIVATE --> SETTINGS
    PRIVATE --> PREFS

    CHAT --> CONTAINER
    CHAT --> INPUT
    CONTAINER --> MESSAGE
    MESSAGE --> TOOLS

    PORTFOLIO --> SUMMARY
    PORTFOLIO --> STOCKS
    PORTFOLIO --> FORMS

    style APP fill:#282c34
    style AUTH fill:#61dafb
    style CHAT fill:#4ade80
    style PORTFOLIO fill:#4ade80

7. Service Layer Architecture

graph TB
    subgraph "API Endpoints"
        CHAT_EP[/api/v1/chat/]
        MARKET_EP[/api/v1/market/]
        PORTFOLIO_EP[/api/v1/portfolio/]
        NEWS_EP[/api/v1/news/]
        AUTH_EP[/api/v1/auth/]
        MEMORY_EP[/api/v1/memory/]
        SYSTEM_EP[/api/v1/system/]
    end

    subgraph "Service Layer"
        CHAT_SVC[ChatService<br/>ADK integration]
        MARKET_SVC[MarketService<br/>External APIs]
        PORTFOLIO_SVC[PortfolioService<br/>Investment logic]
        NEWS_SVC[NewsService<br/>News aggregation]
        AUTH_SVC[AuthService<br/>JWT management]
        MEMORY_SVC[MemoryService<br/>Graph operations]
        API_KEY_SVC[APIKeyService<br/>Key management]
    end

    subgraph "External Integrations"
        YF_INT[Yahoo Finance<br/>Market data]
        FINN_INT[Finnhub Integration<br/>Social sentiment]
        FMP_INT[FMP Integration<br/>Financial data]
        NEWS_INT[NewsAPI Integration<br/>Financial news]
        OPIK_INT[Opik Integration<br/>Observability]
    end

    CHAT_EP --> CHAT_SVC
    MARKET_EP --> MARKET_SVC
    PORTFOLIO_EP --> PORTFOLIO_SVC
    NEWS_EP --> NEWS_SVC
    AUTH_EP --> AUTH_SVC
    MEMORY_EP --> MEMORY_SVC
    SYSTEM_EP --> API_KEY_SVC

    MARKET_SVC --> YF_INT
    MARKET_SVC --> FINN_INT
    MARKET_SVC --> FMP_INT
    NEWS_SVC --> NEWS_INT
    CHAT_SVC --> OPIK_INT

    style CHAT_SVC fill:#ff6b6b
    style MEMORY_SVC fill:#4ecdc4
    style MARKET_SVC fill:#45b7d1
    style NEWS_SVC fill:#96ceb4

8. Data Flow - Complete User Journey

graph LR
    subgraph "User Journey"
        LOGIN2[Login/Register]
        SETUP[Preference Setup]
        CHAT2[AI Chat]
        PORTFOLIO2[Portfolio Management]
        API_KEYS[API Configuration]
    end

    subgraph "Data Processing"
        AUTH2[Authentication]
        MEMORY2[Memory Storage]
        TOOLS2[Tool Execution]
        ANALYSIS[Data Analysis]
    end

    subgraph "External Data"
        MARKET2[Market Data]
        NEWS2[News Data]
        AI2[AI Responses]
    end

    LOGIN2 --> AUTH2
    SETUP --> MEMORY2
    CHAT2 --> TOOLS2
    CHAT2 --> MEMORY2
    PORTFOLIO2 --> ANALYSIS
    API_KEYS --> TOOLS2

    TOOLS2 --> MARKET2
    TOOLS2 --> NEWS2
    TOOLS2 --> AI2

    style LOGIN2 fill:#fbbf24
    style CHAT2 fill:#4ade80
    style PORTFOLIO2 fill:#818cf8
    style MEMORY2 fill:#4ecdc4

9. Security & Performance Architecture

graph TD
    subgraph "Security Layer"
        JWT[JWT Authentication<br/>Access & Refresh tokens]
        ENCRYPT[API Key Encryption<br/>Symmetric encryption]
        ISOLATION[User Data Isolation<br/>Group-based separation]
        CORS[CORS Configuration<br/>Origin restrictions]
        VALIDATE[Input Validation<br/>Pydantic schemas]
    end

    subgraph "Performance Layer"
        CACHE[Data Caching<br/>60s market data TTL]
        RATE[Rate Limiting<br/>API call throttling]
        LAZY[Lazy Loading<br/>Component optimization]
        BATCH[Batch Operations<br/>Multiple stock queries]
        ASYNC[Async Processing<br/>Non-blocking operations]
    end

    subgraph "Monitoring"
        HEALTH[Health Checks<br/>Service monitoring]
        LOGS[Structured Logging<br/>Request tracking]
        METRICS[Performance Metrics<br/>Response times]
        OPIK_MON[Opik Monitoring<br/>Agent behavior]
    end

    JWT --> ENCRYPT
    ENCRYPT --> ISOLATION
    ISOLATION --> CORS
    CORS --> VALIDATE

    CACHE --> RATE
    RATE --> LAZY
    LAZY --> BATCH
    BATCH --> ASYNC

    HEALTH --> LOGS
    LOGS --> METRICS
    METRICS --> OPIK_MON

    style JWT fill:#feca57
    style CACHE fill:#4ecdc4
    style HEALTH fill:#96ceb4

Key Technologies & Versions

Frontend Stack

  • React 18: Modern UI library with concurrent features
  • TypeScript 5+: Type safety and developer experience
  • Vite 5: Fast build tool and dev server
  • Tailwind CSS 3: Utility-first styling framework
  • Axios 1.10: HTTP client with interceptors
  • React Router 6: Client-side routing

Backend Stack

  • FastAPI 0.115+: Modern Python web framework
  • SQLModel 0.0.22: Database ORM (SQLAlchemy + Pydantic)
  • Google ADK 1.2+: Agent development framework
  • Graphiti-core 0.15+: Memory management system
  • Opik 1.7: AI agent observability
  • UV: Fast Python package manager

Infrastructure

  • PostgreSQL 16: Primary application database
  • Neo4j 2025.06: Graph database for memory
  • pgvector: Vector similarity extension
  • Docker Compose: Development environment
  • Alembic: Database migration management

External APIs

  • Google Gemini 2.5: AI model (Flash & Pro variants)
  • OpenAI Embeddings: Memory semantic search
  • Yahoo Finance: Real-time market data via yfinance
  • Finnhub: Social sentiment and alternative data
  • Financial Modeling Prep (FMP): Enhanced financial data and analytics
  • NewsAPI: Financial news aggregation

Environment Configuration

Development Ports

  • Frontend: http://localhost:5173 (Vite dev server)
  • Backend: http://localhost:8000 (FastAPI server)
  • API Docs: http://localhost:8000/docs (Swagger UI)
  • PostgreSQL: localhost:5432 (Database)
  • Neo4j Browser: http://localhost:7474 (Graph UI)

Production Considerations

  • Load Balancing: Multi-instance backend deployment
  • Database Scaling: Read replicas and connection pooling
  • Memory Optimization: Neo4j clustering for large datasets
  • API Rate Limiting: User-based and endpoint-specific limits
  • Monitoring: Comprehensive observability with Opik and custom metrics

Data Flow Summary

  1. Authentication: User logs in, receives JWT tokens
  2. Memory Context: System loads relevant conversation history from Neo4j
  3. Agent Orchestration: Google ADK manager routes queries to specialized agents
  4. Tool Execution: Agents call market data, news, and portfolio tools
  5. AI Processing: Gemini models generate contextual responses
  6. Memory Storage: Conversations and entities stored in graph database
  7. Response Delivery: Structured responses with tool results sent to frontend
  8. UI Updates: React components render AI responses and data visualizations
  9. Persistence: All data persisted across user sessions with proper isolation

This architecture enables Quantbot to provide intelligent, context-aware financial assistance while maintaining high performance, security, and scalability.