# Arhitektura

## Pregled Sistema

Moj AI je napredni AI pravni pomočnik, specializiran za slovensko gradbeno zakonodajo in prostorsko načrtovanje. Aplikacija deluje kot profesionalno orodje za navigacijo po kompleksni slovenski zakonodaji s področja gradbeništva, vključno z GZ (Gradbeni Zakon), ZUreP-3 (Zakon o urejanju prostora) in občinskimi prostorskimi načrti (OPN).

**Status**: Production Ready\
**Zadnja posodobitev**: Januar 2026\
**Arhitektura**: Multi-tenant, Cloud-Native

***

## Tehnološki Stack (Technology Stack)

### Frontend Layer

**Framework & Build Tools**

* React 19.2.3 s TypeScript za type-safe razvoj
* Vite 6.2.0 za hiter development in optimizirane production build-e
* Tailwind CSS za responsive in konsistenten UI design

**State Management**

* React Context API za centralizirano upravljanje stanja:
  * `AuthContext` - avtentikacija in uporabniški profil
  * `LanguageContext` - večjezičnost (slovenščina/angleščina)
  * `ThemeContext` - svetla/temna tema

**Deployment**

* Firebase Hosting z CDN distribucijo
* Avtomatično SSL/TLS šifriranje
* Cache-Control optimizacija za aplikacijske resurse

### Backend Layer

**Runtime Environment**

* Firebase Cloud Functions (Node.js 20)
* Generation 2 (V2) funkcije za izboljšano performance
* Timeouts: 300 sekund za kompleksne AI operacije
* Memory: 1GiB RAM za zahtevne procesne operacije

{% stepper %}
{% step %}

### Core Functions

Opis osnovnih Cloud Functions, ki poganjajo backend.

* `health()` - Health check endpoint
* `askGemini()` - Glavna AI orchestration funkcija
* `uploadFile()` - Upravljanje z dokumenti (Direct V2 handler)
* `deleteDocumentFromFileSearch()` - Brisanje dokumentov iz knjižnice
* `queryFileSearch()` - Direktne poizvedbe po dokumentih
* `handleStripeWebhook()` - Procesiranje plačil
  {% endstep %}

{% step %}

### Agent Orchestration Functions (Frontier Mode)

Funkcije za orkestracijo agentov v Frontier načinu.

* `queryRAGAgent()` - Specialist za dokumente (Smart Router + Long Context)
* `queryFrontierAgent()` - Unified Research Agent (RAG + Google Search)
* `orchestrateAgents()` - Glavni koordinator (router med RAG in Frontier)
  {% endstep %}
  {% endstepper %}

### AI Layer (Gemini)

**Modeli**

* Lightning Mode: `gemini-2.5-flash` s File Search
* Frontier Mode: `gemini-2.5-flash` z Agent Orchestration
* RAG Operations: Direct File API (Multimodal)

**Google Gemini API Integration**

* SDK: `@google/genai` v0.1.0+
* Streaming responses za real-time interakcijo
* Token-based citation system
* Multimodal capabilities (tekst + PDF)

### Database Layer

**Firestore (Native Mode)**

Struktura podatkovnih zbirk:

```
├── users/{uid}
│   ├── Uporabniški profil
│   ├── Naročniške informacije
│   ├── Statistika uporabe
│   └── conversations/{convId}
│       └── Zgodovina pogovorov
├── fileSearchStores/{storeId}
│   └── Metadata index za RAG sistem
├── documents/{docId}
│   └── Sledenje naloženim dokumentom
└── systemPrompts
    └── AI system prompts (admin)
```

**Značilnosti**

* Real-time sinhronizacija
* Offline podpora
* Avtomatsko indeksiranje
* Atomične transakcije
* Strong consistency model

### Storage Layer

**Cloud Storage**

Organizacija bucket-ov:

