# omerbakis/smsai architecture

> Architecture diagram of the GitHub repository omerbakis/smsai, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-04). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/omerbakis/smsai
- Repository: https://github.com/omerbakis/smsai

## Overview

##### Proje tipi ve amacı (README + file tree’dan çıkarım)
Bu proje bir **Python tabanlı tek-servis (monolith) web uygulaması prototipi**. Amaç: SMS akışı yerine hızlı MVP olarak **web chat UI** üzerinden gelen mesajları alıp:
##### Kullanım kayıtlarını tutup `GET /api/usage` ile raporlamak.

Kalıcı DB / gerçek LLM provider / auth / rate-limit yok; bunlar “external/placeholder” olarak diyagrama dahil edilmeli (gelecek ekler).

##### Dosya yapısı → mimari bileşenleri çıkarma
File tree ana sinyaller:

- `app/main.py` → Uygulama entrypoint’i; HTTP server’ı ayağa kaldırır (muhtemelen FastAPI/Flask tarzı).
- `app/router.py` → Multi-model yönlendirme mantığı (fast/multilingual/quality).
- `app/classifier.py` → Dil/intent/complexity sınıflandırma.
- `app/budget.py` → Token limitleri + tahmini maliyet + global/user budget kontrolü.
- `app/storage.py` → Kullanım kayıtları / state saklama (prototipte in-memory veya dosya bazlı olabilir).
- `app/__init__.py` → paket başlangıcı.
- `static/index.html` → Tek sayfa chat UI (frontend).
- `tests/test_api.py`, `tests/test_classifier.py` → API ve sınıflandırma için testler.
- `.env.example` → Konfigürasyon/env var (model isimleri, limitler, vs.).

Buna göre sistem; “UI + API + domain services” şeklinde, tek process içinde modüllere ayrılmış.

##### Diyagramı doğru çizmek için: 3 katmanlı yaklaşım önerisi
Principal-level doğruluk için tek diyagram yerine **3 görünüm** üretin. Aynı bileşen isimlerini tutarlı kullanın.

##### Context (C4 Level 1) – Sistem sınırları
**Amaç:** “Bu sistem kimlerle konuşuyor?”
Bileşenler:
- **User (Web Chat Kullanıcısı)**
- **Web Browser (UI)**
- **SMSAI Prototype Web Service (Python App)**
- **(Future) LLM Providers** (OpenAI/Anthropic vb. placeholder)
- **(Future) Persistent Storage / DB** (placeholder)

Oklar:
- User → Browser → `GET /` (static UI)
- Browser → Service: `POST /api/chat`, `GET /api/usage`
- Service → (Future) LLM Providers: model inference çağrısı
- Service → (Future) DB: usage/budget persistence

Bu seviyede “prototipte hepsi aynı process içinde” notunu ekleyin.

##### Container (C4 Level 2) – Deploy edilebilir parçalar
**Amaç:** “Çalışan parçalar neler?”
Bu projede container sayısı az:

##### Python Web App (single process)
- Serves static: `static/index.html`
- Serves API: `/api/chat`, `/api/usage`

##### Browser UI (static HTML/JS)
- Chat UI; API’ye istek atar.

(Opsiyonel ama faydalı)
##### Config (.env)
- “Runtime config” kutusu; budget limitleri, model seçimi vb.

Oklar:
- Browser UI → Python Web App (HTTP)
- Python Web App → (Future) LLM providers (HTTP)
- Python Web App → (Currently) In-memory storage (`app/storage.py`)

##### Component (C4 Level 3) – `app/` içi bileşen diyagramı (asıl kritik kısım)
**Amaç:** Kod yapısını en doğru temsil eden diyagram.
`app/` altındaki modülleri “components” olarak çizip, request flow’u oklarla gösterin.

Önerilen component kutuları ve sorumlulukları:

##### API Layer / HTTP Handlers
- Kaynak: `app/main.py` (ve varsa routing setupları), `app/router.py` (adı router ama burada “model router”; HTTP router ayrı olabilir)
- Endpointler:
- `POST /api/chat`
- `GET /api/usage`
- `GET /` static
- Görev: request parse, response format.

##### Classifier Service
- Kaynak: `app/classifier.py`
- Çıktılar:
- language
- intent/domain
- complexity (low/medium/high)

##### Budget / Token Manager
- Kaynak: `app/budget.py`
- Fonksiyonlar:
- user bazlı limit kontrolü
- global limit kontrolü
- request cost estimate
- usage update tetikleme

