# System Design

## Overview

Lexari AI is built on a modern, serverless architecture that combines AI-powered natural language processing with decentralized finance protocols. The system is designed for scalability, reliability, and real-time performance.

## System Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Frontend      │    │   Backend       │    │   External      │
│   (Next.js)     │◄──►│   (AWS Lambda)  │◄──►│   Services      │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   WebSocket     │    │   DynamoDB      │    │   LiFi SDK      │
│   Connection    │    │   (Sessions)    │    │   (DeFi)        │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Real-time     │    │   AWS Bedrock   │    │   CoinGecko     │
│   Chat          │    │   (AI Engine)   │    │   (Market Data) │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

## Frontend Architecture

### Technology Stack

* **Framework**: Next.js 15 with React 18
* **Styling**: Tailwind CSS with custom components
* **State Management**: React hooks and context
* **Web3 Integration**: Wagmi + RainbowKit for wallet connections
* **Real-time**: WebSocket connections for live chat

### Key Components

#### Chat Interface

* **ChatInterface.tsx**: Main chat component handling message display and widget triggers
* **ChatMessage.tsx**: Individual message rendering with XML parsing
* **InlineLiFiWidget.tsx**: LiFi widget integration for DeFi operations

#### Wallet Integration

* **Header.tsx**: Wallet connection and navigation
* **LiFiWalletButton.tsx**: Custom wallet management using LiFi's external wallet system

#### Widget System

* **Widget Parsing**: XML-based quote parsing for swap and bridge operations
* **Amount Conversion**: Wei to human-readable amount conversion
* **Chain Resolution**: Chain ID to name mapping

### Frontend Features

* **Real-time Chat**: WebSocket-based live messaging
* **Widget Integration**: Seamless LiFi widget embedding
* **Multi-wallet Support**: MetaMask, Phantom, Coinbase Wallet
* **Responsive Design**: Mobile-first approach
* **Dark Mode**: Default dark theme with professional styling

## Backend Architecture

### Technology Stack

* **Runtime**: AWS Lambda with Node.js 20
* **Infrastructure**: AWS CDK for infrastructure as code
* **Database**: DynamoDB for session and message storage
* **AI Engine**: AWS Bedrock with Claude-3-5-Haiku
* **Real-time**: API Gateway WebSocket API
* **Queue System**: SQS for message processing

### Core Components

#### Lambda Functions

* **queueChatHandler.ts**: WebSocket connection management
* **queueChatExecutor.ts**: Main AI orchestration and response generation
* **api.ts**: HTTP API endpoints

#### AI System

* **Intent Classification**: Multi-step AI processing for user intent
* **Tool Orchestration**: Dynamic tool selection based on intent
* **Contextual Response**: AI-generated responses with tool data

#### DeFi Integration

* **LiFi Handler**: Swap and bridge quote generation
* **Token Management**: Address resolution and validation
* **Chain Support**: Multi-chain operation handling

### Backend Features

* **Intent Classification**: AI-powered query understanding
* **Tool Orchestration**: Dynamic tool selection and execution
* **Real-time Processing**: WebSocket-based live communication
* **Error Handling**: Comprehensive error management and fallbacks
* **Rate Limiting**: API rate limit management
* **Security**: JWT authentication and IAM policies

## Data Flow

### Message Processing Flow

1. **User Input**: User sends message via WebSocket
2. **Queue Processing**: Message queued in SQS
3. **Intent Classification**: AI classifies user intent
4. **Tool Orchestration**: AI selects appropriate tools
5. **Tool Execution**: Tools fetch data or generate quotes
6. **Response Generation**: AI generates contextual response
7. **WebSocket Response**: Response sent back to user

### DeFi Operation Flow

1. **Natural Language**: User requests swap or bridge
2. **Intent Detection**: AI identifies DeFi operation
3. **Request Parsing**: Extract tokens, amounts, chains
4. **LiFi Integration**: Generate quote via LiFi SDK
5. **Widget Trigger**: Frontend displays LiFi widget
6. **User Execution**: User executes transaction via widget

## Database Schema

### DynamoDB Tables

#### Core Table (Sessions & Messages)

```
PK: session#{sessionId}
SK: message#{timestamp}
- createdAt: ISO timestamp
- createdBy: user identifier
- message: message content
- characterId: AI character identifier
- ttl: expiration timestamp
```

#### WebSocket Connections Table

```
PK: session#{sessionId}
SK: character#{characterId}
- connectionId: WebSocket connection ID
- status: connected/disconnected
- ttl: connection expiration
```

## Security Architecture

### Authentication

* **JWT Tokens**: Stateless authentication
* **IAM Policies**: AWS service access control
* **CORS Configuration**: Cross-origin request handling

### Data Protection

* **Encryption**: DynamoDB encryption at rest
* **HTTPS**: All API communications encrypted
* **WAF**: Web Application Firewall protection

### Access Control

* **API Gateway**: Request validation and throttling
* **Lambda Permissions**: Least privilege access
* **Environment Variables**: Secure configuration management

## Scalability Features

### Serverless Architecture

* **Auto-scaling**: Lambda functions scale automatically
* **Pay-per-use**: Cost optimization through serverless
* **Global Distribution**: CloudFront CDN for frontend

### Performance Optimization

* **Connection Pooling**: Efficient database connections
* **Caching**: Response caching where appropriate
* **Async Processing**: Non-blocking operations

## Monitoring & Logging

### CloudWatch Integration

* **Lambda Logs**: Function execution logs
* **API Gateway Logs**: Request/response logging
* **Custom Metrics**: Business-specific metrics

### Error Tracking

* **Error Handling**: Comprehensive error management
* **Fallback Mechanisms**: Graceful degradation
* **Alerting**: Automated error notifications

## Deployment Architecture

### AWS Infrastructure

* **Region**: us-east-1 (primary)
* **CDK Stack**: Infrastructure as code
* **Environment Variables**: Secure configuration
* **CI/CD**: Automated deployment pipeline

### Environment Management

* **Development**: Local development setup
* **Staging**: Pre-production testing
* **Production**: Live environment

## API Endpoints

### WebSocket API

* **$connect**: Connection establishment
* **$disconnect**: Connection termination
* **sendMessage**: Message processing

### HTTP API

* **/v1/callAgent**: Agent interaction endpoint
* **CORS**: Cross-origin resource sharing

## External Integrations

### LiFi SDK

* **Swap Quotes**: Same-chain token swaps
* **Bridge Quotes**: Cross-chain token transfers
* **Route Optimization**: Best route selection

### CoinGecko API

* **Price Data**: Real-time cryptocurrency prices
* **Market Data**: Market cap, volume, trends
* **Token Information**: Token metadata and details

### AWS Bedrock

* **Claude-3-5-Haiku**: Natural language processing
* **Intent Classification**: User intent understanding
* **Response Generation**: Contextual AI responses


---

# 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://lexari-1.gitbook.io/lexari/technical-architecture/architecture.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.