```
├── user-documents/
│   └── {userId}/
│       ├── Uporabniški PDF-ji
│       └── Naloženi dokumenti
└── admin-documents/
    ├── Zakonodaja (ZGO, ZUreP-3)
    └── OPN-ji
```

**Varnostne Značilnosti**

* Šifriranje at-rest
* Avtomatski backup
* Multi-region replikacija
* Verzioniranje dokumentov

### Payment Integration

**Stripe**

* Per-question billing model
* Podpora za slovensko DDV
* Webhook signature verification
* Avtomatično generiranje računov
* Zbiranje podatkov o podjetju

**Pricing**

* Lightning Mode: 0.5 vprašanja
* Frontier Mode: 1.0 vprašanje

***

## RAG Sistem - Hybrid Smart Router

### Arhitekturni Pristop: "Route-then-Read"

Moj AI uporablja napredni **Hybrid Smart Router** sistem namesto tradicionalnih vector store rešitev. Ta pristop združuje deterministično Firestore metadata knjižnico z Gemini-jevim obsežnim Long Context oknom za natančno branje celotnih dokumentov.

### Komponente RAG Sistema

#### 1. The Library (Storage Layer)

**Master Copy**: Dokumenti so shranjeni v Firebase Storage

* Lokacija: `gs://user-documents/...`
* Arhivska kopija vseh PDF datotek

**Metadata Index**: Firestore collection `fileSearchStores`\
Fungira kot "kataložni sistem" z naslednjimi atributi:

```typescript
{
  filename: "OPN_Ziri.pdf",
  keywords: ["Žiri", "Construction", "OPN"],
  city: "Žiri",
  type: "OPN" | "Law" | "User",
  uploadDate: Timestamp,
  fileSize: number
}
```

#### 2. Smart Router (Selection Layer)

Ko uporabnik postavi vprašanje, lahek Router Agent (`gemini-2.0-flash-exp`) analizira poizvedbo glede na Metadata Index.

{% stepper %}
{% step %}

### Proces Smart Router-a

* Input: "Kaj ustreza 58. členu v Žireh?"
* Scan: Router pregleda `documentLibrary`
* Select: Identificira `OPN_Ziri.pdf` kot najbolj relevanten vir
* Comparison: Pri primerjavi izbere več dokumentov (npr. "Primerjaj Žiri in Ljubljana" → `OPN_Ziri.pdf` + `OPN_Ljubljana.pdf`)
  {% endstep %}
  {% endstepper %}

#### 3. Automated Partitioning (Split Strategy)

Za dokumente, ki presegajo 1 milijon tokenov (približno 300 strani), sistem avtomatsko izvede particijo med nalaganjem.

Primer:

```
Original: Large_OPN.pdf (500 strani)

Volumes:
├── Large_OPN_Vol1.pdf (strani 1-250)
└── Large_OPN_Vol2.pdf (strani 251-500)

Routing: Smart Router izbere specifične volume glede na vsebino
poizvedbe (npr. "Pravila za cono X" → izbere Vol 2)
```

Prednosti:

* Omogoča uporabo ekonomičnega `gemini-2.5-flash` modela
* Optimizira stroške brez izgube natančnosti
* Ohranja celovitost kompleksnih tabel

#### 4. Deep Read (Generation Layer)

Ko so dokumenti (ali volume-i) izbrani (max 3):

{% stepper %}
{% step %}

### Check Cache

Preveri, ali obstaja aktiven `fileUri` v Gemini File API.
{% endstep %}

{% step %}

### JIT Upload

Če `fileUri` ne obstaja (ali je potekel >48h), stream iz Firebase Storage → Gemini File API.
{% endstep %}

{% step %}

### Generate

Posreduje **Full Volume URI-je** v `gemini-2.5-flash` kontekstno okno.
{% endstep %}

{% step %}

### Result

Model prebere vsako stran izbranega volume-a za odgovor.
{% endstep %}
{% endstepper %}