##### Model Router (Multi-model routing)
- Kaynak: `app/router.py`
- Input: classification sonuçları + budget/quality politikası
- Output: seçilen model (`fast-model-v1`, `multilingual-model-v1`, `quality-model-v2`)

##### LLM Client / Model Executor (prototip stub olabilir)
- Kodda direkt yoksa bile diyagramda “Model Invocation” olarak gösterin.
- Router’ın seçtiği model ile inference yapar.
- Not: “Production’da external provider entegrasyonu”.

##### Usage Storage / Usage Repository
- Kaynak: `app/storage.py`
- Görev: usage events kayıt, `GET /api/usage` için aggregation.
- Prototip notu: in-memory olabilir → restart’ta silinir.

##### Static Web UI
- Kaynak: `static/index.html`
- HTTP üzerinden servis edilir, API’yi tüketir.

##### Request akışı (oklarla net gösterin)
**POST /api/chat** için:
##### API Handler → Browser UI: response (answer + metadata)

**GET /api/usage** için:
##### API Handler → Client: usage summary

Bu akış diyagramda “happy path” olarak çizilmeli; ayrıca iki hata kolu ekleyin:
- Budget exceeded → 429/403 benzeri
- Model invocation error → 5xx + usage handling kararı (kayıt yazılır mı?)

##### Diyagramda özellikle vurgulanacak mimari desenler
- **Pipeline/Orchestration**: Chat isteği sırasıyla budget → classify → route → infer → log.
- **Policy-based routing**: routing kararı classification ve complexity sinyallerine dayanır.
- **Cross-cutting concern**: budget/token tracking her request’i sarar (middleware gibi). Kodda middleware yoksa bile diyagramda “Budget/Token Manager”i akışın hem başında hem sonunda gösterin.
- **Prototype storage**: `storage.py` kalıcı değil; production target’ta DB’ye evrilecek.

##### Bileşenleri olabildiğince parçalayın (overthink etmeden)
Bu repo küçük; ama diyagramda şu ayrımları yapmanız kaliteyi artırır:
- “API Handler” vs “Domain services (classifier/router/budget)” vs “Storage”
- “Model Router” vs “Model Executor/Client” (ileride external provider olacağı için)
- “Usage write” ve “Usage read” akışlarını ayrı oklarla belirtin

##### Etiketleme (labels)
Her kutuda:
- Modül adı: `app/classifier.py`
- Rol: “Classification Agent”
- Input/Output anahtarları: “message → {lang,intent,complexity}”

Okların üzerinde:
- HTTP route (örn. `POST /api/chat`)
- Data (örn. “message”, “usage record”, “model selection”)

##### Renk/şekil kodlama (basit ama tutarlı)
- **Mavi**: UI / Client
- **Yeşil**: API / HTTP layer
- **Sarı**: Domain services (classifier/router/budget)
- **Mor**: Storage
- **Gri kesik çizgi**: Future externals (LLM provider, DB, Auth)

Şekiller:
- Dikdörtgen: component/service
- Silindir: storage (in-memory/DB)
- Bulut: external provider

##### Diyagrama mutlaka eklenmesi gereken “production gaps” (README notuna uygun)
Prototip olduğunu görünür kılmak için diyagramda “Future/Out of Scope” alanı açın:
- AuthN/AuthZ (kullanıcı kimliği → budget user-key)
- Rate limiting
- Persistent DB (usage/budget)
- Real LLM provider integrations
- Security controls (input validation, logging, secrets)

Bunları **kesik çizgili kutular** ile ekleyip, mevcut akışta nereye oturacağını oklarla gösterin (ör. Auth middleware API handler’ın önünde).

##### Component (app/)
- `/api/chat` handler
- `/api/usage` handler
- Classifier (`classifier.py`)
- Budget manager (`budget.py`)
- Model router (`router.py`)
- LLM client/executor (conceptual)
- Storage/repository (`storage.py`)
- Static UI (`static/index.html`)

