> ## Documentation Index
> Fetch the complete documentation index at: https://finance.qwedai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Design and architecture

> QWED-Finance system architecture with C4 diagrams showing integration with core banking systems, SWIFT messaging, regulators, and downstream audit pipelines.

This page provides a deep dive into the internal design of QWED-Finance.

## System overview

```mermaid theme={null}
C4Context
    title QWED-Finance System Context
    
    Person(user, "Banking Customer", "Interacts with banking services")
    Person(agent, "Banking Agent", "LLM-powered assistant")
    
    System(qwed, "QWED-Finance", "Deterministic verification middleware")
    
    System_Ext(bank, "Core Banking", "Transaction processing")
    System_Ext(swift, "SWIFT Network", "International payments")
    System_Ext(regulator, "Regulators", "RBI, FinCEN, OFAC")
    
    Rel(user, agent, "Requests")
    Rel(agent, qwed, "Verifies outputs")
    Rel(qwed, bank, "Approved transactions")
    Rel(qwed, swift, "Verified messages")
    Rel(qwed, regulator, "Audit receipts")
```

## Guard architecture

### Component diagram

```mermaid theme={null}
graph TB
    subgraph "qwed_finance/"
        direction TB
        
        subgraph "Guards (Domain Logic)"
            CG["compliance_guard.py<br/>AML/KYC/Sanctions"]
            CAL["calendar_guard.py<br/>Day Count Conventions"]
            DG["derivatives_guard.py<br/>Black-Scholes"]
            MG["message_guard.py<br/>ISO 20022 / SWIFT"]
            QG["query_guard.py<br/>SQL Safety"]
            XG["cross_guard.py<br/>Multi-layer"]
            BG["bond_guard.py<br/>YTM / Duration"]
            FXG["fx_guard.py<br/>FX Rates"]
            RG["risk_guard.py<br/>VaR / Ratios"]
            ISO["guards/iso_guard.py<br/>ISO 20022 JSON"]
            TG["guards/trading_guard.py<br/>Order Parameters"]
        end
        
        subgraph "Models (Data Structures)"
            Receipt["models/receipt.py<br/>VerificationReceipt"]
            Schemas["schemas.py<br/>LoanSchema, etc."]
        end
        
        subgraph "Integrations (External APIs)"
            OR["integrations/open_responses.py"]
            UCP["integrations/ucp.py"]
        end
        
        subgraph "Core"
            FV["finance_verifier.py<br/>NPV, IRR, Loans"]
        end
    end
    
    subgraph "External Engines"
        Z3["Z3 SMT Solver"]
        SymPy["SymPy"]
        MP["mpmath"]
        SQLGlot["SQLGlot"]
    end

    CG --> Z3
    FV --> SymPy
    DG --> MP
    QG --> SQLGlot

    XG --> CG
    XG --> MG
    XG --> QG
    XG --> Receipt
    OR --> Receipt
    UCP --> Receipt
```

## Verification flow

### State machine

```mermaid theme={null}
stateDiagram-v2
    [*] --> Received: LLM Output
    
    Received --> Parsing: Extract Data
    Parsing --> GuardSelection: Detect Type
    
    GuardSelection --> ComplianceCheck: Financial Amount
    GuardSelection --> CalendarCheck: Date Calculation
    GuardSelection --> DerivativesCheck: Options/Greeks
    GuardSelection --> MessageCheck: XML/SWIFT
    GuardSelection --> QueryCheck: SQL Query
    
    ComplianceCheck --> SymbolicProof
    CalendarCheck --> SymbolicProof
    DerivativesCheck --> SymbolicProof
    MessageCheck --> SchemaValidation
    QueryCheck --> ASTAnalysis
    
    SymbolicProof --> ReceiptGeneration
    SchemaValidation --> ReceiptGeneration
    ASTAnalysis --> ReceiptGeneration
    
    ReceiptGeneration --> Approved: verified=True
    ReceiptGeneration --> Rejected: verified=False
    ReceiptGeneration --> PendingReview: UCP PENDING_REVIEW
    
    Approved --> [*]
    Rejected --> [*]
    PendingReview --> [*]
```

## Data flow

### Verification receipt lifecycle

```mermaid theme={null}
flowchart LR
    subgraph Input
        LLM["LLM Output"]
    end
    
    subgraph Processing
        Hash["SHA-256<br/>Input Hash"]
        Guard["Guard<br/>Verification"]
        Proof["Symbolic<br/>Proof Steps"]
    end
    
    subgraph Output
        Receipt["Verification<br/>Receipt"]
        Log["Audit<br/>Log"]
    end
    
    LLM --> Hash
    LLM --> Guard
    Guard --> Proof
    Hash --> Receipt
    Proof --> Receipt
    Receipt --> Log
```

### Cross-guard pipeline