### Prednosti Hybrid RAG Sistema

* Cost Efficiency: Eliminira potrebo po dragih Pro modelih
* Table Accuracy: Native PDF branje ohranja kompleksne tabelne strukture
* Scale: Knjižnica lahko vsebuje 1000+ PDF-jev, naložimo samo relevantne
* Deterministic: Brez "black-box" vector store-ov, popoln nadzor nad izbiro dokumentov
* Fresh Data: JIT upload strategija zagotavlja aktualne dokumente

***

## Orchestration Modes - Dual-Mode Arhitektura

Moj AI ponuja dva inteligentno optimizirana načina delovanja:

### Lightning Mode ⚡

Namen: Hitri, dokumentno usmerjeni odgovori za pravne poizvedbe

Capabilities:

* Dostop do Admin File Search Store (zakonodaja, OPN-ji)
* Dostop do User File Search Store (uporabniški dokumenti)
* Brez internetnega iskanja (offline-capable)
* Optimizirano za: Preverjanje specifičnih predpisov, hitre pojasnitve

Tehnična Implementacija:

```typescript
const model = 'gemini-2.5-flash';
const tools = []; // Brez internetnega dostopa
const stores = ['admin-file-search-store', `user-${userId}-file-search-store`];
```

Performance: 5-15 sekund\
Cena: 0.5 vprašanja

System Prompt:\
Slovensko usmerjen AI pravni pomočnik s poudarkom na:

* Zakonodaja (ZGO, ZUreP-3)
* Občinski prostorski načrti (OPN)
* Source attribution: 📚 RAG + 🧠 General knowledge

### Frontier Mode 🔍

Namen: Celoviti, raziskovalno podprti odgovori, ki združujejo RAG, internet in splošno znanje

Capabilities:

* Dostop do Admin + User dokumentov (RAG)
* Google Search Tool za trenutne informacije
* Združuje več virov sočasno
* Optimizirano za: Tržne raziskave, gradbeni stroški, nepremičninski trendi

Agent Orchestration Architecture:

```
User Query
    ↓
1. prepareDocumentContext() - Smart Router skenira knjižnico, izbere PDF-je, JIT Upload v Gemini, ustvari Source Map
    ↓
2. queryFrontierAgent() - System Prompt (z Source Map), Tools: [Google Search], Context: [RAG File Parts]
    ↓
Response z 📚 RAG + 🌐 Internet Attribution
```

**Unified Frontier Components**

{% stepper %}
{% step %}

### prepareDocumentContext()

* Uporabi Smart Router za iskanje dokumentov v Admin/User knjižnici
* JIT Upload izbranih dokumentov v Gemini
* Vrne `parts` (file data) in `sources` (metadata)
  {% endstep %}

{% step %}

### queryFrontierAgent()

* Injicira RAG `parts` v kontekstno okno
* Omogoči `googleSearch` tool
* Injicira **Source Map** v system prompt:

  ```
  Source [1]: OPN_Ziri.pdf (Type: RAG)
  Source [2]: ZGO_Official.pdf (Type: RAG)
  ```
* Navodila: "Citiraj z uporabo \[ID] za RAG vire, standardno tool citation za Web"
* Vrne končni odgovor z veljavnim markdown formatiranjem
  {% endstep %}
  {% endstepper %}

Performance: 15-30 sekund\
Cena: 1.0 vprašanje

System Prompt:\
Slovensko usmerjen AI raziskovalni asistent s poudarkom na:

* Pravna podlaga (dokumenti)
* Trenutne tržne razmere (internet)
* Strokovne ocene (general knowledge)
* Source attribution: 📚 RAG + 🌐 Internet + 🧠 General knowledge

### Primerjalna Tabela

