This document explains the architecture and design decisions behind AXIOM.
AXIOM is designed with three core principles:
- Modularity: Each component has a single, well-defined responsibility
- Scalability: Easy to extend with new features and integrate with external systems
- Blockchain-Ready: Architecture prepared for future blockchain verification integration
┌─────────────────────────────────────────────────────────────┐
│ Client Layer │
│ (Web Apps, Mobile Apps, CLI Tools, Other Services) │
└────────────────────────┬────────────────────────────────────┘
│
│ HTTP/REST
│
┌────────────────────────▼────────────────────────────────────┐
│ Express Server │
│ (backend/server.js) │
├─────────────────────────────────────────────────────────────┤
│ Middleware Layer: │
│ ├── Request Logger (requestLogger.js) │
│ ├── JSON Parser │
│ └── Error Handler (errorHandler.js) │
└────────────────────────┬────────────────────────────────────┘
│
│
┌────────────────────────▼────────────────────────────────────┐
│ Routes Layer │
│ (backend/routes/) │
│ │
│ API Endpoints: │
│ ├── POST /api/ai/summarize │
│ ├── POST /api/ai/extract-claims │
│ └── GET /api/ai/health │
└────────────────────────┬────────────────────────────────────┘
│
│
┌────────────────────────▼────────────────────────────────────┐
│ Controllers Layer │
│ (backend/controllers/) │
│ │
│ Request Handlers: │
│ ├── Input Validation │
│ ├── Business Logic Orchestration │
│ └── Response Formatting │
└────────────────────────┬────────────────────────────────────┘
│
│
┌────────────────────────▼────────────────────────────────────┐
│ AI Agent Module │
│ (backend/ai-agent/) │
│ │
│ Core AI Functions: │
│ ├── Content Summarization │
│ ├── Claim Extraction │
│ ├── Content Validation │
│ └── Response Parsing │
└────────────────────────┬────────────────────────────────────┘
│
│
┌────────────────────────▼────────────────────────────────────┐
│ Google Gemini API │
│ (External AI Service) │
└─────────────────────────────────────────────────────────────┘
Responsibilities:
- Initialize Express application
- Configure middleware
- Register routes
- Handle server lifecycle (start/shutdown)
Key Features:
- Centralized configuration
- Graceful shutdown handling
- Informative startup logs
- Error boundary
Responsibilities:
- Load environment variables
- Validate required configuration
- Provide configuration to other modules
Security:
- Never exposes sensitive data in logs
- Validates API key presence at startup
- Environment-specific settings
Responsibilities:
- Define API endpoints
- Map URLs to controllers
- Document endpoint contracts
Design Pattern:
- RESTful API design
- Clear URL structure
- HTTP method conventions
Responsibilities:
- Handle HTTP request/response
- Validate user input
- Call business logic (AI agent)
- Format responses
Separation of Concerns:
- No AI logic in controllers
- No HTTP logic in AI agent
- Clean interface between layers
Responsibilities:
- Interface with Google Gemini API
- Process AI responses
- Provide AI capabilities as pure functions
Design Principles:
- Stateless: Functions are pure and don't maintain state
- Testable: Easy to unit test
- Reusable: Can be imported and used anywhere
- Independent: No dependencies on Express or HTTP
Key Functions:
summarizeContent(content)
├── Input: String content
├── Process: Send to Gemini API
├── Parse: Extract summary from response
└── Output: Structured result object
extractFactualClaims(content)
├── Input: String content
├── Process: Send to Gemini API with claim extraction prompt
├── Parse: Extract and structure claims
└── Output: Array of claims with metadata
validateContent(content)
├── Input: String content
├── Check: Type, length, format
└── Output: Validation resultRequest Logger:
- Logs all incoming requests
- Provides debugging information
- Helps with monitoring
Error Handler:
- Catches all errors
- Provides consistent error responses
- Environment-aware (shows stack in dev)
- Handles 404s gracefully
1. Client sends POST /api/ai/summarize
↓
2. Request Logger logs the request
↓
3. Express parses JSON body
↓
4. Routes layer forwards to aiController.summarize
↓
5. Controller validates input using aiAgent.validateContent
↓
6. If valid, controller calls aiAgent.summarizeContent
↓
7. AI Agent sends request to Gemini API
↓
8. Gemini API processes and returns summary
↓
9. AI Agent parses and structures response
↓
10. Controller formats final response
↓
11. Express sends JSON response to client
↓
12. Error Handler catches any errors along the way
The architecture is designed for easy blockchain integration:
-
Verification Hash Placeholders
{ verificationHash: null // Ready for blockchain hash }
-
Blockchain Ready Flag
{ blockchainReady: true // Indicates data structure is ready }
-
Timestamping
{ timestamp: "2024-01-08T20:00:00.000Z" // For audit trails }
-
Independent AI Agent
- Can be called from smart contracts
- Pure functions, easy to integrate
- Structured output ready for on-chain storage
┌─────────────────────────────────────────────────────────────┐
│ AXIOM AI Agent │
│ (Current Implementation) │
└────────────────────────┬────────────────────────────────────┘
│
├─────────────────────┐
│ │
▼ ▼
┌────────────────────────────────┐ ┌────────────────────────┐
│ Blockchain Verification │ │ Traditional Storage │
│ Module (Future) │ │ (Database) │
├────────────────────────────────┤ └────────────────────────┘
│ - Hash Generation │
│ - Smart Contract Interaction │
│ - IPFS Storage │
│ - Verification Proofs │
│ - Claim Attestation │
└────────────────────────────────┘
-
Content Hashing
- SHA-256 hash of original content
- SHA-256 hash of summaries/claims
- Merkle tree for multiple claims
-
Smart Contract Integration
- Store verification hashes on-chain
- Timestamp anchoring
- Claim attestation system
- Reputation system for verified claims
-
Decentralized Storage
- IPFS for content storage
- On-chain hash references
- Permanent, verifiable records
-
Verification API
// Future endpoint POST /api/blockchain/verify { "contentHash": "abc123...", "claimHash": "def456..." } Response: { "verified": true, "blockNumber": 12345, "timestamp": "2024-01-08T20:00:00.000Z", "transactionHash": "0x..." }
-
Horizontal Scaling
- Stateless design
- Can run multiple instances behind load balancer
- No session management
-
Async Processing
- AI operations are async
- Non-blocking I/O
- Can handle multiple concurrent requests
-
Module Independence
- AI agent can be extracted to microservice
- Easy to add caching layer
- Simple to add message queue
-
Caching Layer
Client → API → Redis Cache → AI Agent → Gemini -
Queue System
Client → API → Message Queue → Worker Pool → AI Agent -
Microservices
API Gateway ├── Auth Service ├── AI Service (Current AI Agent) ├── Blockchain Service └── Storage Service
-
API Key Protection
- Stored in environment variables
- Never logged or exposed
- Validated at startup
-
Input Validation
- Type checking
- Length limits
- Content sanitization
-
Error Handling
- No sensitive data in error messages
- Stack traces only in development
- Consistent error format
-
Environment Variables
- Never commit .env files
- Use .env.example as template
- Rotate API keys regularly
-
Rate Limiting (Not implemented, recommended for production)
// Future enhancement const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); app.use('/api/', limiter);
-
CORS (Not implemented, add if needed)
// If serving from different domain const cors = require('cors'); app.use(cors({ origin: 'https://yourdomain.com' }));
- One module per file
- Clear file naming (descriptive, lowercase)
- Group related files in folders
- Comprehensive comments
- Descriptive variable names
- Consistent formatting
- JSDoc for functions
try {
// Operation
const result = await operation();
return { success: true, data: result };
} catch (error) {
console.error('Context:', error.message);
throw new Error('User-friendly message');
}// Success
{
success: true,
...data
}
// Error
{
success: false,
error: "message"
}- Test AI agent functions
- Test validation logic
- Test response parsing
- Test API endpoints
- Test error handling
- Test middleware
// tests/aiAgent.test.js
describe('AI Agent', () => {
describe('validateContent', () => {
it('should reject content that is too short', () => {
const result = validateContent('short');
expect(result.valid).toBe(false);
});
it('should accept valid content', () => {
const result = validateContent('This is valid content that is long enough');
expect(result.valid).toBe(true);
});
});
});- Fast startup time
- Minimal memory footprint
- Async operations don't block
- Response caching for identical requests
- Connection pooling for API calls
- Compression for large responses
- CDN for static assets (if added)
- Request logging (all requests)
- Error logging (all errors)
- Server status logging
// Use production logging library
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});AXIOM's architecture is:
- ✅ Clean: Clear separation of concerns
- ✅ Modular: Easy to understand and modify
- ✅ Scalable: Ready for growth
- ✅ Secure: Following security best practices
- ✅ Blockchain-Ready: Prepared for future integration
- ✅ Beginner-Friendly: Well-documented and readable
This architecture provides a solid foundation for a hackathon project while being extensible enough for production use with additional hardening and features.