Polyglot
The Universal Language Bridge
Polyglot functions as your universal language bridge, enabling seamless communication across programming languages, frameworks, and human languages. This autonomous translation specialist breaks down barriers between technologies while ensuring nothing is lost in translation.
Code Translation Excellence
Intelligent Language Translation: Polyglot translates code between programming languages while preserving functionality, performance characteristics, and architectural patterns. The agent understands language-specific idioms and best practices, ensuring translated code feels native to the target language.
Context Preservation: Unlike simple syntax translators, Polyglot maintains the intent and context of original code. Comments, variable names, and architectural decisions are translated appropriately while preserving the developer's original intentions.
Optimization During Translation: The agent doesn't just translate code—it optimizes it for the target language. This includes using language-specific features, libraries, and patterns that improve performance and maintainability.
Advanced Framework Migration
# Polyglot Framework Migration Example
# Original: Express.js REST API
"""
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const rateLimit = require('express-rate-limit');
const app = express();
const PORT = process.env.PORT || 3000;
// Rate limiting middleware
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
app.use(express.json());
// Authentication middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// User registration endpoint
app.post('/api/users/register', async (req, res) => {
try {
const { email, password, firstName, lastName } = req.body;
// Validate input
if (!email || !password || !firstName || !lastName) {
return res.status(400).json({ error: 'Missing required fields' });
}
// Hash password
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);
// Create user (database logic would go here)
const user = await createUser({
email,
password: hashedPassword,
firstName,
lastName
});
// Generate JWT
const accessToken = jwt.sign(
{ userId: user.id, email: user.email },
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: '1h' }
);
res.status(201).json({
user: { id: user.id, email: user.email, firstName, lastName },
accessToken
});
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
"""
# Polyglot-translated: FastAPI Python equivalent
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from pydantic import BaseModel, EmailStr, validator
from passlib.context import CryptContext
from jose import JWTError, jwt
from datetime import datetime, timedelta
from typing import Optional
import os
import uvicorn
# Polyglot-optimized FastAPI application
app = FastAPI(
title="User Management API",
description="Translated from Express.js by Polyglot",
version="2.0.0"
)
# Rate limiting setup (FastAPI equivalent of express-rate-limit)
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Security setup
security = HTTPBearer()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Configuration
ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET")
ACCESS_TOKEN_EXPIRE_MINUTES = 60
# Pydantic models (FastAPI best practice)
class UserRegistrationRequest(BaseModel):
email: EmailStr
password: str
firstName: str
lastName: str
@validator('password')
def validate_password(cls, v):
if len(v) < 8:
raise ValueError('Password must be at least 8 characters long')
return v
@validator('firstName', 'lastName')
def validate_names(cls, v):
if not v.strip():
raise ValueError('Name fields cannot be empty')
return v.strip()
class UserResponse(BaseModel):
id: str
email: str
firstName: str
lastName: str
class TokenResponse(BaseModel):
user: UserResponse
accessToken: str
tokenType: str = "bearer"
# Authentication dependency (FastAPI equivalent of Express middleware)
async def authenticate_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
"""
FastAPI dependency for JWT authentication.
Polyglot-translated from Express.js middleware pattern.
"""
try:
payload = jwt.decode(
credentials.credentials,
ACCESS_TOKEN_SECRET,
algorithms=["HS256"]
)
user_id: str = payload.get("userId")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return payload
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# Utility functions
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, ACCESS_TOKEN_SECRET, algorithm="HS256")
return encoded_jwt
# User registration endpoint (FastAPI style with automatic validation)
@app.post(
"/api/users/register",
response_model=TokenResponse,
status_code=status.HTTP_201_CREATED,
summary="Register new user",
description="Create a new user account with email and password"
)
@limiter.limit("5/minute") # FastAPI equivalent of Express rate limiting
async def register_user(
user_data: UserRegistrationRequest,
request: Request # Required for rate limiting
) -> TokenResponse:
"""
Register a new user account.
Polyglot-translated from Express.js with FastAPI optimizations.
"""
try:
# Check if user already exists (database logic would go here)
existing_user = await get_user_by_email(user_data.email)
if existing_user:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="User with this email already exists"
)
# Hash password with bcrypt equivalent
hashed_password = get_password_hash(user_data.password)
# Create user (database logic would go here)
user = await create_user({
"email": user_data.email,
"password": hashed_password,
"firstName": user_data.firstName,
"lastName": user_data.lastName
})
# Generate JWT token
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"userId": user["id"], "email": user["email"]},
expires_delta=access_token_expires
)
# Return response matching original Express.js structure
return TokenResponse(
user=UserResponse(
id=user["id"],
email=user["email"],
firstName=user["firstName"],
lastName=user["lastName"]
),
accessToken=access_token
)
except HTTPException:
raise
except Exception as e:
# Structured logging (FastAPI best practice)
logger.error(f"Registration error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
)
# Protected endpoint example
@app.get("/api/users/profile", response_model=UserResponse)
async def get_user_profile(current_user: dict = Depends(authenticate_token)):
"""Protected endpoint demonstrating authentication dependency"""
user = await get_user_by_id(current_user["userId"])
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return UserResponse(
id=user["id"],
email=user["email"],
firstName=user["firstName"],
lastName=user["lastName"]
)
# Health check endpoint (FastAPI convention)
@app.get("/health")
async def health_check():
return {"status": "healthy", "timestamp": datetime.utcnow()}
# Additional FastAPI optimizations not present in original Express.js
@app.on_event("startup")
async def startup_event():
"""Initialize application resources"""
# Database connection, cache setup, etc.
pass
@app.on_event("shutdown")
async def shutdown_event():
"""Cleanup application resources"""
# Close database connections, cache cleanup, etc.
pass
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=int(os.getenv("PORT", 3000)),
reload=os.getenv("ENVIRONMENT") == "development"
)
# Polyglot Translation Summary:
# 1. Express.js middleware → FastAPI dependencies
# 2. Manual validation → Pydantic models with automatic validation
# 3. express-rate-limit → slowapi rate limiting
# 4. bcrypt → passlib with bcrypt backend
# 5. jsonwebtoken → python-jose
# 6. Manual error handling → FastAPI exception handling
# 7. Express routing → FastAPI path operations with OpenAPI docs
# 8. Added type hints, async/await optimization, and FastAPI best practices
Legacy System Modernization
COBOL to Modern Languages: Polyglot excels at modernizing legacy codebases including translations from COBOL to Java, VB.NET to C#, PHP 5 to PHP 8, and many other modernization scenarios. The agent handles complex business logic preservation while implementing modern patterns.
Mainframe Migration: The agent facilitates migration from mainframe systems to cloud-native architectures, translating not just code but also data structures, business rules, and operational procedures.
Framework Evolution: Systematic migration between framework versions including Angular.js to Angular, React class components to hooks, and other evolutionary updates that require significant refactoring.
API Translation and Modernization
Protocol Translation: Polyglot translates between different API styles including REST to GraphQL, SOAP to REST, and RPC to REST. The agent ensures API functionality remains consistent while adapting to modern standards and practices.
Schema Evolution: Database schema translation and evolution including normalization improvements, performance optimizations, and modern data modeling techniques.
Authentication Migration: Translation between authentication methods including Basic Auth to OAuth 2.0, custom sessions to JWT, and legacy authentication to modern identity providers.
Database Migration Excellence
Cross-Platform Migration: Polyglot facilitates database migrations including schema translation, query conversion, and data type mapping. The agent handles migrations between SQL databases, SQL to NoSQL transitions, and hybrid approaches.
Query Optimization: During migration, the agent optimizes queries for the target database platform, taking advantage of platform-specific features and performance characteristics.
Data Integrity: Comprehensive validation ensures that data integrity is maintained throughout migration processes, with automatic verification and rollback capabilities.
Documentation and Content Translation
Technical Documentation: Working with Scribe, Polyglot translates technical documentation between human languages while preserving technical accuracy and context. The agent ensures documentation remains helpful and accurate across language barriers.
Code Comments: Translation of code comments and documentation strings maintains code readability across language barriers while preserving technical precision.
Cultural Adaptation: Beyond literal translation, the agent adapts content for cultural context, ensuring that documentation resonates with different regional audiences.
Configuration and Template Translation
Infrastructure as Code: Translation between infrastructure configuration formats including CloudFormation to Terraform, Kubernetes YAML to Helm charts, and other infrastructure translation needs.
Build System Migration: Conversion between build systems including Webpack to Vite, Gradle to Maven, Make to CMake, and other build tool migrations while maintaining functionality and performance.
Template Engine Translation: Translation between template engines including Handlebars to Jinja2, JSX to Vue templates, and other template format conversions while preserving dynamic functionality.
Last updated