| Značilnost |             Lightning | Frontier                        |
| ---------- | --------------------: | ------------------------------- |
| Model      |      gemini-2.5-flash | gemini-2.5-flash (Orchestrated) |
| RAG Dostop |   ✅ Admin + user docs | ✅ Admin + user docs             |
| Internet   |                  ❌ Ne | ✅ Google Search                 |
| Hitrost    |         ⚡ 5-15 sekund | 🔍 15-30 sekund                 |
| Cena       |              0.5 vpr. | 1.0 vpr.                        |
| Use Case   | Hitri pravni odgovori | Raziskovalne analize            |

***

## Data Flow Architecture

### Celotni Podatkovni Tok

```
User Login (Google OAuth)
    ↓
Firebase Auth
    ↓
Load User Profile & Conversations (Firestore)
    ↓
Display Dashboard
    ↓
[Opcijsko] File Upload 
    ↓
Cloud Function: uploadFile() (Direct V2)
    ├─ Buffer Stream (Busboy)
    ├─ Validate (Size/Type)
    ├─ Cloud Storage (Archival)
    ├─ Gemini File API (Multimodal URI)
    └─ Firestore Metadata
    ↓
User Query + Attachments [URI]
    ↓
Cloud Function: askGemini()
    ├─ Orchestrate Agents
    │   ├─ Lightning: RAG Agent (Smart Router + Long Context) → Response
    │   └─ Frontier: Frontier Agent (RAG Context + Google Search Tool) → Response
    ├─ Post-Processing: Tokens [1] → Links (če potrebno)
    ├─ Inject Attachments (Multimodal)
    └─ Save conversation (Firestore)
    ↓
Stream Response to UI
    ↓
Save to Firestore
```

### Lightning Mode Data Flow

```
User Query
    ↓
Load Admin + User RAG Stores
    ↓
Use File Search Tool
    ↓
Query RAG Documents
    ↓
Response z 📚 RAG sources
    ↓
Deduct 0.5 questions
```

### Frontier Mode Data Flow (Unified Execution)

{% stepper %}
{% step %}

### 1. prepareDocumentContext()

* Smart Router izbere Admin/User PDF-je
* JIT Upload omogoči Long Context
  {% endstep %}

{% step %}

### 2. queryFrontierAgent() (Gemini 2.5 Flash)

* Input: User Query + RAG File Context (Tokens)
* Tools: Google Search Available
  {% endstep %}

{% step %}

### 3. Gemini Model Execution

* Prebere RAG Files (Deep Read)
* Izvede Google Search (če potrebno)
* Sintetizira odgovor s Citation Tokens \[1]
  {% endstep %}

{% step %}

### 4. Final Response

Final Response z 📚 RAG + 🌐 Internet sources\
Deduct 1.0 questions
{% endstep %}
{% endstepper %}

***

## Varnost in Zasebnost

### Authentication Model

**Google OAuth 2.0**

* Firebase Auth z Google identity provider
* Varni JWT tokeni
* Avtomatski token refresh
* Session management

**Authorization**

* Role-based access control (user/admin)
* Per-user data isolation
* Firestore security rules

### Data Protection

**Šifriranje**

* Encryption at rest (Firebase Storage)
* Encryption in transit (TLS/SSL)
* Secure API key management (Cloud Functions environment)

**Privacy**

* Per-user File Search Stores (izolacija dokumentov)
* Admin documents - dostopni vsem uporabnikom
* User documents - dostopni samo lastniku
* Brez deljenja podatkov med uporabniki

**Stripe Integration**

* Webhook signature verification
* Secure payment processing
* PCI-DSS compliance preko Stripe
* Slovensko DDV procesiranje

### Firestore Security Rules

```javascript
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // User documents
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
      
      // Conversations
      match /conversations/{conversationId} {
        allow read, write: if request.auth.uid == userId;
      }
    }
    
    // Admin only
    match /systemPrompts/{promptId} {
      allow read: if request.auth != null;
      allow write: if request.auth.token.admin == true;
    }
  }
}
```

***

## Deployment Architecture

