This document explains how localization works in StudyBuddy CLI, how to customize it, and how to add new languages.
- Overview
- Architecture
- Supported Languages
- Language Detection
- Template System
- Adding New Languages
- Customizing Templates
- Configuration
- Testing Localization
StudyBuddy CLI provides comprehensive multilingual support with:
- Automatic language detection based on configuration
- Template-driven prompts using Freemarker
- Fallback system to English when translations are missing
- Consistent localization across all CLI output
- Easy extensibility for new languages
The localization system consists of several key components:
Localization System
├── StudyBuddyLocale # Language enumeration
├── LocalizationService # Core localization service
├── LocalizationConfig # Configuration settings
└── Freemarker Templates # Language-specific prompts
- User Input: Command with optional
--langparameter - Language Detection: Determine target language (user preference or default)
- Template Selection: Choose appropriate Freemarker template
- Prompt Generation: Generate localized prompt for AI
- Output Formatting: Format response with localized labels
Currently supported languages:
| Language | Code | Locale | Status |
|---|---|---|---|
| Spanish | ES | es | Full Support |
| English | EN | en | Full Support |
Spanish (ES) - Default
- Complete template coverage
- Localized field names and labels
- Natural Spanish AI responses
- Cultural context awareness
English (EN)
- Complete template coverage
- Professional English output
- Technical terminology focus
- International context
The system defaults to Spanish (ES) based on the configuration:
studybuddy.default-locale=es- Command Line:
--lang EN(highest priority) - Environment Variable:
STUDYBUDDY_DEFAULT_LOCALE=en - Application Config:
studybuddy.default-locale=es - System Default: Spanish (
ES) (fallback)
# Use default language (Spanish)
./studybuddy.sh summarize "machine learning"
# Force English
./studybuddy.sh summarize "machine learning" --lang EN
# Force Spanish (explicit)
./studybuddy.sh summarize "machine learning" --lang ESTemplates are organized by language in the resources directory:
src/main/resources/templates/prompts/
├── es/ # Spanish templates
│ ├── educational_content.ftl # Educational content generation
│ ├── research.ftl # Academic research
│ └── summarization.ftl # Content summarization
└── en/ # English templates
├── educational_content.ftl # Educational content generation
├── research.ftl # Academic research
└── summarization.ftl # Content summarization
1. educational_content.ftl
- Used for:
summarizeandexplaincommands - Purpose: Generate educational explanations and summaries
- Variables:
topic,subject,contentType,targetAudience,learningObjectives,difficulty,additionalRequirements
2. research.ftl
- Used for:
researchcommand - Purpose: Conduct academic research
- Variables:
topic,subject,context,specificQuestions
3. summarization.ftl
- Used for: Content summarization (future feature)
- Purpose: Summarize existing content
- Variables:
content,summaryType,maxLength,focusAreas
Common variables available in templates:
| Variable | Type | Description |
|---|---|---|
topic |
String | Main topic or concept |
subject |
String | Academic subject area |
contentType |
String | Type of content (summary, explanation) |
targetAudience |
String | Intended audience |
learningObjectives |
List | Learning goals |
difficulty |
String | Difficulty level |
additionalRequirements |
String | Special requirements |
Add the new language to StudyBuddyLocale.java:
public enum StudyBuddyLocale {
SPANISH("es", "Español"),
ENGLISH("en", "English"),
FRENCH("fr", "Français"); // New language
// ... rest of the enum
}Create a new directory for the language templates:
src/main/resources/templates/prompts/fr/
├── educational_content.ftl
├── research.ftl
└── summarization.ftl
Copy existing templates and translate them. For example, fr/educational_content.ftl:
Vous êtes un éducateur expert spécialisé en ${subject!"études générales"}.
Votre objectif est de générer du contenu éducatif attrayant, informatif et approprié pour le niveau de l'étudiant.
## Instructions IMPORTANTES:
- VOUS DEVEZ répondre entièrement en français, sans exception
- Créez du contenu éducatif clair et bien structuré
- Adaptez le niveau de complexité au contexte de l'étudiant
- Incluez des exemples pratiques et des études de cas quand c'est approprié
- Utilisez des méthodologies pédagogiques efficaces
- Assurez-vous que le contenu soit précis et pédagogiquement solide
- TOUT le contenu doit être en français, même si le sujet est en anglais
<#if contentType??>
## Type de contenu: ${contentType}
</#if>
## Sujet/Concept:
${topic}
Veuillez générer du contenu éducatif de haute qualité en FRANÇAIS qui aide les étudiants à apprendre et comprendre efficacement ce sujet.Update domain model methods if needed to support the new language:
private String getLevelDescription(DifficultyLevel level, StudyBuddyLocale locale) {
return switch (locale) {
case SPANISH -> switch (level) {
case BEGINNER -> "principiante, con explicaciones básicas y ejemplos simples";
// ... other levels
};
case ENGLISH -> switch (level) {
case BEGINNER -> "beginner level with basic explanations and simple examples";
// ... other levels
};
case FRENCH -> switch (level) {
case BEGINNER -> "niveau débutant avec explications de base et exemples simples";
// ... other levels
};
};
}Create tests for the new language in LocalizationServiceTest.java:
@Test
void testGenerateResearchPromptFrench() {
String topic = "Intelligence Artificielle";
String subject = "Informatique";
String prompt = localizationService.generateResearchPrompt(
StudyBuddyLocale.FRENCH, topic, subject, null, Collections.emptyList()
);
assertNotNull(prompt);
assertTrue(prompt.contains("assistant de recherche académique"));
assertTrue(prompt.contains(topic));
}StudyBuddy CLI uses Freemarker template syntax:
<#-- Comments -->
${variable} <!-- Variable substitution -->
${variable!"default"} <!-- Variable with default -->
<#if condition??></#if> <!-- Conditional -->
<#list items as item></#list> <!-- Iteration -->1. Adding Custom Instructions
## Instructions IMPORTANTES:
- DEBES responder completamente en español, sin excepción
- Crea contenido educativo claro y bien estructurado
- TODO el contenido debe estar en español, incluso si el tema está en inglés
- Usa un tono profesional pero accesible <!-- Custom addition -->
- Incluye ejemplos del contexto latinoamericano <!-- Custom addition -->2. Adding Conditional Sections
<#if targetAudience??>
## Audiencia objetivo: ${targetAudience}
<#if targetAudience == "universitarios">
Ajusta el contenido para estudiantes universitarios con conocimientos previos.
</#if>
</#if>3. Custom Variable Processing
<#if learningObjectives?? && learningObjectives?size > 0>
## Objetivos de aprendizaje:
<#list learningObjectives as objective>
${objective?counter}. ${objective}
</#list>
</#if>Configure localization behavior in application.properties:
# Default locale
studybuddy.default-locale=es
# Fallback configuration
studybuddy.localization.fallback-to-english=true
# Template configuration
studybuddy.localization.template-encoding=UTF-8
studybuddy.localization.cache-templates=trueOverride configuration with environment variables:
# Set default locale
export STUDYBUDDY_DEFAULT_LOCALE=en
# Disable fallback
export STUDYBUDDY_LOCALIZATION_FALLBACK_TO_ENGLISH=falseConfigure in LocalizationConfig.java:
@ConfigurationProperties(prefix = "studybuddy.localization")
public class LocalizationConfig {
private StudyBuddyLocale defaultLocale = StudyBuddyLocale.SPANISH;
private boolean fallbackToEnglish = true;
private String templateEncoding = "UTF-8";
// getters and setters
}Test the localization service:
# Run all localization tests
./mvnw test -Dtest=LocalizationServiceTest
# Test specific language
./mvnw test -Dtest=LocalizationServiceTest#testGenerateResearchPromptSpanishTest different languages manually:
# Spanish output (default)
./studybuddy.sh summarize "machine learning"
# English output
./studybuddy.sh summarize "machine learning" --lang EN
# Verify language consistency
./studybuddy.sh research "artificial intelligence" --lang ES
./studybuddy.sh explain "neural networks" --lang ENValidate templates by checking:
- Variable substitution: All variables are properly used
- Conditional logic: All conditions work correctly
- Language consistency: Output is in the expected language
- Content quality: Generated content is appropriate
To debug template issues:
- Check template syntax: Verify Freemarker syntax is correct
- Validate variables: Ensure all required variables are provided
- Test fallback: Verify fallback to English works
- Review output: Check that generated prompts produce expected results
- Use consistent terminology across templates in the same language
- Include explicit language instructions for AI models
- Provide fallback values for optional variables
- Test with real data to ensure quality output
- Native speaker review for new language templates
- Cultural context awareness in examples and references
- Technical term accuracy for specialized domains
- Consistent style across all templates
- Version control templates like source code
- Document template changes in commit messages
- Test after modifications to prevent regressions
- Keep templates synchronized across languages for feature parity
For more information about implementation details, see the source code in:
src/main/java/com/michead/studybuddy/localization/src/main/resources/templates/prompts/