```mermaid theme={null}
flowchart TD
    Input["SWIFT MT103 Message"]
    
    subgraph "Cross-Guard Pipeline"
        Step1["1. Message Guard<br/>Validate MT103 Format"]
        Step2["2. Extract Entities<br/>Debtor/Creditor Names"]
        Step3["3. Compliance Guard<br/>Sanctions Screening"]
        Step4["4. Query Guard<br/>Database Lookup Safety"]
    end
    
    Output1["✅ All Clear"]
    Output2["❌ Sanctions Hit"]
    Output3["⚠️ Format Error"]
    
    Input --> Step1
    Step1 -->|Valid| Step2
    Step1 -->|Invalid| Output3
    Step2 --> Step3
    Step3 -->|Clear| Step4
    Step3 -->|Hit| Output2
    Step4 --> Output1
```

## Engine selection matrix

```mermaid theme={null}
quadrantChart
    title Guard-to-Engine Mapping
    x-axis "Numeric Precision" --> "Logical Completeness"
    y-axis "Simple" --> "Complex"
    
    quadrant-1 "Formal Proofs"
    quadrant-2 "Calculations"
    quadrant-3 "Parsing"
    quadrant-4 "Validation"
    
    "Compliance (Z3)": [0.8, 0.7]
    "Calendar (Decimal)": [0.3, 0.4]
    "Derivatives (Math)": [0.2, 0.6]
    "Message (XML)": [0.6, 0.3]
    "Query (AST)": [0.7, 0.5]
```

## Class diagram

```mermaid theme={null}
classDiagram
    class FinanceVerifier {
        +verify_npv(cashflows, rate, llm_output)
        +verify_irr(cashflows, llm_output)
        +verify_monthly_payment(principal, annual_rate, months, llm_output)
        +verify_total_interest(principal, annual_rate, months, llm_output)
        +verify_compound_interest(principal, rate, periods, llm_output, compounding)
    }
    
    class ComplianceGuard {
        -aml_thresholds: dict
        -high_risk_countries: set
        +verify_aml_flag(amount, country_code, llm_flagged)
        +verify_kyc_complete(has_id, has_address_proof, has_tax_id, llm_approved)
        +verify_sanctions_check(entity_name, is_on_sanctions_list, llm_approved)
        +verify_transaction_limit(amount, daily_limit, daily_total, llm_approved)
    }
    
    class MessageGuard {
        +verify_iso20022_xml(xml, type)
        +verify_swift_mt(message, type)
        +verify_bic(bic, llm_says_valid)
        +verify_iban(iban, llm_says_valid)
    }
    
    class QueryGuard {
        -allowed_tables: Set
        +verify_readonly_safety(sql)
        +verify_table_access(sql, allowed_tables)
        +verify_column_access(sql, restricted_columns)
        +verify_no_injection(sql, user_input)
        +sanitize_query(sql)
    }
    
    class VerificationReceipt {
        +receipt_id: str
        +timestamp: str
        +input_hash: str
        +verified: bool
        +proof_steps: List
        +to_json()
        +get_signature(key)
    }
    
    class CrossGuard {
        -compliance: ComplianceGuard
        -message: MessageGuard
        -query: QueryGuard
        -audit_log: AuditLog
        +verify_swift_with_sanctions()
        +verify_iso20022_with_rules()
        +check_business_rules()
        +verify_query_with_pii_protection()
    }

    CrossGuard --> VerificationReceipt : generates
    CrossGuard --> ComplianceGuard : uses
    CrossGuard --> MessageGuard : uses
    CrossGuard --> QueryGuard : uses
```

## Deployment architecture

```mermaid theme={null}
flowchart TB
    subgraph "Production Environment"
        subgraph "API Layer"
            FastAPI["Your API Server"]
            Express["Node.js App<br/>(@qwed-ai/finance)"]
        end
        
        subgraph "QWED-Finance"
            Guards["11 Guards"]
            Audit["Audit Log"]
        end
        
        subgraph "Storage"
            Redis["Redis<br/>(Receipt Cache)"]
            S3["S3/GCS<br/>(Audit Archive)"]
        end
    end
    
    subgraph "External"
        LLM["LLM API"]
        Bank["Bank API"]
    end
    
    LLM --> FastAPI
    LLM --> Express
    FastAPI --> Guards
    Express --> Guards
    Guards --> Audit
    Audit --> Redis
    Audit --> S3
    Guards --> Bank
```

***

## Design principles

### 1. Determinism first

Every verification produces the **same result** for the same input. No randomness.

### 2. Symbolic over statistical

Use solvers and exact arithmetic (Z3, SymPy, mpmath, `Decimal`) instead of probabilistic confidence scores.

### 3. Audit where it matters

`CrossGuard`, `UCPIntegration`, and the built-in `OpenResponsesIntegration` tools generate receipts automatically. Direct guard calls and custom Open Responses tools return result objects; create a receipt with `ReceiptGenerator` when you need an audit record. Invalid input fails closed instead of passing silently.

### 4. Defense in depth

Cross-Guard combines multiple guards for layered security.

***

## Related pages

* [Overview](/finance/overview) — Introduction and quick start
* [The 11 guards](/finance/guards) — Guard implementation details
* [Compliance & Auditing](/finance/compliance) — Receipt and audit log details


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.