### Production Environment

Diagram prikazuje komponente: Client Layer (Browser/Mobile/Tablet) → Firebase Hosting → Firebase Auth → Cloud Functions V2 → Firestore / Storage / Gemini API → Stripe.

### Deployment Process

**Frontend**

```bash
# Build optimiziran production bundle
npm run build

# Deploy na Firebase Hosting
firebase deploy --only hosting
```

**Backend**

```bash
# Deploy Cloud Functions
firebase deploy --only functions

# Deploy Firestore rules
firebase deploy --only firestore:rules
```

**Environment Variables**

* Ločeno upravljanje development/production
* Varne ključe shranjujemo v Cloud Functions environment
* Brez hardcoded secrets v kodi

***

## Performance Optimizations

### Frontend Optimizations

* Code Splitting: React.lazy() za route-based splitting
* Dynamic imports za velike komponente
* Service Workers za offline capability
* IndexedDB za lokalno shranjevanje pogovorov
* Optimistic UI updates
* Vite production build optimizacije, tree-shaking, minification

### Backend Optimizations

* Cloud Functions Generation 2 (V2)
* 1GiB memory allocation za AI operacije
* 300s timeout za kompleksne procese
* Concurrent execution za Frontier mode
* Firestore: composite indexes, pagination, real-time listeners samo kjer potrebno
* RAG System: JIT upload, 48-urni cache Gemini File API, Smart Router za minimizacijo prenESov

***

## Monitoring in Logging

### Firebase Monitoring

* Page load times
* API response times
* Error rates

### Cloud Functions Logs

* Structured logging
* Error tracking
* Performance metrics

### Firestore Usage

* Read/write operations
* Storage usage
* Index performance

### Cost Monitoring

* Gemini API Usage: Token consumption tracking, model usage statistics, cost per query analytics
* Cloud Functions: Invocation counts, execution time, memory usage
* Storage: File storage costs, network egress, backup costs

***

## Scalability

### Horizontal Scaling

* Cloud Functions: avtomatično skaliranje, concurrent execution do 1000 instances, per-function configuration
* Firestore: automatic sharding, multi-region replication, unlimited scaling capability

### Vertical Scaling

* Memory Allocation: 1GiB za AI-intensive funkcije, 256MiB za lahke operacije
* Timeout Configuration: 300s za kompleksne AI operacije, 60s za standardne operacije

***

## Tehnološke Inovacije

1. Hybrid Smart Router RAG System
   * Deterministična metadata knjižnica + Long Context okno za natančno branje dokumentov
2. Agent-as-a-Tool Orchestration
   * Unified Frontier Agent, simultano procesiranje RAG in Web virov, source mapping s \[ID] tokens
3. Automated Document Partitioning
   * Particioniranje velikih dokumentov (>300 strani) v volume-e
4. JIT Upload Strategy
   * Nalaganje samo aktivno potrebnih dokumentov, 48-urni cache window
5. Multi-Source Attribution System
   * Transparenten sistem citiranja z emoji indikatorji:
     * 📚 RAG sources (File Search)
     * 🌐 Internet sources (Google Search)
     * 🧠 General knowledge (AI reasoning)

***

## Zaključek

Moj AI predstavlja sofisticirano cloud-native rešitev za slovenski gradbeni sektor, ki združuje:

* Napredne AI capabilities (Gemini 2.5)
* Hybrid RAG arhitekturo
* Agent orchestration pattern
* Multi-tenant infrastructure
* Enterprise-grade security

Sistem je zasnovan za visoko zanesljivost, skalabilnost in cost-efficiency, hkrati pa ohranja transparentnost virov in natančnost pravnih informacij.

***

**Verzija dokumenta**: 1.0\
**Datum**: Januar 2026\
**Kontakt**: \[Vaša kontaktna informacija za public docs]


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mojai.xyz/tehnicne-specifikacije/arhitektura.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