Her birinde net oklar, net data-flow, ve prototip vs production ayrımı.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================================================
    %% C4-L1: System Context (vertical)
    %% =========================================================
    subgraph "C4-L1: System Context"
        direction TB

        User["User\n(Web chat user)"]:::external

        Browser["Web Browser\n(Renders UI + calls API)"]:::frontend

        Service["SMSAI Prototype Web Service\n(Python monolith)"]:::api

        FutureLLM["(Future) LLM Providers\n(OpenAI/Anthropic/etc.)"]:::future
        FutureDB["(Future) Persistent Storage / DB"]:::future
    end

    User -->|"uses"| Browser
    Browser -->|"GET / (static UI)"| Service
    Browser -->|"POST /api/chat"| Service
    Browser -->|"GET /api/usage"| Service
    Service -.->|"model_inference (HTTP)"| FutureLLM
    Service -.->|"persist_usage/budgets"| FutureDB

    NoteMono["Note:\nPrototype runs as a single-process monolith.\nNo real auth, rate-limit, persistent DB, or real LLM provider yet."]:::note
    Service --- NoteMono

    %% =========================================================
    %% C4-L2: Container View
    %% =========================================================
    subgraph "C4-L2: Containers (Deployable Parts)"
        direction TB

        subgraph "Client Side"
            direction TB
            UI["Browser UI\n(static HTML/JS chat)"]:::frontend
        end

        subgraph "Server Side"
            direction TB
            PyApp["Python Web App\n(single process: static + API)"]:::api
            InMemStore[("In-memory Usage Store\n(prototype state)")]:::storage
        end

        Config["Runtime Config\n(.env template)"]:::config
        ExtAuth["(Future) AuthN/AuthZ\n(user identity -> budget key)"]:::future
        ExtRate["(Future) Rate Limiting"]:::future
        ExtSec["(Future) Security Controls\n(validation/logging/secrets)"]:::future
    end

    UI -->|"HTTP"| PyApp
    PyApp -->|"write/read usage"| InMemStore
    Config -->|"env vars (limits/models)"| PyApp

    UI -.->|"auth context"| ExtAuth
    ExtAuth -.->|"protects endpoints"| PyApp
    ExtRate -.->|"throttles requests"| PyApp
    ExtSec -.->|"hardening"| PyApp

    %% =========================================================
    %% C4-L3: Component View (app/)
    %% =========================================================
    subgraph "C4-L3: Components (Inside Python Web App)"
        direction TB

        subgraph "HTTP / API Layer"
            direction TB
            StaticServe["Static Serving\n(GET /)"]:::api
            ChatHandler["Chat Endpoint Handler\n(POST /api/chat)"]:::api
            UsageHandler["Usage Endpoint Handler\n(GET /api/usage)"]:::api
        end

        subgraph "Domain Services"
            direction TB
            Budget["Budget / Token Manager\nestimate + check + commit\n(message -> cost, limits)"]:::domain
            Classifier["Classification Agent\nmessage -> {lang,intent,complexity}"]:::domain
            ModelRouter["Model Router\npolicy-based selection\nclassification + budget -> model"]:::domain
            LLMExec["LLM Client / Model Executor\n(model, message, context?) -> answer"]:::domain
        end

        subgraph "Data / Storage"
            direction TB
            UsageRepo[("Usage Storage / Repository\n(events + aggregation)\n(in-memory; reset on restart)")]:::storage
        end

        subgraph "Frontend Asset"
            direction TB
            StaticUI["Static Web Chat UI\n(single page)"]:::frontend
        end

        subgraph "Production Gaps (Future / Out of Scope)"
            direction TB
            AuthMW["Auth Middleware"]:::future
            RateMW["Rate Limiter"]:::future
            PersistDB[("(Future) Persistent DB")]:::future
            RealProviders["(Future) Real LLM Provider Integrations"]:::future
        end
    end

    %% ---- Static flow ----
    Browser -->|"GET /"| StaticServe
    StaticServe -->|"serves"| StaticUI

    %% ---- POST /api/chat happy path ----
    StaticUI -->|"POST /api/chat\nmessage"| ChatHandler
    AuthMW -.->|"pre-check"| ChatHandler
    RateMW -.->|"throttle"| ChatHandler

    ChatHandler -->|"canSpend?/estimateCost\n(user+global)"| Budget
    ChatHandler -->|"classify(message)"| Classifier
    Classifier -->|"signals {lang,intent,complexity}"| ModelRouter
    Budget -->|"constraints/quality_policy"| ModelRouter
    ModelRouter -->|"model_selection\n(fast/multilingual/quality)"| ChatHandler
    ChatHandler -->|"run(model,message,context?)"| LLMExec
    LLMExec -.->|"provider API"| RealProviders
    RealProviders -.->|"calls"| FutureLLM

    ChatHandler -->|"commitUsage\n(actual/estimated tokens)"| Budget
    Budget -->|"write usage record"| UsageRepo
    UsageRepo -.->|"future persistence"| PersistDB
    PersistDB -.->|"storage backend"| FutureDB

    ChatHandler -->|"200 response\nanswer + metadata"| StaticUI

    %% ---- Error branches ----
    Budget -->|"budget_exceeded"| BudgetExceeded["Budget Exceeded\n(429/403)"]:::error
    BudgetExceeded -->|"error response"| ChatHandler

    LLMExec -->|"invocation_error"| ModelError["Model Invocation Error\n(5xx)\n(usage policy TBD)"]:::error
    ModelError -->|"error response"| ChatHandler

    %% ---- GET /api/usage flow ----
    StaticUI -->|"GET /api/usage"| UsageHandler
    AuthMW -.->|"protect usage"| UsageHandler
    UsageHandler -->|"read/aggregate"| UsageRepo
    UsageRepo -->|"usage summary"| UsageHandler
    UsageHandler -->|"200 response\nusage report"| StaticUI

    %% ---- Wiring between C4 levels (conceptual alignment) ----
    Service --- PyApp
    PyApp --- ChatHandler
    PyApp --- UsageHandler
    PyApp --- StaticServe
    InMemStore --- UsageRepo
    UI --- StaticUI

    %% =========================================================
    %% Click events (from component_mapping) - paths only
    %% =========================================================
    click PyApp "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click ChatHandler "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click UsageHandler "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click StaticServe "https://github.com/omerbakis/smsai/blob/main/app/main.py"

    click Classifier "https://github.com/omerbakis/smsai/blob/main/app/classifier.py"
    click Budget "https://github.com/omerbakis/smsai/blob/main/app/budget.py"
    click ModelRouter "https://github.com/omerbakis/smsai/blob/main/app/router.py"
    click UsageRepo "https://github.com/omerbakis/smsai/blob/main/app/storage.py"

    click StaticUI "https://github.com/omerbakis/smsai/blob/main/static/index.html"
    click Config "https://github.com/omerbakis/smsai/blob/main/.env.example"

    click NoteMono "https://github.com/omerbakis/smsai/blob/main/.env.example"

    click BudgetExceeded "https://github.com/omerbakis/smsai/blob/main/app/budget.py"
    click ModelError "https://github.com/omerbakis/smsai/blob/main/app/router.py"

    click UI "https://github.com/omerbakis/smsai/blob/main/static/index.html"

    click Service "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click InMemStore "https://github.com/omerbakis/smsai/blob/main/app/storage.py"

    click Browser "https://github.com/omerbakis/smsai/blob/main/static/index.html"

    click AuthMW "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click RateMW "https://github.com/omerbakis/smsai/blob/main/app/main.py"

    click FutureLLM "https://github.com/omerbakis/smsai/blob/main/app/router.py"
    click FutureDB "https://github.com/omerbakis/smsai/blob/main/app/storage.py"
    click PersistDB "https://github.com/omerbakis/smsai/blob/main/app/storage.py"
    click RealProviders "https://github.com/omerbakis/smsai/blob/main/app/router.py"

    click ExtAuth "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click ExtRate "https://github.com/omerbakis/smsai/blob/main/app/main.py"
    click ExtSec "https://github.com/omerbakis/smsai/blob/main/app/main.py"

    click UsageHandler "https://github.com/omerbakis/smsai/blob/main/tests/test_api.py"
    click ChatHandler "https://github.com/omerbakis/smsai/blob/main/tests/test_api.py"
    click Classifier "https://github.com/omerbakis/smsai/blob/main/tests/test_classifier.py"

    %% =========================================================
    %% Styles (colors + shapes via class)
    %% =========================================================
    classDef frontend fill:#1e88e5,stroke:#0d47a1,color:#ffffff,stroke-width:1.5px
    classDef api fill:#43a047,stroke:#1b5e20,color:#ffffff,stroke-width:1.5px
    classDef domain fill:#f9a825,stroke:#f57f17,color:#1b1b1b,stroke-width:1.5px
    classDef storage fill:#8e24aa,stroke:#4a148c,color:#ffffff,stroke-width:1.5px
    classDef future fill:#e0e0e0,stroke:#616161,color:#212121,stroke-width:1.5px,stroke-dasharray: 6 4
    classDef external fill:#90a4ae,stroke:#37474f,color:#111111,stroke-width:1.5px
    classDef note fill:#fff8e1,stroke:#ffb300,color:#212121,stroke-width:1.2px
    classDef error fill:#e53935,stroke:#b71c1c,color:#ffffff,stroke-width:1.5px
```
