CodeQual uses a specialized translator architecture where different types of content are handled by optimized translators, each tuned for specific requirements.
Instead of a one-size-fits-all approach, we have 5 specialized translators:
| Translator | Context | Optimization | Cache TTL | Primary Use |
|---|---|---|---|---|
| APITranslator | api |
Speed (45%), Quality (35%), Cost (20%) | 1 hour | API responses, JSON data |
| ErrorTranslator | error |
Quality (50%), Speed (35%), Cost (15%) | 2 hours | Error messages, exceptions |
| DocumentationTranslator | docs |
Quality (80%), Speed (5%), Cost (15%) | 7 days | Technical docs, README files |
| UITranslator | ui |
Quality (45%), Speed (25%), Cost (30%) | 24 hours | Buttons, labels, tooltips |
| CodeTranslator | sdk |
Quality (70%), Speed (10%), Cost (20%) | 3 days | Code comments, SDKs |
TranslatorFactory (Singleton)
├── APITranslator
│ ├── JSON structure preservation
│ ├── Fast response times
│ └── Key/value awareness
├── ErrorTranslator
│ ├── Common error dictionary
│ ├── Actionable suggestions
│ └── Error code preservation
├── DocumentationTranslator
│ ├── Markdown preservation
│ ├── Code block handling
│ └── Chunk processing for long docs
├── UITranslator
│ ├── Length constraints
│ ├── Common UI terms
│ └── Cultural adaptation
└── CodeTranslator
├── Comment extraction
├── Code structure preservation
└── Language-specific handling
import { TranslatorFactory } from '@codequal/agents/translator/translator-factory';
const factory = TranslatorFactory.getInstance();
// Translate API response
const apiResult = await factory.translate({
content: {
status: 'processing',
message: 'Analysis in progress',
details: { filesProcessed: 10 }
},
targetLanguage: 'es',
context: 'api'
});
// Translate error message
const errorResult = await factory.translate({
content: 'Authentication failed: Invalid API key',
targetLanguage: 'ja',
context: 'error',
options: {
includeSuggestions: true
}
});import { quickTranslate } from '@codequal/agents/translator/translator-factory';
// Auto-detect context and translate
const translated = await quickTranslate(
'Click here to continue',
'zh', // Chinese
'ui' // Optional context hint
);// Translate multiple items efficiently
const results = await factory.translateBatch([
{
content: 'Save',
targetLanguage: 'de',
context: 'ui'
},
{
content: 'Cancel',
targetLanguage: 'de',
context: 'ui'
},
{
content: { error: 'Not found' },
targetLanguage: 'de',
context: 'error'
}
]);Features:
- Preserves JSON structure
- Never translates keys, only values
- Handles nested objects
- Preserves data types (numbers, booleans, null)
Example:
const result = await factory.translate({
content: {
user: {
name: 'John',
status: 'active',
message: 'Welcome back!'
}
},
targetLanguage: 'fr',
context: 'api',
options: {
preserveKeys: true // Default for API
}
});
// Result:
// {
// user: {
// name: 'John',
// status: 'active',
// message: 'Bienvenue!'
// }
// }Features:
- Common error dictionary for instant translation
- Adds helpful suggestions
- Preserves error codes
- Technical level adjustment
Example:
const result = await factory.translate({
content: {
error: 'Rate limit exceeded',
code: 'RATE_LIMIT',
details: { limit: 1000, remaining: 0 }
},
targetLanguage: 'es',
context: 'error',
options: {
technicalLevel: 'beginner',
includeSuggestions: true
}
});Features:
- Preserves markdown formatting
- Handles code blocks without translation
- Chunk processing for long documents
- Glossary support
Example:
const result = await factory.translate({
content: `# Getting Started
Install the package:
\`\`\`bash
npm install @codequal/api-client
\`\`\`
Then import and use:`,
targetLanguage: 'ja',
context: 'docs',
options: {
format: 'markdown',
glossary: {
'package': 'パッケージ',
'import': 'インポート'
}
}
});Features:
- Length constraints for UI space
- Common UI terms dictionary
- Cultural adaptations
- Variable preservation
Example:
const result = await factory.translate({
content: 'Hello {userName}, you have {count} new messages',
targetLanguage: 'ko',
context: 'ui',
options: {
maxLength: 50,
context: 'tooltip',
variables: {
userName: 'string',
count: 'number'
}
}
});Features:
- Extracts and translates only comments
- Preserves code structure
- Handles multiple comment styles
- Language-specific processing
Example:
const result = await factory.translate({
content: `
/**
* Calculate the total price
* @param items - List of items
* @returns Total price
*/
function calculateTotal(items) {
// Sum all item prices
return items.reduce((sum, item) => sum + item.price, 0);
}`,
targetLanguage: 'pt',
context: 'sdk',
options: {
codeLanguage: 'javascript',
translateInlineComments: true,
preserveJSDoc: true
}
});Each translator uses the TranslatorResearcher to select optimal models based on:
- Context requirements (speed vs quality vs cost)
- Target language (some models excel at specific languages)
- Content type (technical vs conversational)
- Special capabilities (JSON support, formatting preservation)
| Context | Quality | Speed | Cost | Example Model Selection |
|---|---|---|---|---|
| API | 35% | 45% | 20% | GPT-3.5-turbo (balanced) |
| Error | 50% | 35% | 15% | Claude-3-sonnet (clarity) |
| Docs | 80% | 5% | 15% | GPT-4-turbo (accuracy) |
| UI | 45% | 25% | 30% | GPT-3.5-turbo (cost-effective) |
| SDK | 70% | 10% | 20% | Claude-3-opus (technical) |
Each translator implements intelligent caching:
// Cache TTLs by context
API: 1 hour // Dynamic content
Error: 2 hours // Semi-static
UI: 24 hours // Stable
Docs: 7 days // Very stable
SDK: 3 days // StableReduce API calls with batch translation:
// Inefficient: Multiple API calls
for (const item of items) {
await translate(item);
}
// Efficient: Single batched call
const results = await factory.translateBatch(items);For production, pre-warm common translations:
// On startup
await warmupTranslations([
{ content: 'Loading...', languages: ['es', 'zh', 'ja'], context: 'ui' },
{ content: 'Error', languages: ['es', 'zh', 'ja'], context: 'error' },
// ... more common phrases
]);- Use the right context - Don't use 'docs' for API responses
- Batch when possible - Group similar translations
- Provide options - Help translators with context hints
- Cache strategically - Leverage built-in caching
- Monitor costs - Higher quality contexts cost more
// Get translator statistics
const stats = factory.getStatistics();
console.log(stats);
// {
// api: { cacheSize: 234, cacheHitRate: 0.85 },
// error: { cacheSize: 45, cacheHitRate: 0.92 },
// // ...
// }
// Clear caches when needed
factory.clearAllCaches();All translators implement graceful fallbacks:
try {
const result = await factory.translate(request);
} catch (error) {
// Translators return original content on failure
// Error is logged but not thrown to user
}- Custom translators - Plugin architecture for domain-specific needs
- Translation memory - Reuse previous translations
- Quality scoring - Rate translation quality
- A/B testing - Compare different models
- Cost optimization - Automatic model downgrade for budget limits